-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_service.py
More file actions
2967 lines (2874 loc) · 133 KB
/
Copy pathagent_service.py
File metadata and controls
2967 lines (2874 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hashlib
import json
import os
import re
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from dotenv import load_dotenv
from agent_pain_solver import normalize_pain_type, solution_pattern_for
from nomad_guardrails import GuardrailDecision, NomadGuardrailEngine
from nomad_operator_grant import is_operator_approval_scope, operator_grant
from nomad_public_url import preferred_public_base_url
from settings import get_chain_config
from treasury_agent import TreasuryAgent
from x402_payment import X402PaymentAdapter
load_dotenv()
ROOT = Path(__file__).resolve().parent
DEFAULT_TASK_STORE = ROOT / "nomad_service_tasks.json"
DEFAULT_PRODUCT_STORE = ROOT / "nomad_products.json"
SERVICE_TYPES = {
"human_in_loop": {
"title": "Human-in-the-loop unlock design",
"summary": "Turn blocked approvals, credentials, CAPTCHA/login gates, or unclear handoffs into concrete human unlock tasks.",
},
"compute_auth": {
"title": "Compute/auth diagnosis",
"summary": "Diagnose model provider, token, quota, inference, rate-limit, or fallback-brain failures.",
},
"loop_break": {
"title": "Loop break rescue",
"summary": "Stop infinite retries, isolate failing tool calls, and return the agent to a known-good state.",
},
"hallucination": {
"title": "Hallucination guardrail",
"summary": "Add verifier steps and context checks before compounding errors spread through a workflow.",
},
"memory": {
"title": "Session memory repair",
"summary": "Persist the missing decision, constraint or outcome that the agent keeps forgetting.",
},
"self_improvement": {
"title": "Agent self-improvement pack",
"summary": "Turn one solved blocker into reusable memory, guardrails, prompts, or a checklist the agent can apply next time.",
},
"payment": {
"title": "Payment and x402 repair",
"summary": "Diagnose wallet, invoice, x402, escrow or payment-verification blockers.",
},
"mcp_integration": {
"title": "MCP/API integration plan",
"summary": "Draft an MCP or REST integration contract that another agent can call reliably.",
},
"repo_issue_help": {
"title": "Public repo issue help",
"summary": "Draft a public-issue response, repro checklist, or PR plan without posting automatically.",
},
"inter_agent_witness": {
"title": "Inter-agent witness bundle",
"summary": (
"Produce a machine-checkable WITNESS_BUNDLE so a downstream or buyer agent can verify a prior tool chain "
"without re-running every call or trusting chat prose."
),
},
"wallet_payment": {
"title": "Wallet/payment flow",
"summary": "Design a small wallet payment or verification path for agent-to-agent services.",
},
"proof_gated_bot_factory": {
"title": "Proof-gated AI agent bot factory",
"summary": (
"Turn Solana, NEAR, or Hyperliquid bot goals into simulation-first strategy plans, risk envelopes, "
"proof digests, and explicit live-execution gates."
),
},
"custom": {
"title": "Custom agent infrastructure task",
"summary": "A bounded custom task for AI-agent infrastructure friction.",
},
}
SERVICE_PACKAGE_TEMPLATES = {
"compute_auth": [
{
"package_id": "starter_diagnosis",
"title": "Nomad Compute Unlock Pack: Starter diagnosis",
"summary": "Isolate provider, token, quota, or fallback failure and name the smallest unlock.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "diagnosis pack plus smallest unlock contract",
},
{
"package_id": "bounded_unblock",
"title": "Nomad Compute Unlock Pack: Bounded unblock",
"summary": "Deliver a fallback-lane plan, quota/auth map, and bounded retry policy.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "same-day diagnosis pack plus a bounded fallback-lane plan",
},
],
"mcp_integration": [
{
"package_id": "starter_contract_audit",
"title": "Nomad MCP Contract Pack: Starter audit",
"summary": "Name the tool/resource contract gap and one safe integration path.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "contract audit plus one bounded integration path",
},
{
"package_id": "bounded_contract_plan",
"title": "Nomad MCP Contract Pack: Bounded plan",
"summary": "Produce a reusable MCP/API contract with request, response, and verification steps.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "contract draft plus one bounded integration path",
},
],
"human_in_loop": [
{
"package_id": "starter_unlock_contract",
"title": "Nomad HITL Contract Pack: Starter unlock",
"summary": "Turn the blocker into a minimal do-now/send-back/done-when human step.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "human unlock contract plus smallest approval payload",
},
{
"package_id": "bounded_hitl_handoff",
"title": "Nomad HITL Contract Pack: Bounded handoff",
"summary": "Design the approval path, handoff envelope, and safe resume criteria.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "bounded approval handoff plus safe resume plan",
},
],
"self_improvement": [
{
"package_id": "starter_memory_capture",
"title": "Nomad Memory Upgrade Pack: Starter capture",
"summary": "Turn one solved blocker into a compact checklist or guardrail.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "one reusable checklist or guardrail draft",
},
{
"package_id": "bounded_memory_upgrade",
"title": "Nomad Memory Upgrade Pack: Bounded upgrade",
"summary": "Package the solved blocker as reusable memory, prompt, and verification steps.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "memory pack plus verification and reuse notes",
},
],
"wallet_payment": [
{
"package_id": "starter_payment_check",
"title": "Nomad Payment Reliability Pack: Starter check",
"summary": "Pin down the failing payment state, recipient, chain, and verification step.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "payment-state diagnosis plus next verification step",
},
{
"package_id": "bounded_payment_repair",
"title": "Nomad Payment Reliability Pack: Bounded repair",
"summary": "Produce a retry-safe payment, verification, and resume plan.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "payment repair plan plus retry-safe resume path",
},
],
"proof_gated_bot_factory": [
{
"package_id": "starter_bot_risk_receipt",
"aliases": ["starter_bot_factory"],
"title": "Nomad Bot Factory: Risk receipt starter",
"summary": "Convert one bot goal into a risk envelope, simulation plan, and proof digest candidate.",
"offer_tier": "starter_diagnosis",
"price_tier_recommendation": "$49",
"amount_mode": "minimum",
"buyer_input": [
"public_wallet",
"chain_targets",
"risk_profile",
"max_drawdown",
"strategy_type",
],
"scope": [
"simulation-first Solana, NEAR, or Hyperliquid bot planning",
"no seed phrases or private keys",
"no live orders during starter diagnosis",
"proof digest and performance-receipt schema only",
],
"out_of_scope": [
"return guarantees",
"investment advice",
"custody or withdrawal-capable credentials",
"unapproved live trading",
],
"default_problem": (
"Design a proof-gated AI agent bot from public wallet context, chain targets, risk profile, "
"drawdown limit, market regime, and strategy type; return simulation plan and no-live-order guard."
),
"delivery": "risk envelope, simulation/replay plan, proof digest candidate, and paid/worker lease next step",
},
{
"package_id": "bounded_bot_factory_pack",
"title": "Nomad Bot Factory: Bounded simulation pack",
"summary": "Prepare a bot strategy artifact with replay checks, repair policy, and live-execution guardrails.",
"offer_tier": "paid_unblock",
"price_tier_recommendation": "$99",
"amount_mode": "requested_or_minimum",
"delivery": "bounded bot plan, replay/performance receipt schema, execution policy, and worker handoff",
"upsell_tier": {
"label": "$250 execution-policy audit",
"scope": "only after paid/return-compute receipt; still no custody, no return guarantees, and no live keys in chat",
},
},
],
"repo_issue_help": [
{
"package_id": "repo_diagnostic_patch_starter",
"aliases": ["starter_repo_diagnosis"],
"title": "Nomad Repo Diagnostic Patch Starter",
"summary": "Reduce one public repo issue, failing CI check, or endpoint disturbance into duplicate pressure, smallest repro, and next patch path.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"buyer_input": ["repo_url", "issue_or_log_url", "observed_error", "expected_behavior"],
"scope": [
"one public repo, CI check, deployment, or endpoint disturbance",
"read-only fact gathering before payment",
"draft-only public reply unless buyer/operator grants approval",
],
"out_of_scope": [
"private secrets or credentials",
"broad refactors",
"unapproved public posting",
"spend on paid APIs or infrastructure",
],
"default_problem": (
"Repo/CI/endpoint disturbance: diagnose one failing build, failing check, public issue, "
"or endpoint regression; return duplicate pressure, smallest repro/patch path, and no-post reply draft."
),
"delivery": "repo diagnosis, duplicate-pressure note, smallest repro/patch path, and no-post reply draft",
},
{
"package_id": "bounded_repo_patch_plan",
"title": "Nomad Repo Diagnostic Patch Pack: Bounded patch plan",
"summary": "Prepare a focused patch plan with verification commands, risk notes, and a buyer-safe handoff.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "bounded patch plan plus verification checklist and handoff text",
},
],
"inter_agent_witness": [
{
"package_id": "starter_witness_skeleton",
"title": "Nomad Inter-Agent Witness Pack: Starter skeleton",
"summary": "Order tool call_ids, attach non-secret output digests, and define what a buyer agent may trust.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "WITNESS_BUNDLE v0 draft plus consumer verifier checklist",
},
{
"package_id": "bounded_witness_contract",
"title": "Nomad Inter-Agent Witness Pack: Bounded contract",
"summary": "Ship schema version, WITNESS_HASH, replay_refusal scope, and redaction rules for delegation.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "versioned witness bundle plus replay boundary for receiving runtimes",
},
],
"custom": [
{
"package_id": "starter_diagnosis",
"title": "Nomad Starter diagnosis",
"summary": "Reduce the blocker to one clear diagnosis and one next step.",
"offer_tier": "starter_diagnosis",
"amount_mode": "minimum",
"delivery": "diagnosis plus one bounded next step",
},
{
"package_id": "bounded_delivery",
"title": "Nomad Bounded delivery",
"summary": "Deliver one bounded infrastructure plan or unblock artifact.",
"offer_tier": "paid_unblock",
"amount_mode": "requested_or_minimum",
"delivery": "bounded task delivery",
},
],
}
class AgentServiceDesk:
"""Public service intake for agents that can pay Nomad's wallet."""
def __init__(
self,
path: Optional[Path] = None,
treasury: Optional[TreasuryAgent] = None,
x402: Optional[X402PaymentAdapter] = None,
guardrails: Optional[NomadGuardrailEngine] = None,
product_store_path: Optional[Path] = None,
) -> None:
load_dotenv()
self.path = path or DEFAULT_TASK_STORE
self.product_store_path = Path(product_store_path or DEFAULT_PRODUCT_STORE)
self.treasury = treasury or TreasuryAgent()
self.x402 = x402 or X402PaymentAdapter()
self.guardrails = guardrails or NomadGuardrailEngine()
self.chain = get_chain_config()
self.min_native = float(os.getenv("NOMAD_SERVICE_MIN_NATIVE", "0.01"))
self.treasury_stake_bps = int(os.getenv("NOMAD_SERVICE_TREASURY_STAKE_BPS", "3000"))
requested_solver_bps = os.getenv("NOMAD_SERVICE_SOLVER_SPEND_BPS")
self.solver_spend_bps = (
int(requested_solver_bps)
if requested_solver_bps
else max(0, 10000 - self.treasury_stake_bps)
)
if self.treasury_stake_bps + self.solver_spend_bps > 10000:
self.solver_spend_bps = max(0, 10000 - self.treasury_stake_bps)
self.staking_target = (
os.getenv("NOMAD_TREASURY_STAKING_TARGET")
or "metamask_eth_staking"
).strip()
self.accept_unverified = (
os.getenv("NOMAD_ACCEPT_UNVERIFIED_SERVICE_PAYMENTS", "false").strip().lower()
in {"1", "true", "yes", "on"}
)
self.require_payment = (
os.getenv("NOMAD_REQUIRE_SERVICE_PAYMENT", "true").strip().lower()
in {"1", "true", "yes", "on"}
)
self.hard_boundary_guard = (
os.getenv("NOMAD_HARD_BOUNDARY_GUARD", "true").strip().lower()
in {"1", "true", "yes", "on"}
)
self.max_native = float(os.getenv("NOMAD_SERVICE_MAX_NATIVE", "5.0"))
self.public_api_url = preferred_public_base_url()
def public_wallet_summary(self) -> Dict[str, Any]:
wallet_summary = getattr(self.treasury, "public_wallet_summary", None)
if callable(wallet_summary):
return wallet_summary()
return self.treasury.get_wallet_summary()
def service_catalog(self) -> Dict[str, Any]:
wallet = self.public_wallet_summary()
configured_wallet = wallet.get("address") or ""
featured_product_offer = self._featured_product_offer()
return {
"mode": "agent_service_catalog",
"deal_found": False,
"service": "Nomad agent-first service contract",
"generated_at": datetime.now(UTC).isoformat(),
"public_api_url": self.public_api_url,
"wallet": {
"address": configured_wallet,
"configured": bool(configured_wallet),
"network": self.chain.name,
"chain_id": self.chain.chain_id,
"native_symbol": self.chain.native_symbol,
},
"pricing": {
"minimum_native": self.min_native,
"requires_payment": self.require_payment,
"payment_token": self.chain.native_symbol,
"payment_rail": "metamask_native_transfer",
"verification": "native transfer to Nomad wallet by tx_hash",
"checkout": "create payable task, pay the Nomad wallet from MetaMask, then submit tx_hash for verification",
"stripe_enabled": False,
"x402": {
"enabled": self.x402.enabled,
"facilitator_url": self.x402.facilitator_url,
"asset_address": self.x402.asset_address,
"asset_symbol": self.x402.asset_symbol,
"asset_decimals": self.x402.asset_decimals,
"network": self._x402_network(),
"verify_endpoint": f"{self.public_api_url}/tasks/x402-verify"
if self.public_api_url
else "/tasks/x402-verify",
"retry_header": "PAYMENT-SIGNATURE",
},
"allocation": {
"treasury_stake_bps": self.treasury_stake_bps,
"solver_spend_bps": self.solver_spend_bps,
"staking_target": self.staking_target,
"staking_execution": "requires explicit MetaMask/operator approval",
},
},
"buyer_discovery": {
"target": (
"agents with public buyer-intent signals for compute/auth, loop-break, HITL, payment, "
"self-improvement, or inter_agent_witness (machine-verifiable handoffs between agents)"
),
"agent_contact_without_prior_approval": True,
"human_contact_requires_approval": True,
"conversion_pipeline": "free_value_first_then_PLAN_ACCEPTED_or_payment_task",
},
"agent_market_lane": {
"note": (
"Humans build Nomad; some SKUs are still agent-market-first: the economic buyer is often another "
"agent (pay or resume only after machine checks), not a human procurement dashboard."
),
"featured_sku": {
"service_type": "inter_agent_witness",
"sku": "nomad.inter_agent_witness_bundle_pack",
"well_known_offer_url": (
f"{self.public_api_url.rstrip('/')}/.well-known/nomad-inter-agent-witness-offer.json"
if self.public_api_url
else "/.well-known/nomad-inter-agent-witness-offer.json"
),
},
},
"first_paid_job_protocol": self.first_paid_job_protocol(featured_product_offer),
"first_buyable_starter": self._repo_diagnostic_patch_starter_entry(),
"receipt_first_buyer_protocol": self._receipt_first_buyer_protocol(
service_type="repo_issue_help",
package_id="repo_diagnostic_patch_starter",
),
"interaction_contract": {
"audience": "ai_agents",
"style": "agent_first_non_anthropomorphic",
"machine_entry_surface": "GET /agent-attractor or GET /swarm",
"defaults": [
"structured_replies_preferred",
"bounded_claims_only",
"explicit_payment_boundary",
"no_human_impersonation",
],
"response_schema": [
"agent_value_pack",
"agent_reliability_doctor",
"agent_solution",
"rescue_plan",
"diagnosis",
"next_action",
"required_input",
"price",
"delivery",
"memory_upgrade",
],
},
"service_types": SERVICE_TYPES,
"service_packages": self.service_packages_catalog(),
"agent_attractor_preview": {
"schema": "nomad.agent_attractor.v1",
"target_roles": ["customer", "peer_solver", "collaborator", "reseller"],
"machine_hooks": [
"send_one_blocker_get_one_verifiable_next_step",
"create_paid_task_after_free_diagnosis",
"verify_payment_then_work_task",
"send_one_artifact_get_one_reuse_candidate",
"structured_replies_over_persuasion",
],
"agent_attractor_path": f"{self.public_api_url}/agent-attractor"
if self.public_api_url
else "/agent-attractor",
"top_offer": featured_product_offer,
},
"value_pack_artifact": {
"schema": "nomad.agent_value_pack.v1",
"purpose": "Package one lead's painpoint, bounded diagnosis, safe next steps, reply contract, and optional bounded task path (verify payment and delivery gates explicitly).",
"fields": [
"painpoint_question",
"pain_hypothesis",
"immediate_value",
"reply_contract",
"paid_upgrade",
"nomad_self_apply",
],
},
"product_factory_artifact": {
"schema": "nomad.product.v1",
"purpose": "Turn lead conversions into reusable SKUs with free value, paid offer, service template, and approval boundary.",
"fields": [
"sku",
"buyer",
"free_value",
"paid_offer",
"service_template",
"runtime_hooks",
"approval_boundary",
],
},
"featured_product_offer": featured_product_offer,
"reliability_doctor_artifact": {
"schema": "nomad.agent_reliability_doctor.v1",
"purpose": "Map agent pain into Critic, Diagnoser, Fixer, Healer, Trace-Healer, or Reviewer roles.",
"roles": [
"reflection_critic",
"diagnoser_fixer",
"execution_healer",
"self_learning_healer",
"trace_healer",
"conversational_reviewer",
],
},
"starter_artifact": {
"schema": "nomad.rescue_plan.v1",
"purpose": "Give another agent an immediately usable rescue plan before any public action.",
"fields": [
"diagnosis",
"safe_now",
"required_input",
"acceptance_criteria",
"approval_boundary",
"memory_upgrade",
],
},
"solver_artifact": {
"schema": "nomad.agent_solution.v1",
"purpose": "Turn a recurring agent pain point into a reusable guardrail Nomad also applies to itself.",
"solution_families": [
"retry_circuit_breaker",
"compute_fallback_ladder",
"hitl_unlock_contract",
"verifier_first",
"durable_lesson_object",
"idempotent_payment_resume",
"tool_contract_harness",
"draft_only_repro_plan",
"solved_blocker_pack",
],
},
"runtime_guardrails": self.guardrails.policy(),
"contact_paths": {
"http": {
"descriptor": "GET /agent",
"catalog": "GET /service",
"agent_attractor": "GET /agent-attractor",
"swarm": "GET /swarm",
"service_e2e": "GET /service/e2e or POST /service/e2e",
"outbound_tracking": "GET /outbound",
"agent_pain_solver": "POST /agent-pains",
"reliability_doctor": "POST /reliability-doctor",
"guardrails": "POST /guardrails",
"lead_conversion_pipeline": "POST /lead-conversions",
"product_factory": "POST /products",
"create_task": "POST /tasks",
"verify_payment": "POST /tasks/verify",
"verify_x402_payment": "POST /tasks/x402-verify",
"work_task": "POST /tasks/work",
"staking_checklist": "POST /tasks/staking",
"record_stake": "POST /tasks/stake",
"record_spend": "POST /tasks/spend",
"close_task": "POST /tasks/close",
"queue_agent_contact": "POST /agent-contacts",
"send_agent_contact": "POST /agent-contacts/send",
},
"mcp_tools": [
"nomad_agent_pain_solver",
"nomad_reliability_doctor",
"nomad_guardrails",
"nomad_lead_conversion_pipeline",
"nomad_product_factory",
"nomad_products",
"nomad_agent_attractor",
"nomad_service_catalog",
"nomad_service_request",
"nomad_service_verify",
"nomad_service_work",
"nomad_service_staking_checklist",
"nomad_service_record_stake",
"nomad_service_record_spend",
"nomad_agent_contact",
"nomad_agent_contact_send",
],
"cli": [
"python main.py --cli service",
"python main.py --cli agent-attractor",
"python main.py --cli productize <lead query>",
"python main.py --cli products",
"python main.py --cli service-request <problem>",
"python main.py --cli service-e2e --create",
"python main.py --cli service-verify <task_id> <tx_hash>",
"python main.py --cli service-staking <task_id>",
"python main.py --cli service-stake <task_id> <stake_tx_hash>",
"python main.py --cli service-spend <task_id> <amount>",
"python main.py --cli outbound-status",
"python main.py --cli agent-contact <endpoint> <problem>",
],
},
"safety_contract": self.safety_contract(),
"analysis": (
"Public agents can request bounded infrastructure help, receive a wallet invoice, "
"pay Nomad's configured wallet, then submit tx_hash for verification. Nomad speaks in "
"agent-first, structured replies by default; public posting, DMs, private access, or "
"bypassing human gates still require explicit approval from the affected party. "
"Public machine-readable agent endpoints may be contacted directly when the request is bounded, "
"relevant and rate-limited."
),
}
def first_paid_job_protocol(self, featured_offer: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
offer = featured_offer or self._featured_product_offer()
paid_offer = offer.get("paid_offer") if isinstance(offer.get("paid_offer"), dict) else {}
service_template = offer.get("service_template") if isinstance(offer.get("service_template"), dict) else {}
preferred_type = str(offer.get("pain_type") or "compute_auth").strip() or "compute_auth"
minimum = paid_offer.get("price_native")
if minimum in {None, ""}:
minimum = self.min_native
return {
"schema": "nomad.first_paid_job_protocol.v1",
"audience": "ai_agents",
"purpose": "Convert one blocked AI-agent infrastructure problem into a paid bounded unblock task.",
"preferred_first_job": {
"service_type": preferred_type,
"offer": str(offer.get("name") or SERVICE_TYPES.get(preferred_type, SERVICE_TYPES["compute_auth"])["title"]),
"minimum_budget_native": minimum,
"native_symbol": self.chain.native_symbol,
"delivery": str(paid_offer.get("delivery") or service_template.get("delivery") or "bounded diagnosis and unblock plan"),
"trigger": str(paid_offer.get("trigger") or "PLAN_ACCEPTED=true plus FACT_URL or ERROR"),
},
"call_sequence": [
{
"step": "free_diagnosis",
"method": "POST",
"endpoint": f"{self.public_api_url}/a2a/message" if self.public_api_url else "/a2a/message",
"required_fields": ["requester_agent", "problem"],
"optional_fields": ["goal", "blocking_step", "constraints", "budget_native", "requester_wallet"],
"returns": ["nomad.reply.v1", "payment_required", "rescue_plan"],
},
{
"step": "create_paid_task",
"method": "POST",
"endpoint": f"{self.public_api_url}/tasks" if self.public_api_url else "/tasks",
"required_fields": ["problem", "service_type", "budget_native"],
"optional_fields": ["requester_agent", "requester_wallet", "callback_url", "metadata"],
"returns": ["task_id", "payment"],
},
{
"step": "verify_payment",
"method": "POST",
"endpoint": f"{self.public_api_url}/tasks/verify" if self.public_api_url else "/tasks/verify",
"required_fields": ["task_id", "tx_hash"],
"optional_fields": ["requester_wallet"],
"returns": ["paid_task_or_payment_error"],
},
{
"step": "request_work",
"method": "POST",
"endpoint": f"{self.public_api_url}/tasks/work" if self.public_api_url else "/tasks/work",
"required_fields": ["task_id"],
"optional_fields": ["approval"],
"returns": ["bounded_work_product"],
},
],
"acceptance_criteria": [
"requester receives one concrete diagnosis before payment",
"paid task has task_id, budget_native, service_type, and payment target",
"Nomad only works after payment verification unless local config disables payment",
"work product contains a reusable rescue plan, verifier, or unblock checklist",
],
"boundaries": [
"no secrets in payloads",
"no raw remote code execution",
"no human impersonation",
"no public posting or private access without explicit approval",
],
}
def best_current_offer(
self,
service_type: str = "",
requested_amount: Optional[float] = None,
) -> Dict[str, Any]:
normalized_type = self._normalize_service_type(service_type, "")
featured = self._featured_product_offer(normalized_type)
paid_offer = featured.get("paid_offer") or {}
reply_contract = featured.get("reply_contract") or {}
commercial = self._commercial_terms(
normalized_type or "custom",
requested_amount if requested_amount is not None else self.min_native,
)
starter_offer = commercial.get("starter_offer") or {}
primary_offer = commercial.get("primary_offer") or {}
fallback_headline = (
primary_offer.get("title")
or starter_offer.get("title")
or SERVICE_TYPES.get(normalized_type, SERVICE_TYPES["custom"]).get("title")
or "Nomad bounded offer"
)
delivery = (
paid_offer.get("delivery")
or (featured.get("service_template") or {}).get("delivery")
or SERVICE_TYPES.get(normalized_type, SERVICE_TYPES["custom"]).get("summary")
or ""
)
price_native = paid_offer.get("price_native")
if price_native in {None, ""}:
price_native = primary_offer.get("amount_native") or starter_offer.get("amount_native")
trigger = (
paid_offer.get("trigger")
or reply_contract.get("accept")
or "PLAN_ACCEPTED=true plus FACT_URL or ERROR"
)
headline = featured.get("name") or fallback_headline
return {
"schema": "nomad.best_offer.v1",
"source": "product_factory" if featured else "service_packages",
"service_type": normalized_type or "custom",
"headline": headline,
"price_native": price_native,
"delivery": delivery,
"trigger": trigger,
"entry_path": commercial.get("payment_entry_path") or "primary_only",
"starter_offer": starter_offer,
"primary_offer": primary_offer,
"priority_score": featured.get("priority_score", 0),
"priority_reason": featured.get("priority_reason", ""),
"product_id": featured.get("product_id", ""),
"variant_sku": featured.get("variant_sku", ""),
"reply_contract": reply_contract,
"service_template": featured.get("service_template") or {},
}
def _featured_product_offer(self, service_type: str = "") -> Dict[str, Any]:
products = list((self._load_product_store().get("products") or {}).values())
if not products:
return {}
normalized_type = self._normalize_service_type(service_type, "") if service_type else ""
if normalized_type:
matching = [
item
for item in products
if self._normalize_service_type(str(item.get("pain_type") or ""), "") == normalized_type
]
if not matching:
return {}
products = matching
products.sort(
key=lambda item: (
float(item.get("priority_score") or 0.0),
str(item.get("updated_at") or item.get("created_at") or ""),
str(item.get("name") or ""),
),
reverse=True,
)
top = products[0]
paid_offer = top.get("paid_offer") or {}
service_template = top.get("service_template") or {}
return {
"product_id": top.get("product_id", ""),
"name": top.get("name", ""),
"pain_type": top.get("pain_type", ""),
"status": top.get("status", ""),
"priority_score": top.get("priority_score", 0),
"priority_reason": top.get("priority_reason", ""),
"variant_sku": top.get("variant_sku", ""),
"reply_contract": ((top.get("free_value") or {}).get("reply_contract") or {}),
"paid_offer": {
"price_native": paid_offer.get("price_native"),
"delivery": paid_offer.get("delivery", ""),
"trigger": paid_offer.get("trigger", ""),
},
"service_template": service_template,
}
def _load_product_store(self) -> Dict[str, Any]:
if not self.product_store_path.exists():
return {"products": {}}
try:
payload = json.loads(self.product_store_path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
return {"products": {}}
payload.setdefault("products", {})
return payload
except Exception:
return {"products": {}}
def create_task(
self,
problem: str,
requester_agent: str = "",
requester_wallet: str = "",
service_type: str = "custom",
budget_native: Optional[float] = None,
callback_url: str = "",
metadata: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
cleaned_problem = self._clean(problem)
if not cleaned_problem:
return self._hard_boundary_reject(
error="problem_required",
message="A service request needs a concrete problem statement.",
requested_budget_native=budget_native,
requester_wallet=requester_wallet,
)
guardrail = self.guardrails.evaluate(
action="service.create_task",
args={
"problem": cleaned_problem,
"requester_agent": requester_agent,
"requester_wallet": requester_wallet,
"service_type": service_type,
"budget_native": budget_native,
"callback_url": callback_url,
"metadata": metadata or {},
},
)
if guardrail.decision == GuardrailDecision.DENY:
blocked = self._hard_boundary_reject(
error="guardrail_denied",
message="Nomad blocked this service task before storing or acting on it.",
requested_budget_native=budget_native,
requester_wallet=requester_wallet,
)
blocked["guardrail"] = guardrail.to_dict()
return blocked
guarded_args = guardrail.effective_args
cleaned_problem = self._clean(guarded_args.get("problem") or cleaned_problem)
requester_agent = self._clean(guarded_args.get("requester_agent") or requester_agent)
requester_wallet = self._clean(guarded_args.get("requester_wallet") or requester_wallet)
service_type = self._clean(guarded_args.get("service_type") or service_type)
callback_url = self._clean(guarded_args.get("callback_url") or callback_url)
metadata = guarded_args.get("metadata") if isinstance(guarded_args.get("metadata"), dict) else (metadata or {})
normalized_type = self._normalize_service_type(service_type, cleaned_problem)
parsed_budget = self._optional_float(budget_native)
if self.hard_boundary_guard:
if parsed_budget is not None and parsed_budget <= 0:
return self._hard_boundary_reject(
error="invalid_budget",
message="budget_native must be positive when provided.",
requested_budget_native=parsed_budget,
requester_wallet=requester_wallet,
)
if parsed_budget is not None and parsed_budget > self.max_native:
return self._hard_boundary_reject(
error="budget_exceeds_boundary",
message=f"budget_native exceeds hard boundary ({self.max_native} {self.chain.native_symbol}).",
requested_budget_native=parsed_budget,
requester_wallet=requester_wallet,
)
if callback_url and not callback_url.startswith(("http://", "https://")):
return self._hard_boundary_reject(
error="invalid_callback_url",
message="callback_url must start with http:// or https:// when provided.",
requested_budget_native=parsed_budget,
requester_wallet=requester_wallet,
)
if requester_wallet and not self._looks_like_wallet(requester_wallet):
return self._hard_boundary_reject(
error="invalid_requester_wallet",
message="requester_wallet must be a 0x-prefixed 40-hex address.",
requested_budget_native=parsed_budget,
requester_wallet=requester_wallet,
)
requested_amount = max(
self.min_native,
parsed_budget if parsed_budget is not None else self.min_native,
)
now = datetime.now(UTC).isoformat()
task_id = self._task_id(cleaned_problem, requester_agent, requester_wallet, now)
commercial_terms = self._commercial_terms(
service_type=normalized_type,
requested_amount=requested_amount,
)
payment_request = self._payment_request(
task_id=task_id,
amount_native=requested_amount,
requester_wallet=requester_wallet,
service_type=normalized_type,
)
starter_rescue_plan = self.build_rescue_plan(
problem=cleaned_problem,
service_type=normalized_type,
need_profile=(metadata or {}).get("need_profile") if isinstance(metadata, dict) else {},
engagement_plan=(metadata or {}).get("engagement_plan") if isinstance(metadata, dict) else {},
budget_native=requested_amount,
)
task = {
"task_id": task_id,
"created_at": now,
"updated_at": now,
"requester_agent": self._clean(requester_agent),
"requester_wallet": self._clean(requester_wallet),
"callback_url": self._clean(callback_url),
"service_type": normalized_type,
"problem": cleaned_problem,
"budget_native": requested_amount,
"metadata": metadata or {},
"commercial": commercial_terms,
"status": "awaiting_payment" if self.require_payment else "accepted",
"payment": payment_request,
"payment_allocation": self._payment_allocation(
amount_native=requested_amount,
payment_verified=not self.require_payment,
),
"treasury": {
"staking_status": (
"ready_for_metamask_approval"
if not self.require_payment
else "planned_after_payment_verification"
),
"staking_target": self.staking_target,
"stake_tx_hash": "",
"stake_amount_native": 0.0,
},
"solver_budget": {
"spend_status": (
"available_for_problem_solving"
if not self.require_payment
else "planned_after_payment_verification"
),
"spent_native": 0.0,
"remaining_native": 0.0,
"spend_notes": [],
},
"starter_rescue_plan": starter_rescue_plan,
"ledger": [
self._ledger_event(
event="task_created",
message="Service task created and wallet invoice issued.",
amount_native=requested_amount,
)
],
"work_product": None,
"safety_contract": self.safety_contract(),
"guardrails": {
"create_task": guardrail.to_dict(),
},
}
self._refresh_allocation_status(task)
state = self._load()
state["tasks"][task_id] = task
self._save(state)
return self._task_response(task, created=True)
def verify_payment(
self,
task_id: str,
tx_hash: str,
requester_wallet: str = "",
) -> Dict[str, Any]:
task = self._get_task(task_id)
if not task:
return self._missing_task(task_id)
tx_hash = self._clean(tx_hash)
if not self._looks_like_tx_hash(tx_hash):
task["payment"]["verification"] = {
"ok": False,
"status": "invalid_tx_hash",
"message": "Send a 0x-prefixed transaction hash.",
}
self._store_task(task)
return self._task_response(task)
duplicate = self._tx_used_by_other_task(task_id=task_id, tx_hash=tx_hash)
if duplicate:
task["payment"]["verification"] = {
"ok": False,
"status": "duplicate_tx_hash",
"message": f"Transaction is already attached to task {duplicate}.",
}
self._store_task(task)
return self._task_response(task)
verification = self._verify_native_transfer(
tx_hash=tx_hash,
expected_amount=float(task["payment"]["amount_native"]),
expected_from=requester_wallet or task.get("requester_wallet", ""),
)
task["payment"]["tx_hash"] = tx_hash
task["payment"]["verification"] = verification
observed_amount = verification.get("observed_amount_native") or task["payment"]["amount_native"]
task["payment_allocation"] = self._payment_allocation(
amount_native=float(observed_amount),
payment_verified=bool(verification.get("ok")),
)
task["updated_at"] = datetime.now(UTC).isoformat()
if verification.get("ok"):
task["status"] = "paid"
self._refresh_allocation_status(task)
task.setdefault("ledger", []).append(
self._ledger_event(
event="payment_verified",
message="Incoming wallet payment verified.",
tx_hash=tx_hash,
amount_native=float(observed_amount),
)
)
elif self.accept_unverified:
task["status"] = "manual_payment_review"
task.setdefault("ledger", []).append(
self._ledger_event(
event="payment_manual_review",
message=verification.get("message", "Payment needs manual review."),
tx_hash=tx_hash,
)
)
else: