@preapexis/piexis 0.2.2 → 0.2.5

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 (149) hide show
  1. package/README.md +85 -131
  2. package/apps/server/src/index.ts +97 -0
  3. package/apps/server/src/session-manager.ts +95 -0
  4. package/apps/server/src/workspace.ts +39 -0
  5. package/{tsconfig.json → apps/server/tsconfig.json} +3 -3
  6. package/apps/web/dist/assets/index-D4n3_lAw.js +10 -0
  7. package/apps/web/dist/assets/index-igiK0FPY.css +1 -0
  8. package/apps/web/dist/index.html +3 -0
  9. package/bin/piexis-web.mjs +24 -0
  10. package/extensions/agents.ts +205 -0
  11. package/extensions/ask-question.ts +54 -95
  12. package/extensions/recommended-tools.ts +62 -0
  13. package/extensions/ui.ts +204 -58
  14. package/extensions/webui.ts +45 -0
  15. package/lib/agent-config.ts +55 -0
  16. package/lib/agents.ts +208 -0
  17. package/lib/question-model.ts +98 -0
  18. package/lib/question-ui.ts +214 -0
  19. package/lib/recommended-tools.ts +119 -0
  20. package/lib/subagent-runner.ts +146 -0
  21. package/lib/ui-tips.json +41 -0
  22. package/package.json +41 -14
  23. package/packages/pi-integration/src/rpc-client.ts +99 -0
  24. package/packages/shared/src/index.ts +27 -0
  25. package/prompts/init.md +10 -2
  26. package/prompts/summary.md +7 -6
  27. package/schemas/agent.schema.json +48 -0
  28. package/skills/{claude-api/LICENSE.txt → caveman/LICENSE} +2 -2
  29. package/skills/caveman/LICENSE-MIT +21 -0
  30. package/skills/caveman/NOTICE +10 -0
  31. package/skills/caveman/SKILL.md +89 -0
  32. package/skills/find-skills/SKILL.md +141 -0
  33. package/skills/ponytail/LICENSE +21 -0
  34. package/skills/ponytail/NOTICE +9 -0
  35. package/skills/ponytail/SKILL.md +52 -0
  36. package/themes/midnight.json +81 -0
  37. package/.github/workflows/publish.yml +0 -35
  38. package/AGENTS.md +0 -58
  39. package/eval/README.md +0 -72
  40. package/eval/permission-cases.json +0 -28
  41. package/eval/permissions.mjs +0 -103
  42. package/extensions/background-tasks.ts +0 -433
  43. package/extensions/background-worker.ts +0 -50
  44. package/extensions/glob.ts +0 -32
  45. package/extensions/mode.ts +0 -397
  46. package/lib/bash-approvals.ts +0 -113
  47. package/lib/bash-policy.ts +0 -164
  48. package/lib/mode-policy.ts +0 -174
  49. package/lib/path-policy.ts +0 -182
  50. package/lib/permission-classifier.ts +0 -128
  51. package/lib/permission-config.ts +0 -91
  52. package/lib/permission-denials.ts +0 -32
  53. package/lib/permission-intent.ts +0 -128
  54. package/lib/permission-taxonomy.ts +0 -15
  55. package/lib/task-broker.ts +0 -65
  56. package/lib/task-checkout.ts +0 -39
  57. package/lib/task-git.ts +0 -44
  58. package/lib/task-patch.ts +0 -106
  59. package/lib/task-permissions.ts +0 -51
  60. package/lib/task-report.ts +0 -62
  61. package/lib/task-worktree-policy.ts +0 -56
  62. package/scripts/release.mjs +0 -32
  63. package/skills/claude-api/SKILL.md +0 -572
  64. package/skills/claude-api/csharp/claude-api/README.md +0 -362
  65. package/skills/claude-api/csharp/claude-api/batches.md +0 -14
  66. package/skills/claude-api/csharp/claude-api/files-api.md +0 -25
  67. package/skills/claude-api/csharp/claude-api/streaming.md +0 -28
  68. package/skills/claude-api/csharp/claude-api/tool-use.md +0 -164
  69. package/skills/claude-api/curl/examples.md +0 -256
  70. package/skills/claude-api/curl/managed-agents.md +0 -371
  71. package/skills/claude-api/go/claude-api/README.md +0 -188
  72. package/skills/claude-api/go/claude-api/files-api.md +0 -23
  73. package/skills/claude-api/go/claude-api/streaming.md +0 -43
  74. package/skills/claude-api/go/claude-api/tool-use.md +0 -220
  75. package/skills/claude-api/go/managed-agents/README.md +0 -564
  76. package/skills/claude-api/java/claude-api/README.md +0 -238
  77. package/skills/claude-api/java/claude-api/files-api.md +0 -27
  78. package/skills/claude-api/java/claude-api/streaming.md +0 -24
  79. package/skills/claude-api/java/claude-api/tool-use.md +0 -228
  80. package/skills/claude-api/java/managed-agents/README.md +0 -443
  81. package/skills/claude-api/php/claude-api/README.md +0 -174
  82. package/skills/claude-api/php/claude-api/batches.md +0 -15
  83. package/skills/claude-api/php/claude-api/files-api.md +0 -13
  84. package/skills/claude-api/php/claude-api/streaming.md +0 -27
  85. package/skills/claude-api/php/claude-api/tool-use.md +0 -253
  86. package/skills/claude-api/php/managed-agents/README.md +0 -443
  87. package/skills/claude-api/python/claude-api/README.md +0 -565
  88. package/skills/claude-api/python/claude-api/batches.md +0 -198
  89. package/skills/claude-api/python/claude-api/files-api.md +0 -170
  90. package/skills/claude-api/python/claude-api/sdk-upgrade.md +0 -286
  91. package/skills/claude-api/python/claude-api/streaming.md +0 -179
  92. package/skills/claude-api/python/claude-api/tool-use.md +0 -627
  93. package/skills/claude-api/python/managed-agents/README.md +0 -335
  94. package/skills/claude-api/ruby/claude-api/README.md +0 -134
  95. package/skills/claude-api/ruby/claude-api/streaming.md +0 -16
  96. package/skills/claude-api/ruby/claude-api/tool-use.md +0 -41
  97. package/skills/claude-api/ruby/managed-agents/README.md +0 -394
  98. package/skills/claude-api/shared/admin-api.md +0 -179
  99. package/skills/claude-api/shared/agent-design.md +0 -101
  100. package/skills/claude-api/shared/anthropic-cli.md +0 -269
  101. package/skills/claude-api/shared/claude-platform-on-aws.md +0 -59
  102. package/skills/claude-api/shared/cost-optimization.md +0 -233
  103. package/skills/claude-api/shared/error-codes.md +0 -262
  104. package/skills/claude-api/shared/live-sources.md +0 -166
  105. package/skills/claude-api/shared/managed-agents-api-reference.md +0 -455
  106. package/skills/claude-api/shared/managed-agents-client-patterns.md +0 -220
  107. package/skills/claude-api/shared/managed-agents-core.md +0 -359
  108. package/skills/claude-api/shared/managed-agents-environments.md +0 -226
  109. package/skills/claude-api/shared/managed-agents-events.md +0 -290
  110. package/skills/claude-api/shared/managed-agents-memory.md +0 -201
  111. package/skills/claude-api/shared/managed-agents-multiagent.md +0 -260
  112. package/skills/claude-api/shared/managed-agents-onboarding.md +0 -82
  113. package/skills/claude-api/shared/managed-agents-outcomes.md +0 -108
  114. package/skills/claude-api/shared/managed-agents-overview.md +0 -77
  115. package/skills/claude-api/shared/managed-agents-scheduled-deployments.md +0 -156
  116. package/skills/claude-api/shared/managed-agents-self-hosted-sandboxes.md +0 -282
  117. package/skills/claude-api/shared/managed-agents-tools.md +0 -504
  118. package/skills/claude-api/shared/managed-agents-webhooks.md +0 -143
  119. package/skills/claude-api/shared/model-migration.md +0 -1872
  120. package/skills/claude-api/shared/models.md +0 -142
  121. package/skills/claude-api/shared/platform-availability.md +0 -53
  122. package/skills/claude-api/shared/prompt-audit.md +0 -223
  123. package/skills/claude-api/shared/prompt-caching.md +0 -292
  124. package/skills/claude-api/shared/token-counting.md +0 -56
  125. package/skills/claude-api/shared/tool-use-concepts.md +0 -526
  126. package/skills/claude-api/typescript/claude-api/README.md +0 -405
  127. package/skills/claude-api/typescript/claude-api/batches.md +0 -106
  128. package/skills/claude-api/typescript/claude-api/files-api.md +0 -98
  129. package/skills/claude-api/typescript/claude-api/streaming.md +0 -178
  130. package/skills/claude-api/typescript/claude-api/tool-use.md +0 -586
  131. package/skills/claude-api/typescript/managed-agents/README.md +0 -359
  132. package/skills-lock.json +0 -359
  133. package/tests/auto-permissions.test.mjs +0 -315
  134. package/tests/background-tasks.test.mjs +0 -27
  135. package/tests/background-worker.test.mjs +0 -60
  136. package/tests/bash-permissions.test.mjs +0 -276
  137. package/tests/glob.test.mjs +0 -31
  138. package/tests/mode.test.mjs +0 -62
  139. package/tests/permission-evaluation.test.mjs +0 -70
  140. package/tests/permission-foundation.test.mjs +0 -194
  141. package/tests/permission-policy.test.mjs +0 -158
  142. package/tests/runtime/README.md +0 -51
  143. package/tests/runtime/harness.mjs +0 -190
  144. package/tests/runtime/permissions.test.mjs +0 -192
  145. package/tests/runtime/tui.test.mjs +0 -60
  146. package/tests/skills-routing.test.mjs +0 -51
  147. package/tests/task-integration.test.mjs +0 -324
  148. package/tests/task-permissions.test.mjs +0 -178
  149. package/tests/task-worktree-policy.test.mjs +0 -53
@@ -1,220 +0,0 @@
1
- # Managed Agents - Common Client Patterns
2
-
3
- Patterns you'll write on the client side when driving a Managed Agent session, grounded in working SDK examples.
4
-
5
- Code samples are TypeScript - other languages follow the same shape; see `{lang}/managed-agents/README.md` (cURL and C#: `curl/managed-agents.md`) for equivalents.
6
-
7
- ---
8
-
9
- ## 1. Lossless stream reconnect
10
-
11
- **Problem:** SSE has no replay. If the connection drops mid-session, a naive reconnect re-opens the stream from "now" and you silently miss every event emitted in between.
12
-
13
- **Solution:** on reconnect, fetch the full event history via `events.list()` *before* consuming the live stream, and dedupe on event ID as the live stream catches up.
14
-
15
- ```ts
16
- const seenEventIds = new Set<string>()
17
- const stream = await client.beta.sessions.events.stream(session.id)
18
-
19
- // Stream is now open and buffering server-side. Read history first.
20
- for await (const event of client.beta.sessions.events.list(session.id)) {
21
- seenEventIds.add(event.id)
22
- handle(event)
23
- }
24
-
25
- // Tail the live stream. Dedupe only gates handle() - terminal checks must run
26
- // even for already-seen events, or a terminal event that was in the history
27
- // response gets skipped by `continue` and the loop never exits.
28
- for await (const event of stream) {
29
- if (!seenEventIds.has(event.id)) {
30
- seenEventIds.add(event.id)
31
- handle(event)
32
- }
33
- if (event.type === 'session.status_terminated') break
34
- if (event.type === 'session.status_idle' && event.stop_reason.type !== 'requires_action') break
35
- }
36
- ```
37
-
38
- ---
39
-
40
- ## 2. `processed_at` - queued vs processed
41
-
42
- Every event on the stream carries `processed_at` (ISO 8601), set when the event finishes processing. For client-sent events (`user.message`, `user.interrupt`, `user.tool_confirmation`) it's `null` while the event is queued behind earlier ones, and populated once the agent processes it - so the same event appears on the stream twice, once with `null` and once with a timestamp. (Exception: a `user.interrupt` sent while the session is paused at its budget is accepted and ignored - it never appears at all; see `shared/managed-agents-events.md` § Reaching a session budget.)
43
-
44
- **Three event types skip the queued phase:** `user.define_outcome`, `user.custom_tool_result`, and `user.tool_result` are processed on receipt and echoed back with `processed_at` already populated. A pending -> acknowledged UI that assumes "first sighting is always `null`" will never clear for these - treat a populated `processed_at` on first sighting as immediately acknowledged.
45
-
46
- ```ts
47
- for await (const event of stream) {
48
- if (event.type === 'user.message') {
49
- if (event.processed_at == null) onQueued(event.id)
50
- else onProcessed(event.id, event.processed_at)
51
- }
52
- }
53
- ```
54
-
55
- Use this to drive pending -> acknowledged UI state for anything you send. How you map a locally-rendered optimistic message to the server-assigned `event.id` is application-specific (typically via the return value of `events.send()` or FIFO ordering).
56
-
57
- ---
58
-
59
- ## 3. Interrupt a running session
60
-
61
- Send `user.interrupt` as a normal event. The session keeps running until it reaches a safe boundary, then goes idle.
62
-
63
- ```ts
64
- await client.beta.sessions.events.send(session.id, {
65
- events: [{ type: 'user.interrupt' }],
66
- })
67
-
68
- // Drain until the session is truly done - see Pattern 5 for the full gate.
69
- for await (const event of stream) {
70
- if (event.type === 'session.status_terminated') break
71
- if (
72
- event.type === 'session.status_idle' &&
73
- event.stop_reason.type !== 'requires_action'
74
- ) break
75
- }
76
- ```
77
-
78
- Reference: `interrupt.ts` - sends the interrupt the moment it sees `span.model_request_start`, drains to idle, then verifies via `sessions.retrieve()`.
79
-
80
- ---
81
-
82
- ## 4. `tool_confirmation` round-trip
83
-
84
- When a call evaluates to `ask` - the tool has `permission_policy: { type: 'always_ask' }`, or it has `{ type: 'auto' }` and the server reached no determination - the `agent.tool_use` / `agent.mcp_tool_use` event carries `evaluated_permission === 'ask'` and the session goes idle waiting for a decision. Respond with `user.tool_confirmation`.
85
-
86
- ```ts
87
- for await (const event of stream) {
88
- if ((event.type === 'agent.tool_use' || event.type === 'agent.mcp_tool_use') && event.evaluated_permission === 'ask') {
89
- await client.beta.sessions.events.send(session.id, {
90
- events: [{
91
- type: 'user.tool_confirmation',
92
- tool_use_id: event.id, // not a toolu_ id - use event.id
93
- result: 'allow', // or 'deny'
94
- // deny_message: '...', // optional, only with result: 'deny'
95
- }],
96
- })
97
- }
98
- }
99
- ```
100
-
101
- Key points:
102
- - `tool_use_id` is `event.id` (typically `sevt_...`), **not** a `toolu_...` ID.
103
- - `result` is `'allow' | 'deny'`. Use `deny_message` to tell the model *why* you denied - it gets surfaced back to the agent.
104
- - Multiple pending tools: respond once per `agent.tool_use` / `agent.mcp_tool_use` event with `evaluated_permission === 'ask'`.
105
- - Gate on `evaluated_permission === 'ask'`, not on the policy you configured - it covers `always_ask` and `auto`-indeterminate alike. Calls the server **denies** under `auto` (`evaluated_permission === 'deny'`, `evaluation.evaluated_permission.reason_code === 'high_risk'`) never enter this flow: the agent gets an error tool result and the session keeps running; sending a confirmation for one is a 400.
106
- - Log `event.evaluation` for audit (`type` + `reason_code`), and tolerate a `type` or `reason_code` you don't recognize - branch on known values, pass unknown ones through.
107
-
108
- Reference: `tool-permissions.ts`.
109
-
110
- ---
111
-
112
- ## 5. Correct idle-break gate
113
-
114
- Do not break on `session.status_idle` alone. The session goes idle transiently - e.g. between parallel tool executions, while waiting for a `user.tool_confirmation`, or while awaiting a `user.custom_tool_result`. Break when idle with a non-`requires_action` `stop_reason` (terminal, or `budget_reached` - resumable only by a budget update, so break unless you intend to change or remove the budget), or on `session.status_terminated`.
115
-
116
- ```ts
117
- for await (const event of stream) {
118
- handle(event)
119
- if (event.type === 'session.status_terminated') break
120
- if (event.type === 'session.status_idle') {
121
- if (event.stop_reason.type === 'requires_action') continue // waiting on you - handle it
122
- break // end_turn, retries_exhausted, or budget_reached - see list below
123
- }
124
- }
125
- ```
126
-
127
- `stop_reason.type` values on `session.status_idle`:
128
- - `requires_action` - agent is waiting on a client-side event (tool confirmation, custom tool result). Handle it, don't break. **Self-hosted exception:** if the session went `requires_action`-idle with no pending `agent.tool_use` / `agent.mcp_tool_use` (`ask`) or `agent.custom_tool_use` to answer, the worker failed the claimed work item (typically a memory-store mount error, logged only on the worker host). Don't `continue` forever on that - surface it, fix the host, and send `user.interrupt` to re-queue the work (`shared/managed-agents-self-hosted-sandboxes.md` § Memory stores -> Troubleshooting).
129
- - `retries_exhausted` - terminal failure. Break, then check `sessions.retrieve()` for the error state.
130
- - `end_turn` - normal completion.
131
- - `budget_reached` - the session hit its spend cap and paused. Not terminal and not resumable by any event: change (typically raise) or remove the session's `budget` to resume, or treat it as done. A `session.usage` event with the final cost immediately precedes this idle. See `shared/managed-agents-core.md` § Session budgets.
132
-
133
- ---
134
-
135
- ## 6. Post-idle status-write race
136
-
137
- The SSE stream emits `session.status_idle` slightly before the session's queryable status reflects it. Clients that break on idle and immediately call `sessions.delete()` or `sessions.archive()` will intermittently 400 with "cannot delete/archive while running."
138
-
139
- Poll before cleanup:
140
-
141
- ```ts
142
- let s
143
- for (let i = 0; i < 10; i++) {
144
- s = await client.beta.sessions.retrieve(session.id)
145
- if (s.status !== 'running') break
146
- await new Promise(r => setTimeout(r, 200))
147
- }
148
- if (s?.status !== 'running') {
149
- await client.beta.sessions.archive(session.id)
150
- } // else: still running after 2s - don't archive, let it settle or escalate
151
- ```
152
-
153
- ---
154
-
155
- ## 7. Stream-first, then send
156
-
157
- Always open the stream **before** sending the kickoff event. Otherwise the agent may process the event and emit the first events before your consumer is attached, and you'll miss them.
158
-
159
- ```ts
160
- const stream = await client.beta.sessions.events.stream(session.id)
161
- await client.beta.sessions.events.send(session.id, {
162
- events: [{ type: 'user.message', content: [{ type: 'text', text: 'Hello' }] }],
163
- })
164
- for await (const event of stream) { /* ... */ }
165
- ```
166
-
167
- The `Promise.all([stream, send])` shape works too, but stream-first is simpler and has the same effect - the stream starts buffering the moment it's opened.
168
-
169
- ---
170
-
171
- ## 8. File-mount gotchas
172
-
173
- **The mounted resource has a different `file_id` than the file you uploaded.** Session creation makes a session-scoped copy.
174
-
175
- ```ts
176
- const uploaded = await client.beta.files.upload({ file, purpose: 'agent_resource' })
177
- // uploaded.id -> the original file
178
- const session = await client.beta.sessions.create({
179
- /* ... */
180
- resources: [{ type: 'file', file_id: uploaded.id, mount_path: '/workspace/data.csv' }],
181
- })
182
- // session.resources[0].file_id !== uploaded.id <- different IDs
183
- ```
184
-
185
- Delete the original via `files.delete(uploaded.id)`; the session-scoped copy is garbage-collected with the session. `mount_path` must be absolute - see `shared/managed-agents-environments.md`.
186
-
187
- ---
188
-
189
- ## 9. Secrets for non-MCP APIs and CLIs - keep them host-side via custom tools
190
-
191
- **Problem:** you want the agent to call a third-party API or run a CLI that needs a secret (API key, token, service-account credential), but you can't or don't want to hand the secret to a vault.
192
-
193
- **First check:** for cloud environments, the first-class answer is now a vault `environment_variable` credential - the agent's shell sees an opaque placeholder and the real secret is substituted at egress. See `shared/managed-agents-tools.md` -> Vaults. Use this pattern instead when that doesn't fit: **self-hosted sandboxes** (env-var credentials not yet supported there), clients that reject the placeholder via local format validation, secrets that must never leave your infrastructure, or calls that need host-side binaries.
194
-
195
- **Solution:** move the authenticated call to your side. Declare a custom tool on the agent; when the agent emits `agent.custom_tool_use`, your orchestrator (the process reading the SSE stream) executes the call with its own credentials and responds with `user.custom_tool_result`. The container never sees the key.
196
-
197
- ```ts
198
- // Agent template: declare the tool, no credentials
199
- tools: [{ type: 'custom', name: 'linear_graphql', input_schema: { /* query, vars */ } }]
200
-
201
- // Orchestrator: handle the call with host-side creds
202
- for await (const event of stream) {
203
- if (event.type === 'agent.custom_tool_use' && event.name === 'linear_graphql') {
204
- const result = await linear.request(event.input.query, event.input.vars) // host's key
205
- await client.beta.sessions.events.send(session.id, {
206
- events: [{
207
- type: 'user.custom_tool_result',
208
- custom_tool_use_id: event.id,
209
- content: [{ type: 'text', text: JSON.stringify(result) }],
210
- }],
211
- })
212
- }
213
- }
214
- ```
215
-
216
- Same shape works for `gh` CLI, local eval scripts, or anything else that needs host-side auth or binaries.
217
-
218
- **Security note:** this does not expose a public endpoint. `agent.custom_tool_use` arrives on the SSE stream your orchestrator already holds open with your Anthropic API key, and `user.custom_tool_result` goes back via `events.send()` under the same key. Your orchestrator is a client, not a server - nothing unauthenticated is listening.
219
-
220
- **Do not embed API keys in the system prompt or user messages as a workaround.** Prompts and messages are stored in the session's event history, returned by `events.list()`, and included in compaction summaries - a secret placed there is durably persisted and readable via the API for the life of the session.
@@ -1,359 +0,0 @@
1
- # Managed Agents - Core Concepts
2
-
3
- ## Architecture
4
-
5
- Managed Agents is built around four core concepts:
6
-
7
- | Concept | Endpoint | What it is |
8
- |---|---|---|
9
- | **Agent** | `/v1/agents` | A persisted, versioned object defining the agent's capabilities and persona: model, system prompt, tools, MCP servers, skills. **Must be created before starting a session.** See the Agents section below. |
10
- | **Session** | `/v1/sessions` | A stateful interaction with an agent. References a pre-created agent by ID + an environment + initial instructions. Produces an event stream. |
11
- | **Environment** | `/v1/environments` | A template defining the configuration for container provisioning. |
12
- | **Container** | N/A | An isolated compute instance where the agent's **tools** execute (bash, file ops, code). The agent loop does not run here - it runs on Anthropic's orchestration layer and acts on the container via tool calls. |
13
-
14
- ```
15
- +-------------------------------------+
16
- | Anthropic orchestration layer |
17
- Agent (config) ------->| (agent loop: Claude + tool calls) |
18
- +--------------+----------------------+
19
- | tool calls
20
- v
21
- Environment (template) --> Container (tool execution workspace)
22
- |
23
- Session -+
24
- +-- Resources (files, repos, memory stores - attached at startup)
25
- +-- Vault IDs (MCP credential references)
26
- +-- Conversation (event stream in/out)
27
- ```
28
-
29
- > **Agent creation is a prerequisite.** Sessions reference a pre-created agent by ID - `model`/`system`/`tools` live on the agent object, never on the session. Every flow starts with `POST /v1/agents`.
30
-
31
- ---
32
-
33
- ## Session Lifecycle
34
-
35
- ```
36
- rescheduling -> running <-> idle -> terminated
37
- ```
38
-
39
- | Status | Description |
40
- | -------------- | ------------------------------------------------------------------ |
41
- | `idle` | Agent has finished the current task, and is awaiting input. It's either waiting for input to continue working via a `user.message`, blocked awaiting a `user.custom_tool_result` or `user.tool_confirmation`, or paused because the session budget cap was reached. The `stop_reason` attached contains more information about why the Agent has stopped working. |
42
- | `running` | Session has starting running, and the Agent is actively doing work. |
43
- | `rescheduling` | Session is (re)scheduling after a retryable error has occurred, ready to be picked up by the orchestration system. |
44
- | `terminated` | Session has ended and is in an irreversible, unusable state - **either on completion or because of an unrecoverable error**. Terminated does not by itself mean failure; fetch the session to tell the two apart. |
45
-
46
- - Events can be sent when the session is `running` or `idle`. Messages are queued and processed in order. Exception: a session paused at its budget (`stop_reason: budget_reached`) accepts only **settle events** - events that resolve work already in progress (`user.tool_confirmation`, `user.tool_result`, `user.custom_tool_result`, `user.interrupt`) rather than starting new work - see § Session budgets.
47
- - The agent transitions `idle -> running` when it receives a new event, then back to `idle` when done.
48
- - Errors surface as `session.error` events in the stream, not as a status value.
49
-
50
- Every session has a live trace view in the Anthropic Console at `https://platform.claude.com/workspaces/{workspace}/sessions/{session_id}`. Print this URL immediately after creating a session so the user can watch tool calls and messages stream in real time. **`{workspace}` is the workspace the API key belongs to** - use `default` only when that's the org's Default workspace. The session response does **not** include a workspace field and the Console has no workspace-agnostic session route, so for non-default workspaces substitute the workspace's ID (visible in the Console URL bar, or expose it as a config value alongside the API key). A `default` link to a session that lives in another workspace lands on a **"Session not found"** page - the **Search workspaces** button there will locate it, but it is not an automatic redirect.
51
-
52
- ### Built-in session features
53
-
54
- - **Context compaction** - if you approach max context, the API automatically condenses session history to keep the interaction going
55
- - **Prompt caching** - historical repeated tokens are cached, reducing processing time and cost
56
- - **Extended thinking** - on by default; `agent.thinking` events signal thinking progress and carry no thinking content
57
-
58
- ### Session operations
59
-
60
- | Operation | Notes |
61
- |---|---|
62
- | List / fetch | Paginated list or single resource by ID |
63
- | Update | `title`, `metadata`, and the session-local `agent.tools`/`agent.mcp_servers` can be overridden (see § Updating the agent configuration mid-session). `budget` can only be changed or removed (see § Session budgets). `vault_ids` is create-only - update requests setting it are rejected. |
64
- | Archive | Session becomes **read-only**. Not reversible. |
65
- | Delete | Permanently deletes session, event history, container, and checkpoints. |
66
-
67
- These are ops/inspection calls - typically made from a terminal, not application code. From the shell (see `shared/anthropic-cli.md`):
68
-
69
- ```sh
70
- ant beta:sessions list --transform '{id,title,status,created_at}' --format jsonl
71
- ant beta:sessions retrieve --session-id "$SID"
72
- ant beta:sessions:events stream --session-id "$SID" # watch events live
73
- ant beta:sessions archive --session-id "$SID"
74
- ant beta:sessions delete --session-id "$SID"
75
- ```
76
-
77
- ---
78
-
79
- ## Sessions
80
-
81
- A session is a running agent instance inside an environment.
82
-
83
- ### Session Object
84
-
85
- Key fields returned by the API:
86
-
87
- | Field | Type | Description |
88
- | --------------- | -------- | --------------------------------------------------- |
89
- | `type` | string | Always `"session"` |
90
- | `id` | string | Unique session ID |
91
- | `title` | string | Human-readable title |
92
- | `status` | string | `idle`, `running`, `rescheduling`, `terminated` |
93
- | `created_at` | string | ISO 8601 timestamp |
94
- | `updated_at` | string | ISO 8601 timestamp |
95
- | `archived_at` | string | ISO 8601 timestamp (nullable) |
96
- | `environment_id` | string | Environment ID |
97
- | `agent` | object | Agent configuration |
98
- | `resources` | array | Attached files, repos, and memory stores |
99
- | `metadata` | object | User-provided key-value pairs (max 8 keys) |
100
- | `usage` | object | Cumulative usage: token counts, `server_tool_use` (web search/fetch request counts), `list_cost` (consumption priced at public list rates, as `{amount, currency}` with the amount an integer string in minor units - cents), and `active_seconds` (time with >=1 thread running; concurrent-thread overlap counted once - unlike `stats.active_seconds`, which sums per-thread time) |
101
- | `budget` | object | The session's spend cap, when one was set at creation - see § Session budgets |
102
- | `stats` | object | Timing statistics - `stats.active_seconds` sums per-thread time, unlike `usage.active_seconds` |
103
-
104
- ### Creating a session
105
-
106
- **A session is meaningless without an agent.** Sessions reference a pre-created agent by ID. Create the agent first via `agents.create()`, then reference it:
107
-
108
- ```ts
109
- // 1. Create the agent (reusable, versioned)
110
- const agent = await client.beta.agents.create(
111
- {
112
- name: "Coding Assistant",
113
- model: "claude-opus-5",
114
- system: "You are a helpful coding agent.",
115
- tools: [{ type: "agent_toolset_20260401"}],
116
- },
117
- );
118
-
119
- // 2. Start a session that references it
120
- const session = await client.beta.sessions.create(
121
- {
122
- agent: agent.id, // string shorthand -> latest version. Or: { type: "agent", id: agent.id, version: agent.version }
123
- environment_id: environmentId,
124
- title: "Hello World Session",
125
- },
126
- );
127
- ```
128
-
129
- > Tip: **Watch it live in Console.** While developing, print a link so you can click through to the session UI instead of parsing the event stream: `https://platform.claude.com/workspaces/{workspace}/sessions/{session.id}`. Use `default` for `{workspace}` only when the API key belongs to the org's Default workspace; otherwise substitute the workspace's ID (the session response does not carry it - read it from the Console URL bar or make it a config value). Include this `print`/`console.log` in code you generate for users who are iterating locally.
130
-
131
- **Session creation parameters:**
132
-
133
- | Field | Type | Required | Description |
134
- | --------------- | -------- | -------- | ---------------------------------------------- |
135
- | `agent` | string or object | **Yes** | Three forms: string shorthand `"agent_abc123"` (latest version); pinned `{type: "agent", id, version}`; or `{type: "agent_with_overrides", id, version?, ...}` to override `model`/`system`/`tools`/`mcp_servers`/`skills` for this session only - see § Override agent configuration for a session |
136
- | `environment_id`| string | **Yes** | Environment ID |
137
- | `title` | string | No | Human-readable name (appears in logs/dashboards) |
138
- | `resources` | array | No | Files, GitHub repos, or memory stores, attached to the container at startup. Memory stores are session-create-only (not addable via `resources.add()`). |
139
- | `initial_events`| array | No | Events to send at creation, processed in order - collapses create + first send into one call. See § Seeding a session with `initial_events` below. |
140
- | `vault_ids` | array | No | Vault IDs (`vlt_*`) - MCP credentials with auto-refresh + `environment_variable` secrets substituted at egress. See `shared/managed-agents-tools.md` -> Vaults. |
141
- | `budget` | object | No | Hard dollar cap on the session's spend: `{type: "limit", max_list_cost: {amount, currency}}`. **Create-only** - can be changed or removed later, never added. See § Session budgets. |
142
- | `metadata` | object | No | User-provided key-value pairs |
143
-
144
- #### Seeding a session with `initial_events`
145
-
146
- Creating a session without `initial_events` registers the session in `idle` and starts no work; the sandbox is provisioned when the session first needs it. Passing a **non-empty** `initial_events` array starts the agent loop in the same call - the session is **created directly in `running`**, never passing through `idle`. A client that waits for an `idle -> running` transition to know work began will wait forever; check `status` on the create response instead.
147
-
148
- ```python
149
- session = client.beta.sessions.create(
150
- agent=AGENT_ID,
151
- environment_id=ENVIRONMENT_ID,
152
- initial_events=[
153
- {"type": "user.message", "content": [{"type": "text", "text": "Review the auth module."}]},
154
- ],
155
- )
156
- ```
157
-
158
- - **Only `user.message` and `user.define_outcome` are accepted**, max **50** events. The tool-result kinds (`user.tool_confirmation`, `user.tool_result`, `user.custom_tool_result`) are rejected because no agent turn exists yet, and `user.interrupt` because there is no turn to stop. Unlike a scheduled deployment's `initial_events`, a session's does **not** accept `system.message`.
159
- - Each event is validated and persisted before the create response returns, in list order, with a server-assigned ID - exactly as if you had posted it to the send-events endpoint immediately after creation. Per-event content rules are the same as on that endpoint.
160
- - **The events are not echoed on the create response.** Read them back with `sessions.events.list(session.id)` if you need their server-assigned IDs.
161
- - **Validation is all-or-nothing:** if any event fails, the whole request is rejected and no session is created. An empty list is equivalent to omitting the field.
162
- - Rejections: more than one `user.define_outcome` -> 400; a `user.define_outcome` without a `rubric` -> 400; more than 100 file-sourced `document` content blocks across the whole list -> 400; a request body over 32 MB -> 413.
163
-
164
- An outcome-driven session is therefore a single call - pass one `user.define_outcome` in `initial_events` instead of creating the session and then sending the event (see `shared/managed-agents-outcomes.md`).
165
-
166
- **Agent configuration fields** (passed to `agents.create()`, not `sessions.create()`):
167
-
168
- | Field | Type | Required | Description |
169
- | ------------- | -------- | -------- | ---------------------------------------------- |
170
- | `name` | string | **Yes** | Human-readable name (1-256 chars) |
171
- | `model` | string or object | **Yes** | Claude model ID (bare string, or an object taking `id`, `speed`, `effort`, and `inference_geo`). All Claude 4.5+ models supported. See § Effort on the agent model and § Pinning inference geography below. |
172
- | `system` | string | No | System prompt - defines the agent's behavior (up to 100K chars) |
173
- | `tools` | array | No | Encompasses three kinds: (1) pre-built Claude Agent tools (`agent_toolset_20260401`), (2) MCP tools (`mcp_toolset`), and (3) custom client-side tools. Max 128. |
174
- | `mcp_servers` | array | No | MCP server connections - standardized third-party capabilities (e.g. GitHub, Asana). Max 20, unique names. See `shared/managed-agents-tools.md` -> MCP Servers. |
175
- | `skills` | array | No | Customized "best-practices" context with progressive disclosure. Max 20. See `shared/managed-agents-tools.md` -> Skills. |
176
- | `description` | string | No | Description of the agent (up to 2048 chars) |
177
- | `multiagent` | object | No | `{type: "coordinator", agents: [...]}` - roster this agent may delegate to. See `shared/managed-agents-multiagent.md`. |
178
- | `metadata` | object | No | Arbitrary key-value pairs (max 16, keys <=64 chars, values <=512 chars) |
179
-
180
- ### Session budgets
181
-
182
- A **session budget** is an optional hard spend ceiling set at session creation. The platform continuously prices everything the session consumes at **public list rates** (the session's **list cost**) and stops issuing new model requests once that total reaches the cap. A session at its budget **pauses and goes `idle` with `stop_reason: budget_reached`** - it is not terminated; history and sandbox are preserved, and changing or removing the budget resumes the paused work automatically.
183
-
184
- ```python
185
- session = client.beta.sessions.create(
186
- agent=AGENT_ID,
187
- environment_id=ENVIRONMENT_ID,
188
- budget={
189
- "type": "limit",
190
- "max_list_cost": {"amount": "2500", "currency": "USD"}, # minor units: "2500" = $25.00
191
- },
192
- )
193
- ```
194
-
195
- - `type` is always `"limit"`. `max_list_cost.amount` is the amount in **minor units of the currency (cents), as an integer string** with no leading zeros, > 0 - `"2500"` is $25.00, `"50"` is fifty cents. A string rather than a number so no float rounding is ever applied; decimal forms such as `"25.00"` are rejected. `max_list_cost.currency` is uppercase ISO-4217; **`USD` is the only supported currency.**
196
- - **What counts toward list cost:** model tokens at each served model's list price, web searches at $10 per 1,000, and session running time at $0.08/hour. List cost is *not* your contracted price - with negotiated discounts, the session hits the cap when the list-price total does, and billed spend may be lower.
197
- - **Enforcement is a pre-request gate:** before every model request the platform checks whether consumed list cost has reached the cap and pauses the thread if it has; the request that crosses the cap completes, so the final figure can exceed the cap by at most one model request per running thread. Treat the budget as a bound on new work, not an exact stop.
198
- - The reported `list_cost` is **rounded to the nearest cent** while enforcement compares exact amounts - rounding can move the reported figure up to half a cent in either direction from the exact amount, so a session whose reported `list_cost` equals its cap may not yet be paused. Treat `stop_reason: budget_reached` (or the 400 on `user.message`), not the reported figure, as the signal that the cap was reached.
199
- - **Create-only.** Adding a budget to a session created without one is a 400. Updates accept exactly two changes: **change the cap** (the new value can be higher or lower than the old cap, but must be strictly greater than the consumed list cost, else 400: `budget.max_list_cost must be greater than the session's consumed list cost`) or **remove** (`budget: null` - the `session.updated` event carries `budget: null` rather than a separate flag). Because the consumed cost usually sits a fraction past the old cap when the session pauses, base the new value on the session's reported `usage.list_cost`, not the old `max_list_cost`. **Removal is one-way**: a removed budget can never be re-added; to keep a cap, change it instead.
200
- - **At the cap, only settle events are accepted** - events that resolve work already in progress rather than starting new work: `user.tool_confirmation`, `user.tool_result`, `user.custom_tool_result`, `user.interrupt`. A `user.interrupt` sent while the session is paused at its budget (all threads paused at the cap) is accepted and ignored: it does not appear in the event list and changes nothing. Raise or remove the budget to continue. Anything that starts new work (e.g. `user.message`) is a 400 naming that list. No event resumes the session - only a budget change/removal does.
201
- - **Multiagent:** one budget shared across all threads, no per-thread caps. Threads pause independently; each thread's consumption is priced at its own served model. A pending tool ask outranks the cap: a session with one thread at `requires_action` and another at `budget_reached` reports `requires_action` at the session level - answer it as usual (settle events aren't blocked).
202
- - **Models without a list price can't be budgeted:** a budgeted create whose agent (or any roster agent, including the advisor's model) uses an unpriced model is a 400. If a running budgeted session's usage comes to include one, changing the budget is rejected - remove the budget to resume.
203
- - Stream behavior at the cap and the `session.usage` event: `shared/managed-agents-events.md` § Reaching a session budget.
204
- - Scheduled deployments can carry a budget too - copied onto each fired session, with different update semantics (clearable and re-addable): `shared/managed-agents-scheduled-deployments.md` § Deployment budgets.
205
-
206
- > **Not the same thing as Messages-API task budgets.** Session budgets are hard, dollar-denominated, platform-enforced caps on one session. `task_budget` on the Messages API is an advisory, token-denominated budget the model uses to pace itself within one agentic loop.
207
-
208
- ---
209
-
210
- ## Agents
211
-
212
- **This is where every Managed Agents flow begins.** The agent object is a persisted, versioned configuration - you create it once, then reference it by ID every time you start a session. No agent -> no session.
213
-
214
- ### Agent Object
215
-
216
- The API is **flat** - `model`, `system`, `tools` etc. are top-level fields, not wrapped in an `agent:{}` sub-object.
217
-
218
- | Field | Type | Required | Description |
219
- | ------------------ | -------- | -------- | -------------------------------------------------- |
220
- | `name` | string | Yes | Human-readable name |
221
- | `model` | string or object | Yes | Claude model ID - bare string, or `{id, speed?, effort?, inference_geo?}` |
222
- | `system` | string | No | System prompt |
223
- | `tools` | array | No | Agent toolset / MCP toolset / custom tools |
224
- | `mcp_servers` | array | No | MCP server connections |
225
- | `skills` | array | No | Skill references (max 20) |
226
- | `description` | string | No | Description of the agent |
227
- | `multiagent` | object | No | Coordinator roster - see `shared/managed-agents-multiagent.md` |
228
- | `metadata` | object | No | Arbitrary key-value pairs |
229
-
230
- ### Lifecycle: create once, run many, update in place
231
-
232
- The agent is a **persistent resource**, not a per-run parameter. The intended pattern:
233
-
234
- ```
235
- +- setup (once) ---------+ +- runtime (every invocation) -+
236
- | agents.create() | | sessions.create( |
237
- | -> store agent_id | ---> | agent={type:..., id: ID} |
238
- | in config/env/db | | ) |
239
- +------------------------+ +------------------------------+
240
- ```
241
-
242
- **Anti-pattern:** calling `agents.create()` at the top of every script run. This accumulates orphaned agent objects, pays create latency on every invocation, and defeats the versioning model. If you see `agents.create()` in a function that's called per-request or per-cron-tick, that's wrong - hoist it to one-time setup and persist the ID.
243
-
244
- > **Recommended - define agents and environments as YAML + apply via the `ant` CLI.** The split is **CLI for the control plane, SDK for the data plane**: agents and environments are relatively static resources you manage with `ant` (version-controlled YAML, applied from CI); sessions are dynamic and driven by your application through the SDK. See `shared/anthropic-cli.md` -> *Version-controlled Managed Agents resources* for the `ant beta:agents create < agent.yaml` / `update --version N` flow. The SDK `agents.create()` call shown elsewhere in this doc is the in-code equivalent - use it when you need to provision programmatically, but prefer the YAML flow for anything a human maintains.
245
-
246
- ### Effort on the agent model
247
-
248
- Pass `model` as an object to set the effort level: `{"id": "claude-opus-5", "effort": "high"}`. `effort` accepts a level string (`low`, `medium`, `high`, `xhigh`, `max`) or an object such as `{"type": "high"}`. The create/update response echoes it in object form and fills in omitted `model` fields with their defaults.
249
-
250
- > Warning: **Effort is agent configuration only.** An `effort` set inside a per-session `model` override is **not applied** - the session runs at the agent's effort. To change effort you must update the agent (or point the session at a different agent). This is the one field where the override form silently does nothing rather than erroring.
251
-
252
- The same object form carries `speed` for fast mode: `{"id": "claude-opus-5", "speed": "fast"}`.
253
-
254
- ### Pinning inference geography (`inference_geo`)
255
-
256
- The `model` object also takes `inference_geo` to pin the geography that serves the agent's model requests: `{"id": "claude-opus-5", "inference_geo": "us"}`. Accepts `"us"` or `"global"` - and unlike the Messages API, where `inference_geo` is a top-level request parameter, here it is always nested inside `model`, never top-level. When unset, each model request follows the workspace's default inference geo at the time it's served.
257
-
258
- - **Validated at every stage:** the pin is checked against the workspace's `allowed_inference_geos` when the agent is saved, when a session is created from it, and on every turn the session serves. If the workspace allowlist later narrows so the pin is no longer allowed, new sessions can't be created from the agent and **running sessions refuse further turns** - pins are never grandfathered (workspaces rely on them for compliance).
259
- - Setting `inference_geo` on a model that doesn't support geographic inference pinning returns a 400.
260
- - **Fixed for a session's lifetime** - the pin can't change mid-session. Set it on the agent, or set/clear it for one session with a `model` override at session create (see § Override agent configuration for a session).
261
- - **Multiagent rosters must be geo-uniform:** the coordinator's pin and every roster member's must all be the same value or all be unset - see `shared/managed-agents-multiagent.md`.
262
- - Unlike `effort`, an `inference_geo` inside a per-session `model` override **is applied** - and because overrides replace the `model` object in full, an override that *omits* `inference_geo` clears the agent's pin for that session.
263
-
264
- ### Versioning
265
-
266
- Each `POST /v1/agents/{id}` (update) creates a new immutable version - a sequential integer, starting at 1 and incrementing on each update. The agent's history is append-only - you can't edit a past version.
267
-
268
- **`version` on update is optional.** Supply it for optimistic concurrency, or omit it to apply the update unconditionally:
269
-
270
- | `version` | Behavior | Fits |
271
- |---|---|---|
272
- | Supplied (must be >= 1) | 409 if it doesn't match the agent's current version - **even when the fields you send already equal the stored values**. Re-read and retry. | Interactive callers; the recommended default |
273
- | Omitted | Applies unconditionally. The most recent update silently replaces any concurrent one, with no error to either caller. | Declarative apply loops - e.g. a CI job syncing checked-in agent definitions, where the loop owns the agent |
274
-
275
- **Update semantics.** Omitted fields are preserved. Scalar fields (`model`, `system`, `name`, `description`) are replaced; `system` and `description` can be cleared with `null`, while `model` and `name` cannot. Array fields (`tools`, `mcp_servers`, `skills`) are replaced wholesale - `null` or `[]` clears them. **`effort` is the sole exception inside a `model` object you supply:** if the model `id` is unchanged, omitting `effort` leaves the stored level alone; if you change the `id`, an omitted `effort` resets to the new model's default. Other `model` fields are replaced along with the object - **supplying `model` without `inference_geo` clears the agent's inference geo pin.**
276
-
277
- **Why version:**
278
- - **Reproducibility** - pin a session to a known-good config: `{type: "agent", id, version: 3}`
279
- - **Safe iteration** - update the agent without breaking sessions already running on the old version
280
- - **Rollback** - if a new system prompt regresses, pin new sessions back to the prior version while you debug
281
-
282
- **`version` is optional.** Omit it (or use the string shorthand `agent="agent_abc123"`) to get the latest version at session-creation time. Pass it explicitly (`{type: "agent", id, version: N}`) to pin for reproducibility.
283
-
284
- **Getting the version to pin:** `agents.create()` and `agents.update()` both return `version` in the response. Store it alongside `agent_id`. To fetch the current latest for an existing agent: `GET /v1/agents/{id}` -> `.version`.
285
-
286
- **When to update vs create new:** Update (`POST /v1/agents/{id}`) when it's conceptually the same agent with tweaked behavior (better prompt, extra tool). Create a new agent when it's a different persona/purpose. Rule of thumb: if you'd give it the same `name`, update.
287
-
288
- ### Agent Endpoints
289
-
290
- | Operation | Method | Path |
291
- | ---------------- | -------- | ------------------------------------- |
292
- | Create | `POST` | `/v1/agents` |
293
- | List | `GET` | `/v1/agents` |
294
- | Get | `GET` | `/v1/agents/{id}` |
295
- | Update | `POST` | `/v1/agents/{id}` |
296
- | Archive | `POST` | `/v1/agents/{id}/archive` |
297
-
298
- > Warning: **Archive is permanent.** Archiving makes the agent read-only: existing sessions continue to run, but **new sessions cannot reference it**, and there is no unarchive. Since agents have no `delete`, this is the terminal lifecycle state. Never archive a production agent as routine cleanup - confirm with the user first.
299
-
300
- ### Using an Agent in a Session
301
-
302
- Reference the agent by string ID (latest version) or by object with an explicit version:
303
-
304
- ```python
305
- # String shorthand - uses the agent's latest version
306
- session = client.beta.sessions.create(
307
- agent=agent.id,
308
- environment_id=environment_id,
309
- )
310
-
311
- # Or pin to a specific version (int)
312
- session = client.beta.sessions.create(
313
- agent={"type": "agent", "id": agent.id, "version": agent.version},
314
- environment_id=environment_id,
315
- )
316
- ```
317
-
318
- ### Override agent configuration for a session
319
-
320
- The third `agent` form, `agent_with_overrides`, replaces parts of the agent's configuration for **a single session** - try a different model or grant an extra tool without versioning the agent. Pass `id` (and optionally `version`; omitted = latest, same default as the other two forms) plus any of `model`, `system`, `tools`, `mcp_servers`, `skills`:
321
-
322
- ```python
323
- session = client.beta.sessions.create(
324
- agent={
325
- "type": "agent_with_overrides",
326
- "id": agent.id,
327
- "model": "claude-opus-5", # replace the agent's model for this session
328
- "system": None, # clear the system prompt for this session
329
- },
330
- environment_id=environment_id,
331
- )
332
- ```
333
-
334
- Each overridable field follows tri-state rules:
335
- - **Omit** -> the session inherits the value from the referenced agent version.
336
- - **`null` (or `[]` for list fields)** -> the session runs with that field cleared. Applies in full to `system` and `skills`. Three exceptions: `model` is never clearable (`model: null` -> 400 `agent_model_required`); clearing `tools` returns 400 when the session's effective `skills` is non-empty (skills require the `read` tool); and clearing `mcp_servers` returns 400 when the effective `tools` still contains an `mcp_toolset` referencing one of the agent's servers - override `tools` in the same request to drop those entries, then clear `mcp_servers`.
337
- - **A value** -> replaces the agent's value **in full**. Overrides never merge - a `tools` override must list every tool the session should have. One exception: an `effort` level inside a `model` override is **not applied** (set it on the agent instead - see § Effort on the agent model). An `inference_geo` inside a `model` override **is** applied - and because the object is replaced in full, an override that omits it clears the agent's pin, so the session follows the workspace's default inference geo. The overridden value is validated against the workspace's `allowed_inference_geos` at session create.
338
-
339
- Overrides are session-local: they do **not** modify the agent resource or create a new agent version. The response's `agent` object reflects the post-override configuration, while its `id` and `version` still identify the base agent - so you can trace a session back to its base. In multiagent sessions, overrides apply to the coordinator and its `{type: "self"}` copies; roster agents referenced by ID always use their own as-created configuration (see `shared/managed-agents-multiagent.md`).
340
-
341
- ### Updating the agent configuration mid-session
342
-
343
- `sessions.update()` can change `agent.tools` and `agent.mcp_servers` (including permission policies and the per-tool web settings - `allowed_domains` / `blocked_domains` etc., see `shared/managed-agents-tools.md` § Web search & web fetch settings) on an **existing** session. Updated domain lists apply to the rest of the session. This is a **session-local override** - it does not create a new agent version and does not propagate back to the agent object. The provided arrays are **full replacements**; to append one tool, `GET` the session, modify, and `POST` back. The session must be `idle` - interrupt first if running. `vault_ids` is **create-only**: the update param exists in the SDK but is rejected by the API ("Not yet supported") - attach vaults when you create the session.
344
-
345
- Among the agent-configuration fields, only `tools` and `mcp_servers` can change after a session is created - to run with a `model`, `system`, or `skills` other than the agent's values, use `agent_with_overrides` at create time (above). (`title`, `metadata`, and `budget` have their own session-update paths - see § Session operations / § Session budgets.) The agent's model configuration - including its `inference_geo` pin - and its configured `system` field are fixed for the session's lifetime; you can still **append system-level context between turns** by sending a `system.message` event (see `shared/managed-agents-events.md` § Adding system context mid-session).
346
-
347
- ```python
348
- client.beta.sessions.update(
349
- session.id,
350
- agent={
351
- "tools": [
352
- {"type": "agent_toolset_20260401"},
353
- {"type": "mcp_toolset", "mcp_server_name": "linear"},
354
- ],
355
- "mcp_servers": [{"type": "url", "name": "linear", "url": "https://mcp.linear.app/sse"}],
356
- },
357
- )
358
- ```
359
-