repld-tool 0.23.2__tar.gz → 0.23.3__tar.gz

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 (77) hide show
  1. {repld_tool-0.23.2 → repld_tool-0.23.3}/PKG-INFO +1 -1
  2. {repld_tool-0.23.2 → repld_tool-0.23.3}/pyproject.toml +1 -1
  3. {repld_tool-0.23.2 → repld_tool-0.23.3}/pyproject.toml.orig +1 -1
  4. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/bridge.py +7 -0
  5. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/core_schemas.py +24 -2
  6. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/help.py +45 -4
  7. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/ipc.py +3 -0
  8. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/kernel.py +3 -1
  9. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/protocol.py +75 -25
  10. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/runtime.py +20 -4
  11. {repld_tool-0.23.2 → repld_tool-0.23.3}/LICENSE +0 -0
  12. {repld_tool-0.23.2 → repld_tool-0.23.3}/README.md +0 -0
  13. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/.ruff_cache/.gitignore +0 -0
  14. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/.ruff_cache/0.15.22/14226964882126921391 +0 -0
  15. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/.ruff_cache/CACHEDIR.TAG +0 -0
  16. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/__init__.py +0 -0
  17. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/__main__.py +0 -0
  18. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/bg.py +0 -0
  19. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/bind.py +0 -0
  20. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/bridge_tools.py +0 -0
  21. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/__init__.py +0 -0
  22. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/browser.py +0 -0
  23. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/captcha.py +0 -0
  24. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/capture.py +0 -0
  25. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/cdp.py +0 -0
  26. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/har.py +0 -0
  27. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/inject.py +0 -0
  28. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/injected_source.py +0 -0
  29. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/observe.py +0 -0
  30. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/pin.py +0 -0
  31. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/png.py +0 -0
  32. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/pool.py +0 -0
  33. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/row.py +0 -0
  34. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/screencast.py +0 -0
  35. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/selector.py +0 -0
  36. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/session.py +0 -0
  37. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/tab.py +0 -0
  38. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/tab_query.py +0 -0
  39. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser/target.py +0 -0
  40. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/browser_dispatch.py +0 -0
  41. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/channel.py +0 -0
  42. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/cli.py +0 -0
  43. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/cli_args.py +0 -0
  44. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/content.py +0 -0
  45. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/dashboard.py +0 -0
  46. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/dashboard_cmd.py +0 -0
  47. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/dashboard_html.py +0 -0
  48. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/display.py +0 -0
  49. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/eventlog.py +0 -0
  50. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/events.py +0 -0
  51. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/exec_cmd.py +0 -0
  52. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gate_cmd.py +0 -0
  53. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gates.py +0 -0
  54. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gist_api.py +0 -0
  55. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gist_cmd.py +0 -0
  56. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gist_deps.py +0 -0
  57. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gist_links.py +0 -0
  58. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gist_lint.py +0 -0
  59. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/gists.py +0 -0
  60. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/kernel_context.py +0 -0
  61. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/killguard.py +0 -0
  62. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/lifecycle_cmd.py +0 -0
  63. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/log_cmd.py +0 -0
  64. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/loopguard.py +0 -0
  65. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/paths.py +0 -0
  66. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/peer.py +0 -0
  67. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/peer_host.py +0 -0
  68. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/peer_pipe_cmd.py +0 -0
  69. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/peer_stub.py +0 -0
  70. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/rebind_cmd.py +0 -0
  71. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/relaunch.py +0 -0
  72. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/render.py +0 -0
  73. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/sessions.py +0 -0
  74. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/spawn.py +0 -0
  75. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/state.py +0 -0
  76. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/tasks.py +0 -0
  77. {repld_tool-0.23.2 → repld_tool-0.23.3}/src/repld/tasks_cmd.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: repld-tool
3
- Version: 0.23.2
3
+ Version: 0.23.3
4
4
  Summary: Persistent Python runtime with MCP channel push. Dev shell and autonomous-agent substrate in one package.
5
5
  Keywords: repl,mcp,agent,browser
6
6
  Author: Fredrik Angelsen
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "repld-tool"
3
- version = "0.23.2"
3
+ version = "0.23.3"
4
4
  description = "Persistent Python runtime with MCP channel push. Dev shell and autonomous-agent substrate in one package."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "repld-tool"
3
- version = "0.23.2"
3
+ version = "0.23.3"
4
4
  description = "Persistent Python runtime with MCP channel push. Dev shell and autonomous-agent substrate in one package."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -54,6 +54,7 @@ from . import (
54
54
  state,
55
55
  )
56
56
  from .core_schemas import (
57
+ BRIDGE_CODE_MODE_KEY,
57
58
  BRIDGE_GOODBYE_METHOD,
58
59
  BRIDGE_INBOX_SOCKET_KEY,
59
60
  BRIDGE_PROJECT_DIR_KEY,
@@ -279,6 +280,7 @@ class Bridge:
279
280
  self._claude_project_dir = os.environ.get("CLAUDE_PROJECT_DIR")
280
281
  self._claude_session_kind = "bg" if os.environ.get("CLAUDE_JOB_DIR") else None
281
282
  self._claude_inbox_socket = os.environ.get("CLAUDE_CODE_MESSAGING_SOCKET")
283
+ self._code_mode = os.environ.get("REPLD_CODE_MODE") == "1"
282
284
  self._inflight: set[object] = set()
283
285
  # Ids of requests the kernel sent to the client (`elicitation/create`),
284
286
  # awaiting the client's reply. Disjoint from `_inflight` by direction.
@@ -687,6 +689,8 @@ class Bridge:
687
689
  if cache
688
690
  else core_schemas.CORE_TOOLS + bridge_tools.SCHEMAS
689
691
  )
692
+ if self._code_mode:
693
+ tools = core_schemas.strip_output_schemas(tools)
690
694
  self._to_client(_response(rid, {"tools": tools}))
691
695
  return True
692
696
 
@@ -793,6 +797,7 @@ class Bridge:
793
797
  and self._claude_project_dir is None
794
798
  and self._claude_session_kind is None
795
799
  and self._claude_inbox_socket is None
800
+ and not self._code_mode
796
801
  ):
797
802
  return msg
798
803
  stamped = dict(msg)
@@ -805,6 +810,8 @@ class Bridge:
805
810
  params[BRIDGE_SESSION_KIND_KEY] = self._claude_session_kind
806
811
  if self._claude_inbox_socket is not None:
807
812
  params[BRIDGE_INBOX_SOCKET_KEY] = self._claude_inbox_socket
813
+ if self._code_mode:
814
+ params[BRIDGE_CODE_MODE_KEY] = True
808
815
  stamped["params"] = params
809
816
  return stamped
810
817
 
@@ -65,6 +65,10 @@ BRIDGE_SESSION_KIND_KEY = "_claude_session_kind"
65
65
  # `--bg` worker drops channel pushes but accepts a line there, so the kernel
66
66
  # delivers `bg` sessions' pushes through it (`ipc.Session._write_inbox`).
67
67
  BRIDGE_INBOX_SOCKET_KEY = "_claude_inbox_socket"
68
+ # True when the bridge's own REPLD_CODE_MODE is "1": whoever launched it
69
+ # promises a client whose scripts consume `exec` results (Claude Code's Code
70
+ # Mode). Nothing the client sends at `initialize` tells the two apart.
71
+ BRIDGE_CODE_MODE_KEY = "_repld_code_mode"
68
72
  CHANNEL_METHOD = "notifications/claude/channel"
69
73
  # Kernel to bridge only, consumed by the bridge and never relayed to the
70
74
  # client: `ipc.rebind_claude_session` telling it the id to stamp from now on.
@@ -113,13 +117,31 @@ CAPABILITIES: dict = {
113
117
 
114
118
  # -- Core tools --------------------------------------------------------------
115
119
 
120
+
121
+ def strip_output_schemas(tools: list[dict]) -> list[dict]:
122
+ """Return `tools` with no `outputSchema`, for a session answered in JSON text alone.
123
+
124
+ A declared `outputSchema` obliges every result to carry `structuredContent`,
125
+ which a `BRIDGE_CODE_MODE_KEY` session never gets.
126
+ """
127
+ return [{k: v for k, v in t.items() if k != "outputSchema"} for t in tools]
128
+
129
+
116
130
  CORE_TOOLS: list[dict] = [
117
131
  {
118
132
  "name": "exec",
119
133
  "title": "Run Python",
120
134
  "description": (
121
- "Run Python in shared __main__. Returns inline within timeout; "
122
- "otherwise {task_id, done:false} with channel push on completion. "
135
+ "Run Python in shared __main__. Returns the cell's output as text "
136
+ "within timeout; otherwise the line `[task <id> still running "
137
+ "after <timeout>s; completion will arrive via channel]` (the id is "
138
+ "in that text, not a field), any output so far, and a channel push "
139
+ "on completion. A value displays as its Python repr, so "
140
+ "print(json.dumps(x)) when the caller will parse the result. One "
141
+ "session's repld calls run one at a time: a long timeout holds its "
142
+ "other calls behind it. A bridge started with REPLD_CODE_MODE=1 "
143
+ "returns JSON values and {task_id, done:false} instead (`repld "
144
+ "help exec`). "
123
145
  "Use defer() for background work that should outlive the response."
124
146
  ),
125
147
  "inputSchema": {
@@ -45,7 +45,8 @@ INSTRUCTIONS_BUDGET = 4096
45
45
  _EXEC_MODEL = (
46
46
  "Execution model: "
47
47
  "exec runs code in shared __main__ (top-level await, _ / _N history). Past "
48
- "`timeout` it returns {task_id, done:false} and pushes a channel message on "
48
+ "`timeout` it returns the text `[task <id> still running after <timeout>s; "
49
+ "completion will arrive via channel]` and pushes a channel message on "
49
50
  "completion, but a session that ends its turn may never see the push "
50
51
  "(`claude -p` never does; an idle `claude --bg` worker only sometimes), so "
51
52
  "poll get_task(task_id) before finishing if you need the result. "
@@ -1530,7 +1531,7 @@ to completion. If B must survive the caller going away, have the target defer()
1530
1531
  the work inside B and return a handle.
1531
1532
 
1532
1533
  A long peer call from an exec cell defers the cell like any slow cell: the
1533
- {task_id, done:false} reply, then a channel push with the value.
1534
+ `[task <id> still running ...]` reply, then a channel push with the value.
1534
1535
 
1535
1536
  == Identity ==
1536
1537
 
@@ -1703,6 +1704,7 @@ gist to its own service, repld://docs/production.
1703
1704
 
1704
1705
  peers.list() -> list[dict]
1705
1706
  peers.get(target, *, start=False) -> Peer target: name | path | "host:name" | "host:path"
1707
+ await peers.close_forwards() -> None cancel the ssh socket forwards of "host:" peers (the kernel does this as it stops)
1706
1708
  await peer.call(target, /, *args, **kwargs) -> JSON value
1707
1709
  await peer.info() -> dict
1708
1710
  await peer.inspect(target) -> dict
@@ -1900,7 +1902,43 @@ Topics:
1900
1902
  _TOPICS: dict[str, str] = {
1901
1903
  "exec": """\
1902
1904
  exec(code, timeout=2.0)
1903
- Inline within timeout; else {task_id, done:false} + channel push.
1905
+ Inline within timeout; else this line, any output so far, + channel push:
1906
+ [task <id> still running after <timeout>s; completion will arrive via channel]
1907
+ The result is text. The task id is in that line, not a field; a value is
1908
+ its Python repr, so print(json.dumps(x)) for a caller that parses it.
1909
+ One session's calls (exec, get_task, cancel, tools) run one at a time on
1910
+ its connection: concurrent calls (a script's Promise.all) run in sequence,
1911
+ and an exec with a long timeout holds the others until it returns.
1912
+
1913
+ REPLD_CODE_MODE=1 in the bridge's environment (read once, at bridge start)
1914
+ shapes that session's exec results for a script (Claude Code's Code Mode):
1915
+ value printed as JSON when json.dumps accepts it (str, bool, None
1916
+ inside containers, dict, list), else its repr as before
1917
+ no output the text `null`, not `(no output)`
1918
+ past timeout the text {"task_id": "...", "done": false}, which the script
1919
+ receives parsed; no sentence, no output so far
1920
+ big output {"truncated": true, "spill_path": "/path", "bytes": N} in
1921
+ place of the head+tail preview; the file holds all of it,
1922
+ so a lone value there is still one line of JSON to parse
1923
+ a raise unchanged: the call throws with the traceback text
1924
+ get_task, cancel and gist tools answer such a session in JSON text alone
1925
+ (no structuredContent, no outputSchema in tools/list): a script receives
1926
+ structuredContent as a string, and JSON text as an object. A gist tool's
1927
+ big output is the same {"truncated": true, ...} pointer. browser_* tools
1928
+ stay prose for a model; a script wanting browser data runs exec on the
1929
+ browser object, e.g. exec("(await browser.get('x')).network()").
1930
+ print() output is untouched, so a cell that prints and returns is still
1931
+ mixed text.
1932
+ To await a backgrounded cell from a script, run through its shell helper
1933
+ repld tasks wait <task_id> --json (--project DIR first, outside the project)
1934
+ which blocks until the task ends, exits 0 (1 if it raised), and prints the
1935
+ get_task snapshot: {"done": true, "text": "{\"answer\": 42}\n",
1936
+ "spill_path": ..., "exception": null, ...}. `text` is the output preview,
1937
+ so JSON.parse it, or read spill_path when "truncated" is true.
1938
+ The variable is a promise by whoever sets it: repld cannot see whether
1939
+ Code Mode is really on, and an ordinary session with it set reads
1940
+ {"task_id": ..., "done": false} with no sentence. Leave it unset for
1941
+ `claude -p` and `--bg`.
1904
1942
  Spill: $XDG_RUNTIME_DIR/repld/{pid}-{tid}.out
1905
1943
  Preview: head+tail + [full output: /path]
1906
1944
 
@@ -2311,6 +2349,7 @@ current_session_id()
2311
2349
  peers.list() -> [{name, cwd, pid, socket_path, started_at, self}]
2312
2350
  peers.get(target, *, start=False) -> Peer sync; a path, or the basename of one live kernel
2313
2351
  peers.get("host:target") -> Peer the same on another machine, over `ssh host`
2352
+ await peers.close_forwards() -> None cancel the ssh socket forwards of host: peers; run at kernel stop
2314
2353
  await peer.call(target, /, *args, **kwargs) -> JSON value; runs the dotted name in THEIR kernel
2315
2354
  await peer.info() -> {peer_protocol, kernel, gists, main}
2316
2355
  await peer.inspect(target) -> {target, kind, signature, async, doc, module, file}
@@ -2404,7 +2443,9 @@ REPL session — import libraries, build up objects, iterate.
2404
2443
  === Timing and deferred tasks ===
2405
2444
 
2406
2445
  If code finishes within timeout (default 2s), result is returned inline.
2407
- Otherwise exec returns {task_id, done:false} and pushes a channel
2446
+ Otherwise exec returns the line
2447
+ `[task <id> still running after <timeout>s; completion will arrive via channel]`
2448
+ (the task id is in that text, not a field) and pushes a channel
2408
2449
  notification when done. Output spills to a file; the inline response
2409
2450
  shows a head+tail preview with a path to the full output. Use Read/Grep
2410
2451
  on that path for the full result.
@@ -260,6 +260,9 @@ class Session:
260
260
  self.elicit_form = False
261
261
  # Same for URL mode, which a client declares separately from form.
262
262
  self.elicit_url = False
263
+ # Whether the bridge stamped `core_schemas.BRIDGE_CODE_MODE_KEY`: this
264
+ # session's `exec` results are shaped for a script, not a reader.
265
+ self.code_mode = False
263
266
  # Set on the first `peer/*` request: a kernel-to-kernel call connection,
264
267
  # one per call, that never sends `initialize`. It is not a session
265
268
  # anything can be pushed to, so `post_channel` refuses and the
@@ -802,7 +802,9 @@ async def _run_cell(task_id: str, src: str, n: int, *, wait_ready: bool = True)
802
802
  return
803
803
 
804
804
  try:
805
- await runtime.run_cell(compiled, __main__.__dict__, n)
805
+ origin = task["origin"]
806
+ as_json = origin is not None and origin.code_mode
807
+ await runtime.run_cell(compiled, __main__.__dict__, n, as_json=as_json)
806
808
  except BaseException as exc:
807
809
  task["exception"] = type(exc).__name__
808
810
 
@@ -22,6 +22,7 @@ import __main__
22
22
  from . import ipc
23
23
  from .browser_dispatch import BrowserDispatchMixin
24
24
  from .core_schemas import (
25
+ BRIDGE_CODE_MODE_KEY,
25
26
  BRIDGE_INBOX_SOCKET_KEY,
26
27
  BRIDGE_PROJECT_DIR_KEY,
27
28
  BRIDGE_SESSION_ID_KEY,
@@ -37,6 +38,7 @@ from .core_schemas import (
37
38
  RESOURCE_TEMPLATES,
38
39
  STATIC_RESOURCES,
39
40
  check_arguments,
41
+ strip_output_schemas,
40
42
  )
41
43
  from .core_schemas import (
42
44
  error as _error,
@@ -877,7 +879,7 @@ class Dispatcher(BrowserDispatchMixin):
877
879
  if method == "ping":
878
880
  return None if rid is None else _response(rid, {})
879
881
  if method == "tools/list":
880
- return self._tools_list(rid)
882
+ return self._tools_list(rid, session)
881
883
  if method == "tools/call":
882
884
  return self._tools_call(rid, params, session)
883
885
  if method == "resources/list":
@@ -940,6 +942,7 @@ class Dispatcher(BrowserDispatchMixin):
940
942
  not elicitation or "form" in elicitation
941
943
  )
942
944
  session.elicit_url = isinstance(elicitation, dict) and "url" in elicitation
945
+ session.code_mode = params.get(BRIDGE_CODE_MODE_KEY) is True
943
946
  if session is not None and claude_id is not None:
944
947
  ipc.register_claude_session(
945
948
  session,
@@ -965,14 +968,31 @@ class Dispatcher(BrowserDispatchMixin):
965
968
  # tools/list, tools/call
966
969
  # ------------------------------------------------------------------
967
970
 
968
- def _tools_list(self, rid) -> dict:
971
+ def _tools_list(self, rid, session: ipc.Session | None = None) -> dict:
969
972
  """Return the full tool catalogue including bridge and gist tools."""
970
973
  if tool_listing_state() != _gist_tools_state:
971
974
  refresh_gist_tools_on_loop(self.ctx.loop)
972
- return _response(rid, {"tools": _build_tools()})
975
+ tools = _build_tools()
976
+ if session is not None and session.code_mode:
977
+ tools = strip_output_schemas(tools)
978
+ return _response(rid, {"tools": tools})
973
979
 
974
980
  def _tools_call(
975
981
  self, rid, params: dict, session: ipc.Session | None = None
982
+ ) -> dict | None:
983
+ """Answer a `tools/call`; `None` once the client cancelled an `exec`.
984
+
985
+ A Code Mode session's result never carries `structuredContent`: Claude
986
+ Code hands a script that as a string, and parses the JSON text block
987
+ every handler sends beside it.
988
+ """
989
+ resp = self._route_tool_call(rid, params, session)
990
+ if resp is not None and session is not None and session.code_mode:
991
+ resp.get("result", {}).pop("structuredContent", None)
992
+ return resp
993
+
994
+ def _route_tool_call(
995
+ self, rid, params: dict, session: ipc.Session | None
976
996
  ) -> dict | None:
977
997
  """Route a `tools/call` to the matching handler; `None` once the client cancelled an `exec`."""
978
998
  name = params.get("name")
@@ -993,7 +1013,7 @@ class Dispatcher(BrowserDispatchMixin):
993
1013
  if name == "get_task":
994
1014
  return self._get_task(rid, args)
995
1015
  if name == "cancel":
996
- return self._cancel(rid, args)
1016
+ return self._cancel(rid, args, session)
997
1017
  if name in _bridge_tool_names():
998
1018
  # We advertise these but never serve them: the bridge answers them
999
1019
  # on the way in. Arriving here means the client is talking to the
@@ -1015,7 +1035,7 @@ class Dispatcher(BrowserDispatchMixin):
1015
1035
  self.ctx.wait_ready()
1016
1036
  if name.startswith("browser_"):
1017
1037
  return self._browser_tool(rid, name, args, session=session)
1018
- return self._gist_tool(rid, name, args)
1038
+ return self._gist_tool(rid, name, args, session)
1019
1039
 
1020
1040
  def _exec(self, rid, args: dict, session: ipc.Session | None = None) -> dict | None:
1021
1041
  """Run a cell and return inline or defer with a task_id; `None` once the client cancelled it."""
@@ -1047,8 +1067,12 @@ class Dispatcher(BrowserDispatchMixin):
1047
1067
  if finished:
1048
1068
  snap = self.ctx.snapshot(task_id)
1049
1069
  assert snap is not None
1070
+ code_mode = session is not None and session.code_mode
1050
1071
  if finished:
1051
- text = _format_spill(snap, "(no output)")
1072
+ # A Code Mode script parses the text: no output and no value is `null`.
1073
+ text = _format_spill(snap, "null" if code_mode else "(no output)")
1074
+ if code_mode and snap["truncated"] and not snap["exception"]:
1075
+ text = _format_spill_pointer(snap["spill_path"])
1052
1076
  return _response(
1053
1077
  rid,
1054
1078
  {
@@ -1062,16 +1086,18 @@ class Dispatcher(BrowserDispatchMixin):
1062
1086
  },
1063
1087
  },
1064
1088
  )
1065
- preview = snap["text"].rstrip()
1066
- msg = f"[task {task_id} still running after {timeout}s; completion will arrive via channel]"
1067
- if preview:
1068
- msg += "\n" + preview
1089
+ meta = {"task_id": task_id, "done": False}
1090
+ if code_mode:
1091
+ # As JSON in the text block, never structuredContent: Claude Code
1092
+ # hands a Code Mode script that as a string, and parses JSON text.
1093
+ msg = json.dumps(meta)
1094
+ else:
1095
+ preview = snap["text"].rstrip()
1096
+ msg = f"[task {task_id} still running after {timeout}s; completion will arrive via channel]"
1097
+ if preview:
1098
+ msg += "\n" + preview
1069
1099
  return _response(
1070
- rid,
1071
- {
1072
- "content": [{"type": "text", "text": msg}],
1073
- "_meta": {"task_id": task_id, "done": False},
1074
- },
1100
+ rid, {"content": [{"type": "text", "text": msg}], "_meta": meta}
1075
1101
  )
1076
1102
 
1077
1103
  def _get_task(self, rid, args: dict) -> dict:
@@ -1092,24 +1118,28 @@ class Dispatcher(BrowserDispatchMixin):
1092
1118
  },
1093
1119
  )
1094
1120
 
1095
- def _cancel(self, rid, args: dict) -> dict:
1096
- """Cancel a running task by id."""
1121
+ def _cancel(self, rid, args: dict, session: ipc.Session | None = None) -> dict:
1122
+ """Cancel a running task by id; a Code Mode session reads the outcome as JSON."""
1097
1123
  tid = args["task_id"]
1098
1124
  accepted = self.ctx.cancel_task(tid)
1125
+ meta = {"task_id": tid, "cancelled": accepted}
1099
1126
  status = "accepted" if accepted else "no-op"
1127
+ text = (
1128
+ json.dumps(meta)
1129
+ if session is not None and session.code_mode
1130
+ else f"cancel task={tid}: {status}"
1131
+ )
1100
1132
  return _response(
1101
- rid,
1102
- {
1103
- "content": [{"type": "text", "text": f"cancel task={tid}: {status}"}],
1104
- "_meta": {"task_id": tid, "cancelled": accepted},
1105
- },
1133
+ rid, {"content": [{"type": "text", "text": text}], "_meta": meta}
1106
1134
  )
1107
1135
 
1108
1136
  # ------------------------------------------------------------------
1109
1137
  # Gist tool dispatch
1110
1138
  # ------------------------------------------------------------------
1111
1139
 
1112
- def _gist_tool(self, rid, name: str, args: dict) -> dict:
1140
+ def _gist_tool(
1141
+ self, rid, name: str, args: dict, session: ipc.Session | None = None
1142
+ ) -> dict:
1113
1143
  """Dispatch to a gist-registered tool handler.
1114
1144
 
1115
1145
  Handlers return str or JSON-serializable data; the text block goes
@@ -1118,6 +1148,8 @@ class Dispatcher(BrowserDispatchMixin):
1118
1148
  exec cell. `structuredContent` carries the dict as-is, it has no
1119
1149
  text-shaped preview to spill. A `content.Image`, or a list holding
1120
1150
  one, becomes one content block per item; an image is never spilled.
1151
+ A Code Mode session gets a spilled block as `_format_spill_pointer`'s
1152
+ JSON, as `exec` does, since a cut preview parses as nothing.
1121
1153
  """
1122
1154
  from .content import Image
1123
1155
 
@@ -1172,9 +1204,12 @@ class Dispatcher(BrowserDispatchMixin):
1172
1204
  and not sp["truncated"]
1173
1205
  ):
1174
1206
  body["structuredContent"] = item
1175
- body["content"].append(
1176
- {"type": "text", "text": _format_spill(sp, text)}
1207
+ shown = (
1208
+ _format_spill_pointer(sp["spill_path"])
1209
+ if sp["truncated"] and session is not None and session.code_mode
1210
+ else _format_spill(sp, text)
1177
1211
  )
1212
+ body["content"].append({"type": "text", "text": shown})
1178
1213
  return _response(rid, body)
1179
1214
  except Exception as exc:
1180
1215
  return _tool_error(rid, f"{name}: {exc}")
@@ -1503,6 +1538,21 @@ def _format_spill(sp: dict, fallback: str) -> str:
1503
1538
  return "\n".join(parts) or fallback
1504
1539
 
1505
1540
 
1541
+ def _format_spill_pointer(spill_path: str) -> str:
1542
+ """Format the JSON a Code Mode script gets for output past the preview size.
1543
+
1544
+ A head+tail preview is neither the data nor parseable; this names the file
1545
+ holding all of it, which the script reads itself.
1546
+ """
1547
+ return json.dumps(
1548
+ {
1549
+ "truncated": True,
1550
+ "spill_path": spill_path,
1551
+ "bytes": os.path.getsize(spill_path),
1552
+ }
1553
+ )
1554
+
1555
+
1506
1556
  def _unknown_task_text(tid: str) -> str:
1507
1557
  """Build the message naming the kernel asked; a task is only known to the kernel it ran on."""
1508
1558
  try:
@@ -9,6 +9,7 @@ import ast
9
9
  import asyncio
10
10
  import gc
11
11
  import inspect
12
+ import json
12
13
  import sys
13
14
  import traceback
14
15
  from typing import Any
@@ -82,8 +83,19 @@ def unwrap_display(result: Any) -> tuple[Any, bool]:
82
83
  return result, False
83
84
 
84
85
 
85
- def print_display(result: Any) -> None:
86
- """Print `result` the way a cell's auto-displayed trailing expression does."""
86
+ def print_display(result: Any, *, as_json: bool = False) -> None:
87
+ """Print `result` the way a cell's auto-displayed trailing expression does.
88
+
89
+ `as_json` prints it as one line of strict JSON when it has such a form
90
+ (a caller that parses the output gets a typed value), else falls back to
91
+ the repr below.
92
+ """
93
+ if as_json:
94
+ try:
95
+ print(json.dumps(result, ensure_ascii=False, allow_nan=False))
96
+ return
97
+ except TypeError, ValueError, RecursionError:
98
+ pass
87
99
  if isinstance(result, str) and "\n" in result:
88
100
  print(result)
89
101
  else:
@@ -178,9 +190,13 @@ def _unwrap_assigned(ns: dict[str, Any], names: set[str]) -> None:
178
190
  ns[name] = val.value
179
191
 
180
192
 
181
- async def run_cell(compiled: tuple, ns: dict[str, Any], n: int) -> Any:
193
+ async def run_cell(
194
+ compiled: tuple, ns: dict[str, Any], n: int, *, as_json: bool = False
195
+ ) -> Any:
182
196
  """Execute a compiled cell and return the last-expression value (or None).
183
197
 
198
+ `as_json` is `print_display`'s: the displayed value as JSON where it has one.
199
+
184
200
  On success, binds `_` and `_{n}` in `ns` to the returned result (when
185
201
  not None). Coroutines from `PyCF_ALLOW_TOP_LEVEL_AWAIT` are awaited.
186
202
  Sync cells run in a background thread to keep the event loop responsive.
@@ -205,7 +221,7 @@ async def run_cell(compiled: tuple, ns: dict[str, Any], n: int) -> Any:
205
221
  if tag in ("eval", "exec_eval") and result is not None:
206
222
  result, quiet = unwrap_display(result)
207
223
  if not quiet:
208
- print_display(result)
224
+ print_display(result, as_json=as_json)
209
225
  # Shift history: _ -> __, __ -> ___. Matches IPython convention.
210
226
  ns["___"] = ns.get("__")
211
227
  ns["__"] = ns.get("_")
File without changes
File without changes
File without changes