zidane 6.4.2 → 6.4.4

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 (114) hide show
  1. package/README.md +7 -5
  2. package/dist/{acp-Ba4OzG71.js → acp-BLO58K3F.js} +5 -5
  3. package/dist/{acp-Ba4OzG71.js.map → acp-BLO58K3F.js.map} +1 -1
  4. package/dist/acp-cli.js +6 -6
  5. package/dist/acp.d.ts +1 -1
  6. package/dist/acp.js +1 -1
  7. package/dist/{agent-BMJKrD84.js → agent-8sUadp5M.js} +72 -9
  8. package/dist/{agent-BMJKrD84.js.map → agent-8sUadp5M.js.map} +1 -1
  9. package/dist/agent.d.ts +1 -1
  10. package/dist/agent.js +2 -2
  11. package/dist/{anthropic-BJhMEi7x.js → anthropic-D3lkw5mv.js} +3 -3
  12. package/dist/{anthropic-BJhMEi7x.js.map → anthropic-D3lkw5mv.js.map} +1 -1
  13. package/dist/{auth-C2Hmb0tt.js → auth-BzYbbdN_.js} +95 -5
  14. package/dist/auth-BzYbbdN_.js.map +1 -0
  15. package/dist/chat/pure.d.ts +3 -3
  16. package/dist/chat/pure.js +1 -1
  17. package/dist/chat.d.ts +4 -4
  18. package/dist/chat.js +4 -4
  19. package/dist/{context-transport-CwJZxs56.js → context-transport-D29WvHcm.js} +3 -3
  20. package/dist/{context-transport-CwJZxs56.js.map → context-transport-D29WvHcm.js.map} +1 -1
  21. package/dist/contexts/daytona.d.ts +1 -1
  22. package/dist/contexts/e2b.d.ts +1 -1
  23. package/dist/eval.d.ts +1 -1
  24. package/dist/eval.js +1 -1
  25. package/dist/extensions.d.ts +1 -1
  26. package/dist/extensions.js +1 -1
  27. package/dist/headless.d.ts +1 -1
  28. package/dist/headless.js +3 -3
  29. package/dist/{index-Gy9wi80M.d.ts → index-C-Nd2ZbV.d.ts} +343 -2
  30. package/dist/index-C-Nd2ZbV.d.ts.map +1 -0
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +11 -10
  33. package/dist/index.js.map +1 -1
  34. package/dist/{login-llWTV13a.js → login-CMVVnAHS.js} +2 -2
  35. package/dist/{login-llWTV13a.js.map → login-CMVVnAHS.js.map} +1 -1
  36. package/dist/{mcp-IaEpSauj.js → mcp-3GXUBwur.js} +3 -3
  37. package/dist/{mcp-IaEpSauj.js.map → mcp-3GXUBwur.js.map} +1 -1
  38. package/dist/mcp.d.ts +1 -1
  39. package/dist/mcp.js +1 -1
  40. package/dist/{messages-D1EryrDs.js → messages-C01kKGj0.js} +2 -2
  41. package/dist/{messages-D1EryrDs.js.map → messages-C01kKGj0.js.map} +1 -1
  42. package/dist/{openai-compat-0MJq4-g9.js → openai-compat-B3c_hzwf.js} +42 -2
  43. package/dist/openai-compat-B3c_hzwf.js.map +1 -0
  44. package/dist/output/stream-json.d.ts +1 -1
  45. package/dist/output/terminal.d.ts +1 -1
  46. package/dist/presets.d.ts +1 -1
  47. package/dist/presets.js +1 -1
  48. package/dist/providers/anthropic.d.ts +1 -1
  49. package/dist/providers/anthropic.js +1 -1
  50. package/dist/providers/arcee.d.ts +1 -1
  51. package/dist/providers/arcee.js +1 -1
  52. package/dist/providers/baseten.d.ts +1 -1
  53. package/dist/providers/baseten.js +1 -1
  54. package/dist/providers/cerebras.d.ts +1 -1
  55. package/dist/providers/cerebras.js +1 -1
  56. package/dist/providers/local.d.ts +1 -1
  57. package/dist/providers/local.js +1 -1
  58. package/dist/providers/openai-compat.d.ts +1 -1
  59. package/dist/providers/openai-compat.js +1 -1
  60. package/dist/providers/openai.d.ts +1 -1
  61. package/dist/providers/openai.js +2 -2
  62. package/dist/providers/openrouter.d.ts +1 -1
  63. package/dist/providers/openrouter.js +1 -1
  64. package/dist/providers/xai.d.ts +1 -1
  65. package/dist/providers/xai.js +1 -1
  66. package/dist/{providers-BSrJx0Tn.js → providers-z1vU0b2Q.js} +100 -4
  67. package/dist/providers-z1vU0b2Q.js.map +1 -0
  68. package/dist/providers.d.ts +2 -2
  69. package/dist/providers.js +5 -5
  70. package/dist/restate.d.ts +52 -2
  71. package/dist/restate.d.ts.map +1 -1
  72. package/dist/restate.js +151 -33
  73. package/dist/restate.js.map +1 -1
  74. package/dist/session/sqlite.d.ts +1 -1
  75. package/dist/{session-B40flcj7.js → session-cr9VdoEO.js} +2 -2
  76. package/dist/{session-B40flcj7.js.map → session-cr9VdoEO.js.map} +1 -1
  77. package/dist/session.d.ts +1 -1
  78. package/dist/session.js +2 -2
  79. package/dist/skills.d.ts +1 -1
  80. package/dist/{stdio-D-02FOVT.js → stdio-BvL8HGYW.js} +2 -2
  81. package/dist/{stdio-D-02FOVT.js.map → stdio-BvL8HGYW.js.map} +1 -1
  82. package/dist/{stdio-loader-Byqw5KjJ.js → stdio-loader-CjfoqBle.js} +2 -2
  83. package/dist/{stdio-loader-Byqw5KjJ.js.map → stdio-loader-CjfoqBle.js.map} +1 -1
  84. package/dist/{tool-formatters-CU0memLh.d.ts → tool-formatters-DPQjso_C.d.ts} +2 -2
  85. package/dist/{tool-formatters-CU0memLh.d.ts.map → tool-formatters-DPQjso_C.d.ts.map} +1 -1
  86. package/dist/{read-state-Dt7UbVsd.js → tool-state-DTs-3ZHH.js} +218 -2
  87. package/dist/tool-state-DTs-3ZHH.js.map +1 -0
  88. package/dist/tools/fetch-url.d.ts +1 -1
  89. package/dist/tools/web-search.d.ts +1 -1
  90. package/dist/tools.d.ts +1 -1
  91. package/dist/tools.js +2 -2
  92. package/dist/{transcript-anchors-4IdT10xC.d.ts → transcript-anchors-BCUpbNxc.d.ts} +2 -2
  93. package/dist/{transcript-anchors-4IdT10xC.d.ts.map → transcript-anchors-BCUpbNxc.d.ts.map} +1 -1
  94. package/dist/{transcript-anchors-CJ4gJn1T.js → transcript-anchors-CgDzYin1.js} +5 -5
  95. package/dist/{transcript-anchors-CJ4gJn1T.js.map → transcript-anchors-CgDzYin1.js.map} +1 -1
  96. package/dist/tui.d.ts +19 -3
  97. package/dist/tui.d.ts.map +1 -1
  98. package/dist/tui.js +90 -54
  99. package/dist/tui.js.map +1 -1
  100. package/dist/{turn-operations-B08dE8kH.d.ts → turn-operations-Bu2Hkinw.d.ts} +3 -3
  101. package/dist/{turn-operations-B08dE8kH.d.ts.map → turn-operations-Bu2Hkinw.d.ts.map} +1 -1
  102. package/dist/{turn-operations-CBdrdYiF.js → turn-operations-CAvi8NYt.js} +67 -2
  103. package/dist/{turn-operations-CBdrdYiF.js.map → turn-operations-CAvi8NYt.js.map} +1 -1
  104. package/dist/types.d.ts +2 -2
  105. package/dist/{xai-CpPbCGWO.js → xai-BPwMQSuF.js} +2 -2
  106. package/dist/{xai-CpPbCGWO.js.map → xai-BPwMQSuF.js.map} +1 -1
  107. package/docs/ARCHITECTURE.md +2 -0
  108. package/docs/RESTATE.md +66 -2
  109. package/package.json +8 -8
  110. package/dist/auth-C2Hmb0tt.js.map +0 -1
  111. package/dist/index-Gy9wi80M.d.ts.map +0 -1
  112. package/dist/openai-compat-0MJq4-g9.js.map +0 -1
  113. package/dist/providers-BSrJx0Tn.js.map +0 -1
  114. package/dist/read-state-Dt7UbVsd.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { m as openaiCompat } from "./openai-compat-0MJq4-g9.js";
1
+ import { m as openaiCompat } from "./openai-compat-B3c_hzwf.js";
2
2
  import { s as resolveOAuthApiKey } from "./oauth-bkEOybqm.js";
3
- import { r as generatePkce } from "./xai-CpPbCGWO.js";
3
+ import { r as generatePkce } from "./xai-BPwMQSuF.js";
4
4
  //#region src/chat/oauth-page/cursor.ts
5
5
  /** pi-ai / zidane OAuth provider id. Also the credentials-file key. */
6
6
  const CURSOR_OAUTH_PROVIDER_ID = "cursor";
@@ -163,6 +163,102 @@ function cursor(params) {
163
163
  };
164
164
  }
165
165
  //#endregion
166
- export { createCursorOAuthProvider as n, cursor as t };
166
+ //#region src/providers/mistral.ts
167
+ const BASE_URL$1 = "https://api.mistral.ai/v1";
168
+ function getApiKey$1(params) {
169
+ if (typeof params?.apiKey === "string" && params.apiKey.length > 0) return params.apiKey;
170
+ if (process.env.MISTRAL_API_KEY) return process.env.MISTRAL_API_KEY;
171
+ throw new Error("No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.");
172
+ }
173
+ /**
174
+ * Model ids that accept `reasoning_effort`. Mistral rejects unknown request
175
+ * fields on some routes, so the knob is sent only for the families that
176
+ * document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the
177
+ * deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`
178
+ * requests stay byte-identical to what they were without this planner.
179
+ */
180
+ const REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\.5|2604))/;
181
+ /**
182
+ * Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two
183
+ * documented values are emitted — `'none'` (thinking chunk omitted, `content`
184
+ * stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends
185
+ * nothing so the model's own default applies.
186
+ *
187
+ * Exported for tests.
188
+ */
189
+ function planMistralReasoning(ctx) {
190
+ if (!REASONING_MODELS.test(ctx.model)) return void 0;
191
+ if (ctx.thinking === void 0 || ctx.thinking === "adaptive") return void 0;
192
+ return { reasoning_effort: ctx.thinking === "off" ? "none" : "high" };
193
+ }
194
+ /**
195
+ * Mistral provider (La Plateforme).
196
+ *
197
+ * Thin wrapper around {@link openaiCompat} with Mistral-specific defaults
198
+ * (base URL, default model, `reasoning_effort` planner). `supportsReasoning`
199
+ * stays off: Mistral carries thinking inside `content` chunks rather than a
200
+ * `reasoning_content` field, so there is nothing to echo back upstream —
201
+ * thinking streams to the UI and is dropped from subsequent requests.
202
+ */
203
+ function mistral(params) {
204
+ return openaiCompat({
205
+ name: "mistral",
206
+ apiKey: getApiKey$1(params),
207
+ baseURL: params?.baseURL || BASE_URL$1,
208
+ defaultModel: params?.defaultModel || "mistral-medium-latest",
209
+ capabilities: params?.capabilities ?? {
210
+ vision: true,
211
+ imageInToolResult: false
212
+ },
213
+ planReasoningRequest: planMistralReasoning,
214
+ extraHeaders: params?.extraHeaders
215
+ });
216
+ }
217
+ //#endregion
218
+ //#region src/providers/zai.ts
219
+ const BASE_URL = "https://api.z.ai/api/paas/v4";
220
+ function getApiKey(params) {
221
+ if (typeof params?.apiKey === "string" && params.apiKey.length > 0) return params.apiKey;
222
+ if (process.env.ZAI_API_KEY) return process.env.ZAI_API_KEY;
223
+ throw new Error("No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.");
224
+ }
225
+ /**
226
+ * Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.
227
+ * GLM has no depth knob — thinking is a binary switch — so any non-`off`
228
+ * level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by
229
+ * default, so a silent omission would not turn thinking off).
230
+ *
231
+ * Exported for tests.
232
+ */
233
+ function planZaiReasoning(ctx) {
234
+ return { thinking: { type: !!ctx.thinking && ctx.thinking !== "off" ? "enabled" : "disabled" } };
235
+ }
236
+ /**
237
+ * Z.ai (Zhipu) GLM provider.
238
+ *
239
+ * Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`
240
+ * round-trip mode: thinking arrives in the `reasoning_content` delta field and
241
+ * is echoed back on assistant messages under the same name, keeping GLM's
242
+ * interleaved/preserved thinking coherent across tool calls.
243
+ */
244
+ function zai(params) {
245
+ return openaiCompat({
246
+ name: "zai",
247
+ apiKey: getApiKey(params),
248
+ baseURL: params?.baseURL || BASE_URL,
249
+ defaultModel: params?.defaultModel || "glm-4.7-flash",
250
+ capabilities: params?.capabilities ?? {
251
+ vision: false,
252
+ imageInToolResult: false
253
+ },
254
+ supportsReasoning: true,
255
+ reasoningMode: "reasoning_content",
256
+ reasoningContentField: "reasoning_content",
257
+ planReasoningRequest: planZaiReasoning,
258
+ extraHeaders: params?.extraHeaders
259
+ });
260
+ }
261
+ //#endregion
262
+ export { cursor as a, planMistralReasoning as i, zai as n, createCursorOAuthProvider as o, mistral as r, planZaiReasoning as t };
167
263
 
168
- //# sourceMappingURL=providers-BSrJx0Tn.js.map
264
+ //# sourceMappingURL=providers-z1vU0b2Q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers-z1vU0b2Q.js","names":["BASE_URL","getApiKey"],"sources":["../src/chat/oauth-page/cursor.ts","../src/providers/cursor.ts","../src/providers/mistral.ts","../src/providers/zai.ts"],"sourcesContent":["/**\n * Cursor OAuth flow.\n *\n * Unlike Anthropic / OpenAI Codex (loopback-redirect PKCE), Cursor uses a\n * **poll-based** PKCE flow with no local callback server:\n *\n * 1. Generate a PKCE verifier + challenge and a random UUID.\n * 2. Open the browser to `cursor.com/loginDeepControl?challenge&uuid&mode&redirectTarget`.\n * 3. Poll `api2.cursor.sh/auth/poll?uuid&verifier` until tokens come back\n * (HTTP 404 = \"not ready yet\", keep polling with backoff).\n * 4. Refresh via `POST api2.cursor.sh/auth/exchange_user_api_key` with\n * `Authorization: Bearer <refresh>`.\n *\n * Token expiry is derived from the access token's JWT `exp` claim (minus a\n * 5-minute safety margin), falling back to +1h when the claim is missing.\n *\n * Flow adapted from https://github.com/ndraiman/pi-cursor-provider, itself\n * derived from https://github.com/ephraimduncan/opencode-cursor.\n *\n * Cursor's auth + inference protocol is unofficial and undocumented — re-verify\n * the endpoints/params below if login starts failing.\n */\n\nimport type {\n OAuthCredentials,\n OAuthLoginCallbacks,\n} from '@earendil-works/pi-ai/oauth'\nimport type { OAuthProviderInterface } from '../../providers/oauth-registry'\nimport { generatePkce } from './pkce'\n\n/** pi-ai / zidane OAuth provider id. Also the credentials-file key. */\nexport const CURSOR_OAUTH_PROVIDER_ID = 'cursor'\n\nconst CURSOR_LOGIN_URL = 'https://cursor.com/loginDeepControl'\nconst CURSOR_POLL_URL = 'https://api2.cursor.sh/auth/poll'\nconst CURSOR_REFRESH_URL = 'https://api2.cursor.sh/auth/exchange_user_api_key'\n\nconst POLL_MAX_ATTEMPTS = 150\nconst POLL_BASE_DELAY_MS = 1000\nconst POLL_MAX_DELAY_MS = 10_000\nconst POLL_BACKOFF_MULTIPLIER = 1.2\nconst POLL_MAX_CONSECUTIVE_ERRORS = 3\n\n/** Fallback lifetime when the JWT carries no `exp`. */\nconst DEFAULT_TOKEN_TTL_MS = 3600 * 1000\n/** Refresh slightly early so requests don't race expiry. */\nconst TOKEN_EXPIRY_SKEW_MS = 5 * 60 * 1000\n\ninterface CursorTokenResponse {\n accessToken: string\n refreshToken: string\n}\n\n/**\n * Derive expiry (epoch ms) from a JWT's `exp` claim, minus a safety skew.\n * Returns `now + 1h` for malformed tokens so a missing claim never wedges\n * refresh into an immediate-expire loop.\n */\nexport function cursorTokenExpiry(token: string): number {\n try {\n const parts = token.split('.')\n const payload = parts[1]\n if (parts.length !== 3 || !payload)\n return Date.now() + DEFAULT_TOKEN_TTL_MS\n\n const json = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))) as { exp?: unknown }\n if (typeof json.exp === 'number')\n return json.exp * 1000 - TOKEN_EXPIRY_SKEW_MS\n }\n catch {\n // fall through to default\n }\n return Date.now() + DEFAULT_TOKEN_TTL_MS\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms))\n}\n\n/**\n * Poll Cursor's auth endpoint until login completes. `404` means the user\n * hasn't finished the browser flow yet; anything else non-2xx is a hard error.\n */\nasync function pollForTokens(\n uuid: string,\n verifier: string,\n callbacks: OAuthLoginCallbacks,\n): Promise<CursorTokenResponse> {\n let wait = POLL_BASE_DELAY_MS\n let consecutiveErrors = 0\n\n for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {\n if (callbacks.signal?.aborted)\n throw new Error('Cursor login aborted')\n\n await delay(wait)\n\n try {\n const url = `${CURSOR_POLL_URL}?uuid=${encodeURIComponent(uuid)}&verifier=${encodeURIComponent(verifier)}`\n const response = await fetch(url, { signal: callbacks.signal })\n\n if (response.status === 404) {\n consecutiveErrors = 0\n wait = Math.min(wait * POLL_BACKOFF_MULTIPLIER, POLL_MAX_DELAY_MS)\n continue\n }\n\n if (response.ok) {\n const data = await response.json() as Partial<CursorTokenResponse>\n if (!data.accessToken || !data.refreshToken)\n throw new Error(`Cursor poll response missing tokens: ${JSON.stringify(data)}`)\n return { accessToken: data.accessToken, refreshToken: data.refreshToken }\n }\n\n throw new Error(`Cursor poll failed (${response.status})`)\n }\n catch (err) {\n if (callbacks.signal?.aborted)\n throw new Error('Cursor login aborted')\n consecutiveErrors++\n if (consecutiveErrors >= POLL_MAX_CONSECUTIVE_ERRORS)\n throw err instanceof Error ? err : new Error(String(err))\n callbacks.onProgress?.('Waiting for Cursor login to complete…')\n }\n }\n\n throw new Error('Cursor authentication timed out')\n}\n\nexport async function loginCursor(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n const { verifier, challenge } = await generatePkce()\n const uuid = crypto.randomUUID()\n\n const authUrl = new URL(CURSOR_LOGIN_URL)\n authUrl.searchParams.set('challenge', challenge)\n authUrl.searchParams.set('uuid', uuid)\n authUrl.searchParams.set('mode', 'login')\n authUrl.searchParams.set('redirectTarget', 'cli')\n\n callbacks.onAuth({\n url: authUrl.toString(),\n instructions: 'A browser window should open. Complete login in Cursor to finish.',\n })\n\n const tokens = await pollForTokens(uuid, verifier, callbacks)\n\n return {\n access: tokens.accessToken,\n refresh: tokens.refreshToken,\n expires: cursorTokenExpiry(tokens.accessToken),\n }\n}\n\nexport async function refreshCursorToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n const response = await fetch(CURSOR_REFRESH_URL, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${credentials.refresh}`,\n 'Content-Type': 'application/json',\n },\n body: '{}',\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => '')\n throw new Error(`Cursor token refresh failed (${response.status}): ${text || response.statusText}`)\n }\n\n const data = await response.json() as Partial<CursorTokenResponse>\n if (!data.accessToken)\n throw new Error(`Cursor token refresh response missing access token: ${JSON.stringify(data)}`)\n\n return {\n access: data.accessToken,\n // Cursor may omit a rotated refresh token — keep the existing one.\n refresh: data.refreshToken || credentials.refresh,\n expires: cursorTokenExpiry(data.accessToken),\n }\n}\n\n/**\n * Build a Cursor `OAuthProviderInterface`. Shape matches Anthropic / Codex so\n * it drops into `BUILTIN_PROVIDERS` and `src/auth.ts` unchanged.\n *\n * No `renderPage` parameter: Cursor's poll flow has no local callback server,\n * so there is no post-redirect page to theme.\n */\nexport function createCursorOAuthProvider(): OAuthProviderInterface {\n return {\n id: CURSOR_OAUTH_PROVIDER_ID,\n name: 'Cursor',\n usesCallbackServer: false,\n login: loginCursor,\n refreshToken: refreshCursorToken,\n getApiKey: credentials => credentials.access,\n }\n}\n","import type { Provider, StreamCallbacks } from '.'\nimport { CURSOR_OAUTH_PROVIDER_ID } from '../chat/oauth-page/cursor'\nimport { resolveOAuthApiKey } from './oauth'\nimport { openaiCompat } from './openai-compat'\n\n/**\n * Cursor provider (OAuth).\n *\n * Auth is fully wired: `bun run auth --cursor` (or the TUI wizard) logs in via\n * Cursor's poll-based PKCE flow and persists credentials; this provider resolves\n * + refreshes the OAuth token on every turn via {@link resolveOAuthApiKey}.\n *\n * Inference is **not** wired yet. Cursor does not expose an OpenAI-compatible\n * HTTP endpoint — it speaks a protobuf/Connect agent protocol over HTTP/2 to\n * `api2.cursor.sh`. Implementing `stream()` requires porting that transport\n * (generated protobuf schemas + an HTTP/2 streaming client) in-process, which\n * is intentionally left as a follow-up. Until then `stream()` resolves the\n * token (proving auth works) and then throws a clear, actionable error.\n *\n * The `openaiCompat` base supplies the message-format helpers (`formatTools`,\n * `userMessage`, `toolResultsMessage`, …) so the provider satisfies the full\n * `Provider` contract and slots into the registry; only `stream` is overridden.\n */\nexport interface CursorParams {\n /** Bypass OAuth resolution with an explicit token (mainly for tests). */\n apiKey?: string\n defaultModel?: string\n /**\n * Extra HTTP headers for the eventual Cursor transport. Accepted for API\n * parity with the other providers and forwarded to the openai-compat base,\n * but inert until Cursor inference is implemented (the `stream` override\n * currently throws before any request is made).\n */\n extraHeaders?: Record<string, string>\n}\n\nconst DEFAULT_MODEL = 'claude-4.6-sonnet'\n\nconst NOT_IMPLEMENTED_MESSAGE\n = 'Cursor OAuth login works, but inference over Cursor is not implemented yet. '\n + 'Cursor uses a protobuf/HTTP-2 agent protocol (not an OpenAI-compatible API), '\n + 'so the streaming transport still needs to be ported. Use another provider for now.'\n\nexport function cursor(params?: CursorParams): Provider {\n const defaultModel = params?.defaultModel || DEFAULT_MODEL\n\n // Base only provides the format/serialization methods; `baseURL` is never\n // hit because we override `stream` below.\n const base = openaiCompat({\n name: 'cursor',\n apiKey: params?.apiKey ?? 'oauth',\n baseURL: 'https://api2.cursor.sh',\n defaultModel,\n capabilities: { vision: true, imageInToolResult: false },\n extraHeaders: params?.extraHeaders,\n })\n\n return {\n ...base,\n meta: { ...base.meta, defaultModel },\n async stream(options, callbacks: StreamCallbacks) {\n // Resolve (and lazily refresh) the OAuth token so auth failures surface\n // here with the right remediation, distinct from the not-implemented path.\n await resolveOAuthApiKey(\n {\n provider: 'cursor',\n providerId: CURSOR_OAUTH_PROVIDER_ID,\n params,\n missingError: 'No Cursor credentials found. Run `bun run auth --cursor` first.',\n refreshError: reason => `Cursor OAuth token refresh failed. Run \\`bun run auth --cursor\\` again. ${reason}`,\n },\n callbacks,\n )\n void options\n throw new Error(NOT_IMPLEMENTED_MESSAGE)\n },\n }\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Mistral La Plateforme — OpenAI-compatible `/v1/chat/completions`. Model ids\n// are plain slugs (`mistral-medium-latest`, `devstral-2512`, …). Reasoning is\n// NOT a separate wire field here: with `reasoning_effort: 'high'` the response\n// `content` becomes a list of `thinking` / `text` chunks (handled by\n// `openaiCompat`'s content-chunk path), and with `'none'` it stays a plain\n// string. See https://docs.mistral.ai/studio-api/conversations/reasoning.\nconst BASE_URL = 'https://api.mistral.ai/v1'\n\nexport interface MistralParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at a regional endpoint or a gateway in\n * front of La Plateforme.\n */\n baseURL?: string\n /**\n * Provider capability flags. The `mistral-medium` / `mistral-large` /\n * `pixtral` families accept `image_url` parts — default:\n * `{ vision: true, imageInToolResult: false }`. Set `vision: false` when\n * pinning a text-only model (`codestral`, `devstral`, `ministral`).\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: MistralParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.MISTRAL_API_KEY)\n return process.env.MISTRAL_API_KEY\n\n throw new Error('No Mistral API key found. Pass `apiKey` or set MISTRAL_API_KEY in your environment.')\n}\n\n/**\n * Model ids that accept `reasoning_effort`. Mistral rejects unknown request\n * fields on some routes, so the knob is sent only for the families that\n * document it (`mistral-small-*`, `mistral-medium-3.5` / `-2604`, and the\n * deprecated-but-live `magistral-*`); `codestral` / `devstral` / `ministral`\n * requests stay byte-identical to what they were without this planner.\n */\nconst REASONING_MODELS = /^(?:magistral-|mistral-small-|mistral-medium-(?:3\\.5|2604))/\n\n/**\n * Map zidane's thinking level to Mistral's `reasoning_effort`. Only the two\n * documented values are emitted — `'none'` (thinking chunk omitted, `content`\n * stays a plain string) and `'high'` (full thinking chunk). `adaptive` sends\n * nothing so the model's own default applies.\n *\n * Exported for tests.\n */\nexport function planMistralReasoning(\n ctx: { model: string, thinking?: ThinkingLevel },\n): Record<string, unknown> | undefined {\n if (!REASONING_MODELS.test(ctx.model))\n return undefined\n if (ctx.thinking === undefined || ctx.thinking === 'adaptive')\n return undefined\n return { reasoning_effort: ctx.thinking === 'off' ? 'none' : 'high' }\n}\n\n/**\n * Mistral provider (La Plateforme).\n *\n * Thin wrapper around {@link openaiCompat} with Mistral-specific defaults\n * (base URL, default model, `reasoning_effort` planner). `supportsReasoning`\n * stays off: Mistral carries thinking inside `content` chunks rather than a\n * `reasoning_content` field, so there is nothing to echo back upstream —\n * thinking streams to the UI and is dropped from subsequent requests.\n */\nexport function mistral(params?: MistralParams): Provider {\n return openaiCompat({\n name: 'mistral',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'mistral-medium-latest',\n capabilities: params?.capabilities ?? { vision: true, imageInToolResult: false },\n planReasoningRequest: planMistralReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n","import type { Provider, ProviderCapabilities } from '.'\nimport type { ThinkingLevel } from '../types'\nimport { openaiCompat } from './openai-compat'\n\n// Z.ai (Zhipu) GLM Open Platform — OpenAI-compatible endpoint. Model ids are\n// plain lowercase slugs (`glm-4.7`, `glm-4.7-flash`, …), reasoning streams in\n// the `reasoning_content` delta field, and thinking is toggled via an\n// `extra_body.thinking` object rather than a `reasoning_effort` string.\n// See https://docs.z.ai/guides/develop/http/introduction and\n// https://docs.z.ai/guides/capabilities/thinking-mode.\nconst BASE_URL = 'https://api.z.ai/api/paas/v4'\n\nexport interface ZaiParams {\n apiKey?: string\n defaultModel?: string\n /**\n * Override the base URL — e.g. point at the dedicated Coding Plan endpoint\n * instead of the standard API endpoint.\n */\n baseURL?: string\n /**\n * Provider capability flags. GLM text models are text-only — default:\n * `{ vision: false, imageInToolResult: false }`.\n */\n capabilities?: ProviderCapabilities\n /**\n * Extra HTTP headers sent on every request. Forwarded to the underlying\n * {@link openaiCompat} client.\n */\n extraHeaders?: Record<string, string>\n}\n\nfunction getApiKey(params?: ZaiParams): string {\n // Resolution order aligned with the other providers: explicit > env > fail.\n if (typeof params?.apiKey === 'string' && params.apiKey.length > 0)\n return params.apiKey\n\n if (process.env.ZAI_API_KEY)\n return process.env.ZAI_API_KEY\n\n throw new Error('No Z.ai API key found. Pass `apiKey` or set ZAI_API_KEY in your environment.')\n}\n\n/**\n * Map zidane's thinking level to Z.ai's `extra_body.thinking` request shape.\n * GLM has no depth knob — thinking is a binary switch — so any non-`off`\n * level enables it and `off` explicitly disables it (GLM-5.x/4.7 think by\n * default, so a silent omission would not turn thinking off).\n *\n * Exported for tests.\n */\nexport function planZaiReasoning(\n ctx: { thinking?: ThinkingLevel },\n): Record<string, unknown> {\n const enabled = !!ctx.thinking && ctx.thinking !== 'off'\n return { thinking: { type: enabled ? 'enabled' : 'disabled' } }\n}\n\n/**\n * Z.ai (Zhipu) GLM provider.\n *\n * Thin wrapper around {@link openaiCompat} pinned to the `reasoning_content`\n * round-trip mode: thinking arrives in the `reasoning_content` delta field and\n * is echoed back on assistant messages under the same name, keeping GLM's\n * interleaved/preserved thinking coherent across tool calls.\n */\nexport function zai(params?: ZaiParams): Provider {\n return openaiCompat({\n name: 'zai',\n apiKey: getApiKey(params),\n baseURL: params?.baseURL || BASE_URL,\n defaultModel: params?.defaultModel || 'glm-4.7-flash',\n capabilities: params?.capabilities ?? { vision: false, imageInToolResult: false },\n supportsReasoning: true,\n reasoningMode: 'reasoning_content',\n reasoningContentField: 'reasoning_content',\n planReasoningRequest: planZaiReasoning,\n extraHeaders: params?.extraHeaders,\n })\n}\n"],"mappings":";;;;;AA+BA,MAAa,2BAA2B;AAExC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,8BAA8B;;AAGpC,MAAM,uBAAuB,OAAO;;AAEpC,MAAM,uBAAuB,MAAS;;;;;;AAYtC,SAAgB,kBAAkB,OAAuB;CACvD,IAAI;EACF,MAAM,QAAQ,MAAM,MAAM,GAAG;EAC7B,MAAM,UAAU,MAAM;EACtB,IAAI,MAAM,WAAW,KAAK,CAAC,SACzB,OAAO,KAAK,IAAI,IAAI;EAEtB,MAAM,OAAO,KAAK,MAAM,KAAK,QAAQ,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,CAAC,CAAC;EAC3E,IAAI,OAAO,KAAK,QAA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AO,OAAO;CAEhB,IAAI,QAAQ,IAAI,aACd,OAAO,QAAQ,IAAI;CAErB,MAAM,IAAI,MAAM,8EAA8E;AAChG;;;;;;;;;AAUA,SAAgB,iBACd,KACyB;CAEzB,OAAO,EAAE,UAAU,EAAE,MADL,CAAC,CAAC,IAAI,YAAY,IAAI,aAAa,QACd,YAAY,WAAW,EAAE;AAChE;;;;;;;;;AAUA,SAAgB,IAAI,QAA8B;CAChD,OAAO,aAAa;EAClB,MAAM;EACN,QAAQ,UAAU,MAAM;EACxB,SAAS,QAAQ,WAAW;EAC5B,cAAc,QAAQ,gBAAgB;EACtC,cAAc,QAAQ,gBAAgB;GAAE,QAAQ;GAAO,mBAAmB;EAAM;EAChF,mBAAmB;EACnB,eAAe;EACf,uBAAuB;EACvB,sBAAsB;EACtB,cAAc,QAAQ;CACxB,CAAC;AACH"}
@@ -1,2 +1,2 @@
1
- import { $f as cerebras, Ap as readOAuthCredentials, Cp as resolvePromptCacheKey, Df as OpenAICompatParams, Dp as credentialsFromParams, Ef as OpenAICompatHttpError, Ep as credentialsFilePath, Jf as LocalParams, Kf as openai, Lf as mapOAIFinishReason, Mp as resolveOAuthApiKey, Np as writeOAuthCredentials, Op as extractRuntimeCredentials, Pf as classifyOpenAICompatError, Pp as OAuthProviderInterface, Qf as CerebrasParams, Sg as setModelCatalog, Sp as derivePromptCacheKey, Tf as OpenAICompatAuthHeader, Tp as ResolveOAuthApiKeyOptions, Uf as OpenAIParams, Xf as CursorParams, Yf as local, Zf as cursor, _f as sanitizeToolSchema, af as StreamCallbacks, bg as ModelCatalogSource, bp as PromptCacheKeyContext, cf as ToolCall, df as TurnResult, dp as applyAnthropicCacheBreakpoints, ep as BasetenParams, ff as XaiParams, gf as SchemaSanitizeResult, hf as SchemaSanitizeProfile, if as ProviderCapabilities, ip as arcee, jp as registerCustomOAuthProvider, kp as isOAuthAccessToken, lf as ToolResult, mf as SchemaSanitizeOptions, nf as HistoryRepair, np as planBasetenReasoning, of as StreamOptions, pf as xai, rf as Provider, rp as ArceeParams, sf as TokenCountPayload, sp as AnthropicParams, tp as baseten, uf as ToolSpec, up as anthropic, vf as sanitizeToolSpecs, vg as ModelCatalog, wp as OAuthParams, xf as openrouter, xg as getModelCatalog, xp as PromptCacheKeyOption, yf as OpenRouterParams, yg as ModelCatalogEntry, zf as openaiCompat } from "./index-Gy9wi80M.js";
2
- export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, HistoryRepair, type LocalParams, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogSource, type OAuthParams, type OAuthProviderInterface, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, type PromptCacheKeyContext, type PromptCacheKeyOption, Provider, ProviderCapabilities, type ResolveOAuthApiKeyOptions, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, isOAuthAccessToken, local, mapOAIFinishReason, openai, openaiCompat, openrouter, planBasetenReasoning, readOAuthCredentials, registerCustomOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai };
1
+ import { $f as planMistralReasoning, Af as OpenAICompatParams, Ap as OAuthParams, Bf as mapOAIFinishReason, Bp as OAuthProviderInterface, Dp as PromptCacheKeyOption, Ep as PromptCacheKeyContext, Fg as ModelCatalogSource, Fp as isOAuthAccessToken, Hf as openaiCompat, Ig as getModelCatalog, Ip as readOAuthCredentials, Kf as OpenAIParams, Lf as classifyOpenAICompatError, Lg as setModelCatalog, Lp as registerCustomOAuthProvider, Mp as credentialsFilePath, Ng as ModelCatalog, Np as credentialsFromParams, Of as OpenAICompatAuthHeader, Op as derivePromptCacheKey, Pg as ModelCatalogEntry, Pp as extractRuntimeCredentials, Qf as mistral, Rp as resolveOAuthApiKey, Sf as OpenRouterParams, Yf as openai, Zf as MistralParams, _f as SchemaSanitizeOptions, _p as applyAnthropicCacheBreakpoints, af as StreamCallbacks, ap as cerebras, bf as sanitizeToolSchema, cf as ToolCall, cp as planBasetenReasoning, df as TurnResult, ep as LocalParams, ff as ZaiParams, gf as xai, gp as anthropic, hf as XaiParams, if as ProviderCapabilities, ip as CerebrasParams, jp as ResolveOAuthApiKeyOptions, kf as OpenAICompatHttpError, kp as resolvePromptCacheKey, lf as ToolResult, lp as ArceeParams, mf as zai, nf as HistoryRepair, np as CursorParams, of as StreamOptions, op as BasetenParams, pf as planZaiReasoning, pp as AnthropicParams, rf as Provider, rp as cursor, sf as TokenCountPayload, sp as baseten, tp as local, uf as ToolSpec, up as arcee, vf as SchemaSanitizeProfile, wf as openrouter, xf as sanitizeToolSpecs, yf as SchemaSanitizeResult, zp as writeOAuthCredentials } from "./index-C-Nd2ZbV.js";
2
+ export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, HistoryRepair, type LocalParams, type MistralParams, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogSource, type OAuthParams, type OAuthProviderInterface, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, type PromptCacheKeyContext, type PromptCacheKeyOption, Provider, ProviderCapabilities, type ResolveOAuthApiKeyOptions, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, type ZaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, registerCustomOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
package/dist/providers.js CHANGED
@@ -1,12 +1,12 @@
1
- import { E as getModelCatalog, S as resolvePromptCacheKey, b as sanitizeToolSpecs, f as mapOAIFinishReason, j as setModelCatalog, l as classifyOpenAICompatError, m as openaiCompat, n as OpenAICompatHttpError, x as derivePromptCacheKey, y as sanitizeToolSchema } from "./openai-compat-0MJq4-g9.js";
2
- import { n as anthropic, r as applyAnthropicCacheBreakpoints } from "./anthropic-BJhMEi7x.js";
1
+ import { E as getModelCatalog, S as resolvePromptCacheKey, b as sanitizeToolSpecs, f as mapOAIFinishReason, j as setModelCatalog, l as classifyOpenAICompatError, m as openaiCompat, n as OpenAICompatHttpError, x as derivePromptCacheKey, y as sanitizeToolSchema } from "./openai-compat-B3c_hzwf.js";
2
+ import { n as anthropic, r as applyAnthropicCacheBreakpoints } from "./anthropic-D3lkw5mv.js";
3
3
  import { a as readOAuthCredentials, c as writeOAuthCredentials, i as isOAuthAccessToken, n as credentialsFromParams, o as registerCustomOAuthProvider, r as extractRuntimeCredentials, s as resolveOAuthApiKey, t as credentialsFilePath } from "./oauth-bkEOybqm.js";
4
4
  import { arcee } from "./providers/arcee.js";
5
5
  import { baseten, planBasetenReasoning } from "./providers/baseten.js";
6
6
  import { cerebras } from "./providers/cerebras.js";
7
- import { t as xai } from "./xai-CpPbCGWO.js";
8
- import { t as cursor } from "./providers-BSrJx0Tn.js";
7
+ import { t as xai } from "./xai-BPwMQSuF.js";
8
+ import { a as cursor, i as planMistralReasoning, n as zai, r as mistral, t as planZaiReasoning } from "./providers-z1vU0b2Q.js";
9
9
  import { local } from "./providers/local.js";
10
10
  import { openai } from "./providers/openai.js";
11
11
  import { openrouter } from "./providers/openrouter.js";
12
- export { OpenAICompatHttpError, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, isOAuthAccessToken, local, mapOAIFinishReason, openai, openaiCompat, openrouter, planBasetenReasoning, readOAuthCredentials, registerCustomOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai };
12
+ export { OpenAICompatHttpError, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, extractRuntimeCredentials, getModelCatalog, isOAuthAccessToken, local, mapOAIFinishReason, mistral, openai, openaiCompat, openrouter, planBasetenReasoning, planMistralReasoning, planZaiReasoning, readOAuthCredentials, registerCustomOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
package/dist/restate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Fp as AgentBehavior, Ip as AgentClock, Km as ToolContext, Nm as ToolResultContent, Xi as McpToolWrap, Yi as McpToolMeta, gh as SessionStore, km as ToolBatchExecutor, of as StreamOptions, qm as ToolDef, rf as Provider } from "./index-Gy9wi80M.js";
1
+ import { $m as ToolDef, Fm as ToolBatchExecutor, Hp as AgentClock, Qm as ToolContext, Vp as AgentBehavior, Xi as McpToolWrap, Yi as McpToolMeta, jh as SessionStore, mh as ToolStateStore, of as StreamOptions, rf as Provider, zm as ToolResultContent } from "./index-C-Nd2ZbV.js";
2
2
  import { g as TaskExitInfo, h as TaskEntry, l as ExecutionHandle, o as DetachedTasksCapability } from "./types-M2DauK2D.js";
3
3
 
4
4
  //#region src/restate/types.d.ts
@@ -838,6 +838,56 @@ declare function wrapAgentTools(tools: Record<string, ToolDef>, ctx: RestateCont
838
838
  exclude?: readonly string[];
839
839
  }): Record<string, ToolDef>;
840
840
  //#endregion
841
+ //#region src/restate/tool-state.d.ts
842
+ /** Default virtual-object state key holding the tool-state map. */
843
+ declare const DEFAULT_TOOL_STATE_KEY = "zidane_tool_state";
844
+ interface RestateToolStateStoreOptions {
845
+ /** Override the state key. Defaults to {@link DEFAULT_TOOL_STATE_KEY}. */
846
+ key?: string;
847
+ /**
848
+ * Per-value size budget enforced when a tool stages a write. Defaults to
849
+ * the library's `DEFAULT_MAX_VALUE_BYTES` (64 KiB), which is far below
850
+ * Restate's own journal-entry ceiling on purpose: an oversized state value
851
+ * doesn't fail politely there — the invocation fails with `RT0003`
852
+ * (MessageSizeLimit) and is retried under the configured policy, i.e. a fat
853
+ * write becomes a poison pill rather than a dropped one.
854
+ */
855
+ maxValueBytes?: number;
856
+ }
857
+ /**
858
+ * Build a {@link ToolStateStore} over the bound virtual object's state.
859
+ *
860
+ * ```ts
861
+ * const agent = createAgent({
862
+ * provider,
863
+ * tools: wrapAgentTools({ shell }, ctx),
864
+ * session: createSession({ id: ctx.key, store: restateSessionStore(ctx) }),
865
+ * toolState: restateToolStateStore(ctx),
866
+ * })
867
+ * ```
868
+ *
869
+ * Single-writer like the session store: the state belongs to the object key,
870
+ * so bind one key per conversation and one agent per invocation.
871
+ *
872
+ * Build it INSIDE the handler. The returned store closes over this `ctx`, so
873
+ * an agent constructed once at module scope and reused across invocations
874
+ * would commit through a context that is already finished, and would never
875
+ * re-hydrate (the controller memoizes the load for the life of the agent).
876
+ * Same rule as `restateSessionStore` / `restateProvider` / `restateClock` —
877
+ * but easier to get wrong here, because `toolState` looks like
878
+ * agent-lifetime configuration rather than a per-invocation binding.
879
+ *
880
+ * The map is a schema you own: one JSON object, no versioning, no migration.
881
+ * A value written by an earlier deploy is still there after you change its
882
+ * shape, so either read tolerantly or move to a fresh `key`.
883
+ *
884
+ * Enabling this adds a `ctx.get` at run start, which changes the journal
885
+ * shape for NEW invocations. Existing in-flight invocations replay against
886
+ * the old shape — drain them (or accept the failed attempts) before rolling
887
+ * it out.
888
+ */
889
+ declare function restateToolStateStore(ctx: RestateObjectContextLike, options?: RestateToolStateStoreOptions): ToolStateStore;
890
+ //#endregion
841
891
  //#region src/restate/wait-background.d.ts
842
892
  interface RestateWaitBackgroundOptions {
843
893
  /** The Restate context the awakeable + journal entries bind to. */
@@ -891,5 +941,5 @@ declare function restateWaitBackground(options: RestateWaitBackgroundOptions): (
891
941
  signal?: AbortSignal;
892
942
  }) => Promise<TaskExitInfo | null>;
893
943
  //#endregion
894
- export { type AwakeableWithTimeoutOptions, type ReplayDoneHooks, type ReplayTracker, type ReplayTrackerOptions, type RestateAwakeable, type RestateAwakeableToolOptions, type RestateClockOptions, type RestateContextLike, type RestateDurableStart, type RestateDurableWait, type RestateMcpToolWrapOptions, type RestateObjectContextLike, type RestatePromiseAllLike, type RestatePromiseLike, type RestatePromiseRaceLike, type RestateProviderOptions, type RestateRunOptions, type RestateSessionStoreOptions, type RestateToolBatchExecutorOptions, type RestateToolOptions, type RestateWaitBackgroundOptions, awakeableWithTimeout, createReplayTracker, deterministicUuid, replayAwareAbort, restateAwakeableTool, restateBehavior, restateClock, restateMcpToolWrap, restateProvider, restateSessionStore, restateTool, restateToolBatchExecutor, restateWaitBackground, shouldRethrowRestateControlError, wrapAgentTools };
944
+ export { type AwakeableWithTimeoutOptions, DEFAULT_TOOL_STATE_KEY, type ReplayDoneHooks, type ReplayTracker, type ReplayTrackerOptions, type RestateAwakeable, type RestateAwakeableToolOptions, type RestateClockOptions, type RestateContextLike, type RestateDurableStart, type RestateDurableWait, type RestateMcpToolWrapOptions, type RestateObjectContextLike, type RestatePromiseAllLike, type RestatePromiseLike, type RestatePromiseRaceLike, type RestateProviderOptions, type RestateRunOptions, type RestateSessionStoreOptions, type RestateToolBatchExecutorOptions, type RestateToolOptions, type RestateToolStateStoreOptions, type RestateWaitBackgroundOptions, awakeableWithTimeout, createReplayTracker, deterministicUuid, replayAwareAbort, restateAwakeableTool, restateBehavior, restateClock, restateMcpToolWrap, restateProvider, restateSessionStore, restateTool, restateToolBatchExecutor, restateToolStateStore, restateWaitBackground, shouldRethrowRestateControlError, wrapAgentTools };
895
945
  //# sourceMappingURL=restate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"restate.d.ts","names":[],"sources":["../src/restate/types.ts","../src/restate/awakeable.ts","../src/restate/awakeable-tool.ts","../src/restate/behavior.ts","../src/restate/clock.ts","../src/restate/errors.ts","../src/restate/replay.ts","../src/restate/mcp.ts","../src/restate/parallel.ts","../src/restate/provider.ts","../src/restate/session.ts","../src/restate/tool.ts","../src/restate/wait-background.ts"],"mappings":";;;;;;;;AAmBA;;;;;;;;;;;AAYO;AAUP;;UAtBiB,iBAAA;EAwBC;EAtBhB,gBAAA;EAqBA;EAnBA,gBAAA;EAoBS;EAlBT,oBAAA;EAkBkB;EAhBlB,gBAAA;EAuCe;EArCf,mBAAA;EAqCiC;EAnCjC,KAAA;AAAA;;;;;;;;UAUe,gBAAA;EACf,EAAA;EACA,OAAA,EAAS,OAAO,CAAC,CAAA;AAAA;;;;;;;;;;;;;;;;;;;;;UAuBF,kBAAA;EACf,GAAA,MACE,IAAA,UACA,EAAA,QAAU,OAAA,CAAQ,CAAA,IAAK,CAAA,EACvB,OAAA,GAAU,iBAAA,KACP,OAAA,CAAQ,CAAA;EACb,IAAA;IAAQ,GAAA,QAAW,OAAA;EAAA;EACnB,IAAA;IAAQ,MAAA;EAAA;EACR,SAAA,WAAoB,gBAAA,CAAiB,CAAA;EA0BP;;;;;;;;;;;;EAb9B,KAAA,GAAQ,MAAA,aAAmB,OAAA;AAAA;;;;;;AAcP;;UAJL,wBAAA,SAAiC,kBAAA;EAChD,GAAA;EACA,GAAA,MAAS,IAAA,aAAiB,OAAA,CAAQ,CAAA;EAClC,GAAA,MAAS,IAAA,UAAc,KAAA,EAAO,CAAA;EAC9B,KAAA,GAAQ,IAAA;AAAA;;;;;AAtEH;AAUP;;;;;UClBiB,sBAAA,kBAAwC,OAAA,YAAmB,OAA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AK,kBAAA,EACL,OAAA,GAAS,kBAAA,CAAmB,KAAA,EAAO,OAAA,IAClC,OAAA;AP5KiG;;;;ACnHpG;;;;ADmHoG,iBOkhBpF,cAAA,CACd,KAAA,EAAO,MAAA,SAAe,OAAA,GACtB,GAAA,EAAK,kBAAA,EACL,IAAA,GAAM,IAAA,CAAK,kBAAA;EAAwC,OAAA;AAAA,IAClD,MAAA,SAAe,OAAA;;;UCnmBD,4BAAA;EZ6BsB;EY3BrC,GAAA,EAAK,kBAAA;EZwCsB;;;;;;EYjC3B,KAAA,GAAQ,MAAA,EAAQ,eAAA,EAAiB,MAAA,aAAmB,OAAA,UAAiB,SAAA,eAAwB,SAAA;EZezE;;;;;;EYRpB,QAAA,GAAW,WAAA,UAAqB,MAAA,UAAgB,MAAA,EAAQ,eAAA,KAAoB,OAAA;EZW5E;;;;;EYLA,MAAA,IAAU,WAAA,UAAqB,MAAA,UAAgB,IAAA,EAAM,YAAA,SAAqB,MAAA,EAAQ,eAAA,KAAoB,OAAA;EZO1F;;;;;EYDZ,SAAA;EZckC;AAAA;AAUpC;;;EYlBE,QAAA,GAAW,sBAAA;EZoBe;EYlB1B,UAAA,GAAa,iBAAA;EZgBmC;EYdhD,WAAA;EZckE;EYZlE,aAAA,GAAgB,aAAA;AAAA;;;;;;iBAiDF,qBAAA,CACd,OAAA,EAAS,4BAAA,IACP,MAAA,EAAQ,eAAA,EAAiB,MAAA,UAAgB,IAAA;EAAS,SAAA;EAAoB,MAAA,GAAS,WAAA;AAAA,MAAkB,OAAA,CAAQ,YAAA"}
1
+ {"version":3,"file":"restate.d.ts","names":[],"sources":["../src/restate/types.ts","../src/restate/awakeable.ts","../src/restate/awakeable-tool.ts","../src/restate/behavior.ts","../src/restate/clock.ts","../src/restate/errors.ts","../src/restate/replay.ts","../src/restate/mcp.ts","../src/restate/parallel.ts","../src/restate/provider.ts","../src/restate/session.ts","../src/restate/tool.ts","../src/restate/tool-state.ts","../src/restate/wait-background.ts"],"mappings":";;;;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ZmCqB;AAUpC;;;;;;;;;;;;;;;;iBYVgB,qBAAA,CACd,GAAA,EAAK,wBAAA,EACL,OAAA,GAAS,4BAAA,GACR,cAAA;;;UC7Cc,4BAAA;Eb6BsB;Ea3BrC,GAAA,EAAK,kBAAA;EbwCsB;;;;;;EajC3B,KAAA,GAAQ,MAAA,EAAQ,eAAA,EAAiB,MAAA,aAAmB,OAAA,UAAiB,SAAA,eAAwB,SAAA;EbezE;;;;;;EaRpB,QAAA,GAAW,WAAA,UAAqB,MAAA,UAAgB,MAAA,EAAQ,eAAA,KAAoB,OAAA;EbW5E;;;;;EaLA,MAAA,IAAU,WAAA,UAAqB,MAAA,UAAgB,IAAA,EAAM,YAAA,SAAqB,MAAA,EAAQ,eAAA,KAAoB,OAAA;EbO1F;;;;;EaDZ,SAAA;EbckC;AAAA;AAUpC;;;EalBE,QAAA,GAAW,sBAAA;EboBe;EalB1B,UAAA,GAAa,iBAAA;EbgBmC;EadhD,WAAA;EbckE;EaZlE,aAAA,GAAgB,aAAA;AAAA;;;;;;iBAiDF,qBAAA,CACd,OAAA,EAAS,4BAAA,IACP,MAAA,EAAQ,eAAA,EAAiB,MAAA,UAAgB,IAAA;EAAS,SAAA;EAAoB,MAAA,GAAS,WAAA;AAAA,MAAkB,OAAA,CAAQ,YAAA"}
package/dist/restate.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as buildAliasMaps } from "./aliasing-lVFbm81n.js";
2
2
  import { r as coerceToolResultContent } from "./types-BIarq1qE.js";
3
- import { a as hydrateReadStateFromSessionAsync } from "./read-state-Dt7UbVsd.js";
3
+ import { i as stagedToolState, l as hydrateReadStateFromSessionAsync, r as isToolStateOps } from "./tool-state-DTs-3ZHH.js";
4
4
  import { createHash } from "node:crypto";
5
5
  //#region src/restate/awakeable.ts
6
6
  /**
@@ -318,26 +318,52 @@ function restateTool(inner, ctx, options = {}) {
318
318
  return ctx.run(nameFor(seq, canonicalName, input, toolCtx.callId), async () => {
319
319
  options.replayTracker?.markLive();
320
320
  await hydrateOnce(toolCtx);
321
+ const staged = stagedToolState(toolCtx.state);
322
+ staged?.clear();
321
323
  if (shellBackgroundDisabled && input.run_in_background === true) return SHELL_BACKGROUND_DISABLED_MESSAGE;
322
324
  if (!softErrors) {
323
325
  const out = await inner.execute(input, toolCtx);
324
- return coerceBlocks ? coerceToolResultContent(out) : out;
326
+ return attachToolState(coerceBlocks ? coerceToolResultContent(out) : out, staged);
325
327
  }
326
328
  try {
327
329
  const out = await inner.execute(input, toolCtx);
328
- return coerceBlocks ? coerceToolResultContent(out) : out;
330
+ return attachToolState(coerceBlocks ? coerceToolResultContent(out) : out, staged);
329
331
  } catch (err) {
330
332
  if (isRestateControlOrAbort(err, toolCtx.signal)) throw err;
331
- return makeSoftToolError(err);
333
+ return attachToolState(makeSoftToolError(err), staged);
332
334
  }
333
335
  }, runOpts);
334
336
  };
335
- const executeDurably = softErrors ? async (input, toolCtx) => rethrowSoftToolError(await runJournaled(input, toolCtx)) : runJournaled;
336
- const durableExecuteImpl = softErrors ? (input, toolCtx) => unwrapDurableSoftError(runJournaled(input, toolCtx)) : runJournaled;
337
- const executeTwoPhase = async (input, toolCtx) => {
337
+ const finishJournaled = async (journaled, staged) => {
338
+ let value;
339
+ try {
340
+ value = await journaled;
341
+ } catch (err) {
342
+ staged?.clear();
343
+ throw err;
344
+ }
345
+ const output = applyToolState(value, staged);
346
+ return softErrors ? rethrowSoftToolError(output) : output;
347
+ };
348
+ const executeDurably = (input, toolCtx) => {
349
+ const staged = stagedToolState(toolCtx.state);
350
+ if (!softErrors && !staged) return runJournaled(input, toolCtx);
351
+ return finishJournaled(runJournaled(input, toolCtx), staged);
352
+ };
353
+ const durableExecuteImpl = (input, toolCtx) => {
354
+ const staged = stagedToolState(toolCtx.state);
355
+ if (!softErrors && !staged) return runJournaled(input, toolCtx);
356
+ return unwrapDurableToolValue(runJournaled(input, toolCtx), staged, softErrors);
357
+ };
358
+ const executeTwoPhaseInner = async (input, toolCtx) => {
338
359
  const start = durableStart;
360
+ const staged = stagedToolState(toolCtx.state);
339
361
  seq += 1;
340
362
  const entry = nameFor(seq, canonicalName, input, toolCtx.callId);
363
+ const runFinal = async (body) => applyToolState(await ctx.run(entry, async () => {
364
+ options.replayTracker?.markLive();
365
+ return attachToolState(await body(), staged);
366
+ }, runOpts), staged);
341
367
  const token = await ctx.run(`${entry}-start`, async () => {
342
368
  options.replayTracker?.markLive();
343
369
  await hydrateOnce(toolCtx);
@@ -356,17 +382,11 @@ function restateTool(inner, ctx, options = {}) {
356
382
  const wait = start.wait;
357
383
  if (wait) {
358
384
  if (wait.inline?.(token, input, toolCtx)) {
359
- if (!onAbort || !signal) return await ctx.run(entry, () => {
360
- options.replayTracker?.markLive();
361
- return wait.result(token, null, input, toolCtx);
362
- }, runOpts);
385
+ if (!onAbort || !signal) return await runFinal(() => wait.result(token, null, input, toolCtx));
363
386
  if (signal.aborted) fireAbortCleanup();
364
387
  else signal.addEventListener("abort", fireAbortCleanup, { once: true });
365
388
  try {
366
- return await ctx.run(entry, () => {
367
- options.replayTracker?.markLive();
368
- return wait.result(token, null, input, toolCtx);
369
- }, runOpts);
389
+ return await runFinal(() => wait.result(token, null, input, toolCtx));
370
390
  } finally {
371
391
  signal.removeEventListener("abort", fireAbortCleanup);
372
392
  }
@@ -392,18 +412,12 @@ function restateTool(inner, ctx, options = {}) {
392
412
  }, runOpts);
393
413
  if (marker.awakeableId !== awakeable.id) throw new Error(`restateTool(${canonicalName}): journal drift — registration marker carries awakeable "${marker.awakeableId}" but this replay minted "${awakeable.id}". Refusing to park on an unreachable awakeable.`);
394
414
  const resumed = await parkWithSignal(awakeable.promise, signal, canonicalName);
395
- return await ctx.run(entry, () => {
396
- options.replayTracker?.markLive();
397
- return wait.result(token, resumed, input, toolCtx);
398
- }, runOpts);
415
+ return await runFinal(() => wait.result(token, resumed, input, toolCtx));
399
416
  } finally {
400
417
  signal?.removeEventListener("abort", fireAbortCleanup);
401
418
  }
402
419
  }
403
- const attach = () => ctx.run(entry, () => {
404
- options.replayTracker?.markLive();
405
- return start.attach(token, input, toolCtx);
406
- }, runOpts);
420
+ const attach = () => runFinal(() => start.attach(token, input, toolCtx));
407
421
  if (!onAbort || !signal) return attach();
408
422
  if (signal.aborted) {
409
423
  fireAbortCleanup();
@@ -416,6 +430,15 @@ function restateTool(inner, ctx, options = {}) {
416
430
  signal.removeEventListener("abort", fireAbortCleanup);
417
431
  }
418
432
  };
433
+ const executeTwoPhase = async (input, toolCtx) => {
434
+ const staged = stagedToolState(toolCtx.state);
435
+ try {
436
+ return await executeTwoPhaseInner(input, toolCtx);
437
+ } catch (err) {
438
+ staged?.clear();
439
+ throw err;
440
+ }
441
+ };
419
442
  if (durableStart) {
420
443
  const { durableExecute: _dropped, ...rest } = inner;
421
444
  return {
@@ -431,20 +454,59 @@ function restateTool(inner, ctx, options = {}) {
431
454
  durableExecute: durableExecuteImpl
432
455
  };
433
456
  }
457
+ function isToolStateEnvelope(value) {
458
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
459
+ const candidate = value;
460
+ return candidate.__zidaneToolState === 1 && Array.isArray(candidate.ops) && "output" in candidate;
461
+ }
462
+ /**
463
+ * Wrap the output with the staged ops so they cross the journal as DATA.
464
+ * Returns the output untouched when nothing was staged — the no-state path
465
+ * must not change the journaled shape.
466
+ */
467
+ function attachToolState(output, staged) {
468
+ const ops = staged?.pending() ?? [];
469
+ return ops.length === 0 ? output : {
470
+ __zidaneToolState: 1,
471
+ ops,
472
+ output
473
+ };
474
+ }
434
475
  /**
435
- * Compose the soft-error unwrap into the runtime's mappable durable promise.
436
- * A journaled sentinel becomes a thrown (rejected) value so the Restate batch
437
- * scheduler classifies it as a tool failure → `tool_result { isError }`; a real
438
- * action failure (control error) is rethrown verbatim. Non-mappable promises
439
- * (a ctx without the SDK's `RestatePromise`) pass through so the loop's durable
440
- * guard surfaces the "not a mappable durable promise" error instead.
476
+ * Inverse of {@link attachToolState}, run OUTSIDE the journal: re-seed the
477
+ * staging view from the journaled ops so the loop's commit writes the same
478
+ * thing on a live attempt and on every replay. A value with no envelope
479
+ * clears the view — whatever it holds was staged by an attempt no journal
480
+ * entry records, and committing that would be a write replay can't reproduce.
441
481
  */
442
- function unwrapDurableSoftError(promise) {
482
+ function applyToolState(value, staged) {
483
+ if (isToolStateEnvelope(value)) {
484
+ if (isToolStateOps(value.ops)) staged?.restore(value.ops);
485
+ else staged?.clear();
486
+ return value.output;
487
+ }
488
+ staged?.clear();
489
+ return value;
490
+ }
491
+ /**
492
+ * Compose the state unwrap + soft-error unwrap into the runtime's mappable
493
+ * durable promise. A journaled sentinel becomes a thrown (rejected) value so
494
+ * the Restate batch scheduler classifies it as a tool failure →
495
+ * `tool_result { isError }`; a real action failure (control error) is rethrown
496
+ * verbatim. Non-mappable promises (a ctx without the SDK's `RestatePromise`)
497
+ * pass through so the loop's durable guard surfaces the "not a mappable
498
+ * durable promise" error instead.
499
+ */
500
+ function unwrapDurableToolValue(promise, staged, softErrors) {
443
501
  const mappable = promise;
444
502
  if (typeof mappable.map !== "function") return promise;
445
503
  return mappable.map((value, failure) => {
446
- if (failure !== void 0) throw failure instanceof Error ? failure : new Error(String(failure));
447
- return rethrowSoftToolError(value);
504
+ if (failure !== void 0) {
505
+ staged?.clear();
506
+ throw failure instanceof Error ? failure : new Error(String(failure));
507
+ }
508
+ const output = applyToolState(value, staged);
509
+ return softErrors ? rethrowSoftToolError(output) : output;
448
510
  });
449
511
  }
450
512
  /**
@@ -903,6 +965,62 @@ function maxDefined(values) {
903
965
  return max;
904
966
  }
905
967
  //#endregion
968
+ //#region src/restate/tool-state.ts
969
+ /** Default virtual-object state key holding the tool-state map. */
970
+ const DEFAULT_TOOL_STATE_KEY = "zidane_tool_state";
971
+ /**
972
+ * Build a {@link ToolStateStore} over the bound virtual object's state.
973
+ *
974
+ * ```ts
975
+ * const agent = createAgent({
976
+ * provider,
977
+ * tools: wrapAgentTools({ shell }, ctx),
978
+ * session: createSession({ id: ctx.key, store: restateSessionStore(ctx) }),
979
+ * toolState: restateToolStateStore(ctx),
980
+ * })
981
+ * ```
982
+ *
983
+ * Single-writer like the session store: the state belongs to the object key,
984
+ * so bind one key per conversation and one agent per invocation.
985
+ *
986
+ * Build it INSIDE the handler. The returned store closes over this `ctx`, so
987
+ * an agent constructed once at module scope and reused across invocations
988
+ * would commit through a context that is already finished, and would never
989
+ * re-hydrate (the controller memoizes the load for the life of the agent).
990
+ * Same rule as `restateSessionStore` / `restateProvider` / `restateClock` —
991
+ * but easier to get wrong here, because `toolState` looks like
992
+ * agent-lifetime configuration rather than a per-invocation binding.
993
+ *
994
+ * The map is a schema you own: one JSON object, no versioning, no migration.
995
+ * A value written by an earlier deploy is still there after you change its
996
+ * shape, so either read tolerantly or move to a fresh `key`.
997
+ *
998
+ * Enabling this adds a `ctx.get` at run start, which changes the journal
999
+ * shape for NEW invocations. Existing in-flight invocations replay against
1000
+ * the old shape — drain them (or accept the failed attempts) before rolling
1001
+ * it out.
1002
+ */
1003
+ function restateToolStateStore(ctx, options = {}) {
1004
+ const key = options.key ?? "zidane_tool_state";
1005
+ const maxValueBytes = options.maxValueBytes;
1006
+ let cache;
1007
+ return {
1008
+ ...maxValueBytes !== void 0 ? { maxValueBytes } : {},
1009
+ load: async () => {
1010
+ cache = await ctx.get(key) ?? {};
1011
+ return { ...cache };
1012
+ },
1013
+ commit: (ops) => {
1014
+ if (ops.length === 0) return;
1015
+ const next = { ...cache ?? {} };
1016
+ for (const op of ops) if (op.delete === true) delete next[op.key];
1017
+ else next[op.key] = op.value;
1018
+ cache = next;
1019
+ ctx.set(key, next);
1020
+ }
1021
+ };
1022
+ }
1023
+ //#endregion
906
1024
  //#region src/restate/wait-background.ts
907
1025
  function entryToExit(entry) {
908
1026
  return {
@@ -981,6 +1099,6 @@ function restateWaitBackground(options) {
981
1099
  };
982
1100
  }
983
1101
  //#endregion
984
- export { awakeableWithTimeout, createReplayTracker, deterministicUuid, replayAwareAbort, restateAwakeableTool, restateBehavior, restateClock, restateMcpToolWrap, restateProvider, restateSessionStore, restateTool, restateToolBatchExecutor, restateWaitBackground, shouldRethrowRestateControlError, wrapAgentTools };
1102
+ export { DEFAULT_TOOL_STATE_KEY, awakeableWithTimeout, createReplayTracker, deterministicUuid, replayAwareAbort, restateAwakeableTool, restateBehavior, restateClock, restateMcpToolWrap, restateProvider, restateSessionStore, restateTool, restateToolBatchExecutor, restateToolStateStore, restateWaitBackground, shouldRethrowRestateControlError, wrapAgentTools };
985
1103
 
986
1104
  //# sourceMappingURL=restate.js.map