@markusylisiurunen/tau 0.3.101 → 0.3.103

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 (97) hide show
  1. package/README.md +18 -23
  2. package/dist/core/config/ownership.js +3 -1
  3. package/dist/core/config/ownership.js.map +1 -1
  4. package/dist/core/config/schema.js +3 -1
  5. package/dist/core/config/schema.js.map +1 -1
  6. package/dist/core/history/migrations.js +46 -1
  7. package/dist/core/history/migrations.js.map +1 -1
  8. package/dist/core/history/setup.js +24 -7
  9. package/dist/core/history/setup.js.map +1 -1
  10. package/dist/core/mcp/cli.js +1 -1
  11. package/dist/core/mcp/cli.js.map +1 -1
  12. package/dist/core/static/tau_docs/client-tools.md +46 -385
  13. package/dist/core/static/tau_docs/code-mode.md +104 -43
  14. package/dist/core/static/tau_docs/configuration.md +77 -171
  15. package/dist/core/static/tau_docs/getting-started.md +25 -96
  16. package/dist/core/static/tau_docs/history.md +30 -228
  17. package/dist/core/static/tau_docs/how-tau-works.md +53 -0
  18. package/dist/core/static/tau_docs/image-generation.md +15 -107
  19. package/dist/core/static/tau_docs/index.md +46 -45
  20. package/dist/core/static/tau_docs/instructions-and-skills.md +81 -0
  21. package/dist/core/static/tau_docs/manifest.json +15 -20
  22. package/dist/core/static/tau_docs/mcp.md +77 -0
  23. package/dist/core/static/tau_docs/models-and-credentials.md +67 -0
  24. package/dist/core/static/tau_docs/openrouter.md +31 -129
  25. package/dist/core/static/tau_docs/pdf-unpacking.md +8 -21
  26. package/dist/core/static/tau_docs/personas.md +48 -144
  27. package/dist/core/static/tau_docs/remote-sessions.md +33 -170
  28. package/dist/core/static/tau_docs/sdk.md +150 -0
  29. package/dist/core/static/tau_docs/security.md +6 -193
  30. package/dist/core/static/tau_docs/session-protocol.md +84 -246
  31. package/dist/core/static/tau_docs/sessions.md +41 -205
  32. package/dist/core/static/tau_docs/speech-generation.md +16 -129
  33. package/dist/core/static/tau_docs/subagents.md +57 -229
  34. package/dist/core/static/tau_docs/telegram.md +152 -220
  35. package/dist/core/static/tau_docs/tools.md +44 -167
  36. package/dist/core/static/tau_docs/troubleshooting.md +23 -217
  37. package/dist/core/static/tau_docs/tui.md +42 -276
  38. package/dist/core/subagents/claude_code_runner.mjs +65 -65
  39. package/dist/core/telegram/adapter.js +178 -61
  40. package/dist/core/telegram/adapter.js.map +1 -1
  41. package/dist/core/telegram/cli.js +1 -3
  42. package/dist/core/telegram/cli.js.map +1 -1
  43. package/dist/core/telegram/config.js +3 -1
  44. package/dist/core/telegram/config.js.map +1 -1
  45. package/dist/core/telegram/runtime.js +1 -1
  46. package/dist/core/telegram/runtime.js.map +1 -1
  47. package/dist/core/utils/scribe_transcription.js +283 -0
  48. package/dist/core/utils/scribe_transcription.js.map +1 -0
  49. package/dist/core/utils/speech_cleanup.js +198 -0
  50. package/dist/core/utils/speech_cleanup.js.map +1 -0
  51. package/dist/core/utils/speech_to_text.js +3 -3
  52. package/dist/core/utils/speech_to_text_keywords.js +5 -4
  53. package/dist/core/utils/speech_to_text_keywords.js.map +1 -1
  54. package/dist/core/version.js +1 -1
  55. package/dist/diff_tool/app/dist/assets/{core-CXVpaOO1.js → core-Cnp6wBC7.js} +1 -1
  56. package/dist/diff_tool/app/dist/assets/engine-oniguruma-ConHyUk6.js +1 -0
  57. package/dist/diff_tool/app/dist/assets/{highlights-DuJNYjEh.js → highlights-DeO0fGqQ.js} +1 -1
  58. package/dist/diff_tool/app/dist/assets/index-BDuQ2wXS.js +221 -0
  59. package/dist/diff_tool/app/dist/assets/langs-DDFHLNuJ.js +1 -0
  60. package/dist/diff_tool/app/dist/assets/{loader-bi21_x0K.js → loader-DrwOwtvp.js} +1 -1
  61. package/dist/diff_tool/app/dist/assets/{preload-helper-CRzLMJPS.js → preload-helper-DclECHGd.js} +1 -1
  62. package/dist/diff_tool/app/dist/assets/{shiki-D6ZyrNQD.js → shiki-CwKGJZFi.js} +2 -2
  63. package/dist/diff_tool/app/dist/assets/{stream-tokenizer-BdsyU_yB.js → stream-tokenizer-D4-m26wx.js} +1 -1
  64. package/dist/diff_tool/app/dist/assets/{themes-9lpTYI_i.js → themes-Do3waJhf.js} +2 -2
  65. package/dist/diff_tool/app/dist/index.html +2 -2
  66. package/dist/history/worker/index.js +83 -63
  67. package/dist/history/worker/index.js.map +1 -1
  68. package/dist/history/worker/migrations/0003_digest_schedule.sql +36 -0
  69. package/dist/history/worker/migrations/0004_recent_sessions.sql +1 -0
  70. package/dist/history/worker/migrations/0005_external_content.sql +58 -0
  71. package/dist/history/worker/migrations/0006_external_content_cutover.sql +44 -0
  72. package/dist/store/session_snapshot_migrations.js +14 -1
  73. package/dist/store/session_snapshot_migrations.js.map +1 -1
  74. package/dist/tui/chat_view.js +3 -1
  75. package/dist/tui/chat_view.js.map +1 -1
  76. package/dist/tui/listen_capture.js +7 -5
  77. package/dist/tui/listen_capture.js.map +1 -1
  78. package/dist/tui/session_chat_controller.js +93 -15
  79. package/dist/tui/session_chat_controller.js.map +1 -1
  80. package/dist/tui/ui/custom_editor.js +3 -0
  81. package/dist/tui/ui/custom_editor.js.map +1 -1
  82. package/package.json +8 -7
  83. package/dist/core/static/tau_docs/config-reference.md +0 -355
  84. package/dist/core/static/tau_docs/credentials.md +0 -165
  85. package/dist/core/static/tau_docs/models.md +0 -57
  86. package/dist/core/static/tau_docs/node-sdk.md +0 -430
  87. package/dist/core/static/tau_docs/ownership-and-scope.md +0 -107
  88. package/dist/core/static/tau_docs/prompts-and-project-context.md +0 -147
  89. package/dist/core/static/tau_docs/sdk-diff-review.md +0 -92
  90. package/dist/core/static/tau_docs/session-protocol-methods.md +0 -655
  91. package/dist/core/static/tau_docs/skills.md +0 -135
  92. package/dist/core/static/tau_docs/telegram-projects.md +0 -197
  93. package/dist/core/utils/gemini_transcription.js +0 -566
  94. package/dist/core/utils/gemini_transcription.js.map +0 -1
  95. package/dist/diff_tool/app/dist/assets/engine-oniguruma-Rz_7DPcV.js +0 -1
  96. package/dist/diff_tool/app/dist/assets/index-F9is7PUw.js +0 -221
  97. package/dist/diff_tool/app/dist/assets/langs-CTftvgbb.js +0 -1
@@ -1,165 +0,0 @@
1
- # Credentials
2
-
3
- Tau reads secrets from configuration, environment variables, and its own OAuth storage. Put each secret on the process that makes the authenticated request. In a remote session, that is usually not the attached terminal.
4
-
5
- This page covers where secrets come from. [Models](models.md) covers providers and model metadata.
6
-
7
- ## Credential ownership
8
-
9
- The host makes model calls and runs services such as web search and remote history, so most credentials belong in the host's environment or the host user's global configuration. Common cases:
10
-
11
- | Operation | Where the credential belongs |
12
- | --- | --- |
13
- | Main-agent, native Tau subagent, sampling, and maintenance model calls | Session host |
14
- | Claude Code subagent subscription login | Claude Code on the execution environment |
15
- | OpenAI Codex OAuth accounts | Session host home |
16
- | Exa-backed `web.search` and `web.fetch` | Session host |
17
- | Remote history replication and queries | Session host |
18
- | Fly Sprite API | Session host startup |
19
- | `/listen` and `/speak` | TUI client |
20
- | Telegram transcription and voice responses | Telegram runner |
21
- | Standalone `tau tool` commands | The process running that command |
22
-
23
- With local `tau`, all of these are usually one machine. With `tau attach`, a key set only in the attached client's shell does not reach the remote host. Run `tau auth` on the host machine, and set host environment variables where `tau serve` or the SDK host runs. See [ownership and scope](ownership-and-scope.md) for the full boundary.
24
-
25
- Claude Code subagents use a Claude subscription login on the execution environment. Sign in with Claude Code there; `tau auth` does not manage this account. Tau checks the account before sending a task and does not fall back to API billing. See [Claude Code subagents](subagents.md#claude-code-subagents) for setup and extra-usage charges.
26
-
27
- ## Provider API keys
28
-
29
- Tau accepts provider API keys in global configuration:
30
-
31
- ```json
32
- {
33
- "apiKeys": {
34
- "anthropic": "<anthropic-api-key>",
35
- "openai": "<openai-api-key>",
36
- "google": "<gemini-api-key>"
37
- }
38
- }
39
- ```
40
-
41
- The keys of the map are provider IDs, such as `openai`, not model IDs. `apiKeys` is allowed only in the global `~/.config/tau/config.json` of the process that uses it. Project values are rejected. Values are literal strings and do not expand environment variables.
42
-
43
- For model requests, a provider's environment variable wins over its entry in `apiKeys`. Cloud and workload identity authentication that the provider supports still works. OpenAI uses `OPENAI_API_KEY`. Anthropic also accepts `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_OAUTH_TOKEN`. Codex OAuth is separate and always uses the active stored account.
44
-
45
- Set model credentials where the host runs. Restart that process after changing its environment variables or its `apiKeys`.
46
-
47
- ## Feature-specific keys
48
-
49
- Features check the environment variable first, then global configuration:
50
-
51
- | Feature | Resolution order |
52
- | --- | --- |
53
- | Exa web search and fetch | `EXA_API_KEY`, then `apiKeys.exa` |
54
- | Google image generation, speech-to-text, and Telegram transcription | `GEMINI_API_KEY`, then `apiKeys.google` |
55
- | Mistral PDF OCR | `MISTRAL_API_KEY`, then `apiKeys.mistral` |
56
- | OpenRouter decisions and chat | `OPENROUTER_API_KEY`, then `apiKeys.openrouter` |
57
- | OpenAI image generation, speech rewriting, and transcription spelling hints | `OPENAI_API_KEY`, then `apiKeys.openai` |
58
- | ElevenLabs speech generation, `/speak` synthesis, Telegram voice synthesis, and voice listing | `ELEVENLABS_API_KEY`, then `apiKeys.elevenlabs` |
59
-
60
- `web.discover` does not require Exa. `web.search` and `web.fetch` do. `/speak` and Telegram `/tts_on` voice responses require OpenAI for text rewriting and ElevenLabs for synthesis. `/listen` and incoming Telegram voice notes use Google, with optional OpenAI spelling hints. PDF OCR through `tau tool pdf-unpack` uses Mistral.
61
-
62
- Set these on the process that runs the feature. For example, `/speak` in an attached TUI reads `OPENAI_API_KEY` and `ELEVENLABS_API_KEY` on the client machine, while a session that uses a Google model reads its key on the host.
63
-
64
- For `tau tool` commands, credentials and configuration belong to the machine that runs the command. The agent's Bash tool removes inherited API-key environment variables, so a command the agent runs may need its key in global configuration on that machine. See [configuration](configuration.md) for configuration file locations and [security](security.md) for command environment handling.
65
-
66
- ## MCP OAuth
67
-
68
- HTTP MCP servers can use browser-based OAuth without an API token. Configure the server with `type: "http"` and its `url`, without an `Authorization` header, then run:
69
-
70
- ```sh
71
- tau mcp login cloudflare-api
72
- tau mcp login cloudflare-api --scope dns.write
73
- tau mcp login cloudflare-api --all
74
- tau mcp logout cloudflare-api
75
- ```
76
-
77
- Run these commands on the host, from the session's working directory, so the CLI resolves the same global and project MCP configuration as the session. The sign-in belongs to the server's URL, so every session on that host that uses the URL shares it. `login` without flags requests the authentication challenge's scopes (or the resource metadata's default scopes when the challenge has none) together with existing granted scopes. Repeat `--scope` to add specific permissions to the existing grant. `--all` requests every scope advertised by the authorization server and fails if it advertises none. When additional scopes exceed the client registration, login registers a new client and keeps the previous grant until authorization succeeds. The service decides which permissions it grants; requesting all does not guarantee unrestricted access. `--all` and `--scope` cannot be combined.
78
-
79
- OAuth requests and discovery redirects require HTTPS, except for HTTP on loopback. Registration and token requests do not follow redirects.
80
-
81
- Login prints an authorization URL. Open it in your browser and approve access at the service. The callback listener binds to loopback and waits up to five minutes. For a remote host, forward the printed callback port through SSH before opening the authorization URL in your local browser, for example `ssh -N -L <port>:127.0.0.1:<port> <host>`. A later login reuses the registered callback port, which must be free.
82
-
83
- OAuth credentials are stored privately in the host's `~/.config/tau/auth.json`, keyed by server URL. Servers with the same URL share the grant. Access-token refresh is automatic and coordinated across host processes. Existing sessions read updated credentials without restarting and reconnect to refresh available tools after login or logout. An explicit `Authorization` header takes precedence; remove it before OAuth login.
84
-
85
- When a call needs additional permissions, it fails with the required scopes and a login command. Tau does not open a browser, persist pending scope requests, or automatically repeat that operation after login. The user authorizes explicitly, then tells the agent to continue. Logout removes the local credentials but does not revoke the grant at the service; use the service's account settings to revoke it.
86
-
87
- ## OpenAI Codex OAuth
88
-
89
- The `openai-codex` provider uses ChatGPT Plus or Pro OAuth accounts managed by Tau. Authenticate on the host:
90
-
91
- ```sh
92
- tau auth login codex
93
- ```
94
-
95
- The flow opens or prints a browser URL. It may instead ask for a device code or a pasted redirect URL. Tau stores the result in the host user's `~/.config/tau/auth.json` with private file permissions. Do not edit this file directly. The auth commands handle concurrent access and token refresh.
96
-
97
- Tau can store several Codex accounts, and at most one is active. `tau auth list` shows each identity, marks the active one, and shows usage windows for information, without revealing tokens.
98
-
99
- ```sh
100
- tau auth login codex
101
- tau auth list
102
- tau auth use codex --account developer@example.com
103
- tau auth logout codex --account developer@example.com
104
- ```
105
-
106
- - A login activates the account only when no other accounts are stored. Later logins add or refresh an account without changing which one is active.
107
- - `auth use` makes an account active and deactivates the previous one.
108
- - Logout removes the account. Logging out the active account leaves no account active, even if others remain. Choose one with `tau auth use`.
109
- - With no active account, requests fail with instructions to log in or select an account.
110
- - Tau never switches accounts automatically, whether an account fails or runs out of usage. Usage never affects selection.
111
- - Account IDs and emails match case-insensitively.
112
-
113
- Every new request reads the current auth storage, in every session. Switching accounts takes effect without a host restart and does not affect a request already in progress.
114
-
115
- ## History indirection
116
-
117
- History can name environment variables instead of embedding secrets in configuration.
118
-
119
- Remote history is global-only configuration:
120
-
121
- ```json
122
- {
123
- "history": {
124
- "endpoint": "https://history.example.net",
125
- "apiKeyEnv": "TEAM_HISTORY_KEY"
126
- }
127
- }
128
- ```
129
-
130
- History resolves its API key in this order:
131
-
132
- 1. `TAU_HISTORY_API_KEY`
133
- 2. The host environment variable named by `history.apiKeyEnv`
134
- 3. Inline `history.apiKey`
135
-
136
- If `history` is configured but no key is found, the host fails to start. Without `history`, history stays on the host machine. See [history](history.md) for service behavior.
137
-
138
- ## Hosted execution credentials
139
-
140
- The Fly Sprite connection is host configuration. It must be in place when the host starts, before a client asks for a Sprite session. The connection needs a token:
141
-
142
- ```json
143
- {
144
- "flySprites": {
145
- "baseURL": "https://api.sprites.dev",
146
- "tokenEnv": "FLY_SPRITES_TOKEN"
147
- }
148
- }
149
- ```
150
-
151
- An inline `token` wins when present. Otherwise Tau reads the variable named by `tokenEnv`. Session creation fails if neither gives a token.
152
-
153
- The host reads these settings from its own startup configuration, never from an attached client. `/reload` does not reload them. Restart the host after changing the Sprite connection or its environment variables.
154
-
155
- ## Safe verification
156
-
157
- Check a credential by using it, without printing its value:
158
-
159
- - Run `tau auth list` to check Codex identities, the active account, refresh status, and usage windows.
160
- - Restart the process that uses `apiKeys` after changing them.
161
- - Make a small request with the intended persona to verify model authentication and endpoint access.
162
- - After setting Exa, speech, history, or Fly credentials, use that feature. If a credential is missing, the error names where Tau looks for it.
163
- - For remote sessions, first confirm which machine is the host and which process runs the feature.
164
-
165
- Do not check by printing the environment, `config.json`, or `auth.json` into a transcript. If a secret ends up in shell history, logs, a session, or version control, rotate it at the provider and replace it. Broader handling guidance is in [security](security.md) and failure checks are in [troubleshooting](troubleshooting.md).
@@ -1,57 +0,0 @@
1
- # Models
2
-
3
- A model definition tells Tau how to call a provider's model and what the model can do, including its limits and cost. A persona picks one provider and model, and credentials authorize the request. Because these are separate, model metadata can be updated without changing personas.
4
-
5
- Tau ships a model catalog and refreshes compatible metadata from `pi.dev`. The catalog a session sees therefore depends on the installed Tau version and on the host's cached copy of the remote catalog.
6
-
7
- ## Providers, models, and personas
8
-
9
- A **provider** has its own authentication and one or more request APIs. A **model** is named by a provider ID and an exact model ID, such as `openai/gpt-6.1-sol`. A [persona](personas.md) combines a model with a system prompt, settings, tools, and subagents.
10
-
11
- The bundled catalog comes from Tau's model library, `pi-ai`. It lists known provider IDs and model IDs, with request API names, endpoints, capabilities, token limits, and pricing. A model in the catalog is not necessarily usable: the provider may lack credentials, the account may not have access to the model, or the endpoint may reject it. See [credentials](credentials.md).
12
-
13
- ## Remote catalog
14
-
15
- A Tau host that runs models loads cached catalogs from `~/.config/tau/models-store.json` at startup. If the cache is older than four hours, it checks `pi.dev` in the background. This check happens only at startup; there is no recurring refresh. Set `TAU_OFFLINE` to skip it, or `refreshModelCatalog: false` to skip it for one [Node SDK](node-sdk.md) client. Skipping the check does not remove an existing cache or block an explicit `tau models refresh`.
16
-
17
- Tau requests the catalog separately for each provider that its `pi-ai` version supports. Each request has a 15-second timeout. A successful provider is cached even when another fails. A failed provider keeps its previous cached data, or the bundled data if there is none. Run `tau models refresh` on the host to refresh immediately, regardless of cache age. It keeps every successful update and exits nonzero if any provider failed.
18
-
19
- Remote data replaces matching model records completely and can add new model IDs. Tau sends its `pi-ai` version to `pi.dev` so the service returns compatible records. Cached data older than the bundled catalog is ignored.
20
-
21
- A session keeps the catalog that was available when it was created. A background refresh does not change it. Run `/reload` to use the host's latest cache. Switching personas keeps the session's current catalog.
22
-
23
- ## Unbundled model IDs
24
-
25
- Custom personas and subagent launch allowlists may name a model ID that is not in the catalog, as long as the provider is known. Tau then builds the model from that provider's default template. This lets you use newly released models, but Tau does not know their real capabilities or prices. Prefer IDs from the catalog when accurate metadata matters.
26
-
27
- ## Model system notices
28
-
29
- `modelSystemNotices` is set in `config.json`, and its keys are checked against the model catalog:
30
-
31
- ```json
32
- {
33
- "modelSystemNotices": {
34
- "openai/gpt-5.7-preview": "Use the preview endpoint only for non-production analysis."
35
- }
36
- }
37
- ```
38
-
39
- Keys use the exact form `<provider>/<model>`. Provider IDs must be known. Model IDs are case-sensitive and must be in the catalog. Values must be non-empty strings. The map merges by key across configuration levels, and the nearest notice wins.
40
-
41
- When a main agent or subagent using that model receives user input, Tau adds the notice to the start of the input as a system block that the model sees and the transcript hides. The block is saved with the user message, and later compaction treats it as part of the history. Maintenance prompts and compaction messages do not get a new notice. Ephemeral agents never receive model system notices.
42
-
43
- Use notices for guidance specific to one model. Never put credentials or other secrets in them, because the notice is saved in the session.
44
-
45
- ## Applying and verifying changes
46
-
47
- Run `/reload` in an idle TUI session after refreshing the model catalog or changing `modelSystemNotices`. Reload loads the session's configuration and content again, reapplies the active persona if its ID still exists, and reports model or configuration warnings. The TUI refuses to reload while a turn is running.
48
-
49
- To check, without starting the TUI, that a persona resolves to the expected provider and model for a new local session:
50
-
51
- ```sh
52
- tau --debug --persona release-coder
53
- ```
54
-
55
- Debug output shows persona IDs and the selected model IDs, but not every metadata field. It also prints the full system prompt and project context, so be careful where you share it. A small real request is the final check for the endpoint, API compatibility, model access, and credentials.
56
-
57
- Unknown providers, persona models that cannot be resolved, and notices for IDs missing from the catalog produce configuration warnings. In a remote session, the warnings name files on the session's execution environment. See [troubleshooting](troubleshooting.md).
@@ -1,430 +0,0 @@
1
- # Node SDK
2
-
3
- Tau's Node SDK is a typed client for creating, observing, and controlling sessions without handling the wire protocol yourself. Use the in-process client when your application should run the host itself, the WebSocket client to connect to a long-running `tau serve` host, or the transport adapter to bring your own connection.
4
-
5
- The SDK speaks the same [session protocol](session-protocol.md) as the TUI, so sessions behave the same in local applications, remote integrations, and the terminal.
6
-
7
- ## Install and import
8
-
9
- Tau requires Node.js 24 or later.
10
-
11
- ```sh
12
- npm install @markusylisiurunen/tau
13
- ```
14
-
15
- Import the SDK from its package entry point:
16
-
17
- ```ts
18
- import { createTauSdkClient } from "@markusylisiurunen/tau/sdk";
19
- ```
20
-
21
- Tau is an ES module package.
22
-
23
- ## Choose a client
24
-
25
- ### Own an in-process host
26
-
27
- `createTauSdkClient()` creates a local host and connects through an in-process transport:
28
-
29
- ```ts
30
- const client = await createTauSdkClient({
31
- persona: "gpt-6.1-sol-coder:high",
32
- });
33
- ```
34
-
35
- The host uses the current user's Tau session store and history database. The `cwd` option decides which configuration the host reads at startup, for host-wide services, and defaults to `process.cwd()`. Each session reads its own configuration and content from the execution environment and `cwd` passed to `client.sessions.create()`.
36
-
37
- The in-process options are:
38
-
39
- ```ts
40
- type TauSdkClientOptions = {
41
- cwd?: string;
42
- persona?: string;
43
- reasoning?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
44
- noAgentContextFiles?: boolean;
45
- refreshModelCatalog?: boolean;
46
- onDiagnostic?: (diagnostic: TauSdkHostDiagnostic) => void;
47
- connectTimeoutMs?: number;
48
- initialize?: { client: { name: string; version: string } };
49
- clientTools?: TauSdkClientTool[];
50
- };
51
- ```
52
-
53
- `persona`, `reasoning`, and `noAgentContextFiles` apply to sessions created by this host. `persona` (an ID, optionally with `:<reasoning>`) must exist in the new session's directory, or creation fails. Recovered sessions keep their saved settings. `connectTimeoutMs` defaults to 5,000 ms. Default initialization metadata is `{ client: { name: "tau-sdk", version: "1" } }`.
54
-
55
- The in-process host never writes background diagnostics to stdout or stderr. `onDiagnostic` receives them as structured objects. `history_recording` reports delayed, dropped, or recovered local recording, with a session ID and pending operation and byte counts. `history_replication_failed` reports remote delivery failures. Neither stops agent work; see [history](history.md) for retries and durability limits. `session_config_warnings` reports `cwd` and `warnings` when the host loads a session with invalid configuration or content. The session still starts, and an error thrown by `onDiagnostic` does not block it.
56
-
57
- By default, an in-process client starts one background model catalog check against `pi.dev`. Each session keeps the catalog it started with until `session.reload()`. Set `refreshModelCatalog: false` to skip this client's check, or `TAU_OFFLINE` to skip automatic checks for the whole process. See [models](models.md) and [security](security.md).
58
-
59
- Closing this client saves live sessions, shuts down its host, and cancels and waits for its catalog refresh. A refresh shared with another in-process client continues until the last of them closes.
60
-
61
- ### Connect to `tau serve`
62
-
63
- `createTauSdkWebSocketClient()` connects to a long-running WebSocket host:
64
-
65
- ```ts
66
- import { createTauSdkWebSocketClient } from "@markusylisiurunen/tau/sdk";
67
-
68
- const client = await createTauSdkWebSocketClient({
69
- url: "wss://tau.example.com",
70
- authToken: process.env.TAU_WS_AUTH_TOKEN,
71
- initialize: {
72
- client: { name: "acme-automation", version: "1.0.0" },
73
- },
74
- });
75
- ```
76
-
77
- Options are `url`, optional `authToken`, `connectTimeoutMs`, `initialize`, `clientTools`, and an optional `webSocketFactory` for runtimes that need their own WebSocket implementation. Closing the client closes only its connection; the sessions stay on the server.
78
-
79
- The WebSocket token gives full access to all sessions. See [remote sessions](remote-sessions.md) for deployment and TLS, and [security](security.md) for the trust model.
80
-
81
- ### Supply a protocol transport
82
-
83
- `createTauSdkClientFromTransport(transport, options?)` builds the same client on top of any `SessionProtocolTransport`, so you can use another transport with the same session behavior.
84
-
85
- A custom transport implements:
86
-
87
- ```ts
88
- type SessionProtocolTransport = {
89
- readonly ready: SessionProtocolReadyMessage;
90
- connect(initializeParams, timeoutMs): Promise<void>;
91
- request(method, params): Promise<unknown>;
92
- onDelta(listener): () => void;
93
- onEphemeral(listener): () => void;
94
- onPendingUserMessages(listener): () => void;
95
- onSubagentActivities(listener): () => void;
96
- onClientTool(listener): () => void;
97
- onFailure(listener): () => void;
98
- close(): Promise<void>;
99
- };
100
- ```
101
-
102
- When the transport fails for good, it must call the `onFailure` listeners, so the SDK can abort client tools and reject open requests.
103
-
104
- ## Create and run a session
105
-
106
- A typical integration creates a session (which also observes it), listens for updates, submits work, and closes cleanly:
107
-
108
- ```ts
109
- import {
110
- TauSessionProtocolResponseError,
111
- TauTransportError,
112
- createTauSdkClient,
113
- } from "@markusylisiurunen/tau/sdk";
114
-
115
- const client = await createTauSdkClient();
116
- const session = await client.sessions.create({
117
- executionEnvironment: {
118
- kind: "local",
119
- cwd: process.cwd(),
120
- },
121
- attributes: {
122
- source: "sdk",
123
- repository: "github.com/example/atlas",
124
- },
125
- });
126
-
127
- const unsubscribe = session.onDelta((delta) => {
128
- console.log(delta.sessionId, delta.fromRevision, delta.toRevision);
129
- });
130
-
131
- try {
132
- const result = await session.submit("Summarize the current changes.");
133
- const snapshot = await session.snapshot();
134
- console.log(result.userHistoryEntryId, result.turn.status, snapshot.revision);
135
- } catch (error) {
136
- if (error instanceof TauSessionProtocolResponseError) {
137
- console.error(error.code, error.message);
138
- } else if (error instanceof TauTransportError) {
139
- console.error(error.message);
140
- } else {
141
- throw error;
142
- }
143
- } finally {
144
- unsubscribe();
145
- await session.unobserve();
146
- await client.close();
147
- }
148
- ```
149
-
150
- Creating a session requires the full execution environment and the creation attributes, which never change afterward. Tau sets the `machine` and `cwd` attributes itself and replaces any values you send for them. The `cwd` of the execution environment must be absolute and is a path in the chosen environment, which may not be where the SDK runs. A Fly Sprite session refers to an existing Sprite that the host is configured to reach. See [sessions](sessions.md) for creation attributes and [ownership and scope](ownership-and-scope.md) for which machine owns which paths.
151
-
152
- To set the main conversation's automatic-compaction threshold at creation, pass `autoCompactThresholdTokens` as a safe integer of at least 50,000. Omit it or pass `null` to use the persona default, falling back to the model's context window minus 16,384 tokens. Applying a persona resets the threshold to `null`, even when reapplying the same persona, unless the call supplies a new threshold. The effective threshold cannot exceed this model-based limit.
153
-
154
- Use `session.setAutoCompactThreshold(50000)` to change the threshold from the next logical turn, or `session.setAutoCompactThreshold(null)` to restore the default. Snapshot `settings` contain both `autoCompactThresholdTokens` (the configured value) and `effectiveAutoCompactThresholdTokens` (the trigger for the selected model). See [automatic compaction](sessions.md#automatic-compaction) for timing, limits, and costs.
155
-
156
- `session.unobserve()` stops observing, and that `TauSdkSession` object can no longer be used. The session itself is not deleted. `client.close()` closes the whole client and is safe to call more than once.
157
-
158
- The connected `TauSdkClient` exposes:
159
-
160
- | Member | Purpose |
161
- | --- | --- |
162
- | `ready` | The validated server `ready` message and advertised methods. |
163
- | `sessions.create(input)` | Create and observe a session, and return its object. |
164
- | `sessions.list()` | List each session's `{ sessionId, lifecycle }`. |
165
- | `sessions.setRetention(id, durationMs)` | [Keep a session loaded without clients](session-protocol.md#keep-a-session-loaded-without-clients), or clear with `null`. |
166
- | `sessions.collect(id)` | Unload a session if nothing holds it, and return `{ disposed }`. |
167
- | `sessions.observe(sessionId)` | Observe an existing session and return its object. |
168
- | `subscribe(listener)` | Receive deltas for every observed session on this connection. |
169
- | `subscribePendingUserMessages(listener)` | Receive pending-state replacements across observed sessions. |
170
- | `subscribeSubagentActivities(listener)` | Receive subagent-activity changes across observed sessions. |
171
- | `subscribeEphemeral(listener)` | Receive ephemeral events, which are not guaranteed, across observed sessions. |
172
- | `close()` | Close the client and everything it owns. |
173
-
174
- Each subscription returns an unsubscribe function.
175
-
176
- ## Use the session object
177
-
178
- `TauSdkSession.id` is the session's ID. Each method corresponds to a protocol method; the [method reference](session-protocol-methods.md) gives exact results, turn outcomes, and when a call returns `busy` or interrupts work.
179
-
180
- | SDK method | Purpose |
181
- | --- | --- |
182
- | `record(text, options?)` | Append user text without running a turn. |
183
- | `submit(text, options?)` | Append user text and run an idle session turn. |
184
- | `queue(text, options?)` | Run now, or after the running turn. |
185
- | `steer(text)` | Change the running turn's direction at its next safe point. |
186
- | `cancelPendingMessages()` | Cancel all queued messages and steering not yet applied. |
187
- | `retry()` | Run from current history without appending user text. |
188
- | `exec(command, options?)` | Run a command in a login Bash in the execution environment. |
189
- | `sample({ context, options })` | Run a standalone model call without changing the session. |
190
- | `interrupt()` | Ask the session's running work to stop. |
191
- | `snapshot()` | Read the complete current snapshot. |
192
- | `setAutoCompactThreshold(thresholdTokens)` | Set or reset automatic compaction, starting with the next logical turn. |
193
- | `setReasoning(reasoning)` | Set reasoning, starting with the next turn. |
194
- | `setPersona(personaId, overrides?)` | Atomically apply a persona, with optional `{ reasoning, autoCompactThresholdTokens }` overrides, and return the updated snapshot. Pass `null` without overrides to apply the workspace default. |
195
- | `resolvePrompt(promptId)` | Load a current prompt body from the execution environment. |
196
- | `autocompletePaths({ query, limit })` | Get a limited list of path suggestions from the execution environment. |
197
- | `reload()` | Reload the session's configuration and content. |
198
- | `compact(mode, options?)` | Manually compact model context. |
199
- | `rewindToHistoryEntryId(id)` | Rewind from one user history entry while idle. |
200
- | `interruptSubagent(subagentId)` | Interrupt one live subagent run. |
201
- | `createEphemeralContext(options)` | Create an agent context on the host that is not saved. |
202
- | `submitEphemeralThread(options)` | Run or continue one ephemeral thread. |
203
- | `closeEphemeralContext(contextId)` | Close an ephemeral context and its threads. |
204
- | `unobserve()` | Stop observing. |
205
-
206
- `submit`, `queue`, and `record` accept `{ historyEntryId?: string }`; without it, Tau generates the ID. Use `getTauSdkSessionTurnRecord(snapshot, id)` to tell whether an accepted turn is unknown, running, or finished, or `getTauSdkSessionTurnOutcome(snapshot, id)` when you only need the final outcome.
207
-
208
- `createEphemeralContext` accepts an optional `workingDirectory` for project instructions, skills, and tool defaults. Relative paths resolve against the session directory; omitting it uses the session directory. This does not change the main session.
209
-
210
- `createEphemeralContext` and `submitEphemeralThread` accept an optional `reasoning` effort. Without it, a new context uses the session's current effort. On submission, the given effort becomes the thread's effort before the turn runs. A fork copies the source thread's effort, then applies any given effort.
211
-
212
- ### Execute a command
213
-
214
- `exec` generates a unique execution ID for you. It supports exact positional arguments, environment variables other than `HOME`, binary stdin, a starting `cwd`, a timeout, a capture limit, and a cancellation signal:
215
-
216
- ```ts
217
- const controller = new AbortController();
218
- const result = await session.exec('exec "$0" "$@"', {
219
- args: ["git", "status", "--short"],
220
- cwd: "/srv/workspaces/atlas",
221
- timeoutMs: 10_000,
222
- maxCaptureBytes: 256 * 1024,
223
- signal: controller.signal,
224
- });
225
-
226
- console.log(result.exitCode, result.output);
227
- ```
228
-
229
- Aborting the signal cancels only this command, with `session.cancelExec`, and rejects the call. Turns and other commands keep running. The command is never added to the conversation.
230
-
231
- ### Sample a model
232
-
233
- `sample` uses the session's current model and credentials, but only the context you supply, in Tau's provider-independent format:
234
-
235
- ```ts
236
- const sampled = await session.sample({
237
- context: {
238
- systemPrompt: "Classify the request in one word.",
239
- messages: [
240
- {
241
- role: "user",
242
- content: [{ type: "text", text: "I cannot log in." }],
243
- timestamp: Date.now(),
244
- },
245
- ],
246
- },
247
- options: { reasoning: "low", maxTokens: 100 },
248
- });
249
-
250
- console.log(sampled.message.content);
251
- ```
252
-
253
- You can reuse the returned assistant message in a later sample's context. If you pass tool schemas, the model may return tool calls, but Tau never runs them. Sampling sends no deltas, changes neither the snapshot revision nor the cost, and adds nothing to the conversation.
254
-
255
- ## Consume streamed state
256
-
257
- `TauSdkClient` has subscriptions for all sessions on the connection, and `TauSdkSession` has subscriptions for one session. Prefer the session's own unless one component handles several sessions.
258
-
259
- ### Snapshot deltas
260
-
261
- `session.onDelta(listener)` receives only that session's `TauSdkDelta` messages. Deltas that arrive before the first listener is added are kept and delivered to it. Apply them to your snapshot with `applySessionProtocolDelta`. If a revision is missing or a change is invalid, fetch a fresh copy with `session.snapshot()`.
262
-
263
- Methods that return a full snapshot, such as reload, compact, rewind, and persona change, let the session object drop the kept deltas up to that revision. Do not replay UI effects from those dropped deltas.
264
-
265
- ### Pending input
266
-
267
- `session.pendingUserMessages()` returns a copy of the full pending-message state. `session.onPendingUserMessages(listener)` sends the current state right away, then each newer full replacement. Its revision is separate from the snapshot's.
268
-
269
- ```ts
270
- const stopPending = session.onPendingUserMessages(({ state }) => {
271
- console.log(state.messages.map((message) => [message.mode, message.text]));
272
- });
273
- ```
274
-
275
- All clients observing the live session share pending input. It is empty after recovery.
276
-
277
- ### Subagent activity
278
-
279
- `session.subagentActivities()` returns the current live activity. `session.onSubagentActivities(listener)` sends the current subagents right away as `agent.set` changes, then later replacements and removals for each subagent.
280
-
281
- To keep your own copy, use `applySessionProtocolSubagentActivitiesMessage`. This channel has its own revision and does not replace the saved `snapshot.agents`.
282
-
283
- ### Ephemeral events
284
-
285
- `session.onEphemeral(listener)` receives footer notices, ephemeral thread progress, and timeline notices that are not saved. Delivery is not guaranteed, and these events are never replayed or included in `session.snapshot()`.
286
-
287
- If you show `timeline.item` events, accept only the current epoch and place each by its sequence number. Compaction and rewind causes decide which of these items you keep. The [session protocol](session-protocol.md) gives the application rules.
288
-
289
- ## Host a browser diff review
290
-
291
- `startTauSdkDiffReview()` starts the built-in browser review UI for an observed session, without the TUI and without opening a browser. Your application can put it behind its own reverse proxy, store review state, restore earlier conversations, and receive the submitted review once through a callback.
292
-
293
- See [SDK browser diff review](sdk-diff-review.md) for startup, storage, submission, and lifecycle.
294
-
295
- ## Provide client tools
296
-
297
- Pass `TauSdkClientTool` entries in `clientTools` to give the model tools that run in your process:
298
-
299
- ```ts
300
- import {
301
- createTauSdkClient,
302
- truncateTauClientToolText,
303
- } from "@markusylisiurunen/tau/sdk";
304
-
305
- const client = await createTauSdkClient({
306
- clientTools: [
307
- {
308
- schema: {
309
- name: "local_picker",
310
- description: "Choose one item from the user's local workspace.",
311
- parameters: {
312
- type: "object",
313
- properties: {
314
- choice: { type: "string" },
315
- },
316
- required: ["choice"],
317
- additionalProperties: false,
318
- },
319
- executionTimeoutMs: 60_000,
320
- },
321
- describe: (args) => {
322
- const input = args as { choice: string };
323
- return {
324
- subject: truncateTauClientToolText(input.choice),
325
- };
326
- },
327
- execute: async (args, context) => {
328
- const input = args as { choice: string };
329
- context.signal.throwIfAborted();
330
- const status = await context.executionEnvironment.exec(
331
- "git status --short",
332
- {
333
- signal: context.signal,
334
- },
335
- );
336
- return {
337
- content: status.output || "Working tree is clean.",
338
- presentation: {
339
- subject: truncateTauClientToolText(input.choice),
340
- },
341
- };
342
- },
343
- },
344
- ],
345
- });
346
- ```
347
-
348
- The handler receives `sessionId`, the calling `agentId`, `callId`, an `AbortSignal`, and the execution-environment API. The handler runs on the client machine, while `context.executionEnvironment.exec()` runs commands in the session's execution environment.
349
-
350
- `describe` is optional. If present, the SDK calls it before accepting the call, with the arguments and a smaller context of `sessionId`, `agentId`, `callId`, and `signal`, without execution-environment access. It may return a partial presentation for the running card, with `subject`, `subjectWrap`, `details`, or `metadata`. Tau sets the action and operation, fills in omitted fields, and acknowledges with the result before calling `execute`.
351
-
352
- The execution result may include the same partial shape for the finished card. Return a string or `{ content, presentation? }` for success, or `{ ok: false, error, presentation? }` for a handled failure. `content` may be a string, sent as one text block, or an ordered array of text and image blocks. Omitted presentation fields get Tau's defaults, and an empty `details` or `metadata` array hides that default. If `describe` throws, the SDK reports a preparation error and does not call `execute`. If no result is returned, because of cancellation, timeout, detach, or another failure, the host shows a complete default card.
353
-
354
- Tau keeps every presentation field you set, up to the protocol limits, without truncating or normalizing it. `truncateTauClientToolText` truncates text for you by lines and characters, keeping the start or the middle. Use its result directly as a subject. For a block of detail text, split the result on `\n` and make each line one `details` entry; use `maxLines: 1` when the result goes into a single entry. The helper does not replace protocol validation. The SDK aborts handlers when the host cancels, the client closes, or the transport fails, and `client.close()` waits for running handlers to finish.
355
-
356
- Each assistant turn keeps the tool definitions it started with. Client tools are not affected by the persona's tool list. Names must not match host tools or tools of another observing client. See [client tools](client-tools.md) for authority, limits, command-backed tools, and disconnect behavior.
357
-
358
- ### Build a code-mode tool
359
-
360
- `createTauCodeModeClientTool()` turns an API you define into a client tool that runs one-off JavaScript programs against it:
361
-
362
- ```ts
363
- import {
364
- buildTauCodeModeToolDescription,
365
- createTauCodeModeClientTool,
366
- } from "@markusylisiurunen/tau/sdk";
367
-
368
- const name = "tickets";
369
- const tickets = createTauCodeModeClientTool({
370
- name,
371
- description: buildTauCodeModeToolDescription({
372
- name,
373
- description: "Read support tickets.",
374
- }),
375
- documentation: "# Tickets API\n\nUse `tickets.get(id)` to read one ticket.",
376
- api: {
377
- get: async ([id], { signal }) => ticketClient.get(String(id), { signal }),
378
- },
379
- });
380
- ```
381
-
382
- Pass `tickets` in `clientTools`. The model's code receives your API namespace, `docs` (read on demand), `printText`, the async `printImage`, `truncate` and `truncateLines`, and the real `Date` and `Math`. API calls pass through a size-limited JSON bridge. The submitted code, truncated and wrapped, is the subject of the running and finished tool cards. You write the description; the description builder is optional.
383
-
384
- Use `await printImage({ data, mimeType })` to return a base64 image. Results contain an ordered `content` array of text and image blocks, and SDK client tools keep that order: consecutive text output forms one block, and each image splits the text before and after it. The helper validates and prepares JPEG, PNG, or WebP images outside the sandbox, creates no files, and uses the limits described in [tools](tools.md).
385
-
386
- Each program must finish within the definition's `timeoutMs`, which defaults to 60,000 ms and includes time spent waiting for API calls. The helper appends this deadline to the tool description so the model can see it, and uses the same value as the tool's `executionTimeoutMs`.
387
-
388
- Code-mode calls and standalone runs accept an optional `maxOutputTokens` (1 through 65,536), with a default text budget of 8,192 tokens. Saving output to files is off unless the definition provides a `persistOutput` callback.
389
-
390
- The SDK also exports `executeTauCodeMode` for standalone runs. The separate `@markusylisiurunen/tau/code-mode` entry point also exports `runTauClientToolCommand` and `runTauCodeModeCommand` for command tools. Use these helpers instead of implementing the protocol yourself.
391
-
392
- ## Cancel and close deliberately
393
-
394
- Most turn and session-changing methods do not accept an `AbortSignal`. Call `session.interrupt()` to stop running work on the host. `session.exec()` is the exception: its optional signal cancels only that command.
395
-
396
- `client.close()` ends the connection: it rejects open requests, aborts client tool handlers, waits for them to finish, and closes the transport. For the default in-process client, it also saves sessions and shuts down the host.
397
-
398
- Always close clients in `finally`. Never use a client after `close()`.
399
-
400
- ## Handle errors
401
-
402
- All exported SDK and transport errors extend `TauSessionClientError`:
403
-
404
- - `TauSessionProtocolResponseError` means the host returned a protocol error. It exposes `code`, `message`, `requestId`, and optional `data`.
405
- - `TauTransportError` means the connection failed: during setup, framing, version checks, a timeout, closing, or another fatal transport error.
406
-
407
- Branch on a protocol error's `code`, not its message. A successful request can still return a failed, aborted, or blocked turn outcome, so inspect `result.turn.status` separately.
408
-
409
- An exception in one listener does not stop delivery to others. Handle errors inside your listeners, and keep state updates deterministic.
410
-
411
- ## Use the public types and helpers
412
-
413
- The SDK entry point exports every type an integration needs, so you never import from internal modules:
414
-
415
- - `TauSdkClient`, `TauSdkSession`, client option types, session summaries, and request and result aliases;
416
- - `TauSdkDelta`, `SessionProtocolSnapshot`, pending-message types, subagent-activity types, and ephemeral event types;
417
- - `TauSdkClientTool`, its execution context and execution-environment API, and code-mode definition and result types;
418
- - `SessionProtocolTransport`, listener types, WebSocket options, and transport errors.
419
-
420
- It also exports `applySessionProtocolDelta`, `applySessionProtocolSubagentActivitiesMessage`, the turn-ledger helpers, and user-text projection helpers:
421
-
422
- ```ts
423
- import {
424
- getTauUserDisplayText,
425
- getTauUserModelText,
426
- projectTauUserText,
427
- } from "@markusylisiurunen/tau/sdk";
428
- ```
429
-
430
- Use `getTauUserDisplayText` before showing user text from a snapshot. It removes Tau metadata and leading hidden `<system>` blocks. `getTauUserModelText` removes Tau metadata but keeps the hidden blocks the model sees. `projectTauUserText` returns both. These helpers are for user messages only.