@markusylisiurunen/tau 0.3.45 → 0.3.47

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 (106) hide show
  1. package/README.md +56 -6
  2. package/dist/code_mode/command.d.ts +2 -0
  3. package/dist/code_mode/command.js +31 -0
  4. package/dist/code_mode/command.js.map +1 -0
  5. package/dist/code_mode/index.d.ts +4 -0
  6. package/dist/code_mode/index.js +4 -0
  7. package/dist/code_mode/index.js.map +1 -0
  8. package/dist/code_mode/runtime.d.ts +82 -0
  9. package/dist/code_mode/runtime.js +298 -0
  10. package/dist/code_mode/runtime.js.map +1 -0
  11. package/dist/core/agent/agent_runtime.js +1 -1
  12. package/dist/core/agent/agent_runtime.js.map +1 -1
  13. package/dist/core/debug.js +2 -2
  14. package/dist/core/debug.js.map +1 -1
  15. package/dist/core/runtime/chat_runtime.js +10 -6
  16. package/dist/core/runtime/chat_runtime.js.map +1 -1
  17. package/dist/core/runtime/deps.js +0 -1
  18. package/dist/core/runtime/deps.js.map +1 -1
  19. package/dist/core/runtime/runtime_bootstrap.js +20 -3
  20. package/dist/core/runtime/runtime_bootstrap.js.map +1 -1
  21. package/dist/core/runtime/session_prompt_composer.js +6 -4
  22. package/dist/core/runtime/session_prompt_composer.js.map +1 -1
  23. package/dist/core/session/runner.js +4 -3
  24. package/dist/core/session/runner.js.map +1 -1
  25. package/dist/core/static/code_mode/history/documentation.md +1 -12
  26. package/dist/core/static/code_mode/history/sandbox_runner.mjs +1 -111
  27. package/dist/core/static/code_mode/nook/documentation.md +1 -14
  28. package/dist/core/static/code_mode/nook/sandbox_runner.mjs +1 -147
  29. package/dist/core/static/code_mode/sandbox_runner.mjs +186 -0
  30. package/dist/core/static/code_mode/web/documentation.md +1 -13
  31. package/dist/core/static/code_mode/web/sandbox_runner.mjs +1 -115
  32. package/dist/core/subagents/agent_supervisor.js +64 -31
  33. package/dist/core/subagents/agent_supervisor.js.map +1 -1
  34. package/dist/core/subagents/types.js +0 -1
  35. package/dist/core/subagents/types.js.map +1 -1
  36. package/dist/core/tools/bash.js +1 -1
  37. package/dist/core/tools/bash.js.map +1 -1
  38. package/dist/core/tools/code_mode.js +41 -47
  39. package/dist/core/tools/code_mode.js.map +1 -1
  40. package/dist/core/tools/code_mode_worker.js +43 -12
  41. package/dist/core/tools/code_mode_worker.js.map +1 -1
  42. package/dist/core/tools/history.js +16 -26
  43. package/dist/core/tools/history.js.map +1 -1
  44. package/dist/core/tools/nook.js +33 -21
  45. package/dist/core/tools/nook.js.map +1 -1
  46. package/dist/core/tools/web.js +15 -20
  47. package/dist/core/tools/web.js.map +1 -1
  48. package/dist/core/utils/context_builder.js +11 -9
  49. package/dist/core/utils/context_builder.js.map +1 -1
  50. package/dist/core/utils/spawn_capture.js +19 -5
  51. package/dist/core/utils/spawn_capture.js.map +1 -1
  52. package/dist/core/version.js +1 -1
  53. package/dist/host/execution_runtime.js +3 -2
  54. package/dist/host/execution_runtime.js.map +1 -1
  55. package/dist/host/hosted_ephemeral_agent_session.js +3 -2
  56. package/dist/host/hosted_ephemeral_agent_session.js.map +1 -1
  57. package/dist/host/local_session_host.js +90 -32
  58. package/dist/host/local_session_host.js.map +1 -1
  59. package/dist/host/session_host.js.map +1 -1
  60. package/dist/host/session_protocol_handler.js +29 -0
  61. package/dist/host/session_protocol_handler.js.map +1 -1
  62. package/dist/protocol/index.d.ts +2 -2
  63. package/dist/protocol/index.js +1 -1
  64. package/dist/protocol/index.js.map +1 -1
  65. package/dist/protocol/session_protocol.d.ts +66 -3
  66. package/dist/protocol/session_protocol.js +297 -1
  67. package/dist/protocol/session_protocol.js.map +1 -1
  68. package/dist/sdk/client_tool_command.d.ts +63 -0
  69. package/dist/sdk/client_tool_command.js +282 -0
  70. package/dist/sdk/client_tool_command.js.map +1 -0
  71. package/dist/sdk/code_mode.d.ts +6 -0
  72. package/dist/sdk/code_mode.js +58 -0
  73. package/dist/sdk/code_mode.js.map +1 -0
  74. package/dist/sdk/index.d.ts +8 -4
  75. package/dist/sdk/index.js +4 -1
  76. package/dist/sdk/index.js.map +1 -1
  77. package/dist/sdk/session.js +123 -40
  78. package/dist/sdk/session.js.map +1 -1
  79. package/dist/sdk/types.d.ts +21 -10
  80. package/dist/transport/in_process_session_transport.js +15 -1
  81. package/dist/transport/in_process_session_transport.js.map +1 -1
  82. package/dist/transport/index.d.ts +1 -1
  83. package/dist/transport/index.js.map +1 -1
  84. package/dist/transport/session_protocol_transport_helpers.js +14 -0
  85. package/dist/transport/session_protocol_transport_helpers.js.map +1 -1
  86. package/dist/transport/session_transport.d.ts +3 -1
  87. package/dist/transport/stdio_session_transport.d.ts +3 -1
  88. package/dist/transport/stdio_session_transport.js +15 -1
  89. package/dist/transport/stdio_session_transport.js.map +1 -1
  90. package/dist/transport/websocket_session_transport.d.ts +3 -1
  91. package/dist/transport/websocket_session_transport.js +15 -1
  92. package/dist/transport/websocket_session_transport.js.map +1 -1
  93. package/dist/tui/chat_controller/diff_review_service.js +2 -2
  94. package/dist/tui/chat_controller/diff_review_service.js.map +1 -1
  95. package/dist/tui/chat_view.js.map +1 -1
  96. package/dist/tui/command_client_tools.js +211 -21
  97. package/dist/tui/command_client_tools.js.map +1 -1
  98. package/dist/tui/session_chat_app.js +1 -1
  99. package/dist/tui/session_chat_app.js.map +1 -1
  100. package/dist/tui/session_chat_controller.js +49 -17
  101. package/dist/tui/session_chat_controller.js.map +1 -1
  102. package/dist/tui/session_tool_execution_backend.js +2 -2
  103. package/dist/tui/session_tool_execution_backend.js.map +1 -1
  104. package/dist/tui/ui/subagent_panel.js +25 -48
  105. package/dist/tui/ui/subagent_panel.js.map +1 -1
  106. package/package.json +6 -2
package/README.md CHANGED
@@ -143,7 +143,7 @@ For stdio attach, use `--session <id>` before `--`:
143
143
  tau attach --session 0195d6e4-4cf9-7f44-a2d8-f8f7f49ee9d3 -- ssh vps 'cd /path/to/repo && tau rpc'
144
144
  ```
145
145
 
146
- Session attach renders the authoritative session snapshot, streams recoverable `session.delta` updates and independently revisioned, non-persisted `session.pendingUserMessages` replacements, submits normal user input through `session.submit`, `session.queue`, and `session.steer`, supports steering/interruption, runs `!`/`!!` Bash commands in the session execution environment, records `/listen` from the local microphone, speaks `/speak` locally, reloads session content with `/reload`, switches session personas with `/persona:<id>` or `Ctrl+P`, inserts session prompt templates with `/prompt:<id>`, manages persistent autonomous goals with `/goal`, compacts the session with `/compact-all` or `/compact-keep-last`, creates a new session with `/new`, and exits with `/exit` or `Ctrl+C` twice.
146
+ Session attach renders the authoritative session snapshot, streams recoverable `session.delta` updates plus independently revisioned, non-persisted pending-message replacements and per-agent subagent-activity updates, submits normal user input through `session.submit`, `session.queue`, and `session.steer`, supports steering/interruption, runs `!`/`!!` Bash commands in the session execution environment, records `/listen` from the local microphone, speaks `/speak` locally, reloads session content with `/reload`, switches session personas with `/persona:<id>` or `Ctrl+P`, inserts session prompt templates with `/prompt:<id>`, manages persistent autonomous goals with `/goal`, compacts the session with `/compact-all` or `/compact-keep-last`, creates a new session with `/new`, and exits with `/exit` or `Ctrl+C` twice.
147
147
 
148
148
  The host owns the active transcript as one ordered timeline of messages, tool calls, notices, and maintenance operations. Durable items retain their exact position across reattach; ephemeral transcript notices use the same ordering while attached but are not recovered. Successful compaction starts a new numeric timeline epoch containing the summary and future activity, while rewind removes every item after its selected boundary.
149
149
 
@@ -669,24 +669,74 @@ A project or nested directory can select a different exact set without defining
669
669
 
670
670
  The most specific `.tau/config.json` selection wins. Unknown names are skipped, and `enabledClientTools: []` disables every configured command client tool for that workspace.
671
671
 
672
- For every call, Tau validates the arguments against the configured schema, starts the command directly without a shell, and writes one versioned JSON request to stdin:
672
+ For every call, Tau validates the arguments against the configured schema, starts the command directly without a shell, and speaks a version 2 newline-delimited JSON protocol over stdin and stdout. The initial stdin frame contains the invocation:
673
673
 
674
674
  ```json
675
675
  {
676
- "version": 1,
676
+ "version": 2,
677
+ "type": "invoke",
677
678
  "sessionId": "session-id",
678
679
  "callId": "call-id",
679
680
  "arguments": { "message": "Build finished" }
680
681
  }
681
682
  ```
682
683
 
683
- A successful command must exit with code zero and write exactly one JSON result to stdout:
684
+ Commands may send `exec` frames to run commands in the session execution environment. Tau returns the ordinary `session.exec` result in a matching `exec.result` stdin frame. The command finishes with one stdout result frame:
684
685
 
685
686
  ```json
686
- { "content": "Notification shown." }
687
+ { "version": 2, "type": "result", "content": "Notification shown." }
687
688
  ```
688
689
 
689
- The `content` string becomes the model-visible tool result. A nonzero exit fails the tool using stderr, falling back to stdout when stderr is empty. Tau runs the command from the TUI's current working directory with the TUI process environment unchanged, limits total output to 1 MiB, and terminates the command's process group on cancellation, terminal transport failure, timeout, or excess output. Process-group termination escalates to `SIGKILL` after two seconds even if the command leader exits first. `executionTimeoutMs` defaults to 60 seconds.
690
+ Use `runTauClientToolCommand()` from `@markusylisiurunen/tau/sdk` or `@markusylisiurunen/tau/code-mode` to handle this framing and receive the same `{ sessionId, callId, signal, executionEnvironment }` context as an in-process SDK client tool. The command itself still runs on the TUI machine; only `context.executionEnvironment.exec()` runs through `session.exec` in the session execution environment.
691
+
692
+ The result `content` becomes model-visible. A nonzero exit fails the tool using stderr, falling back to stdout when stderr is empty. Tau runs the command from the TUI's current working directory with the TUI process environment unchanged, limits each command-to-TUI protocol frame and total stdout and stderr to 1 MiB, allows at most eight execution requests to remain active while their responses are delivered with stdin backpressure, and terminates the command's process group on cancellation, terminal transport failure, timeout, or excess output. Closing protocol stdin aborts the command helper and its pending execution requests. Process-group termination escalates to `SIGKILL` after two seconds even if the command leader exits first. `executionTimeoutMs` defaults to 60 seconds.
693
+
694
+ ```ts
695
+ #!/usr/bin/env node
696
+ import { runTauClientToolCommand } from "@markusylisiurunen/tau/sdk";
697
+
698
+ await runTauClientToolCommand(async (args, context) => {
699
+ const status = await context.executionEnvironment.exec("git status --short");
700
+ return { content: status.output || "working tree clean" };
701
+ });
702
+ ```
703
+
704
+ Tau's `@markusylisiurunen/tau/code-mode` export implements this command framing plus the same isolated one-shot JavaScript runtime used by Tau's built-in code-mode tools. A code-mode command remains an ordinary configured client tool with the exact `{ code: string }` schema and a complete author-controlled description:
705
+
706
+ ```json
707
+ {
708
+ "name": "linear",
709
+ "defaultEnabled": true,
710
+ "description": "Search Linear issues. When this tool is useful, your first call must be a documentation-only program that does nothing except print docs with console.log(docs). Read the returned documentation before writing a later tool call that uses linear. Do not guess API signatures.",
711
+ "parameters": {
712
+ "type": "object",
713
+ "properties": { "code": { "type": "string" } },
714
+ "required": ["code"],
715
+ "additionalProperties": false
716
+ },
717
+ "command": ".config/tau/tools/linear"
718
+ }
719
+ ```
720
+
721
+ The executable owns authenticated clients and explicitly exposes trusted handlers. Handler arguments and results cross a JSON boundary; generated code receives only the declared namespace plus `docs`, `console`, `Date`, and `Math`:
722
+
723
+ ```ts
724
+ #!/usr/bin/env node
725
+ import { runTauCodeModeCommand } from "@markusylisiurunen/tau/code-mode";
726
+
727
+ await runTauCodeModeCommand({
728
+ name: "linear",
729
+ documentation:
730
+ "# Linear API\n\nUse `linear.issues.get(id)` to read an issue.",
731
+ api: {
732
+ issues: {
733
+ get: async ([id], { signal }) => linearClient.issue(id, { signal }),
734
+ },
735
+ },
736
+ });
737
+ ```
738
+
739
+ Trusted code-mode API handlers receive the command's execution-environment facade in their context and may intentionally expose narrower workspace operations through the declared API. Generated code does not receive an undeclared shell namespace. Tau prepends canonical runtime guidance to the executable's API documentation. The installed runtime therefore documents its actual capabilities, 60-second default timeout, 8,192-token output projection, 128-call total limit, and eight-call concurrency limit without duplicating those details in `config.json`. The optional `buildTauCodeModeToolDescription()` helper produces the recommended progressive-disclosure description, but descriptions are otherwise passed through unchanged.
690
740
 
691
741
  Configured names must be unique and cannot replace built-in TUI or host tools. Only one observing client may advertise a given name for a session. `--no-client-tools` disables command client tools together with `diff_review` and `prefill_input`.
692
742
 
@@ -0,0 +1,2 @@
1
+ import { type TauCodeModeDefinition } from "./runtime.js";
2
+ export declare function runTauCodeModeCommand(definition: TauCodeModeDefinition): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { runTauClientToolCommand } from "../sdk/client_tool_command.js";
2
+ import { executeTauCodeMode, validateTauCodeModeDefinition, } from "./runtime.js";
3
+ export async function runTauCodeModeCommand(definition) {
4
+ validateTauCodeModeDefinition(definition);
5
+ await runTauClientToolCommand(async (args, context) => {
6
+ const code = parseCodeArguments(args);
7
+ return await executeTauCodeMode({
8
+ ...definition,
9
+ code,
10
+ signal: context.signal,
11
+ invocation: {
12
+ sessionId: context.sessionId,
13
+ callId: context.callId,
14
+ },
15
+ executionEnvironment: context.executionEnvironment,
16
+ });
17
+ });
18
+ }
19
+ function parseCodeArguments(value) {
20
+ if (typeof value !== "object" || value === null) {
21
+ throw new Error("code-mode command arguments must be an object");
22
+ }
23
+ const args = value;
24
+ if (typeof args.code !== "string" ||
25
+ !args.code.trim() ||
26
+ Object.keys(args).some((key) => key !== "code")) {
27
+ throw new Error("code-mode command arguments must contain exactly one non-empty 'code' string");
28
+ }
29
+ return args.code;
30
+ }
31
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../../src/code_mode/command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACL,kBAAkB,EAElB,6BAA6B,GAC9B,MAAM,cAAc,CAAC;AAEtB,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,UAAiC;IAC3E,6BAA6B,CAAC,UAAU,CAAC,CAAC;IAC1C,MAAM,uBAAuB,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE;QACpD,MAAM,IAAI,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;QACtC,OAAO,MAAM,kBAAkB,CAAC;YAC9B,GAAG,UAAU;YACb,IAAI;YACJ,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,UAAU,EAAE;gBACV,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB;YACD,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;SACnD,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAc;IACxC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IACD,MAAM,IAAI,GAAG,KAAgC,CAAC;IAC9C,IACE,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;QAC7B,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;QACjB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,KAAK,MAAM,CAAC,EAC/C,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,8EAA8E,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC;AACnB,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { runTauClientToolCommand, TAU_CLIENT_TOOL_COMMAND_PROTOCOL_VERSION, type TauClientToolCommandHandler, } from "../sdk/client_tool_command.js";
2
+ export { runTauCodeModeCommand } from "./command.js";
3
+ export type { BuildTauCodeModeToolDescriptionOptions, ExecuteTauCodeModeOptions, TauCodeModeApi, TauCodeModeDefinition, TauCodeModeExecutionStatus, TauCodeModeHandler, TauCodeModeHandlerContext, TauCodeModeInvocation, TauCodeModeJsonValue, TauCodeModePersistOutput, TauCodeModeResult, } from "./runtime.js";
4
+ export { buildTauCodeModeToolDescription, executeTauCodeMode, TAU_CODE_MODE_DEFAULT_TIMEOUT_MS, TAU_CODE_MODE_MAX_OUTPUT_TOKENS, } from "./runtime.js";
@@ -0,0 +1,4 @@
1
+ export { runTauClientToolCommand, TAU_CLIENT_TOOL_COMMAND_PROTOCOL_VERSION, } from "../sdk/client_tool_command.js";
2
+ export { runTauCodeModeCommand } from "./command.js";
3
+ export { buildTauCodeModeToolDescription, executeTauCodeMode, TAU_CODE_MODE_DEFAULT_TIMEOUT_MS, TAU_CODE_MODE_MAX_OUTPUT_TOKENS, } from "./runtime.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/code_mode/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wCAAwC,GAEzC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAcrD,OAAO,EACL,+BAA+B,EAC/B,kBAAkB,EAClB,gCAAgC,EAChC,+BAA+B,GAChC,MAAM,cAAc,CAAC"}
@@ -0,0 +1,82 @@
1
+ import type { TauSdkClientToolExecutionEnvironment } from "../sdk/types.js";
2
+ export declare const TAU_CODE_MODE_DEFAULT_TIMEOUT_MS = 60000;
3
+ export declare const TAU_CODE_MODE_MAX_OUTPUT_TOKENS = 8192;
4
+ export type TauCodeModeJsonValue = null | boolean | number | string | TauCodeModeJsonValue[] | {
5
+ [key: string]: TauCodeModeJsonValue;
6
+ };
7
+ export type TauCodeModeInvocation = {
8
+ sessionId: string;
9
+ callId: string;
10
+ };
11
+ export type TauCodeModeHandlerContext = {
12
+ signal: AbortSignal;
13
+ invocation: TauCodeModeInvocation | null;
14
+ executionEnvironment: TauSdkClientToolExecutionEnvironment | null;
15
+ };
16
+ export type TauCodeModeHandler = (args: unknown[], context: TauCodeModeHandlerContext) => unknown | Promise<unknown>;
17
+ export type TauCodeModeApi = {
18
+ [key: string]: TauCodeModeApi | TauCodeModeHandler;
19
+ };
20
+ export type TauCodeModeExecutionStatus = "succeeded" | "failed" | "timed-out" | "cancelled";
21
+ type TauCodeModeProjection = {
22
+ content: string;
23
+ truncated: boolean;
24
+ truncatedBy: "lines" | "bytes" | null;
25
+ totalLines: number;
26
+ totalBytes: number;
27
+ outputLines: number;
28
+ outputBytes: number;
29
+ maxLines: number;
30
+ maxTokens: number;
31
+ };
32
+ type TauCodeModeExecutionCapture = {
33
+ output: string;
34
+ stdout: string;
35
+ stderr: string;
36
+ exitCode: number | null;
37
+ truncated: boolean;
38
+ timedOut: boolean;
39
+ aborted: boolean;
40
+ closeSignal: string | null;
41
+ };
42
+ export type TauCodeModePersistOutput = (output: {
43
+ content: string;
44
+ captureTruncated: boolean;
45
+ contextTruncated: boolean;
46
+ status: TauCodeModeExecutionStatus;
47
+ }, context: TauCodeModeHandlerContext) => Promise<{
48
+ path: string;
49
+ } | undefined>;
50
+ export type TauCodeModeDefinition = {
51
+ name: string;
52
+ documentation: string;
53
+ api: TauCodeModeApi;
54
+ timeoutMs?: number;
55
+ persistOutput?: TauCodeModePersistOutput;
56
+ };
57
+ export type ExecuteTauCodeModeOptions = TauCodeModeDefinition & {
58
+ code: string;
59
+ signal?: AbortSignal;
60
+ invocation?: TauCodeModeInvocation | null;
61
+ executionEnvironment?: TauSdkClientToolExecutionEnvironment | null;
62
+ };
63
+ export type TauCodeModeResult = {
64
+ content: string;
65
+ };
66
+ export type BuildTauCodeModeToolDescriptionOptions = {
67
+ name: string;
68
+ description: string;
69
+ };
70
+ export type TauCodeModeRuntimeResult = {
71
+ result: TauCodeModeResult;
72
+ status: TauCodeModeExecutionStatus;
73
+ execution: TauCodeModeExecutionCapture;
74
+ durationMs: number;
75
+ projection: TauCodeModeProjection;
76
+ persistedPath?: string;
77
+ };
78
+ export declare function buildTauCodeModeToolDescription({ name, description, }: BuildTauCodeModeToolDescriptionOptions): string;
79
+ export declare function validateTauCodeModeDefinition(definition: TauCodeModeDefinition): void;
80
+ export declare function executeTauCodeMode(options: ExecuteTauCodeModeOptions): Promise<TauCodeModeResult>;
81
+ export declare function runTauCodeMode(options: ExecuteTauCodeModeOptions): Promise<TauCodeModeRuntimeResult>;
82
+ export {};
@@ -0,0 +1,298 @@
1
+ import stripAnsi from "strip-ansi";
2
+ import { CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES, CODE_MODE_MAX_BRIDGE_REQUESTS, CODE_MODE_MAX_CONCURRENT_BRIDGE_REQUESTS, executeCodeModeWorker, } from "../core/tools/code_mode_worker.js";
3
+ import { bytesToTokens } from "../core/utils/token.js";
4
+ import { formatBytes, truncateForTokens } from "../core/utils/truncate.js";
5
+ export const TAU_CODE_MODE_DEFAULT_TIMEOUT_MS = 60_000;
6
+ export const TAU_CODE_MODE_MAX_OUTPUT_TOKENS = 8_192;
7
+ const sandboxRunnerUrl = new URL("../core/static/code_mode/sandbox_runner.mjs", import.meta.url);
8
+ const javascriptIdentifierPattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
9
+ const reservedNames = new Set([...Object.getOwnPropertyNames(globalThis), "docs"]);
10
+ const unsafeApiKeys = new Set(["__proto__", "constructor", "prototype"]);
11
+ export function buildTauCodeModeToolDescription({ name, description, }) {
12
+ validateName(name);
13
+ const trimmedDescription = description.trim();
14
+ if (!trimmedDescription)
15
+ throw new Error("code-mode tool description must not be empty");
16
+ return [
17
+ trimmedDescription,
18
+ "When this tool is useful, your first call must be a documentation-only program that does nothing except print docs with console.log(docs).",
19
+ `Read the returned documentation before writing a later tool call that uses ${name}.`,
20
+ "Do not guess API signatures.",
21
+ ].join(" ");
22
+ }
23
+ export function validateTauCodeModeDefinition(definition) {
24
+ validateName(definition.name);
25
+ if (!definition.documentation.trim()) {
26
+ throw new Error("code-mode documentation must not be empty");
27
+ }
28
+ validateTimeout(definition.timeoutMs);
29
+ registerMethods(definition.api);
30
+ }
31
+ export async function executeTauCodeMode(options) {
32
+ const runtime = await runTauCodeMode(options);
33
+ if (runtime.status === "succeeded")
34
+ return runtime.result;
35
+ throw new Error(runtime.result.content);
36
+ }
37
+ export async function runTauCodeMode(options) {
38
+ validateName(options.name);
39
+ if (typeof options.code !== "string" || !options.code.trim()) {
40
+ throw new Error("code-mode source must be a non-empty string");
41
+ }
42
+ if (!options.documentation.trim()) {
43
+ throw new Error("code-mode documentation must not be empty");
44
+ }
45
+ validateTimeout(options.timeoutMs);
46
+ const methods = registerMethods(options.api);
47
+ const timeoutMs = options.timeoutMs ?? TAU_CODE_MODE_DEFAULT_TIMEOUT_MS;
48
+ const invocation = options.invocation ?? null;
49
+ const executionEnvironment = options.executionEnvironment ?? null;
50
+ const signal = options.signal ?? new AbortController().signal;
51
+ const docs = buildRuntimeDocumentation(options.name, options.documentation, timeoutMs);
52
+ const startedAt = Date.now();
53
+ let execution;
54
+ try {
55
+ execution = await executeCodeModeWorker({
56
+ sandboxRunnerUrl,
57
+ workerData: {
58
+ code: options.code,
59
+ docs,
60
+ name: options.name,
61
+ methods: methods.map(({ id, path }) => ({ id, path })),
62
+ },
63
+ signal,
64
+ timeoutMs,
65
+ handleRequest: async (request, requestSignal) => {
66
+ const method = methods[request.methodId];
67
+ if (!method)
68
+ throw new Error(`unsupported ${options.name} API method`);
69
+ const args = parseBridgeArguments(request.argsJson, options.name, method.path);
70
+ const value = await method.handler(args, {
71
+ signal: requestSignal,
72
+ invocation,
73
+ executionEnvironment,
74
+ });
75
+ return serializeBridgeResult(value, options.name, method.path);
76
+ },
77
+ });
78
+ }
79
+ catch (error) {
80
+ const message = error instanceof Error ? error.stack || error.message : String(error);
81
+ const output = `${message}\n`;
82
+ execution = {
83
+ output,
84
+ stdout: "",
85
+ stderr: output,
86
+ exitCode: 1,
87
+ truncated: false,
88
+ timedOut: false,
89
+ aborted: false,
90
+ closeSignal: null,
91
+ };
92
+ }
93
+ const durationMs = Math.max(0, Date.now() - startedAt);
94
+ const status = getExecutionStatus(execution);
95
+ const output = appendTerminationNote(stripAnsi(execution.output), execution, timeoutMs);
96
+ const projection = truncateForTokens(output, {
97
+ maxTokens: TAU_CODE_MODE_MAX_OUTPUT_TOKENS,
98
+ strategy: "middle",
99
+ });
100
+ let persistedPath;
101
+ if (options.persistOutput) {
102
+ try {
103
+ const persisted = await options.persistOutput({
104
+ content: output,
105
+ captureTruncated: execution.truncated,
106
+ contextTruncated: projection.truncated,
107
+ status,
108
+ }, { signal, invocation, executionEnvironment });
109
+ if (persisted?.path.trim())
110
+ persistedPath = persisted.path;
111
+ }
112
+ catch { }
113
+ }
114
+ const result = {
115
+ content: formatResultContent({ execution, projection, persistedPath, status }),
116
+ };
117
+ return {
118
+ result,
119
+ status,
120
+ execution,
121
+ durationMs,
122
+ projection,
123
+ ...(persistedPath ? { persistedPath } : {}),
124
+ };
125
+ }
126
+ function validateName(name) {
127
+ let isIdentifier = javascriptIdentifierPattern.test(name);
128
+ if (isIdentifier) {
129
+ try {
130
+ Function(`"use strict"; let ${name};`);
131
+ }
132
+ catch {
133
+ isIdentifier = false;
134
+ }
135
+ }
136
+ if (!isIdentifier || reservedNames.has(name)) {
137
+ throw new Error(`code-mode name '${name}' must be a non-reserved JavaScript identifier`);
138
+ }
139
+ }
140
+ function validateTimeout(timeoutMs) {
141
+ if (timeoutMs !== undefined && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
142
+ throw new Error("code-mode timeoutMs must be a positive integer");
143
+ }
144
+ }
145
+ function registerMethods(api) {
146
+ const methods = [];
147
+ const visit = (value, path) => {
148
+ if (!isPlainObject(value)) {
149
+ throw new Error(`code-mode API '${formatPath(path)}' must be a plain object with function leaves`);
150
+ }
151
+ const entries = Object.entries(value);
152
+ if (entries.length === 0) {
153
+ throw new Error(`code-mode API '${formatPath(path)}' must not be empty`);
154
+ }
155
+ for (const [key, child] of entries) {
156
+ const childPath = [...path, key];
157
+ if (!key || unsafeApiKeys.has(key)) {
158
+ throw new Error(`code-mode API key '${formatPath(childPath)}' is not allowed`);
159
+ }
160
+ if (typeof child === "function") {
161
+ methods.push({ id: methods.length, path: childPath, handler: child });
162
+ }
163
+ else {
164
+ visit(child, childPath);
165
+ }
166
+ }
167
+ };
168
+ visit(api, []);
169
+ return methods;
170
+ }
171
+ function isPlainObject(value) {
172
+ if (typeof value !== "object" || value === null || Array.isArray(value))
173
+ return false;
174
+ const prototype = Object.getPrototypeOf(value);
175
+ return prototype === Object.prototype || prototype === null;
176
+ }
177
+ function formatPath(path) {
178
+ return path.length > 0 ? path.join(".") : "<root>";
179
+ }
180
+ function parseBridgeArguments(argsJson, name, path) {
181
+ const method = `${name}.${formatPath(path)}`;
182
+ if (Buffer.byteLength(argsJson, "utf8") > CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES) {
183
+ throw new Error(`${method} arguments exceeded the ${formatBytes(CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES)} bridge payload limit`);
184
+ }
185
+ let args;
186
+ try {
187
+ args = JSON.parse(argsJson);
188
+ }
189
+ catch {
190
+ throw new Error(`invalid ${method} arguments`);
191
+ }
192
+ if (!Array.isArray(args)) {
193
+ throw new Error(`invalid ${method} arguments`);
194
+ }
195
+ return args;
196
+ }
197
+ function serializeBridgeResult(value, name, path) {
198
+ let json;
199
+ try {
200
+ json = JSON.stringify(value, (_key, nested) => {
201
+ if (nested === undefined ||
202
+ typeof nested === "function" ||
203
+ typeof nested === "symbol" ||
204
+ typeof nested === "bigint" ||
205
+ (typeof nested === "number" && !Number.isFinite(nested))) {
206
+ throw new TypeError("Code-mode API results must be JSON-serializable values");
207
+ }
208
+ return nested;
209
+ });
210
+ }
211
+ catch (error) {
212
+ const detail = error instanceof Error ? error.message : String(error);
213
+ throw new Error(`${name}.${formatPath(path)} returned a non-JSON value: ${detail}`);
214
+ }
215
+ if (json === undefined) {
216
+ throw new Error(`${name}.${formatPath(path)} returned a non-JSON value`);
217
+ }
218
+ if (Buffer.byteLength(json, "utf8") > CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES) {
219
+ throw new Error(`${name}.${formatPath(path)} result exceeded the ${formatBytes(CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES)} bridge payload limit`);
220
+ }
221
+ return json;
222
+ }
223
+ function buildRuntimeDocumentation(name, documentation, timeoutMs) {
224
+ return [
225
+ "# Code-mode runtime",
226
+ "",
227
+ "## Available globals",
228
+ "",
229
+ `- \`${name}\`: the explicitly exposed API documented below.`,
230
+ "- `docs`: this document.",
231
+ "- `console`: program output through `debug`, `error`, `info`, `log`, and `warn`.",
232
+ "- `Date`: standard date handling with live current-time access.",
233
+ "- `Math`: standard math operations, including `Math.random()`.",
234
+ "",
235
+ "Top-level `await` is supported. The program return value is ignored; only console output is returned.",
236
+ "Generated code has no direct filesystem, process, environment, network, credential, import, timer, or `fetch` access.",
237
+ "",
238
+ "## API boundary",
239
+ "",
240
+ `Arguments passed to \`${name}\` methods and their results cross a JSON serialization boundary with a ${formatBytes(CODE_MODE_MAX_BRIDGE_PAYLOAD_BYTES)} limit per request or response.`,
241
+ `A program may make at most ${CODE_MODE_MAX_BRIDGE_REQUESTS} API calls, with at most ${CODE_MODE_MAX_CONCURRENT_BRIDGE_REQUESTS} unresolved calls concurrently. Exceeding any bridge limit fails the program.`,
242
+ `The program must finish within ${formatDuration(timeoutMs)}.`,
243
+ "",
244
+ "## Output",
245
+ "",
246
+ `Output is middle-truncated above roughly ${TAU_CODE_MODE_MAX_OUTPUT_TOKENS.toLocaleString("en-US")} tokens. Print only information needed for the task.`,
247
+ "",
248
+ documentation.trim(),
249
+ ].join("\n");
250
+ }
251
+ function formatDuration(timeoutMs) {
252
+ if (timeoutMs % 1_000 === 0) {
253
+ const seconds = timeoutMs / 1_000;
254
+ return `${seconds} second${seconds === 1 ? "" : "s"}`;
255
+ }
256
+ return `${timeoutMs}ms`;
257
+ }
258
+ function getExecutionStatus(execution) {
259
+ if (execution.aborted)
260
+ return "cancelled";
261
+ if (execution.timedOut)
262
+ return "timed-out";
263
+ return execution.exitCode === 0 ? "succeeded" : "failed";
264
+ }
265
+ function appendTerminationNote(output, execution, timeoutMs) {
266
+ let note;
267
+ if (execution.timedOut) {
268
+ note = `(tau) timed out after ${timeoutMs}ms`;
269
+ }
270
+ else if (execution.aborted) {
271
+ note = "(tau) aborted";
272
+ }
273
+ else if (execution.closeSignal) {
274
+ note = `(tau) terminated by signal ${execution.closeSignal}`;
275
+ }
276
+ if (!note)
277
+ return output;
278
+ return `${output}${output && !output.endsWith("\n") ? "\n" : ""}${note}\n`;
279
+ }
280
+ function formatResultContent(args) {
281
+ const { execution, projection, persistedPath, status } = args;
282
+ const output = projection.content.trimEnd();
283
+ if (!output && status === "succeeded") {
284
+ return persistedPath
285
+ ? `Program produced no output\n\n[Output saved to ${persistedPath}.]`
286
+ : "Program produced no output";
287
+ }
288
+ const truncationNote = projection.truncated || execution.truncated
289
+ ? `\n\n[Output truncated for context: ${projection.outputLines} lines / ${formatBytes(projection.outputBytes)} shown of ${projection.totalLines} lines / ${formatBytes(projection.totalBytes)} (full output estimate: ~${bytesToTokens(projection.totalBytes)} tokens).${persistedPath ? ` Output before context truncation saved to ${persistedPath}.` : ""}]`
290
+ : persistedPath
291
+ ? `\n\n[Output saved to ${persistedPath}.]`
292
+ : "";
293
+ const exitNote = status === "failed" && execution.exitCode !== null && execution.exitCode !== 0
294
+ ? `\n(exit ${execution.exitCode})`
295
+ : "";
296
+ return `${output || "(no output)"}${truncationNote}${exitNote}`;
297
+ }
298
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/code_mode/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,wCAAwC,EACxC,qBAAqB,GACtB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAG3E,MAAM,CAAC,MAAM,gCAAgC,GAAG,MAAM,CAAC;AACvD,MAAM,CAAC,MAAM,+BAA+B,GAAG,KAAK,CAAC;AAErD,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,6CAA6C,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,MAAM,2BAA2B,G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OAAO,aAAa;YAClB,CAAC,CAAC,kDAAkD,aAAa,IAAI;YACrE,CAAC,CAAC,4BAA4B,CAAC;IACnC,CAAC;IAED,MAAM,cAAc,GAClB,UAAU,CAAC,SAAS,IAAI,SAAS,CAAC,SAAS;QACzC,CAAC,CAAC,sCAAsC,UAAU,CAAC,WAAW,YAAY,WAAW,CAAC,UAAU,CAAC,WAAW,CAAC,aAAa,UAAU,CAAC,UAAU,YAAY,WAAW,CAAC,UAAU,CAAC,UAAU,CAAC,4BAA4B,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,YAAY,aAAa,CAAC,CAAC,CAAC,8CAA8C,aAAa,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG;QAC/V,CAAC,CAAC,aAAa;YACb,CAAC,CAAC,wBAAwB,aAAa,IAAI;YAC3C,CAAC,CAAC,EAAE,CAAC;IACX,MAAM,QAAQ,GACZ,MAAM,KAAK,QAAQ,IAAI,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,SAAS,CAAC,QAAQ,KAAK,CAAC;QAC5E,CAAC,CAAC,WAAW,SAAS,CAAC,QAAQ,GAAG;QAClC,CAAC,CAAC,EAAE,CAAC;IACT,OAAO,GAAG,MAAM,IAAI,aAAa,GAAG,cAAc,GAAG,QAAQ,EAAE,CAAC;AAClE,CAAC"}
@@ -156,7 +156,7 @@ export class AgentRuntime {
156
156
  : undefined;
157
157
  }
158
158
  else {
159
- this.agentId = randomUUID();
159
+ this.agentId = options.agentId ?? randomUUID();
160
160
  this.revision = 0;
161
161
  this.historyEntries = [];
162
162
  this.modelContextKey = modelContextKey;