sensorium-trace 0.18.2__py3-none-any.whl

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 (135) hide show
  1. sensorium/__init__.py +0 -0
  2. sensorium/__main__.py +4 -0
  3. sensorium/_c/rt/sensorium_c_rt.c +1446 -0
  4. sensorium/_typescript/package-lock.json +68 -0
  5. sensorium/_typescript/package.json +39 -0
  6. sensorium/_typescript/src/bindings.mjs +792 -0
  7. sensorium/_typescript/src/cap.mjs +227 -0
  8. sensorium/_typescript/src/capabilities.mjs +40 -0
  9. sensorium/_typescript/src/dbg.mjs +348 -0
  10. sensorium/_typescript/src/escape.mjs +351 -0
  11. sensorium/_typescript/src/focus.mjs +135 -0
  12. sensorium/_typescript/src/hook.mjs +127 -0
  13. sensorium/_typescript/src/index.mjs +1 -0
  14. sensorium/_typescript/src/naming.mjs +63 -0
  15. sensorium/_typescript/src/positions.mjs +37 -0
  16. sensorium/_typescript/src/probe.mjs +246 -0
  17. sensorium/_typescript/src/qualname.mjs +236 -0
  18. sensorium/_typescript/src/redact.mjs +711 -0
  19. sensorium/_typescript/src/register.mjs +15 -0
  20. sensorium/_typescript/src/resolve.mjs +260 -0
  21. sensorium/_typescript/src/rt.mjs +798 -0
  22. sensorium/_typescript/src/setup.mjs +11 -0
  23. sensorium/_typescript/src/tally.mjs +164 -0
  24. sensorium/_typescript/src/tasks.mjs +175 -0
  25. sensorium/_typescript/src/transform.mjs +800 -0
  26. sensorium/_typescript/src/vite.mjs +99 -0
  27. sensorium/c/__init__.py +8 -0
  28. sensorium/c/cc.py +612 -0
  29. sensorium/c/cli.py +60 -0
  30. sensorium/c/convert.py +669 -0
  31. sensorium/c/decode.py +300 -0
  32. sensorium/c/driver.py +365 -0
  33. sensorium/c/dwarf.py +706 -0
  34. sensorium/c/format.py +271 -0
  35. sensorium/c/pkg.py +187 -0
  36. sensorium/c/plan.py +277 -0
  37. sensorium/cli.py +140 -0
  38. sensorium/driver.py +47 -0
  39. sensorium/exit.py +33 -0
  40. sensorium/invocations.py +83 -0
  41. sensorium/limits.py +253 -0
  42. sensorium/mcp/__init__.py +0 -0
  43. sensorium/mcp/audit.py +162 -0
  44. sensorium/mcp/child.py +240 -0
  45. sensorium/mcp/cmd.py +101 -0
  46. sensorium/mcp/jsonrpc.py +172 -0
  47. sensorium/mcp/result.py +187 -0
  48. sensorium/mcp/schema.py +390 -0
  49. sensorium/mcp/server.py +493 -0
  50. sensorium/mcp/tools.py +299 -0
  51. sensorium/paths.py +80 -0
  52. sensorium/query/__init__.py +0 -0
  53. sensorium/query/caps.py +150 -0
  54. sensorium/query/dbg_dialects.py +64 -0
  55. sensorium/query/diff_cmd.py +748 -0
  56. sensorium/query/diff_notes.py +117 -0
  57. sensorium/query/exceptions_c.py +263 -0
  58. sensorium/query/exceptions_cmd.py +788 -0
  59. sensorium/query/exceptions_group.py +571 -0
  60. sensorium/query/exceptions_invocation.py +487 -0
  61. sensorium/query/exceptions_rust.py +683 -0
  62. sensorium/query/exceptions_typescript.py +688 -0
  63. sensorium/query/expr.py +606 -0
  64. sensorium/query/failures_cmd.py +306 -0
  65. sensorium/query/flow_cmd.py +778 -0
  66. sensorium/query/flow_report.py +128 -0
  67. sensorium/query/flow_values.py +195 -0
  68. sensorium/query/fmt.py +280 -0
  69. sensorium/query/frame_cmd.py +237 -0
  70. sensorium/query/grep_cmd.py +156 -0
  71. sensorium/query/help.py +18 -0
  72. sensorium/query/info_cmd.py +527 -0
  73. sensorium/query/info_rust.py +214 -0
  74. sensorium/query/info_typescript.py +261 -0
  75. sensorium/query/js_inspect.py +394 -0
  76. sensorium/query/moves.py +254 -0
  77. sensorium/query/redact_cmd.py +304 -0
  78. sensorium/query/refocus_cmd.py +661 -0
  79. sensorium/query/refocus_env.py +493 -0
  80. sensorium/query/refocus_facts.py +269 -0
  81. sensorium/query/refocus_licence.py +187 -0
  82. sensorium/query/refocus_report.py +327 -0
  83. sensorium/query/refocus_rust.py +537 -0
  84. sensorium/query/refocus_threads.py +197 -0
  85. sensorium/query/refocus_typescript.py +756 -0
  86. sensorium/query/refocus_world.py +666 -0
  87. sensorium/query/runs_cmd.py +213 -0
  88. sensorium/query/rust_debug.py +176 -0
  89. sensorium/query/sites.py +171 -0
  90. sensorium/query/tree_cmd.py +511 -0
  91. sensorium/query/tree_threads.py +168 -0
  92. sensorium/query/vocab.py +723 -0
  93. sensorium/query/watch_cmd.py +657 -0
  94. sensorium/record/__init__.py +0 -0
  95. sensorium/record/boot.py +797 -0
  96. sensorium/record/boot_io.py +141 -0
  97. sensorium/record/budget.py +135 -0
  98. sensorium/record/capture.py +433 -0
  99. sensorium/record/children.py +755 -0
  100. sensorium/record/children_merge.py +179 -0
  101. sensorium/record/elide.py +55 -0
  102. sensorium/record/fingerprint.py +26 -0
  103. sensorium/record/thread_starts.py +261 -0
  104. sensorium/record/tracer.py +798 -0
  105. sensorium/record/tracer_exc.py +199 -0
  106. sensorium/record/tracer_frames.py +618 -0
  107. sensorium/redact.py +304 -0
  108. sensorium/redact_content.py +156 -0
  109. sensorium/redact_key.py +317 -0
  110. sensorium/redact_store.py +502 -0
  111. sensorium/redact_values.py +433 -0
  112. sensorium/store/__init__.py +0 -0
  113. sensorium/store/db.py +284 -0
  114. sensorium/store/gc.py +360 -0
  115. sensorium/store/payloads.py +69 -0
  116. sensorium/store/reader.py +438 -0
  117. sensorium/store/writer.py +283 -0
  118. sensorium/ts/__init__.py +10 -0
  119. sensorium/ts/build.py +783 -0
  120. sensorium/ts/cli.py +130 -0
  121. sensorium/ts/driver.py +472 -0
  122. sensorium/ts/focus.py +146 -0
  123. sensorium/ts/harness.py +314 -0
  124. sensorium/ts/ingest.py +380 -0
  125. sensorium/ts/invocation.py +252 -0
  126. sensorium/ts/pkg.py +167 -0
  127. sensorium/ts/redaction.py +64 -0
  128. sensorium/ts/spool.py +168 -0
  129. sensorium/ts/truncation.py +81 -0
  130. sensorium/ts/wrapper.py +255 -0
  131. sensorium_trace-0.18.2.dist-info/METADATA +245 -0
  132. sensorium_trace-0.18.2.dist-info/RECORD +135 -0
  133. sensorium_trace-0.18.2.dist-info/WHEEL +4 -0
  134. sensorium_trace-0.18.2.dist-info/entry_points.txt +3 -0
  135. sensorium_trace-0.18.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,493 @@
1
+ """The MCP server: two threads, two eras, one way out.
2
+
3
+ TWO THREADS. The calling thread reads stdin and answers two things
4
+ itself: `ping`, because a liveness check queued behind a three-minute
5
+ `record` would report the server dead while it was working, and
6
+ `notifications/cancelled`, whose point is to reach a call the worker is
7
+ blocked inside. Everything else is queued on one `deque` behind one
8
+ `Condition` for one daemon worker -- serialised on purpose (D14): the
9
+ store is SQLite and a call is a child process, so the honest offer is
10
+ one question at a time.
11
+
12
+ THE ONE CRITICAL SECTION. The worker pops a request and publishes the
13
+ `Child` it will spawn -- `_inflight = (id, child)` -- without releasing
14
+ the Condition in between, and the reader reads `_inflight` under the
15
+ same lock: a cancel arriving in a gap between the two would find the
16
+ request in neither place and be lost. The child is published BEFORE it
17
+ is spawned for the same reason, which is why `Child.run` re-reads the
18
+ cancelled flag under its own lock after `Popen`. Everything but the
19
+ spawn is decided AND answered inside that section -- microseconds of
20
+ work, and a gap is the bug.
21
+
22
+ THE WORKER OWNS THE SESSION, so the era rules need no second lock for
23
+ state with exactly one writer, and the reader's two methods need no
24
+ session at all (`ping` is exempt from the era check; a cancel names an
25
+ id). No request takes the worker down either: an exception becomes one
26
+ stderr line and a `-32603` naming the class. Pipe errors are not among
27
+ them -- `Writer` swallows those into `closing`, because by then there
28
+ is nobody to tell.
29
+
30
+ TWO ERAS ON ONE PROCESS (spec §3, P5). A request whose `_meta` carries
31
+ `io.modelcontextprotocol/protocolVersion` is served statelessly under
32
+ 2026-07-28's per-request model; one without that key is legacy and
33
+ needs `initialize` to have happened -- `initialize` and `ping` are the
34
+ only methods exempt from the check. The key's ABSENCE is what decides,
35
+ never its value: the SDK sends `"_meta": {}` on every legacy request,
36
+ and keying off emptiness would read those as modern.
37
+
38
+ ONE SHUTDOWN PATH. `serve()`'s `finally` -- reached by EOF, by the
39
+ `SystemExit` the SIGTERM handler raises, by `KeyboardInterrupt`, by a
40
+ broken pipe or by a bug -- ignores SIGTERM, marks the writer closing,
41
+ closes the queue, kills the in-flight child's group and joins the
42
+ worker. The handler does three things and none is the kill: one that
43
+ ran `Child.cancel()` would re-enter a kill already in its grace wait,
44
+ on the thread holding that child's lock, and hang. The join is not
45
+ tidiness -- a daemon thread mid-write at interpreter finalisation
46
+ prints a traceback onto the client's stdout.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ import collections
51
+ import importlib.metadata
52
+ import os
53
+ import signal
54
+ import sys
55
+ import threading
56
+ from dataclasses import dataclass
57
+
58
+ from sensorium import paths
59
+ from sensorium.mcp import audit, jsonrpc, result, tools
60
+ from sensorium.mcp.child import Child
61
+ from sensorium.mcp.jsonrpc import Incoming, Writer, parse_line
62
+ from sensorium.mcp.schema import Rejection
63
+ from sensorium.mcp.tools import Tool
64
+
65
+ #: Every revision this server answers, newest first: the per-request
66
+ #: era, then the three `initialize` ones. `STRUCTURED_LEGACY` is the
67
+ #: legacy pair that knows `Tool.title` (no result carries structured
68
+ #: content and no tool an output schema: R18, and `result.py` says why).
69
+ SUPPORTED = ("2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26")
70
+ LEGACY = SUPPORTED[1:]
71
+ LEGACY_LATEST = "2025-11-25"
72
+ STRUCTURED_LEGACY = ("2025-06-18", "2025-11-25")
73
+
74
+ #: 2026-07-28's per-request protocol fields, and the one we answer with.
75
+ META_VERSION = "io.modelcontextprotocol/protocolVersion"
76
+ META_CAPS = "io.modelcontextprotocol/clientCapabilities"
77
+ META_SERVER = "io.modelcontextprotocol/serverInfo"
78
+
79
+ #: How long a listing may be cached, and by whom -- private: the tools
80
+ #: are THIS process's CLI over one developer's store. `COMPLETE` is the
81
+ #: only `resultType` we send: we never stream.
82
+ TTL_MS = 3600000
83
+ CACHE_SCOPE = "private"
84
+ COMPLETE = "complete"
85
+ NAME = "sensorium"
86
+
87
+ #: Spec §3.3 (D15, P29): what the model does not get from its prior,
88
+ #: sent with both handshakes, pinned under 800 characters by a test. The
89
+ #: last sentence is this deployment's, not the spec paragraph's.
90
+ INSTRUCTIONS = (
91
+ "sensorium answers debugging questions from a recorded execution "
92
+ "trace. Start with `runs`, then `info` on the run you mean; `last` is "
93
+ "the newest trace and the default. Event ids eN and frame ids fN "
94
+ "printed by one answer are valid arguments to the next. Every result "
95
+ "begins with an exit line: 0 answered, 1 the trace says no or none, 2 "
96
+ "fix the arguments and ask again, 3 the trace cannot settle it and "
97
+ "only a new recording can. Never repeat a 3 on the same run; never "
98
+ "re-record on a 2. Two plays: a wrong value or a swallowed error is "
99
+ "`exceptions`, then `frame` on the guilty fN, then `tree` with "
100
+ "`around` set to the parent's event id; a flaky or "
101
+ "environment-dependent test is two recordings and `diff`. `record` "
102
+ "and `refocus` execute your program and exist only under "
103
+ "`--allow-run`.")
104
+
105
+ #: The refusals that are this module's own words.
106
+ _BAD_CALL_PARAMS = "tools/call needs a string name and an object arguments"
107
+ _NOT_INITIALIZED = ("not initialized: send initialize or server/discover "
108
+ "first, or carry _meta protocolVersion")
109
+ _NO_DISCOVER_META = "server/discover needs _meta protocolVersion"
110
+
111
+ #: What the worker pops when it is time to stop. Not `None`: a request
112
+ #: whose id is null is a real request and must not read alike.
113
+ _DONE = object()
114
+
115
+
116
+ @dataclass
117
+ class Options:
118
+ """This process's policy (§6). `store` reaches the children as
119
+ `SENSORIUM_DIR`, which `cmd.run` sets for us (D16, P9)."""
120
+
121
+ allow_run: bool = False
122
+ store: str | None = None
123
+ max_output: int = 65536
124
+ timeout: float = 60.0
125
+ run_timeout: float = 600.0
126
+
127
+
128
+ @dataclass
129
+ class Session:
130
+ """The legacy era's state, owned by the worker: what `initialize`
131
+ settled on, and whether the modern probe was answered."""
132
+
133
+ legacy_version: str | None = None
134
+ discovered: bool = False
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class _Call:
139
+ """A call decided inside the critical section -- so `child` can be
140
+ published with the pop -- and run outside it."""
141
+
142
+ tool: Tool
143
+ arguments: dict
144
+ child: Child
145
+ modern: bool
146
+
147
+
148
+ def version() -> str:
149
+ """This package's version, or `?` when it is not installed."""
150
+ try:
151
+ return importlib.metadata.version("sensorium-trace")
152
+ except importlib.metadata.PackageNotFoundError:
153
+ return "?"
154
+
155
+
156
+ class Server:
157
+ """One conversation on one pair of pipes."""
158
+
159
+ def __init__(self, options: Options, stdin, stdout, stderr,
160
+ table: dict[str, Tool] | None = None) -> None:
161
+ self.options = options
162
+ self._stdin, self._stderr = stdin, stderr
163
+ self.writer = Writer(stdout)
164
+ self.table = (tools.table(options.allow_run) if table is None
165
+ else table) # P22: once, before any thread exists
166
+ self.session = Session()
167
+ self._cond = threading.Condition()
168
+ self._queue: collections.deque = collections.deque()
169
+ self._inflight: tuple[object, Child] | None = None
170
+
171
+ # -- the reader thread --------------------------------------------------
172
+ def serve(self) -> int:
173
+ """Read stdin until it ends, then shut down. Always 0."""
174
+ self.log(f"serving {len(self.table)} tools "
175
+ f"(allow_run={self.options.allow_run}) "
176
+ f"store={paths.trace_root()}")
177
+ if audit.disabled():
178
+ self.log("audit off (SENSORIUM_NO_INVOCATION_LOG)")
179
+ worker = threading.Thread(target=self._work, daemon=True,
180
+ name="sensorium-mcp-worker")
181
+ worker.start()
182
+ try:
183
+ self._read()
184
+ finally:
185
+ self._shutdown(worker)
186
+ return 0
187
+
188
+ def log(self, msg: str) -> None:
189
+ """The only writer of stderr; stdout is JSON-RPC and nothing
190
+ else. A diagnostic is never a reason to lose a call."""
191
+ try:
192
+ self._stderr.write(f"sensorium mcp: {msg}\n")
193
+ self._stderr.flush()
194
+ except (BrokenPipeError, ValueError):
195
+ pass
196
+
197
+ def _read(self) -> None:
198
+ for line in self._stdin:
199
+ message = parse_line(line)
200
+ if message is None:
201
+ continue # a blank line or a dropped notification
202
+ if not isinstance(message, Incoming):
203
+ code, text, id_ = message # parse_line's own refusal
204
+ self.writer.error(id_, code, text)
205
+ elif message.notification:
206
+ if message.method == "notifications/cancelled":
207
+ self._cancel(message.params)
208
+ elif message.method == "ping":
209
+ self.writer.result(
210
+ message.id, self._modern({"resultType": COMPLETE})
211
+ if _is_modern(message.params) else {})
212
+ else:
213
+ with self._cond:
214
+ self._queue.append(message)
215
+ self._cond.notify()
216
+
217
+ def _cancel(self, params: dict) -> None:
218
+ """P21: the id is compared as the JSON value it arrived as --
219
+ `"7"` is not the call whose id is `7`. The kill runs here and
220
+ may hold this thread for the child's grace period: accepted,
221
+ since the only thing behind it is another cancel."""
222
+ if "requestId" not in params:
223
+ return
224
+ wanted, queued = params["requestId"], None
225
+ with self._cond:
226
+ flying = self._inflight
227
+ child = (flying[1] if flying is not None
228
+ and flying[0] == wanted else None)
229
+ for index, waiting in enumerate(self._queue):
230
+ if child is None and waiting is not _DONE \
231
+ and waiting.id == wanted:
232
+ queued = waiting
233
+ del self._queue[index]
234
+ break
235
+ if child is not None:
236
+ child.cancel()
237
+ elif queued is not None:
238
+ # Nothing was spawned, so there is no duration to report.
239
+ audit.record_cancel(queued.params.get("name"),
240
+ _arguments(queued.params), True, None)
241
+
242
+ def _shutdown(self, worker: threading.Thread) -> None:
243
+ """The one way out, from EOF, SIGTERM, Ctrl-C or a bug."""
244
+ _ignore_sigterm() # a second SIGTERM must not unwind the kill
245
+ self.writer.closing = True
246
+ with self._cond:
247
+ # One hold for both: apart, the worker could pop and publish
248
+ # a new child between them, killed by nobody.
249
+ flying = self._inflight
250
+ self._queue.clear() # whatever is left will not be served
251
+ self._queue.append(_DONE)
252
+ self._cond.notify()
253
+ if flying is not None:
254
+ flying[1].cancel() # the full kill, on this thread
255
+ worker.join(5.0)
256
+
257
+ # -- the worker thread --------------------------------------------------
258
+ def _work(self) -> None:
259
+ while True:
260
+ failure: Exception | None = None
261
+ call: _Call | None = None
262
+ with self._cond:
263
+ while not self._queue:
264
+ self._cond.wait()
265
+ message = self._queue.popleft()
266
+ if message is _DONE:
267
+ return
268
+ try:
269
+ call = self._plan(message)
270
+ except Exception as exc: # our bug, not theirs
271
+ failure = exc
272
+ if call is not None:
273
+ self._inflight = (message.id, call.child)
274
+ try:
275
+ if call is not None:
276
+ self._run(message, call)
277
+ except Exception as exc:
278
+ failure = exc
279
+ finally:
280
+ with self._cond:
281
+ self._inflight = None
282
+ if failure is not None:
283
+ self.log(f"internal error on {message.method} id "
284
+ f"{message.id}: {type(failure).__name__}: {failure}")
285
+ self.writer.error(message.id, jsonrpc.INTERNAL_ERROR,
286
+ "Internal error",
287
+ {"type": type(failure).__name__})
288
+
289
+ def _plan(self, message: Incoming) -> _Call | None:
290
+ """Answer `message`, or hand back the call left to run. `None`
291
+ is "answered": what `writer.result` and `_fault` return."""
292
+ params = message.params
293
+ modern = _is_modern(params)
294
+ if message.method == "initialize":
295
+ return self.writer.result(message.id, self._initialize(params))
296
+ if message.method == "server/discover" and not modern:
297
+ return self._fault(message, jsonrpc.INVALID_PARAMS,
298
+ _NO_DISCOVER_META)
299
+ if not self._era_ok(message, params, modern):
300
+ return None
301
+ structured = modern or self.session.legacy_version in STRUCTURED_LEGACY
302
+ if message.method == "server/discover":
303
+ return self.writer.result(message.id, self._discover(params))
304
+ if message.method == "tools/list":
305
+ return self.writer.result(message.id,
306
+ self._listing(structured, modern))
307
+ if message.method == "tools/call":
308
+ return self._plan_call(message, modern)
309
+ return self._fault(message, jsonrpc.METHOD_NOT_FOUND,
310
+ f"Method not found: {message.method}")
311
+
312
+ def _fault(self, message: Incoming, code: int, text: str,
313
+ data: object = None) -> None:
314
+ self.writer.error(message.id, code, text, data)
315
+
316
+ def _era_ok(self, message: Incoming, params: dict, modern: bool) -> bool:
317
+ """P5. False means refused, with nothing left to do."""
318
+ if not modern:
319
+ if self.session.legacy_version is None:
320
+ self._fault(message, jsonrpc.INVALID_PARAMS, _NOT_INITIALIZED)
321
+ return False
322
+ return True
323
+ offered = _meta(params)[META_VERSION]
324
+ if offered not in SUPPORTED:
325
+ self._fault(message, jsonrpc.UNSUPPORTED_VERSION,
326
+ "Unsupported protocol version",
327
+ {"supported": list(SUPPORTED), "requested": offered})
328
+ return False
329
+ if META_CAPS not in _meta(params):
330
+ self._fault(message, jsonrpc.INVALID_PARAMS,
331
+ f"missing _meta key {META_CAPS}")
332
+ return False
333
+ return True
334
+
335
+ def _initialize(self, params: dict) -> dict:
336
+ """P27: the offered version is echoed iff we speak it. Offering
337
+ `2026-07-28` here is a confused client -- that revision has no
338
+ `initialize` -- and is answered the newest legacy one, as an
339
+ unknown date is: echoing anything offered would claim a revision
340
+ we cannot speak."""
341
+ offered = params.get("protocolVersion")
342
+ answered = offered if offered in LEGACY else LEGACY_LATEST
343
+ self.session.legacy_version = answered
344
+ self.log(f"handshake initialize {offered} -> {answered}")
345
+ return {"protocolVersion": answered,
346
+ "capabilities": {"tools": {}},
347
+ "serverInfo": self._info(),
348
+ "instructions": INSTRUCTIONS}
349
+
350
+ def _discover(self, params: dict) -> dict:
351
+ self.session.discovered = True
352
+ self.log(f"handshake discover {_meta(params)[META_VERSION]}")
353
+ return {"resultType": COMPLETE,
354
+ "supportedVersions": list(SUPPORTED),
355
+ "capabilities": {"tools": {}},
356
+ "instructions": INSTRUCTIONS,
357
+ "ttlMs": TTL_MS, "cacheScope": CACHE_SCOPE,
358
+ "_meta": {META_SERVER: self._info()}}
359
+
360
+ def _listing(self, structured: bool, modern: bool) -> dict:
361
+ """`cursor` is ignored: the tool list is one page."""
362
+ listed = {"tools": [tools.to_wire(tool, structured)
363
+ for tool in self.table.values()]}
364
+ if not modern:
365
+ return listed
366
+ listed.update(resultType=COMPLETE, ttlMs=TTL_MS,
367
+ cacheScope=CACHE_SCOPE)
368
+ return self._modern(listed)
369
+
370
+ def _info(self) -> dict:
371
+ return {"name": NAME, "version": version()}
372
+
373
+ def _modern(self, answer: dict) -> dict:
374
+ """P6: every per-request-era result says who wrote it. Only
375
+ `_meta`: `resultType` is written by whoever built the result,
376
+ because two hands on one key is how they disagree."""
377
+ return {**answer, "_meta": {META_SERVER: self._info()}}
378
+
379
+ # -- one tool call ------------------------------------------------------
380
+ def _plan_call(self, message: Incoming, modern: bool) -> _Call | None:
381
+ """Refuse the call, answer it, or hand back the child to run."""
382
+ params = message.params
383
+ name, given = params.get("name"), params.get("arguments")
384
+ if not isinstance(name, str) or not (given is None
385
+ or isinstance(given, dict)):
386
+ # No tool was named, so there is nothing to audit under.
387
+ return self._fault(message, jsonrpc.INVALID_PARAMS,
388
+ _BAD_CALL_PARAMS)
389
+ arguments = _arguments(params)
390
+ tool = self.table.get(name)
391
+ if tool is None:
392
+ text = f"Unknown tool: {name}"
393
+ audit.record_rejection(name, jsonrpc.INVALID_PARAMS,
394
+ "unknown_tool", text)
395
+ return self._fault(message, jsonrpc.INVALID_PARAMS, text)
396
+ try:
397
+ argv, extras = tools.command_argv(tool, arguments)
398
+ except Rejection as rejected:
399
+ # P30: an argument the model can fix comes back as a RESULT
400
+ # in the CLI's exit-2 words -- an error response is swallowed
401
+ # by the client, field names and all.
402
+ #
403
+ # The audit runs BEFORE the write, as it does for an unknown
404
+ # tool above: a failure here is then the request's only
405
+ # answer (`_work`'s -32603), where after the write it was a
406
+ # SECOND response for an id that already had its result.
407
+ audit.record_rejection(tool.name, jsonrpc.INVALID_PARAMS,
408
+ rejected.reason, rejected.message,
409
+ rejected.fields)
410
+ answer = result.rejection_result(rejected, modern)
411
+ self.writer.result(message.id,
412
+ self._modern(answer) if modern else answer)
413
+ return None
414
+ return _Call(tool, arguments, Child(
415
+ argv, cwd=extras.get("cwd"), python=extras.get("python"),
416
+ env=dict(os.environ),
417
+ timeout=(self.options.run_timeout if tool.executes
418
+ else self.options.timeout),
419
+ log=self.log, name=tool.name), modern)
420
+
421
+ def _run(self, message: Incoming, call: _Call) -> None:
422
+ """Spawn, wait, answer -- the slow part, outside the lock. P20:
423
+ a cancelled call is never answered, because the client has
424
+ stopped waiting and may have reused the id."""
425
+ outcome = call.child.run()
426
+ with self._cond:
427
+ self._inflight = None # cleared before the answer is written
428
+ if outcome.cancelled:
429
+ audit.record_cancel(call.tool.name, call.arguments, False,
430
+ outcome.ms)
431
+ return
432
+ answer, truncated = result.call_result(
433
+ call.tool, outcome, self.options.max_output, call.modern)
434
+ shown = len(answer["content"][0]["text"].encode("utf-8"))
435
+ self.writer.result(message.id, self._modern(answer) if call.modern
436
+ else answer)
437
+ audit.record_call(call.tool.name, call.arguments, outcome, shown,
438
+ truncated)
439
+
440
+
441
+ def _meta(params: dict) -> dict:
442
+ """`params["_meta"]`, or an empty one -- a `_meta` that is not an
443
+ object carries no keys, which is what a legacy request looks like."""
444
+ found = params.get("_meta")
445
+ return found if isinstance(found, dict) else {}
446
+
447
+
448
+ def _is_modern(params: dict) -> bool:
449
+ """P5: the era is the version KEY's presence, never its value."""
450
+ return META_VERSION in _meta(params)
451
+
452
+
453
+ def _arguments(params: dict) -> dict:
454
+ given = params.get("arguments")
455
+ return given if isinstance(given, dict) else {}
456
+
457
+
458
+ def _ignore_sigterm() -> None:
459
+ try:
460
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
461
+ except ValueError:
462
+ pass # not the main thread: nobody installed a handler either
463
+
464
+
465
+ def main(options: Options, table: dict[str, Tool] | None = None) -> int:
466
+ """Serve on this process's own stdio. Always 0, and says which 0:
467
+ EOF, SIGTERM (which the handler turns into a `SystemExit` the reader
468
+ loop unwinds through), or stdout closed under us. None is a failure,
469
+ and `serve()`'s `finally` has killed whatever was running."""
470
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
471
+ sys.stdout.reconfigure(encoding="utf-8")
472
+ server = Server(options, sys.stdin, sys.stdout, sys.stderr, table)
473
+
474
+ def _terminated(signum, frame):
475
+ # Three lines, and no kill: the shutdown is one path and this is
476
+ # only how it is asked for. See the module docstring.
477
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
478
+ server.writer.closing = True
479
+ raise SystemExit(0)
480
+
481
+ signal.signal(signal.SIGTERM, _terminated)
482
+ try:
483
+ server.serve()
484
+ except SystemExit as leaving:
485
+ if leaving.code not in (0, None):
486
+ raise
487
+ server.log("exit 0 (sigterm)")
488
+ return 0
489
+ except BrokenPipeError:
490
+ server.log("exit 0 (pipe)")
491
+ return 0
492
+ server.log("exit 0 (eof)")
493
+ return 0