agents 0.32.0 → 0.34.0
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.
- package/README.md +1 -1
- package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
- package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
- package/dist/browser/ai.js +2 -3
- package/dist/browser/ai.js.map +1 -1
- package/dist/browser/index.d.ts +33 -21
- package/dist/browser/index.js +937 -4
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tools/ai-sdk.d.ts +4 -4
- package/dist/browser/tools/ai-sdk.js +9 -3
- package/dist/browser/tools/ai-sdk.js.map +1 -1
- package/dist/browser/tools/pi.d.ts +11 -8
- package/dist/browser/tools/pi.js +58 -11
- package/dist/browser/tools/pi.js.map +1 -1
- package/dist/browser/tools/tanstack-ai.d.ts +4 -4
- package/dist/browser/tools/tanstack-ai.js +3 -3
- package/dist/browser/tools/tanstack-ai.js.map +1 -1
- package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
- package/dist/browser-tool-DOqT1oSD.js +360 -0
- package/dist/browser-tool-DOqT1oSD.js.map +1 -0
- package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
- package/dist/capability-DBAKc6UZ.js.map +1 -1
- package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
- package/dist/chat/index.d.ts +37 -6
- package/dist/chat/index.js +39 -3
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.js +1 -0
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +3 -3
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +62 -60
- package/dist/client-CkT8voRY.js +3740 -0
- package/dist/client-CkT8voRY.js.map +1 -0
- package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
- package/dist/connector-Bphz6wIw.js.map +1 -0
- package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
- package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
- package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
- package/dist/experimental/channels/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
- package/dist/harness/ai-sdk/index.d.ts +2 -2
- package/dist/harness/container/index.d.ts +2 -2
- package/dist/harness/container/index.js +1 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/opencode/index.d.ts +1 -1
- package/dist/harness/pi/index.d.ts +200 -37
- package/dist/harness/pi/index.js +202 -100
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/harness/think/index.d.ts +2 -2
- package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
- package/dist/images-D4gtE06D.js.map +1 -0
- package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
- package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
- package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
- package/dist/index.d.ts +21 -21
- package/dist/index.js +2 -2
- package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
- package/dist/input-schema-D6GilRXI.js.map +1 -0
- package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
- package/dist/input-schema-y8W5bOdM.js.map +1 -0
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
- package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +45 -2
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +42 -36
- package/dist/mcp/client/index.js +2 -2
- package/dist/mcp/index.d.ts +16 -16
- package/dist/mcp/index.js +2 -2
- package/dist/models/ai-sdk/index.d.ts +9 -5
- package/dist/models/ai-sdk/index.js +1 -1
- package/dist/models/opencode/index.d.ts +3 -3
- package/dist/models/opencode/index.js +2 -2
- package/dist/models/opencode/index.js.map +1 -1
- package/dist/models/pi-ai/index.d.ts +4 -4
- package/dist/models/pi-ai/index.js +64 -170
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
- package/dist/queue-B_wl6K0Z.js.map +1 -0
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
- package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
- package/dist/scheduler-DGNEmxQR.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
- package/dist/session-CRY0bGiI.js.map +1 -0
- package/dist/sessions/index.d.ts +1 -1
- package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
- package/dist/settings-D2F_qONv.js.map +1 -0
- package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
- package/dist/src-BO1FdLK1.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
- package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
- package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
- package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
- package/dist/tool-CmAGY6Fo.js.map +1 -0
- package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
- package/dist/tool-Kxcj8_22.js.map +1 -0
- package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
- package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
- package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
- package/dist/voice/index.d.ts +2 -2
- package/dist/web/fetch/index.js +1 -1
- package/dist/web/fetch/tools/ai-sdk.js +2 -2
- package/dist/web/fetch/tools/pi.d.ts +9 -7
- package/dist/web/fetch/tools/pi.js +31 -7
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/fetch/tools/tanstack-ai.js +2 -2
- package/dist/web/search/index.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +2 -2
- package/dist/web/search/tools/pi.d.ts +9 -4
- package/dist/web/search/tools/pi.js +27 -11
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +2 -2
- package/dist/websockets/index.d.ts +2 -2
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
- package/dist/websockets-W4uhRg4-.js.map +1 -0
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/agent-class.md +30 -4
- package/docs/browse-the-web.md +50 -3
- package/docs/chat-agents.md +13 -10
- package/docs/client-tools-continuation.md +1 -1
- package/docs/codemode.md +1 -1
- package/docs/configuration.md +6 -3
- package/docs/cross-domain-authentication.md +1 -1
- package/docs/fetch-the-web.md +20 -0
- package/docs/harnesses/pi.md +242 -33
- package/docs/harnesses/think.md +1 -1
- package/docs/http-websockets.md +40 -32
- package/docs/human-in-the-loop.md +2 -2
- package/docs/lifecycle.md +56 -0
- package/docs/mcp-client.md +104 -7
- package/docs/models-pi-ai.md +24 -10
- package/docs/models.md +42 -17
- package/docs/resumable-streaming.md +1 -1
- package/docs/retries.md +3 -6
- package/docs/search-the-web.md +10 -0
- package/docs/voice.md +1 -1
- package/package.json +16 -9
- package/dist/ai-sdk-Kon40i0q.js.map +0 -1
- package/dist/browser-1eUbPvC2.js +0 -931
- package/dist/browser-1eUbPvC2.js.map +0 -1
- package/dist/browser-tool-DRan7Lk6.js +0 -497
- package/dist/browser-tool-DRan7Lk6.js.map +0 -1
- package/dist/client-DMWujQJ1.js +0 -2325
- package/dist/client-DMWujQJ1.js.map +0 -1
- package/dist/connector-CM-uuxKM.js.map +0 -1
- package/dist/images-CfuRCjwq.js.map +0 -1
- package/dist/input-schema-B0Etuo-o.js.map +0 -1
- package/dist/input-schema-BQykTEp_.js.map +0 -1
- package/dist/lifecycle-v1rKHV2C.js.map +0 -1
- package/dist/queue-CcIjVYTE.js.map +0 -1
- package/dist/scheduler-FIHv2-kJ.js.map +0 -1
- package/dist/session-7CDgVE0z.js.map +0 -1
- package/dist/settings-Dk2il2Hf.js.map +0 -1
- package/dist/src-DoGNJ4Ud.js.map +0 -1
- package/dist/tool-CxKsvxjm.js.map +0 -1
- package/dist/tool-DkT_DJBm.js.map +0 -1
- package/dist/websockets-C6SJtWCJ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["exhaustive"],"sources":["../../../src/harness/pi/session-store.ts","../../../src/harness/pi/harness.ts","../../../src/harness/pi/skills.ts"],"sourcesContent":["import type { SqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite\";\nimport { openDurableObjectSqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite/cloudflare\";\n\n/**\n * pi's session store on a Durable Object's SQLite database.\n *\n * pi owns its sessions: conversations, entries, tasks, submissions, and\n * documents live in pi's own schema, created and migrated by pi's portable\n * `SqliteStorage` through pi's own Durable Object adapter. The store keeps\n * pi's tables under a prefix, so they cannot collide with the SDK's or the\n * host's tables in the same object.\n *\n * It is the Durable Object counterpart of `agents/sessions` for a harness\n * that brings its own session model, and has nothing pi-harness specific in\n * it: any harness built on pi-durable can open its storage with it.\n */\nexport type PiSessionStoreOptions = {\n /**\n * Prefix for every table and index pi creates. Must not start with `_cf_`,\n * which Durable Objects reserve. Default `pi_`.\n */\n readonly prefix?: string;\n};\n\nconst DEFAULT_PREFIX = \"pi_\";\n\n/** Open pi-durable's storage over this object's SQLite database. */\nexport function openPiSessionStore(\n storage: DurableObjectStorage,\n options: PiSessionStoreOptions = {}\n): Promise<SqliteStorage> {\n const prefix = options.prefix ?? DEFAULT_PREFIX;\n // pi validates the prefix as a SQLite identifier; Durable Objects also\n // reserve `_cf_` in any case, which pi does not know about.\n if (prefix.toLowerCase().startsWith(\"_cf_\")) {\n return Promise.reject(\n new Error(\"The pi session store prefix must not start with _cf_\")\n );\n }\n return openDurableObjectSqliteStorage(storage, { prefix });\n}\n","import type { Api, Model, ModelThinkingLevel } from \"@earendil-works/pi-ai\";\nimport {\n LiveDoc,\n ROOT_CONVERSATION_ID,\n watchEvents,\n type AgentEventStream,\n type Conversation,\n type ConversationId,\n type AgentChange,\n type EntryRecord,\n type Harness,\n type HarnessInspection,\n type ModelRef,\n type SettledSubmissionRecord,\n type TaskId,\n type UserInput,\n type Wake\n} from \"@earendil-works/pi-durable\";\nimport type { SqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite\";\nimport {\n LifecycleCapability,\n type CapabilityStartContext,\n type LifecycleJobContext,\n type LifecycleJobOutcome\n} from \"../../lifecycle\";\nimport { isDurableObjectMemoryLimitReset } from \"../../retries\";\nimport {\n BACKGROUND_CONTEXT,\n withAbortSignal,\n type Context\n} from \"@earendil-works/chord/context\";\nimport { openPiSessionStore } from \"./session-store\";\nimport type {\n PiOperationResult,\n PiPendingOperation,\n PiPromptResponse,\n PiReceipt,\n PiSessionId,\n PiSessionInfo,\n PiSessionOptions,\n PiSubmitOptions\n} from \"./types\";\n\nconst BG = BACKGROUND_CONTEXT;\n\n/** The root session's id. */\nexport const ROOT_SESSION: PiSessionId = String(ROOT_CONVERSATION_ID);\n\n/**\n * The wake timings. They suit a real deployment; only tests change them,\n * with `setWakeTimingForTests`, so a suite does not sit on the real\n * heartbeat.\n *\n * Longest one wake waits on pi. It waits inside an alarm invocation, which\n * has a 15 minute wall-time limit, so a longer run is waited on across\n * several alarms.\n */\nconst WAIT_BUDGET_MS = 10 * 60_000;\n\n/**\n * The wake job's heartbeat while it waits, and how often it re-checks work\n * it cannot wait on, such as background tasks. If the object is evicted, the\n * job is still due and its alarm restarts the object.\n */\nconst HEARTBEAT_MS = 30_000;\n\n/**\n * How often a wait re-reads `pi.wake()` when the factory did not pass\n * `onWake`, so nothing tells the harness when it changes.\n */\nconst POLL_MS = 1_000;\n\n/**\n * The longest a wake job whose dispatch keeps failing waits before it tries\n * again. Its delay starts at the heartbeat and doubles up to this.\n */\nconst MAX_WAKE_BACKOFF_MS = 10 * 60_000;\n\n/**\n * Wake dispatches that failed in a row. Stored, so the backoff holds across\n * restarts, and outside the job: a push that saved it in the job's payload\n * could overwrite a submit's due-now push.\n */\nconst WAKE_ERRORS_KEY = \"pi-harness:wake-errors\";\n\nlet setWakeTiming: (harness: PiHarness, timing: WakeTiming) => void;\n\n/**\n * @internal Shorten a harness's wake timings, so a test suite does not sit\n * on the real heartbeat. Not exported from `agents/harness/pi`.\n */\nexport function setWakeTimingForTests(\n harness: PiHarness,\n timing: WakeTiming\n): void {\n setWakeTiming(harness, timing);\n}\n\nconst WAKE_FN = \"wake\";\n\n/**\n * The one wake job. Before Pi 1.4 there was one per session, with ids\n * `pi-wake:<session>`; a left-over one hands over to this one.\n */\nconst WAKE_JOB_ID = \"pi-wake\";\n\n/**\n * What the factory is handed: the things only the harness can build.\n * Everything else `Harness.open` takes (models, registry, settings, env,\n * onReport) the factory builds itself.\n */\nexport type PiHarnessContext = {\n /** pi's storage over this object's SQLite, its migrations already run. */\n readonly storage: SqliteStorage;\n /** Background context, for the open itself. */\n readonly context: Context;\n /**\n * Pass this to `Harness.open` as its `onWake` option. pi calls it when it\n * next needs to run, and the harness sets this object's alarm for then.\n *\n * With it, pi sets no in-memory timer for a sleeping task (a retry\n * backoff, a poll, a `sleepUntil`), so the object can hibernate until the\n * alarm. Without it the harness still works, but pi's timer keeps the\n * object in memory, and billed, while a task sleeps, and the harness logs\n * a warning when it opens pi.\n *\n * The harness reads pi's wake times against `Date.now()`, so do not pass\n * `now` to `Harness.open`.\n */\n readonly onWake: (wake: Wake) => void;\n};\n\n/**\n * Opens pi's `Harness`. The harness adopts what it returns. Pass `onWake`\n * through to `Harness.open`.\n *\n * ```ts\n * harness: async ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install(await skills(sources));\n * return Harness.open(storage, { models, registry, onWake }, context);\n * }\n * ```\n */\nexport type PiHarnessFactory = (\n context: PiHarnessContext\n) => Harness | Promise<Harness>;\n\n/**\n * A model, as pi-ai describes one: `createAI`'s `ai(\"@cf/…\")` returns one.\n *\n * Only its `provider` and `id` are used. pi stores that reference with\n * the session and resolves it, at each request, against the `Models` the\n * factory opened pi with. So the model must be one those `Models` list,\n * and options passed to `ai(id, options)` here, such as `fallback`, are not\n * applied.\n */\nexport type PiModel = Pick<Model<Api>, \"provider\" | \"id\">;\n\n/**\n * Applied to a session the first time it is created. Without a model, a\n * session's generation fails as unanswered until `session.setModel` sets one.\n */\nexport type PiSessionDefaults = {\n /**\n * Model for new sessions, by its `provider` and `id`; it must be on the\n * `Models` the factory opens pi with (see `PiModel`). Change one\n * session's with `session.setModel`.\n */\n readonly model?: PiModel;\n readonly thinkingLevel?: ModelThinkingLevel;\n};\n\n/** How long the wake waits on pi, and how often it checks. */\ntype WakeTiming = {\n /** Longest one wake waits inside an alarm. Default 600_000. */\n readonly waitBudgetMs?: number;\n /** Heartbeat while waiting. Default 30_000. */\n readonly heartbeatMs?: number;\n /** How often a wait re-reads `pi.wake()` without `onWake`. Default 1_000. */\n readonly pollMs?: number;\n};\n\n/** `PiHarness`'s options. Only `harness`, which opens pi, is required. */\nexport type PiHarnessOptions = {\n /** Opens pi's `Harness` over the storage this object prepared. */\n readonly harness: PiHarnessFactory;\n /** What a new session starts with. */\n readonly defaults?: PiSessionDefaults;\n};\n\ntype Opened = {\n readonly pi: Harness;\n readonly storage: SqliteStorage;\n};\n\n/** pi-durable's stored reference to a pi-ai model. */\nfunction modelRef(model: PiModel): ModelRef {\n return { provider: model.provider, modelId: model.id };\n}\n\nfunction conversationId(session: PiSessionId): ConversationId {\n const id = Number(session);\n if (!Number.isSafeInteger(id) || id < 1) {\n throw new Error(`Invalid pi session ${JSON.stringify(session)}`);\n }\n return id as ConversationId;\n}\n\n/** The text of an assistant entry, for an operation's result. */\nfunction assistantText(entry: EntryRecord | undefined): string {\n const message = entry?.model?.[0];\n if (message?.role !== \"assistant\") return \"\";\n return message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\"\");\n}\n\nfunction signalContext(signal: AbortSignal | undefined): Context {\n return signal ? withAbortSignal(signal, BG) : BG;\n}\n\n/**\n * pi-durable hosted in a Durable Object, behind a small harness interface:\n * `harness.prompt()`, `harness.sessions`, `harness.session(id)`. How a session reaches a\n * client (sockets, SSE, RPC) is the host's glue, built on `session.events()`.\n *\n * pi owns everything about a run: the transcript, the inbox of steers and\n * follow-ups, generation and tool tasks, retries, crash recovery, and the\n * live view. It keeps all of it in its own tables in this object's SQLite\n * database (see `session-store.ts`).\n *\n * What pi cannot do on a Durable Object is wake itself: its scheduler runs\n * in memory, and an evicted object has no memory. The harness is that wake,\n * with one Lifecycle job driven by `pi.wake()`. Input goes to pi once, in\n * `submit()`, after the job is scheduled. While pi has work running, the\n * job waits on it, rescheduling itself as a heartbeat. While pi's tasks\n * sleep, the job is due when the first one wakes; pi tells the harness\n * through the `onWake` the factory passes to `Harness.open`. When pi has\n * nothing to do, the job completes. An eviction mid-run leaves the job due,\n * so its alarm restarts the object, pi reopens and resumes its own tasks,\n * and the job waits again.\n */\nexport class PiHarness extends LifecycleCapability {\n readonly sessions: PiSessions;\n readonly #options: PiHarnessOptions;\n /** The in-memory wait on pi's running work, inside an alarm's work. */\n #waiting: Promise<void> | undefined;\n /** Resolves the current wait's sleep early: `pi.wake()` changed. */\n #changed: (() => void) | undefined;\n /** Submissions between their wake and pi's admission. */\n #admitting = 0;\n /** Whether pi has called `onWake`, so the factory passed it. */\n #onWakeWired = false;\n #waitBudgetMs = WAIT_BUDGET_MS;\n #heartbeatMs = HEARTBEAT_MS;\n #pollMs = POLL_MS;\n #opening: Promise<Opened> | undefined;\n /** Settles once the last pi that closed on its own has closed. */\n #lastClose: Promise<unknown> = Promise.resolve();\n /** Every pi that has begun closing, on its own or by `dispose()`. */\n readonly #closing = new WeakSet<Harness>();\n\n static {\n setWakeTiming = (harness, timing) => harness.#setWakeTiming(timing);\n }\n\n constructor(options: PiHarnessOptions) {\n super(\"pi-harness\");\n this.#options = options;\n this.sessions = new PiSessions(this);\n }\n\n #setWakeTiming(timing: WakeTiming): void {\n for (const [name, value] of Object.entries(timing)) {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`PiHarness timing.${name} must be a positive number`);\n }\n }\n this.#waitBudgetMs = timing.waitBudgetMs ?? this.#waitBudgetMs;\n this.#heartbeatMs = timing.heartbeatMs ?? this.#heartbeatMs;\n this.#pollMs = timing.pollMs ?? this.#pollMs;\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────\n\n override async onStart(_context: CapabilityStartContext): Promise<void> {\n await this.#open();\n }\n\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n if (context.job.fn !== WAKE_FN) return;\n let outcome: LifecycleJobOutcome;\n if (context.job.id !== WAKE_JOB_ID) {\n // A per-session wake from before Pi 1.4: hand over to the one wake.\n await this.#wake();\n outcome = undefined;\n } else {\n outcome = await this.#wakeStep();\n }\n // It got through, so a failing wake's backoff starts over.\n const kv = this.lifecycle.storage.kv;\n if (kv.get(WAKE_ERRORS_KEY) !== undefined) kv.delete(WAKE_ERRORS_KEY);\n return outcome;\n }\n\n /**\n * A wake dispatch that failed through Lifecycle's retries, as when pi\n * cannot be opened. Lifecycle would complete the job, and pi's work would\n * never be woken again, so try again later: at the heartbeat, doubling\n * while the failures continue, up to 10 minutes.\n */\n onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): LifecycleJobOutcome | void {\n if (context.job.fn !== WAKE_FN) return;\n console.error(\n `pi wake job \"${context.job.id}\" failed after ${context.attempt} ` +\n \"attempts; retrying with backoff\",\n error\n );\n this.#wakeError(error);\n const kv = this.lifecycle.storage.kv;\n const errors = (kv.get<number>(WAKE_ERRORS_KEY) ?? 0) + 1;\n kv.put(WAKE_ERRORS_KEY, errors);\n const delay = Math.min(\n this.#heartbeatMs * 2 ** (errors - 1),\n MAX_WAKE_BACKOFF_MS\n );\n return { rescheduleAt: Date.now() + delay };\n }\n\n /** Close pi's in-memory resources. Durable state is untouched. */\n async dispose(): Promise<void> {\n const opening = this.#opening;\n this.#opening = undefined;\n const opened = await opening?.catch(() => undefined);\n // Closing calls #piClosing, which also ends a wait sleeping on this pi.\n await opened?.pi.close(BG);\n }\n\n // ── The harness interface ────────────────────────────────────────────────\n\n /** A handle on one session. No I/O until you call it. */\n session(id: PiSessionId = ROOT_SESSION): PiSession {\n return new PiSession(this, id);\n }\n\n /** Submit a prompt and wait for its answer. */\n prompt(\n input: UserInput,\n options: PiSubmitOptions = {}\n ): Promise<PiPromptResponse> {\n return this.session(options.session).prompt(input, options);\n }\n\n /** Durably submit a prompt. Resolves before the model runs. */\n submit(input: UserInput, options: PiSubmitOptions = {}): Promise<PiReceipt> {\n return this.session(options.session).submit(input, options);\n }\n\n /** Stop one operation, or everything running in a session. */\n abort(\n options: PiSessionOptions & { readonly operationId?: string } = {}\n ): Promise<boolean> {\n return this.session(options.session).abort(options.operationId);\n }\n\n /**\n * Run again the tasks pi's crash-loop guard parked in a session's work.\n * False when nothing was parked.\n */\n retry(options: PiSessionOptions = {}): Promise<boolean> {\n return this.session(options.session).retry();\n }\n\n wait(\n operationId: string,\n options: PiSessionOptions & { readonly signal?: AbortSignal } = {}\n ): Promise<PiOperationResult> {\n return this.session(options.session).wait(operationId, options.signal);\n }\n\n /** The session's active transcript, as pi's entries. */\n messages(options: PiSessionOptions = {}): Promise<EntryRecord[]> {\n return this.session(options.session).messages();\n }\n\n /** Submissions pi has not settled yet, oldest first. */\n async pending(options: PiSessionOptions = {}): Promise<PiPendingOperation[]> {\n const { pi } = await this.#open();\n const id =\n options.session === undefined\n ? undefined\n : conversationId(options.session);\n const inspection = await pi.inspect(BG);\n const parked = await this.#parked(inspection);\n return inspection.submissions.flatMap((record): PiPendingOperation[] => {\n if (record.requestId === undefined) return [];\n if (id !== undefined && record.conversationId !== id) return [];\n let status: PiPendingOperation[\"status\"];\n switch (record.status) {\n case \"queued\":\n status = \"queued\";\n break;\n case \"placed\":\n status = parked.some((task) =>\n task.sessions.has(record.conversationId)\n )\n ? \"parked\"\n : \"running\";\n break;\n case \"done\":\n case \"unanswered\":\n // Settled. pi's inspection holds only unsettled submissions.\n return [];\n default: {\n // A status added by a newer pi: decide what it reports.\n const exhaustive: never = record;\n return exhaustive;\n }\n }\n return [\n {\n operationId: record.requestId,\n session: String(record.conversationId),\n status\n }\n ];\n });\n }\n\n /** The opened pi Harness, for anything the interface does not cover. */\n async pi(): Promise<Harness> {\n return (await this.#open()).pi;\n }\n\n // ── Used by PiSession and PiSessions ─────────────────────────────────────\n\n /** @internal */\n async conversation(session: PiSessionId): Promise<Conversation> {\n const { pi } = await this.#open();\n const conversation = await pi.conversation(conversationId(session), BG);\n if (!conversation) throw new Error(`Unknown pi session ${session}`);\n return conversation;\n }\n\n /** @internal */\n async storage(): Promise<SqliteStorage> {\n return (await this.#open()).storage;\n }\n\n /** @internal */\n async enqueue(\n session: PiSessionId,\n input: UserInput,\n options: PiSubmitOptions\n ): Promise<PiReceipt> {\n const operationId = options.operationId ?? crypto.randomUUID();\n const { storage } = await this.#open();\n const conversation = await this.conversation(session);\n const accepted = await this.#admit(async () => {\n // The one admission. pi deduplicates by request id.\n const accepted =\n (await storage.submissionByRequest(\n conversation.id,\n operationId,\n BG\n )) === undefined;\n await conversation.submit(\n {\n type: \"input\",\n content: input,\n whenBusy: options.whenBusy ?? \"followUp\",\n requestId: operationId,\n ...(options.entry ? { entry: options.entry } : {})\n },\n BG\n );\n return accepted;\n });\n return { operationId, session, accepted };\n }\n\n /** @internal Run again the tasks pi's restart limit parked in a session. */\n async retryParked(session: PiSessionId): Promise<boolean> {\n const { pi } = await this.#open();\n const id = conversationId(session);\n const parked = (await this.#parked(await pi.inspect(BG))).filter((task) =>\n task.sessions.has(id)\n );\n if (parked.length === 0) return false;\n await this.#admit(async () => {\n for (const task of parked) await pi.retryTask(task.id, BG);\n });\n return true;\n }\n\n /** @internal Withdraw a queued input, or abort the run it joined. */\n async withdraw(session: PiSessionId, operationId: string): Promise<boolean> {\n const { pi, storage } = await this.#open();\n const id = conversationId(session);\n const record = await storage.submissionByRequest(id, operationId, BG);\n if (!record || record.status === \"done\" || record.status === \"unanswered\") {\n return false;\n }\n const outcome = await pi.abortSubmission(record.id, BG, id);\n switch (outcome) {\n case \"aborted\":\n return true;\n case \"already_placed\":\n await (await pi.conversation(id, BG))?.abort(BG);\n return true;\n case \"settled\":\n case \"not_found\":\n return false;\n default: {\n // An outcome added by a newer pi: decide whether it withdrew.\n const exhaustive: never = outcome;\n return exhaustive;\n }\n }\n }\n\n /** @internal Wait for pi to settle an operation, by its request id. */\n async settled(\n session: PiSessionId,\n operationId: string,\n signal?: AbortSignal\n ): Promise<PiOperationResult> {\n const conversation = await this.conversation(session);\n const context = signalContext(signal);\n const submission = await this.#findSubmission(\n conversation.id,\n operationId,\n context\n );\n if (!submission) {\n return {\n operationId,\n session,\n status: \"unanswered\",\n reason: \"not_found\"\n };\n }\n return this.#result(\n session,\n operationId,\n await submission.wait(context),\n context\n );\n }\n\n // ── The wake ─────────────────────────────────────────────────────────────\n\n /**\n * Hand pi work inside the wake. The wake is scheduled first, so if the\n * object dies after pi has the work, that job restarts it; while `hand`\n * is in flight the step will not complete. The wake steps again after, so\n * it sees the work even if it just completed.\n */\n async #admit<T>(hand: () => Promise<T>): Promise<T> {\n this.#admitting++;\n let result: T;\n try {\n await this.#wake();\n result = await hand();\n } finally {\n this.#admitting--;\n }\n await this.#wake();\n return result;\n }\n\n /** Schedule the wake job now, or at `time`. */\n #wake(time = Date.now()): Promise<unknown> {\n // A push made while the job is dispatching supersedes that dispatch's\n // outcome, so a submit is never lost to a wake that is completing.\n return this.lifecycle.jobs.push({\n id: WAKE_JOB_ID,\n fn: WAKE_FN,\n time,\n singleflight: true,\n recoveryLoop: true\n });\n }\n\n /** Schedule the wake job for what `pi.wake()` says, if pi needs one. */\n async #wakeFor(wake: Wake): Promise<void> {\n if (wake.active) await this.#wake();\n else if (wake.at !== undefined) await this.#wake(wake.at);\n }\n\n /**\n * pi's `onWake`, handed to the factory. pi calls it after open and\n * whenever `pi.wake()` changes. It must not block, so the job push is\n * left running.\n */\n readonly #onWake = (wake: Wake): void => {\n this.#onWakeWired = true;\n this.#changed?.();\n // A running wait re-reads pi.wake() and steps again when it ends.\n if (this.#waiting) return;\n this.#wakeFor(wake).catch((error: unknown) => this.#wakeError(error));\n };\n\n /**\n * One run of the wake job. It never admits or replays anything: it reads\n * `pi.wake()`, which is all of pi's sessions at once. Running work is\n * waited on; a sleep reschedules the job for when it ends; no work\n * completes the job. pi does all the work in between.\n */\n async #wakeStep(): Promise<LifecycleJobOutcome> {\n const heartbeat = { rescheduleAt: Date.now() + this.#heartbeatMs };\n if (this.#waiting) return heartbeat;\n const { pi } = await this.#open();\n // The alarm may be for a sleeping task: make due ones runnable.\n pi.resume();\n const wake = pi.wake();\n if (wake.active) {\n const wait = this.#waitWhileActive(pi).then(\n (ended) => {\n this.#waiting = undefined;\n // Step again now: pi may be sleeping, or have nothing left. After\n // a failed wait, as when pi's Session fails, the heartbeat that is\n // already due steps instead, so a pi that keeps failing is not\n // reopened in a loop.\n if (ended) void this.#wake();\n },\n (error: unknown) => {\n // A memory-limit reset: the alarm's breaker backs the job off.\n this.#waiting = undefined;\n throw error;\n }\n );\n this.#waiting = wait;\n // The wait runs past this dispatch, inside the alarm's work, so the\n // object stays alive for it, and a memory-limit reset it ends with\n // counts against the alarm's breaker. The heartbeat covers an\n // eviction.\n if (!this.lifecycle.trackAlarmWork(wait)) wait.catch(() => {});\n return heartbeat;\n }\n // A submit between its wake and pi's admission: check again later.\n if (this.#admitting > 0) return heartbeat;\n if (wake.at !== undefined) return { rescheduleAt: wake.at };\n // Nothing to do. A task parked by pi's restart limit is not work: it\n // waits for `retry()`.\n return undefined;\n }\n\n /**\n * Wait while pi has work running, up to the wait budget. With `onWake`, a\n * change ends each sleep early, and so does pi closing; without it, the\n * sleep is `pollMs`. A task sleeping beside the running work, such as a\n * retry backoff, also ends the sleep when it is due, and the wait calls\n * `pi.resume()` to run it: with `onWake`, pi arms no timer for it, and\n * the wake job's alarm is not set for it while the job waits. Whether the\n * wait ended, with pi idle or at the budget, rather than failing. Rejects\n * with a memory-limit reset.\n */\n async #waitWhileActive(pi: Harness): Promise<boolean> {\n const deadline = Date.now() + this.#waitBudgetMs;\n try {\n // Once pi begins closing, pi.wake() throws (SessionFailed after a\n // storage error), which is what ends this loop: a closed pi's wake does\n // not go inactive. Closing kicks `#changed` only so the loop reads it\n // again now rather than at the end of its sleep.\n let wake = pi.wake();\n while (wake.active) {\n const now = Date.now();\n const left = deadline - now;\n if (left <= 0) return true;\n let sleep = this.#onWakeWired ? left : Math.min(left, this.#pollMs);\n // `at` is a sleep not yet due on pi's clock, so this is positive.\n // That holds because pi keeps its default clock, `Date.now`; see\n // `PiHarnessContext`.\n if (wake.at !== undefined) sleep = Math.min(sleep, wake.at - now);\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, sleep);\n this.#changed = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n this.#changed = undefined;\n // A sleep beside the running work came due: make it runnable.\n if (wake.at !== undefined && Date.now() >= wake.at) pi.resume();\n wake = pi.wake();\n }\n return true;\n } catch (error) {\n // A pi that began closing is expected to throw; it is no longer the\n // harness's pi, and Pi reports a failure itself (`session_failed`).\n if (!this.#closing.has(pi)) this.#wakeError(error);\n // Only Lifecycle's alarm breaker can act on a memory-limit reset,\n // including one that failed pi's Session (SessionFailed's cause).\n if (isDurableObjectMemoryLimitReset(error)) throw error;\n return false;\n }\n }\n\n #wakeError(error: unknown): void {\n this.lifecycle.events.emit(\"pi:wake_error\", {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n\n // ── pi ───────────────────────────────────────────────────────────────────\n\n /**\n * pi, opened. Waits for Lifecycle startup first, so pi is only ever\n * opened inside it: startup holds the input gate (`blockConcurrencyWhile`)\n * and awaits the open in `onStart`, so an open begun before startup would\n * be awaited behind a closed gate, with its timers and I/O held back, and\n * never finish.\n *\n * pi stays open until `dispose()`, or until it closes on its own: any\n * storage error fails pi's Session for good. Then the next call, or the\n * wake job's next step, opens pi again once the failed pi has closed, and\n * pi recovers from what it had committed. Closing waits for running task\n * code to return, so code that ignores its abort signal delays the reopen.\n * An open that fails is not kept either, so the next call tries again.\n */\n async #open(): Promise<Opened> {\n await this.lifecycle.ready();\n if (this.#opening === undefined) {\n const opening: Promise<Opened> = this.#doOpen((pi, closed) =>\n this.#piClosing(opening, pi, closed)\n ).catch((error: unknown) => {\n if (this.#opening === opening) this.#opening = undefined;\n throw error;\n });\n this.#opening = opening;\n }\n return this.#opening;\n }\n\n async #doOpen(\n onClose: (pi: Harness, closed: Promise<unknown>) => void\n ): Promise<Opened> {\n // A pi that closed on its own closes its storage last, after its tasks\n // have returned; let it finish before another opens over the same\n // database.\n await this.#lastClose;\n const storage = await openPiSessionStore(this.lifecycle.storage);\n const pi = await this.#options.harness({\n storage,\n context: BG,\n onWake: this.#onWake\n });\n try {\n const closed = pi.closed;\n // Called synchronously when pi begins closing, unlike `closed`, so a\n // closed pi is never handed out. It must not call pi.\n pi.subscribeClose(() => onClose(pi, closed));\n await pi.root(BG, { agent: this.agentDefaults() });\n // Continue whatever the last pi left, in this isolate or the last one:\n // pi reconciles tasks that were running to pending and schedules them\n // again.\n pi.resume();\n // pi calls onWake right after open, from a microtask.\n await new Promise((resolve) => setTimeout(resolve, 0));\n if (!this.#onWakeWired) {\n console.warn(\n \"PiHarness: the harness factory did not pass onWake to Harness.open, \" +\n \"so pi's timers keep this Durable Object in memory while a task \" +\n \"sleeps. Pass it: harness: ({ storage, context, onWake }) => \" +\n \"Harness.open(storage, { ...options, onWake }, context)\"\n );\n }\n // Whatever the last pi left gets a wake, including work whose wake\n // failed out. With `onWake`, pi has already said so; this covers a\n // factory without it. The job id is fixed, so this is idempotent.\n await this.#wakeFor(pi.wake());\n } catch (error) {\n // pi is open and running its tasks: close it, so the next open does\n // not start a second pi over the same database beside it.\n pi.close(BG).catch(() => {});\n throw error;\n }\n return { pi, storage };\n }\n\n /**\n * pi began closing: on its own, as a storage error makes it, or by\n * `dispose()`.\n */\n #piClosing(\n opening: Promise<Opened>,\n pi: Harness,\n closed: Promise<unknown>\n ): void {\n this.#closing.add(pi);\n // End a wait sleeping on this pi now: pi will not call onWake again.\n this.#changed?.();\n // `dispose()` took its pi out of `#opening` already, and an open begun\n // since must stay.\n if (this.#opening !== opening) return;\n // Drop it, so the next call opens pi again once this one has closed.\n this.#opening = undefined;\n this.#lastClose = closed;\n }\n\n /** @internal The per-conversation defaults supported by pi-durable. */\n agentDefaults(): AgentChange {\n const defaults = this.#options.defaults;\n return {\n ...(defaults?.model === undefined\n ? {}\n : { model: modelRef(defaults.model) }),\n ...(defaults?.thinkingLevel === undefined\n ? {}\n : { thinkingLevel: defaults.thinkingLevel })\n };\n }\n\n /**\n * Tasks pi's restart limit parked, each with the sessions whose work it\n * is: its own, and every session that owns that one, such as the session\n * of a tool that started a subagent.\n */\n async #parked(\n inspection: HarnessInspection\n ): Promise<{ id: TaskId; sessions: Set<ConversationId> }[]> {\n const { storage } = await this.#open();\n const parked: { id: TaskId; sessions: Set<ConversationId> }[] = [];\n for (const { record, state } of inspection.tasks) {\n if (state.kind !== \"blocked\" || state.reason !== \"restart_limit\") {\n continue;\n }\n const sessions = new Set<ConversationId>();\n let id: ConversationId | undefined = record.conversationId;\n while (id !== undefined && !sessions.has(id)) {\n sessions.add(id);\n id = (await storage.conversation(id, BG))?.owner?.conversationId;\n }\n parked.push({ id: record.id, sessions });\n }\n return parked;\n }\n\n async #findSubmission(\n id: ConversationId,\n operationId: string,\n context: Context\n ) {\n const { pi, storage } = await this.#open();\n // Read from pi's storage: the Harness only reacquires submissions by id.\n const record = await storage.submissionByRequest(id, operationId, context);\n return record ? pi.submission(record.id, context) : undefined;\n }\n\n async #result(\n session: PiSessionId,\n operationId: string,\n settled: SettledSubmissionRecord,\n context: Context\n ): Promise<PiOperationResult> {\n if (settled.status === \"unanswered\") {\n return {\n operationId,\n session,\n status: \"unanswered\",\n reason: settled.reason\n };\n }\n if (settled.type !== \"input\")\n return { operationId, session, status: \"done\" };\n const conversation = await this.conversation(session);\n const page = await conversation.entries(\n { minEntryId: settled.answer, maxEntryId: settled.answer },\n 1,\n undefined,\n context\n );\n return {\n operationId,\n session,\n status: \"done\",\n text: assistantText(page.items[0])\n };\n }\n}\n\n/** One pi conversation, addressed through the harness. */\nexport class PiSession {\n readonly #harness: PiHarness;\n readonly id: PiSessionId;\n\n constructor(harness: PiHarness, id: PiSessionId) {\n this.#harness = harness;\n this.id = id;\n }\n\n /** Durably submit a prompt. Resolves before the model runs. */\n submit(input: UserInput, options: PiSubmitOptions = {}): Promise<PiReceipt> {\n return this.#harness.enqueue(this.id, input, options);\n }\n\n /** Submit and wait for the answer and the updated transcript. */\n async prompt(\n input: UserInput,\n options: PiSubmitOptions = {}\n ): Promise<PiPromptResponse> {\n const receipt = await this.submit(input, options);\n const result = await this.wait(receipt.operationId);\n return { ...result, messages: await this.messages() };\n }\n\n /** Join the running work after its current tool round. */\n steer(input: UserInput, options: Omit<PiSubmitOptions, \"whenBusy\"> = {}) {\n return this.submit(input, { ...options, whenBusy: \"steer\" });\n }\n\n /** Wait for an operation to settle. Aborting `signal` stops only the wait. */\n wait(operationId: string, signal?: AbortSignal): Promise<PiOperationResult> {\n return this.#harness.settled(this.id, operationId, signal);\n }\n\n /**\n * Withdraw one queued operation (or abort the run it joined), or, with no\n * id, abort the session: pi withdraws queued inputs and aborts the\n * running work.\n */\n async abort(operationId?: string): Promise<boolean> {\n if (operationId !== undefined) {\n return this.#harness.withdraw(this.id, operationId);\n }\n const conversation = await this.#harness.conversation(this.id);\n await conversation.abort(BG);\n return true;\n }\n\n /**\n * Run again the tasks pi's crash-loop guard (`settings.restartLimit`)\n * parked in this session's work, including subagent sessions it owns.\n * False when nothing was parked.\n */\n retry(): Promise<boolean> {\n return this.#harness.retryParked(this.id);\n }\n\n /** Start a new context, optionally from a handoff note. */\n async reset(handoff?: string): Promise<void> {\n await (await this.#harness.conversation(this.id)).reset(handoff, BG);\n }\n\n /**\n * Change this session's model, by its `provider` and `id`; it must be on\n * the `Models` the factory opened pi with (see `PiModel`).\n */\n async setModel(model: PiModel): Promise<void> {\n await (\n await this.#harness.conversation(this.id)\n ).configure({ model: modelRef(model) }, BG);\n }\n\n /** The active transcript, as pi's entries since the newest reset. */\n async messages(): Promise<EntryRecord[]> {\n const view = await (await this.#harness.conversation(this.id)).context(BG);\n return [...view.entries];\n }\n\n /** pi's agent events for this session: a snapshot, then one batch per commit. */\n async events(context: Context = BG): Promise<AgentEventStream> {\n const pi = await this.#harness.pi();\n return watchEvents(pi, conversationId(this.id), context);\n }\n\n async busy(): Promise<boolean> {\n const pi = await this.#harness.pi();\n const live = await pi.snapshot(LiveDoc, conversationId(this.id), BG);\n return live?.run !== undefined;\n }\n}\n\n/** Every pi conversation in this object. */\nexport class PiSessions {\n readonly #harness: PiHarness;\n\n constructor(harness: PiHarness) {\n this.#harness = harness;\n }\n\n get(id: PiSessionId): PiSession {\n return this.#harness.session(id);\n }\n\n /** A new top-level session, configured like the root. */\n async create(): Promise<PiSession> {\n const pi = await this.#harness.pi();\n const conversation = await pi.createConversation(\n {\n ownership: { kind: \"ownerless\" },\n agent: this.#harness.agentDefaults()\n },\n BG\n );\n return this.#harness.session(String(conversation.id));\n }\n\n /** A new session that sees `from`'s history up to its newest entry. */\n async fork(from: PiSessionId): Promise<PiSession> {\n const conversation = await this.#harness.conversation(from);\n const newest = await conversation.entries({}, 1, undefined, BG);\n const at = newest.items[0];\n if (!at) throw new Error(`Session ${from} has no entries to fork from`);\n const fork = await conversation.fork(\n at.id,\n { ownership: { kind: \"ownerless\" } },\n BG\n );\n return this.#harness.session(String(fork.id));\n }\n\n /**\n * Every conversation, including ones subagent tools own. Read from pi's\n * storage directly: the Harness has no conversation listing.\n */\n async list(): Promise<PiSessionInfo[]> {\n const storage = await this.#harness.storage();\n const pi = await this.#harness.pi();\n const sessions: PiSessionInfo[] = [];\n let cursor: Parameters<SqliteStorage[\"scanConversations\"]>[2];\n for (;;) {\n const page = await storage.scanConversations({}, 100, cursor, BG);\n for (const record of page.items) {\n const live = await pi.snapshot(LiveDoc, record.id, BG);\n sessions.push({\n id: String(record.id),\n ...(record.parent\n ? { parent: String(record.parent.conversationId) }\n : {}),\n busy: live?.run !== undefined\n });\n }\n if (page.next === undefined) return sessions;\n cursor = page.next;\n }\n }\n}\n","import { Type } from \"@earendil-works/pi-ai\";\nimport type {\n Extension,\n ToolExecutionResult,\n ToolRegistration\n} from \"@earendil-works/pi-durable\";\nimport {\n formatSkillDiagnostic,\n loadSkillCatalog,\n renderSkillResource,\n type SkillCatalog\n} from \"../../skills/catalog\";\nimport type { SkillSource } from \"../../skills/source\";\n\nfunction textResult(text: string): ToolExecutionResult {\n return { output: [{ type: \"text\", text }] };\n}\n\n/** A failed tool call: pi sends it to the model as an error result. */\nfunction errorResult(error: Error): ToolExecutionResult {\n return { output: [{ type: \"text\", text: error.message }], isError: true };\n}\n\n/**\n * Model-facing tools for a catalog: `activate_skill` and\n * `read_skill_resource`. These match the tools `@cloudflare/think` offers, so\n * a skill behaves the same in both frameworks.\n */\nfunction skillTools(catalog: SkillCatalog): ToolRegistration[] {\n const names = catalog.skills.map((entry) => entry.skill.name);\n if (names.length === 0) return [];\n const nameSchema = Type.Union(names.map((name) => Type.Literal(name)));\n\n const activateParameters = Type.Object({ name: nameSchema });\n const activateSkill: ToolRegistration<typeof activateParameters> = {\n name: \"activate_skill\",\n description:\n \"Activate a skill by name. Use this when the user's task matches one of the available skills; the response contains the skill's full instructions.\",\n parameters: activateParameters,\n replay: \"safe\",\n async execute(input) {\n const activated = catalog.activate(input.name);\n return activated.ok\n ? textResult(activated.value)\n : errorResult(activated.error);\n }\n };\n\n const resourceParameters = Type.Object({\n name: Type.Optional(nameSchema),\n path: Type.String({ minLength: 1 })\n });\n const readResource: ToolRegistration<typeof resourceParameters> = {\n name: \"read_skill_resource\",\n description:\n \"Read a file bundled with a skill, such as a reference document or template. Provide the skill name and the file's path from the skill's resource list, or a qualified path like skill-name/references/file.md.\",\n parameters: resourceParameters,\n replay: \"safe\",\n async execute(input) {\n const read = await catalog.readResource(\n input.name === undefined\n ? { path: input.path }\n : { name: input.name, path: input.path }\n );\n return read.ok\n ? textResult(renderSkillResource(read.value))\n : errorResult(read.error);\n }\n };\n\n return [activateSkill, readResource];\n}\n\n/**\n * `agents/skills` sources as a pi extension, named `agents.skills`: the\n * activation tools and a `skills` system prompt section. Install it on\n * pi's registry in the harness factory. Sources are read once, when the\n * extension is built.\n *\n * ```ts\n * import * as agentSkills from \"agents/skills\";\n *\n * registry.install(\n * await skills([agentSkills.workspace(workspace), agentSkills.r2(env.SKILLS)])\n * );\n * ```\n *\n * @param sources - Skill sources in priority order.\n * @returns The pi extension.\n */\nexport async function skills(\n sources: readonly SkillSource[]\n): Promise<Extension> {\n const catalog = await loadSkillCatalog(sources);\n for (const diagnostic of catalog.diagnostics) {\n console.warn(`pi skills: ${formatSkillDiagnostic(diagnostic)}`);\n }\n const prompt = catalog.prompt();\n return {\n name: \"agents.skills\",\n tools: skillTools(catalog),\n sections: prompt === null ? [] : [{ key: \"skills\", render: () => prompt }]\n };\n}\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,iBAAiB;;AAGvB,SAAgB,mBACd,SACA,UAAiC,CAAC,GACV;CACxB,MAAM,SAAS,QAAQ,UAAU;CAGjC,IAAI,OAAO,YAAY,CAAC,CAAC,WAAW,MAAM,GACxC,OAAO,QAAQ,uBACb,IAAI,MAAM,sDAAsD,CAClE;CAEF,OAAO,+BAA+B,SAAS,EAAE,OAAO,CAAC;AAC3D;;;ACGA,MAAM,KAAK;;AAGX,MAAa,eAA4B,OAAO,oBAAoB;;;;;;;;;;AAWpE,MAAM,iBAAiB,KAAK;;;;;;AAO5B,MAAM,eAAe;;;;;AAMrB,MAAM,UAAU;;;;;A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ACzB,MAAM,SAAS,KAAA,IACX,EAAE,MAAM,MAAM,KAAK,IACnB;IAAE,MAAM,MAAM;IAAM,MAAM,MAAM;GAAK,CAC3C;GACA,OAAO,KAAK,KACR,WAAW,oBAAoB,KAAK,KAAK,CAAC,IAC1C,YAAY,KAAK,KAAK;EAC5B;CAGgC,CAAC;AACrC;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,OACpB,SACoB;CACpB,MAAM,UAAU,MAAM,iBAAiB,OAAO;CAC9C,KAAK,MAAM,cAAc,QAAQ,aAC/B,QAAQ,KAAK,cAAc,sBAAsB,UAAU,GAAG;CAEhE,MAAM,SAAS,QAAQ,OAAO;CAC9B,OAAO;EACL,MAAM;EACN,OAAO,WAAW,OAAO;EACzB,UAAU,WAAW,OAAO,CAAC,IAAI,CAAC;GAAE,KAAK;GAAU,cAAc;EAAO,CAAC;CAC3E;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["exhaustive"],"sources":["../../../src/harness/pi/session-store.ts","../../../src/harness/pi/harness.ts","../../../src/harness/pi/skills.ts"],"sourcesContent":["import type { SqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite\";\nimport { openDurableObjectSqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite/cloudflare\";\n\n/**\n * pi's session store on a Durable Object's SQLite database.\n *\n * pi owns its sessions: conversations, entries, tasks, submissions, and\n * documents live in pi's own schema, created and migrated by pi's portable\n * `SqliteStorage` through pi's own Durable Object adapter. The store keeps\n * pi's tables under a prefix, so they cannot collide with the SDK's or the\n * host's tables in the same object.\n *\n * It is the Durable Object counterpart of `agents/sessions` for a harness\n * that brings its own session model, and has nothing pi-harness specific in\n * it: any harness built on pi-durable can open its storage with it.\n */\nexport type PiSessionStoreOptions = {\n /**\n * Prefix for every table and index pi creates. Must not start with `_cf_`,\n * which Durable Objects reserve. Default `pi_`.\n */\n readonly prefix?: string;\n};\n\nconst DEFAULT_PREFIX = \"pi_\";\n\n/** Open pi-durable's storage over this object's SQLite database. */\nexport function openPiSessionStore(\n storage: DurableObjectStorage,\n options: PiSessionStoreOptions = {}\n): Promise<SqliteStorage> {\n const prefix = options.prefix ?? DEFAULT_PREFIX;\n // pi validates the prefix as a SQLite identifier; Durable Objects also\n // reserve `_cf_` in any case, which pi does not know about.\n if (prefix.toLowerCase().startsWith(\"_cf_\")) {\n return Promise.reject(\n new Error(\"The pi session store prefix must not start with _cf_\")\n );\n }\n return openDurableObjectSqliteStorage(storage, { prefix });\n}\n","import type { Api, Model, ModelThinkingLevel } from \"@earendil-works/pi-ai\";\nimport {\n LiveDoc,\n ROOT_CONVERSATION_ID,\n type Conversation,\n type ConversationId,\n type ConversationWatch,\n type ConversationWindow,\n type Cursor,\n type AgentChange,\n type EntryQuery,\n type EntryRecord,\n type Harness,\n type ModelRef,\n type Page,\n type SettledSubmissionRecord,\n type SignalResult,\n type SignalToken,\n type SubmissionDraft,\n type TaskId,\n type UserInput,\n type Wake\n} from \"@earendil-works/pi-durable\";\nimport type { SqliteStorage } from \"@earendil-works/pi-durable/storage/sqlite\";\nimport {\n LifecycleCapability,\n type CapabilityStartContext,\n type LifecycleJobContext,\n type LifecycleJobOutcome\n} from \"../../lifecycle\";\nimport { isDurableObjectMemoryLimitReset } from \"../../retries\";\nimport {\n BACKGROUND_CONTEXT,\n withAbortSignal,\n type Context\n} from \"@earendil-works/chord/context\";\nimport { openPiSessionStore } from \"./session-store\";\nimport type {\n PiContinueOptions,\n PiOperationResult,\n PiPendingOperation,\n PiPromptResponse,\n PiReceipt,\n PiSessionCreateOptions,\n PiSessionId,\n PiSessionInfo,\n PiSessionOptions,\n PiSubmitOptions\n} from \"./types\";\n\nconst BG = BACKGROUND_CONTEXT;\n\n/** The root session's id. */\nexport const ROOT_SESSION: PiSessionId = String(ROOT_CONVERSATION_ID);\n\n/**\n * The wake timings. They suit a real deployment; only tests change them,\n * with `setWakeTimingForTests`, so a suite does not sit on the real\n * heartbeat.\n *\n * Longest one wake waits on pi. It waits inside an alarm invocation, which\n * has a 15 minute wall-time limit, so a longer run is waited on across\n * several alarms.\n */\nconst WAIT_BUDGET_MS = 10 * 60_000;\n\n/**\n * The wake job's heartbeat while it waits, and how often it re-checks work\n * it cannot wait on, such as background tasks. If the object is evicted, the\n * job is still due and its alarm restarts the object.\n */\nconst HEARTBEAT_MS = 30_000;\n\n/**\n * How often a wait re-reads `pi.wake()` when the factory did not pass\n * `onWake`, so nothing tells the harness when it changes.\n */\nconst POLL_MS = 1_000;\n\n/**\n * The longest a wake job whose dispatch keeps failing waits before it tries\n * again. Its delay starts at the heartbeat and doubles up to this.\n */\nconst MAX_WAKE_BACKOFF_MS = 10 * 60_000;\n\n/**\n * Wake dispatches that failed in a row. Stored, so the backoff holds across\n * restarts, and outside the job: a push that saved it in the job's payload\n * could overwrite a submit's due-now push.\n */\nconst WAKE_ERRORS_KEY = \"pi-harness:wake-errors\";\n\nlet setWakeTiming: (harness: PiHarness, timing: WakeTiming) => void;\n\n/**\n * @internal Shorten a harness's wake timings, so a test suite does not sit\n * on the real heartbeat. Not exported from `agents/harness/pi`.\n */\nexport function setWakeTimingForTests(\n harness: PiHarness,\n timing: WakeTiming\n): void {\n setWakeTiming(harness, timing);\n}\n\nconst WAKE_FN = \"wake\";\n\n/**\n * The one wake job. Before Pi 1.4 there was one per session, with ids\n * `pi-wake:<session>`; a left-over one hands over to this one.\n */\nconst WAKE_JOB_ID = \"pi-wake\";\n\n/**\n * What the factory is handed: the things only the harness can build.\n * Everything else `Harness.open` takes (models, registry, settings, env,\n * onReport) the factory builds itself.\n */\nexport type PiHarnessContext = {\n /** pi's storage over this object's SQLite, its migrations already run. */\n readonly storage: SqliteStorage;\n /** Background context, for the open itself. */\n readonly context: Context;\n /**\n * Pass this to `Harness.open` as its `onWake` option. pi calls it when it\n * next needs to run, and the harness sets this object's alarm for then.\n *\n * With it, pi sets no in-memory timer for a sleeping task (a retry\n * backoff, a poll, a `sleepUntil`), so the object can hibernate until the\n * alarm. Without it the harness still works, but pi's timer keeps the\n * object in memory, and billed, while a task sleeps, and the harness logs\n * a warning when it opens pi.\n *\n * The harness reads pi's wake times against `Date.now()`, so do not pass\n * `now` to `Harness.open`.\n */\n readonly onWake: (wake: Wake) => void;\n};\n\n/**\n * Opens pi's `Harness`. The harness adopts what it returns. Pass `onWake`\n * through to `Harness.open`.\n *\n * ```ts\n * harness: async ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install(await skills(sources));\n * return Harness.open(storage, { models, registry, onWake }, context);\n * }\n * ```\n */\nexport type PiHarnessFactory = (\n context: PiHarnessContext\n) => Harness | Promise<Harness>;\n\n/**\n * A model, as pi-ai describes one: `createAI`'s `ai(\"@cf/…\")` returns one.\n *\n * Only its `provider` and `id` are used. pi stores that reference with\n * the session and resolves it, at each request, against the `Models` the\n * factory opened pi with. So the model must be one those `Models` list,\n * and options passed to `ai(id, options)` here, such as `fallback`, are not\n * applied.\n */\nexport type PiModel = Pick<Model<Api>, \"provider\" | \"id\">;\n\n/**\n * Applied to a session the first time it is created. Without a model, a\n * session's generation fails as unanswered until `session.setModel` sets one.\n */\nexport type PiSessionDefaults = {\n /**\n * Model for new sessions, by its `provider` and `id`; it must be on the\n * `Models` the factory opens pi with (see `PiModel`). Change one\n * session's with `session.setModel`.\n */\n readonly model?: PiModel;\n readonly thinkingLevel?: ModelThinkingLevel;\n /**\n * Most tool rounds one run takes: the round that reaches it runs its\n * tools, then the run's operations end unanswered with reason\n * `turn_limit`. An integer, 1 or more. Default: no limit.\n */\n readonly maxTurns?: number;\n};\n\n/** How long the wake waits on pi, and how often it checks. */\ntype WakeTiming = {\n /** Longest one wake waits inside an alarm. Default 600_000. */\n readonly waitBudgetMs?: number;\n /** Heartbeat while waiting. Default 30_000. */\n readonly heartbeatMs?: number;\n /** How often a wait re-reads `pi.wake()` without `onWake`. Default 1_000. */\n readonly pollMs?: number;\n};\n\n/** `PiHarness`'s options. Only `harness`, which opens pi, is required. */\nexport type PiHarnessOptions = {\n /** Opens pi's `Harness` over the storage this object prepared. */\n readonly harness: PiHarnessFactory;\n /** What a new session starts with. */\n readonly defaults?: PiSessionDefaults;\n};\n\n/**\n * `change` applied over `base` as pi applies an `AgentChange`: a field that is\n * `undefined` in `change` keeps `base`'s, any other value (`null` included)\n * replaces it. A plain spread would copy the `undefined` over `base`'s value.\n */\nfunction applyAgentChange<T extends object>(base: T, change: T): T {\n const applied = { ...base, ...change };\n for (const key in base) {\n if (change[key] === undefined) applied[key] = base[key];\n }\n return applied;\n}\n\n/** What `harness.root()` returns. */\nexport type PiRootResult = {\n /** The root session. */\n readonly session: PiSession;\n /**\n * Whether this call created the root, so its `agent` and `init` were\n * applied. `false` when the root already existed: something used it\n * first, and `init` did not run.\n */\n readonly created: boolean;\n};\n\ntype Opened = {\n readonly pi: Harness;\n readonly storage: SqliteStorage;\n};\n\n/** pi-durable's stored reference to a pi-ai model. */\nfunction modelRef(model: PiModel): ModelRef {\n return { provider: model.provider, modelId: model.id };\n}\n\nfunction conversationId(session: PiSessionId): ConversationId {\n const id = Number(session);\n if (!Number.isSafeInteger(id) || id < 1) {\n throw new Error(`Invalid pi session ${JSON.stringify(session)}`);\n }\n return id as ConversationId;\n}\n\n/** The text of an assistant entry, for an operation's result. */\nfunction assistantText(entry: EntryRecord | undefined): string {\n const message = entry?.model?.[0];\n if (message?.role !== \"assistant\") return \"\";\n return message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\"\");\n}\n\nfunction signalContext(signal: AbortSignal | undefined): Context {\n return signal ? withAbortSignal(signal, BG) : BG;\n}\n\n/**\n * pi-durable hosted in a Durable Object, behind a small harness interface:\n * `harness.prompt()`, `harness.sessions`, `harness.session(id)`. How a session reaches a\n * client (sockets, SSE, RPC) is the host's glue, built on `session.events()`.\n *\n * pi owns everything about a run: the transcript, the inbox of steers and\n * follow-ups, generation and tool tasks, retries, crash recovery, and the\n * live view. It keeps all of it in its own tables in this object's SQLite\n * database (see `session-store.ts`).\n *\n * What pi cannot do on a Durable Object is wake itself: its scheduler runs\n * in memory, and an evicted object has no memory. The harness is that wake,\n * with one Lifecycle job driven by `pi.wake()`. Anything that can start\n * work, such as `submit()`, `signal()`, `abort()` or `reset()`, goes to pi\n * once, after the job is scheduled. While pi has work running, the\n * job waits on it, rescheduling itself as a heartbeat. While pi's tasks\n * sleep, the job is due when the first one wakes; pi tells the harness\n * through the `onWake` the factory passes to `Harness.open`. When pi has\n * nothing to do, the job completes. An eviction mid-run leaves the job due,\n * so its alarm restarts the object, pi reopens and resumes its own tasks,\n * and the job waits again.\n */\nexport class PiHarness extends LifecycleCapability {\n readonly sessions: PiSessions;\n readonly #options: PiHarnessOptions;\n /** The in-memory wait on pi's running work, inside an alarm's work. */\n #waiting: Promise<void> | undefined;\n /** Resolves the current wait's sleep early: `pi.wake()` changed. */\n #changed: (() => void) | undefined;\n /** Calls that can start work, between their wake and pi's admission. */\n #admitting = 0;\n /** Whether pi has called `onWake`, so the factory passed it. */\n #onWakeWired = false;\n #waitBudgetMs = WAIT_BUDGET_MS;\n #heartbeatMs = HEARTBEAT_MS;\n #pollMs = POLL_MS;\n #opening: Promise<Opened> | undefined;\n /** Settles once the last pi that closed on its own has closed. */\n #lastClose: Promise<unknown> = Promise.resolve();\n /** Every pi that has begun closing, on its own or by `dispose()`. */\n readonly #closing = new WeakSet<Harness>();\n\n static {\n setWakeTiming = (harness, timing) => harness.#setWakeTiming(timing);\n }\n\n constructor(options: PiHarnessOptions) {\n super(\"pi-harness\");\n this.#options = options;\n this.sessions = new PiSessions(this);\n }\n\n #setWakeTiming(timing: WakeTiming): void {\n for (const [name, value] of Object.entries(timing)) {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`PiHarness timing.${name} must be a positive number`);\n }\n }\n this.#waitBudgetMs = timing.waitBudgetMs ?? this.#waitBudgetMs;\n this.#heartbeatMs = timing.heartbeatMs ?? this.#heartbeatMs;\n this.#pollMs = timing.pollMs ?? this.#pollMs;\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────\n\n override async onStart(_context: CapabilityStartContext): Promise<void> {\n await this.#open();\n }\n\n async onJob(\n context: LifecycleJobContext\n ): Promise<LifecycleJobOutcome | void> {\n if (context.job.fn !== WAKE_FN) return;\n let outcome: LifecycleJobOutcome;\n if (context.job.id !== WAKE_JOB_ID) {\n // A per-session wake from before Pi 1.4: hand over to the one wake.\n await this.#wake();\n outcome = undefined;\n } else {\n outcome = await this.#wakeStep();\n }\n // It got through, so a failing wake's backoff starts over.\n const kv = this.lifecycle.storage.kv;\n if (kv.get(WAKE_ERRORS_KEY) !== undefined) kv.delete(WAKE_ERRORS_KEY);\n return outcome;\n }\n\n /**\n * A wake dispatch that failed through Lifecycle's retries, as when pi\n * cannot be opened. Lifecycle would complete the job, and pi's work would\n * never be woken again, so try again later: at the heartbeat, doubling\n * while the failures continue, up to 10 minutes.\n */\n onJobError(\n context: LifecycleJobContext,\n error: unknown\n ): LifecycleJobOutcome | void {\n if (context.job.fn !== WAKE_FN) return;\n console.error(\n `pi wake job \"${context.job.id}\" failed after ${context.attempt} ` +\n \"attempts; retrying with backoff\",\n error\n );\n this.#wakeError(error);\n const kv = this.lifecycle.storage.kv;\n const errors = (kv.get<number>(WAKE_ERRORS_KEY) ?? 0) + 1;\n kv.put(WAKE_ERRORS_KEY, errors);\n const delay = Math.min(\n this.#heartbeatMs * 2 ** (errors - 1),\n MAX_WAKE_BACKOFF_MS\n );\n return { rescheduleAt: Date.now() + delay };\n }\n\n /** Close pi's in-memory resources. Durable state is untouched. */\n async dispose(): Promise<void> {\n const opening = this.#opening;\n this.#opening = undefined;\n const opened = await opening?.catch(() => undefined);\n // Closing calls #piClosing, which also ends a wait sleeping on this pi.\n await opened?.pi.close(BG);\n }\n\n // ── The harness interface ────────────────────────────────────────────────\n\n /** A handle on one session. No I/O until you call it. */\n session(id: PiSessionId = ROOT_SESSION): PiSession {\n return new PiSession(this, id);\n }\n\n /**\n * The root session, creating it with `agent` and `init` in one commit\n * when it does not exist yet, as pi's `Harness.root()` does. `agent` is\n * applied over `defaults`. When the root already exists, nothing is\n * written and `init` does not run; `created` says which happened.\n *\n * Without this call, the first use of the root creates it with\n * `defaults`. So call it before anything else uses the root, for example\n * to seed the root's transcript with an existing history.\n */\n async root(options: PiSessionCreateOptions = {}): Promise<PiRootResult> {\n const { pi } = await this.#open();\n // pi runs `init` only in the commit that creates the root, and runs a\n // commit's callback once: it never retries one. `root()` resolves only\n // once that commit is stored, and rejects if the callback throws or the\n // commit fails. So `init` ran in a resolved call exactly when the\n // root was created by it.\n let created = false;\n await this.#root(pi, {\n ...(options.agent ? { agent: options.agent } : {}),\n init: async (tx, id) => {\n created = true;\n await options.init?.(tx, id);\n }\n });\n return { session: this.session(ROOT_SESSION), created };\n }\n\n /** Submit a prompt and wait for its answer. */\n prompt(\n input: UserInput,\n options: PiSubmitOptions = {}\n ): Promise<PiPromptResponse> {\n return this.session(options.session).prompt(input, options);\n }\n\n /** Durably submit a prompt. Resolves before the model runs. */\n submit(input: UserInput, options: PiSubmitOptions = {}): Promise<PiReceipt> {\n return this.session(options.session).submit(input, options);\n }\n\n /**\n * Run an idle session again on its transcript as it is, without new input.\n * See `PiSession.continue`.\n */\n continue(\n options: PiSessionOptions & PiContinueOptions = {}\n ): Promise<PiReceipt> {\n return this.session(options.session).continue(options);\n }\n\n /** Stop one operation, or everything running in a session. */\n abort(\n options: PiSessionOptions & { readonly operationId?: string } = {}\n ): Promise<boolean> {\n return this.session(options.session).abort(options.operationId);\n }\n\n wait(\n operationId: string,\n options: PiSessionOptions & { readonly signal?: AbortSignal } = {}\n ): Promise<PiOperationResult> {\n return this.session(options.session).wait(operationId, options.signal);\n }\n\n /** The session's active transcript, as pi's entries. */\n messages(options: PiSessionOptions = {}): Promise<EntryRecord[]> {\n return this.session(options.session).messages();\n }\n\n /** Submissions pi has not settled yet, oldest first. */\n async pending(options: PiSessionOptions = {}): Promise<PiPendingOperation[]> {\n const { pi } = await this.#open();\n const id =\n options.session === undefined\n ? undefined\n : conversationId(options.session);\n const inspection = await pi.inspect(BG);\n return inspection.submissions.flatMap((record): PiPendingOperation[] => {\n if (record.requestId === undefined) return [];\n if (id !== undefined && record.conversationId !== id) return [];\n let status: PiPendingOperation[\"status\"];\n switch (record.status) {\n case \"queued\":\n status = \"queued\";\n break;\n case \"placed\":\n status = \"running\";\n break;\n case \"done\":\n case \"unanswered\":\n // Settled. pi's inspection holds only unsettled submissions.\n return [];\n default: {\n // A status added by a newer pi: decide what it reports.\n const exhaustive: never = record;\n return exhaustive;\n }\n }\n return [\n {\n operationId: record.requestId,\n session: String(record.conversationId),\n status\n }\n ];\n });\n }\n\n /**\n * Deliver `value` to pi task `taskId` under `key`, as pi's\n * `Harness.signal()` does: for a tool parked on that signal, such as one\n * waiting for a person's answer or a webhook. The wake job is scheduled\n * first, so if the object dies while the woken call runs, the job's alarm\n * restarts it. Call this rather than `pi().signal()`, which does not.\n */\n async signal<T>(\n taskId: TaskId,\n signal: SignalToken<T>,\n key: string,\n value: T\n ): Promise<SignalResult> {\n const { pi } = await this.#open();\n return this.#admit(() => pi.signal(taskId, signal, key, value, BG));\n }\n\n /** The opened pi Harness, for anything the interface does not cover. */\n async pi(): Promise<Harness> {\n return (await this.#open()).pi;\n }\n\n // ── Used by PiSession and PiSessions ─────────────────────────────────────\n\n /**\n * @internal Every use of a session goes through here. The first use of\n * the root creates it, with `defaults`.\n */\n async conversation(session: PiSessionId): Promise<Conversation> {\n const { pi } = await this.#open();\n const id = conversationId(session);\n if (id === ROOT_CONVERSATION_ID) return this.#root(pi, {});\n const conversation = await pi.conversation(id, BG);\n if (!conversation) throw new Error(`Unknown pi session ${session}`);\n return conversation;\n }\n\n /**\n * pi's root conversation, created with `options` over `defaults` when\n * absent. pi checks for the root and creates it in one commit, so two\n * calls never both create it.\n */\n #root(pi: Harness, options: PiSessionCreateOptions): Promise<Conversation> {\n return pi.root(BG, {\n agent: this.agentOverDefaults(options.agent),\n ...(options.init ? { init: options.init } : {})\n });\n }\n\n /** @internal */\n async storage(): Promise<SqliteStorage> {\n return (await this.#open()).storage;\n }\n\n /** @internal */\n async enqueue(\n session: PiSessionId,\n input: UserInput,\n options: PiSubmitOptions\n ): Promise<PiReceipt> {\n return this.#admitDraft(session, options.operationId, {\n type: \"input\",\n content: input,\n whenBusy: options.whenBusy ?? \"followUp\",\n ...(options.whenIdle ? { whenIdle: options.whenIdle } : {}),\n ...(options.onAbort ? { onAbort: options.onAbort } : {}),\n ...(options.entry ? { entry: options.entry } : {}),\n ...(options.notify ? { notify: options.notify } : {})\n });\n }\n\n /** @internal Start a run on the context as it is, without new input. */\n enqueueContinue(\n session: PiSessionId,\n options: PiContinueOptions\n ): Promise<PiReceipt> {\n return this.#admitDraft(session, options.operationId, {\n type: \"continue\",\n ...(options.notify ? { notify: options.notify } : {})\n });\n }\n\n async #admitDraft(\n session: PiSessionId,\n requested: string | undefined,\n draft: SubmissionDraft\n ): Promise<PiReceipt> {\n const operationId = requested ?? crypto.randomUUID();\n const { storage } = await this.#open();\n const conversation = await this.conversation(session);\n const accepted = await this.#admit(async () => {\n // The one admission. pi deduplicates by request id.\n const accepted =\n (await storage.submissionByRequest(\n conversation.id,\n operationId,\n BG\n )) === undefined;\n await conversation.submit({ ...draft, requestId: operationId }, BG);\n return accepted;\n });\n return { operationId, session, accepted };\n }\n\n /** @internal Withdraw a queued input, or abort the run it joined. */\n async withdraw(session: PiSessionId, operationId: string): Promise<boolean> {\n const { pi, storage } = await this.#open();\n const id = conversationId(session);\n const record = await storage.submissionByRequest(id, operationId, BG);\n if (!record || record.status === \"done\" || record.status === \"unanswered\") {\n return false;\n }\n const outcome = await this.#admit(() =>\n pi.abortSubmission(record.id, BG, id)\n );\n switch (outcome) {\n case \"aborted\":\n return true;\n case \"already_placed\":\n await this.abortConversation(session);\n return true;\n case \"settled\":\n case \"not_found\":\n return false;\n default: {\n // An outcome added by a newer pi: decide whether it withdrew.\n const exhaustive: never = outcome;\n return exhaustive;\n }\n }\n }\n\n /**\n * @internal Abort a session's running work and withdraw its queued\n * inputs. Stopping a parked call runs its `cancel()`, which is work, so\n * the wake is scheduled first.\n */\n async abortConversation(session: PiSessionId): Promise<void> {\n const conversation = await this.conversation(session);\n await this.#admit(() => conversation.abort(BG));\n }\n\n /**\n * @internal Start a new context. Inputs kept behind a failed run or an\n * abort run in it, so the wake is scheduled first.\n */\n async resetConversation(\n session: PiSessionId,\n handoff: string | undefined\n ): Promise<void> {\n const conversation = await this.conversation(session);\n await this.#admit(() => conversation.reset(handoff, BG));\n }\n\n /** @internal Wait for pi to settle an operation, by its request id. */\n async settled(\n session: PiSessionId,\n operationId: string,\n signal?: AbortSignal\n ): Promise<PiOperationResult> {\n const conversation = await this.conversation(session);\n const context = signalContext(signal);\n const submission = await this.#findSubmission(\n conversation.id,\n operationId,\n context\n );\n if (!submission) {\n return {\n operationId,\n session,\n status: \"unanswered\",\n reason: \"not_found\"\n };\n }\n return this.#result(\n session,\n operationId,\n await submission.wait(context),\n context\n );\n }\n\n // ── The wake ─────────────────────────────────────────────────────────────\n\n /**\n * Hand pi work inside the wake. The wake is scheduled first, so if the\n * object dies after pi has the work, that job restarts it; while `hand`\n * is in flight the step will not complete. The wake steps again after, so\n * it sees the work even if it just completed.\n */\n async #admit<T>(hand: () => Promise<T>): Promise<T> {\n this.#admitting++;\n let result: T;\n try {\n await this.#wake();\n result = await hand();\n } finally {\n this.#admitting--;\n }\n await this.#wake();\n return result;\n }\n\n /** Schedule the wake job now, or at `time`. */\n #wake(time = Date.now()): Promise<unknown> {\n // A push made while the job is dispatching supersedes that dispatch's\n // outcome, so a submit is never lost to a wake that is completing.\n return this.lifecycle.jobs.push({\n id: WAKE_JOB_ID,\n fn: WAKE_FN,\n time,\n singleflight: true,\n recoveryLoop: true\n });\n }\n\n /** Schedule the wake job for what `pi.wake()` says, if pi needs one. */\n async #wakeFor(wake: Wake): Promise<void> {\n if (wake.active) await this.#wake();\n else if (wake.at !== undefined) await this.#wake(wake.at);\n }\n\n /**\n * pi's `onWake`, handed to the factory. pi calls it after open and\n * whenever `pi.wake()` changes. It must not block, so the job push is\n * left running.\n */\n readonly #onWake = (wake: Wake): void => {\n this.#onWakeWired = true;\n this.#changed?.();\n // A running wait re-reads pi.wake() and steps again when it ends.\n if (this.#waiting) return;\n this.#wakeFor(wake).catch((error: unknown) => this.#wakeError(error));\n };\n\n /**\n * One run of the wake job. It never admits or replays anything: it reads\n * `pi.wake()`, which is all of pi's sessions at once. Running work is\n * waited on; a sleep reschedules the job for when it ends; no work\n * completes the job. pi does all the work in between.\n */\n async #wakeStep(): Promise<LifecycleJobOutcome> {\n const heartbeat = { rescheduleAt: Date.now() + this.#heartbeatMs };\n if (this.#waiting) return heartbeat;\n const { pi } = await this.#open();\n // The alarm may be for a sleeping task: make due ones runnable.\n pi.resume();\n const wake = pi.wake();\n if (wake.active) {\n const wait = this.#waitWhileActive(pi).then(\n (ended) => {\n this.#waiting = undefined;\n // Step again now: pi may be sleeping, or have nothing left. After\n // a failed wait, as when pi's Session fails, the heartbeat that is\n // already due steps instead, so a pi that keeps failing is not\n // reopened in a loop.\n if (ended) void this.#wake();\n },\n (error: unknown) => {\n // A memory-limit reset: the alarm's breaker backs the job off.\n this.#waiting = undefined;\n throw error;\n }\n );\n this.#waiting = wait;\n // The wait runs past this dispatch, inside the alarm's work, so the\n // object stays alive for it, and a memory-limit reset it ends with\n // counts against the alarm's breaker. The heartbeat covers an\n // eviction.\n if (!this.lifecycle.trackAlarmWork(wait)) wait.catch(() => {});\n return heartbeat;\n }\n // A submit between its wake and pi's admission: check again later.\n if (this.#admitting > 0) return heartbeat;\n if (wake.at !== undefined) return { rescheduleAt: wake.at };\n // Nothing to do.\n return undefined;\n }\n\n /**\n * Wait while pi has work running, up to the wait budget. With `onWake`, a\n * change ends each sleep early, and so does pi closing; without it, the\n * sleep is `pollMs`. A task sleeping beside the running work, such as a\n * retry backoff, also ends the sleep when it is due, and the wait calls\n * `pi.resume()` to run it: with `onWake`, pi arms no timer for it, and\n * the wake job's alarm is not set for it while the job waits. Whether the\n * wait ended, with pi idle or at the budget, rather than failing. Rejects\n * with a memory-limit reset.\n */\n async #waitWhileActive(pi: Harness): Promise<boolean> {\n const deadline = Date.now() + this.#waitBudgetMs;\n try {\n // Once pi begins closing, pi.wake() throws (SessionFailed after a\n // storage error), which is what ends this loop: a closed pi's wake does\n // not go inactive. Closing kicks `#changed` only so the loop reads it\n // again now rather than at the end of its sleep.\n let wake = pi.wake();\n while (wake.active) {\n const now = Date.now();\n const left = deadline - now;\n if (left <= 0) return true;\n let sleep = this.#onWakeWired ? left : Math.min(left, this.#pollMs);\n // `at` is a sleep not yet due on pi's clock, so this is positive.\n // That holds because pi keeps its default clock, `Date.now`; see\n // `PiHarnessContext`.\n if (wake.at !== undefined) sleep = Math.min(sleep, wake.at - now);\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, sleep);\n this.#changed = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n this.#changed = undefined;\n // A sleep beside the running work came due: make it runnable.\n if (wake.at !== undefined && Date.now() >= wake.at) pi.resume();\n wake = pi.wake();\n }\n return true;\n } catch (error) {\n // A pi that began closing is expected to throw; it is no longer the\n // harness's pi, and Pi reports a failure itself (`storage_failed`).\n if (!this.#closing.has(pi)) this.#wakeError(error);\n // Only Lifecycle's alarm breaker can act on a memory-limit reset,\n // including one that failed pi's Session (SessionFailed's cause).\n if (isDurableObjectMemoryLimitReset(error)) throw error;\n return false;\n }\n }\n\n #wakeError(error: unknown): void {\n this.lifecycle.events.emit(\"pi:wake_error\", {\n error: error instanceof Error ? error.message : String(error)\n });\n }\n\n // ── pi ───────────────────────────────────────────────────────────────────\n\n /**\n * pi, opened. Waits for Lifecycle startup first, so pi is only ever\n * opened inside it: startup holds the input gate (`blockConcurrencyWhile`)\n * and awaits the open in `onStart`, so an open begun before startup would\n * be awaited behind a closed gate, with its timers and I/O held back, and\n * never finish.\n *\n * pi stays open until `dispose()`, or until it closes on its own: any\n * storage error fails pi's Session for good. Then the next call, or the\n * wake job's next step, opens pi again once the failed pi has closed, and\n * pi recovers from what it had committed. Closing waits for running task\n * code to return, so code that ignores its abort signal delays the reopen.\n * An open that fails is not kept either, so the next call tries again.\n */\n async #open(): Promise<Opened> {\n await this.lifecycle.ready();\n if (this.#opening === undefined) {\n const opening: Promise<Opened> = this.#doOpen((pi, closed) =>\n this.#piClosing(opening, pi, closed)\n ).catch((error: unknown) => {\n if (this.#opening === opening) this.#opening = undefined;\n throw error;\n });\n this.#opening = opening;\n }\n return this.#opening;\n }\n\n async #doOpen(\n onClose: (pi: Harness, closed: Promise<unknown>) => void\n ): Promise<Opened> {\n // A pi that closed on its own closes its storage last, after its tasks\n // have returned; let it finish before another opens over the same\n // database.\n await this.#lastClose;\n const storage = await openPiSessionStore(this.lifecycle.storage);\n const pi = await this.#options.harness({\n storage,\n context: BG,\n onWake: this.#onWake\n });\n try {\n const closed = pi.closed;\n // Called synchronously when pi begins closing, unlike `closed`, so a\n // closed pi is never handed out. It must not call pi.\n pi.subscribeClose(() => onClose(pi, closed));\n // Opening creates no conversation: the root's first use creates it\n // (see `conversation()`), so `root()` can seed it.\n // Continue whatever the last pi left, in this isolate or the last one:\n // pi reconciles tasks that were running to pending and schedules them\n // again.\n pi.resume();\n // pi calls onWake right after open, from a microtask.\n await new Promise((resolve) => setTimeout(resolve, 0));\n if (!this.#onWakeWired) {\n console.warn(\n \"PiHarness: the harness factory did not pass onWake to Harness.open, \" +\n \"so pi's timers keep this Durable Object in memory while a task \" +\n \"sleeps. Pass it: harness: ({ storage, context, onWake }) => \" +\n \"Harness.open(storage, { ...options, onWake }, context)\"\n );\n }\n // Whatever the last pi left gets a wake, including work whose wake\n // failed out. With `onWake`, pi has already said so; this covers a\n // factory without it. The job id is fixed, so this is idempotent.\n await this.#wakeFor(pi.wake());\n } catch (error) {\n // pi is open and running its tasks: close it, so the next open does\n // not start a second pi over the same database beside it.\n pi.close(BG).catch(() => {});\n throw error;\n }\n return { pi, storage };\n }\n\n /**\n * pi began closing: on its own, as a storage error makes it, or by\n * `dispose()`.\n */\n #piClosing(\n opening: Promise<Opened>,\n pi: Harness,\n closed: Promise<unknown>\n ): void {\n this.#closing.add(pi);\n // End a wait sleeping on this pi now: pi will not call onWake again.\n this.#changed?.();\n // `dispose()` took its pi out of `#opening` already, and an open begun\n // since must stay.\n if (this.#opening !== opening) return;\n // Drop it, so the next call opens pi again once this one has closed.\n this.#opening = undefined;\n this.#lastClose = closed;\n }\n\n /**\n * @internal `agent` applied over the defaults, by pi's rule for an\n * `AgentChange`: a field set to a value replaces the default, `null`\n * clears it, and `undefined` leaves it in place.\n */\n agentOverDefaults(agent: AgentChange = {}): AgentChange {\n return applyAgentChange(this.agentDefaults(), agent);\n }\n\n /** @internal The per-conversation defaults supported by pi-durable. */\n agentDefaults(): AgentChange {\n const defaults = this.#options.defaults;\n return {\n ...(defaults?.model === undefined\n ? {}\n : { model: modelRef(defaults.model) }),\n ...(defaults?.thinkingLevel === undefined\n ? {}\n : { thinkingLevel: defaults.thinkingLevel }),\n ...(defaults?.maxTurns === undefined\n ? {}\n : { maxTurns: defaults.maxTurns })\n };\n }\n\n async #findSubmission(\n id: ConversationId,\n operationId: string,\n context: Context\n ) {\n const { pi, storage } = await this.#open();\n // Read from pi's storage: the Harness only reacquires submissions by id.\n const record = await storage.submissionByRequest(id, operationId, context);\n return record ? pi.submission(record.id, context) : undefined;\n }\n\n async #result(\n session: PiSessionId,\n operationId: string,\n settled: SettledSubmissionRecord,\n context: Context\n ): Promise<PiOperationResult> {\n if (settled.status === \"unanswered\") {\n return {\n operationId,\n session,\n status: \"unanswered\",\n reason: settled.reason\n };\n }\n if (settled.type === \"write\")\n return { operationId, session, status: \"done\" };\n const conversation = await this.conversation(session);\n const page = await conversation.entries(\n { minEntryId: settled.answer, maxEntryId: settled.answer },\n 1,\n undefined,\n context\n );\n return {\n operationId,\n session,\n status: \"done\",\n text: assistantText(page.items[0])\n };\n }\n}\n\n/** One pi conversation, addressed through the harness. */\nexport class PiSession {\n readonly #harness: PiHarness;\n readonly id: PiSessionId;\n\n constructor(harness: PiHarness, id: PiSessionId) {\n this.#harness = harness;\n this.id = id;\n }\n\n /** Durably submit a prompt. Resolves before the model runs. */\n submit(input: UserInput, options: PiSubmitOptions = {}): Promise<PiReceipt> {\n return this.#harness.enqueue(this.id, input, options);\n }\n\n /** Submit and wait for the answer and the updated transcript. */\n async prompt(\n input: UserInput,\n options: PiSubmitOptions = {}\n ): Promise<PiPromptResponse> {\n const receipt = await this.submit(input, options);\n const result = await this.wait(receipt.operationId);\n return { ...result, messages: await this.messages() };\n }\n\n /**\n * Start a run on the transcript as it is, without a new message: for\n * example, after a run ended unanswered because the model failed or the\n * object kept crashing. Only an idle session takes one; a busy one rejects\n * with pi-durable's `ConversationBusy`. A transcript that ends in an answer\n * settles `unanswered` with reason `nothing_to_answer`.\n */\n continue(options: PiContinueOptions = {}): Promise<PiReceipt> {\n return this.#harness.enqueueContinue(this.id, options);\n }\n\n /** Join the running work after its current tool round. */\n steer(input: UserInput, options: Omit<PiSubmitOptions, \"whenBusy\"> = {}) {\n return this.submit(input, { ...options, whenBusy: \"steer\" });\n }\n\n /** Wait for an operation to settle. Aborting `signal` stops only the wait. */\n wait(operationId: string, signal?: AbortSignal): Promise<PiOperationResult> {\n return this.#harness.settled(this.id, operationId, signal);\n }\n\n /**\n * Withdraw one queued operation (or abort the run it joined), or, with no\n * id, abort the session: pi withdraws queued inputs, apart from those\n * submitted with `onAbort: \"keep\"`, and aborts the running work.\n */\n async abort(operationId?: string): Promise<boolean> {\n if (operationId !== undefined) {\n return this.#harness.withdraw(this.id, operationId);\n }\n await this.#harness.abortConversation(this.id);\n return true;\n }\n\n /** Start a new context, optionally from a handoff note. */\n async reset(handoff?: string): Promise<void> {\n await this.#harness.resetConversation(this.id, handoff);\n }\n\n /**\n * Change this session's model, by its `provider` and `id`; it must be on\n * the `Models` the factory opened pi with (see `PiModel`).\n */\n async setModel(model: PiModel): Promise<void> {\n await (\n await this.#harness.conversation(this.id)\n ).configure({ model: modelRef(model) }, BG);\n }\n\n /** The active transcript, as pi's entries since the newest reset. */\n async messages(): Promise<EntryRecord[]> {\n const view = await (await this.#harness.conversation(this.id)).context(BG);\n return [...view.entries];\n }\n\n /**\n * Watch this session: pi's conversation view, a window over the transcript\n * with the session's documents, such as `pi.live` (the answer being\n * streamed, running tools, and why the last run ended without an answer)\n * and `pi.inbox`. The first value holds the newest entries; new entries\n * are appended. Each change carries pi's operations, for a client that\n * forwards them. To render more than the window, merge each value into a\n * `ConversationTranscript` that pages with `entries()`.\n */\n async watch(\n window?: ConversationWindow,\n context: Context = BG\n ): Promise<ConversationWatch> {\n return (await this.#harness.conversation(this.id)).watch(context, window);\n }\n\n /**\n * A page of this session's transcript, newest first unless `query.order`\n * is `ascending`, including entries before its resets. The loader a\n * `ConversationTranscript` takes.\n */\n async entries(\n query: Omit<EntryQuery, \"conversationId\">,\n limit: number,\n context: Context = BG\n ): Promise<Page<EntryRecord, Cursor>> {\n return (await this.#harness.conversation(this.id)).entries(\n query,\n limit,\n undefined,\n context\n );\n }\n\n async busy(): Promise<boolean> {\n const pi = await this.#harness.pi();\n const live = await pi.snapshot(LiveDoc, conversationId(this.id), BG);\n return live?.run !== undefined;\n }\n}\n\n/** Every pi conversation in this object. */\nexport class PiSessions {\n readonly #harness: PiHarness;\n\n constructor(harness: PiHarness) {\n this.#harness = harness;\n }\n\n get(id: PiSessionId): PiSession {\n return this.#harness.session(id);\n }\n\n /**\n * A new top-level session, configured with `defaults`, then `agent`; `init`\n * runs in the commit that creates it.\n */\n async create(options: PiSessionCreateOptions = {}): Promise<PiSession> {\n const pi = await this.#harness.pi();\n const conversation = await pi.createConversation(\n {\n ownership: { kind: \"ownerless\" },\n agent: this.#harness.agentOverDefaults(options.agent),\n ...(options.init ? { init: options.init } : {})\n },\n BG\n );\n return this.#harness.session(String(conversation.id));\n }\n\n /**\n * A new session that sees `from`'s history up to its newest entry, with\n * `from`'s configuration, then `agent`; `init` runs in the commit that\n * creates it.\n */\n async fork(\n from: PiSessionId,\n options: PiSessionCreateOptions = {}\n ): Promise<PiSession> {\n const conversation = await this.#harness.conversation(from);\n const newest = await conversation.entries({}, 1, undefined, BG);\n const at = newest.items[0];\n if (!at) throw new Error(`Session ${from} has no entries to fork from`);\n const fork = await conversation.fork(\n at.id,\n {\n ownership: { kind: \"ownerless\" },\n ...(options.agent ? { agent: options.agent } : {}),\n ...(options.init ? { init: options.init } : {})\n },\n BG\n );\n return this.#harness.session(String(fork.id));\n }\n\n /**\n * Every conversation, including ones subagent tools own. Read from pi's\n * storage directly: the Harness has no conversation listing. The root is\n * listed once it exists: its first use, or `harness.root()`, creates it.\n */\n async list(): Promise<PiSessionInfo[]> {\n const storage = await this.#harness.storage();\n const pi = await this.#harness.pi();\n const sessions: PiSessionInfo[] = [];\n let cursor: Parameters<SqliteStorage[\"scanConversations\"]>[2];\n for (;;) {\n const page = await storage.scanConversations({}, 100, cursor, BG);\n for (const record of page.items) {\n const live = await pi.snapshot(LiveDoc, record.id, BG);\n sessions.push({\n id: String(record.id),\n ...(record.parent\n ? { parent: String(record.parent.conversationId) }\n : {}),\n busy: live?.run !== undefined\n });\n }\n if (page.next === undefined) return sessions;\n cursor = page.next;\n }\n }\n}\n","import { StringEnum } from \"@earendil-works/pi-ai\";\nimport type {\n Extension,\n ToolExecutionResult,\n ToolRegistration\n} from \"@earendil-works/pi-durable\";\nimport { obj, opt, str } from \"@earendil-works/pi-schema\";\nimport {\n formatSkillDiagnostic,\n loadSkillCatalog,\n renderSkillResource,\n type SkillCatalog\n} from \"../../skills/catalog\";\nimport type { SkillSource } from \"../../skills/source\";\n\nfunction textResult(text: string): ToolExecutionResult {\n return { output: [{ type: \"text\", text }] };\n}\n\n/** A failed tool call: pi sends it to the model as an error result. */\nfunction errorResult(error: Error): ToolExecutionResult {\n return { output: [{ type: \"text\", text: error.message }], isError: true };\n}\n\n/**\n * Model-facing tools for a catalog: `activate_skill` and\n * `read_skill_resource`. These match the tools `@cloudflare/think` offers, so\n * a skill behaves the same in both frameworks.\n */\nfunction skillTools(catalog: SkillCatalog): ToolRegistration[] {\n const names = catalog.skills.map((entry) => entry.skill.name);\n if (names.length === 0) return [];\n const nameSchema = StringEnum(names);\n\n const activateParameters = obj({ name: nameSchema }, { open: true });\n const activateSkill: ToolRegistration<typeof activateParameters> = {\n name: \"activate_skill\",\n description:\n \"Activate a skill by name. Use this when the user's task matches one of the available skills; the response contains the skill's full instructions.\",\n parameters: activateParameters,\n replay: \"safe\",\n async execute(input) {\n const activated = catalog.activate(input.name);\n return activated.ok\n ? textResult(activated.value)\n : errorResult(activated.error);\n }\n };\n\n const resourceParameters = obj(\n { name: opt(nameSchema), path: str({ minLength: 1 }) },\n { open: true }\n );\n const readResource: ToolRegistration<typeof resourceParameters> = {\n name: \"read_skill_resource\",\n description:\n \"Read a file bundled with a skill, such as a reference document or template. Provide the skill name and the file's path from the skill's resource list, or a qualified path like skill-name/references/file.md.\",\n parameters: resourceParameters,\n replay: \"safe\",\n async execute(input) {\n const read = await catalog.readResource(\n input.name === undefined\n ? { path: input.path }\n : { name: input.name, path: input.path }\n );\n return read.ok\n ? textResult(renderSkillResource(read.value))\n : errorResult(read.error);\n }\n };\n\n return [activateSkill, readResource];\n}\n\n/**\n * `agents/skills` sources as a pi extension, named `agents.skills`: the\n * activation tools and a `skills` system prompt section. Install it on\n * pi's registry in the harness factory. Sources are read once, when the\n * extension is built.\n *\n * ```ts\n * import * as agentSkills from \"agents/skills\";\n *\n * registry.install(\n * await skills([agentSkills.workspace(workspace), agentSkills.r2(env.SKILLS)])\n * );\n * ```\n *\n * @param sources - Skill sources in priority order.\n * @returns The pi extension.\n */\nexport async function skills(\n sources: readonly SkillSource[]\n): Promise<Extension> {\n const catalog = await loadSkillCatalog(sources);\n for (const diagnostic of catalog.diagnostics) {\n console.warn(`pi skills: ${formatSkillDiagnostic(diagnostic)}`);\n }\n const prompt = catalog.prompt();\n return {\n name: \"agents.skills\",\n tools: skillTools(catalog),\n sections: prompt === null ? [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come,
|
|
7
7
|
x as Connection
|
|
8
|
-
} from "../../capability-runner-
|
|
8
|
+
} from "../../capability-runner-uFOdSANC.js";
|
|
9
9
|
import { n as ClientToolSchema } from "../../client-tools-aIBO0Fk7.js";
|
|
10
10
|
import { o as SearchResult } from "../../types-B7LojTe4.js";
|
|
11
|
-
import { n as WebSocketHandlers } from "../../options-
|
|
11
|
+
import { n as WebSocketHandlers } from "../../options-CiXaymmZ.js";
|
|
12
12
|
import {
|
|
13
13
|
a as HarnessSessions,
|
|
14
14
|
c as OperationStatus,
|
|
@@ -314,6 +314,13 @@ const BINDING_ORIGIN = "https://workers-binding.ai";
|
|
|
314
314
|
const REST_API_ORIGIN = "https://api.cloudflare.com/client/v4/accounts";
|
|
315
315
|
/** The provider-native path, for a model object reached with a token. */
|
|
316
316
|
const GATEWAY_ORIGIN = "https://gateway.ai.cloudflare.com/v1";
|
|
317
|
+
/** Builds the `FormData` a multipart request sends. */
|
|
318
|
+
function multipartForm(fields) {
|
|
319
|
+
const form = new FormData();
|
|
320
|
+
for (const [name, value] of Object.entries(fields)) if (typeof value === "string") form.append(name, value);
|
|
321
|
+
else form.append(name, new Blob([new Uint8Array(value.bytes)], { type: value.contentType }), name);
|
|
322
|
+
return form;
|
|
323
|
+
}
|
|
317
324
|
/**
|
|
318
325
|
* Drops entries whose value is `undefined`. The AI SDK types call headers as
|
|
319
326
|
* `Record<string, string | undefined>`, and an undefined value reaches the
|
|
@@ -534,6 +541,17 @@ function bindingTransport(binding) {
|
|
|
534
541
|
},
|
|
535
542
|
async run(request) {
|
|
536
543
|
try {
|
|
544
|
+
if (request.multipart !== void 0) {
|
|
545
|
+
const form = new Response(multipartForm(request.multipart));
|
|
546
|
+
return await raw.run(request.model, { multipart: {
|
|
547
|
+
body: form.body,
|
|
548
|
+
contentType: form.headers.get("content-type")
|
|
549
|
+
} }, {
|
|
550
|
+
...Object.keys(request.headers).length > 0 ? { extraHeaders: request.headers } : {},
|
|
551
|
+
returnRawResponse: true,
|
|
552
|
+
signal: request.signal
|
|
553
|
+
});
|
|
554
|
+
}
|
|
537
555
|
if (request.audio !== void 0) return await raw.run(request.model, {
|
|
538
556
|
...request.input,
|
|
539
557
|
audio: {
|
|
@@ -669,9 +687,34 @@ function httpTransport({ accountId, apiToken }) {
|
|
|
669
687
|
});
|
|
670
688
|
}
|
|
671
689
|
}
|
|
690
|
+
/**
|
|
691
|
+
* A multipart body goes to Workers AI's own run route too. `fetch` writes
|
|
692
|
+
* the content type with the form's boundary, so the caller's must not
|
|
693
|
+
* replace it.
|
|
694
|
+
*/
|
|
695
|
+
async function runMultipart(request, fields) {
|
|
696
|
+
const url = `${runBase}/run/${request.model}`;
|
|
697
|
+
const headers = withCredential(request.headers, "authorization", apiToken);
|
|
698
|
+
headers.delete("content-type");
|
|
699
|
+
try {
|
|
700
|
+
return await bareWorkersAIAnswer(await fetch(url, {
|
|
701
|
+
body: multipartForm(fields),
|
|
702
|
+
headers,
|
|
703
|
+
method: "POST",
|
|
704
|
+
signal: request.signal
|
|
705
|
+
}));
|
|
706
|
+
} catch (error) {
|
|
707
|
+
throw normalizeThrownError(error, {
|
|
708
|
+
model: request.model,
|
|
709
|
+
requestBodyValues: request.input,
|
|
710
|
+
url
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
}
|
|
672
714
|
return {
|
|
673
715
|
logIdFallback() {},
|
|
674
716
|
async run(request) {
|
|
717
|
+
if (request.multipart !== void 0) return runMultipart(request, request.multipart);
|
|
675
718
|
if (request.audio !== void 0) return runRawAudio(request, request.audio);
|
|
676
719
|
const workersAI = isWorkersAIId(request.model);
|
|
677
720
|
const run = runOptions(request);
|
|
@@ -1038,7 +1081,6 @@ const STRICT_OPENAI = {
|
|
|
1038
1081
|
nullAssistantContent: "allowed",
|
|
1039
1082
|
reasoningEffortLevels: "basic",
|
|
1040
1083
|
reasoningOff: "unsupported",
|
|
1041
|
-
reasoningOffStreamLabel: "content",
|
|
1042
1084
|
reasoningReplay: "drop",
|
|
1043
1085
|
requiresAssistantAfterToolResult: false,
|
|
1044
1086
|
toolCallIds: "any",
|
|
@@ -1070,8 +1112,7 @@ const OVERRIDES = [
|
|
|
1070
1112
|
requiresAssistantAfterToolResult: true,
|
|
1071
1113
|
toolCallIds: "alnum-9"
|
|
1072
1114
|
}],
|
|
1073
|
-
["@cf/google/", { modelEchoSuffix: "-external" }]
|
|
1074
|
-
["@cf/nvidia/nemotron-", { reasoningOffStreamLabel: "reasoning" }]
|
|
1115
|
+
["@cf/google/", { modelEchoSuffix: "-external" }]
|
|
1075
1116
|
];
|
|
1076
1117
|
/** The quirks for a catalog id: base profile plus the longest matching override. */
|
|
1077
1118
|
function quirksFor(modelId) {
|
|
@@ -1313,7 +1354,6 @@ function prepareChatCompletionsRequest(input, modelId) {
|
|
|
1313
1354
|
}
|
|
1314
1355
|
return {
|
|
1315
1356
|
body,
|
|
1316
|
-
reasoningOff: isRecord$3(body.chat_template_kwargs) && body.chat_template_kwargs.enable_thinking === false,
|
|
1317
1357
|
warnings
|
|
1318
1358
|
};
|
|
1319
1359
|
}
|
|
@@ -1580,13 +1620,12 @@ function stripEchoSuffix(chunk, modelId) {
|
|
|
1580
1620
|
model: chunk.model.slice(0, -suffix.length)
|
|
1581
1621
|
} : chunk;
|
|
1582
1622
|
}
|
|
1583
|
-
function normalizeDelta(delta
|
|
1623
|
+
function normalizeDelta(delta) {
|
|
1584
1624
|
const out = { ...delta };
|
|
1585
1625
|
const reasoning = typeof out.reasoning_content === "string" && out.reasoning_content !== "" ? out.reasoning_content : typeof out.reasoning === "string" && out.reasoning !== "" ? out.reasoning : void 0;
|
|
1586
1626
|
delete out.reasoning;
|
|
1587
1627
|
delete out.reasoning_content;
|
|
1588
|
-
if (reasoning !== void 0)
|
|
1589
|
-
else out.reasoning_content = reasoning;
|
|
1628
|
+
if (reasoning !== void 0) out.reasoning_content = reasoning;
|
|
1590
1629
|
if (Array.isArray(out.tool_calls)) out.tool_calls = out.tool_calls.map((call, index) => {
|
|
1591
1630
|
if (!isRecord(call)) return call;
|
|
1592
1631
|
const fn = isRecord(call.function) ? call.function : void 0;
|
|
@@ -1599,9 +1638,7 @@ function normalizeDelta(delta, relabelReasoning) {
|
|
|
1599
1638
|
* The transform. Backpressure is preserved: nothing is buffered except the
|
|
1600
1639
|
* single pending usage chunk, which must wait for the tail.
|
|
1601
1640
|
*/
|
|
1602
|
-
function normalizeChatCompletionsStream(modelId
|
|
1603
|
-
const quirks = quirksFor(modelId);
|
|
1604
|
-
const relabelReasoning = options.reasoningOff === true && quirks.reasoningOffStreamLabel === "reasoning";
|
|
1641
|
+
function normalizeChatCompletionsStream(modelId) {
|
|
1605
1642
|
let id;
|
|
1606
1643
|
let model;
|
|
1607
1644
|
let created;
|
|
@@ -1668,7 +1705,7 @@ function normalizeChatCompletionsStream(modelId, options = {}) {
|
|
|
1668
1705
|
const choices = chunk.choices.map((choice) => {
|
|
1669
1706
|
if (!isRecord(choice)) return choice;
|
|
1670
1707
|
if (typeof choice.finish_reason === "string") sawFinishReason = true;
|
|
1671
|
-
const delta = isRecord(choice.delta) ? normalizeDelta(choice.delta
|
|
1708
|
+
const delta = isRecord(choice.delta) ? normalizeDelta(choice.delta) : choice.delta;
|
|
1672
1709
|
if (isRecord(delta)) {
|
|
1673
1710
|
if (typeof delta.content === "string" && delta.content !== "") sawContent = true;
|
|
1674
1711
|
if (typeof delta.reasoning_content === "string") sawContent = true;
|
|
@@ -1825,32 +1862,71 @@ function sseDataStream() {
|
|
|
1825
1862
|
*/
|
|
1826
1863
|
const PROMPT_AND_STEPS_ONLY = /^@cf\/black-forest-labs\/flux-1/;
|
|
1827
1864
|
/**
|
|
1865
|
+
* The FLUX.2 models (`flux-2-dev`, `flux-2-klein-4b`, `flux-2-klein-9b`) take
|
|
1866
|
+
* their whole input as multipart form data, even a bare prompt: `prompt`,
|
|
1867
|
+
* `width`, `height`, `seed`, `guidance`, and up to four reference images as
|
|
1868
|
+
* `input_image_0` to `input_image_3`.
|
|
1869
|
+
*
|
|
1870
|
+
* @see https://developers.cloudflare.com/workers-ai/models/flux-2-klein-9b/
|
|
1871
|
+
*/
|
|
1872
|
+
const MULTIPART_FORM = /^@cf\/black-forest-labs\/flux-2-/;
|
|
1873
|
+
/**
|
|
1874
|
+
* The klein models are distilled to a fixed four steps, so `steps` is not
|
|
1875
|
+
* one of their fields; `flux-2-dev` takes it.
|
|
1876
|
+
*/
|
|
1877
|
+
const FIXED_STEPS = /^@cf\/black-forest-labs\/flux-2-klein-/;
|
|
1878
|
+
/** Reports each knob that is set as one the model does not take. */
|
|
1879
|
+
function dropped(modelId, message, knobs) {
|
|
1880
|
+
return knobs.filter(([, value]) => value !== void 0).map(([feature]) => ({
|
|
1881
|
+
feature,
|
|
1882
|
+
message: `${modelId} ${message}`
|
|
1883
|
+
}));
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1828
1886
|
* Builds the run-path body for a text-to-image model: `prompt`, `width`,
|
|
1829
|
-
* `height`, `num_steps`, `guidance`, `strength`, `negative_prompt` and `seed
|
|
1830
|
-
*
|
|
1887
|
+
* `height`, `num_steps`, `guidance`, `strength`, `negative_prompt` and `seed`;
|
|
1888
|
+
* the flux-1 two-key subset; or the FLUX.2 form fields. Every knob the model
|
|
1889
|
+
* does not take comes back as a warning.
|
|
1831
1890
|
*
|
|
1832
1891
|
* @experimental This surface is experimental and may change.
|
|
1833
1892
|
*/
|
|
1834
1893
|
function buildImageInput(modelId, prompt, settings) {
|
|
1835
|
-
const warnings = [];
|
|
1836
1894
|
const input = { prompt };
|
|
1837
1895
|
if (PROMPT_AND_STEPS_ONLY.test(modelId)) {
|
|
1838
1896
|
if (settings.steps !== void 0) input.steps = settings.steps;
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1897
|
+
return {
|
|
1898
|
+
body: "prompt-and-steps",
|
|
1899
|
+
input,
|
|
1900
|
+
warnings: dropped(modelId, "takes only a prompt and steps.", [
|
|
1901
|
+
["size", settings.width ?? settings.height],
|
|
1902
|
+
["seed", settings.seed],
|
|
1903
|
+
["guidance", settings.guidance],
|
|
1904
|
+
["negativePrompt", settings.negativePrompt],
|
|
1905
|
+
["strength", settings.strength],
|
|
1906
|
+
["files", settings.sourceImage === true ? true : void 0],
|
|
1907
|
+
["mask", settings.mask === true ? true : void 0]
|
|
1908
|
+
])
|
|
1909
|
+
};
|
|
1910
|
+
}
|
|
1911
|
+
if (MULTIPART_FORM.test(modelId)) {
|
|
1912
|
+
const fixedSteps = FIXED_STEPS.test(modelId);
|
|
1913
|
+
if (settings.width !== void 0) input.width = settings.width;
|
|
1914
|
+
if (settings.height !== void 0) input.height = settings.height;
|
|
1915
|
+
if (settings.seed !== void 0) input.seed = settings.seed;
|
|
1916
|
+
if (settings.guidance !== void 0) input.guidance = settings.guidance;
|
|
1917
|
+
if (settings.steps !== void 0 && !fixedSteps) input.steps = settings.steps;
|
|
1918
|
+
const warnings = dropped(modelId, "does not take this.", [
|
|
1843
1919
|
["negativePrompt", settings.negativePrompt],
|
|
1844
1920
|
["strength", settings.strength],
|
|
1845
|
-
["files", settings.sourceImage === true ? true : void 0],
|
|
1846
1921
|
["mask", settings.mask === true ? true : void 0]
|
|
1847
|
-
])
|
|
1848
|
-
|
|
1849
|
-
|
|
1922
|
+
]);
|
|
1923
|
+
if (fixedSteps && settings.steps !== void 0) warnings.push({
|
|
1924
|
+
feature: "steps",
|
|
1925
|
+
message: `${modelId} always runs four steps.`
|
|
1850
1926
|
});
|
|
1851
1927
|
return {
|
|
1928
|
+
body: "multipart",
|
|
1852
1929
|
input,
|
|
1853
|
-
minimal: true,
|
|
1854
1930
|
warnings
|
|
1855
1931
|
};
|
|
1856
1932
|
}
|
|
@@ -1862,11 +1938,27 @@ function buildImageInput(modelId, prompt, settings) {
|
|
|
1862
1938
|
if (settings.strength !== void 0) input.strength = settings.strength;
|
|
1863
1939
|
if (settings.negativePrompt !== void 0) input.negative_prompt = settings.negativePrompt;
|
|
1864
1940
|
return {
|
|
1941
|
+
body: "json",
|
|
1865
1942
|
input,
|
|
1866
|
-
|
|
1867
|
-
warnings
|
|
1943
|
+
warnings: []
|
|
1868
1944
|
};
|
|
1869
1945
|
}
|
|
1946
|
+
/**
|
|
1947
|
+
* The form fields for a `multipart` image request: each `input` value as
|
|
1948
|
+
* text, then the reference images as `input_image_0`, `input_image_1`, and
|
|
1949
|
+
* so on. Images past {@link MAX_MULTIPART_SOURCE_IMAGES} are left out; the
|
|
1950
|
+
* caller warns about them.
|
|
1951
|
+
*
|
|
1952
|
+
* @experimental This surface is experimental and may change.
|
|
1953
|
+
*/
|
|
1954
|
+
function imageMultipartFields(input, images) {
|
|
1955
|
+
const fields = {};
|
|
1956
|
+
for (const [name, value] of Object.entries(input)) if (value !== void 0) fields[name] = String(value);
|
|
1957
|
+
images.slice(0, 4).forEach((image, index) => {
|
|
1958
|
+
fields[`input_image_${index}`] = image;
|
|
1959
|
+
});
|
|
1960
|
+
return fields;
|
|
1961
|
+
}
|
|
1870
1962
|
const JPEG_PREFIX = "/9j/";
|
|
1871
1963
|
const PNG_PREFIX = "iVBORw0KGgo";
|
|
1872
1964
|
const WEBP_PREFIX = "UklGR";
|
|
@@ -1886,6 +1978,6 @@ function imageMediaTypeOf(base64) {
|
|
|
1886
1978
|
return "image/png";
|
|
1887
1979
|
}
|
|
1888
1980
|
//#endregion
|
|
1889
|
-
export {
|
|
1981
|
+
export { isRetryableStatus as C, isRunPathLanguageModelId as E, isAbortError as S, isDynamicRouteId as T, headersToObject as _, normalizeChatCompletionsStream as a, CloudflareAIError as b, GATEWAY_PROVIDER_NAMES as c, requireGatewayProvider as d, resolveGatewayProvider as f, errorFromResponse as g, errorFromGatewayEnvelope as h, sseDataStream as i, gatewaySlugForBaseUrl as l, definedHeaders as m, imageMediaTypeOf as n, normalizeChatCompletion as o, createTransport as p, imageMultipartFields as r, prepareChatCompletionsRequest as s, buildImageInput as t, isGatewayShapedUrl as u, isGatewayErrorEnvelope as v, isCatalogModelId as w, classifyStatus as x, unwrapEnvelope as y };
|
|
1890
1982
|
|
|
1891
|
-
//# sourceMappingURL=images-
|
|
1983
|
+
//# sourceMappingURL=images-D4gtE06D.js.map
|