@animalabs/agent-framework 0.6.10 → 0.7.2

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 (83) hide show
  1. package/dist/src/agent.d.ts +2 -0
  2. package/dist/src/agent.d.ts.map +1 -1
  3. package/dist/src/agent.js +3 -0
  4. package/dist/src/agent.js.map +1 -1
  5. package/dist/src/code-execution/index.d.ts +14 -0
  6. package/dist/src/code-execution/index.d.ts.map +1 -0
  7. package/dist/src/code-execution/index.js +13 -0
  8. package/dist/src/code-execution/index.js.map +1 -0
  9. package/dist/src/code-execution/py-runner.d.ts +91 -0
  10. package/dist/src/code-execution/py-runner.d.ts.map +1 -0
  11. package/dist/src/code-execution/py-runner.js +364 -0
  12. package/dist/src/code-execution/py-runner.js.map +1 -0
  13. package/dist/src/code-execution/runtime-py.d.ts +32 -0
  14. package/dist/src/code-execution/runtime-py.d.ts.map +1 -0
  15. package/dist/src/code-execution/runtime-py.js +265 -0
  16. package/dist/src/code-execution/runtime-py.js.map +1 -0
  17. package/dist/src/code-execution/tool-definition.d.ts +16 -0
  18. package/dist/src/code-execution/tool-definition.d.ts.map +1 -0
  19. package/dist/src/code-execution/tool-definition.js +45 -0
  20. package/dist/src/code-execution/tool-definition.js.map +1 -0
  21. package/dist/src/framework.d.ts +157 -15
  22. package/dist/src/framework.d.ts.map +1 -1
  23. package/dist/src/framework.js +1068 -104
  24. package/dist/src/framework.js.map +1 -1
  25. package/dist/src/index.d.ts +2 -0
  26. package/dist/src/index.d.ts.map +1 -1
  27. package/dist/src/index.js +4 -0
  28. package/dist/src/index.js.map +1 -1
  29. package/dist/src/mcpl/channel-registry.d.ts +99 -7
  30. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  31. package/dist/src/mcpl/channel-registry.js +374 -49
  32. package/dist/src/mcpl/channel-registry.js.map +1 -1
  33. package/dist/src/mcpl/prose-grammar.d.ts +24 -0
  34. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -0
  35. package/dist/src/mcpl/prose-grammar.js +33 -0
  36. package/dist/src/mcpl/prose-grammar.js.map +1 -0
  37. package/dist/src/mcpl/prose-stream-router.d.ts +58 -0
  38. package/dist/src/mcpl/prose-stream-router.d.ts.map +1 -0
  39. package/dist/src/mcpl/prose-stream-router.js +168 -0
  40. package/dist/src/mcpl/prose-stream-router.js.map +1 -0
  41. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  42. package/dist/src/modules/workspace/index.js +13 -4
  43. package/dist/src/modules/workspace/index.js.map +1 -1
  44. package/dist/src/types/agent.d.ts +17 -0
  45. package/dist/src/types/agent.d.ts.map +1 -1
  46. package/dist/src/types/framework.d.ts +33 -0
  47. package/dist/src/types/framework.d.ts.map +1 -1
  48. package/dist/src/types/trace.d.ts +32 -0
  49. package/dist/src/types/trace.d.ts.map +1 -1
  50. package/dist/test/channel-registry-routing.test.js +186 -10
  51. package/dist/test/channel-registry-routing.test.js.map +1 -1
  52. package/dist/test/code-execution.test.d.ts +11 -0
  53. package/dist/test/code-execution.test.d.ts.map +1 -0
  54. package/dist/test/code-execution.test.js +412 -0
  55. package/dist/test/code-execution.test.js.map +1 -0
  56. package/dist/test/explicit-prose-routing.test.d.ts +11 -0
  57. package/dist/test/explicit-prose-routing.test.d.ts.map +1 -0
  58. package/dist/test/explicit-prose-routing.test.js +247 -0
  59. package/dist/test/explicit-prose-routing.test.js.map +1 -0
  60. package/dist/test/present-while-acting.test.js +85 -8
  61. package/dist/test/present-while-acting.test.js.map +1 -1
  62. package/dist/test/prose-stream-router.test.d.ts +2 -0
  63. package/dist/test/prose-stream-router.test.d.ts.map +1 -0
  64. package/dist/test/prose-stream-router.test.js +87 -0
  65. package/dist/test/prose-stream-router.test.js.map +1 -0
  66. package/dist/test/trunk-channel-routing.test.js +2 -2
  67. package/dist/test/trunk-channel-routing.test.js.map +1 -1
  68. package/dist/tsconfig.tsbuildinfo +1 -1
  69. package/package.json +4 -4
  70. package/src/agent.ts +3 -0
  71. package/src/code-execution/index.ts +19 -0
  72. package/src/code-execution/py-runner.ts +433 -0
  73. package/src/code-execution/runtime-py.ts +265 -0
  74. package/src/code-execution/tool-definition.ts +52 -0
  75. package/src/framework.ts +1160 -107
  76. package/src/index.ts +17 -0
  77. package/src/mcpl/channel-registry.ts +454 -54
  78. package/src/mcpl/prose-grammar.ts +40 -0
  79. package/src/mcpl/prose-stream-router.ts +161 -0
  80. package/src/modules/workspace/index.ts +13 -4
  81. package/src/types/agent.ts +18 -0
  82. package/src/types/framework.ts +35 -0
  83. package/src/types/trace.ts +47 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"py-runner.js","sourceRoot":"","sources":["../../../src/code-execution/py-runner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,eAAe,EAAkB,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAoCxD,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAC7C,MAAM,yBAAyB,GAAG,OAAO,CAAC;AAC1C,MAAM,uBAAuB,GAAG,OAAO,CAAC;AACxC,MAAM,eAAe,GAAG,MAAM,CAAC;AAU/B,MAAM,OAAO,QAAQ;IACF,UAAU,CAAS;IACnB,iBAAiB,CAAS;IAC1B,eAAe,CAAS;IACxB,aAAa,CAAS;IACtB,UAAU,CAAwB;IAClC,KAAK,CAAS;IAEvB,KAAK,GAA0C,IAAI,CAAC;IACpD,UAAU,GAAyB,IAAI,CAAC;IACxC,MAAM,GAAqB,IAAI,CAAC;IAChC,UAAU,GAAkB,IAAI,CAAC;IACjC,OAAO,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,MAAM,EAAE,QAAQ,CAAC,CAAC;QAC3B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Python runtime for client-side programmatic tool calling (PTC).
3
+ *
4
+ * This is the interpreter-side half of the `code_execution` tool: a small
5
+ * asyncio REPL that mimics the environment Anthropic's server-side PTC was
6
+ * trained on (see docs/en/agents-and-tools/tool-use/programmatic-tool-calling):
7
+ *
8
+ * - scripts run with top-level `await` (PyCF_ALLOW_TOP_LEVEL_AWAIT)
9
+ * - host tools are injected as async functions taking a single dict and
10
+ * returning a string (the tool_result text)
11
+ * - a pending tool call that gets no response raises TimeoutError with the
12
+ * same message shape the managed runtime produces
13
+ * - interpreter globals persist across execs (container-reuse semantics)
14
+ *
15
+ * Embedded as a TS string because tsc does not copy non-TS assets to dist/;
16
+ * PyRunner materializes it to a temp file at spawn.
17
+ *
18
+ * Protocol (JSON lines):
19
+ * host -> py : {op:"init", tools:[{py_name,tool_name}], call_timeout_s}
20
+ * {op:"exec", id, code}
21
+ * {op:"tool_result", id, result}
22
+ * {op:"cancel", id, reason?}
23
+ * py -> host : {op:"ready"}
24
+ * {op:"tool_call", id, exec_id, name, args}
25
+ * {op:"exec_result", id, stdout, stderr, return_code}
26
+ *
27
+ * IMPORTANT: the python source below must not contain backticks or the
28
+ * sequence dollar+brace (TS template literal syntax). String.raw preserves
29
+ * backslashes, so \n inside python string literals is fine.
30
+ */
31
+ export declare const PYTHON_RUNTIME_SOURCE: string;
32
+ //# sourceMappingURL=runtime-py.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-py.d.ts","sourceRoot":"","sources":["../../../src/code-execution/runtime-py.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,eAAO,MAAM,qBAAqB,EAAE,MAyOnC,CAAC"}
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Python runtime for client-side programmatic tool calling (PTC).
3
+ *
4
+ * This is the interpreter-side half of the `code_execution` tool: a small
5
+ * asyncio REPL that mimics the environment Anthropic's server-side PTC was
6
+ * trained on (see docs/en/agents-and-tools/tool-use/programmatic-tool-calling):
7
+ *
8
+ * - scripts run with top-level `await` (PyCF_ALLOW_TOP_LEVEL_AWAIT)
9
+ * - host tools are injected as async functions taking a single dict and
10
+ * returning a string (the tool_result text)
11
+ * - a pending tool call that gets no response raises TimeoutError with the
12
+ * same message shape the managed runtime produces
13
+ * - interpreter globals persist across execs (container-reuse semantics)
14
+ *
15
+ * Embedded as a TS string because tsc does not copy non-TS assets to dist/;
16
+ * PyRunner materializes it to a temp file at spawn.
17
+ *
18
+ * Protocol (JSON lines):
19
+ * host -> py : {op:"init", tools:[{py_name,tool_name}], call_timeout_s}
20
+ * {op:"exec", id, code}
21
+ * {op:"tool_result", id, result}
22
+ * {op:"cancel", id, reason?}
23
+ * py -> host : {op:"ready"}
24
+ * {op:"tool_call", id, exec_id, name, args}
25
+ * {op:"exec_result", id, stdout, stderr, return_code}
26
+ *
27
+ * IMPORTANT: the python source below must not contain backticks or the
28
+ * sequence dollar+brace (TS template literal syntax). String.raw preserves
29
+ * backslashes, so \n inside python string literals is fine.
30
+ */
31
+ export const PYTHON_RUNTIME_SOURCE = String.raw `
32
+ import ast
33
+ import asyncio
34
+ import inspect
35
+ import io
36
+ import json
37
+ import sys
38
+ import threading
39
+ import traceback
40
+
41
+ PROTO_OUT = sys.stdout # protocol channel (real stdout)
42
+ REAL_STDERR = sys.stderr # runtime diagnostics outside execs
43
+ CALL_TIMEOUT_S = 270.0
44
+ OUTPUT_CAP_CHARS = 2_000_000
45
+
46
+ _send_lock = threading.Lock()
47
+
48
+
49
+ def send(obj):
50
+ line = json.dumps(obj, ensure_ascii=False, default=str)
51
+ with _send_lock:
52
+ PROTO_OUT.write(line + "\n")
53
+ PROTO_OUT.flush()
54
+
55
+
56
+ class CappedIO(io.StringIO):
57
+ """StringIO that stops recording past a cap (keeps a truncation flag)."""
58
+
59
+ def __init__(self, cap):
60
+ super().__init__()
61
+ self._cap = cap
62
+ self.truncated = False
63
+
64
+ def write(self, s):
65
+ if not isinstance(s, str):
66
+ s = str(s)
67
+ if self.tell() >= self._cap:
68
+ self.truncated = True
69
+ return len(s)
70
+ remaining = self._cap - self.tell()
71
+ if len(s) > remaining:
72
+ self.truncated = True
73
+ return super().write(s[:remaining])
74
+ return super().write(s)
75
+
76
+
77
+ # Persistent interpreter state (mirrors container reuse: variables survive
78
+ # between exec calls until the host reclaims the interpreter).
79
+ SCRIPT_GLOBALS = {"__name__": "__main__", "__builtins__": __builtins__}
80
+ _injected_py_names = set()
81
+
82
+ _pending_tool_futures = {}
83
+ _next_tool_call_id = 0
84
+ _current_exec_id = None
85
+ _current_exec_task = None
86
+
87
+
88
+ def _make_tool_fn(tool_name, py_name):
89
+ async def tool_fn(args=None):
90
+ global _next_tool_call_id
91
+ if args is None:
92
+ args = {}
93
+ if not isinstance(args, dict):
94
+ raise TypeError(
95
+ "tool functions take a single dict of arguments, e.g. await "
96
+ + py_name + "({...})"
97
+ )
98
+ _next_tool_call_id += 1
99
+ call_id = "t" + str(_next_tool_call_id)
100
+ fut = asyncio.get_running_loop().create_future()
101
+ _pending_tool_futures[call_id] = fut
102
+ send({
103
+ "op": "tool_call",
104
+ "id": call_id,
105
+ "exec_id": _current_exec_id,
106
+ "name": tool_name,
107
+ "args": args,
108
+ })
109
+ try:
110
+ return await asyncio.wait_for(fut, timeout=CALL_TIMEOUT_S)
111
+ except asyncio.TimeoutError:
112
+ raise TimeoutError(
113
+ "Calling tool ['" + tool_name + "'] timed out (no response after "
114
+ + str(int(CALL_TIMEOUT_S)) + "s)."
115
+ )
116
+ finally:
117
+ _pending_tool_futures.pop(call_id, None)
118
+
119
+ tool_fn.__name__ = py_name
120
+ tool_fn.__qualname__ = py_name
121
+ tool_fn.__doc__ = (
122
+ "Host tool '" + tool_name + "'. Takes a single dict of arguments and "
123
+ "returns the tool result as a string."
124
+ )
125
+ return tool_fn
126
+
127
+
128
+ def handle_init(msg):
129
+ global CALL_TIMEOUT_S
130
+ timeout = msg.get("call_timeout_s")
131
+ if isinstance(timeout, (int, float)) and timeout > 0:
132
+ CALL_TIMEOUT_S = float(timeout)
133
+
134
+ # Remove functions injected by a previous init that are no longer present
135
+ # (tool list changed) without touching user-defined globals.
136
+ new_tools = msg.get("tools") or []
137
+ new_py_names = set()
138
+ tools_dict = {}
139
+ for entry in new_tools:
140
+ py_name = entry.get("py_name")
141
+ tool_name = entry.get("tool_name")
142
+ if not py_name or not tool_name:
143
+ continue
144
+ fn = _make_tool_fn(tool_name, py_name)
145
+ SCRIPT_GLOBALS[py_name] = fn
146
+ tools_dict[tool_name] = fn
147
+ new_py_names.add(py_name)
148
+ for stale in _injected_py_names - new_py_names:
149
+ SCRIPT_GLOBALS.pop(stale, None)
150
+ _injected_py_names.clear()
151
+ _injected_py_names.update(new_py_names)
152
+ # Exact-name escape hatch: tools["mcpl--server--tool"]({...})
153
+ SCRIPT_GLOBALS["tools"] = tools_dict
154
+
155
+
156
+ async def _run_script(exec_id, code):
157
+ global _current_exec_id, _current_exec_task
158
+ out = CappedIO(OUTPUT_CAP_CHARS)
159
+ err = CappedIO(OUTPUT_CAP_CHARS)
160
+ old_out, old_err, old_in = sys.stdout, sys.stderr, sys.stdin
161
+ sys.stdout, sys.stderr = out, err
162
+ sys.stdin = io.StringIO("") # input() must not steal the protocol channel
163
+ return_code = 0
164
+ try:
165
+ compiled = compile(code, "<script>", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
166
+ result = eval(compiled, SCRIPT_GLOBALS)
167
+ if inspect.iscoroutine(result):
168
+ await result
169
+ except asyncio.CancelledError:
170
+ err.write("\nKeyboardInterrupt: script cancelled by host\n")
171
+ return_code = 1
172
+ except BaseException:
173
+ traceback.print_exc(file=err)
174
+ return_code = 1
175
+ finally:
176
+ sys.stdout, sys.stderr, sys.stdin = old_out, old_err, old_in
177
+ _current_exec_id = None
178
+ _current_exec_task = None
179
+ # Fail any tool futures still pending: their exec is gone.
180
+ for fut in list(_pending_tool_futures.values()):
181
+ if not fut.done():
182
+ fut.cancel()
183
+ _pending_tool_futures.clear()
184
+
185
+ stdout_text = out.getvalue()
186
+ if out.truncated:
187
+ stdout_text += "\n[stdout truncated at " + str(OUTPUT_CAP_CHARS) + " chars]"
188
+ stderr_text = err.getvalue()
189
+ if err.truncated:
190
+ stderr_text += "\n[stderr truncated at " + str(OUTPUT_CAP_CHARS) + " chars]"
191
+ send({
192
+ "op": "exec_result",
193
+ "id": exec_id,
194
+ "stdout": stdout_text,
195
+ "stderr": stderr_text,
196
+ "return_code": return_code,
197
+ })
198
+
199
+
200
+ async def main():
201
+ global _current_exec_id, _current_exec_task
202
+ loop = asyncio.get_running_loop()
203
+ queue = asyncio.Queue()
204
+
205
+ def reader():
206
+ for raw_line in sys.stdin:
207
+ loop.call_soon_threadsafe(queue.put_nowait, raw_line)
208
+ loop.call_soon_threadsafe(queue.put_nowait, None)
209
+
210
+ threading.Thread(target=reader, daemon=True).start()
211
+ send({"op": "ready"})
212
+
213
+ while True:
214
+ line = await queue.get()
215
+ if line is None:
216
+ break
217
+ line = line.strip()
218
+ if not line:
219
+ continue
220
+ try:
221
+ msg = json.loads(line)
222
+ except Exception:
223
+ REAL_STDERR.write("[pytc-runtime] bad protocol line\n")
224
+ REAL_STDERR.flush()
225
+ continue
226
+ op = msg.get("op")
227
+ if op == "init":
228
+ handle_init(msg)
229
+ elif op == "exec":
230
+ if _current_exec_task is not None and not _current_exec_task.done():
231
+ send({
232
+ "op": "exec_result",
233
+ "id": msg.get("id"),
234
+ "stdout": "",
235
+ "stderr": "RuntimeError: another script is already running in this interpreter",
236
+ "return_code": 1,
237
+ })
238
+ continue
239
+ _current_exec_id = msg.get("id")
240
+ _current_exec_task = asyncio.ensure_future(
241
+ _run_script(msg.get("id"), msg.get("code") or "")
242
+ )
243
+ elif op == "tool_result":
244
+ fut = _pending_tool_futures.get(msg.get("id"))
245
+ if fut is not None and not fut.done():
246
+ fut.set_result(str(msg.get("result", "")))
247
+ elif op == "cancel":
248
+ if _current_exec_task is not None and not _current_exec_task.done():
249
+ _current_exec_task.cancel()
250
+ elif op == "exit":
251
+ break
252
+
253
+ # Drain: give a cancelled exec a moment to emit its exec_result.
254
+ if _current_exec_task is not None and not _current_exec_task.done():
255
+ _current_exec_task.cancel()
256
+ try:
257
+ await asyncio.wait_for(_current_exec_task, timeout=2)
258
+ except BaseException:
259
+ pass
260
+
261
+
262
+ if __name__ == "__main__":
263
+ asyncio.run(main())
264
+ `;
265
+ //# sourceMappingURL=runtime-py.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-py.js","sourceRoot":"","sources":["../../../src/code-execution/runtime-py.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,MAAM,CAAC,MAAM,qBAAqB,GAAW,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyOtD,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Synthesized `code_execution` tool definition.
3
+ *
4
+ * The name, input shape ({code}), and description framing deliberately track
5
+ * Anthropic's server-side programmatic tool calling so models' trained
6
+ * priors transfer: python scripts, tools as async functions taking a single
7
+ * dict and returning a string, stdout as the return channel, persistent
8
+ * interpreter state, asyncio.gather for fan-out.
9
+ */
10
+ import type { ToolDefinition } from '../types/index.js';
11
+ export declare const CODE_EXECUTION_TOOL_NAME = "code_execution";
12
+ export declare function buildCodeExecutionToolDefinition(opts?: {
13
+ idleReclaimMs?: number;
14
+ toolCallTimeoutMs?: number;
15
+ }): ToolDefinition;
16
+ //# sourceMappingURL=tool-definition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-definition.d.ts","sourceRoot":"","sources":["../../../src/code-execution/tool-definition.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,eAAO,MAAM,wBAAwB,mBAAmB,CAAC;AAEzD,wBAAgB,gCAAgC,CAAC,IAAI,CAAC,EAAE;IACtD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,GAAG,cAAc,CAkCjB"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Synthesized `code_execution` tool definition.
3
+ *
4
+ * The name, input shape ({code}), and description framing deliberately track
5
+ * Anthropic's server-side programmatic tool calling so models' trained
6
+ * priors transfer: python scripts, tools as async functions taking a single
7
+ * dict and returning a string, stdout as the return channel, persistent
8
+ * interpreter state, asyncio.gather for fan-out.
9
+ */
10
+ export const CODE_EXECUTION_TOOL_NAME = 'code_execution';
11
+ export function buildCodeExecutionToolDefinition(opts) {
12
+ const idleMinutes = Math.max(1, Math.round((opts?.idleReclaimMs ?? 300_000) / 60_000));
13
+ const callTimeoutSeconds = Math.round((opts?.toolCallTimeoutMs ?? 270_000) / 1000);
14
+ return {
15
+ name: CODE_EXECUTION_TOOL_NAME,
16
+ description: 'Run Python code that can call your other tools programmatically. ' +
17
+ 'Every tool you have is available inside the script as an async Python function: ' +
18
+ "the function name is the tool name with '--' replaced by '__' " +
19
+ "(e.g. tool 'mcpl--discord--fetch_history' is the function mcpl__discord__fetch_history). " +
20
+ 'Each function takes a single dict of arguments and returns a string — the same text ' +
21
+ 'the tool would have returned to you directly; parse structured results with json.loads. ' +
22
+ "An exact-name lookup dict is also available: tools['mcpl--discord--fetch_history']({...}). " +
23
+ 'Use top-level await; run independent calls in parallel with asyncio.gather. ' +
24
+ 'Only what you print() (plus stderr and the exit code) comes back to you — intermediate ' +
25
+ 'tool results stay in the script, so filter or aggregate large data there and print only ' +
26
+ 'what you need. Interpreter state (variables, imports) persists across code_execution ' +
27
+ `calls but is reclaimed after ~${idleMinutes} minutes idle. A tool call that receives no ` +
28
+ `response within ~${callTimeoutSeconds}s raises TimeoutError inside the script. ` +
29
+ 'Use this when fanning out across many items, looping over tool calls, or when tool ' +
30
+ 'results are large and you only need a slice or summary. Call tools directly (not via ' +
31
+ 'code) when a single call answers the question or when you need to reason about each ' +
32
+ 'result before deciding the next step.',
33
+ inputSchema: {
34
+ type: 'object',
35
+ properties: {
36
+ code: {
37
+ type: 'string',
38
+ description: 'Python code to execute. Top-level await is allowed.',
39
+ },
40
+ },
41
+ required: ['code'],
42
+ },
43
+ };
44
+ }
45
+ //# sourceMappingURL=tool-definition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-definition.js","sourceRoot":"","sources":["../../../src/code-execution/tool-definition.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,MAAM,CAAC,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAEzD,MAAM,UAAU,gCAAgC,CAAC,IAGhD;IACC,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,aAAa,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;IACvF,MAAM,kBAAkB,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,iBAAiB,IAAI,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;IACnF,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,WAAW,EACT,mEAAmE;YACnE,kFAAkF;YAClF,gEAAgE;YAChE,2FAA2F;YAC3F,sFAAsF;YACtF,0FAA0F;YAC1F,6FAA6F;YAC7F,8EAA8E;YAC9E,yFAAyF;YACzF,0FAA0F;YAC1F,uFAAuF;YACvF,iCAAiC,WAAW,8CAA8C;YAC1F,oBAAoB,kBAAkB,2CAA2C;YACjF,qFAAqF;YACrF,uFAAuF;YACvF,sFAAsF;YACtF,uCAAuC;QACzC,WAAW,EAAE;YACX,IAAI,EAAE,QAAiB;YACvB,UAAU,EAAE;gBACV,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;oBACd,WAAW,EAAE,qDAAqD;iBACnE;aACF;YACD,QAAQ,EAAE,CAAC,MAAM,CAAC;SACnB;KACF,CAAC;AACJ,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { JsStore } from '@animalabs/chronicle';
2
2
  import type { Membrane, NormalizedRequest } from '@animalabs/membrane';
3
3
  import { ContextManager } from '@animalabs/context-manager';
4
+ import type { TokenBudget } from '@animalabs/context-manager';
4
5
  import type { FrameworkConfig, TraceEventListener, InferenceLogQuery, InferenceLogQueryResult, InferenceLogEntryWithId, ProcessLogQuery, ProcessLogQueryResult, ProcessLogEntryWithId, ProcessEvent, ToolCall, ToolResult, AgentConfig, Module, ContextMaintenanceSnapshot, AgentRuntimeSettingsPatch, AgentRuntimeSettingsSnapshot } from './types/index.js';
5
6
  import { Agent } from './agent.js';
6
7
  import { ChannelRegistry } from './mcpl/channel-registry.js';
@@ -44,20 +45,36 @@ export declare class AgentFramework {
44
45
  private processLoggingPersist;
45
46
  private processLoggingBroadcast;
46
47
  private activeStreams;
47
- /** Per-agent output locus pinned for the CURRENT logical turn (see
48
- * resolveTurnLocus in driveStream). Lives here — not in driveStream
49
- * locals — so the pin survives a context-budget stream restart, which
50
- * continues the same logical turn in a fresh driveStream. A mid-turn
51
- * injected channel message replaces the pin for the next conversational
52
- * round; otherwise it remains stable. Cleared at the start of every
53
- * non-restart turn. */
48
+ /** Per-agent output locus FROZEN for the CURRENT logical turn. Resolved
49
+ * eagerly in startAgentStream (home → addressed trigger → global default)
50
+ * and never moved until the next turn: mid-turn injected messages — ambient
51
+ * chatter, reactions, system markers — must not hijack where the agent's
52
+ * plain prose lands (2026-07-21 Cairn lounge misroute). Lives here — not in
53
+ * driveStream locals — so the pin survives a context-budget stream restart,
54
+ * which continues the same logical turn in a fresh driveStream. Cleared or
55
+ * re-set at the start of every non-restart turn. */
54
56
  private turnLocusPins;
55
- /** A tool boundary injected fresh external input into the live stream.
56
- * Presence (including a null value) tells driveStream to clear sticky
57
- * explicit-send suppression before handling the next model round. A
58
- * string also moves that round's reply locus to the newest injected
59
- * channel. */
60
- private midTurnRoutingResets;
57
+ /** A tool boundary injected fresh CONVERSATIONAL input (a real message —
58
+ * not a reaction or a system marker) into the live stream. Tells
59
+ * driveStream to clear sticky explicit-send suppression before handling
60
+ * the next model round. Never affects routing: the turn locus is frozen. */
61
+ private midTurnInputSignals;
62
+ /** Last outbound locus announced to each agent as a durable `[routing]`
63
+ * window message. Announce-on-change only: steady state emits nothing
64
+ * (KV-safe, no per-turn chatter). In-memory — after a process restart the
65
+ * first turn's locus is announced once to re-establish the baseline. */
66
+ private lastAnnouncedLocus;
67
+ /** Latest bounced (undelivered) prose per agent — the `{{unsent}}` source. */
68
+ private proseClipboards;
69
+ /** Sticky per-TURN delivery target set by the turn's first `>>` prefix.
70
+ * Cleared at every non-restart turn start; survives context restarts. */
71
+ private proseTargetPins;
72
+ /** Agents whose current turn requested `!` continuation — re-woken when the
73
+ * turn completes instead of pausing until the next external event. */
74
+ private proseContinuations;
75
+ /** Consecutive bounce-wakes per agent; capped so an agent that keeps
76
+ * emitting unprefixed prose can't wake-loop (notices still append). */
77
+ private proseBounceStreaks;
61
78
  private pendingAssistantBlocks;
62
79
  /** Streams the FRAMEWORK cancelled for non-terminal reasons, keyed
63
80
  * `${agentName}:${streamId}`: an endTurn tool result or a context-budget
@@ -143,6 +160,13 @@ export declare class AgentFramework {
143
160
  /** Forks whose TTL closure turn has been queued — disposed (removed from
144
161
  * agents/agentConfigs/conversationAgentHomes) when their stream ends. */
145
162
  private closingConversationAgents;
163
+ private codeExecutionConfig;
164
+ private codeExecutionRunners;
165
+ private scriptToolWaiters;
166
+ /** Agents whose running script hit an endTurn-carrying inner result —
167
+ * deferred and applied to the final code_execution result instead of
168
+ * cancelling the stream mid-script (which would wedge the turn). */
169
+ private scriptDeferredEndTurn;
146
170
  private mcplTools;
147
171
  private mcplToolRefreshInFlight;
148
172
  private mcplToolRefreshPending;
@@ -263,8 +287,36 @@ export declare class AgentFramework {
263
287
  private buildAgentSettingsTool;
264
288
  private getToolsForAgent;
265
289
  getAgentRuntimeSettings(agentName: string): AgentRuntimeSettingsSnapshot;
266
- updateAgentRuntimeSettings(agentName: string, patch: AgentRuntimeSettingsPatch): AgentRuntimeSettingsSnapshot;
267
- resetAgentRuntimeSettings(agentName: string, keys?: Array<keyof AgentRuntimeSettingsPatch>): AgentRuntimeSettingsSnapshot;
290
+ /**
291
+ * Apply runtime settings.
292
+ *
293
+ * `opts.persist: false` makes the change EPHEMERAL: it takes effect live but
294
+ * is not written to the `framework/state` slot, so a restart reverts it. That
295
+ * is the mode for operator experiments ("change it, watch, revert") — the
296
+ * default persists, because a durable operational change should survive a
297
+ * bounce like every other override.
298
+ *
299
+ * Nothing here notifies the agent. Discovery is deliberately PULL: the agent
300
+ * can read current settings any time via the `agent_settings` tool's `get`
301
+ * action, which costs no context perturbation. Pushing a notice injects text
302
+ * into the very context being tuned — it invalidates the KV prefix and can
303
+ * itself trip a classifier — so callers opt into that explicitly rather than
304
+ * getting it by default.
305
+ *
306
+ * KNOWN LIMITATION of `persist: false`: the change still lands in the agent's
307
+ * in-memory override map, and `persistAgentRuntimeSettings` writes that whole
308
+ * map. So a LATER persisting call promotes any still-live ephemeral change to
309
+ * durable as a side effect. Ephemeral means "not written by THIS call", not
310
+ * "can never be written". Reset the ephemeral key before persisting something
311
+ * else if that matters. Making it airtight needs per-key ephemeral tracking
312
+ * inside Agent.
313
+ */
314
+ updateAgentRuntimeSettings(agentName: string, patch: AgentRuntimeSettingsPatch, opts?: {
315
+ persist?: boolean;
316
+ }): AgentRuntimeSettingsSnapshot;
317
+ resetAgentRuntimeSettings(agentName: string, keys?: Array<keyof AgentRuntimeSettingsPatch>, opts?: {
318
+ persist?: boolean;
319
+ }): AgentRuntimeSettingsSnapshot;
268
320
  cancelAgentRuntimeSettingsTransition(agentName: string): AgentRuntimeSettingsSnapshot;
269
321
  /** Counts-only context-maintenance diagnostics for authenticated debug UIs. */
270
322
  getContextMaintenanceSnapshot(): ContextMaintenanceSnapshot;
@@ -295,7 +347,24 @@ export declare class AgentFramework {
295
347
  */
296
348
  previewActivation(agentName: string, opts?: {
297
349
  injections?: boolean;
350
+ budget?: TokenBudget;
298
351
  }): Promise<NormalizedRequest>;
352
+ /**
353
+ * Non-committing preview of the FOLD PLAN at a hypothetical budget and/or
354
+ * context settings — the numbers behind an operator's "what happens if I set
355
+ * the budget to X" before they apply it.
356
+ *
357
+ * Unlike `previewActivation` (which renders a request), this returns the
358
+ * picker's plan: resulting tokens, whether it fits, how many summaries would
359
+ * have to be produced first, and the per-chunk fold levels. Commits nothing:
360
+ * no resolution persistence, no compression enqueue, no transition
361
+ * bookkeeping — see `AutobiographicalStrategy.previewContext`.
362
+ *
363
+ * Returns null when the agent's strategy has no fold plan (non-adaptive).
364
+ */
365
+ previewContextSettings(agentName: string, budgetTokens: number, overrides?: Record<string, unknown>, opts?: {
366
+ render?: boolean;
367
+ }): unknown;
299
368
  /**
300
369
  * Check if process logging is enabled.
301
370
  */
@@ -639,6 +708,46 @@ export declare class AgentFramework {
639
708
  */
640
709
  private derivePushEventChannel;
641
710
  private processInferenceRequests;
711
+ /**
712
+ * Announce-on-change locus notice (turn-frozen routing). Appends a durable
713
+ * `[routing]` window message when the turn's effective outbound locus
714
+ * differs from the last one announced — the agent must never have to guess
715
+ * where its plain prose lands. Durable append (never retracted) keeps the
716
+ * KV prefix stable; change-only keeps it out of steady-state turns. The
717
+ * first resolution after boot announces only a non-null locus ("prose has
718
+ * no destination" is the unremarkable boot default). Never triggers
719
+ * inference; never locus-eligible itself (system + no channel metadata).
720
+ */
721
+ private announceLocusIfChanged;
722
+ /**
723
+ * Durable window notice for a channel the agent did not ask to open —
724
+ * subscription-policy admission, or an open forced by the agent's own
725
+ * delivery into a closed channel. The agent must always learn that new
726
+ * traffic will start flowing, and that `channel_close` opts out (their
727
+ * decision outranks policy). System message: never triggers inference,
728
+ * never conversational, never locus-eligible.
729
+ */
730
+ private recordChannelAutoOpenNotice;
731
+ /**
732
+ * Explicit-prose-routing delivery gateway (docs/explicit-prose-routing.md).
733
+ * Every prose segment of an `explicit`-mode agent flows through here:
734
+ * parse the `>>` prefix, resolve the target, deliver — or bounce to the
735
+ * clipboard with a resend notice. Misdelivery is structurally impossible:
736
+ * nothing is ever sent to a destination the model did not name (directly
737
+ * or via the turn's sticky target).
738
+ */
739
+ private deliverProse;
740
+ private deliverProseEnvelope;
741
+ /** Cap on consecutive bounce-triggered wakes (notices still append after). */
742
+ private static readonly PROSE_BOUNCE_WAKE_CAP;
743
+ private bounceProse;
744
+ /**
745
+ * One-time mode primer (docs/explicit-prose-routing.md): when an agent's
746
+ * configured proseRouting differs from the last mode we primed them for,
747
+ * append the teaching notice and persist the new mode. A brand-new agent
748
+ * in default locus mode is recorded silently — no primer for the status quo.
749
+ */
750
+ private maybePrimeProseMode;
642
751
  private startAgentStream;
643
752
  private driveStream;
644
753
  /**
@@ -648,6 +757,39 @@ export declare class AgentFramework {
648
757
  */
649
758
  executeToolCall(call: ToolCall): Promise<ToolResult>;
650
759
  private executeMcplToolCall;
760
+ /** Event-pushing wrapper for the model-driven dispatch path. */
761
+ private dispatchCodeExecutionToolCall;
762
+ /**
763
+ * Run one code_execution script for an agent. Never rejects.
764
+ *
765
+ * The script runs in the agent's persistent python interpreter with every
766
+ * tool on the agent's CURRENT surface injected (minus code_execution
767
+ * itself). Inner tool calls are dispatched through dispatchToolCall — the
768
+ * exact model path, including MCPL state/checkpoint handling, channel
769
+ * routing, and traces — and resolved via scriptToolWaiters, so their
770
+ * results reach the running script and never the model context.
771
+ */
772
+ private runCodeExecution;
773
+ private getOrCreateScriptRunner;
774
+ /**
775
+ * Resolve one script-inner tool call to the string the script's tool
776
+ * function returns. Never rejects — errors become "Error: ..." strings,
777
+ * matching the managed PTC runtime ("Claude's code receives this error").
778
+ *
779
+ * Results are serialized with the HISTORY serializer (images become
780
+ * placeholders): programmatic tool results are text-only by contract, and
781
+ * a script variable holding megabytes of base64 helps nobody.
782
+ */
783
+ private handleScriptToolCall;
784
+ /**
785
+ * Dispatch a script-inner tool call through the NORMAL dispatch path and
786
+ * resolve with its result. The waiter intercept in handleProcessEvent
787
+ * (keyed by the pytc- call ID) routes the tool-result event here instead
788
+ * of into the agent's pending tool round.
789
+ */
790
+ private dispatchScriptToolCall;
791
+ /** Abort a running script when the agent's turn dies underneath it. */
792
+ private abortAgentScript;
651
793
  private toMembraneToolResult;
652
794
  /**
653
795
  * If `data` is an MCP tool-result content array carrying at least one image,