zidane 5.10.0 → 5.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{agent-AnumGPWj.d.ts → agent-Bt123Fdy.d.ts} +103 -3
  2. package/dist/agent-Bt123Fdy.d.ts.map +1 -0
  3. package/dist/chat/pure.d.ts +3 -3
  4. package/dist/chat/pure.js +1 -1
  5. package/dist/chat.d.ts +6 -6
  6. package/dist/chat.js +3 -3
  7. package/dist/contexts/docker.d.ts +1 -1
  8. package/dist/{contexts-CbI8dRfI.js → contexts-GKAWYq07.js} +113 -7
  9. package/dist/contexts-GKAWYq07.js.map +1 -0
  10. package/dist/contexts.d.ts +3 -3
  11. package/dist/contexts.js +2 -2
  12. package/dist/eval.d.ts +1 -1
  13. package/dist/eval.js +3 -3
  14. package/dist/{headless-D0qfvzG9.js → headless-Cn6XXmr3.js} +4 -4
  15. package/dist/{headless-D0qfvzG9.js.map → headless-Cn6XXmr3.js.map} +1 -1
  16. package/dist/headless.d.ts +1 -1
  17. package/dist/headless.js +1 -1
  18. package/dist/{index-B65HjjKZ.d.ts → index-4pQUnr2W.d.ts} +2 -2
  19. package/dist/{index-B65HjjKZ.d.ts.map → index-4pQUnr2W.d.ts.map} +1 -1
  20. package/dist/{index-DsvHiyYU.d.ts → index-BodGKXBV.d.ts} +3 -3
  21. package/dist/{index-DsvHiyYU.d.ts.map → index-BodGKXBV.d.ts.map} +1 -1
  22. package/dist/{index-LX8KCBXU.d.ts → index-C7BvI1Hi.d.ts} +14 -4
  23. package/dist/index-C7BvI1Hi.d.ts.map +1 -0
  24. package/dist/index.d.ts +6 -6
  25. package/dist/index.js +7 -7
  26. package/dist/{login-DocBwMVo.js → login-DoGslmKC.js} +2 -2
  27. package/dist/{login-DocBwMVo.js.map → login-DoGslmKC.js.map} +1 -1
  28. package/dist/{mcp-DzuTfq-I.js → mcp-BdN9UjTO.js} +32 -7
  29. package/dist/mcp-BdN9UjTO.js.map +1 -0
  30. package/dist/mcp.d.ts +1 -1
  31. package/dist/mcp.js +1 -1
  32. package/dist/output/stream-json.d.ts +2 -2
  33. package/dist/output/stream-json.js +1 -1
  34. package/dist/output/terminal.d.ts +2 -2
  35. package/dist/{presets-CTNbWXWz.js → presets-DCrQmY3b.js} +3 -2
  36. package/dist/presets-DCrQmY3b.js.map +1 -0
  37. package/dist/presets.d.ts +2 -2
  38. package/dist/presets.js +1 -1
  39. package/dist/providers.d.ts +1 -1
  40. package/dist/restate.d.ts +192 -16
  41. package/dist/restate.d.ts.map +1 -1
  42. package/dist/restate.js +133 -5
  43. package/dist/restate.js.map +1 -1
  44. package/dist/session/sqlite.d.ts +1 -1
  45. package/dist/session.d.ts +1 -1
  46. package/dist/skills.d.ts +2 -2
  47. package/dist/{tool-formatters-5nr1eXPn.d.ts → tool-formatters-BuB31L-c.d.ts} +2 -2
  48. package/dist/{tool-formatters-5nr1eXPn.d.ts.map → tool-formatters-BuB31L-c.d.ts.map} +1 -1
  49. package/dist/tools/fetch-url.d.ts +1 -1
  50. package/dist/tools/web-search.d.ts +1 -1
  51. package/dist/{tools-ycHDeHBZ.js → tools-Bk9TqmCV.js} +225 -18
  52. package/dist/tools-Bk9TqmCV.js.map +1 -0
  53. package/dist/tools.d.ts +3 -3
  54. package/dist/tools.js +2 -2
  55. package/dist/{transcript-anchors-D6Sw-Gzk.js → transcript-anchors-Bkuspqgn.js} +5 -5
  56. package/dist/{transcript-anchors-D6Sw-Gzk.js.map → transcript-anchors-Bkuspqgn.js.map} +1 -1
  57. package/dist/{transcript-anchors-DezrH1sp.d.ts → transcript-anchors-DhVgKmEl.d.ts} +4 -4
  58. package/dist/{transcript-anchors-DezrH1sp.d.ts.map → transcript-anchors-DhVgKmEl.d.ts.map} +1 -1
  59. package/dist/tui.d.ts +3 -3
  60. package/dist/tui.js +7 -7
  61. package/dist/{turn-operations-C70p-7Nn.js → turn-operations-DLWN2J7f.js} +13 -1
  62. package/dist/{turn-operations-C70p-7Nn.js.map → turn-operations-DLWN2J7f.js.map} +1 -1
  63. package/dist/{turn-operations-CICEEhrU.d.ts → turn-operations-DYKtoVd9.d.ts} +3 -3
  64. package/dist/{turn-operations-CICEEhrU.d.ts.map → turn-operations-DYKtoVd9.d.ts.map} +1 -1
  65. package/dist/{types-CRf_uTpK.d.ts → types-BMwiYRIJ.d.ts} +100 -6
  66. package/dist/types-BMwiYRIJ.d.ts.map +1 -0
  67. package/dist/types-BiobHM1D.js.map +1 -1
  68. package/dist/types.d.ts +5 -5
  69. package/docs/RESTATE.md +79 -5
  70. package/docs/RUN_IN_BACKGROUND.md +10 -1
  71. package/docs/SKILL.md +11 -4
  72. package/package.json +1 -1
  73. package/dist/agent-AnumGPWj.d.ts.map +0 -1
  74. package/dist/contexts-CbI8dRfI.js.map +0 -1
  75. package/dist/index-LX8KCBXU.d.ts.map +0 -1
  76. package/dist/mcp-DzuTfq-I.js.map +0 -1
  77. package/dist/presets-CTNbWXWz.js.map +0 -1
  78. package/dist/tools-ycHDeHBZ.js.map +0 -1
  79. package/dist/types-CRf_uTpK.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"restate.js","names":[],"sources":["../src/restate/errors.ts","../src/restate/behavior.ts","../src/restate/clock.ts","../src/restate/parallel.ts","../src/restate/provider.ts","../src/restate/session.ts","../src/restate/tool.ts"],"sourcesContent":["/**\n * Restate control-flow errors must escape the agent loop. If they are turned\n * into model-visible tool results, the runtime can retry/suspend incorrectly.\n *\n * Kept structural so `zidane/restate` does not need to import the SDK at\n * runtime just to recognize the common error shapes.\n */\nexport function shouldRethrowRestateControlError(error: unknown): boolean {\n if (!(error instanceof Error))\n return false\n\n const codeValue = Reflect.get(error, 'code')\n const code = typeof codeValue === 'number'\n ? codeValue\n : undefined\n if (code === 599)\n return true\n\n const name = error.name\n if (\n name === 'TerminalError'\n || name === 'TimeoutError'\n || name === 'CancelledError'\n || name === 'SuspendedError'\n ) {\n return true\n }\n\n const ctorName = error.constructor?.name\n const serializedCtorNameValue = Reflect.get(error, 'constructorName')\n const serializedCtorName = typeof serializedCtorNameValue === 'string'\n ? serializedCtorNameValue\n : undefined\n if (\n ctorName === 'TerminalError'\n || ctorName === 'TimeoutError'\n || ctorName === 'CancelledError'\n || ctorName === 'SuspendedError'\n || serializedCtorName === 'TerminalError'\n || serializedCtorName === 'TimeoutError'\n || serializedCtorName === 'CancelledError'\n || serializedCtorName === 'SuspendedError'\n ) {\n return true\n }\n\n return typeof name === 'string' && name.toLowerCase().includes('suspend')\n}\n","import type { AgentBehavior } from '../types'\nimport { shouldRethrowRestateControlError } from './errors'\n\n/**\n * Conservative behavior defaults for agents running inside Restate.\n *\n * The helper is opt-in and returns a plain AgentBehavior object, so callers can\n * spread or override it without changing non-Restate harness defaults.\n */\nexport function restateBehavior(overrides: AgentBehavior = {}): AgentBehavior {\n return {\n maxConcurrentTools: 1,\n disableBackgroundTasks: true,\n cache: true,\n shouldRethrowToolError: shouldRethrowRestateControlError,\n ...overrides,\n }\n}\n","/**\n * Restate-backed {@link AgentClock} — journals `now()` + `randomUUID()` so\n * `SessionTurn.createdAt`, `runId`, and fallback / synthetic turn ids stay\n * byte-identical across replays of the same invocation.\n *\n * Pass to `agent.run({ clock: restateClock(ctx) })` or bake it into\n * `createAgent({ clock: restateClock(ctx) })` for the duration of a\n * handler invocation. The clock holds a reference to `ctx`; do not reuse\n * a clock instance across invocations.\n */\n\nimport type { AgentClock } from '../types'\nimport type { RestateContextLike } from './types'\n\n/**\n * Wrap a Restate context's `date.now()` + `rand.uuidv4()` into the\n * {@link AgentClock} shape Zidane consumes for journaled metadata.\n *\n * The returned clock is a thin live view onto `ctx` — each call hits\n * the SDK afresh. No caching, no closure-captured values. Restate's\n * journal handles determinism on its end.\n */\nexport function restateClock(ctx: RestateContextLike): AgentClock {\n return {\n now: () => ctx.date.now(),\n randomUUID: () => ctx.rand.uuidv4(),\n }\n}\n","import type { ToolResult } from '../providers'\nimport type { ToolBatchExecutionContext, ToolBatchExecutor } from '../types'\n\nexport interface RestatePromiseAllLike<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>> {\n all: (values: readonly TPromise[]) => Promise<readonly unknown[]>\n}\n\nexport type RestatePromiseLike<T> = Promise<T> & {\n map: <U>(mapper: (value?: T, failure?: unknown) => U) => Promise<U>\n}\n\nexport interface RestateToolBatchExecutorOptions<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>> {\n /**\n * Wait for a safe fleet through Restate's durable combinator. Pass\n * `RestatePromise` from `@restatedev/restate-sdk` in real deployments.\n */\n promises: RestatePromiseAllLike<TPromise>\n}\n\n/**\n * Tool batch scheduler for Restate-backed agents.\n *\n * It preserves unsafe-tool barriers and emits results in model submission\n * order. Safe fleets are started in submission order, capped by\n * `maxConcurrentTools`, and joined via the supplied durable `all()`.\n */\nexport function restateToolBatchExecutor<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>>(\n options: RestateToolBatchExecutorOptions<TPromise>,\n): ToolBatchExecutor {\n return async (ctx: ToolBatchExecutionContext): Promise<ToolResult[]> => {\n const results: ToolResult[] = []\n const { toolCalls } = ctx\n\n const fillRemaining = (from: number, factory: (index: number) => ToolResult): ToolResult[] => {\n for (let i = from; i < toolCalls.length; i++)\n results[i] = factory(i)\n return results\n }\n\n for (let i = 0; i < toolCalls.length;) {\n if (ctx.signal.aborted)\n return fillRemaining(i, ctx.interruptedResult)\n if (ctx.steeringQueue.length > 0)\n return fillRemaining(i, ctx.skippedResult)\n\n if (!ctx.isConcurrencySafe(i)) {\n results[i] = await ctx.execute(i)\n i += 1\n continue\n }\n\n const start = i\n const fleet: number[] = []\n while (\n i < toolCalls.length\n && ctx.isConcurrencySafe(i)\n && fleet.length < ctx.maxConcurrentTools\n ) {\n fleet.push(i)\n i += 1\n }\n\n const fleetResults = fleet.every(index => ctx.canExecuteDurably(index))\n ? await ctx.executeDurable(\n fleet,\n async <T>(values: readonly Promise<T>[]): Promise<readonly T[]> => {\n const results = await options.promises.all(values as readonly TPromise[])\n return results as readonly T[]\n },\n )\n : await executeSequential(ctx, fleet)\n for (let offset = 0; offset < fleetResults.length; offset++)\n results[start + offset] = fleetResults[offset]\n }\n\n return results\n }\n}\n\nasync function executeSequential(\n ctx: ToolBatchExecutionContext,\n indices: readonly number[],\n): Promise<ToolResult[]> {\n const results: ToolResult[] = []\n for (const index of indices) {\n if (ctx.signal.aborted) {\n results.push(ctx.interruptedResult(index))\n continue\n }\n if (ctx.steeringQueue.length > 0) {\n results.push(ctx.skippedResult(index))\n continue\n }\n results.push(await ctx.execute(index))\n }\n return results\n}\n","/**\n * Restate-backed Provider wrapper.\n *\n * Wraps `Provider.stream` so every assistant turn (the LLM call as a\n * whole) is journaled. The model is invoked once per turn — the live\n * stream still fires `onText` / `onThinking` callbacks for UX during the\n * original execution. On replay, `ctx.run` returns the journaled\n * `TurnResult` immediately and the inner provider is NEVER re-invoked →\n * no duplicate billed tokens, no duplicate stream chunks.\n *\n * Replay caveat: stream callbacks don't re-fire on replay. Consumers\n * that paint live UI from `stream:text` should reconstruct transcripts\n * from `session.turns` via `eventsFromTurns` (zidane/chat) instead of\n * relying on hook re-emission. The chat layer already does this.\n *\n * Journal-entry naming: a monotonic per-wrapper counter (`llm-call-1`,\n * `llm-call-2`, …). One wrapper instance per Restate handler invocation\n * resets the counter; Restate's journal is invocation-scoped so names\n * don't need to be globally unique. The counter ticks the same way on\n * replay because the wrapper is constructed fresh each attempt.\n */\n\nimport type { Provider, StreamCallbacks, StreamOptions, TurnResult } from '../providers'\nimport type { RestateContextLike, RestateRunOptions } from './types'\n\nexport interface RestateProviderOptions {\n /**\n * `ctx.run` options forwarded on every wrapped stream call.\n *\n * Default depends on {@link streamCallbacks}:\n *\n * - `'suppress'` → `{ maxRetryAttempts: 3 }` — provider transients\n * (rate limits, 5xx, connection resets) get retried inside the\n * journal entry; nothing streams to the host, so a retry is\n * invisible.\n * - `'live'` (the default) → `{ maxRetryAttempts: 1 }`. A live stream\n * that fails AFTER emitting deltas would be re-run inside the same\n * journal entry, re-firing `onText` into the loop's accumulating\n * text buffer and producing duplicated partial1+full2 output. The\n * loop's own retry (which only re-issues on a clean slate) is the\n * correct retry layer in live mode.\n *\n * Once the cap is reached the failure becomes terminal and surfaces\n * through the loop's normal `AgentProviderError` path. Set this\n * explicitly to override either default — but with live callbacks,\n * `maxRetryAttempts > 1` re-introduces the duplicate-delta hazard.\n */\n runOptions?: RestateRunOptions\n /**\n * Override the journal-entry name. Receives the 1-indexed sequence\n * number for this wrapper instance and the `StreamOptions` of the\n * call. Default: `llm-call-<n>`. Override to inject extra structure\n * (e.g. `${agentName}/llm-call-${n}`) when multiple agents share a\n * service.\n */\n entryName?: (seq: number, opts: StreamOptions) => string\n /**\n * Whether live stream callbacks should fire during the original execution.\n * Use `'suppress'` for strict durable mode: the model call still returns a\n * full TurnResult, and UIs reconstruct from persisted session turns.\n *\n * Default: `'live'`.\n */\n streamCallbacks?: 'live' | 'suppress'\n}\n\n/**\n * Wrap a Zidane `Provider` so its `stream()` method journals each turn's\n * response inside `ctx.run`. All other Provider methods (`formatTools`,\n * `userMessage`, `toolResultsMessage`, `classifyError`, …) pass through\n * unchanged — they're pure functions over already-deterministic inputs.\n */\nexport function restateProvider(\n inner: Provider,\n ctx: RestateContextLike,\n options: RestateProviderOptions = {},\n): Provider {\n // Live callbacks must not retry inside the journal entry — a stream that\n // fails after emitting deltas would re-fire `onText` on the retry and\n // duplicate text in the loop's accumulator. See the `runOptions` doc.\n const runOpts: RestateRunOptions = options.runOptions\n ?? (options.streamCallbacks === 'suppress' ? { maxRetryAttempts: 3 } : { maxRetryAttempts: 1 })\n const nameFor = options.entryName ?? ((seq: number) => `llm-call-${seq}`)\n let seq = 0\n\n return {\n ...inner,\n stream(streamOpts: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n seq += 1\n const durableCallbacks = options.streamCallbacks === 'suppress'\n ? suppressStreamingCallbacks(callbacks)\n : callbacks\n return ctx.run<TurnResult>(\n nameFor(seq, streamOpts),\n () => inner.stream(streamOpts, durableCallbacks),\n runOpts,\n )\n },\n }\n}\n\nfunction suppressStreamingCallbacks(callbacks: StreamCallbacks): StreamCallbacks {\n return {\n ...callbacks,\n onText: () => {},\n onThinking: undefined,\n onServerToolUse: undefined,\n onServerToolResult: undefined,\n }\n}\n","/**\n * Restate-backed `SessionStore` — turn / run state lives in the bound\n * virtual object's K/V state instead of SQLite / file / remote HTTP.\n *\n * Trade-offs vs. journal-only replay\n * ----------------------------------\n * If you only care about durable execution within ONE invocation,\n * skip this — the journaled `ctx.run` entries (LLM calls, tool\n * executions) are enough to replay the loop to byte-identical state\n * after a crash. The in-memory `createMemoryStore()` is the right\n * choice; turns rematerialize from the journal each replay.\n *\n * Pick this store when EXTERNAL consumers (TUI, web GUI, support\n * tooling) need to read a session's history WITHOUT re-entering the\n * agent handler. Virtual-object state is exposed via the SDK's read\n * APIs (`ctx.get` from another handler, `restate-cli`, the Restate\n * web UI) — same data, different access path. The journal is\n * invocation-local; this state is the externally-visible projection\n * of it.\n *\n * Storage layout\n * --------------\n * One virtual-object key per session, three K/V slots:\n *\n * `session-data` → `SessionData` minus the `turns` array (small header)\n * `session-turns` → `SessionTurn[]` (the conversation history)\n * `session-runs` → `SessionRun[]` (run lifecycle records)\n *\n * Splitting `turns` / `runs` out keeps the header light for `load()` —\n * a handler that only needs metadata doesn't pull the full history.\n *\n * Listing / discovery\n * -------------------\n * `list()` returns `[]` because virtual objects don't expose cross-key\n * enumeration. `delete()` clears the current object's session keys only.\n * Use a separate index handler if you need discovery (one virtual object\n * per `projectRoot` that maintains an indexed list of session ids; this\n * store doesn't own that concern).\n * `generateSessionId` is omitted so the agent falls back to its\n * default UUID generator — for a session bound 1:1 to a virtual-\n * object key, pass `id: ctx.key` to `createSession()` instead and\n * skip ID generation entirely.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '../session'\nimport type { SessionTurn } from '../types'\nimport type { RestateObjectContextLike } from './types'\n\nconst KEY_DATA = 'session-data'\nconst KEY_TURNS = 'session-turns'\nconst KEY_RUNS = 'session-runs'\n\n/**\n * Construct a `SessionStore` backed by the bound virtual-object's K/V\n * state. The store is single-tenant — every method ignores the\n * `sessionId` argument because the virtual object is already keyed by\n * `ctx.key`. Calling `appendTurns('other-id', …)` writes to the\n * CURRENT object's state, not the one named in the argument. Bind one\n * virtual-object key per session and the contract holds.\n */\nexport function restateSessionStore(ctx: RestateObjectContextLike): SessionStore {\n let nextTurnSeq: number | undefined\n\n async function generateTurnId(): Promise<string> {\n if (nextTurnSeq === undefined) {\n const existing = (await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? []\n nextTurnSeq = existing.length\n }\n nextTurnSeq += 1\n return `turn_${nextTurnSeq}`\n }\n\n return {\n /**\n * Turn ids are deterministic from the persisted turn count. Random ids\n * are replay-stable only when the whole handler replays from the same\n * point; restarting from an arbitrary journal step can shift the RNG\n * sequence before a state write.\n */\n generateTurnId,\n\n async load(_sessionId: string): Promise<SessionData | null> {\n const header = await ctx.get<Omit<SessionData, 'turns' | 'runs'>>(KEY_DATA)\n const turns = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n const runs = sanitizeRunsForState((await ctx.get<SessionRun[]>(KEY_RUNS)) ?? [])\n if (!header) {\n if (turns.length === 0 && runs.length === 0)\n return null\n return {\n id: _sessionId,\n turns,\n runs,\n status: inferStatus(runs),\n metadata: {},\n createdAt: inferCreatedAt(turns, runs),\n updatedAt: inferUpdatedAt(turns, runs),\n }\n }\n return { ...header, turns, runs }\n },\n\n async save(session: SessionData): Promise<void> {\n const { turns, runs, ...header } = session\n ctx.set(KEY_DATA, header)\n ctx.set(KEY_TURNS, sanitizeTurnsForState(turns))\n ctx.set(KEY_RUNS, sanitizeRunsForState(runs))\n },\n\n async delete(_sessionId: string): Promise<void> {\n ctx.clear(KEY_DATA)\n ctx.clear(KEY_TURNS)\n ctx.clear(KEY_RUNS)\n },\n\n /**\n * Always empty — virtual objects don't support cross-key\n * enumeration. Maintain a separate index handler if discovery\n * matters.\n */\n async list(): Promise<string[]> {\n return []\n },\n\n async appendTurns(_sessionId: string, turns: SessionTurn[]): Promise<void> {\n const existing = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n ctx.set(KEY_TURNS, [...existing, ...sanitizeTurnsForState(turns)])\n },\n\n async getTurns(_sessionId: string, from = 0, limit?: number): Promise<SessionTurn[]> {\n const turns = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n return turns.slice(from, limit !== undefined ? from + limit : undefined)\n },\n\n async updateRun(_sessionId: string, run: SessionRun): Promise<void> {\n const runs = sanitizeRunsForState((await ctx.get<SessionRun[]>(KEY_RUNS)) ?? [])\n const idx = runs.findIndex(r => r.id === run.id)\n const next = [...runs]\n if (idx >= 0)\n next[idx] = sanitizeRunForState(run)\n else\n next.push(sanitizeRunForState(run))\n ctx.set(KEY_RUNS, next)\n },\n\n async updateStatus(_sessionId: string, status: SessionData['status']): Promise<void> {\n const header = await ctx.get<Omit<SessionData, 'turns' | 'runs'>>(KEY_DATA)\n const now = await ctx.date.now()\n if (header) {\n ctx.set(KEY_DATA, { ...header, status, updatedAt: now })\n }\n else {\n ctx.set(KEY_DATA, {\n id: _sessionId,\n status,\n metadata: {},\n createdAt: now,\n updatedAt: now,\n })\n }\n },\n }\n}\n\nfunction sanitizeTurnsForState(turns: readonly SessionTurn[]): SessionTurn[] {\n return turns.map(sanitizeTurnForState)\n}\n\nfunction sanitizeTurnForState(turn: SessionTurn): SessionTurn {\n if (!turn.usage || turn.usage.timeToFirstTokenMs === undefined)\n return turn\n\n const { timeToFirstTokenMs: _timeToFirstTokenMs, ...usage } = turn.usage\n return { ...turn, usage }\n}\n\nfunction sanitizeRunsForState(runs: readonly SessionRun[]): SessionRun[] {\n return runs.map(sanitizeRunForState)\n}\n\nfunction sanitizeRunForState(run: SessionRun): SessionRun {\n if (!run.turnUsage?.some(usage => usage.timeToFirstTokenMs !== undefined))\n return run\n\n return {\n ...run,\n turnUsage: run.turnUsage.map((usage) => {\n if (usage.timeToFirstTokenMs === undefined)\n return usage\n const { timeToFirstTokenMs: _timeToFirstTokenMs, ...stableUsage } = usage\n return stableUsage\n }),\n }\n}\n\nfunction inferStatus(runs: readonly SessionRun[]): SessionData['status'] {\n if (runs.some(run => run.status === 'running'))\n return 'running'\n if (runs.some(run => run.status === 'error'))\n return 'error'\n if (runs.some(run => run.status === 'completed'))\n return 'completed'\n return 'idle'\n}\n\nfunction inferCreatedAt(turns: readonly SessionTurn[], runs: readonly SessionRun[]): number {\n return minDefined([\n ...turns.map(turn => turn.createdAt),\n ...runs.map(run => run.startedAt),\n ]) ?? 0\n}\n\nfunction inferUpdatedAt(turns: readonly SessionTurn[], runs: readonly SessionRun[]): number {\n return maxDefined([\n ...turns.map(turn => turn.createdAt),\n ...runs.map(run => run.endedAt ?? run.startedAt),\n ]) ?? inferCreatedAt(turns, runs)\n}\n\nfunction minDefined(values: readonly number[]): number | undefined {\n let min: number | undefined\n for (const value of values) {\n if (min === undefined || value < min)\n min = value\n }\n return min\n}\n\nfunction maxDefined(values: readonly number[]): number | undefined {\n let max: number | undefined\n for (const value of values) {\n if (max === undefined || value > max)\n max = value\n }\n return max\n}\n","/**\n * Restate-backed tool wrappers.\n *\n * Wraps `ToolDef.execute` so every tool invocation is journaled. The\n * tool body runs on the original execution; after Restate persists the\n * journal entry, replay returns the recorded result without re-executing.\n * If the process dies before the entry is durable, the latest in-flight\n * tool can run again, so non-idempotent tools still need idempotency keys.\n *\n * `tool:gate`, `tool:transform`, `tool:after` hooks fire OUTSIDE the\n * journaled boundary, so they re-execute on replay. Built-in handlers\n * are deterministic given the journaled input + output (truncation,\n * image-stripping, `<edit-outcomes>` merge — all pure). Consumer hooks\n * that hit external services should themselves wrap side effects in\n * `ctx.run` so the substitution / annotation is replay-stable.\n *\n * `isConcurrencySafe` is preserved — Restate's per-key serialization\n * doesn't preclude in-handler parallelism. The loop's scheduler still\n * fans out safe tools up to `behavior.maxConcurrentTools`, each call\n * lands in its own journal entry. Order-of-journal-completion does NOT\n * affect replay correctness: Restate journals by call-site name, not\n * by completion order.\n */\n\nimport type { Session } from '../session'\nimport type { ToolDef } from '../tools/types'\nimport type { RestateContextLike, RestateRunOptions } from './types'\nimport { hydrateReadStateFromSessionAsync } from '../tools/read-state'\n\nexport interface RestateToolOptions {\n /**\n * `ctx.run` options forwarded on every wrapped tool call. Defaults to\n * `{ maxRetryAttempts: 1 }` — tool errors are typically deterministic\n * (validation failures, missing files) so blind retries waste budget.\n * Override per-tool for network-heavy custom tools that benefit from\n * SDK-level retries.\n */\n runOptions?: RestateRunOptions\n /**\n * Override the journal-entry name. Receives the canonical tool name\n * and the call's input. Default: `tool-<name>-<seq>` where `<seq>` is\n * a per-wrapper monotonic counter. Override to inject the model's\n * `callId` (read it off `ToolContext.callId` inside `execute` if you\n * need an LLM-visible key — but the default counter is sufficient\n * for journal correctness).\n */\n entryName?: (seq: number, name: string, input: Record<string, unknown>) => string\n /**\n * Hide and reject the built-in shell tool's background mode. Defaults to\n * `true` because Restate cannot recover host-local background processes.\n */\n disableShellBackground?: boolean\n}\n\nconst SHELL_BACKGROUND_DISABLED_MESSAGE = 'shell error: background mode is disabled for Restate-backed agents. Fall back to foreground (drop `run_in_background`).'\nconst HYDRATED_READ_STATE_SESSIONS = new WeakSet<Session>()\n\n/**\n * Wrap a single `ToolDef` so its `execute` runs inside `ctx.run`. The\n * tool's `spec` and `isConcurrencySafe` pass through unchanged.\n */\nexport function restateTool(\n inner: ToolDef,\n ctx: RestateContextLike,\n options: RestateToolOptions = {},\n): ToolDef {\n const runOpts: RestateRunOptions = options.runOptions ?? { maxRetryAttempts: 1 }\n const nameFor = options.entryName ?? ((seq: number, name: string) => `tool-${name}-${seq}`)\n const canonicalName = inner.spec.name\n const disableShellBackground = options.disableShellBackground ?? true\n const shellBackgroundDisabled = disableShellBackground && canonicalName === 'shell'\n let seq = 0\n const hydrateOnce = async (toolCtx: Parameters<ToolDef['execute']>[1]) => {\n if (toolCtx.session && !HYDRATED_READ_STATE_SESSIONS.has(toolCtx.session)) {\n HYDRATED_READ_STATE_SESSIONS.add(toolCtx.session)\n await hydrateReadStateFromSessionAsync(toolCtx.session, toolCtx.handle.cwd, {\n defaultLineNumbers: toolCtx.behavior?.readLineNumbers ?? true,\n readFileForHash: async (path) => {\n try {\n return await toolCtx.execution.readFile(toolCtx.handle, path)\n }\n catch {\n return null\n }\n },\n })\n }\n }\n const executeDurably = (input: Record<string, unknown>, toolCtx: Parameters<ToolDef['execute']>[1]) => {\n seq += 1\n return ctx.run(\n nameFor(seq, canonicalName, input),\n async () => {\n await hydrateOnce(toolCtx)\n if (shellBackgroundDisabled && input.run_in_background === true)\n return SHELL_BACKGROUND_DISABLED_MESSAGE\n return inner.execute(input, toolCtx)\n },\n runOpts,\n )\n }\n\n return {\n ...inner,\n spec: shellBackgroundDisabled ? withoutShellBackgroundInput(inner.spec) : inner.spec,\n execute: executeDurably,\n durableExecute: executeDurably,\n }\n}\n\nfunction withoutShellBackgroundInput(spec: ToolDef['spec']): ToolDef['spec'] {\n const inputSchema = spec.inputSchema\n const properties = isRecord(inputSchema.properties) ? inputSchema.properties : undefined\n if (!properties || !Object.hasOwn(properties, 'run_in_background'))\n return spec\n\n const { run_in_background: _runInBackground, ...nextProperties } = properties\n const required = Array.isArray(inputSchema.required)\n ? inputSchema.required.filter(name => name !== 'run_in_background')\n : inputSchema.required\n return {\n ...spec,\n description: stripShellBackgroundDescription(spec.description),\n inputSchema: {\n ...inputSchema,\n properties: nextProperties,\n ...(required !== inputSchema.required ? { required } : {}),\n },\n }\n}\n\nfunction stripShellBackgroundDescription(description: string): string {\n return description\n .split('\\n')\n .filter(line =>\n !line.includes('run_in_background')\n && !line.includes('<task-notification>')\n && !line.includes('background task'),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Wrap an entire tool map at once — convenience for the common case of\n * \"journal every tool the agent has\". Pass-through for tools whose\n * names are listed in `opts.exclude` (e.g. fully-deterministic local\n * helpers where journaling is pure overhead).\n *\n * The returned map is a fresh object; the input is untouched.\n */\nexport function wrapAgentTools(\n tools: Record<string, ToolDef>,\n ctx: RestateContextLike,\n opts: RestateToolOptions & { exclude?: readonly string[] } = {},\n): Record<string, ToolDef> {\n const excludeSet = new Set(opts.exclude ?? [])\n const wrapped: Record<string, ToolDef> = {}\n for (const [name, def] of Object.entries(tools)) {\n wrapped[name] = excludeSet.has(name) ? def : restateTool(def, ctx, opts)\n }\n return wrapped\n}\n"],"mappings":";;;;;;;;;AAOA,SAAgB,iCAAiC,OAAyB;CACxE,IAAI,EAAE,iBAAiB,QACrB,OAAO;CAET,MAAM,YAAY,QAAQ,IAAI,OAAO,MAAM;CAI3C,KAHa,OAAO,cAAc,WAC9B,YACA,KAAA,OACS,KACX,OAAO;CAET,MAAM,OAAO,MAAM;CACnB,IACE,SAAS,mBACN,SAAS,kBACT,SAAS,oBACT,SAAS,kBAEZ,OAAO;CAGT,MAAM,WAAW,MAAM,aAAa;CACpC,MAAM,0BAA0B,QAAQ,IAAI,OAAO,iBAAiB;CACpE,MAAM,qBAAqB,OAAO,4BAA4B,WAC1D,0BACA,KAAA;CACJ,IACE,aAAa,mBACV,aAAa,kBACb,aAAa,oBACb,aAAa,oBACb,uBAAuB,mBACvB,uBAAuB,kBACvB,uBAAuB,oBACvB,uBAAuB,kBAE1B,OAAO;CAGT,OAAO,OAAO,SAAS,YAAY,KAAK,YAAY,EAAE,SAAS,SAAS;AAC1E;;;;;;;;;ACtCA,SAAgB,gBAAgB,YAA2B,CAAC,GAAkB;CAC5E,OAAO;EACL,oBAAoB;EACpB,wBAAwB;EACxB,OAAO;EACP,wBAAwB;EACxB,GAAG;CACL;AACF;;;;;;;;;;;ACKA,SAAgB,aAAa,KAAqC;CAChE,OAAO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C,MAAM,QAAQ,KAAK;AAC5E;;;;;;;;;AAUA,SAAgB,eACd,OACA,KACA,OAA6D,CAAC,GACrC;CACzB,MAAM,aAAa,IAAI,IAAI,KAAK,WAAW,CAAC,CAAC;CAC7C,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,GAC5C,QAAQ,QAAQ,WAAW,IAAI,IAAI,IAAI,MAAM,YAAY,KAAK,KAAK,IAAI;CAEzE,OAAO;AACT"}
1
+ {"version":3,"file":"restate.js","names":[],"sources":["../src/restate/awakeable.ts","../src/restate/awakeable-tool.ts","../src/restate/errors.ts","../src/restate/behavior.ts","../src/restate/clock.ts","../src/restate/parallel.ts","../src/restate/provider.ts","../src/restate/session.ts","../src/restate/tool.ts"],"sourcesContent":["/**\n * Awakeable helpers — durable waits with deadlines.\n *\n * `awakeableWithTimeout` packages the canonical \"park until a resumer\n * fires, but not forever\" shape: an awakeable raced against a durable\n * `ctx.sleep(timeoutMs)` timer. The race itself survives process death —\n * on replay both branches resume from the journal and the same side\n * wins. This is the three-line building block for\n * `ExecutionContext.waitBackground` implementations on durable hosts\n * (runner fires task-exit → `resolveAwakeable(id, info)`; the timeout\n * branch maps to the seam's `null` return).\n */\n\nimport type { RestateAwakeable, RestateContextLike } from './types'\n\n/**\n * Structural subset of the SDK's `RestatePromise` static surface used by\n * {@link awakeableWithTimeout} — mirrors `RestatePromiseAllLike` from\n * `./parallel`. Pass `RestatePromise` from `@restatedev/restate-sdk` so\n * the race goes through the journaled combinator; native `Promise.race`\n * over two durable promises leaves the winner to the runtime's replay\n * ordering instead of an explicit journal entry.\n */\nexport interface RestatePromiseRaceLike<TPromise extends Promise<unknown> = Promise<unknown>> {\n race: (values: readonly TPromise[]) => Promise<unknown>\n}\n\nexport interface AwakeableWithTimeoutOptions<TPromise extends Promise<unknown> = Promise<unknown>> {\n /**\n * Durable deadline in milliseconds. Unset / non-positive = no timeout\n * (the returned awakeable is the plain `ctx.awakeable()` passthrough).\n */\n timeoutMs?: number\n /**\n * Durable race combinator — pass `RestatePromise` from the SDK. When\n * omitted, native `Promise.race` is used: correct at runtime and\n * replay-safe for THIS pattern (both branches are journaled\n * primitives), but the SDK combinator is the recommended belt-and-\n * braces choice for deterministic replay.\n */\n promises?: RestatePromiseRaceLike<TPromise>\n}\n\n/**\n * Mint an awakeable that resolves with the resumer's payload, or `null`\n * when `timeoutMs` elapses first. The id is journal-stable (send it\n * out-of-band as usual); the timeout is a durable `ctx.sleep`, so a\n * parked invocation suspends instead of holding a worker.\n *\n * Timeout surfaces as `null` — a resumer that resolves `undefined` is\n * indistinguishable from a timeout, so resolve a concrete payload.\n *\n * ```ts\n * // waitBackground for a durable host, in three lines:\n * const { id, promise } = awakeableWithTimeout<TaskExitInfo>(ctx, { timeoutMs, promises: RestatePromise })\n * await registerExitResumer(taskId, id) // runner → ctx.resolveAwakeable(id, info)\n * return await promise // TaskExitInfo, or null on timeout\n * ```\n */\nexport function awakeableWithTimeout<T, TPromise extends Promise<unknown> = Promise<unknown>>(\n ctx: RestateContextLike,\n options: AwakeableWithTimeoutOptions<TPromise> = {},\n): RestateAwakeable<T | null> {\n const awakeable = ctx.awakeable<T>()\n const timeoutMs = options.timeoutMs\n if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0)\n return awakeable\n\n const timer = ctx.sleep(timeoutMs)\n const raced = options.promises\n ? options.promises.race([awakeable.promise, timer] as readonly unknown[] as readonly TPromise[])\n : Promise.race<unknown>([awakeable.promise, timer])\n return {\n id: awakeable.id,\n // The sleep branch resolves `undefined`; normalize to the seam's\n // `null` so callers get one documented timeout sentinel.\n promise: raced.then(value => (value === undefined ? null : value as T)),\n }\n}\n","/**\n * Awakeable-backed tool — durable human/external-in-the-loop waits.\n *\n * Builds a `ToolDef` whose `execute` parks on a Restate awakeable: the\n * tool mints a journal-stable awakeable id, broadcasts it out-of-band\n * (webhook, queue, collab stream — the `notify` callback), and suspends\n * until a resumer calls `ctx.resolveAwakeable(id, value)` on the SDK\n * side. The classic shape for `ask_user` / `request_review` /\n * `wait_for_approval` tools inside durable handlers.\n *\n * Replay contract\n * ---------------\n * - **Broadcast-once-across-replays**: `notify` runs inside `ctx.run`,\n * so a crash + replay returns the journaled marker without re-sending\n * the notification. The user is pinged exactly once per tool call, no\n * matter how many times the worker restarts.\n * - **Marker invariant**: the journaled marker records the awakeable id\n * it was broadcast for. On replay the freshly-minted awakeable id must\n * match (the SDK derives awakeable ids deterministically from the\n * journal position); a mismatch means the journal and the code path\n * drifted — the tool throws instead of parking on an id nobody will\n * ever resolve.\n */\n\nimport type { ToolContext, ToolDef } from '../tools/types'\nimport type { ToolResultContent } from '../types'\nimport type { RestateContextLike, RestateRunOptions } from './types'\n\n/** Journaled broadcast marker — see \"Marker invariant\" in the module doc. */\ninterface AwakeableNotifyMarker {\n notified: true\n awakeableId: string\n}\n\nexport interface RestateAwakeableToolOptions<T = unknown> {\n /** Canonical tool name (what the model calls). */\n name: string\n /** Model-facing tool description. */\n description: string\n /** JSON schema for the tool input. */\n inputSchema: Record<string, unknown>\n /** The Restate context the awakeable + journal entries bind to. */\n ctx: RestateContextLike\n /**\n * Send the awakeable id (plus the call's input) out-of-band so a\n * resumer can later call `ctx.resolveAwakeable(awakeableId, value)`.\n * Runs inside `ctx.run` — fires exactly once across replays.\n */\n notify: (info: {\n awakeableId: string\n input: Record<string, unknown>\n toolCtx: ToolContext\n }) => void | Promise<void>\n /**\n * Map the resolved awakeable payload to the tool result. Default:\n * strings pass through, everything else is JSON-stringified.\n */\n toResult?: (value: T, input: Record<string, unknown>) => string | ToolResultContent[]\n /**\n * `ctx.run` options for the notify entry. Defaults to\n * `{ maxRetryAttempts: 1 }`, matching `restateTool`'s rationale.\n */\n runOptions?: RestateRunOptions\n /**\n * Concurrency-safety flag passed through to the `ToolDef`. Defaults to\n * `false` — a parked wait holding a scheduler slot should barrier.\n */\n isConcurrencySafe?: boolean\n}\n\n/**\n * Build a `ToolDef` that parks on a Restate awakeable until an external\n * resumer resolves it. See the module doc for the replay contract.\n *\n * Do NOT additionally wrap the returned tool in `restateTool` — the\n * journal discipline is already internal, and an outer `ctx.run` would\n * illegally nest the suspension point inside a journaled closure.\n */\nexport function restateAwakeableTool<T = unknown>(\n options: RestateAwakeableToolOptions<T>,\n): ToolDef {\n const { name, description, inputSchema, ctx, notify, toResult } = options\n const runOpts: RestateRunOptions = options.runOptions ?? { maxRetryAttempts: 1 }\n let seq = 0\n\n const execute = async (input: Record<string, unknown>, toolCtx: ToolContext): Promise<string | ToolResultContent[]> => {\n seq += 1\n // Mint BEFORE the journaled broadcast: the awakeable's journal\n // position precedes the notify entry, so on replay both come back\n // in the same order with the same id.\n const awakeable = ctx.awakeable<T>()\n\n const marker = await ctx.run<AwakeableNotifyMarker>(\n `awakeable-${name}-${seq}-notify`,\n async () => {\n await notify({ awakeableId: awakeable.id, input, toolCtx })\n return { notified: true, awakeableId: awakeable.id }\n },\n runOpts,\n )\n\n // Marker invariant — a drifted journal would otherwise park this\n // call on an id that was never broadcast (nobody will resolve it).\n if (marker.awakeableId !== awakeable.id) {\n throw new Error(\n `restateAwakeableTool(${name}): journal drift — broadcast marker carries awakeable \"${marker.awakeableId}\" but this replay minted \"${awakeable.id}\". The journal and the code path no longer line up; refusing to park on an unreachable awakeable.`,\n )\n }\n\n const value = await awakeable.promise\n if (toResult)\n return toResult(value, input)\n return typeof value === 'string' ? value : JSON.stringify(value)\n }\n\n return {\n spec: { name, description, inputSchema },\n ...(options.isConcurrencySafe !== undefined ? { isConcurrencySafe: options.isConcurrencySafe } : {}),\n execute,\n // The awakeable park IS the durable body — the loop's durable path\n // can use it directly without an extra wrapper.\n durableExecute: execute,\n }\n}\n","/**\n * Restate control-flow errors must escape the agent loop. If they are turned\n * into model-visible tool results, the runtime can retry/suspend incorrectly.\n *\n * Kept structural so `zidane/restate` does not need to import the SDK at\n * runtime just to recognize the common error shapes.\n */\nexport function shouldRethrowRestateControlError(error: unknown): boolean {\n if (!(error instanceof Error))\n return false\n\n const codeValue = Reflect.get(error, 'code')\n const code = typeof codeValue === 'number'\n ? codeValue\n : undefined\n if (code === 599)\n return true\n\n const name = error.name\n if (\n name === 'TerminalError'\n || name === 'TimeoutError'\n || name === 'CancelledError'\n || name === 'SuspendedError'\n ) {\n return true\n }\n\n const ctorName = error.constructor?.name\n const serializedCtorNameValue = Reflect.get(error, 'constructorName')\n const serializedCtorName = typeof serializedCtorNameValue === 'string'\n ? serializedCtorNameValue\n : undefined\n if (\n ctorName === 'TerminalError'\n || ctorName === 'TimeoutError'\n || ctorName === 'CancelledError'\n || ctorName === 'SuspendedError'\n || serializedCtorName === 'TerminalError'\n || serializedCtorName === 'TimeoutError'\n || serializedCtorName === 'CancelledError'\n || serializedCtorName === 'SuspendedError'\n ) {\n return true\n }\n\n return typeof name === 'string' && name.toLowerCase().includes('suspend')\n}\n","import type { AgentBehavior } from '../types'\nimport { shouldRethrowRestateControlError } from './errors'\n\n/**\n * Conservative behavior defaults for agents running inside Restate.\n *\n * The helper is opt-in and returns a plain AgentBehavior object, so callers can\n * spread or override it without changing non-Restate harness defaults.\n *\n * `disableBackgroundTasks: 'non-durable'` is capability-aware: background\n * tasks stay enabled for execution contexts whose\n * `capabilities.detachedTasks` is `'durable'` (tasks live on a remote\n * runner and survive worker crashes) and are disabled for everything\n * else (host-local processes don't survive process death). Hosts on\n * plain `ProcessContext` see the same effective behavior as the old\n * blanket `true`.\n */\nexport function restateBehavior(overrides: AgentBehavior = {}): AgentBehavior {\n return {\n maxConcurrentTools: 1,\n disableBackgroundTasks: 'non-durable',\n cache: true,\n shouldRethrowToolError: shouldRethrowRestateControlError,\n ...overrides,\n }\n}\n","/**\n * Restate-backed {@link AgentClock} — journals `now()` + `randomUUID()` so\n * `SessionTurn.createdAt`, `runId`, and fallback / synthetic turn ids stay\n * byte-identical across replays of the same invocation.\n *\n * Pass to `agent.run({ clock: restateClock(ctx) })` or bake it into\n * `createAgent({ clock: restateClock(ctx) })` for the duration of a\n * handler invocation. The clock holds a reference to `ctx`; do not reuse\n * a clock instance across invocations.\n */\n\nimport type { AgentClock } from '../types'\nimport type { RestateContextLike } from './types'\n\n/**\n * Wrap a Restate context's `date.now()` + `rand.uuidv4()` into the\n * {@link AgentClock} shape Zidane consumes for journaled metadata.\n *\n * The returned clock is a thin live view onto `ctx` — each call hits\n * the SDK afresh. No caching, no closure-captured values. Restate's\n * journal handles determinism on its end.\n */\nexport function restateClock(ctx: RestateContextLike): AgentClock {\n return {\n now: () => ctx.date.now(),\n randomUUID: () => ctx.rand.uuidv4(),\n }\n}\n","import type { ToolResult } from '../providers'\nimport type { ToolBatchExecutionContext, ToolBatchExecutor } from '../types'\n\nexport interface RestatePromiseAllLike<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>> {\n all: (values: readonly TPromise[]) => Promise<readonly unknown[]>\n}\n\nexport type RestatePromiseLike<T> = Promise<T> & {\n map: <U>(mapper: (value?: T, failure?: unknown) => U) => Promise<U>\n}\n\nexport interface RestateToolBatchExecutorOptions<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>> {\n /**\n * Wait for a safe fleet through Restate's durable combinator. Pass\n * `RestatePromise` from `@restatedev/restate-sdk` in real deployments.\n */\n promises: RestatePromiseAllLike<TPromise>\n}\n\n/**\n * Tool batch scheduler for Restate-backed agents.\n *\n * It preserves unsafe-tool barriers and emits results in model submission\n * order. Safe fleets are started in submission order, capped by\n * `maxConcurrentTools`, and joined via the supplied durable `all()`.\n */\nexport function restateToolBatchExecutor<TPromise extends Promise<unknown> = RestatePromiseLike<unknown>>(\n options: RestateToolBatchExecutorOptions<TPromise>,\n): ToolBatchExecutor {\n return async (ctx: ToolBatchExecutionContext): Promise<ToolResult[]> => {\n const results: ToolResult[] = []\n const { toolCalls } = ctx\n\n const fillRemaining = (from: number, factory: (index: number) => ToolResult): ToolResult[] => {\n for (let i = from; i < toolCalls.length; i++)\n results[i] = factory(i)\n return results\n }\n\n for (let i = 0; i < toolCalls.length;) {\n if (ctx.signal.aborted)\n return fillRemaining(i, ctx.interruptedResult)\n if (ctx.steeringQueue.length > 0)\n return fillRemaining(i, ctx.skippedResult)\n\n if (!ctx.isConcurrencySafe(i)) {\n results[i] = await ctx.execute(i)\n i += 1\n continue\n }\n\n const start = i\n const fleet: number[] = []\n while (\n i < toolCalls.length\n && ctx.isConcurrencySafe(i)\n && fleet.length < ctx.maxConcurrentTools\n ) {\n fleet.push(i)\n i += 1\n }\n\n const fleetResults = fleet.every(index => ctx.canExecuteDurably(index))\n ? await ctx.executeDurable(\n fleet,\n async <T>(values: readonly Promise<T>[]): Promise<readonly T[]> => {\n const results = await options.promises.all(values as readonly TPromise[])\n return results as readonly T[]\n },\n )\n : await executeSequential(ctx, fleet)\n for (let offset = 0; offset < fleetResults.length; offset++)\n results[start + offset] = fleetResults[offset]\n }\n\n return results\n }\n}\n\nasync function executeSequential(\n ctx: ToolBatchExecutionContext,\n indices: readonly number[],\n): Promise<ToolResult[]> {\n const results: ToolResult[] = []\n for (const index of indices) {\n if (ctx.signal.aborted) {\n results.push(ctx.interruptedResult(index))\n continue\n }\n if (ctx.steeringQueue.length > 0) {\n results.push(ctx.skippedResult(index))\n continue\n }\n results.push(await ctx.execute(index))\n }\n return results\n}\n","/**\n * Restate-backed Provider wrapper.\n *\n * Wraps `Provider.stream` so every assistant turn (the LLM call as a\n * whole) is journaled. The model is invoked once per turn — the live\n * stream still fires `onText` / `onThinking` callbacks for UX during the\n * original execution. On replay, `ctx.run` returns the journaled\n * `TurnResult` immediately and the inner provider is NEVER re-invoked →\n * no duplicate billed tokens, no duplicate stream chunks.\n *\n * Replay caveat: stream callbacks don't re-fire on replay. Consumers\n * that paint live UI from `stream:text` should reconstruct transcripts\n * from `session.turns` via `eventsFromTurns` (zidane/chat) instead of\n * relying on hook re-emission. The chat layer already does this.\n *\n * Journal-entry naming: a monotonic per-wrapper counter (`llm-call-1`,\n * `llm-call-2`, …). One wrapper instance per Restate handler invocation\n * resets the counter; Restate's journal is invocation-scoped so names\n * don't need to be globally unique. The counter ticks the same way on\n * replay because the wrapper is constructed fresh each attempt.\n */\n\nimport type { Provider, StreamCallbacks, StreamOptions, TurnResult } from '../providers'\nimport type { RestateContextLike, RestateRunOptions } from './types'\n\nexport interface RestateProviderOptions {\n /**\n * `ctx.run` options forwarded on every wrapped stream call.\n *\n * Default depends on {@link streamCallbacks}:\n *\n * - `'suppress'` → `{ maxRetryAttempts: 3 }` — provider transients\n * (rate limits, 5xx, connection resets) get retried inside the\n * journal entry; nothing streams to the host, so a retry is\n * invisible.\n * - `'live'` (the default) → `{ maxRetryAttempts: 1 }`. A live stream\n * that fails AFTER emitting deltas would be re-run inside the same\n * journal entry, re-firing `onText` into the loop's accumulating\n * text buffer and producing duplicated partial1+full2 output. The\n * loop's own retry (which only re-issues on a clean slate) is the\n * correct retry layer in live mode.\n *\n * Once the cap is reached the failure becomes terminal and surfaces\n * through the loop's normal `AgentProviderError` path. Set this\n * explicitly to override either default — but with live callbacks,\n * `maxRetryAttempts > 1` re-introduces the duplicate-delta hazard.\n */\n runOptions?: RestateRunOptions\n /**\n * Override the journal-entry name. Receives the 1-indexed sequence\n * number for this wrapper instance and the `StreamOptions` of the\n * call. Default: `llm-call-<n>`. Override to inject extra structure\n * (e.g. `${agentName}/llm-call-${n}`) when multiple agents share a\n * service.\n */\n entryName?: (seq: number, opts: StreamOptions) => string\n /**\n * Whether live stream callbacks should fire during the original execution.\n * Use `'suppress'` for strict durable mode: the model call still returns a\n * full TurnResult, and UIs reconstruct from persisted session turns.\n *\n * Default: `'live'`.\n */\n streamCallbacks?: 'live' | 'suppress'\n}\n\n/**\n * Wrap a Zidane `Provider` so its `stream()` method journals each turn's\n * response inside `ctx.run`. All other Provider methods (`formatTools`,\n * `userMessage`, `toolResultsMessage`, `classifyError`, …) pass through\n * unchanged — they're pure functions over already-deterministic inputs.\n */\nexport function restateProvider(\n inner: Provider,\n ctx: RestateContextLike,\n options: RestateProviderOptions = {},\n): Provider {\n // Live callbacks must not retry inside the journal entry — a stream that\n // fails after emitting deltas would re-fire `onText` on the retry and\n // duplicate text in the loop's accumulator. See the `runOptions` doc.\n const runOpts: RestateRunOptions = options.runOptions\n ?? (options.streamCallbacks === 'suppress' ? { maxRetryAttempts: 3 } : { maxRetryAttempts: 1 })\n const nameFor = options.entryName ?? ((seq: number) => `llm-call-${seq}`)\n let seq = 0\n\n return {\n ...inner,\n stream(streamOpts: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n seq += 1\n const durableCallbacks = options.streamCallbacks === 'suppress'\n ? suppressStreamingCallbacks(callbacks)\n : callbacks\n return ctx.run<TurnResult>(\n nameFor(seq, streamOpts),\n () => inner.stream(streamOpts, durableCallbacks),\n runOpts,\n )\n },\n }\n}\n\nfunction suppressStreamingCallbacks(callbacks: StreamCallbacks): StreamCallbacks {\n return {\n ...callbacks,\n onText: () => {},\n onThinking: undefined,\n onServerToolUse: undefined,\n onServerToolResult: undefined,\n }\n}\n","/**\n * Restate-backed `SessionStore` — turn / run state lives in the bound\n * virtual object's K/V state instead of SQLite / file / remote HTTP.\n *\n * Trade-offs vs. journal-only replay\n * ----------------------------------\n * If you only care about durable execution within ONE invocation,\n * skip this — the journaled `ctx.run` entries (LLM calls, tool\n * executions) are enough to replay the loop to byte-identical state\n * after a crash. The in-memory `createMemoryStore()` is the right\n * choice; turns rematerialize from the journal each replay.\n *\n * Pick this store when EXTERNAL consumers (TUI, web GUI, support\n * tooling) need to read a session's history WITHOUT re-entering the\n * agent handler. Virtual-object state is exposed via the SDK's read\n * APIs (`ctx.get` from another handler, `restate-cli`, the Restate\n * web UI) — same data, different access path. The journal is\n * invocation-local; this state is the externally-visible projection\n * of it.\n *\n * Storage layout\n * --------------\n * One virtual-object key per session, three K/V slots:\n *\n * `session-data` → `SessionData` minus the `turns` array (small header)\n * `session-turns` → `SessionTurn[]` (the conversation history)\n * `session-runs` → `SessionRun[]` (run lifecycle records)\n *\n * Splitting `turns` / `runs` out keeps the header light for `load()` —\n * a handler that only needs metadata doesn't pull the full history.\n *\n * Listing / discovery\n * -------------------\n * `list()` returns `[]` because virtual objects don't expose cross-key\n * enumeration. `delete()` clears the current object's session keys only.\n * Use a separate index handler if you need discovery (one virtual object\n * per `projectRoot` that maintains an indexed list of session ids; this\n * store doesn't own that concern).\n * `generateSessionId` is omitted so the agent falls back to its\n * default UUID generator — for a session bound 1:1 to a virtual-\n * object key, pass `id: ctx.key` to `createSession()` instead and\n * skip ID generation entirely.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '../session'\nimport type { SessionTurn } from '../types'\nimport type { RestateObjectContextLike } from './types'\n\nconst KEY_DATA = 'session-data'\nconst KEY_TURNS = 'session-turns'\nconst KEY_RUNS = 'session-runs'\n\n/**\n * Construct a `SessionStore` backed by the bound virtual-object's K/V\n * state. The store is single-tenant — every method ignores the\n * `sessionId` argument because the virtual object is already keyed by\n * `ctx.key`. Calling `appendTurns('other-id', …)` writes to the\n * CURRENT object's state, not the one named in the argument. Bind one\n * virtual-object key per session and the contract holds.\n */\nexport function restateSessionStore(ctx: RestateObjectContextLike): SessionStore {\n let nextTurnSeq: number | undefined\n\n async function generateTurnId(): Promise<string> {\n if (nextTurnSeq === undefined) {\n const existing = (await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? []\n nextTurnSeq = existing.length\n }\n nextTurnSeq += 1\n return `turn_${nextTurnSeq}`\n }\n\n return {\n /**\n * Turn ids are deterministic from the persisted turn count. Random ids\n * are replay-stable only when the whole handler replays from the same\n * point; restarting from an arbitrary journal step can shift the RNG\n * sequence before a state write.\n */\n generateTurnId,\n\n async load(_sessionId: string): Promise<SessionData | null> {\n const header = await ctx.get<Omit<SessionData, 'turns' | 'runs'>>(KEY_DATA)\n const turns = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n const runs = sanitizeRunsForState((await ctx.get<SessionRun[]>(KEY_RUNS)) ?? [])\n if (!header) {\n if (turns.length === 0 && runs.length === 0)\n return null\n return {\n id: _sessionId,\n turns,\n runs,\n status: inferStatus(runs),\n metadata: {},\n createdAt: inferCreatedAt(turns, runs),\n updatedAt: inferUpdatedAt(turns, runs),\n }\n }\n return { ...header, turns, runs }\n },\n\n async save(session: SessionData): Promise<void> {\n const { turns, runs, ...header } = session\n // Journal-stable header timestamps. The in-memory `Session` stamps\n // `createdAt` / `updatedAt` with raw `Date.now()` (its `touch()`\n // helper is synchronous and can't await a journaled clock), so the\n // values arriving here differ on every replay — and a replayed\n // `ctx.set` with drifting values is exactly the non-determinism\n // Restate exists to prevent. Source both from the journal instead:\n // `createdAt` sticks to the first persisted value, `updatedAt`\n // comes from `ctx.date.now()` (journaled — replay returns the\n // recorded reading).\n const prior = await ctx.get<Omit<SessionData, 'turns' | 'runs'>>(KEY_DATA)\n const now = await ctx.date.now()\n ctx.set(KEY_DATA, {\n ...header,\n createdAt: prior?.createdAt ?? now,\n updatedAt: now,\n })\n ctx.set(KEY_TURNS, sanitizeTurnsForState(turns))\n ctx.set(KEY_RUNS, sanitizeRunsForState(runs))\n },\n\n async delete(_sessionId: string): Promise<void> {\n ctx.clear(KEY_DATA)\n ctx.clear(KEY_TURNS)\n ctx.clear(KEY_RUNS)\n },\n\n /**\n * Always empty — virtual objects don't support cross-key\n * enumeration. Maintain a separate index handler if discovery\n * matters.\n */\n async list(): Promise<string[]> {\n return []\n },\n\n async appendTurns(_sessionId: string, turns: SessionTurn[]): Promise<void> {\n const existing = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n ctx.set(KEY_TURNS, [...existing, ...sanitizeTurnsForState(turns)])\n },\n\n async getTurns(_sessionId: string, from = 0, limit?: number): Promise<SessionTurn[]> {\n const turns = sanitizeTurnsForState((await ctx.get<SessionTurn[]>(KEY_TURNS)) ?? [])\n return turns.slice(from, limit !== undefined ? from + limit : undefined)\n },\n\n async updateRun(_sessionId: string, run: SessionRun): Promise<void> {\n const runs = sanitizeRunsForState((await ctx.get<SessionRun[]>(KEY_RUNS)) ?? [])\n const idx = runs.findIndex(r => r.id === run.id)\n const next = [...runs]\n if (idx >= 0)\n next[idx] = sanitizeRunForState(run)\n else\n next.push(sanitizeRunForState(run))\n ctx.set(KEY_RUNS, next)\n },\n\n async updateStatus(_sessionId: string, status: SessionData['status']): Promise<void> {\n const header = await ctx.get<Omit<SessionData, 'turns' | 'runs'>>(KEY_DATA)\n const now = await ctx.date.now()\n if (header) {\n ctx.set(KEY_DATA, { ...header, status, updatedAt: now })\n }\n else {\n ctx.set(KEY_DATA, {\n id: _sessionId,\n status,\n metadata: {},\n createdAt: now,\n updatedAt: now,\n })\n }\n },\n }\n}\n\nfunction sanitizeTurnsForState(turns: readonly SessionTurn[]): SessionTurn[] {\n return turns.map(sanitizeTurnForState)\n}\n\nfunction sanitizeTurnForState(turn: SessionTurn): SessionTurn {\n if (!turn.usage || turn.usage.timeToFirstTokenMs === undefined)\n return turn\n\n const { timeToFirstTokenMs: _timeToFirstTokenMs, ...usage } = turn.usage\n return { ...turn, usage }\n}\n\nfunction sanitizeRunsForState(runs: readonly SessionRun[]): SessionRun[] {\n return runs.map(sanitizeRunForState)\n}\n\nfunction sanitizeRunForState(run: SessionRun): SessionRun {\n if (!run.turnUsage?.some(usage => usage.timeToFirstTokenMs !== undefined))\n return run\n\n return {\n ...run,\n turnUsage: run.turnUsage.map((usage) => {\n if (usage.timeToFirstTokenMs === undefined)\n return usage\n const { timeToFirstTokenMs: _timeToFirstTokenMs, ...stableUsage } = usage\n return stableUsage\n }),\n }\n}\n\nfunction inferStatus(runs: readonly SessionRun[]): SessionData['status'] {\n if (runs.some(run => run.status === 'running'))\n return 'running'\n if (runs.some(run => run.status === 'error'))\n return 'error'\n if (runs.some(run => run.status === 'completed'))\n return 'completed'\n return 'idle'\n}\n\nfunction inferCreatedAt(turns: readonly SessionTurn[], runs: readonly SessionRun[]): number {\n return minDefined([\n ...turns.map(turn => turn.createdAt),\n ...runs.map(run => run.startedAt),\n ]) ?? 0\n}\n\nfunction inferUpdatedAt(turns: readonly SessionTurn[], runs: readonly SessionRun[]): number {\n return maxDefined([\n ...turns.map(turn => turn.createdAt),\n ...runs.map(run => run.endedAt ?? run.startedAt),\n ]) ?? inferCreatedAt(turns, runs)\n}\n\nfunction minDefined(values: readonly number[]): number | undefined {\n let min: number | undefined\n for (const value of values) {\n if (min === undefined || value < min)\n min = value\n }\n return min\n}\n\nfunction maxDefined(values: readonly number[]): number | undefined {\n let max: number | undefined\n for (const value of values) {\n if (max === undefined || value > max)\n max = value\n }\n return max\n}\n","/**\n * Restate-backed tool wrappers.\n *\n * Wraps `ToolDef.execute` so every tool invocation is journaled. The\n * tool body runs on the original execution; after Restate persists the\n * journal entry, replay returns the recorded result without re-executing.\n * If the process dies before the entry is durable, the latest in-flight\n * tool can run again, so non-idempotent tools still need idempotency keys.\n *\n * `tool:gate`, `tool:transform`, `tool:after` hooks fire OUTSIDE the\n * journaled boundary, so they re-execute on replay. Built-in handlers\n * are deterministic given the journaled input + output (truncation,\n * image-stripping, `<edit-outcomes>` merge — all pure). Consumer hooks\n * that hit external services should themselves wrap side effects in\n * `ctx.run` so the substitution / annotation is replay-stable.\n *\n * `isConcurrencySafe` is preserved — Restate's per-key serialization\n * doesn't preclude in-handler parallelism. The loop's scheduler still\n * fans out safe tools up to `behavior.maxConcurrentTools`, each call\n * lands in its own journal entry. Order-of-journal-completion does NOT\n * affect replay correctness: Restate journals by call-site name, not\n * by completion order.\n */\n\nimport type { DetachedTasksCapability } from '../contexts'\nimport type { Session } from '../session'\nimport type { ToolContext, ToolDef } from '../tools/types'\nimport type { ToolResultContent } from '../types'\nimport type { RestateContextLike, RestateRunOptions } from './types'\nimport { hydrateReadStateFromSessionAsync } from '../tools/read-state'\n\n/**\n * Opt-in two-phase journaling for long-running, re-attachable tools.\n *\n * The default `restateTool` wrapping journals only the COMPLETED result —\n * a crash mid-execute re-runs the tool on replay, which is unacceptable\n * for builds / migrations / deploys. `durableStart` splits the execution:\n *\n * 1. `start` runs inside its own `ctx.run` entry, journaled BEFORE the\n * body — it kicks off the side effect and returns a re-attach token\n * (a background task id, a job handle, an idempotency key).\n * 2. `attach` runs inside the result entry with the journaled token —\n * on replay it receives the SAME token and re-attaches to the\n * already-running work instead of starting it again.\n *\n * The wrapped tool's own `execute` is bypassed; the start/attach pair IS\n * the execution.\n */\nexport interface RestateDurableStart<Token = unknown> {\n /** Kick off the side effect; journaled before `attach`. Must be cheap + idempotent-safe up to journal persistence. */\n start: (input: Record<string, unknown>, toolCtx: ToolContext) => Promise<Token> | Token\n /** Await / re-attach to the work identified by `token` and produce the tool result. */\n attach: (token: Token, input: Record<string, unknown>, toolCtx: ToolContext) => Promise<string | ToolResultContent[]>\n /**\n * Best-effort cleanup when the per-call abort signal fires before\n * `attach` settles (run abort, `agent.cancelTool`, sibling-cascade\n * cancel, `agent.destroy()` mid-run). Without it, the journaled token\n * identifies a remote job that keeps running with nobody attached —\n * a leak for hosts whose jobs outlive the session.\n *\n * Contract:\n * - Fires at most once per call, outside the journal (an aborting\n * invocation can't open new `ctx.run` entries reliably) — journal\n * your own cleanup on the host side if it must be durable.\n * - May run concurrently with a still-unwinding `attach`; make it\n * idempotent against \"job already gone\".\n * - NOT called on process death — that's not termination: the\n * journaled token re-attaches on replay instead. This seam is for\n * deliberate aborts, where no replay is coming.\n * - Errors are swallowed (surfaced under `ZIDANE_DEBUG`) — cleanup\n * failure must not mask the abort itself.\n */\n onAbort?: (token: Token, input: Record<string, unknown>, toolCtx: ToolContext) => Promise<void> | void\n}\n\nexport interface RestateToolOptions<Token = unknown> {\n /**\n * `ctx.run` options forwarded on every wrapped tool call. Defaults to\n * `{ maxRetryAttempts: 1 }` — tool errors are typically deterministic\n * (validation failures, missing files) so blind retries waste budget.\n * Override per-tool for network-heavy custom tools that benefit from\n * SDK-level retries.\n */\n runOptions?: RestateRunOptions\n /**\n * Override the journal-entry name. Receives the canonical tool name\n * and the call's input. Default: `tool-<name>-<seq>` where `<seq>` is\n * a per-wrapper monotonic counter. Override to inject the model's\n * `callId` (read it off `ToolContext.callId` inside `execute` if you\n * need an LLM-visible key — but the default counter is sufficient\n * for journal correctness).\n */\n entryName?: (seq: number, name: string, input: Record<string, unknown>) => string\n /**\n * Hide and reject the built-in shell tool's background mode.\n *\n * Default: derived from {@link RestateToolOptions.detachedTasks} —\n * disabled unless the execution context declares `'durable'` detached\n * tasks. An explicit boolean always wins.\n */\n disableShellBackground?: boolean\n /**\n * `detachedTasks` capability of the execution context the agent will\n * run with (see `ContextCapabilities.detachedTasks` /\n * `resolveDetachedTasksCapability`). Drives the\n * `disableShellBackground` default: a `'durable'` context keeps its\n * background tasks across worker crashes, so the wrapper leaves the\n * shell tool's background mode intact.\n *\n * Default: `undefined`, treated as non-durable (background disabled).\n */\n detachedTasks?: DetachedTasksCapability\n /**\n * Two-phase start/attach journaling for crash-safe long tools — see\n * {@link RestateDurableStart}. Per-tool by nature; not accepted by\n * `wrapAgentTools` (a single start/attach pair can't fit a whole map).\n */\n durableStart?: RestateDurableStart<Token>\n}\n\nconst SHELL_BACKGROUND_DISABLED_MESSAGE = 'shell error: background mode is disabled for Restate-backed agents. Fall back to foreground (drop `run_in_background`).'\nconst HYDRATED_READ_STATE_SESSIONS = new WeakSet<Session>()\n\n/**\n * Wrap a single `ToolDef` so its `execute` runs inside `ctx.run`. The\n * tool's `spec` and `isConcurrencySafe` pass through unchanged.\n */\nexport function restateTool<Token = unknown>(\n inner: ToolDef,\n ctx: RestateContextLike,\n options: RestateToolOptions<Token> = {},\n): ToolDef {\n const runOpts: RestateRunOptions = options.runOptions ?? { maxRetryAttempts: 1 }\n const nameFor = options.entryName ?? ((seq: number, name: string) => `tool-${name}-${seq}`)\n const canonicalName = inner.spec.name\n const disableShellBackground = options.disableShellBackground ?? (options.detachedTasks !== 'durable')\n const shellBackgroundDisabled = disableShellBackground && canonicalName === 'shell'\n const durableStart = options.durableStart\n let seq = 0\n const hydrateOnce = async (toolCtx: Parameters<ToolDef['execute']>[1]) => {\n if (toolCtx.session && !HYDRATED_READ_STATE_SESSIONS.has(toolCtx.session)) {\n HYDRATED_READ_STATE_SESSIONS.add(toolCtx.session)\n await hydrateReadStateFromSessionAsync(toolCtx.session, toolCtx.handle.cwd, {\n defaultLineNumbers: toolCtx.behavior?.readLineNumbers ?? true,\n readFileForHash: async (path) => {\n try {\n return await toolCtx.execution.readFile(toolCtx.handle, path)\n }\n catch {\n return null\n }\n },\n })\n }\n }\n // IMPORTANT: NOT async, and the `ctx.run` promise is returned without\n // native combinators — `durableExecute` consumers (the Restate batch\n // scheduler) need the runtime's own promise shape (`.map`) intact.\n const executeDurably = (input: Record<string, unknown>, toolCtx: Parameters<ToolDef['execute']>[1]) => {\n seq += 1\n return ctx.run(\n nameFor(seq, canonicalName, input),\n async () => {\n await hydrateOnce(toolCtx)\n if (shellBackgroundDisabled && input.run_in_background === true)\n return SHELL_BACKGROUND_DISABLED_MESSAGE\n return inner.execute(input, toolCtx)\n },\n runOpts,\n )\n }\n\n // Two-phase mode: journal the start token BEFORE the body so a crash\n // mid-execution re-attaches on replay instead of re-running. The await\n // between the two entries makes this a native-async composition, so the\n // tool deliberately does NOT advertise `durableExecute` — the batch\n // scheduler runs it sequentially via plain `execute`, which is the\n // right shape for long re-attachable work anyway.\n const executeTwoPhase = async (input: Record<string, unknown>, toolCtx: Parameters<ToolDef['execute']>[1]) => {\n const start = durableStart!\n seq += 1\n const entry = nameFor(seq, canonicalName, input)\n const token = await ctx.run(\n `${entry}-start`,\n async () => {\n await hydrateOnce(toolCtx)\n return start.start(input, toolCtx)\n },\n runOpts,\n )\n\n const attach = () => ctx.run(\n entry,\n () => start.attach(token, input, toolCtx),\n runOpts,\n )\n\n // Abort seam — see RestateDurableStart.onAbort. At-most-once via the\n // `fired` latch; armed only while attach is in flight.\n const onAbort = start.onAbort\n const signal = toolCtx.signal as AbortSignal | undefined\n if (!onAbort || !signal)\n return attach()\n\n let fired = false\n const fireAbortCleanup = (): void => {\n if (fired)\n return\n fired = true\n Promise.resolve(onAbort(token, input, toolCtx)).catch((err: unknown) => {\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/restate] durableStart onAbort threw: ${err instanceof Error ? err.message : String(err)}\\n`)\n })\n }\n\n // Pre-aborted: the journaled start already launched the job — clean\n // it up, then still run attach so the call surfaces the host's own\n // cancellation shape (it should fail fast on an aborted signal).\n if (signal.aborted) {\n fireAbortCleanup()\n return attach()\n }\n signal.addEventListener('abort', fireAbortCleanup, { once: true })\n try {\n return await attach()\n }\n finally {\n signal.removeEventListener('abort', fireAbortCleanup)\n }\n }\n\n if (durableStart) {\n // Strip any pre-existing `durableExecute` — see the executeTwoPhase\n // comment; advertising one here would hand the batch scheduler a\n // native promise it can't `.map`.\n const { durableExecute: _dropped, ...rest } = inner\n return {\n ...rest,\n spec: shellBackgroundDisabled ? withoutShellBackgroundInput(inner.spec) : inner.spec,\n execute: executeTwoPhase,\n }\n }\n\n return {\n ...inner,\n spec: shellBackgroundDisabled ? withoutShellBackgroundInput(inner.spec) : inner.spec,\n execute: executeDurably,\n durableExecute: executeDurably,\n }\n}\n\nfunction withoutShellBackgroundInput(spec: ToolDef['spec']): ToolDef['spec'] {\n const inputSchema = spec.inputSchema\n const properties = isRecord(inputSchema.properties) ? inputSchema.properties : undefined\n if (!properties || !Object.hasOwn(properties, 'run_in_background'))\n return spec\n\n const { run_in_background: _runInBackground, ...nextProperties } = properties\n const required = Array.isArray(inputSchema.required)\n ? inputSchema.required.filter(name => name !== 'run_in_background')\n : inputSchema.required\n return {\n ...spec,\n description: stripShellBackgroundDescription(spec.description),\n inputSchema: {\n ...inputSchema,\n properties: nextProperties,\n ...(required !== inputSchema.required ? { required } : {}),\n },\n }\n}\n\nfunction stripShellBackgroundDescription(description: string): string {\n return description\n .split('\\n')\n .filter(line =>\n !line.includes('run_in_background')\n && !line.includes('<task-notification>')\n && !line.includes('background task'),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Wrap an entire tool map at once — convenience for the common case of\n * \"journal every tool the agent has\". Pass-through for tools whose\n * names are listed in `opts.exclude` (e.g. fully-deterministic local\n * helpers where journaling is pure overhead).\n *\n * The returned map is a fresh object; the input is untouched.\n */\nexport function wrapAgentTools(\n tools: Record<string, ToolDef>,\n ctx: RestateContextLike,\n opts: Omit<RestateToolOptions, 'durableStart'> & { exclude?: readonly string[] } = {},\n): Record<string, ToolDef> {\n const excludeSet = new Set(opts.exclude ?? [])\n // `detachedTasks: 'durable'` implies the host's `waitBackground` parks\n // on an awakeable (that's the durable wait pattern) — and a Restate\n // suspension point must NOT nest inside a journaled `ctx.run` closure.\n // Auto-exclude the built-in `wait_task` from wrapping so its park runs\n // outside the journal; the wait result is replay-safe anyway (a replayed\n // wait re-attaches to an already-terminated task and resolves from the\n // registry). Hosts with a journal-safe wait (e.g. a bridge RPC poll)\n // can re-wrap explicitly via `restateTool(waitTask, ctx, …)`.\n const skipWaitTask = opts.detachedTasks === 'durable'\n const wrapped: Record<string, ToolDef> = {}\n for (const [name, def] of Object.entries(tools)) {\n const passThrough = excludeSet.has(name) || (skipWaitTask && def.spec.name === 'wait_task')\n wrapped[name] = passThrough ? def : restateTool(def, ctx, opts)\n }\n return wrapped\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,SAAgB,qBACd,KACA,UAAiD,CAAC,GACtB;CAC5B,MAAM,YAAY,IAAI,UAAa;CACnC,MAAM,YAAY,QAAQ;CAC1B,IAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,GAC/E,OAAO;CAET,MAAM,QAAQ,IAAI,MAAM,SAAS;CACjC,MAAM,QAAQ,QAAQ,WAClB,QAAQ,SAAS,KAAK,CAAC,UAAU,SAAS,KAAK,CAA8C,IAC7F,QAAQ,KAAc,CAAC,UAAU,SAAS,KAAK,CAAC;CACpD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,YAAY,QAAQ,IAC/C,YAAY,SAAS,QAAO,SAAQ,SAAS,mBAAmB,IAChE,YAAY;CAChB,OAAO;EACL,GAAG;EACH,aAAa,gCAAgC,KAAK,WAAW;EAC7D,aAAa;GACX,GAAG;GACH,YAAY;GACZ,GAAI,aAAa,YAAY,WAAW,EAAE,SAAS,IAAI,CAAC;EAC1D;CACF;AACF;AAEA,SAAS,gCAAgC,aAA6B;CACpE,OAAO,YACJ,MAAM,IAAI,EACV,QAAO,SACN,CAAC,KAAK,SAAS,mBAAmB,KAC/B,CAAC,KAAK,SAAS,qBAAqB,KACpC,CAAC,KAAK,SAAS,iBAAiB,CACrC,EACC,KAAK,IAAI,EACT,QAAQ,WAAW,MAAM,EACzB,KAAK;AACV;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;;;;;AAUA,SAAgB,eACd,OACA,KACA,OAAmF,CAAC,GAC3D;CACzB,MAAM,aAAa,IAAI,IAAI,KAAK,WAAW,CAAC,CAAC;CAS7C,MAAM,eAAe,KAAK,kBAAkB;CAC5C,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,GAE5C,QAAQ,QADY,WAAW,IAAI,IAAI,KAAM,gBAAgB,IAAI,KAAK,SAAS,cACjD,MAAM,YAAY,KAAK,KAAK,IAAI;CAEhE,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { L as SessionStore } from "../agent-AnumGPWj.js";
1
+ import { L as SessionStore } from "../agent-Bt123Fdy.js";
2
2
 
3
3
  //#region src/session/sqlite.d.ts
4
4
  interface SqliteStoreOptions {
package/dist/session.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as RemoteStoreOptions, F as SessionData, G as createFileMapStore, H as createMemoryStore, I as SessionRun, L as SessionStore, N as CreateSessionOptions, P as Session, Q as ToWireMessagesOptions, R as createSession, U as FileMapAdapter, V as createRemoteStore, W as FileMapStoreOptions, at as fromAnthropic, ct as toOpenAI, et as autoDetectAndConvert, fn as SessionContentBlock, gn as SessionTurn, hn as SessionMessage, lt as toWireMessages, ot as fromOpenAI, st as toAnthropic, z as loadSession } from "./agent-AnumGPWj.js";
1
+ import { B as RemoteStoreOptions, F as SessionData, G as createFileMapStore, H as createMemoryStore, I as SessionRun, L as SessionStore, N as CreateSessionOptions, P as Session, Q as ToWireMessagesOptions, R as createSession, U as FileMapAdapter, V as createRemoteStore, W as FileMapStoreOptions, at as fromAnthropic, ct as toOpenAI, et as autoDetectAndConvert, fn as SessionContentBlock, gn as SessionTurn, hn as SessionMessage, lt as toWireMessages, ot as fromOpenAI, st as toAnthropic, z as loadSession } from "./agent-Bt123Fdy.js";
2
2
  export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, fromAnthropic, fromOpenAI, loadSession, toAnthropic, toOpenAI, toWireMessages };
package/dist/skills.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { A as SkillResource, M as SkillsConfig, O as SkillConfig, c as DeactivationReason, d as createSkillActivationState, j as SkillSource, k as SkillDiagnostic, l as SkillActivationState, o as ActivationVia, s as ActiveSkill, u as SkillActivationStateOptions } from "./agent-AnumGPWj.js";
2
- import { C as buildCatalog, S as parseSkillFile, T as installAllowedToolsGate, _ as SourcedScanPath, a as SkillValidationResult, b as inferSource, c as parseAllowedToolPattern, d as validateSkillForWrite, f as validateSkillName, g as stripShellInterpolations, h as interpolateShellCommands, i as SkillValidationIssue, l as validateResourcePath, m as InterpolateShellCommandsOptions, n as writeSkillToDisk, o as isToolAllowedByUnion, p as resolveSkills, r as writeSkillsToDisk, s as matchesAllowedTool, t as defineSkill, u as validateResourcePathReal, v as discoverSkills, w as IMPLICITLY_ALLOWED_SKILL_TOOLS, x as parseFrontmatter, y as getDefaultScanPaths } from "./index-DsvHiyYU.js";
1
+ import { A as SkillResource, M as SkillsConfig, O as SkillConfig, c as DeactivationReason, d as createSkillActivationState, j as SkillSource, k as SkillDiagnostic, l as SkillActivationState, o as ActivationVia, s as ActiveSkill, u as SkillActivationStateOptions } from "./agent-Bt123Fdy.js";
2
+ import { C as buildCatalog, S as parseSkillFile, T as installAllowedToolsGate, _ as SourcedScanPath, a as SkillValidationResult, b as inferSource, c as parseAllowedToolPattern, d as validateSkillForWrite, f as validateSkillName, g as stripShellInterpolations, h as interpolateShellCommands, i as SkillValidationIssue, l as validateResourcePath, m as InterpolateShellCommandsOptions, n as writeSkillToDisk, o as isToolAllowedByUnion, p as resolveSkills, r as writeSkillsToDisk, s as matchesAllowedTool, t as defineSkill, u as validateResourcePathReal, v as discoverSkills, w as IMPLICITLY_ALLOWED_SKILL_TOOLS, x as parseFrontmatter, y as getDefaultScanPaths } from "./index-BodGKXBV.js";
3
3
  export { type ActivationVia, type ActiveSkill, type DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, type InterpolateShellCommandsOptions, type SkillActivationState, type SkillActivationStateOptions, type SkillConfig, type SkillDiagnostic, type SkillResource, type SkillSource, type SkillValidationIssue, type SkillValidationResult, type SkillsConfig, type SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, interpolateShellCommands, isToolAllowedByUnion, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
@@ -1,4 +1,4 @@
1
- import { ut as Provider, yn as ThinkingLevel } from "./agent-AnumGPWj.js";
1
+ import { ut as Provider, yn as ThinkingLevel } from "./agent-Bt123Fdy.js";
2
2
  import { OAuthProviderInterface } from "@earendil-works/pi-ai/oauth";
3
3
  import { ReactNode } from "react";
4
4
 
@@ -1468,4 +1468,4 @@ declare function displayNameFor(name: string, input?: Record<string, unknown>):
1468
1468
  declare function formatToolCall(name: string, input: Record<string, unknown>): ToolFormatLine | null;
1469
1469
  //#endregion
1470
1470
  export { anthropicDescriptor as $, SessionMeta as A, collectReferences as B, EditHunk as C, Owner as D, EditPayload as E, CompletionContext as F, ProviderKey as G, mergeReferences as H, CompletionItem as I, CustomField as J, detectAuth as K, CompletionProvider as L, StreamEvent as M, ToolCallDisplay as N, Picked as O, ActiveTrigger as P, ProviderDescriptor as Q, CompletionReference as R, EditDiffDisplay as S, EditOutcomeKind as T, AuthMethod as U, findActiveTrigger as V, ProviderAuth as W, ModelOption as X, ModelInfo as Y, OUTPUT_RESERVE_TOKENS as Z, isEditErrorResult as _, formatToolCall as a, getModelInfo as at, selectableTurnIds as b, splitPromptSegments as c, modelSupportsReasoning as ct, RequestApproval as d, openrouterDescriptor as dt, cerebrasDescriptor as et, SafeModeActions as f, piIdOf as ft, EDIT_TOOL_NAMES as g, useSafeModeQueue as h, displayNameFor as i, getContextWindow as it, Settings as j, Screen as k, ApprovalDecision as l, modelsForDescriptor as lt, useSafeModeActions as m, ToolDisplayMeta as n, effectiveContextWindow as nt, PromptSegment as o, localDescriptor as ot, SafeModeProvider as p, restoreModelOptions as pt, BUILTIN_PROVIDERS as q, ToolFormatLine as r, enabledModelOptions as rt, PromptSegmentRef as s, modelOptionsFor as st, TOOL_DISPLAY as t, credKeyOf as tt, ApprovalRequest as u, openaiDescriptor as ut, isTurnHighlighted as v, EditOutcome as w, turnSelectionOwnership as x, isVisible as y, applyInsert as z };
1471
- //# sourceMappingURL=tool-formatters-5nr1eXPn.d.ts.map
1471
+ //# sourceMappingURL=tool-formatters-BuB31L-c.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-formatters-5nr1eXPn.d.ts","names":[],"sources":["../src/chat/providers.ts","../src/chat/auth.ts","../src/chat/completion-core.ts","../src/chat/types.ts","../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BiB,cAAA;EPiCyB;;;;;EO3BxC,MAAA;EPoC8B;AAQhC;;;;EOtCE,IAAI;AAAA;AAAA,UAGW,eAAA;EP+Cf;;;;;;AAAkF;AAgBpF;;EOrDE,WAAA,aAAwB,KAAA,EAAO,MAAA;EPqDL;;;;;EO/C1B,MAAA,GAAS,KAAA,EAAO,MAAA,sBAA4B,cAAA;AAAA;AAAA,cAOjC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,eAAA;APoDzC;AAGV;;;;;;;;;;;;;;AAHU,iBO4OM,cAAA,CACd,IAAA,UACA,KAAA,GAAQ,MAAM;;;;;;;iBAkBA,cAAA,CAAe,IAAA,UAAc,KAAA,EAAO,MAAA,oBAA0B,cAAc"}
1
+ {"version":3,"file":"tool-formatters-BuB31L-c.d.ts","names":[],"sources":["../src/chat/providers.ts","../src/chat/auth.ts","../src/chat/completion-core.ts","../src/chat/types.ts","../src/chat/turn-selection.ts","../src/chat/safe-mode-context.tsx","../src/chat/prompt-segments.ts","../src/chat/tool-formatters.ts"],"mappings":";;;;;;;;;;;;;;;;;UA8CiB,SAAA;EACf,EAAA;EACA,IAAA;EACA,aAAA;EACA,SAAA;EACA,SAAA;EACA,KAAA;EACA,IAAA;IAAS,KAAA;IAAe,MAAA;IAAgB,SAAA;IAAoB,UAAA;EAAA;EAC5D,QAAA;EA4BkF;AAAA;AAgBpF;;;;;EApCE,OAAA,YAAmB,WAAW;AAAA;;;;;AAgDtB;UAxCO,WAAA;EA2CkB;EAzCjC,EAAA;EAwDe;EAtDf,KAAA;EAqGkB;EAnGlB,WAAA;EAwHuB;;;;;EAlHvB,cAAA;IAAmB,KAAA;IAAgB,MAAA;IAAiB,SAAA;IAAoB,UAAA;EAAA;AAAA;;;;;;;;;;;;;;UAgBzD,WAAA;EAwHI;EAtHnB,GAAA;EA0Hc;EAxHd,KAAA;;EAEA,MAAA;EAsHgD;EApHhD,WAAA;EAyHoB;EAvHpB,IAAA;EAuH2B;EArH3B,QAAA;AAAA;AA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U,gBAAgB;ELgDxC;EK9CA,OAAA;AAAA;;;;;iBAmBc,gBAAA,CAAA;EAAmB;AAAA;EAAc,QAAA,EAAU,SAAS;AAAA,gCAAE,GAAA,CAAA,OAAA;AAAA,iBAuDtD,gBAAA,CAAA,YAA6B,eAAe;AAAA,iBAI5C,kBAAA,CAAA,GAAsB,eAAe;;;;;;;;AL1GrD;;;;;;;;;;;UM7BiB,gBAAA;EACf,KAAA;EACA,GAAA;ENkC4D;EMhC5D,UAAA;AAAA;;;ANyC8B;AAQhC;;;KMxCY,aAAA;EACJ,IAAA;EAAe,IAAA;AAAA;EACf,IAAA;EAAc,IAAA;EAAc,UAAA;AAAA;;;ANkDgD;AAgBpF;;;;;;;;;;;AAYU;AAGV;;;;;;;iBMzDgB,mBAAA,CACd,IAAA,UACA,IAAA,WAAe,gBAAA,KACd,aAAa;;;;;;;;ANbhB;;;;;;;;;;;;UO1BiB,cAAA;EPiCyB;;;;;EO3BxC,MAAA;EPoC8B;AAQhC;;;;EOtCE,IAAI;AAAA;AAAA,UAGW,eAAA;EP+Cf;;;;;;AAAkF;AAgBpF;;EOrDE,WAAA,aAAwB,KAAA,EAAO,MAAA;EPqDL;;;;;EO/C1B,MAAA,GAAS,KAAA,EAAO,MAAA,sBAA4B,cAAA;AAAA;AAAA,cAOjC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,eAAA;APoDzC;AAGV;;;;;;;;;;;;;;AAHU,iBOyPM,cAAA,CACd,IAAA,UACA,KAAA,GAAQ,MAAM;;;;;;;iBAkBA,cAAA,CAAe,IAAA,UAAc,KAAA,EAAO,MAAA,oBAA0B,cAAc"}
@@ -1,4 +1,4 @@
1
- import { b as ToolDef } from "../agent-AnumGPWj.js";
1
+ import { b as ToolDef } from "../agent-Bt123Fdy.js";
2
2
 
3
3
  //#region src/tools/fetch-url.d.ts
4
4
  declare function isBlockedAddress(ip: string): boolean;
@@ -1,4 +1,4 @@
1
- import { b as ToolDef } from "../agent-AnumGPWj.js";
1
+ import { b as ToolDef } from "../agent-Bt123Fdy.js";
2
2
 
3
3
  //#region src/tools/web-search.d.ts
4
4
  declare const webSearch: ToolDef;