@passioncode-ai/passioncode 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +22 -5
  3. package/SECURITY.md +1 -1
  4. package/bin/passioncode.js +5 -5
  5. package/family.json +1 -1
  6. package/package.json +1 -1
  7. package/payload/.claude-plugin/marketplace.json +2 -2
  8. package/payload/manifest.json +8 -8
  9. package/payload/plugins/fabric-agent-adapter/.claude-plugin/plugin.json +1 -1
  10. package/payload/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/SKILL.md +20 -4
  11. package/payload/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/references/provider-entry.md +57 -0
  12. package/payload/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/scripts/adapt_project.py +15 -2
  13. package/payload/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/scripts/fabric_provider.py +267 -0
  14. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/SKILL.md +19 -3
  15. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/references/interop.md +77 -0
  16. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/references/protocol.md +1 -1
  17. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/check_service.py +177 -0
  18. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-interop.mjs +215 -0
  19. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-service.mjs +8 -1
  20. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_interop.py +470 -0
  21. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_service.py +14 -2
  22. package/payload/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/sample_service.py +118 -1
  23. package/payload/plugins/fabric-agent-adapter/skills/creating-fabric-agents/SKILL.md +9 -3
  24. package/payload/plugins/passioncode/.claude-plugin/plugin.json +1 -1
@@ -0,0 +1,470 @@
1
+ #!/usr/bin/env python3
2
+ """Reference kit for the fabric-interop/0.1 extension: how agents are called.
3
+
4
+ Standard library only, Python 3.9+. It sits beside fabric_service.py and uses it for
5
+ atomic, private writes. Every function implements one rule of the extension and names
6
+ it, so a service that calls these functions inherits the rule:
7
+
8
+ - C3.1 a capability is served as the MCP tool of its own name, annotations from its effect;
9
+ - C3.2 long work is a job: a stable id, fabric.job.get / fabric.job.cancel, a result envelope;
10
+ - C3.3 a question for a person is an elicitation (form mode, never a secret; URL mode for those);
11
+ - C3.4 every answer is a child span of the caller's traceparent, and so is every event.
12
+
13
+ Normative source: fabric-agent-contract docs/specification/interop.md (DEC-0016, rulings DEC-0017).
14
+ """
15
+
16
+ # #region interop-kit — docs: plugins/fabric-agent-adapter/skills/building-fabric-services/references/interop.md#the-kit
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ from pathlib import Path
22
+ import re
23
+ import secrets
24
+ import sys
25
+ from typing import Any, Callable, Dict, List, Optional
26
+
27
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
28
+ import fabric_service as _fs # noqa: E402
29
+
30
+ PROTOCOL = "fabric-interop/0.1"
31
+ EXTENSION_KEY = "https://fabric.passioncode.ai/agent-contract/extensions/interop/0.1"
32
+ MCP_REVISION = "2026-07-28"
33
+ CONTRACT_VERSION = "0.1.0"
34
+ JOB_STATES = ("working", "input_required", "completed", "failed", "cancelled")
35
+ OUTCOMES = ("succeeded", "partial", "failed", "cancelled", "blocked")
36
+ ENVELOPE_REQUIRED = ["id", "contractVersion", "outcome", "done", "proof", "scope", "notVerified", "artifacts",
37
+ "createdAt", "producer", "output", "usage"]
38
+ # The job handle inline, as a job tool's outputSchema carries it (contract interop-job-handle.schema.json).
39
+ JOB_HANDLE_SCHEMA: Dict[str, Any] = {
40
+ "type": "object", "required": ["job"], "additionalProperties": False,
41
+ "properties": {"job": {"type": "object", "required": ["id", "status"], "additionalProperties": False,
42
+ "properties": {"id": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9._:-]+$"},
43
+ "status": {"const": "working"}}}},
44
+ }
45
+ TERMINAL = ("completed", "failed", "cancelled")
46
+
47
+ _TRACEPARENT = re.compile(r"^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")
48
+ _JOB_ID = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
49
+ _KEY = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
50
+ _SECRET_WORDS = re.compile(r"pass(word|phrase)|secret|api[\s_-]?key|access[\s_-]?key|private[\s_-]?key|"
51
+ r"(access|auth|bearer|refresh|session)[\s_-]?token|^token$|credential", re.IGNORECASE)
52
+
53
+
54
+ class InteropError(_fs.ServiceError):
55
+ """A rule of fabric-interop/0.1 was violated; the message is one readable sentence."""
56
+
57
+
58
+ class UnknownJob(InteropError):
59
+ def __init__(self, job_id: str):
60
+ self.job_id = job_id
61
+ super().__init__("unknown-job: no job %s here." % job_id)
62
+
63
+
64
+ # --- C3.4 trace context --------------------------------------------------------
65
+
66
+ def parse_traceparent(value: Any) -> Optional[Dict[str, str]]:
67
+ """W3C Trace Context Level 1, lowercase hex; version ff and all-zero ids are invalid."""
68
+ match = _TRACEPARENT.match(value) if isinstance(value, str) else None
69
+ if not match:
70
+ return None
71
+ version, trace_id, span_id, flags = match.groups()
72
+ if version == "ff" or set(trace_id) == {"0"} or set(span_id) == {"0"}:
73
+ return None
74
+ return {"version": version, "trace_id": trace_id, "span_id": span_id, "flags": flags}
75
+
76
+
77
+ def _span_id() -> str:
78
+ while True:
79
+ value = secrets.token_hex(8)
80
+ if set(value) != {"0"}:
81
+ return value
82
+
83
+
84
+ def child_traceparent(parent: Optional[str]) -> str:
85
+ """A new span under `parent`; a missing or broken parent starts a new trace (W3C: restart)."""
86
+ parsed = parse_traceparent(parent)
87
+ trace_id = parsed["trace_id"] if parsed else secrets.token_hex(16)
88
+ flags = parsed["flags"] if parsed else "01"
89
+ return "00-%s-%s-%s" % (trace_id, _span_id(), flags)
90
+
91
+
92
+ def trace_ids(traceparent: Optional[str]) -> Dict[str, str]:
93
+ """The `traceId`/`spanId` pair an event about this span carries (C3.4 c), or {}."""
94
+ parsed = parse_traceparent(traceparent)
95
+ return {"trace_id": parsed["trace_id"], "span_id": parsed["span_id"]} if parsed else {}
96
+
97
+
98
+ # --- C3.1 capabilities as tools --------------------------------------------------
99
+
100
+ def expected_annotations(effect: str, idempotency: str) -> Dict[str, bool]:
101
+ """effect none -> readOnlyHint; delete|merge|deploy|change-policy -> destructiveHint; idempotency required -> idempotentHint."""
102
+ hints: Dict[str, bool] = {}
103
+ if effect == "none":
104
+ hints["readOnlyHint"] = True
105
+ if effect in ("delete", "merge", "deploy", "change-policy"):
106
+ hints["destructiveHint"] = True
107
+ if idempotency == "required":
108
+ hints["idempotentHint"] = True
109
+ return hints
110
+
111
+
112
+ def job_tool_output_schema(output_schema: Dict[str, Any]) -> Dict[str, Any]:
113
+ """DEC-0017: a job-backed tool's outputSchema is oneOf[result envelope, job handle], self-contained,
114
+ so structuredContent always conforms; the manifest's capability keeps the pure output schema."""
115
+ return {"oneOf": [{"type": "object", "required": list(ENVELOPE_REQUIRED), "properties": {"output": output_schema}},
116
+ JOB_HANDLE_SCHEMA]}
117
+
118
+
119
+ def is_job_capability(capability: Dict[str, Any]) -> bool:
120
+ block = (capability.get("extensions") or {}).get(EXTENSION_KEY) or {}
121
+ return capability.get("job") is True or block.get("job") is True
122
+
123
+
124
+ def tool_for_capability(capability: Dict[str, Any], input_schema: Dict[str, Any], output_schema: Dict[str, Any],
125
+ title: Optional[str] = None) -> Dict[str, Any]:
126
+ """The MCP tool for one manifest capability: its name, its input schema as it is, derived annotations,
127
+ and its output schema — wrapped in the job union when the capability is a job (DEC-0017)."""
128
+ tool: Dict[str, Any] = {
129
+ "name": capability["name"],
130
+ "inputSchema": input_schema,
131
+ "outputSchema": job_tool_output_schema(output_schema) if is_job_capability(capability) else output_schema,
132
+ "annotations": expected_annotations(capability.get("effect", ""), capability.get("idempotency", "")),
133
+ }
134
+ if capability.get("description"):
135
+ tool["description"] = capability["description"]
136
+ if title:
137
+ tool["title"] = title
138
+ return tool
139
+
140
+
141
+ def tool_result(structured: Any, *, is_error: bool = False, traceparent: Optional[str] = None) -> Dict[str, Any]:
142
+ """A tools/call result: structuredContent plus its JSON as text, for clients that read only text."""
143
+ result: Dict[str, Any] = {
144
+ "resultType": "complete",
145
+ "content": [{"type": "text", "text": json.dumps(structured, ensure_ascii=False)}],
146
+ "structuredContent": structured,
147
+ "isError": is_error,
148
+ }
149
+ if traceparent:
150
+ result["_meta"] = {"traceparent": traceparent}
151
+ return result
152
+
153
+
154
+ def unknown_job_result(job_id: str, traceparent: Optional[str] = None) -> Dict[str, Any]:
155
+ """C3.2: fabric.job.get for an unknown id answers isError with unknown-job, never a fresh job."""
156
+ return tool_result({"error": {"code": "unknown-job", "message": "No job %s here." % job_id}},
157
+ is_error=True, traceparent=traceparent)
158
+
159
+
160
+ # --- C3.2 the result envelope ------------------------------------------------------
161
+
162
+ def _usage(usage: Any) -> Dict[str, Any]:
163
+ if not isinstance(usage, dict):
164
+ raise InteropError("usage must be an object.")
165
+ for key in ("inputTokens", "outputTokens", "wallMs"):
166
+ if key not in usage:
167
+ raise InteropError("usage.%s is required." % key)
168
+ for key, value in usage.items():
169
+ if key not in ("inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "costUsd", "wallMs"):
170
+ raise InteropError("usage.%s is not a usage field." % key)
171
+ numeric = isinstance(value, (int, float)) and not isinstance(value, bool)
172
+ if not numeric or value < 0 or (key != "costUsd" and not isinstance(value, int)):
173
+ raise InteropError("usage.%s must be a non-negative %s." % (key, "number" if key == "costUsd" else "integer"))
174
+ return dict(usage)
175
+
176
+
177
+ def result_envelope(*, outcome: str, done: List[Dict[str, Any]], proof: List[Dict[str, Any]], scope: Dict[str, Any],
178
+ not_verified: List[Dict[str, Any]], output: Any, usage: Dict[str, Any], producer: Dict[str, Any],
179
+ artifacts: Optional[List[Dict[str, Any]]] = None, traceparent: Optional[str] = None,
180
+ result_id: Optional[str] = None, created_at: Optional[str] = None) -> Dict[str, Any]:
181
+ """The full result envelope (contract result.schema.json, DEC-0011, DEC-0017): the same shape a
182
+ synchronous call returns, with output, usage and — when the work was traced — its trace."""
183
+ if outcome not in OUTCOMES:
184
+ raise InteropError("outcome must be one of %s." % ", ".join(OUTCOMES))
185
+ for label, value in (("done", done), ("proof", proof), ("notVerified", not_verified), ("artifacts", artifacts or [])):
186
+ if not isinstance(value, list):
187
+ raise InteropError("%s must be a list, even when empty." % label)
188
+ if outcome == "succeeded" and not_verified:
189
+ raise InteropError("A succeeded result cannot keep unverified claims (FAC-SEM-001); report partial.")
190
+ if not isinstance(scope, dict) or not isinstance(producer, dict):
191
+ raise InteropError("scope and producer must be objects.")
192
+ envelope: Dict[str, Any] = {
193
+ "id": result_id or "urn:fabric:result:" + secrets.token_hex(12), "contractVersion": CONTRACT_VERSION,
194
+ "outcome": outcome, "done": list(done), "proof": list(proof), "scope": dict(scope),
195
+ "notVerified": list(not_verified), "artifacts": list(artifacts or []), "createdAt": created_at or _fs.now_iso(),
196
+ "producer": dict(producer), "output": output, "usage": _usage(usage),
197
+ }
198
+ if parse_traceparent(traceparent):
199
+ envelope["trace"] = {"traceparent": traceparent}
200
+ return envelope
201
+
202
+
203
+ # --- C3.3 awaiting a choice ------------------------------------------------------------
204
+
205
+ def form_request(message: str, properties: Dict[str, Dict[str, Any]], required: Optional[List[str]] = None) -> Dict[str, Any]:
206
+ """An elicitation in form mode: a flat object of primitive fields, and never a secret (FAC-SEM-018)."""
207
+ for field, schema in properties.items():
208
+ words = " ".join(str(schema.get(key, "")) for key in ("title", "description", "format"))
209
+ if _SECRET_WORDS.search(field) or _SECRET_WORDS.search(words):
210
+ raise InteropError("Form mode cannot ask for %s: a secret goes through url_request." % field)
211
+ if schema.get("type") not in ("string", "number", "integer", "boolean", "array"):
212
+ raise InteropError("Form field %s must be a primitive (string, number, integer, boolean or an enum array)." % field)
213
+ requested: Dict[str, Any] = {"type": "object", "properties": properties}
214
+ if required:
215
+ requested["required"] = list(required)
216
+ return {"method": "elicitation/create", "params": {"mode": "form", "message": message, "requestedSchema": requested}}
217
+
218
+
219
+ def choice_request(message: str, field: str, options: List[Any], title: Optional[str] = None) -> Dict[str, Any]:
220
+ """A titled single-select: oneOf [{const, title}] — what Fabric turns into an interaction point."""
221
+ schema: Dict[str, Any] = {"type": "string", "oneOf": [{"const": value, "title": label} for value, label in options]}
222
+ if title:
223
+ schema["title"] = title
224
+ return form_request(message, {field: schema}, [field])
225
+
226
+
227
+ def url_request(message: str, url: str) -> Dict[str, Any]:
228
+ """URL mode: the person opens `url` out of band; for credentials and payments. Put nothing sensitive in the URL."""
229
+ if not url.startswith(("https://", "http://127.0.0.1", "http://localhost")):
230
+ raise InteropError("A URL-mode request needs an https URL (or this machine's loopback).")
231
+ return {"method": "elicitation/create", "params": {"mode": "url", "message": message, "url": url}}
232
+
233
+
234
+ # --- C3.2 jobs ---------------------------------------------------------------------
235
+
236
+ class JobStore:
237
+ """Durable jobs, one private JSON file each under `directory`, written atomically.
238
+
239
+ A job id survives a restart of the agent, so fabric.job.get after a restart finds
240
+ the same job. The file holds the public `job` object exactly as fabric.job.get
241
+ returns it, and a `private` part (the capability, its input, the trace) that is
242
+ never returned. The Node kit reads and writes the same format.
243
+ """
244
+
245
+ def __init__(self, directory: Path):
246
+ self.dir = Path(directory)
247
+
248
+ def _path(self, job_id: str) -> Path:
249
+ if not _JOB_ID.match(job_id or ""):
250
+ raise UnknownJob(str(job_id))
251
+ return self.dir / ("%s.json" % job_id)
252
+
253
+ def _load(self, job_id: str) -> Dict[str, Any]:
254
+ try:
255
+ return json.loads(self._path(job_id).read_text(encoding="utf-8"))
256
+ except FileNotFoundError:
257
+ raise UnknownJob(job_id) from None
258
+ except ValueError:
259
+ raise InteropError("Job %s is unreadable on disk." % job_id) from None
260
+
261
+ def _save(self, record: Dict[str, Any]) -> Dict[str, Any]:
262
+ record["job"]["updatedAt"] = _fs.now_iso()
263
+ _fs.ensure_private_dir(self.dir)
264
+ _fs.atomic_write(self._path(record["job"]["id"]), (json.dumps(record, ensure_ascii=False) + "\n").encode(), 0o600)
265
+ return dict(record["job"])
266
+
267
+ def create(self, capability: str, arguments: Any, traceparent: Optional[str] = None,
268
+ poll_interval_ms: Optional[int] = None) -> Dict[str, Any]:
269
+ """Start a job; returns the handle a job-capable tool puts in structuredContent."""
270
+ job_id = "job_" + secrets.token_hex(12)
271
+ job: Dict[str, Any] = {"id": job_id, "status": "working"}
272
+ if poll_interval_ms:
273
+ job["pollIntervalMs"] = int(poll_interval_ms)
274
+ self._save({"job": job, "private": {"capability": capability, "input": arguments,
275
+ "traceparent": traceparent if parse_traceparent(traceparent) else None}})
276
+ return {"job": {"id": job_id, "status": "working"}}
277
+
278
+ def get(self, job_id: str) -> Dict[str, Any]:
279
+ return dict(self._load(job_id)["job"])
280
+
281
+ def private(self, job_id: str) -> Dict[str, Any]:
282
+ return dict(self._load(job_id)["private"])
283
+
284
+ def traceparent(self, job_id: str) -> Optional[str]:
285
+ return self._load(job_id)["private"].get("traceparent")
286
+
287
+ def _transition(self, job_id: str, status: str, **fields: Any) -> Dict[str, Any]:
288
+ record = self._load(job_id)
289
+ job = record["job"]
290
+ if job["status"] in TERMINAL:
291
+ raise InteropError("Job %s is already %s; a terminal job does not change." % (job_id, job["status"]))
292
+ for key in ("inputRequests", "result", "error", "statusMessage"):
293
+ job.pop(key, None)
294
+ job["status"] = status
295
+ job.update({key: value for key, value in fields.items() if value is not None})
296
+ return self._save(record)
297
+
298
+ def working(self, job_id: str, message: Optional[str] = None) -> Dict[str, Any]:
299
+ return self._transition(job_id, "working", statusMessage=message)
300
+
301
+ def request_input(self, job_id: str, input_requests: Dict[str, Dict[str, Any]], message: Optional[str] = None) -> Dict[str, Any]:
302
+ """input_required with MCP elicitation requests, keyed; build them with choice_request / form_request / url_request."""
303
+ if not input_requests:
304
+ raise InteropError("input_required needs at least one input request.")
305
+ for key, request in input_requests.items():
306
+ if not _KEY.match(key) or request.get("method") != "elicitation/create":
307
+ raise InteropError("Input request %r must be a keyed elicitation/create request." % key)
308
+ return self._transition(job_id, "input_required", inputRequests=input_requests, statusMessage=message)
309
+
310
+ def answer(self, job_id: str, input_responses: Dict[str, Any]) -> Dict[str, Any]:
311
+ """Apply inputResponses to an input_required job; unknown keys are ignored (MCP Tasks rule).
312
+
313
+ Returns the responses that matched; when any did, the job is working again."""
314
+ job = self.get(job_id)
315
+ if job["status"] != "input_required":
316
+ return {}
317
+ matched = {key: value for key, value in (input_responses or {}).items()
318
+ if key in job.get("inputRequests", {}) and isinstance(value, dict)
319
+ and value.get("action") in ("accept", "decline", "cancel")}
320
+ if matched:
321
+ self.working(job_id)
322
+ return matched
323
+
324
+ def complete(self, job_id: str, envelope: Dict[str, Any]) -> Dict[str, Any]:
325
+ """The envelope carries the job's trace, authoritative for the stored result (DEC-0017); one that names
326
+ another span is refused, so fabric.job.get's _meta and the envelope always agree (FAC-SEM-022)."""
327
+ if not isinstance(envelope, dict) or not set(ENVELOPE_REQUIRED) <= set(envelope):
328
+ raise InteropError("A completed job carries the full result envelope; build it with result_envelope.")
329
+ stored = self.traceparent(job_id)
330
+ given = (envelope.get("trace") or {}).get("traceparent")
331
+ ids = lambda value: ((parse_traceparent(value) or {}).get("trace_id"), (parse_traceparent(value) or {}).get("span_id"))
332
+ if stored and given and ids(given) != ids(stored):
333
+ raise InteropError("Job %s ran in span %s; its result names another trace." % (job_id, stored))
334
+ if stored and not given:
335
+ envelope = dict(envelope, trace={"traceparent": stored})
336
+ return self._transition(job_id, "completed", result=envelope)
337
+
338
+ def fail(self, job_id: str, code: Any, message: str) -> Dict[str, Any]:
339
+ return self._transition(job_id, "failed", error={"code": code, "message": message})
340
+
341
+ def cancel(self, job_id: str) -> Dict[str, Any]:
342
+ return self._transition(job_id, "cancelled")
343
+
344
+
345
+ # --- a minimal MCP tool server (streamable HTTP, JSON responses) ------------------------
346
+
347
+ class CallContext:
348
+ """What a tool handler gets: the child span it runs in, and a way to start a job."""
349
+
350
+ def __init__(self, server: "McpToolServer", tool: str, arguments: Any, traceparent: str):
351
+ self.server = server
352
+ self.tool = tool
353
+ self.arguments = arguments
354
+ self.traceparent = traceparent
355
+
356
+ def start_job(self, poll_interval_ms: Optional[int] = None) -> Dict[str, Any]:
357
+ if self.server.jobs is None:
358
+ raise InteropError("This server has no job store.")
359
+ handle = self.server.jobs.create(self.tool, self.arguments, self.traceparent, poll_interval_ms)
360
+ self.server.job_started(handle["job"]["id"], self)
361
+ return handle
362
+
363
+
364
+ Handler = Callable[[Any, CallContext], Any]
365
+ OnInput = Callable[[str, Dict[str, Any], CallContext], None]
366
+
367
+ JOB_REQUEST_SCHEMA = {"type": "object", "required": ["id"], "additionalProperties": False, "properties": {
368
+ "id": {"type": "string", "minLength": 1, "maxLength": 128},
369
+ "inputResponses": {"type": "object"}}}
370
+
371
+
372
+ class McpToolServer:
373
+ """tools/list and tools/call for an MCP 2026-07-28 server, with fabric.job.get/cancel built in.
374
+
375
+ `handle(message)` takes one JSON-RPC message and returns the response (None for a
376
+ notification). Every result carries `_meta.traceparent`, a child span of the
377
+ caller's. It is deliberately small: a service with a full MCP SDK should use that
378
+ and keep only the helpers above.
379
+ """
380
+
381
+ def __init__(self, name: str, version: str, jobs: Optional[JobStore] = None,
382
+ on_job_started: Optional[Callable[[str, CallContext], None]] = None,
383
+ on_input: Optional[OnInput] = None):
384
+ self.info = {"name": name, "version": version}
385
+ self.jobs = jobs
386
+ self.tools: List[Dict[str, Any]] = []
387
+ self.handlers: Dict[str, Handler] = {}
388
+ self._on_job_started = on_job_started
389
+ self._on_input = on_input
390
+
391
+ def add_tool(self, tool: Dict[str, Any], handler: Handler) -> None:
392
+ if tool["name"] in self.handlers:
393
+ raise InteropError("Tool %s is served twice." % tool["name"])
394
+ self.tools.append(tool)
395
+ self.handlers[tool["name"]] = handler
396
+
397
+ def job_started(self, job_id: str, ctx: CallContext) -> None:
398
+ if self._on_job_started:
399
+ self._on_job_started(job_id, ctx)
400
+
401
+ def _job_tools(self) -> List[Dict[str, Any]]:
402
+ if self.jobs is None:
403
+ return []
404
+ return [
405
+ {"name": "fabric.job.get", "description": "The state of a job this agent started; answer an input request with inputResponses.",
406
+ "inputSchema": JOB_REQUEST_SCHEMA, "annotations": {"idempotentHint": True}},
407
+ {"name": "fabric.job.cancel", "description": "Ask this agent to stop a job it started.",
408
+ "inputSchema": {"type": "object", "required": ["id"], "additionalProperties": False, "properties": {"id": JOB_REQUEST_SCHEMA["properties"]["id"]}},
409
+ "annotations": {"idempotentHint": True}},
410
+ ]
411
+
412
+ @staticmethod
413
+ def _error(rid: Any, code: int, message: str) -> Dict[str, Any]:
414
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
415
+
416
+ def handle(self, message: Any) -> Optional[Dict[str, Any]]:
417
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
418
+ return self._error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid request.")
419
+ if "id" not in message:
420
+ return None # a notification gets no response
421
+ rid = message["id"]
422
+ params = message.get("params") or {}
423
+ meta = params.get("_meta") or {}
424
+ span = child_traceparent(meta.get("traceparent"))
425
+ method = message["method"]
426
+ if method == "server/discover":
427
+ return {"jsonrpc": "2.0", "id": rid, "result": {"resultType": "complete", "capabilities": {"tools": {}},
428
+ "serverInfo": self.info, "_meta": {"traceparent": span}}}
429
+ if method == "tools/list":
430
+ return {"jsonrpc": "2.0", "id": rid, "result": {"resultType": "complete", "tools": self.tools + self._job_tools(),
431
+ "_meta": {"traceparent": span}}}
432
+ if method != "tools/call":
433
+ return self._error(rid, -32601, "Method %s is not served here." % method)
434
+ name = params.get("name")
435
+ arguments = params.get("arguments") or {}
436
+ if name in ("fabric.job.get", "fabric.job.cancel") and self.jobs is not None:
437
+ return {"jsonrpc": "2.0", "id": rid, "result": self._job_call(name, arguments, span)}
438
+ handler = self.handlers.get(name)
439
+ if handler is None:
440
+ return self._error(rid, -32602, "Unknown tool: %s." % name)
441
+ try:
442
+ structured = handler(arguments, CallContext(self, name, arguments, span))
443
+ except InteropError as exc:
444
+ return {"jsonrpc": "2.0", "id": rid, "result": tool_result({"error": {"code": "tool-error", "message": str(exc)}}, is_error=True, traceparent=span)}
445
+ return {"jsonrpc": "2.0", "id": rid, "result": tool_result(structured, traceparent=span)}
446
+
447
+ def _job_call(self, name: str, arguments: Dict[str, Any], span: str) -> Dict[str, Any]:
448
+ job_id = str(arguments.get("id", ""))
449
+ try:
450
+ job_span = self.jobs.traceparent(job_id) or span
451
+ state = self.jobs.get(job_id)
452
+ job_span = ((state.get("result") or {}).get("trace") or {}).get("traceparent") or job_span
453
+ if name == "fabric.job.cancel":
454
+ state = self.jobs.get(job_id)
455
+ if state["status"] not in TERMINAL:
456
+ state = self.jobs.cancel(job_id)
457
+ return tool_result({"job": state}, traceparent=job_span)
458
+ responses = arguments.get("inputResponses")
459
+ if responses:
460
+ matched = self.jobs.answer(job_id, responses)
461
+ if matched and self._on_input:
462
+ private = self.jobs.private(job_id)
463
+ self._on_input(job_id, matched, CallContext(self, private["capability"], private["input"], job_span))
464
+ return tool_result({"job": self.jobs.get(job_id)}, traceparent=job_span)
465
+ except UnknownJob:
466
+ return unknown_job_result(job_id, traceparent=span)
467
+
468
+
469
+ __all__ = [name for name in dir() if not name.startswith("_")]
470
+ # #endregion interop-kit
@@ -46,6 +46,8 @@ _INSTANCE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
46
46
  _KIND = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){0,5}$")
47
47
  _ORIGIN = re.compile(r"^http://127\.0\.0\.1:([0-9]{3,5})$")
48
48
  _CODE = re.compile(r"^[A-Za-z0-9_-]{16,256}$")
49
+ _TRACE_ID = re.compile(r"^(?!0{32}$)[0-9a-f]{32}$")
50
+ _SPAN_ID = re.compile(r"^(?!0{16}$)[0-9a-f]{16}$")
49
51
 
50
52
 
51
53
  class ServiceError(Exception):
@@ -404,8 +406,12 @@ def build_well_known(*, service_id: str, instance: str, name: str, version: str,
404
406
  # --- events ------------------------------------------------------------------
405
407
 
406
408
  def make_event(event_id: Any, at: str, kind: str, level: str, text: str, *, subject: Optional[Dict[str, str]] = None,
407
- link: Optional[str] = None, notify: bool = False) -> Dict[str, Any]:
408
- """One activity event: one sentence a person reads, never a machine id."""
409
+ link: Optional[str] = None, notify: bool = False, trace_id: Optional[str] = None,
410
+ span_id: Optional[str] = None) -> Dict[str, Any]:
411
+ """One activity event: one sentence a person reads, never a machine id.
412
+
413
+ An event about traced work carries its trace as a pair, `trace_id` and `span_id`
414
+ (fabric-interop/0.1 C3.4 c); fabric_interop.trace_ids(traceparent) gives both."""
409
415
  if level not in LEVELS:
410
416
  raise ServiceError("level must be one of %s." % ", ".join(LEVELS))
411
417
  if not _KIND.match(kind):
@@ -415,6 +421,10 @@ def make_event(event_id: Any, at: str, kind: str, level: str, text: str, *, subj
415
421
  raise ServiceError("An event needs a sentence.")
416
422
  if link is not None and (not link.startswith("/") or link.startswith("//")):
417
423
  raise ServiceError("link must be a path on this service.")
424
+ if (trace_id is None) != (span_id is None):
425
+ raise ServiceError("An event carries traceId and spanId together, or neither.")
426
+ if trace_id is not None and not (_TRACE_ID.match(trace_id) and _SPAN_ID.match(str(span_id))):
427
+ raise ServiceError("traceId is 32 and spanId 16 lowercase hex characters, not all zeros.")
418
428
  event: Dict[str, Any] = {"id": str(event_id), "at": at, "kind": kind, "level": level, "text": text[:500]}
419
429
  if subject:
420
430
  event["subject"] = subject
@@ -422,6 +432,8 @@ def make_event(event_id: Any, at: str, kind: str, level: str, text: str, *, subj
422
432
  event["link"] = link
423
433
  if notify:
424
434
  event["notify"] = True
435
+ if trace_id is not None:
436
+ event["traceId"], event["spanId"] = trace_id, span_id
425
437
  return event
426
438
 
427
439