@averyyy/pi-agent-core 1.4.0-piclient.9 → 1.5.0-piclient.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -6
- package/dist/harness/pico3/system.d.ts.map +1 -1
- package/dist/harness/pico3/system.js +2 -1
- package/dist/harness/pico3/system.js.map +1 -1
- package/dist/harness/pico3/types.d.ts +9 -18
- package/dist/harness/pico3/types.d.ts.map +1 -1
- package/dist/harness/pico3/types.js.map +1 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +11 -10
- package/dist/proxy.js.map +1 -1
- package/dist/types.d.ts +16 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +8 -7
package/README.md
CHANGED
|
@@ -455,18 +455,20 @@ const agent = new Agent({
|
|
|
455
455
|
|
|
456
456
|
## Tools
|
|
457
457
|
|
|
458
|
-
Define tools using `AgentTool
|
|
458
|
+
Define tools using `AgentTool`. `parameters` is any JSON Schema object; built with `@earendil-works/pi-schema`'s builders, it also types `params` (other schemas give `unknown`, `AgentTool<any>` gives `any`):
|
|
459
459
|
|
|
460
460
|
```typescript
|
|
461
|
-
import {
|
|
461
|
+
import { obj, str } from "@earendil-works/pi-schema";
|
|
462
462
|
|
|
463
|
-
const
|
|
463
|
+
const readFileParameters = obj({
|
|
464
|
+
path: str({ description: "File path" }),
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
const readFileTool: AgentTool<typeof readFileParameters> = {
|
|
464
468
|
name: "read_file",
|
|
465
469
|
label: "Read File", // For UI display
|
|
466
470
|
description: "Read a file's contents",
|
|
467
|
-
parameters:
|
|
468
|
-
path: Type.String({ description: "File path" }),
|
|
469
|
-
}),
|
|
471
|
+
parameters: readFileParameters,
|
|
470
472
|
// Override execution mode for this tool (optional).
|
|
471
473
|
// "sequential" forces the entire batch to run one at a time.
|
|
472
474
|
// "parallel" allows concurrent execution with other tool calls.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system.d.ts","sourceRoot":"","sources":["../../../src/harness/pico3/system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EACX,kBAAkB,EAClB,WAAW,EACX,MAAM,EACN,KAAK,EACL,QAAQ,EACR,UAAU,EACV,EAAE,EACF,SAAS,EACT,eAAe,EACf,OAAO,EACP,MAAM,EACN,aAAa,EACb,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"system.d.ts","sourceRoot":"","sources":["../../../src/harness/pico3/system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EACX,kBAAkB,EAClB,WAAW,EACX,MAAM,EACN,KAAK,EACL,QAAQ,EACR,UAAU,EACV,EAAE,EACF,SAAS,EACT,eAAe,EACf,OAAO,EACP,MAAM,EACN,aAAa,EACb,MAAM,YAAY,CAAC;AAQpB,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC7D,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;CACzB;AACD,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,SAAS,EAAE,UAAU,EAAE;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;CACzB,GAAG,aAAa,CAAC,CAAC,CAAC,CAEnB;AAED,MAAM,MAAM,eAAe,GAAG;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC;AAC9C,MAAM,MAAM,SAAS,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC;AAC9D,eAAO,MAAM,cAAc;aAC1B,QAAQ;aACR,WAAW;aAIX,MA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IAAC,KAAK,EAAE,SAAS,kBAAkB,EAAE,CAAA;CAAE,CAAC,CA2BvE;AAED,4GAA4G;AAC5G,wBAAsB,gBAAgB,CACrC,EAAE,EAAE,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAC3B,cAAc,EAAE,EAAE,EAClB,QAAQ,EAAE,mBAAmB,EAC7B,SAAS,EAAE,SAAS,EACpB,OAAO,EAAE,SAAS,EAClB,KAAK,EAAE,SAAS,kBAAkB,EAAE,EACpC,GAAG,EAAE,MAAM,GACT,OAAO,CAAC;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,KAAK,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IAAC,KAAK,CAAC,EAAE,WAAW,EAAE,CAAA;CAAE,GAAG,SAAS,CAAC,CAuE5G;AAED,sGAAsG;AACtG,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAQxF;AAED,YAAY,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { toStored } from "./types.js";
|
|
1
2
|
export function defineSystemSection(definition) {
|
|
2
3
|
return Object.freeze(definition);
|
|
3
4
|
}
|
|
@@ -167,7 +168,7 @@ export async function planManagedEntry(tx, conversationId, snapshot, canonical,
|
|
|
167
168
|
const toolOf = (t) => ({
|
|
168
169
|
name: t.name,
|
|
169
170
|
description: t.description,
|
|
170
|
-
parameters:
|
|
171
|
+
parameters: toStored(t.parameters),
|
|
171
172
|
});
|
|
172
173
|
// Previous effective tools: those declared by the newest managed entry chain (we recompute from canonical's owner: the tail message).
|
|
173
174
|
const { messages } = await tx.context(conversationId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/harness/pico3/system.ts"],"names":[],"mapp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AK,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7E,CAAC;IACF,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord\";\nimport type {\n\tAnyToolDeclaration,\n\tContextEdit,\n\tCoreTx,\n\tEntry,\n\tHookInfo,\n\tHookResult,\n\tId,\n\tJsonValue,\n\tRewindableState,\n\tRuntime,\n\tStored,\n\tSystemMessage,\n} from \"./types.ts\";\n\n// ---------------------------------------------------------------------------\n// Sections (pico §12.1). A section is a stable key plus a pure renderer. Only\n// keys, payloads and rendered text are stored; never renderers.\n// ---------------------------------------------------------------------------\n\nexport interface SystemSection<T extends JsonValue = JsonValue> {\n\treadonly key: string;\n\trender(value: T): string;\n}\nexport function defineSystemSection<T extends JsonValue>(definition: {\n\tkey: string;\n\trender(value: T): string;\n}): SystemSection<T> {\n\treturn Object.freeze(definition);\n}\n\nexport type EnvironmentInfo = { cwd: string };\nexport type SkillInfo = { name: string; description: string };\nexport const systemSections = {\n\tidentity: defineSystemSection<string>({ key: \"identity\", render: (v) => v }),\n\tenvironment: defineSystemSection<EnvironmentInfo>({\n\t\tkey: \"environment\",\n\t\trender: (v) => `Working directory: ${v.cwd}`,\n\t}),\n\tskills: defineSystemSection<SkillInfo[]>({\n\t\tkey: \"skills\",\n\t\trender: (v) => v.map((s) => `- ${s.name}: ${s.description}`).join(\"\\n\"),\n\t}),\n} as const;\n\n/** Section seed for a new conversation (§8.1): set with a checked pair, or remove an inherited key. */\nexport type SectionSeed = { key: string; value: JsonValue } | { key: string; remove: true };\nexport const sectionSeed = <T extends JsonValue>(section: SystemSection<T>, value: T): SectionSeed => ({\n\tkey: section.key,\n\tvalue,\n});\nexport const removeSection = (key: string): SectionSeed => ({ key, remove: true });\n\n// ---------------------------------------------------------------------------\n// The managed entry (§12.3)\n// ---------------------------------------------------------------------------\n\nexport type SectionRecord =\n\t| { key: string; action: \"set\"; value: JsonValue; rendered: string }\n\t| { key: string; action: \"remove\" };\nexport type SystemEntryData = { baseline?: true; sections: SectionRecord[] };\n/** A metadata-only delta has `model: []`. */\nexport type SystemEntry = Entry & { kind: \"pi.system\"; model: [] | [Stored<SystemMessage>]; data: SystemEntryData };\n\n// ---------------------------------------------------------------------------\n// Canonical state (§12.4): fold the fork-visible managed entries from the\n// newest baseline forward. Uses the kind scan; never depends on heads or edits.\n// ---------------------------------------------------------------------------\n\ntype SectionState = { value: JsonValue; rendered: string };\nexport type Canonical = Map<string, SectionState>; // insertion order is canonical order\n\nexport async function foldCanonical(\n\treads: Pick<CoreTx, \"scanEntries\">,\n\tconversationId: Id,\n): Promise<{ canonical: Canonical; newestManaged: Id | null; newestBaseline: Id | null }> {\n\tconst managed: SystemEntry[] = [];\n\tlet before: Id | undefined;\n\tlet baseline: Id | null = null;\n\tscan: for (;;) {\n\t\tconst page = await reads.scanEntries({\n\t\t\tconversationId,\n\t\t\tkind: \"pi.system\",\n\t\t\tlimit: 64,\n\t\t\t...(before === undefined ? {} : { before }),\n\t\t});\n\t\tfor (const e of page) {\n\t\t\tmanaged.push(e as SystemEntry);\n\t\t\tif ((e as SystemEntry).data.baseline) {\n\t\t\t\tbaseline = e.id;\n\t\t\t\tbreak scan;\n\t\t\t}\n\t\t}\n\t\tif (page.length < 64) break;\n\t\tbefore = page[page.length - 1]!.id;\n\t}\n\tmanaged.reverse();\n\tconst canonical: Canonical = new Map();\n\tfor (const e of managed)\n\t\tfor (const r of e.data.sections)\n\t\t\tr.action === \"remove\"\n\t\t\t\t? canonical.delete(r.key)\n\t\t\t\t: canonical.set(r.key, { value: r.value, rendered: r.rendered });\n\treturn { canonical, newestManaged: managed[managed.length - 1]?.id ?? null, newestBaseline: baseline };\n}\n\n// ---------------------------------------------------------------------------\n// Draft (§12.2): what `systemInstructions` handlers edit.\n// ---------------------------------------------------------------------------\n\nexport interface SystemSectionDraft {\n\tget<T extends JsonValue>(section: SystemSection<T>): T | undefined; // owned copy\n\tset<T extends JsonValue>(section: SystemSection<T>, value: T): void; // existing key keeps position; new key appends\n\tdelete(section: { key: string }): void;\n\twrap<T extends JsonValue>(section: SystemSection<T>, transform: (rendered: string) => string): void; // preparation-local\n}\n\nclass Draft implements SystemSectionDraft {\n\tvalues = new Map<string, JsonValue>();\n\twrappers = new Map<string, ((r: string) => string)[]>();\n\ttouched = new Set<string>();\n\tconstructor(seed: Canonical) {\n\t\tfor (const [k, s] of seed) this.values.set(k, s.value);\n\t}\n\tget<T extends JsonValue>(section: SystemSection<T>) {\n\t\tconst v = this.values.get(section.key);\n\t\treturn v === undefined ? undefined : (structuredClone(v) as T);\n\t}\n\tset<T extends JsonValue>(section: SystemSection<T>, value: T) {\n\t\tthis.values.set(section.key, value);\n\t\tthis.touched.add(section.key);\n\t}\n\tdelete(section: { key: string }) {\n\t\tthis.values.delete(section.key);\n\t\tthis.wrappers.delete(section.key);\n\t\tthis.touched.add(section.key);\n\t}\n\twrap<T extends JsonValue>(section: SystemSection<T>, transform: (r: string) => string) {\n\t\t(this.wrappers.get(section.key) ?? this.wrappers.set(section.key, []).get(section.key)!).push(transform);\n\t\tthis.touched.add(section.key);\n\t}\n\tsnapshot() {\n\t\treturn {\n\t\t\tvalues: new Map(this.values),\n\t\t\twrappers: new Map([...this.wrappers].map(([k, v]) => [k, [...v]])),\n\t\t\ttouched: new Set(this.touched),\n\t\t};\n\t}\n\trestore(s: ReturnType<Draft[\"snapshot\"]>) {\n\t\tthis.values = s.values;\n\t\tthis.wrappers = s.wrappers;\n\t\tthis.touched = s.touched;\n\t}\n}\n\n/** Render touched sections (wrappers apply after rendering, in registration order); untouched keep their stored text. */\nfunction freeze(draft: Draft, canonical: Canonical, registry: ReadonlyMap<string, SystemSection>): Canonical {\n\tconst desired: Canonical = new Map();\n\tfor (const [key, value] of draft.values) {\n\t\tif (!draft.touched.has(key)) {\n\t\t\tconst prev = canonical.get(key);\n\t\t\tif (prev) desired.set(key, prev);\n\t\t\tcontinue;\n\t\t}\n\t\tconst def = registry.get(key);\n\t\tif (def === undefined) continue; // unregistered: cannot re-render; treated as removed\n\t\tlet rendered = (def as SystemSection).render(value);\n\t\tfor (const w of draft.wrappers.get(key) ?? []) rendered = w(rendered);\n\t\tdesired.set(key, { value, rendered });\n\t}\n\treturn desired;\n}\n\n// ---------------------------------------------------------------------------\n// Preparation (§12.5)\n// ---------------------------------------------------------------------------\n\nexport interface SectionRegistry {\n\treadonly map: ReadonlyMap<string, SystemSection>;\n\treadonly revision: number;\n}\nexport interface ToolRegistry {\n\treadonly map: ReadonlyMap<string, AnyToolDeclaration>;\n\treadonly revision: number;\n}\n\n/** Snapshot S. Compared field by field before the `prepared` commit. */\nexport interface PreparationSnapshot {\n\tnewestManaged: Id | null;\n\tnewestBaseline: Id | null;\n\tnewestHead: Id | null;\n\tsettings: { model?: JsonValue; thinkingLevel: JsonValue; selectedTools: string[]; profile: JsonValue };\n\tsectionsRev: number;\n\ttoolsRev: number;\n}\nexport const sameSnapshot = (a: PreparationSnapshot, b: PreparationSnapshot) => JSON.stringify(a) === JSON.stringify(b);\n\nexport async function takeSnapshot(\n\ttx: Pick<CoreTx, \"scanEntries\" | \"newestEntry\" | \"snapshot\" | \"conversation\">,\n\tconversationId: Id,\n\tsections: SectionRegistry,\n\ttools: ToolRegistry,\n): Promise<{ snapshot: PreparationSnapshot; canonical: Canonical; seed: readonly SectionSeed[] | undefined }> {\n\tconst { canonical, newestManaged, newestBaseline } = await foldCanonical(tx, conversationId);\n\tconst head = await tx.newestEntry(conversationId, { withHead: true });\n\tconst r = tx.snapshot({ doc: \"rewindable\", conversationId }); // a plain copy: the snapshot outlives this transaction\n\tconst conv = await tx.conversation(conversationId);\n\treturn {\n\t\tsnapshot: {\n\t\t\tnewestManaged,\n\t\t\tnewestBaseline,\n\t\t\tnewestHead: head?.id ?? null,\n\t\t\tsettings: {\n\t\t\t\t...(r.model === undefined ? {} : { model: r.model }),\n\t\t\t\tthinkingLevel: r.thinkingLevel,\n\t\t\t\tselectedTools: [...r.selectedTools],\n\t\t\t\tprofile: r.profile,\n\t\t\t},\n\t\t\tsectionsRev: sections.revision,\n\t\t\ttoolsRev: tools.revision,\n\t\t},\n\t\tcanonical,\n\t\tseed: newestManaged === null ? conv?.sections : undefined, // §8.1: the seed applies while there is no local managed entry\n\t};\n}\n\nexport interface SystemInstructionsHooks {\n\t/** Edit the draft; optionally override the tool loadout (last override wins). A throwing handler's edits are rolled back. */\n\tsystemInstructions(\n\t\tinput: {\n\t\t\tsections: SystemSectionDraft;\n\t\t\tconfig: PreparationSnapshot[\"settings\"];\n\t\t\ttools: readonly AnyToolDeclaration[];\n\t\t},\n\t\tinfo: HookInfo,\n\t\tctx: Context,\n\t): HookResult<{ tools?: readonly AnyToolDeclaration[] }>;\n}\n\n/** Off the line: seed the draft, run handlers, freeze. */\nexport async function prepareDraft(\n\trt: Pick<Runtime<SystemInstructionsHooks>, \"hooks\" | \"tools\">,\n\tsections: SectionRegistry,\n\tcanonical: Canonical,\n\tseed: readonly SectionSeed[] | undefined,\n\tsettings: PreparationSnapshot[\"settings\"],\n\tonReport: (m: string) => void,\n\tctx: Context,\n): Promise<{ desired: Canonical; tools: readonly AnyToolDeclaration[] }> {\n\tconst draft = new Draft(canonical);\n\tfor (const s of seed ?? [])\n\t\t\"remove\" in s ? draft.delete({ key: s.key }) : draft.set({ key: s.key, render: () => \"\" }, s.value);\n\n\tconst defaultTools: AnyToolDeclaration[] = [];\n\tfor (const name of settings.selectedTools) {\n\t\tconst t = rt.tools.get(name);\n\t\tt ? defaultTools.push(t) : onReport(`selected tool ${name} is not registered`);\n\t}\n\tlet tools: readonly AnyToolDeclaration[] = defaultTools;\n\tfor (const binding of rt.hooks.handlers()) {\n\t\tconst before = draft.snapshot();\n\t\ttry {\n\t\t\tconst out = await binding.handlers.systemInstructions?.(\n\t\t\t\t{ sections: draft, config: settings, tools: defaultTools },\n\t\t\t\tbinding.api,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tif (out?.tools) tools = out.tools;\n\t\t} catch (error) {\n\t\t\tif (ctx.abortSignal?.aborted) throw error;\n\t\t\tdraft.restore(before); // collect / skip: this handler's edits are rolled back\n\t\t\tonReport(String(error));\n\t\t}\n\t}\n\treturn { desired: freeze(draft, canonical, sections.map), tools };\n}\n\n/** On the line, in the `prepared` commit: diff desired against canonical; baseline if a head intervened. */\nexport async function planManagedEntry(\n\ttx: Pick<CoreTx, \"context\">,\n\tconversationId: Id,\n\tsnapshot: PreparationSnapshot,\n\tcanonical: Canonical,\n\tdesired: Canonical,\n\ttools: readonly AnyToolDeclaration[],\n\tnow: number,\n): Promise<{ data: SystemEntryData; model: [] | [Stored<SystemMessage>]; edits?: ContextEdit[] } | undefined> {\n\t// §12.4: no managed history at all → first preparation appends a full baseline; and a usable\n\t// baseline must follow the newest head.\n\tconst needBaseline =\n\t\tsnapshot.newestManaged === null ||\n\t\t(snapshot.newestHead !== null &&\n\t\t\t(snapshot.newestBaseline === null || snapshot.newestHead > snapshot.newestBaseline));\n\tconst toolOf = (t: AnyToolDeclaration) => ({\n\t\tname: t.name,\n\t\tdescription: t.description,\n\t\tparameters: structuredClone(t.parameters) as Stored<SystemMessage>[\"toolsAdded\"] extends (infer X)[] | undefined\n\t\t\t? X extends { parameters: infer PP }\n\t\t\t\t? PP\n\t\t\t\t: never\n\t\t\t: never,\n\t});\n\n\t// Previous effective tools: those declared by the newest managed entry chain (we recompute from canonical's owner: the tail message).\n\tconst { messages } = await tx.context(conversationId);\n\tconst previous = new Map<string, { name: string }>();\n\tfor (const m of messages)\n\t\tif (m.role === \"system\") {\n\t\t\tfor (const t of (m as SystemMessage).toolsRemoved ?? []) previous.delete(t.name);\n\t\t\tfor (const t of (m as SystemMessage).toolsAdded ?? []) previous.set(t.name, t);\n\t\t}\n\n\tif (needBaseline) {\n\t\tconst sections: SectionRecord[] = [...desired].map(([key, s]) => ({\n\t\t\tkey,\n\t\t\taction: \"set\",\n\t\t\tvalue: s.value,\n\t\t\trendered: s.rendered,\n\t\t}));\n\t\tconst content = sections.map((s) => (s.action === \"set\" ? `## ${s.key}\\n${s.rendered}` : \"\")).join(\"\\n\\n\");\n\t\tconst { entries } = await tx.context(conversationId);\n\t\tconst edits: ContextEdit[] = entries\n\t\t\t.filter((e: Entry) => e.kind === \"pi.system\" && e.id > (snapshot.newestHead ?? 0))\n\t\t\t.map((e: Entry) => ({ target: e.id, action: \"omit\" as const }));\n\t\tconst message = {\n\t\t\trole: \"system\",\n\t\t\tcontent,\n\t\t\ttoolsAdded: tools.map(toolOf),\n\t\t\ttimestamp: now,\n\t\t} as Stored<SystemMessage>;\n\t\treturn { data: { baseline: true, sections }, model: [message], ...(edits.length ? { edits } : {}) };\n\t}\n\n\tconst changed: SectionRecord[] = [];\n\tfor (const [key, s] of desired) {\n\t\tconst prev = canonical.get(key);\n\t\tif (!prev || prev.rendered !== s.rendered || JSON.stringify(prev.value) !== JSON.stringify(s.value))\n\t\t\tchanged.push({ key, action: \"set\", value: s.value, rendered: s.rendered });\n\t}\n\tfor (const key of canonical.keys()) if (!desired.has(key)) changed.push({ key, action: \"remove\" });\n\tconst added = tools.filter((t) => !previous.has(t.name));\n\tconst removed = [...previous.values()].filter((p) => !tools.some((t) => t.name === p.name));\n\tif (changed.length === 0 && added.length === 0 && removed.length === 0) return undefined;\n\n\tconst renderChanged = changed.some((s) => s.action === \"remove\" || canonical.get(s.key)?.rendered !== s.rendered);\n\tif (!renderChanged && added.length === 0 && removed.length === 0) return { data: { sections: changed }, model: [] }; // metadata-only delta\n\tconst content = changed\n\t\t.map((s) =>\n\t\t\ts.action === \"set\"\n\t\t\t\t? `The ${s.key} section now reads:\\n${s.rendered}`\n\t\t\t\t: `The ${s.key} section no longer applies.`,\n\t\t)\n\t\t.join(\"\\n\\n\");\n\tconst message = {\n\t\trole: \"system\",\n\t\tcontent,\n\t\t...(added.length ? { toolsAdded: added.map(toolOf) } : {}),\n\t\t...(removed.length ? { toolsRemoved: removed } : {}),\n\t\ttimestamp: now,\n\t} as Stored<SystemMessage>;\n\treturn { data: { sections: changed }, model: [message] };\n}\n\n/** Tools effective in a projected request: fold toolsAdded/toolsRemoved across its SystemMessages. */\nexport function effectiveTools(messages: readonly { role: string }[]): { name: string }[] {\n\tconst tools = new Map<string, { name: string }>();\n\tfor (const m of messages)\n\t\tif (m.role === \"system\") {\n\t\t\tfor (const t of (m as SystemMessage).toolsRemoved ?? []) tools.delete(t.name);\n\t\t\tfor (const t of (m as SystemMessage).toolsAdded ?? []) tools.set(t.name, t);\n\t\t}\n\treturn [...tools.values()];\n}\n\nexport type { RewindableState, Runtime };\n"]}
|
|
1
|
+
{"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/harness/pico3/system.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAWtC,MAAM,UAAU,mBAAmB,CAAsB,UAGxD;IACA,OAAO,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AAClC,CAAC;AAID,MAAM,CAAC,MAAM,cAAc,GAAG;IAC7B,QAAQ,EAAE,mBAAmB,CAAS,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;IAC5E,WAAW,EAAE,mBAAmB,CAAkB;QACjD,GAAG,EAAE,aAAa;QAClB,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,sBAAsB,CAAC,CAAC,GAAG,EAAE;KAC5C,CAAC;IACF,MAAM,EAAE,mBAAmB,CAAc;QACxC,GAAG,EAAE,QAAQ;QACb,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;KACvE,CAAC;CACO,CAAC;AAIX,MAAM,CAA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;KACW,CAAC;IAC3B,OAAO,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;AAC1D,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,cAAc,CAAC,QAAqC;IACnE,MAAM,KAAK,GAAG,IAAI,GAAG,EAA4B,CAAC;IAClD,KAAK,MAAM,CAAC,IAAI,QAAQ;QACvB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACzB,KAAK,MAAM,CAAC,IAAK,CAAmB,CAAC,YAAY,IAAI,EAAE;gBAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC9E,KAAK,MAAM,CAAC,IAAK,CAAmB,CAAC,UAAU,IAAI,EAAE;gBAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7E,CAAC;IACF,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord\";\nimport type {\n\tAnyToolDeclaration,\n\tContextEdit,\n\tCoreTx,\n\tEntry,\n\tHookInfo,\n\tHookResult,\n\tId,\n\tJsonValue,\n\tRewindableState,\n\tRuntime,\n\tStored,\n\tSystemMessage,\n} from \"./types.ts\";\nimport { toStored } from \"./types.ts\";\n\n// ---------------------------------------------------------------------------\n// Sections (pico §12.1). A section is a stable key plus a pure renderer. Only\n// keys, payloads and rendered text are stored; never renderers.\n// ---------------------------------------------------------------------------\n\nexport interface SystemSection<T extends JsonValue = JsonValue> {\n\treadonly key: string;\n\trender(value: T): string;\n}\nexport function defineSystemSection<T extends JsonValue>(definition: {\n\tkey: string;\n\trender(value: T): string;\n}): SystemSection<T> {\n\treturn Object.freeze(definition);\n}\n\nexport type EnvironmentInfo = { cwd: string };\nexport type SkillInfo = { name: string; description: string };\nexport const systemSections = {\n\tidentity: defineSystemSection<string>({ key: \"identity\", render: (v) => v }),\n\tenvironment: defineSystemSection<EnvironmentInfo>({\n\t\tkey: \"environment\",\n\t\trender: (v) => `Working directory: ${v.cwd}`,\n\t}),\n\tskills: defineSystemSection<SkillInfo[]>({\n\t\tkey: \"skills\",\n\t\trender: (v) => v.map((s) => `- ${s.name}: ${s.description}`).join(\"\\n\"),\n\t}),\n} as const;\n\n/** Section seed for a new conversation (§8.1): set with a checked pair, or remove an inherited key. */\nexport type SectionSeed = { key: string; value: JsonValue } | { key: string; remove: true };\nexport const sectionSeed = <T extends JsonValue>(section: SystemSection<T>, value: T): SectionSeed => ({\n\tkey: section.key,\n\tvalue,\n});\nexport const removeSection = (key: string): SectionSeed => ({ key, remove: true });\n\n// ---------------------------------------------------------------------------\n// The managed entry (§12.3)\n// ---------------------------------------------------------------------------\n\nexport type SectionRecord =\n\t| { key: string; action: \"set\"; value: JsonValue; rendered: string }\n\t| { key: string; action: \"remove\" };\nexport type SystemEntryData = { baseline?: true; sections: SectionRecord[] };\n/** A metadata-only delta has `model: []`. */\nexport type SystemEntry = Entry & { kind: \"pi.system\"; model: [] | [Stored<SystemMessage>]; data: SystemEntryData };\n\n// ---------------------------------------------------------------------------\n// Canonical state (§12.4): fold the fork-visible managed entries from the\n// newest baseline forward. Uses the kind scan; never depends on heads or edits.\n// ---------------------------------------------------------------------------\n\ntype SectionState = { value: JsonValue; rendered: string };\nexport type Canonical = Map<string, SectionState>; // insertion order is canonical order\n\nexport async function foldCanonical(\n\treads: Pick<CoreTx, \"scanEntries\">,\n\tconversationId: Id,\n): Promise<{ canonical: Canonical; newestManaged: Id | null; newestBaseline: Id | null }> {\n\tconst managed: SystemEntry[] = [];\n\tlet before: Id | undefined;\n\tlet baseline: Id | null = null;\n\tscan: for (;;) {\n\t\tconst page = await reads.scanEntries({\n\t\t\tconversationId,\n\t\t\tkind: \"pi.system\",\n\t\t\tlimit: 64,\n\t\t\t...(before === undefined ? {} : { before }),\n\t\t});\n\t\tfor (const e of page) {\n\t\t\tmanaged.push(e as SystemEntry);\n\t\t\tif ((e as SystemEntry).data.baseline) {\n\t\t\t\tbaseline = e.id;\n\t\t\t\tbreak scan;\n\t\t\t}\n\t\t}\n\t\tif (page.length < 64) break;\n\t\tbefore = page[page.length - 1]!.id;\n\t}\n\tmanaged.reverse();\n\tconst canonical: Canonical = new Map();\n\tfor (const e of managed)\n\t\tfor (const r of e.data.sections)\n\t\t\tr.action === \"remove\"\n\t\t\t\t? canonical.delete(r.key)\n\t\t\t\t: canonical.set(r.key, { value: r.value, rendered: r.rendered });\n\treturn { canonical, newestManaged: managed[managed.length - 1]?.id ?? null, newestBaseline: baseline };\n}\n\n// ---------------------------------------------------------------------------\n// Draft (§12.2): what `systemInstructions` handlers edit.\n// ---------------------------------------------------------------------------\n\nexport interface SystemSectionDraft {\n\tget<T extends JsonValue>(section: SystemSection<T>): T | undefined; // owned copy\n\tset<T extends JsonValue>(section: SystemSection<T>, value: T): void; // existing key keeps position; new key appends\n\tdelete(section: { key: string }): void;\n\twrap<T extends JsonValue>(section: SystemSection<T>, transform: (rendered: string) => string): void; // preparation-local\n}\n\nclass Draft implements SystemSectionDraft {\n\tvalues = new Map<string, JsonValue>();\n\twrappers = new Map<string, ((r: string) => string)[]>();\n\ttouched = new Set<string>();\n\tconstructor(seed: Canonical) {\n\t\tfor (const [k, s] of seed) this.values.set(k, s.value);\n\t}\n\tget<T extends JsonValue>(section: SystemSection<T>) {\n\t\tconst v = this.values.get(section.key);\n\t\treturn v === undefined ? undefined : (structuredClone(v) as T);\n\t}\n\tset<T extends JsonValue>(section: SystemSection<T>, value: T) {\n\t\tthis.values.set(section.key, value);\n\t\tthis.touched.add(section.key);\n\t}\n\tdelete(section: { key: string }) {\n\t\tthis.values.delete(section.key);\n\t\tthis.wrappers.delete(section.key);\n\t\tthis.touched.add(section.key);\n\t}\n\twrap<T extends JsonValue>(section: SystemSection<T>, transform: (r: string) => string) {\n\t\t(this.wrappers.get(section.key) ?? this.wrappers.set(section.key, []).get(section.key)!).push(transform);\n\t\tthis.touched.add(section.key);\n\t}\n\tsnapshot() {\n\t\treturn {\n\t\t\tvalues: new Map(this.values),\n\t\t\twrappers: new Map([...this.wrappers].map(([k, v]) => [k, [...v]])),\n\t\t\ttouched: new Set(this.touched),\n\t\t};\n\t}\n\trestore(s: ReturnType<Draft[\"snapshot\"]>) {\n\t\tthis.values = s.values;\n\t\tthis.wrappers = s.wrappers;\n\t\tthis.touched = s.touched;\n\t}\n}\n\n/** Render touched sections (wrappers apply after rendering, in registration order); untouched keep their stored text. */\nfunction freeze(draft: Draft, canonical: Canonical, registry: ReadonlyMap<string, SystemSection>): Canonical {\n\tconst desired: Canonical = new Map();\n\tfor (const [key, value] of draft.values) {\n\t\tif (!draft.touched.has(key)) {\n\t\t\tconst prev = canonical.get(key);\n\t\t\tif (prev) desired.set(key, prev);\n\t\t\tcontinue;\n\t\t}\n\t\tconst def = registry.get(key);\n\t\tif (def === undefined) continue; // unregistered: cannot re-render; treated as removed\n\t\tlet rendered = (def as SystemSection).render(value);\n\t\tfor (const w of draft.wrappers.get(key) ?? []) rendered = w(rendered);\n\t\tdesired.set(key, { value, rendered });\n\t}\n\treturn desired;\n}\n\n// ---------------------------------------------------------------------------\n// Preparation (§12.5)\n// ---------------------------------------------------------------------------\n\nexport interface SectionRegistry {\n\treadonly map: ReadonlyMap<string, SystemSection>;\n\treadonly revision: number;\n}\nexport interface ToolRegistry {\n\treadonly map: ReadonlyMap<string, AnyToolDeclaration>;\n\treadonly revision: number;\n}\n\n/** Snapshot S. Compared field by field before the `prepared` commit. */\nexport interface PreparationSnapshot {\n\tnewestManaged: Id | null;\n\tnewestBaseline: Id | null;\n\tnewestHead: Id | null;\n\tsettings: { model?: JsonValue; thinkingLevel: JsonValue; selectedTools: string[]; profile: JsonValue };\n\tsectionsRev: number;\n\ttoolsRev: number;\n}\nexport const sameSnapshot = (a: PreparationSnapshot, b: PreparationSnapshot) => JSON.stringify(a) === JSON.stringify(b);\n\nexport async function takeSnapshot(\n\ttx: Pick<CoreTx, \"scanEntries\" | \"newestEntry\" | \"snapshot\" | \"conversation\">,\n\tconversationId: Id,\n\tsections: SectionRegistry,\n\ttools: ToolRegistry,\n): Promise<{ snapshot: PreparationSnapshot; canonical: Canonical; seed: readonly SectionSeed[] | undefined }> {\n\tconst { canonical, newestManaged, newestBaseline } = await foldCanonical(tx, conversationId);\n\tconst head = await tx.newestEntry(conversationId, { withHead: true });\n\tconst r = tx.snapshot({ doc: \"rewindable\", conversationId }); // a plain copy: the snapshot outlives this transaction\n\tconst conv = await tx.conversation(conversationId);\n\treturn {\n\t\tsnapshot: {\n\t\t\tnewestManaged,\n\t\t\tnewestBaseline,\n\t\t\tnewestHead: head?.id ?? null,\n\t\t\tsettings: {\n\t\t\t\t...(r.model === undefined ? {} : { model: r.model }),\n\t\t\t\tthinkingLevel: r.thinkingLevel,\n\t\t\t\tselectedTools: [...r.selectedTools],\n\t\t\t\tprofile: r.profile,\n\t\t\t},\n\t\t\tsectionsRev: sections.revision,\n\t\t\ttoolsRev: tools.revision,\n\t\t},\n\t\tcanonical,\n\t\tseed: newestManaged === null ? conv?.sections : undefined, // §8.1: the seed applies while there is no local managed entry\n\t};\n}\n\nexport interface SystemInstructionsHooks {\n\t/** Edit the draft; optionally override the tool loadout (last override wins). A throwing handler's edits are rolled back. */\n\tsystemInstructions(\n\t\tinput: {\n\t\t\tsections: SystemSectionDraft;\n\t\t\tconfig: PreparationSnapshot[\"settings\"];\n\t\t\ttools: readonly AnyToolDeclaration[];\n\t\t},\n\t\tinfo: HookInfo,\n\t\tctx: Context,\n\t): HookResult<{ tools?: readonly AnyToolDeclaration[] }>;\n}\n\n/** Off the line: seed the draft, run handlers, freeze. */\nexport async function prepareDraft(\n\trt: Pick<Runtime<SystemInstructionsHooks>, \"hooks\" | \"tools\">,\n\tsections: SectionRegistry,\n\tcanonical: Canonical,\n\tseed: readonly SectionSeed[] | undefined,\n\tsettings: PreparationSnapshot[\"settings\"],\n\tonReport: (m: string) => void,\n\tctx: Context,\n): Promise<{ desired: Canonical; tools: readonly AnyToolDeclaration[] }> {\n\tconst draft = new Draft(canonical);\n\tfor (const s of seed ?? [])\n\t\t\"remove\" in s ? draft.delete({ key: s.key }) : draft.set({ key: s.key, render: () => \"\" }, s.value);\n\n\tconst defaultTools: AnyToolDeclaration[] = [];\n\tfor (const name of settings.selectedTools) {\n\t\tconst t = rt.tools.get(name);\n\t\tt ? defaultTools.push(t) : onReport(`selected tool ${name} is not registered`);\n\t}\n\tlet tools: readonly AnyToolDeclaration[] = defaultTools;\n\tfor (const binding of rt.hooks.handlers()) {\n\t\tconst before = draft.snapshot();\n\t\ttry {\n\t\t\tconst out = await binding.handlers.systemInstructions?.(\n\t\t\t\t{ sections: draft, config: settings, tools: defaultTools },\n\t\t\t\tbinding.api,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tif (out?.tools) tools = out.tools;\n\t\t} catch (error) {\n\t\t\tif (ctx.abortSignal?.aborted) throw error;\n\t\t\tdraft.restore(before); // collect / skip: this handler's edits are rolled back\n\t\t\tonReport(String(error));\n\t\t}\n\t}\n\treturn { desired: freeze(draft, canonical, sections.map), tools };\n}\n\n/** On the line, in the `prepared` commit: diff desired against canonical; baseline if a head intervened. */\nexport async function planManagedEntry(\n\ttx: Pick<CoreTx, \"context\">,\n\tconversationId: Id,\n\tsnapshot: PreparationSnapshot,\n\tcanonical: Canonical,\n\tdesired: Canonical,\n\ttools: readonly AnyToolDeclaration[],\n\tnow: number,\n): Promise<{ data: SystemEntryData; model: [] | [Stored<SystemMessage>]; edits?: ContextEdit[] } | undefined> {\n\t// §12.4: no managed history at all → first preparation appends a full baseline; and a usable\n\t// baseline must follow the newest head.\n\tconst needBaseline =\n\t\tsnapshot.newestManaged === null ||\n\t\t(snapshot.newestHead !== null &&\n\t\t\t(snapshot.newestBaseline === null || snapshot.newestHead > snapshot.newestBaseline));\n\tconst toolOf = (t: AnyToolDeclaration) => ({\n\t\tname: t.name,\n\t\tdescription: t.description,\n\t\tparameters: toStored(t.parameters),\n\t});\n\n\t// Previous effective tools: those declared by the newest managed entry chain (we recompute from canonical's owner: the tail message).\n\tconst { messages } = await tx.context(conversationId);\n\tconst previous = new Map<string, { name: string }>();\n\tfor (const m of messages)\n\t\tif (m.role === \"system\") {\n\t\t\tfor (const t of (m as SystemMessage).toolsRemoved ?? []) previous.delete(t.name);\n\t\t\tfor (const t of (m as SystemMessage).toolsAdded ?? []) previous.set(t.name, t);\n\t\t}\n\n\tif (needBaseline) {\n\t\tconst sections: SectionRecord[] = [...desired].map(([key, s]) => ({\n\t\t\tkey,\n\t\t\taction: \"set\",\n\t\t\tvalue: s.value,\n\t\t\trendered: s.rendered,\n\t\t}));\n\t\tconst content = sections.map((s) => (s.action === \"set\" ? `## ${s.key}\\n${s.rendered}` : \"\")).join(\"\\n\\n\");\n\t\tconst { entries } = await tx.context(conversationId);\n\t\tconst edits: ContextEdit[] = entries\n\t\t\t.filter((e: Entry) => e.kind === \"pi.system\" && e.id > (snapshot.newestHead ?? 0))\n\t\t\t.map((e: Entry) => ({ target: e.id, action: \"omit\" as const }));\n\t\tconst message = {\n\t\t\trole: \"system\",\n\t\t\tcontent,\n\t\t\ttoolsAdded: tools.map(toolOf),\n\t\t\ttimestamp: now,\n\t\t} as Stored<SystemMessage>;\n\t\treturn { data: { baseline: true, sections }, model: [message], ...(edits.length ? { edits } : {}) };\n\t}\n\n\tconst changed: SectionRecord[] = [];\n\tfor (const [key, s] of desired) {\n\t\tconst prev = canonical.get(key);\n\t\tif (!prev || prev.rendered !== s.rendered || JSON.stringify(prev.value) !== JSON.stringify(s.value))\n\t\t\tchanged.push({ key, action: \"set\", value: s.value, rendered: s.rendered });\n\t}\n\tfor (const key of canonical.keys()) if (!desired.has(key)) changed.push({ key, action: \"remove\" });\n\tconst added = tools.filter((t) => !previous.has(t.name));\n\tconst removed = [...previous.values()].filter((p) => !tools.some((t) => t.name === p.name));\n\tif (changed.length === 0 && added.length === 0 && removed.length === 0) return undefined;\n\n\tconst renderChanged = changed.some((s) => s.action === \"remove\" || canonical.get(s.key)?.rendered !== s.rendered);\n\tif (!renderChanged && added.length === 0 && removed.length === 0) return { data: { sections: changed }, model: [] }; // metadata-only delta\n\tconst content = changed\n\t\t.map((s) =>\n\t\t\ts.action === \"set\"\n\t\t\t\t? `The ${s.key} section now reads:\\n${s.rendered}`\n\t\t\t\t: `The ${s.key} section no longer applies.`,\n\t\t)\n\t\t.join(\"\\n\\n\");\n\tconst message = {\n\t\trole: \"system\",\n\t\tcontent,\n\t\t...(added.length ? { toolsAdded: added.map(toolOf) } : {}),\n\t\t...(removed.length ? { toolsRemoved: removed } : {}),\n\t\ttimestamp: now,\n\t} as Stored<SystemMessage>;\n\treturn { data: { sections: changed }, model: [message] };\n}\n\n/** Tools effective in a projected request: fold toolsAdded/toolsRemoved across its SystemMessages. */\nexport function effectiveTools(messages: readonly { role: string }[]): { name: string }[] {\n\tconst tools = new Map<string, { name: string }>();\n\tfor (const m of messages)\n\t\tif (m.role === \"system\") {\n\t\t\tfor (const t of (m as SystemMessage).toolsRemoved ?? []) tools.delete(t.name);\n\t\t\tfor (const t of (m as SystemMessage).toolsAdded ?? []) tools.set(t.name, t);\n\t\t}\n\treturn [...tools.values()];\n}\n\nexport type { RewindableState, Runtime };\n"]}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import type { JsonValue as ChordJsonValue, Context, JsonRepresentation } from "@earendil-works/chord";
|
|
12
12
|
import type { Op } from "@earendil-works/chord/delta";
|
|
13
|
-
import type { Api, AssistantMessage, AssistantMessageEvent, DeferredHandle, ImageContent, Message as ModelMessage, Model as ModelOf, TextContent, ToolCall, ToolResultMessage, UserMessage } from "@earendil-works/pi-ai";
|
|
13
|
+
import type { Api, AssistantMessage, AssistantMessageEvent, DeferredHandle, ImageContent, Message as ModelMessage, Model as ModelOf, TextContent, Tool, ToolCall, ToolResultMessage, UserMessage } from "@earendil-works/pi-ai";
|
|
14
14
|
import type { Static, TSchema } from "typebox";
|
|
15
15
|
import type { ThinkingLevel } from "../../types.ts";
|
|
16
16
|
import type { SectionRegistry, SectionSeed, ToolRegistry } from "./system.ts";
|
|
@@ -44,25 +44,16 @@ export interface Conversation {
|
|
|
44
44
|
/** §8.1 section seed: applied by preparation while the conversation has no local managed entry. Private: not in ConversationView. */
|
|
45
45
|
readonly sections?: readonly SectionSeed[];
|
|
46
46
|
}
|
|
47
|
-
/**
|
|
48
|
-
|
|
49
|
-
* here until it lands): a SystemMessage at its historical position.
|
|
50
|
-
*/
|
|
51
|
-
export interface SystemMessage {
|
|
47
|
+
/** Native system messages with JSON tool schemas at durable positions. */
|
|
48
|
+
export type SystemMessage = Omit<Extract<ModelMessage, {
|
|
52
49
|
role: "system";
|
|
53
|
-
|
|
54
|
-
toolsAdded?:
|
|
55
|
-
|
|
56
|
-
description: string;
|
|
57
|
-
parameters: TSchema;
|
|
58
|
-
}[];
|
|
59
|
-
toolsRemoved?: {
|
|
60
|
-
name: string;
|
|
61
|
-
}[];
|
|
62
|
-
timestamp: number;
|
|
63
|
-
}
|
|
50
|
+
}>, "toolsAdded"> & {
|
|
51
|
+
toolsAdded?: Tool<JsonObject>[];
|
|
52
|
+
};
|
|
64
53
|
export type Message = ModelMessage | SystemMessage;
|
|
65
|
-
export type StoredMessage = Stored<Message
|
|
54
|
+
export type StoredMessage = Stored<Exclude<Message, {
|
|
55
|
+
role: "system";
|
|
56
|
+
}> | SystemMessage>;
|
|
66
57
|
export type Model = ModelOf<Api>;
|
|
67
58
|
export interface ContextEdit {
|
|
68
59
|
readonly target: Id;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/harness/pico3/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,SAAS,IAAI,cAAc,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC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AACD,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC9C,YAAY,EAAM;QACjB,KAAK,CAAC,gBAAgB,EAAE,gCAAgC,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACpC,CAAC;CACD;AACD,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC5C,YAAY,EAAM;QACjB,KAAK,CAAC,gBAAgB,EAAE,8BAA8B,CAAC,CAAC;QACxD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IAClC,CAAC;CACD;AACD,MAAM,OAAO,OAAQ,SAAQ,KAAK;IACjC,YAAY,KAAc;QACzB,KAAK,CAAC,oBAAoB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACvB,CAAC;CACD;AACD,MAAM,OAAO,MAAO,SAAQ,KAAK;IAChC;QACC,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;IACtB,CAAC;CACD;AACD,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC3C,YAAY,IAAY,EAAE,IAAY;QACrC,KAAK,CAAC,QAAQ,IAAI,wBAAwB,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IACjC,CAAC;CACD","sourcesContent":["/**\n * harness-v3 — records, documents, storage, kinds, transactions, runtime, tools, hooks.\n *\n * Durable model: four tables (conversations, entries, tasks, inputs) and three documents\n * (session, per-conversation rewindable, per-conversation sticky). Every durable position\n * is strict JSON (`JsonValue`); nothing durable is `unknown`.\n *\n * Single process. A storage path has one owning process and one owning Session at a time.\n * Two processes opening the same JSONL directory is unsupported.\n */\nimport type { JsonValue as ChordJsonValue, Context, JsonRepresentation } from \"@earendil-works/chord\";\nimport type { Op } from \"@earendil-works/chord/delta\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tDeferredHandle,\n\tImageContent,\n\tMessage as ModelMessage,\n\tModel as ModelOf,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n\tUserMessage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ThinkingLevel } from \"../../types.ts\";\nimport type { SectionRegistry, SectionSeed, ToolRegistry } from \"./system.ts\";\n\n// ---------------------------------------------------------------------------\n// Strict durable JSON\n// ---------------------------------------------------------------------------\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = ChordJsonValue;\n/** Optional properties represent absent keys; committed values are normalized through JSON serialization. */\nexport type JsonObject = { [key: string]: JsonValue };\n\n/** Coerce an in-memory value (e.g. a pi-ai message) to its stored representation. */\nexport const toStored = <T>(value: T): Stored<T> => JSON.parse(JSON.stringify(value)) as Stored<T>;\n\n/**\n * The JSON representation of a value: what survives `JSON.parse(JSON.stringify(v))`.\n * Optional keys stay optional; `undefined` values vanish; functions are never durable.\n * Use for imported pi-ai types at durable positions.\n */\nexport type Stored<T> = JsonRepresentation<T>;\n\nexport type Id = number;\nexport type Seq = number;\n\n/** Compile-time assertion helper. */\nexport type Assert<T extends true> = T;\n/** True iff T is strict JSON (structurally). */\nexport type IsJson<T> = [T] extends [JsonValue] ? true : false;\n\n// ---------------------------------------------------------------------------\n// Records\n// ---------------------------------------------------------------------------\n\nexport interface Conversation {\n\treadonly id: Id;\n\treadonly parent?: { readonly conversationId: Id; readonly at: Id };\n\treadonly owner?: Id; // task that created it\n\t/** §8.1 section seed: applied by preparation while the conversation has no local managed entry. Private: not in ConversationView. */\n\treadonly sections?: readonly SectionSeed[];\n}\n\n/**\n * System instructions and the tool loadout ride inside `messages` (pi-ai PR #9116, shimmed\n * here until it lands): a SystemMessage at its historical position.\n */\nexport interface SystemMessage {\n\trole: \"system\";\n\tcontent: string;\n\ttoolsAdded?: { name: string; description: string; parameters: TSchema }[];\n\ttoolsRemoved?: { name: string }[];\n\ttimestamp: number;\n}\nexport type Message = ModelMessage | SystemMessage;\nexport type StoredMessage = Stored<Message>;\nexport type Model = ModelOf<Api>;\n\nexport interface ContextEdit {\n\treadonly target: Id;\n\treadonly action: \"omit\" | \"replace\";\n\treadonly messages?: readonly StoredMessage[];\n}\n\nexport interface Entry {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly kind: string;\n\treadonly model?: readonly StoredMessage[]; // what the model sees; absent = display/bookkeeping only\n\treadonly data?: JsonObject;\n\treadonly head?: Id; // context starts here (may be a parent's entry). Assigned by the kernel; `self` in NewEntry\n\treadonly edits?: readonly ContextEdit[];\n\treadonly byTaskId?: Id;\n}\nexport type NewEntry = Omit<Entry, \"id\" | \"conversationId\" | \"byTaskId\" | \"head\"> & { readonly head?: Id | \"self\" };\n\n/** A typed witness for an entry kind: `is()` narrows, and typed writes take `EntryInput<E>`. */\nexport interface EntryKind<E extends Entry = Entry> {\n\treadonly kind: string;\n\tis(entry: Entry | undefined): entry is E;\n}\nexport type EntryInput<E extends Entry> = Omit<E, \"id\" | \"conversationId\" | \"kind\" | \"byTaskId\" | \"head\"> &\n\t(E extends { readonly head: Id } ? { readonly head: Id | \"self\" } : { readonly head?: never });\nexport function defineEntry<E extends Entry>(kind: string): EntryKind<E> {\n\tif (kind.startsWith(\"pi.\")) throw new Error(`entry kind names beginning with \"pi.\" are reserved: ${kind}`);\n\treturn Object.freeze({ kind, is: (entry: Entry | undefined): entry is E => entry?.kind === kind });\n}\n\nexport type Checkpoint = JsonObject & { readonly phase: string };\n\nexport type Completion<R extends JsonValue = JsonValue, F extends JsonValue = JsonValue> =\n\t| { readonly status: \"completed\"; readonly result: R }\n\t| { readonly status: \"failed\"; readonly failure: F };\nexport type Outcome<R extends JsonValue = JsonValue, F extends JsonValue = JsonValue, A extends JsonValue = JsonValue> =\n\t| Completion<R, F>\n\t| { readonly status: \"aborted\"; readonly result: A }\n\t| { readonly status: \"orphaned\" }\n\t/** The kind broke its contract (a handler threw or returned an invalid shape). Not one of its declared failures. */\n\t| { readonly status: \"faulted\"; readonly error: string };\n\nexport interface Task<I extends JsonValue = JsonValue, C extends Checkpoint = Checkpoint> {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly kind: string;\n\treadonly input: I;\n\treadonly status: \"pending\" | \"running\" | \"terminal\";\n\treadonly checkpoint?: C;\n\treadonly abort?: true; // the durable mark\n\treadonly outcome?: Outcome;\n\treadonly after: readonly Id[];\n\treadonly owns: readonly Id[]; // conversations this task created\n\treadonly background?: true; // does not hold the conversation busy; survives conversation abort\n}\nexport type TaskPatch = { readonly id: Id } & Partial<\n\tOmit<Pick<Task, \"status\" | \"checkpoint\" | \"abort\" | \"outcome\" | \"owns\">, \"checkpoint\">\n> & { checkpoint?: Checkpoint | null };\n\nexport interface Input {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly requestId?: string;\n\treadonly status: \"queued\" | \"placed\" | \"done\" | \"unanswered\";\n\treadonly entry?: Id;\n\treadonly answer?: Id;\n\treadonly reason?: \"aborted\" | \"stale\" | \"terminated\" | \"failed\";\n\treadonly detail?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Documents (Chord-tracked). Mutated in place inside a commit, diffed at the end.\n// ---------------------------------------------------------------------------\n\nexport type ModelRef = { provider: string; modelId: string };\nexport type RetryPolicy = { enabled: boolean; maxRetries: number; baseDelayMs: number; maxAgentDelayMs?: number };\n\n/** One running tool call, at the index of its call in the assistant message. */\nexport type ToolSlot = {\n\tcallId: string;\n\tname: string;\n\targs: JsonValue;\n\tstatus: \"pending\" | \"running\" | \"done\" | \"error\" | \"aborted\";\n\twaitingOn?: string;\n\toutput?: string; // bounded stream as it stands\n\tprogress?: string;\n\tdetails?: JsonValue;\n\tcontinuedBy?: Id; // a background task that took the work over; its live state is `tasks[continuedBy]`\n\tentry?: Id;\n\t/** Private task-lifetime coordination state. Never projected into ConversationView. */\n\tmemos?: { [key: string]: JsonValue };\n};\n/** The current turn, shaped for rendering. Reset when a generation starts; cleared when the turn ends. */\nexport type TurnState = {\n\tmessage?: Stored<AssistantMessage>; // streaming assistant message\n\ttools: ToolSlot[]; // tools of the assistant message being executed, by call index\n};\n\n/** Private durable namespace slices stored in authoritative documents. */\nexport type PluginSlices = { [namespace: string]: JsonObject };\n\n/** Rewound by forks: forks see the state as of their fork point. Core config fields come from the built-in kinds' declarations. */\nexport type RewindableState = {\n\tmodel?: ModelRef;\n\tthinkingLevel: ThinkingLevel;\n\tselectedTools: string[];\n\tprofile: string;\n\tthreshold: number;\n\tkeepRecent: number;\n\tplugins: PluginSlices;\n\t[key: string]: JsonValue | undefined; // ordinary kinds' declared config, keyed by their disjoint names\n};\n/** The present. Never folded historically; truncated to its last base. */\nexport type StickyState = {\n\tretry: RetryPolicy;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tinbox: QueuedInput[];\n\tturn: TurnState;\n\ttasks: { [taskId: string]: JsonObject }; // non-turn tasks' live slots; retired by the kernel on terminal\n\tplugins: PluginSlices;\n\t[key: string]: JsonValue | undefined;\n};\nexport type SessionState = { plugins: PluginSlices; [key: string]: JsonValue | undefined };\n\nexport type QueuedInput =\n\t| { id: Id; mode: \"steer\" | \"followUp\"; input: Stored<UserInput> }\n\t| { id: Id; mode: \"write\"; entry: Stored<NewEntry> };\n\nexport type DocRef =\n\t| { doc: \"session\" }\n\t| { doc: \"rewindable\"; conversationId: Id }\n\t| { doc: \"sticky\"; conversationId: Id };\n\nexport type NamespaceDefaults<T extends JsonObject> = {\n\treadonly rewindable?: Partial<T>;\n\treadonly sticky?: Partial<T>;\n\treadonly session?: Partial<T>;\n};\n\n/** Current process authority for one durable namespace string. */\nexport interface Namespace<T extends JsonObject = JsonObject> {\n\treadonly id: string;\n\t/** Type-only invariant marker. */\n\treadonly valueType?: (value: T) => T;\n\tunregister(): void;\n}\n\n/** Internal erased registration paired with the public namespace token. */\nexport interface NamespaceRegistration {\n\treadonly token: object;\n\treadonly defaults: { readonly rewindable: JsonObject; readonly sticky: JsonObject; readonly session: JsonObject };\n\treadonly routes: ReadonlyMap<string, DocRef[\"doc\"]>;\n\treadonly project?: (slice: Readonly<JsonObject>) => JsonValue;\n}\n\n/** First writer wins, including when the stored winner is null. */\nexport function memoOnce<T extends JsonValue>(slot: JsonObject, key: string, candidate: T): T {\n\tif (!Object.hasOwn(slot, \"memos\")) slot.memos = {};\n\tconst memos = slot.memos as { [key: string]: JsonValue };\n\tif (Object.hasOwn(memos, key)) return memos[key] as T;\n\tmemos[key] = candidate;\n\treturn candidate;\n}\n\n// ---------------------------------------------------------------------------\n// Configuration facade: every registered kind's `config` merged flat.\n// ---------------------------------------------------------------------------\n\ntype UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;\n/** A declared slice; the undeclared `ConfigShape` (index signature) counts as no keys. */\ntype Declared<S> = string extends keyof S ? object : S;\ntype RewindableOf<K> = K extends unknown\n\t? ConfigOf<K> extends { readonly rewindable: infer RC }\n\t\t? Declared<RC>\n\t\t: object\n\t: never;\ntype StickyOf<K> = K extends unknown\n\t? ConfigOf<K> extends { readonly sticky: infer SC }\n\t\t? Declared<SC>\n\t\t: object\n\t: never;\nexport type ConfigOfKinds<Ks extends readonly AnyKind[]> = UnionToIntersection<\n\tRewindableOf<Ks[number]> | StickyOf<Ks[number]>\n> extends infer M\n\t? { [K in keyof M]: M[K] }\n\t: never;\ntype KeysOfKind<K> = (keyof RewindableOf<K> | keyof StickyOf<K>) & string;\ntype IsUnion<U, C = U> = U extends unknown ? ([C] extends [U] ? false : true) : never;\n/** The kinds declaring `Key`. */\ntype Owners<Ks extends readonly AnyKind[], Key extends string> = {\n\t[I in keyof Ks]: Key extends KeysOfKind<Ks[I]> ? Ks[I] : never;\n}[number];\ntype AllKeys<Ks extends readonly AnyKind[]> = { [I in keyof Ks]: KeysOfKind<Ks[I]> }[number];\ntype ClashingKeys<Ks extends readonly AnyKind[]> = {\n\t[Key in AllKeys<Ks>]: true extends IsUnion<Owners<Ks, Key>> ? Key : never;\n}[AllKeys<Ks>];\n/** `true` iff no two kinds declare the same config key. Asserted at open at compile time and at runtime. */\nexport type DisjointConfig<Ks extends readonly AnyKind[]> = [ClashingKeys<Ks>] extends [never] ? true : false;\n\nexport interface ConfigFacade<Cfg extends object> {\n\tget(ctx: Context): Promise<Readonly<Cfg>>;\n\t/** One commit, routed to the declaring documents. */\n\tset(patch: { [K in keyof Cfg]?: Cfg[K] }, ctx: Context): Promise<void>;\n\t/** Delete persisted overrides. Declared defaults become visible; `model` becomes absent. */\n\treset(keys: readonly (keyof Cfg)[], ctx: Context): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Storage: six write types, a handful of reads. One owning Session per instance.\n// ---------------------------------------------------------------------------\n\nexport type Write =\n\t| { type: \"conversation\"; conversation: Conversation }\n\t| { type: \"entry\"; entry: Entry }\n\t| { type: \"task\"; task: Task } // create\n\t| { type: \"task.patch\"; patch: TaskPatch } // `checkpoint: null` clears\n\t| { type: \"input\"; input: Input } // create or replace whole\n\t| { type: \"doc\"; ref: DocRef; ops: Op[] };\n\nexport interface EntryScan {\n\tconversationId: Id;\n\tkind?: string;\n\twithHead?: boolean;\n\tbefore?: Id; // strictly less\n\tlimit: number;\n}\nexport interface TaskScan {\n\tconversationId?: Id;\n\tstatus?: Task[\"status\"][];\n\tkind?: string;\n}\n\nexport interface Storage {\n\t/** Persist one batch atomically: all or nothing. Returns the commit sequence. */\n\tcommit(writes: readonly Write[], ctx: Context): Promise<Seq>;\n\tmintId(): Id;\n\tconversation(id: Id, ctx: Context): Promise<Conversation | undefined>;\n\tconversations(ctx: Context): Promise<Conversation[]>;\n\tentries(ids: readonly Id[], ctx: Context): Promise<Map<Id, Entry>>;\n\t/** Newest-first, fork-aware: this conversation's entries, then the parent's up to the fork point, and so on. */\n\tscanEntries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n\ttask(id: Id, ctx: Context): Promise<Task | undefined>;\n\tscanTasks(scan: TaskScan, ctx: Context): Promise<Task[]>;\n\tinput(id: Id, ctx: Context): Promise<Input | undefined>;\n\tinputByRequest(conversationId: Id, requestId: string, ctx: Context): Promise<Input | undefined>;\n\tdoc(ref: DocRef, ctx: Context): Promise<JsonObject | undefined>;\n\t/** Rewindable doc as of the atomic commit containing entry `at` (fork inheritance). See \"commit-granular history\". */\n\tdocAsOf(conversationId: Id, at: Id, ctx: Context): Promise<JsonObject | undefined>;\n\t/** Rewrite a doc log from its last base. */\n\ttruncate(ref: DocRef, ctx: Context): Promise<void>;\n\tclose(ctx: Context): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Kinds\n// ---------------------------------------------------------------------------\n\n/** A hook may synchronously or asynchronously omit its replacement value. */\n// biome-ignore lint/suspicious/noConfusingVoidType: void is the intentional callback no-value result\nexport type HookResult<T> = T | void | Promise<T | void>;\n\nexport interface HookApi {\n\treadonly kind: string;\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n}\n/** Kept as the concise name used by existing kind hook declarations. */\nexport type HookInfo = HookApi;\nexport interface HookBinding<H extends object> {\n\treadonly handlers: Partial<H>;\n\treadonly namespace: Namespace;\n\treadonly api: HookApi;\n}\nexport interface HookRunner<H extends object> {\n\thandlers(): readonly HookBinding<H>[];\n\t/** Call `fn` on each handler; `onValue` sees non-undefined results and may return true to stop. A throwing handler is reported and skipped. */\n\teach<V>(\n\t\tctx: Context,\n\t\tfn: (handlers: Partial<H>, api: HookApi) => HookResult<V>,\n\t\tonValue?: (v: V) => unknown,\n\t): Promise<void>;\n}\n\n/** What a phase handler returns: advance to a checkpoint, or finish. A builder runs on the line and may terminalize or ask to retry. */\nexport type Step<C extends Checkpoint, R extends JsonValue, F extends JsonValue, Tx extends TaskTx = TaskTx> =\n\t| {\n\t\t\treadonly next:\n\t\t\t\t| C\n\t\t\t\t| ((\n\t\t\t\t\t\ttx: Tx,\n\t\t\t\t\t\tcurrent: Task,\n\t\t\t\t\t\tctx: Context,\n\t\t\t\t ) => C | Completion<R, F> | \"retry\" | Promise<C | Completion<R, F> | \"retry\">);\n\t }\n\t| { readonly done: Closure<R, F, Tx> };\nexport type Closure<R extends JsonValue, F extends JsonValue, Tx extends TaskTx = TaskTx> = (\n\ttx: Tx,\n\tcurrent: Task,\n\tctx: Context,\n) => Completion<R, F> | Promise<Completion<R, F>>;\nexport type AbortClosure<A extends JsonValue, Tx extends TaskTx = TaskTx> = (\n\ttx: Tx,\n\tcurrent: Task,\n\tctx: Context,\n) => A | Promise<A>;\n\nexport type CheckpointAt<C extends Checkpoint, P extends C[\"phase\"]> = Extract<C, { readonly phase: P }>;\nexport type PhaseHandler<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tP extends C[\"phase\"],\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tH extends object,\n\tTx extends TaskTx = TaskTx,\n> = (\n\ttask: Task<I, CheckpointAt<C, P>> & { readonly checkpoint: CheckpointAt<C, P> },\n\trt: Runtime<H, Tx>,\n\tctx: Context,\n) => Promise<Step<C, R, F, Tx>>;\n\n/** A config slice: JSON values; a key whose default is `undefined` is optional (only `model` among the built-ins). */\nexport type ConfigShape = { [key: string]: JsonValue | undefined };\n/** Per-kind configuration: defaults, split by document. Keys across all kinds must be disjoint. */\nexport interface KindConfig<RC extends ConfigShape = ConfigShape, SC extends ConfigShape = ConfigShape> {\n\treadonly rewindable?: RC;\n\treadonly sticky?: SC;\n}\n\n/** Phantom carrier so `TaskOf<K>` etc. can read a kind's types back out. Never set at runtime. */\nexport interface KindTypes<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object,\n\tCfg extends KindConfig,\n\tS extends JsonObject,\n> {\n\tinput: I;\n\tcheckpoint: C;\n\tresult: R;\n\tfailure: F;\n\taborted: A;\n\thooks: H;\n\tconfig: Cfg;\n\tslot: S;\n}\n\n/**\n * A task kind. `initial` runs when there is no checkpoint; `phases` is exhaustive over\n * `C[\"phase\"]`. Phases named in `inflight` are written by a handler immediately before an\n * external effect and are entered by the scheduler only after reopen; a `next` transition\n * into one is rejected as a contract fault.\n */\nexport interface Kind<\n\tI extends JsonValue = JsonValue,\n\tC extends Checkpoint = Checkpoint,\n\tR extends JsonValue = JsonValue,\n\tF extends JsonValue = JsonValue,\n\tA extends JsonValue = JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n\tTx extends TaskTx = TaskTx,\n> {\n\treadonly types?: KindTypes<I, C, R, F, A, H, Cfg, S>;\n\treadonly name: string;\n\t/** A turn kind makes the conversation busy for admission. */\n\treadonly turn?: boolean;\n\treadonly config?: Cfg;\n\t/** Live slot (`sticky.tasks[id]`) initializer. */\n\treadonly slot?: (input: I) => S;\n\t/** Rendering projection for a non-turn task. Raw checkpoints and slots are never published. */\n\treadonly describe?: (task: Task<I, C> & { readonly slot?: Readonly<S> }) => JsonValue;\n\treadonly inflight?: readonly C[\"phase\"][];\n\tinitial(\n\t\ttask: Task<I, never> & { readonly checkpoint?: undefined },\n\t\trt: Runtime<H, Tx>,\n\t\tctx: Context,\n\t): Promise<Step<C, R, F, Tx>>;\n\treadonly phases: { readonly [P in C[\"phase\"]]: PhaseHandler<I, C, P, R, F, H, Tx> };\n\tabort(task: Task<I, C>, rt: Runtime<H, Tx>, ctx: Context): Promise<AbortClosure<A, Tx>>;\n}\n\n/** Internal kind type for fixed core machinery. */\nexport type CoreKind<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n> = Kind<I, C, R, F, A, H, Cfg, S, CoreTx>;\n\n/** Author an ordinary kind. Names may not begin with `pi.`. */\nexport function defineTask<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n>(definition: Kind<I, C, R, F, A, H, Cfg, S>): Kind<I, C, R, F, A, H, Cfg, S> {\n\tif (definition.name.startsWith(\"pi.\"))\n\t\tthrow new Error(`task kind names beginning with \"pi.\" are reserved: ${definition.name}`);\n\treturn Object.freeze({ ...definition });\n}\n\n/**\n * The erased kind the kernel stores. Handlers are invoked through `KindAdapter`, the one\n * place a concrete `Kind<…>` is narrowed to this and its outputs are validated.\n */\nexport interface AnyKind {\n\treadonly types?: unknown;\n\treadonly name: string;\n\treadonly turn?: boolean;\n\treadonly config?: KindConfig;\n\treadonly slot?: (input: never) => JsonObject;\n\treadonly describe?: unknown;\n\treadonly inflight?: readonly string[];\n\treadonly initial: unknown;\n\treadonly phases: { readonly [phase: string]: unknown };\n\treadonly abort: unknown;\n}\n\nexport interface TaskRef<K extends AnyKind = AnyKind> {\n\treadonly id: Id;\n\treadonly kind: K;\n}\nexport interface EntryRef<E extends Entry = Entry> {\n\treadonly id: Id;\n\treadonly kind: EntryKind<E>;\n}\n\ntype TypesOf<K> = K extends { types?: infer T } ? NonNullable<T> : never;\nexport type TaskOf<K> = TypesOf<K> extends KindTypes<\n\tinfer I,\n\tinfer C,\n\tinfer R,\n\tinfer F,\n\tinfer A,\n\tobject,\n\tKindConfig,\n\tJsonObject\n>\n\t? Omit<Task<I, C>, \"outcome\"> & { readonly outcome?: Outcome<R, F, A> }\n\t: never;\nexport type InputOf<K> = TypesOf<K> extends KindTypes<\n\tinfer I,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tKindConfig,\n\tJsonObject\n>\n\t? I\n\t: never;\nexport type HooksOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tinfer H,\n\tKindConfig,\n\tJsonObject\n>\n\t? H\n\t: never;\nexport type ConfigOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tinfer Cfg,\n\tJsonObject\n>\n\t? Cfg\n\t: never;\nexport type SlotOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tKindConfig,\n\tinfer S\n>\n\t? S\n\t: never;\n\nexport type TaskSpec = {\n\tkind: string;\n\tconversationId?: Id;\n\tinput: JsonValue;\n\tafter?: Id[];\n\tbackground?: true;\n};\n\n// ---------------------------------------------------------------------------\n// Transactions. One implementation; three views.\n// ---------------------------------------------------------------------------\n\nexport interface ConversationSpec {\n\tparent?: { conversationId: Id; at: Id | \"start\" };\n\trewindable?: Partial<RewindableState>;\n\tsticky?: Partial<StickyState>;\n\tsections?: readonly SectionSeed[];\n}\nexport interface OwnedConversationSpec {\n\tinherit?: boolean;\n\trewindable?: Partial<RewindableState>;\n\tsticky?: Partial<StickyState>;\n}\nexport type UserInput = string | UserMessage[\"content\"];\nexport interface SendInput {\n\tcontent: UserInput;\n\trequestId?: string;\n\twhenBusy?: \"steer\" | \"followUp\" | \"reject\";\n}\nexport type ContextView = { head: Entry | undefined; entries: Entry[]; messages: StoredMessage[] };\n\nexport type GenerationStatus =\n\t| { stage: \"waiting\"; on: \"compaction\" }\n\t| { stage: \"preparing\" }\n\t| { stage: \"requesting\"; attempt: number }\n\t| { stage: \"streaming\"; attempt: number }\n\t| { stage: \"retrying\"; attempt: number; retryAt: number; lastError: string }\n\t| { stage: \"deferred\"; attempt: number; pollAt: number };\n\nexport interface TurnView {\n\tinputs: Id[];\n\tgeneration?: GenerationStatus;\n\tmessage?: Stored<AssistantMessage>;\n\ttools: Omit<ToolSlot, \"memos\">[];\n}\n\nexport interface ConversationView {\n\tconversation: Omit<Conversation, \"sections\">;\n\tentries: Entry[];\n\tconfig: { [key: string]: JsonValue | undefined };\n\tinbox: QueuedInput[];\n\tturn?: TurnView;\n\tcompaction?: {\n\t\ttaskId: Id;\n\t\treason: \"threshold\" | \"manual\" | \"overflow\";\n\t\tstage: \"summarizing\" | \"retrying\";\n\t\tattempt: number;\n\t\tretryAt?: number;\n\t};\n\ttasks: { [taskId: string]: { kind: string; background?: true; marked?: true; status: JsonValue } };\n\tplugins: { [namespace: string]: JsonValue };\n}\n\nexport type ViewEvent =\n\t| { type: \"entry.added\"; entry: Entry }\n\t| { type: \"head.moved\"; entry: Entry }\n\t| { type: \"turn.started\"; inputs: Id[] }\n\t| { type: \"turn.ended\"; inputs: Id[]; status: \"done\"; answer: Id }\n\t| {\n\t\t\ttype: \"turn.ended\";\n\t\t\tinputs: Id[];\n\t\t\tstatus: \"unanswered\";\n\t\t\treason: \"terminated\" | \"aborted\" | \"failed\" | \"stale\";\n\t\t\tdetail?: string;\n\t }\n\t| { type: \"input.queued\"; input: Id; mode: \"steer\" | \"followUp\" | \"write\" }\n\t| { type: \"input.placed\"; input: Id; entry: Id }\n\t| { type: \"input.aborted\"; input: Id }\n\t| { type: \"generation.started\"; taskId: Id; attempt: number }\n\t| { type: \"generation.retrying\"; taskId: Id; attempt: number; retryAt: number; error: string }\n\t| { type: \"generation.deferred\"; taskId: Id; pollAt: number }\n\t| { type: \"generation.completed\"; taskId: Id; entry: Id; toolCalls: number }\n\t| {\n\t\t\ttype: \"generation.failed\";\n\t\t\ttaskId: Id;\n\t\t\treason: \"provider\" | \"overflow\" | \"retries_exhausted\" | \"no_model\";\n\t\t\tdetail: string;\n\t\t\tentry?: Id;\n\t }\n\t| { type: \"tool.waiting\"; taskId: Id; callId: string; on: string }\n\t| { type: \"tool.started\"; taskId: Id; callId: string; name: string }\n\t| { type: \"tool.finished\"; taskId: Id; callId: string; entry: Id; isError: boolean; control?: ToolControl }\n\t| { type: \"tool.aborted\"; taskId: Id; callId: string; entry: Id }\n\t| { type: \"compaction.started\"; taskId: Id; reason: \"threshold\" | \"manual\" | \"overflow\"; through: Id }\n\t| { type: \"compaction.retrying\"; taskId: Id; attempt: number; retryAt: number; error: string }\n\t| { type: \"compaction.finished\"; taskId: Id; summary: Id }\n\t| {\n\t\t\ttype: \"compaction.failed\";\n\t\t\ttaskId: Id;\n\t\t\treason: \"stale\" | \"declined\" | \"provider\" | \"retries_exhausted\" | \"no_model\";\n\t\t\tdetail: string;\n\t }\n\t| { type: \"task.started\"; taskId: Id; kind: string; background?: true }\n\t| {\n\t\t\ttype: \"task.ended\";\n\t\t\ttaskId: Id;\n\t\t\tkind: string;\n\t\t\toutcome: \"completed\" | \"failed\" | \"aborted\" | \"orphaned\" | \"faulted\";\n\t }\n\t| { type: \"config.changed\"; keys: string[] }\n\t| { type: \"warning\"; source: string; message: string }\n\t| { type: `plugin.${string}`; data: JsonValue };\n\nexport interface Envelope {\n\treadonly revision: number;\n\treadonly ops: Op[];\n\treadonly events: ViewEvent[];\n}\n\n/** Reads available to every view. Scans reject after a same-batch write to their domain (`ReadAfterWrite`). */\nexport interface TxReads {\n\tconversation(id: Id): Promise<Conversation | undefined>;\n\tentry(id: Id): Promise<Entry | undefined>;\n\tentry<E extends Entry>(kind: EntryKind<E>, id: Id): Promise<E | undefined>;\n\tentries(ids: readonly Id[]): Promise<Map<Id, Entry>>;\n\tnewestEntry(conversationId: Id, opts?: { kind?: string; withHead?: boolean }): Promise<Entry | undefined>;\n\tnewestEntry<E extends Entry>(conversationId: Id, kind: EntryKind<E>): Promise<E | undefined>;\n\tscanEntries(scan: EntryScan): Promise<Entry[]>;\n\tcontext(conversationId: Id, at?: Id): Promise<ContextView>;\n\ttask(id: Id): Promise<Task | undefined>;\n\ttask<K extends AnyKind>(ref: TaskRef<K>): Promise<TaskOf<K> | undefined>;\n\ttasks(scan: TaskScan): Promise<Task[]>;\n\tinput(id: Id): Promise<Input | undefined>;\n\trewindableAsOf(conversationId: Id, at: Id): Promise<RewindableState | undefined>;\n\t/** Plain copies. Document proxies cannot escape a transaction. */\n\tsnapshot(ref: { doc: \"rewindable\"; conversationId: Id }): RewindableState;\n\tsnapshot(ref: { doc: \"sticky\"; conversationId: Id }): StickyState;\n\tsnapshot(ref: { doc: \"session\" }): SessionState;\n}\n\ninterface SharedTx extends TxReads {\n\tplugins<T extends JsonObject>(namespace: Namespace<T>): T;\n\temit<T extends JsonObject>(namespace: Namespace<T>, name: string, data: JsonValue): void;\n\tconfig(conversationId: Id): { get<K extends string>(key: K): JsonValue | undefined };\n\t/** Passive entry: queued when busy, appended when idle. Returns the input id. */\n\twrite(conversationId: Id, entry: NewEntry): Promise<Id>;\n\twrite<E extends Entry>(conversationId: Id, kind: EntryKind<E>, entry: EntryInput<E>): Promise<Id>;\n\tcreateTask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts?: { conversationId?: Id; background?: true; after?: Id[] },\n\t): TaskRef<K>;\n\tcreateConversation(spec: ConversationSpec): Id;\n}\n\n/** What the host gets. */\nexport interface HostTx extends SharedTx {\n\t/** Config through the facade; raw core fields are not exposed to the host tx. */\n\tconfig(conversationId: Id): {\n\t\tget<K extends string>(key: K): JsonValue | undefined;\n\t\tset(key: string, value: JsonValue): void;\n\t\treset(key: string): void;\n\t};\n}\n\n/** What an ordinary task gets: scoped shared operations plus its own checkpoint and slot. */\nexport interface TaskTx extends SharedTx {\n\tcheckpoint<C extends Checkpoint>(value: C): void;\n\tslot<K extends AnyKind>(ref: TaskRef<K>): SlotOf<K>;\n\t/** Create a conversation this task owns. `parent` must be in the task's subtree. */\n\tcreateConversation(spec: ConversationSpec): Id;\n}\n\n/** Internal full authority for the fixed turn machinery. Never handed to ordinary kinds or the host. */\nexport interface CoreTx extends TaskTx {\n\temit<T extends JsonObject>(namespace: Namespace<T>, name: string, data: JsonValue): void;\n\temit(event: ViewEvent): void;\n\trewindable(conversationId: Id): RewindableState;\n\tsticky(conversationId: Id): StickyState;\n\tsession(): SessionState;\n\ttoolSlot(task: { conversationId: Id; input: { index: number } }): ToolSlot;\n\tappendEntry(conversationId: Id, entry: NewEntry): Id;\n\tappendEntry<E extends Entry>(conversationId: Id, kind: EntryKind<E>, entry: EntryInput<E>): EntryRef<E>;\n\tcreateTask(spec: TaskSpec): Id;\n\tcreateTask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts?: { conversationId?: Id; background?: true; after?: Id[] },\n\t): TaskRef<K>;\n\tsend(conversationId: Id, input: SendInput): Promise<Id>;\n\tresolveInputs(\n\t\tids: readonly Id[],\n\t\tresolution:\n\t\t\t| { status: \"done\"; answer: Id }\n\t\t\t| { status: \"unanswered\"; reason: NonNullable<Input[\"reason\"]>; detail?: string },\n\t): Promise<void>;\n\t/** Inbox placement at a safe boundary. `headBoundary`: the newest head as the caller knows it (including a same-batch self-head it appended). */\n\tboundary(\n\t\tconversationId: Id,\n\t\tat: \"postTools\" | \"final\",\n\t\theadBoundary: Id | undefined,\n\t): Promise<{ triggers: Id[]; terminated: boolean }>;\n\t/** Internal owned-conversation path. Sanitizes caller overrides while preserving inherited rewindable namespace slices. */\n\tcreateOwnedConversation(ownerTaskId: Id, sourceConversationId: Id, spec: OwnedConversationSpec): Promise<Id>;\n\t/** Internal host-fork path for an already validated historical snapshot. */\n\tcreateForkConversation(spec: ConversationSpec): Id;\n\tmarkTask(id: Id): void;\n}\n\n/** Thrown when a scan-shaped read follows a same-batch write to its domain. Poisons the transaction. */\nexport class ReadAfterWrite extends Error {\n\tconstructor(read: string, write: string) {\n\t\tsuper(`${read} after ${write} in the same transaction: the answer would not include the buffered write`);\n\t\tthis.name = \"ReadAfterWrite\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Runtime: what a kind's handlers get. Every commit checks the invocation token.\n// ---------------------------------------------------------------------------\n\nexport interface RequestOptions {\n\tmessages: StoredMessage[];\n\tthinkingLevel: ThinkingLevel;\n}\nexport interface Models {\n\tresolve(ref: ModelRef): Model | undefined;\n\tstream(model: Model, request: RequestOptions, ctx: Context): AsyncIterable<AssistantMessageEvent>;\n\tfetchDeferred(\n\t\tmodel: Model,\n\t\thandle: DeferredHandle,\n\t\tctx: Context,\n\t): Promise<AssistantMessage | { deferred: DeferredHandle }>;\n\tcancelDeferred(model: Model, handle: DeferredHandle, ctx: Context): Promise<void>;\n}\n\nexport interface Runtime<H extends object = object, Tx extends TaskTx = TaskTx> {\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n\treadonly kind: AnyKind;\n\tcommit<T>(fn: (tx: Tx, current: Task, ctx: Context) => T | Promise<T>, ctx: Context): Promise<T>;\n\treadonly hooks: HookRunner<H>;\n\treadonly models: Models;\n\treadonly tools: ReadonlyMap<string, ToolDeclaration>;\n\treadonly registries: { sections: SectionRegistry; tools: ToolRegistry };\n\treadonly kinds: ReadonlyMap<string, AnyKind>;\n\treadonly processHost: ProcessHost | undefined;\n\treadonly plugins: ReadonlyMap<string, PluginHandler>;\n\tnow(): number;\n\tsleep(untilMs: number, ctx: Context): Promise<void>;\n\twaitForInput(id: Id, ctx: Context): Promise<Input>;\n\twaitForTask(id: Id, ctx: Context): Promise<Task>;\n\tabortTask(id: Id, ctx: Context): Promise<\"marked\" | \"terminal\">;\n\tabortConversation(id: Id, ctx: Context): Promise<void>;\n\tcreateOwnedConversation(spec: OwnedConversationSpec, ctx: Context): Promise<Id>;\n\t/** Admission for a conversation owned by this task; the runtime verifies ownership before invoking the kernel. */\n\tsendOwned(conversationId: Id, input: SendInput, ctx: Context): Promise<Id>;\n\t// off-line reads\n\tcontext(conversationId: Id, at: Id | undefined, ctx: Context): Promise<ContextView>;\n\tnewestEntry(\n\t\tconversationId: Id,\n\t\topts: { kind?: string; withHead?: boolean },\n\t\tctx: Context,\n\t): Promise<Entry | undefined>;\n\trewindable(conversationId: Id, ctx: Context): Promise<RewindableState>;\n\tsticky(conversationId: Id, ctx: Context): Promise<StickyState>;\n\trewindableAsOf(conversationId: Id, at: Id, ctx: Context): Promise<RewindableState | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Tools\n// ---------------------------------------------------------------------------\n\nexport type ToolControl = { terminate?: true; handoff?: string; addTools?: string[] };\nexport interface ToolDiagnostic {\n\tseverity: \"info\" | \"warn\" | \"error\";\n\tmessage: string;\n\tcode?: string;\n}\nexport interface ToolResult {\n\t/** Omit when the tool streamed through `api.stream`: the bounded stream is the content. */\n\tcontent?: (TextContent | ImageContent)[];\n\tisError?: boolean;\n\tdetails?: JsonValue;\n\tdiagnostics?: ToolDiagnostic[];\n\tcontrol?: ToolControl;\n}\nexport interface ToolDeclaration<P extends TSchema = TSchema> {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly parameters: P;\n\treadonly replay?: \"safe\" | \"unsafe\"; // default unsafe\n\treadonly output?: { maxBytes?: number; maxLines?: number; retain?: \"head\" | \"tail\" };\n\texecute(args: Static<P>, api: ToolApi, ctx: Context): Promise<ToolResult>;\n}\n/** Erased declaration held by the registry. */\nexport type AnyToolDeclaration = ToolDeclaration<TSchema>;\n\n/** The narrow handle a task gets to a conversation it owns. */\nexport interface OwnedConversation {\n\treadonly id: Id;\n\tsend(\n\t\tinput: SendInput,\n\t\tctx: Context,\n\t): Promise<{ id: Id; wait(ctx: Context): Promise<Input>; result(ctx: Context): Promise<Input | undefined> }>;\n\tabort(ctx: Context): Promise<void>;\n}\n\nexport interface BeforeToolApi extends HookApi {\n\treadonly callId: string;\n\twaiting(ctx: Context): Promise<void>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, ctx: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, ctx: Context): Promise<T | undefined>;\n\temit(name: string, data: JsonValue, ctx: Context): Promise<void>;\n}\n\nexport interface ToolApi {\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n\treadonly callId: string;\n\t/** Pipe raw output here. The kernel bounds it per the declaration, flushes it on a throttle, and uses it as the result content unless the tool returns its own. Synchronous. */\n\tstream(chunk: string | Uint8Array): void;\n\t/** Mutate the live slot's free fields (`progress`, `details`, `continuedBy`). Identity fields are protected. */\n\tprogress(\n\t\tupdate: (slot: Pick<ToolSlot, \"progress\" | \"details\" | \"continuedBy\">) => void,\n\t\tctx: Context,\n\t): Promise<void>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, ctx: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, ctx: Context): Promise<T | undefined>;\n\tconversation(spec: OwnedConversationSpec, ctx: Context): Promise<OwnedConversation>;\n\ttask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts: { background?: true; after?: Id[] },\n\t\tctx: Context,\n\t): Promise<TaskRef<K>>;\n\tgetTask<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<TaskOf<K> | undefined>;\n\twaitForTask<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<TaskOf<K>>;\n\t/** Snapshot of another task's live slot (in this task's conversation or subtree). */\n\tslot<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<SlotOf<K> | undefined>;\n}\n\nexport interface ProcessSpec {\n\tcommand: string;\n\targs: string[];\n\tcwd: string;\n\tenv?: { [key: string]: string };\n}\nexport type ProcessStatus =\n\t| { status: \"running\"; stdout: string; stderr: string; droppedStdout: number; droppedStderr: number }\n\t| {\n\t\t\tstatus: \"exited\";\n\t\t\texitCode: number;\n\t\t\tstdout: string;\n\t\t\tstderr: string;\n\t\t\tdroppedStdout: number;\n\t\t\tdroppedStderr: number;\n\t }\n\t| { status: \"unknown\" };\nexport interface ProcessHost {\n\tstart(key: string, spec: ProcessSpec, ctx: Context): Promise<void>;\n\tstatus(key: string, ctx: Context): Promise<ProcessStatus>;\n\tkill(key: string, signal: \"SIGTERM\" | \"SIGKILL\", ctx: Context): Promise<void>;\n}\n\nexport type PluginHandler = (input: JsonValue, api: ToolApi, ctx: Context) => Promise<JsonValue>;\n\n// ---------------------------------------------------------------------------\n// Invocation tokens and invokers\n// ---------------------------------------------------------------------------\n\n/** An unforgeable capability: only the scheduler creates these, one per invocation. */\nexport class InvocationToken {\n\t#alive = true;\n\treadonly taskId: Id;\n\treadonly mode: \"run\" | \"abort\";\n\tconstructor(taskId: Id, mode: \"run\" | \"abort\") {\n\t\tthis.taskId = taskId;\n\t\tthis.mode = mode;\n\t}\n\tget alive() {\n\t\treturn this.#alive;\n\t}\n\t/** Called by the scheduler when the invocation returns. */\n\trevoke() {\n\t\tthis.#alive = false;\n\t}\n}\n\nexport type Invoker =\n\t| { readonly type: \"host\"; readonly conversationId?: Id }\n\t/** Harness internals acting with core authority (send, reset, abort, retire). Never exported. */\n\t| { readonly type: \"kernel\"; readonly conversationId?: Id }\n\t| {\n\t\t\treadonly type: \"task\";\n\t\t\treadonly token: InvocationToken;\n\t\t\treadonly id: Id;\n\t\t\treadonly conversationId: Id;\n\t\t\treadonly kind: AnyKind;\n\t\t\treadonly core: boolean;\n\t\t\treadonly mode: \"run\" | \"abort\";\n\t };\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class Forbidden extends Error {\n\tconstructor(what: string) {\n\t\tsuper(`forbidden: ${what}`);\n\t\tthis.name = \"Forbidden\";\n\t}\n}\nexport class ConversationBusy extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} is busy`);\n\t\tthis.name = \"ConversationBusy\";\n\t}\n}\nexport class GenerationInProgress extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} already has a live generation`);\n\t\tthis.name = \"GenerationInProgress\";\n\t}\n}\nexport class CollapseInProgress extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} already has a live collapse`);\n\t\tthis.name = \"CollapseInProgress\";\n\t}\n}\nexport class Faulted extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(`Session faulted: ${String(cause)}`);\n\t\tthis.name = \"Faulted\";\n\t}\n}\nexport class Closed extends Error {\n\tconstructor() {\n\t\tsuper(\"Session is closed\");\n\t\tthis.name = \"Closed\";\n\t}\n}\nexport class TaskContractFault extends Error {\n\tconstructor(kind: string, what: string) {\n\t\tsuper(`kind ${kind} broke its contract: ${what}`);\n\t\tthis.name = \"TaskContractFault\";\n\t}\n}\n\nexport type { ToolCall, ToolResultMessage, AssistantMessage, UserMessage, DeferredHandle, ThinkingLevel };\nexport type RequestMessage = StoredMessage;\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/harness/pico3/types.ts"],"names":[],"mappings":"AAuCA,qFAAqF;AACrF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAI,KAAQ,EAAa,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAc,CAAC;AA8DnG,MAAM,UAAU,WAAW,CAAkB,IAAY;IACxD,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uDAAuD,IAAI,EAAE,CAAC,CAAC;IAC3G,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,KAAwB,EAAc,EAAE,CAAC,KAAK,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC,CAAC;AACpG,CAAC;AAgID,mEAAmE;AACnE,MAAM,UAAU,QAAQ,CAAsB,IAAgB,EAAE,GAAW,EAAE,SAAY;IACxF,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC;QAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IACnD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAqC,CAAC;IACzD,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC,GAAG,CAAM,CAAC;IACtD,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACvB,OAAO,SAAS,CAAC;AAClB,CAAC;AA4OD,+DAA+D;AAC/D,MAAM,UAAU,UAAU,CASxB,UAA0C;IAC3C,IAAI,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QACpC,MAAM,IAAI,KAAK,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B,EAAE,gCAAgC,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACpC,CAAC;CACD;AACD,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC5C,YAAY,EAAM;QACjB,KAAK,CAAC,gBAAgB,EAAE,8BAA8B,CAAC,CAAC;QACxD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IAClC,CAAC;CACD;AACD,MAAM,OAAO,OAAQ,SAAQ,KAAK;IACjC,YAAY,KAAc;QACzB,KAAK,CAAC,oBAAoB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACvB,CAAC;CACD;AACD,MAAM,OAAO,MAAO,SAAQ,KAAK;IAChC;QACC,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;IACtB,CAAC;CACD;AACD,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC3C,YAAY,IAAY,EAAE,IAAY;QACrC,KAAK,CAAC,QAAQ,IAAI,wBAAwB,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IACjC,CAAC;CACD","sourcesContent":["/**\n * harness-v3 — records, documents, storage, kinds, transactions, runtime, tools, hooks.\n *\n * Durable model: four tables (conversations, entries, tasks, inputs) and three documents\n * (session, per-conversation rewindable, per-conversation sticky). Every durable position\n * is strict JSON (`JsonValue`); nothing durable is `unknown`.\n *\n * Single process. A storage path has one owning process and one owning Session at a time.\n * Two processes opening the same JSONL directory is unsupported.\n */\nimport type { JsonValue as ChordJsonValue, Context, JsonRepresentation } from \"@earendil-works/chord\";\nimport type { Op } from \"@earendil-works/chord/delta\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tDeferredHandle,\n\tImageContent,\n\tMessage as ModelMessage,\n\tModel as ModelOf,\n\tTextContent,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n\tUserMessage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ThinkingLevel } from \"../../types.ts\";\nimport type { SectionRegistry, SectionSeed, ToolRegistry } from \"./system.ts\";\n\n// ---------------------------------------------------------------------------\n// Strict durable JSON\n// ---------------------------------------------------------------------------\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = ChordJsonValue;\n/** Optional properties represent absent keys; committed values are normalized through JSON serialization. */\nexport type JsonObject = { [key: string]: JsonValue };\n\n/** Coerce an in-memory value (e.g. a pi-ai message) to its stored representation. */\nexport const toStored = <T>(value: T): Stored<T> => JSON.parse(JSON.stringify(value)) as Stored<T>;\n\n/**\n * The JSON representation of a value: what survives `JSON.parse(JSON.stringify(v))`.\n * Optional keys stay optional; `undefined` values vanish; functions are never durable.\n * Use for imported pi-ai types at durable positions.\n */\nexport type Stored<T> = JsonRepresentation<T>;\n\nexport type Id = number;\nexport type Seq = number;\n\n/** Compile-time assertion helper. */\nexport type Assert<T extends true> = T;\n/** True iff T is strict JSON (structurally). */\nexport type IsJson<T> = [T] extends [JsonValue] ? true : false;\n\n// ---------------------------------------------------------------------------\n// Records\n// ---------------------------------------------------------------------------\n\nexport interface Conversation {\n\treadonly id: Id;\n\treadonly parent?: { readonly conversationId: Id; readonly at: Id };\n\treadonly owner?: Id; // task that created it\n\t/** §8.1 section seed: applied by preparation while the conversation has no local managed entry. Private: not in ConversationView. */\n\treadonly sections?: readonly SectionSeed[];\n}\n\n/** Native system messages with JSON tool schemas at durable positions. */\nexport type SystemMessage = Omit<Extract<ModelMessage, { role: \"system\" }>, \"toolsAdded\"> & {\n\ttoolsAdded?: Tool<JsonObject>[];\n};\nexport type Message = ModelMessage | SystemMessage;\nexport type StoredMessage = Stored<Exclude<Message, { role: \"system\" }> | SystemMessage>;\nexport type Model = ModelOf<Api>;\n\nexport interface ContextEdit {\n\treadonly target: Id;\n\treadonly action: \"omit\" | \"replace\";\n\treadonly messages?: readonly StoredMessage[];\n}\n\nexport interface Entry {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly kind: string;\n\treadonly model?: readonly StoredMessage[]; // what the model sees; absent = display/bookkeeping only\n\treadonly data?: JsonObject;\n\treadonly head?: Id; // context starts here (may be a parent's entry). Assigned by the kernel; `self` in NewEntry\n\treadonly edits?: readonly ContextEdit[];\n\treadonly byTaskId?: Id;\n}\nexport type NewEntry = Omit<Entry, \"id\" | \"conversationId\" | \"byTaskId\" | \"head\"> & { readonly head?: Id | \"self\" };\n\n/** A typed witness for an entry kind: `is()` narrows, and typed writes take `EntryInput<E>`. */\nexport interface EntryKind<E extends Entry = Entry> {\n\treadonly kind: string;\n\tis(entry: Entry | undefined): entry is E;\n}\nexport type EntryInput<E extends Entry> = Omit<E, \"id\" | \"conversationId\" | \"kind\" | \"byTaskId\" | \"head\"> &\n\t(E extends { readonly head: Id } ? { readonly head: Id | \"self\" } : { readonly head?: never });\nexport function defineEntry<E extends Entry>(kind: string): EntryKind<E> {\n\tif (kind.startsWith(\"pi.\")) throw new Error(`entry kind names beginning with \"pi.\" are reserved: ${kind}`);\n\treturn Object.freeze({ kind, is: (entry: Entry | undefined): entry is E => entry?.kind === kind });\n}\n\nexport type Checkpoint = JsonObject & { readonly phase: string };\n\nexport type Completion<R extends JsonValue = JsonValue, F extends JsonValue = JsonValue> =\n\t| { readonly status: \"completed\"; readonly result: R }\n\t| { readonly status: \"failed\"; readonly failure: F };\nexport type Outcome<R extends JsonValue = JsonValue, F extends JsonValue = JsonValue, A extends JsonValue = JsonValue> =\n\t| Completion<R, F>\n\t| { readonly status: \"aborted\"; readonly result: A }\n\t| { readonly status: \"orphaned\" }\n\t/** The kind broke its contract (a handler threw or returned an invalid shape). Not one of its declared failures. */\n\t| { readonly status: \"faulted\"; readonly error: string };\n\nexport interface Task<I extends JsonValue = JsonValue, C extends Checkpoint = Checkpoint> {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly kind: string;\n\treadonly input: I;\n\treadonly status: \"pending\" | \"running\" | \"terminal\";\n\treadonly checkpoint?: C;\n\treadonly abort?: true; // the durable mark\n\treadonly outcome?: Outcome;\n\treadonly after: readonly Id[];\n\treadonly owns: readonly Id[]; // conversations this task created\n\treadonly background?: true; // does not hold the conversation busy; survives conversation abort\n}\nexport type TaskPatch = { readonly id: Id } & Partial<\n\tOmit<Pick<Task, \"status\" | \"checkpoint\" | \"abort\" | \"outcome\" | \"owns\">, \"checkpoint\">\n> & { checkpoint?: Checkpoint | null };\n\nexport interface Input {\n\treadonly id: Id;\n\treadonly conversationId: Id;\n\treadonly requestId?: string;\n\treadonly status: \"queued\" | \"placed\" | \"done\" | \"unanswered\";\n\treadonly entry?: Id;\n\treadonly answer?: Id;\n\treadonly reason?: \"aborted\" | \"stale\" | \"terminated\" | \"failed\";\n\treadonly detail?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Documents (Chord-tracked). Mutated in place inside a commit, diffed at the end.\n// ---------------------------------------------------------------------------\n\nexport type ModelRef = { provider: string; modelId: string };\nexport type RetryPolicy = { enabled: boolean; maxRetries: number; baseDelayMs: number; maxAgentDelayMs?: number };\n\n/** One running tool call, at the index of its call in the assistant message. */\nexport type ToolSlot = {\n\tcallId: string;\n\tname: string;\n\targs: JsonValue;\n\tstatus: \"pending\" | \"running\" | \"done\" | \"error\" | \"aborted\";\n\twaitingOn?: string;\n\toutput?: string; // bounded stream as it stands\n\tprogress?: string;\n\tdetails?: JsonValue;\n\tcontinuedBy?: Id; // a background task that took the work over; its live state is `tasks[continuedBy]`\n\tentry?: Id;\n\t/** Private task-lifetime coordination state. Never projected into ConversationView. */\n\tmemos?: { [key: string]: JsonValue };\n};\n/** The current turn, shaped for rendering. Reset when a generation starts; cleared when the turn ends. */\nexport type TurnState = {\n\tmessage?: Stored<AssistantMessage>; // streaming assistant message\n\ttools: ToolSlot[]; // tools of the assistant message being executed, by call index\n};\n\n/** Private durable namespace slices stored in authoritative documents. */\nexport type PluginSlices = { [namespace: string]: JsonObject };\n\n/** Rewound by forks: forks see the state as of their fork point. Core config fields come from the built-in kinds' declarations. */\nexport type RewindableState = {\n\tmodel?: ModelRef;\n\tthinkingLevel: ThinkingLevel;\n\tselectedTools: string[];\n\tprofile: string;\n\tthreshold: number;\n\tkeepRecent: number;\n\tplugins: PluginSlices;\n\t[key: string]: JsonValue | undefined; // ordinary kinds' declared config, keyed by their disjoint names\n};\n/** The present. Never folded historically; truncated to its last base. */\nexport type StickyState = {\n\tretry: RetryPolicy;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tinbox: QueuedInput[];\n\tturn: TurnState;\n\ttasks: { [taskId: string]: JsonObject }; // non-turn tasks' live slots; retired by the kernel on terminal\n\tplugins: PluginSlices;\n\t[key: string]: JsonValue | undefined;\n};\nexport type SessionState = { plugins: PluginSlices; [key: string]: JsonValue | undefined };\n\nexport type QueuedInput =\n\t| { id: Id; mode: \"steer\" | \"followUp\"; input: Stored<UserInput> }\n\t| { id: Id; mode: \"write\"; entry: Stored<NewEntry> };\n\nexport type DocRef =\n\t| { doc: \"session\" }\n\t| { doc: \"rewindable\"; conversationId: Id }\n\t| { doc: \"sticky\"; conversationId: Id };\n\nexport type NamespaceDefaults<T extends JsonObject> = {\n\treadonly rewindable?: Partial<T>;\n\treadonly sticky?: Partial<T>;\n\treadonly session?: Partial<T>;\n};\n\n/** Current process authority for one durable namespace string. */\nexport interface Namespace<T extends JsonObject = JsonObject> {\n\treadonly id: string;\n\t/** Type-only invariant marker. */\n\treadonly valueType?: (value: T) => T;\n\tunregister(): void;\n}\n\n/** Internal erased registration paired with the public namespace token. */\nexport interface NamespaceRegistration {\n\treadonly token: object;\n\treadonly defaults: { readonly rewindable: JsonObject; readonly sticky: JsonObject; readonly session: JsonObject };\n\treadonly routes: ReadonlyMap<string, DocRef[\"doc\"]>;\n\treadonly project?: (slice: Readonly<JsonObject>) => JsonValue;\n}\n\n/** First writer wins, including when the stored winner is null. */\nexport function memoOnce<T extends JsonValue>(slot: JsonObject, key: string, candidate: T): T {\n\tif (!Object.hasOwn(slot, \"memos\")) slot.memos = {};\n\tconst memos = slot.memos as { [key: string]: JsonValue };\n\tif (Object.hasOwn(memos, key)) return memos[key] as T;\n\tmemos[key] = candidate;\n\treturn candidate;\n}\n\n// ---------------------------------------------------------------------------\n// Configuration facade: every registered kind's `config` merged flat.\n// ---------------------------------------------------------------------------\n\ntype UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;\n/** A declared slice; the undeclared `ConfigShape` (index signature) counts as no keys. */\ntype Declared<S> = string extends keyof S ? object : S;\ntype RewindableOf<K> = K extends unknown\n\t? ConfigOf<K> extends { readonly rewindable: infer RC }\n\t\t? Declared<RC>\n\t\t: object\n\t: never;\ntype StickyOf<K> = K extends unknown\n\t? ConfigOf<K> extends { readonly sticky: infer SC }\n\t\t? Declared<SC>\n\t\t: object\n\t: never;\nexport type ConfigOfKinds<Ks extends readonly AnyKind[]> = UnionToIntersection<\n\tRewindableOf<Ks[number]> | StickyOf<Ks[number]>\n> extends infer M\n\t? { [K in keyof M]: M[K] }\n\t: never;\ntype KeysOfKind<K> = (keyof RewindableOf<K> | keyof StickyOf<K>) & string;\ntype IsUnion<U, C = U> = U extends unknown ? ([C] extends [U] ? false : true) : never;\n/** The kinds declaring `Key`. */\ntype Owners<Ks extends readonly AnyKind[], Key extends string> = {\n\t[I in keyof Ks]: Key extends KeysOfKind<Ks[I]> ? Ks[I] : never;\n}[number];\ntype AllKeys<Ks extends readonly AnyKind[]> = { [I in keyof Ks]: KeysOfKind<Ks[I]> }[number];\ntype ClashingKeys<Ks extends readonly AnyKind[]> = {\n\t[Key in AllKeys<Ks>]: true extends IsUnion<Owners<Ks, Key>> ? Key : never;\n}[AllKeys<Ks>];\n/** `true` iff no two kinds declare the same config key. Asserted at open at compile time and at runtime. */\nexport type DisjointConfig<Ks extends readonly AnyKind[]> = [ClashingKeys<Ks>] extends [never] ? true : false;\n\nexport interface ConfigFacade<Cfg extends object> {\n\tget(ctx: Context): Promise<Readonly<Cfg>>;\n\t/** One commit, routed to the declaring documents. */\n\tset(patch: { [K in keyof Cfg]?: Cfg[K] }, ctx: Context): Promise<void>;\n\t/** Delete persisted overrides. Declared defaults become visible; `model` becomes absent. */\n\treset(keys: readonly (keyof Cfg)[], ctx: Context): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Storage: six write types, a handful of reads. One owning Session per instance.\n// ---------------------------------------------------------------------------\n\nexport type Write =\n\t| { type: \"conversation\"; conversation: Conversation }\n\t| { type: \"entry\"; entry: Entry }\n\t| { type: \"task\"; task: Task } // create\n\t| { type: \"task.patch\"; patch: TaskPatch } // `checkpoint: null` clears\n\t| { type: \"input\"; input: Input } // create or replace whole\n\t| { type: \"doc\"; ref: DocRef; ops: Op[] };\n\nexport interface EntryScan {\n\tconversationId: Id;\n\tkind?: string;\n\twithHead?: boolean;\n\tbefore?: Id; // strictly less\n\tlimit: number;\n}\nexport interface TaskScan {\n\tconversationId?: Id;\n\tstatus?: Task[\"status\"][];\n\tkind?: string;\n}\n\nexport interface Storage {\n\t/** Persist one batch atomically: all or nothing. Returns the commit sequence. */\n\tcommit(writes: readonly Write[], ctx: Context): Promise<Seq>;\n\tmintId(): Id;\n\tconversation(id: Id, ctx: Context): Promise<Conversation | undefined>;\n\tconversations(ctx: Context): Promise<Conversation[]>;\n\tentries(ids: readonly Id[], ctx: Context): Promise<Map<Id, Entry>>;\n\t/** Newest-first, fork-aware: this conversation's entries, then the parent's up to the fork point, and so on. */\n\tscanEntries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n\ttask(id: Id, ctx: Context): Promise<Task | undefined>;\n\tscanTasks(scan: TaskScan, ctx: Context): Promise<Task[]>;\n\tinput(id: Id, ctx: Context): Promise<Input | undefined>;\n\tinputByRequest(conversationId: Id, requestId: string, ctx: Context): Promise<Input | undefined>;\n\tdoc(ref: DocRef, ctx: Context): Promise<JsonObject | undefined>;\n\t/** Rewindable doc as of the atomic commit containing entry `at` (fork inheritance). See \"commit-granular history\". */\n\tdocAsOf(conversationId: Id, at: Id, ctx: Context): Promise<JsonObject | undefined>;\n\t/** Rewrite a doc log from its last base. */\n\ttruncate(ref: DocRef, ctx: Context): Promise<void>;\n\tclose(ctx: Context): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Kinds\n// ---------------------------------------------------------------------------\n\n/** A hook may synchronously or asynchronously omit its replacement value. */\n// biome-ignore lint/suspicious/noConfusingVoidType: void is the intentional callback no-value result\nexport type HookResult<T> = T | void | Promise<T | void>;\n\nexport interface HookApi {\n\treadonly kind: string;\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n}\n/** Kept as the concise name used by existing kind hook declarations. */\nexport type HookInfo = HookApi;\nexport interface HookBinding<H extends object> {\n\treadonly handlers: Partial<H>;\n\treadonly namespace: Namespace;\n\treadonly api: HookApi;\n}\nexport interface HookRunner<H extends object> {\n\thandlers(): readonly HookBinding<H>[];\n\t/** Call `fn` on each handler; `onValue` sees non-undefined results and may return true to stop. A throwing handler is reported and skipped. */\n\teach<V>(\n\t\tctx: Context,\n\t\tfn: (handlers: Partial<H>, api: HookApi) => HookResult<V>,\n\t\tonValue?: (v: V) => unknown,\n\t): Promise<void>;\n}\n\n/** What a phase handler returns: advance to a checkpoint, or finish. A builder runs on the line and may terminalize or ask to retry. */\nexport type Step<C extends Checkpoint, R extends JsonValue, F extends JsonValue, Tx extends TaskTx = TaskTx> =\n\t| {\n\t\t\treadonly next:\n\t\t\t\t| C\n\t\t\t\t| ((\n\t\t\t\t\t\ttx: Tx,\n\t\t\t\t\t\tcurrent: Task,\n\t\t\t\t\t\tctx: Context,\n\t\t\t\t ) => C | Completion<R, F> | \"retry\" | Promise<C | Completion<R, F> | \"retry\">);\n\t }\n\t| { readonly done: Closure<R, F, Tx> };\nexport type Closure<R extends JsonValue, F extends JsonValue, Tx extends TaskTx = TaskTx> = (\n\ttx: Tx,\n\tcurrent: Task,\n\tctx: Context,\n) => Completion<R, F> | Promise<Completion<R, F>>;\nexport type AbortClosure<A extends JsonValue, Tx extends TaskTx = TaskTx> = (\n\ttx: Tx,\n\tcurrent: Task,\n\tctx: Context,\n) => A | Promise<A>;\n\nexport type CheckpointAt<C extends Checkpoint, P extends C[\"phase\"]> = Extract<C, { readonly phase: P }>;\nexport type PhaseHandler<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tP extends C[\"phase\"],\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tH extends object,\n\tTx extends TaskTx = TaskTx,\n> = (\n\ttask: Task<I, CheckpointAt<C, P>> & { readonly checkpoint: CheckpointAt<C, P> },\n\trt: Runtime<H, Tx>,\n\tctx: Context,\n) => Promise<Step<C, R, F, Tx>>;\n\n/** A config slice: JSON values; a key whose default is `undefined` is optional (only `model` among the built-ins). */\nexport type ConfigShape = { [key: string]: JsonValue | undefined };\n/** Per-kind configuration: defaults, split by document. Keys across all kinds must be disjoint. */\nexport interface KindConfig<RC extends ConfigShape = ConfigShape, SC extends ConfigShape = ConfigShape> {\n\treadonly rewindable?: RC;\n\treadonly sticky?: SC;\n}\n\n/** Phantom carrier so `TaskOf<K>` etc. can read a kind's types back out. Never set at runtime. */\nexport interface KindTypes<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object,\n\tCfg extends KindConfig,\n\tS extends JsonObject,\n> {\n\tinput: I;\n\tcheckpoint: C;\n\tresult: R;\n\tfailure: F;\n\taborted: A;\n\thooks: H;\n\tconfig: Cfg;\n\tslot: S;\n}\n\n/**\n * A task kind. `initial` runs when there is no checkpoint; `phases` is exhaustive over\n * `C[\"phase\"]`. Phases named in `inflight` are written by a handler immediately before an\n * external effect and are entered by the scheduler only after reopen; a `next` transition\n * into one is rejected as a contract fault.\n */\nexport interface Kind<\n\tI extends JsonValue = JsonValue,\n\tC extends Checkpoint = Checkpoint,\n\tR extends JsonValue = JsonValue,\n\tF extends JsonValue = JsonValue,\n\tA extends JsonValue = JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n\tTx extends TaskTx = TaskTx,\n> {\n\treadonly types?: KindTypes<I, C, R, F, A, H, Cfg, S>;\n\treadonly name: string;\n\t/** A turn kind makes the conversation busy for admission. */\n\treadonly turn?: boolean;\n\treadonly config?: Cfg;\n\t/** Live slot (`sticky.tasks[id]`) initializer. */\n\treadonly slot?: (input: I) => S;\n\t/** Rendering projection for a non-turn task. Raw checkpoints and slots are never published. */\n\treadonly describe?: (task: Task<I, C> & { readonly slot?: Readonly<S> }) => JsonValue;\n\treadonly inflight?: readonly C[\"phase\"][];\n\tinitial(\n\t\ttask: Task<I, never> & { readonly checkpoint?: undefined },\n\t\trt: Runtime<H, Tx>,\n\t\tctx: Context,\n\t): Promise<Step<C, R, F, Tx>>;\n\treadonly phases: { readonly [P in C[\"phase\"]]: PhaseHandler<I, C, P, R, F, H, Tx> };\n\tabort(task: Task<I, C>, rt: Runtime<H, Tx>, ctx: Context): Promise<AbortClosure<A, Tx>>;\n}\n\n/** Internal kind type for fixed core machinery. */\nexport type CoreKind<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n> = Kind<I, C, R, F, A, H, Cfg, S, CoreTx>;\n\n/** Author an ordinary kind. Names may not begin with `pi.`. */\nexport function defineTask<\n\tI extends JsonValue,\n\tC extends Checkpoint,\n\tR extends JsonValue,\n\tF extends JsonValue,\n\tA extends JsonValue,\n\tH extends object = object,\n\tCfg extends KindConfig = KindConfig,\n\tS extends JsonObject = JsonObject,\n>(definition: Kind<I, C, R, F, A, H, Cfg, S>): Kind<I, C, R, F, A, H, Cfg, S> {\n\tif (definition.name.startsWith(\"pi.\"))\n\t\tthrow new Error(`task kind names beginning with \"pi.\" are reserved: ${definition.name}`);\n\treturn Object.freeze({ ...definition });\n}\n\n/**\n * The erased kind the kernel stores. Handlers are invoked through `KindAdapter`, the one\n * place a concrete `Kind<…>` is narrowed to this and its outputs are validated.\n */\nexport interface AnyKind {\n\treadonly types?: unknown;\n\treadonly name: string;\n\treadonly turn?: boolean;\n\treadonly config?: KindConfig;\n\treadonly slot?: (input: never) => JsonObject;\n\treadonly describe?: unknown;\n\treadonly inflight?: readonly string[];\n\treadonly initial: unknown;\n\treadonly phases: { readonly [phase: string]: unknown };\n\treadonly abort: unknown;\n}\n\nexport interface TaskRef<K extends AnyKind = AnyKind> {\n\treadonly id: Id;\n\treadonly kind: K;\n}\nexport interface EntryRef<E extends Entry = Entry> {\n\treadonly id: Id;\n\treadonly kind: EntryKind<E>;\n}\n\ntype TypesOf<K> = K extends { types?: infer T } ? NonNullable<T> : never;\nexport type TaskOf<K> = TypesOf<K> extends KindTypes<\n\tinfer I,\n\tinfer C,\n\tinfer R,\n\tinfer F,\n\tinfer A,\n\tobject,\n\tKindConfig,\n\tJsonObject\n>\n\t? Omit<Task<I, C>, \"outcome\"> & { readonly outcome?: Outcome<R, F, A> }\n\t: never;\nexport type InputOf<K> = TypesOf<K> extends KindTypes<\n\tinfer I,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tKindConfig,\n\tJsonObject\n>\n\t? I\n\t: never;\nexport type HooksOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tinfer H,\n\tKindConfig,\n\tJsonObject\n>\n\t? H\n\t: never;\nexport type ConfigOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tinfer Cfg,\n\tJsonObject\n>\n\t? Cfg\n\t: never;\nexport type SlotOf<K> = TypesOf<K> extends KindTypes<\n\tJsonValue,\n\tCheckpoint,\n\tJsonValue,\n\tJsonValue,\n\tJsonValue,\n\tobject,\n\tKindConfig,\n\tinfer S\n>\n\t? S\n\t: never;\n\nexport type TaskSpec = {\n\tkind: string;\n\tconversationId?: Id;\n\tinput: JsonValue;\n\tafter?: Id[];\n\tbackground?: true;\n};\n\n// ---------------------------------------------------------------------------\n// Transactions. One implementation; three views.\n// ---------------------------------------------------------------------------\n\nexport interface ConversationSpec {\n\tparent?: { conversationId: Id; at: Id | \"start\" };\n\trewindable?: Partial<RewindableState>;\n\tsticky?: Partial<StickyState>;\n\tsections?: readonly SectionSeed[];\n}\nexport interface OwnedConversationSpec {\n\tinherit?: boolean;\n\trewindable?: Partial<RewindableState>;\n\tsticky?: Partial<StickyState>;\n}\nexport type UserInput = string | UserMessage[\"content\"];\nexport interface SendInput {\n\tcontent: UserInput;\n\trequestId?: string;\n\twhenBusy?: \"steer\" | \"followUp\" | \"reject\";\n}\nexport type ContextView = { head: Entry | undefined; entries: Entry[]; messages: StoredMessage[] };\n\nexport type GenerationStatus =\n\t| { stage: \"waiting\"; on: \"compaction\" }\n\t| { stage: \"preparing\" }\n\t| { stage: \"requesting\"; attempt: number }\n\t| { stage: \"streaming\"; attempt: number }\n\t| { stage: \"retrying\"; attempt: number; retryAt: number; lastError: string }\n\t| { stage: \"deferred\"; attempt: number; pollAt: number };\n\nexport interface TurnView {\n\tinputs: Id[];\n\tgeneration?: GenerationStatus;\n\tmessage?: Stored<AssistantMessage>;\n\ttools: Omit<ToolSlot, \"memos\">[];\n}\n\nexport interface ConversationView {\n\tconversation: Omit<Conversation, \"sections\">;\n\tentries: Entry[];\n\tconfig: { [key: string]: JsonValue | undefined };\n\tinbox: QueuedInput[];\n\tturn?: TurnView;\n\tcompaction?: {\n\t\ttaskId: Id;\n\t\treason: \"threshold\" | \"manual\" | \"overflow\";\n\t\tstage: \"summarizing\" | \"retrying\";\n\t\tattempt: number;\n\t\tretryAt?: number;\n\t};\n\ttasks: { [taskId: string]: { kind: string; background?: true; marked?: true; status: JsonValue } };\n\tplugins: { [namespace: string]: JsonValue };\n}\n\nexport type ViewEvent =\n\t| { type: \"entry.added\"; entry: Entry }\n\t| { type: \"head.moved\"; entry: Entry }\n\t| { type: \"turn.started\"; inputs: Id[] }\n\t| { type: \"turn.ended\"; inputs: Id[]; status: \"done\"; answer: Id }\n\t| {\n\t\t\ttype: \"turn.ended\";\n\t\t\tinputs: Id[];\n\t\t\tstatus: \"unanswered\";\n\t\t\treason: \"terminated\" | \"aborted\" | \"failed\" | \"stale\";\n\t\t\tdetail?: string;\n\t }\n\t| { type: \"input.queued\"; input: Id; mode: \"steer\" | \"followUp\" | \"write\" }\n\t| { type: \"input.placed\"; input: Id; entry: Id }\n\t| { type: \"input.aborted\"; input: Id }\n\t| { type: \"generation.started\"; taskId: Id; attempt: number }\n\t| { type: \"generation.retrying\"; taskId: Id; attempt: number; retryAt: number; error: string }\n\t| { type: \"generation.deferred\"; taskId: Id; pollAt: number }\n\t| { type: \"generation.completed\"; taskId: Id; entry: Id; toolCalls: number }\n\t| {\n\t\t\ttype: \"generation.failed\";\n\t\t\ttaskId: Id;\n\t\t\treason: \"provider\" | \"overflow\" | \"retries_exhausted\" | \"no_model\";\n\t\t\tdetail: string;\n\t\t\tentry?: Id;\n\t }\n\t| { type: \"tool.waiting\"; taskId: Id; callId: string; on: string }\n\t| { type: \"tool.started\"; taskId: Id; callId: string; name: string }\n\t| { type: \"tool.finished\"; taskId: Id; callId: string; entry: Id; isError: boolean; control?: ToolControl }\n\t| { type: \"tool.aborted\"; taskId: Id; callId: string; entry: Id }\n\t| { type: \"compaction.started\"; taskId: Id; reason: \"threshold\" | \"manual\" | \"overflow\"; through: Id }\n\t| { type: \"compaction.retrying\"; taskId: Id; attempt: number; retryAt: number; error: string }\n\t| { type: \"compaction.finished\"; taskId: Id; summary: Id }\n\t| {\n\t\t\ttype: \"compaction.failed\";\n\t\t\ttaskId: Id;\n\t\t\treason: \"stale\" | \"declined\" | \"provider\" | \"retries_exhausted\" | \"no_model\";\n\t\t\tdetail: string;\n\t }\n\t| { type: \"task.started\"; taskId: Id; kind: string; background?: true }\n\t| {\n\t\t\ttype: \"task.ended\";\n\t\t\ttaskId: Id;\n\t\t\tkind: string;\n\t\t\toutcome: \"completed\" | \"failed\" | \"aborted\" | \"orphaned\" | \"faulted\";\n\t }\n\t| { type: \"config.changed\"; keys: string[] }\n\t| { type: \"warning\"; source: string; message: string }\n\t| { type: `plugin.${string}`; data: JsonValue };\n\nexport interface Envelope {\n\treadonly revision: number;\n\treadonly ops: Op[];\n\treadonly events: ViewEvent[];\n}\n\n/** Reads available to every view. Scans reject after a same-batch write to their domain (`ReadAfterWrite`). */\nexport interface TxReads {\n\tconversation(id: Id): Promise<Conversation | undefined>;\n\tentry(id: Id): Promise<Entry | undefined>;\n\tentry<E extends Entry>(kind: EntryKind<E>, id: Id): Promise<E | undefined>;\n\tentries(ids: readonly Id[]): Promise<Map<Id, Entry>>;\n\tnewestEntry(conversationId: Id, opts?: { kind?: string; withHead?: boolean }): Promise<Entry | undefined>;\n\tnewestEntry<E extends Entry>(conversationId: Id, kind: EntryKind<E>): Promise<E | undefined>;\n\tscanEntries(scan: EntryScan): Promise<Entry[]>;\n\tcontext(conversationId: Id, at?: Id): Promise<ContextView>;\n\ttask(id: Id): Promise<Task | undefined>;\n\ttask<K extends AnyKind>(ref: TaskRef<K>): Promise<TaskOf<K> | undefined>;\n\ttasks(scan: TaskScan): Promise<Task[]>;\n\tinput(id: Id): Promise<Input | undefined>;\n\trewindableAsOf(conversationId: Id, at: Id): Promise<RewindableState | undefined>;\n\t/** Plain copies. Document proxies cannot escape a transaction. */\n\tsnapshot(ref: { doc: \"rewindable\"; conversationId: Id }): RewindableState;\n\tsnapshot(ref: { doc: \"sticky\"; conversationId: Id }): StickyState;\n\tsnapshot(ref: { doc: \"session\" }): SessionState;\n}\n\ninterface SharedTx extends TxReads {\n\tplugins<T extends JsonObject>(namespace: Namespace<T>): T;\n\temit<T extends JsonObject>(namespace: Namespace<T>, name: string, data: JsonValue): void;\n\tconfig(conversationId: Id): { get<K extends string>(key: K): JsonValue | undefined };\n\t/** Passive entry: queued when busy, appended when idle. Returns the input id. */\n\twrite(conversationId: Id, entry: NewEntry): Promise<Id>;\n\twrite<E extends Entry>(conversationId: Id, kind: EntryKind<E>, entry: EntryInput<E>): Promise<Id>;\n\tcreateTask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts?: { conversationId?: Id; background?: true; after?: Id[] },\n\t): TaskRef<K>;\n\tcreateConversation(spec: ConversationSpec): Id;\n}\n\n/** What the host gets. */\nexport interface HostTx extends SharedTx {\n\t/** Config through the facade; raw core fields are not exposed to the host tx. */\n\tconfig(conversationId: Id): {\n\t\tget<K extends string>(key: K): JsonValue | undefined;\n\t\tset(key: string, value: JsonValue): void;\n\t\treset(key: string): void;\n\t};\n}\n\n/** What an ordinary task gets: scoped shared operations plus its own checkpoint and slot. */\nexport interface TaskTx extends SharedTx {\n\tcheckpoint<C extends Checkpoint>(value: C): void;\n\tslot<K extends AnyKind>(ref: TaskRef<K>): SlotOf<K>;\n\t/** Create a conversation this task owns. `parent` must be in the task's subtree. */\n\tcreateConversation(spec: ConversationSpec): Id;\n}\n\n/** Internal full authority for the fixed turn machinery. Never handed to ordinary kinds or the host. */\nexport interface CoreTx extends TaskTx {\n\temit<T extends JsonObject>(namespace: Namespace<T>, name: string, data: JsonValue): void;\n\temit(event: ViewEvent): void;\n\trewindable(conversationId: Id): RewindableState;\n\tsticky(conversationId: Id): StickyState;\n\tsession(): SessionState;\n\ttoolSlot(task: { conversationId: Id; input: { index: number } }): ToolSlot;\n\tappendEntry(conversationId: Id, entry: NewEntry): Id;\n\tappendEntry<E extends Entry>(conversationId: Id, kind: EntryKind<E>, entry: EntryInput<E>): EntryRef<E>;\n\tcreateTask(spec: TaskSpec): Id;\n\tcreateTask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts?: { conversationId?: Id; background?: true; after?: Id[] },\n\t): TaskRef<K>;\n\tsend(conversationId: Id, input: SendInput): Promise<Id>;\n\tresolveInputs(\n\t\tids: readonly Id[],\n\t\tresolution:\n\t\t\t| { status: \"done\"; answer: Id }\n\t\t\t| { status: \"unanswered\"; reason: NonNullable<Input[\"reason\"]>; detail?: string },\n\t): Promise<void>;\n\t/** Inbox placement at a safe boundary. `headBoundary`: the newest head as the caller knows it (including a same-batch self-head it appended). */\n\tboundary(\n\t\tconversationId: Id,\n\t\tat: \"postTools\" | \"final\",\n\t\theadBoundary: Id | undefined,\n\t): Promise<{ triggers: Id[]; terminated: boolean }>;\n\t/** Internal owned-conversation path. Sanitizes caller overrides while preserving inherited rewindable namespace slices. */\n\tcreateOwnedConversation(ownerTaskId: Id, sourceConversationId: Id, spec: OwnedConversationSpec): Promise<Id>;\n\t/** Internal host-fork path for an already validated historical snapshot. */\n\tcreateForkConversation(spec: ConversationSpec): Id;\n\tmarkTask(id: Id): void;\n}\n\n/** Thrown when a scan-shaped read follows a same-batch write to its domain. Poisons the transaction. */\nexport class ReadAfterWrite extends Error {\n\tconstructor(read: string, write: string) {\n\t\tsuper(`${read} after ${write} in the same transaction: the answer would not include the buffered write`);\n\t\tthis.name = \"ReadAfterWrite\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Runtime: what a kind's handlers get. Every commit checks the invocation token.\n// ---------------------------------------------------------------------------\n\nexport interface RequestOptions {\n\tmessages: StoredMessage[];\n\tthinkingLevel: ThinkingLevel;\n}\nexport interface Models {\n\tresolve(ref: ModelRef): Model | undefined;\n\tstream(model: Model, request: RequestOptions, ctx: Context): AsyncIterable<AssistantMessageEvent>;\n\tfetchDeferred(\n\t\tmodel: Model,\n\t\thandle: DeferredHandle,\n\t\tctx: Context,\n\t): Promise<AssistantMessage | { deferred: DeferredHandle }>;\n\tcancelDeferred(model: Model, handle: DeferredHandle, ctx: Context): Promise<void>;\n}\n\nexport interface Runtime<H extends object = object, Tx extends TaskTx = TaskTx> {\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n\treadonly kind: AnyKind;\n\tcommit<T>(fn: (tx: Tx, current: Task, ctx: Context) => T | Promise<T>, ctx: Context): Promise<T>;\n\treadonly hooks: HookRunner<H>;\n\treadonly models: Models;\n\treadonly tools: ReadonlyMap<string, ToolDeclaration>;\n\treadonly registries: { sections: SectionRegistry; tools: ToolRegistry };\n\treadonly kinds: ReadonlyMap<string, AnyKind>;\n\treadonly processHost: ProcessHost | undefined;\n\treadonly plugins: ReadonlyMap<string, PluginHandler>;\n\tnow(): number;\n\tsleep(untilMs: number, ctx: Context): Promise<void>;\n\twaitForInput(id: Id, ctx: Context): Promise<Input>;\n\twaitForTask(id: Id, ctx: Context): Promise<Task>;\n\tabortTask(id: Id, ctx: Context): Promise<\"marked\" | \"terminal\">;\n\tabortConversation(id: Id, ctx: Context): Promise<void>;\n\tcreateOwnedConversation(spec: OwnedConversationSpec, ctx: Context): Promise<Id>;\n\t/** Admission for a conversation owned by this task; the runtime verifies ownership before invoking the kernel. */\n\tsendOwned(conversationId: Id, input: SendInput, ctx: Context): Promise<Id>;\n\t// off-line reads\n\tcontext(conversationId: Id, at: Id | undefined, ctx: Context): Promise<ContextView>;\n\tnewestEntry(\n\t\tconversationId: Id,\n\t\topts: { kind?: string; withHead?: boolean },\n\t\tctx: Context,\n\t): Promise<Entry | undefined>;\n\trewindable(conversationId: Id, ctx: Context): Promise<RewindableState>;\n\tsticky(conversationId: Id, ctx: Context): Promise<StickyState>;\n\trewindableAsOf(conversationId: Id, at: Id, ctx: Context): Promise<RewindableState | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Tools\n// ---------------------------------------------------------------------------\n\nexport type ToolControl = { terminate?: true; handoff?: string; addTools?: string[] };\nexport interface ToolDiagnostic {\n\tseverity: \"info\" | \"warn\" | \"error\";\n\tmessage: string;\n\tcode?: string;\n}\nexport interface ToolResult {\n\t/** Omit when the tool streamed through `api.stream`: the bounded stream is the content. */\n\tcontent?: (TextContent | ImageContent)[];\n\tisError?: boolean;\n\tdetails?: JsonValue;\n\tdiagnostics?: ToolDiagnostic[];\n\tcontrol?: ToolControl;\n}\nexport interface ToolDeclaration<P extends TSchema = TSchema> {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly parameters: P;\n\treadonly replay?: \"safe\" | \"unsafe\"; // default unsafe\n\treadonly output?: { maxBytes?: number; maxLines?: number; retain?: \"head\" | \"tail\" };\n\texecute(args: Static<P>, api: ToolApi, ctx: Context): Promise<ToolResult>;\n}\n/** Erased declaration held by the registry. */\nexport type AnyToolDeclaration = ToolDeclaration<TSchema>;\n\n/** The narrow handle a task gets to a conversation it owns. */\nexport interface OwnedConversation {\n\treadonly id: Id;\n\tsend(\n\t\tinput: SendInput,\n\t\tctx: Context,\n\t): Promise<{ id: Id; wait(ctx: Context): Promise<Input>; result(ctx: Context): Promise<Input | undefined> }>;\n\tabort(ctx: Context): Promise<void>;\n}\n\nexport interface BeforeToolApi extends HookApi {\n\treadonly callId: string;\n\twaiting(ctx: Context): Promise<void>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, ctx: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, ctx: Context): Promise<T | undefined>;\n\temit(name: string, data: JsonValue, ctx: Context): Promise<void>;\n}\n\nexport interface ToolApi {\n\treadonly taskId: Id;\n\treadonly conversationId: Id;\n\treadonly callId: string;\n\t/** Pipe raw output here. The kernel bounds it per the declaration, flushes it on a throttle, and uses it as the result content unless the tool returns its own. Synchronous. */\n\tstream(chunk: string | Uint8Array): void;\n\t/** Mutate the live slot's free fields (`progress`, `details`, `continuedBy`). Identity fields are protected. */\n\tprogress(\n\t\tupdate: (slot: Pick<ToolSlot, \"progress\" | \"details\" | \"continuedBy\">) => void,\n\t\tctx: Context,\n\t): Promise<void>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, ctx: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, ctx: Context): Promise<T | undefined>;\n\tconversation(spec: OwnedConversationSpec, ctx: Context): Promise<OwnedConversation>;\n\ttask<K extends AnyKind>(\n\t\tkind: K,\n\t\tinput: InputOf<K>,\n\t\topts: { background?: true; after?: Id[] },\n\t\tctx: Context,\n\t): Promise<TaskRef<K>>;\n\tgetTask<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<TaskOf<K> | undefined>;\n\twaitForTask<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<TaskOf<K>>;\n\t/** Snapshot of another task's live slot (in this task's conversation or subtree). */\n\tslot<K extends AnyKind>(ref: TaskRef<K>, ctx: Context): Promise<SlotOf<K> | undefined>;\n}\n\nexport interface ProcessSpec {\n\tcommand: string;\n\targs: string[];\n\tcwd: string;\n\tenv?: { [key: string]: string };\n}\nexport type ProcessStatus =\n\t| { status: \"running\"; stdout: string; stderr: string; droppedStdout: number; droppedStderr: number }\n\t| {\n\t\t\tstatus: \"exited\";\n\t\t\texitCode: number;\n\t\t\tstdout: string;\n\t\t\tstderr: string;\n\t\t\tdroppedStdout: number;\n\t\t\tdroppedStderr: number;\n\t }\n\t| { status: \"unknown\" };\nexport interface ProcessHost {\n\tstart(key: string, spec: ProcessSpec, ctx: Context): Promise<void>;\n\tstatus(key: string, ctx: Context): Promise<ProcessStatus>;\n\tkill(key: string, signal: \"SIGTERM\" | \"SIGKILL\", ctx: Context): Promise<void>;\n}\n\nexport type PluginHandler = (input: JsonValue, api: ToolApi, ctx: Context) => Promise<JsonValue>;\n\n// ---------------------------------------------------------------------------\n// Invocation tokens and invokers\n// ---------------------------------------------------------------------------\n\n/** An unforgeable capability: only the scheduler creates these, one per invocation. */\nexport class InvocationToken {\n\t#alive = true;\n\treadonly taskId: Id;\n\treadonly mode: \"run\" | \"abort\";\n\tconstructor(taskId: Id, mode: \"run\" | \"abort\") {\n\t\tthis.taskId = taskId;\n\t\tthis.mode = mode;\n\t}\n\tget alive() {\n\t\treturn this.#alive;\n\t}\n\t/** Called by the scheduler when the invocation returns. */\n\trevoke() {\n\t\tthis.#alive = false;\n\t}\n}\n\nexport type Invoker =\n\t| { readonly type: \"host\"; readonly conversationId?: Id }\n\t/** Harness internals acting with core authority (send, reset, abort, retire). Never exported. */\n\t| { readonly type: \"kernel\"; readonly conversationId?: Id }\n\t| {\n\t\t\treadonly type: \"task\";\n\t\t\treadonly token: InvocationToken;\n\t\t\treadonly id: Id;\n\t\t\treadonly conversationId: Id;\n\t\t\treadonly kind: AnyKind;\n\t\t\treadonly core: boolean;\n\t\t\treadonly mode: \"run\" | \"abort\";\n\t };\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class Forbidden extends Error {\n\tconstructor(what: string) {\n\t\tsuper(`forbidden: ${what}`);\n\t\tthis.name = \"Forbidden\";\n\t}\n}\nexport class ConversationBusy extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} is busy`);\n\t\tthis.name = \"ConversationBusy\";\n\t}\n}\nexport class GenerationInProgress extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} already has a live generation`);\n\t\tthis.name = \"GenerationInProgress\";\n\t}\n}\nexport class CollapseInProgress extends Error {\n\tconstructor(id: Id) {\n\t\tsuper(`conversation ${id} already has a live collapse`);\n\t\tthis.name = \"CollapseInProgress\";\n\t}\n}\nexport class Faulted extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(`Session faulted: ${String(cause)}`);\n\t\tthis.name = \"Faulted\";\n\t}\n}\nexport class Closed extends Error {\n\tconstructor() {\n\t\tsuper(\"Session is closed\");\n\t\tthis.name = \"Closed\";\n\t}\n}\nexport class TaskContractFault extends Error {\n\tconstructor(kind: string, what: string) {\n\t\tsuper(`kind ${kind} broke its contract: ${what}`);\n\t\tthis.name = \"TaskContractFault\";\n\t}\n}\n\nexport type { ToolCall, ToolResultMessage, AssistantMessage, UserMessage, DeferredHandle, ThinkingLevel };\nexport type RequestMessage = StoredMessage;\n"]}
|
package/dist/proxy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK,2BAA2B,EAEhC,KAAK,KAAK,EACV,KAAK,mBAAmB,EACxB,KAAK,UAAU,EACf,KAAK,QAAQ,EAEb,KAAK,iBAAiB,EACtB,MAAM,uBAAuB,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,0BAA0B,GACnC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;CAAE,GACnE;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC3D;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GACrE;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GACzE;IAAE,IAAI,EAAE,gB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tC,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAqCD,wBAAgB,WAAW,CAC1B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,kBAAkB,GACzB,2BAA2B,CA+I7B"}
|
package/dist/proxy.js
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
* Proxy stream function for apps that route LLM calls through a server.
|
|
3
3
|
* The server manages auth and proxies requests to LLM providers.
|
|
4
4
|
*/
|
|
5
|
-
|
|
6
|
-
import { createAssistantMessageEventStream, parseStreamingJson, } from "@earendil-works/pi-ai";
|
|
5
|
+
import { createAssistantMessageEventStream, ToolCallArgumentsStream, } from "@earendil-works/pi-ai";
|
|
7
6
|
/**
|
|
8
7
|
* Stream function that proxies through a server instead of calling LLM providers directly.
|
|
9
8
|
* The server strips the partial field from delta events to reduce bandwidth.
|
|
@@ -99,6 +98,8 @@ export function streamProxy(model, context, options) {
|
|
|
99
98
|
const decoder = new TextDecoder();
|
|
100
99
|
let buffer = "";
|
|
101
100
|
let sawTerminalEvent = false;
|
|
101
|
+
// Argument streams of open tool calls by content index, kept off the content blocks.
|
|
102
|
+
const toolArguments = new Map();
|
|
102
103
|
const processLine = (line) => {
|
|
103
104
|
if (!line.startsWith("data: "))
|
|
104
105
|
return;
|
|
@@ -106,7 +107,7 @@ export function streamProxy(model, context, options) {
|
|
|
106
107
|
if (!data)
|
|
107
108
|
return;
|
|
108
109
|
const proxyEvent = JSON.parse(data);
|
|
109
|
-
const event = processProxyEvent(proxyEvent, partial);
|
|
110
|
+
const event = processProxyEvent(proxyEvent, partial, toolArguments);
|
|
110
111
|
if (event) {
|
|
111
112
|
if (event.type === "done" || event.type === "error")
|
|
112
113
|
sawTerminalEvent = true;
|
|
@@ -173,7 +174,7 @@ export function streamProxy(model, context, options) {
|
|
|
173
174
|
/**
|
|
174
175
|
* Process a proxy event and update the partial message.
|
|
175
176
|
*/
|
|
176
|
-
function processProxyEvent(proxyEvent, partial) {
|
|
177
|
+
function processProxyEvent(proxyEvent, partial, toolArguments) {
|
|
177
178
|
switch (proxyEvent.type) {
|
|
178
179
|
case "provider_stream_event":
|
|
179
180
|
return undefined;
|
|
@@ -243,15 +244,15 @@ function processProxyEvent(proxyEvent, partial) {
|
|
|
243
244
|
id: proxyEvent.id,
|
|
244
245
|
name: proxyEvent.toolName,
|
|
245
246
|
arguments: {},
|
|
246
|
-
partialJson: "",
|
|
247
247
|
};
|
|
248
|
+
toolArguments.set(proxyEvent.contentIndex, new ToolCallArgumentsStream());
|
|
248
249
|
return { type: "toolcall_start", contentIndex: proxyEvent.contentIndex, partial };
|
|
249
250
|
case "toolcall_delta": {
|
|
250
251
|
const content = partial.content[proxyEvent.contentIndex];
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
partial.content[proxyEvent.contentIndex] = { ...content };
|
|
252
|
+
const args = toolArguments.get(proxyEvent.contentIndex);
|
|
253
|
+
if (content?.type === "toolCall" && args !== undefined) {
|
|
254
|
+
// A new block object, so reactive consumers see the change.
|
|
255
|
+
partial.content[proxyEvent.contentIndex] = { ...content, arguments: args.append(proxyEvent.delta) };
|
|
255
256
|
return {
|
|
256
257
|
type: "toolcall_delta",
|
|
257
258
|
contentIndex: proxyEvent.contentIndex,
|
|
@@ -265,7 +266,7 @@ function processProxyEvent(proxyEvent, partial) {
|
|
|
265
266
|
const content = partial.content[proxyEvent.contentIndex];
|
|
266
267
|
if (content?.type === "toolCall") {
|
|
267
268
|
Object.assign(content, proxyEvent.toolCall);
|
|
268
|
-
delete
|
|
269
|
+
toolArguments.delete(proxyEvent.contentIndex);
|
|
269
270
|
return {
|
|
270
271
|
type: "toolcall_end",
|
|
271
272
|
contentIndex: proxyEvent.contentIndex,
|
package/dist/proxy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.js","sourceRoot":"","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,MAAM,EAAE,KAAK,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC;YACvG,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;gBACpD,OAAO,CAAC,qBAAqB,GAAG,UAAU,CAAC,qBAAqB,CAAC;YAClE,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"provider_stream_event\"; data: unknown; model: Model<Api> }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t\t\tdeferred?: AssistantMessage[\"deferred\"];\n\t\t\tmessage?: AssistantMessage;\n\t\t\tproviderThinkingLevel?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tmessage?: AssistantMessage;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t\t\tproviderThinkingLevel?: string;\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"samplingParams\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tsamplingParams: options.samplingParams,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(\n\tmodel: Model<any>,\n\tcontext: TranscriptContext,\n\toptions: ProxyStreamOptions,\n): AssistantMessageEventStream {\n\tconst stream = createAssistantMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"pending\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet sawTerminalEvent = false;\n\n\t\t\tconst processLine = (line: string): void => {\n\t\t\t\tif (!line.startsWith(\"data: \")) return;\n\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\tif (!data) return;\n\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\tif (event) {\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") sawTerminalEvent = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tprocessLine(line);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\t// The final event may not be newline-terminated; flush the decoder and\n\t\t\t// process whatever is left in the buffer.\n\t\t\tbuffer += decoder.decode();\n\t\t\tif (buffer) {\n\t\t\t\tprocessLine(buffer);\n\t\t\t}\n\n\t\t\tif (!sawTerminalEvent) {\n\t\t\t\t// A clean EOF without a done/error event means the server dropped the\n\t\t\t\t// response mid-stream. Surface it as an error instead of leaving\n\t\t\t\t// consumers waiting on a result that never arrives.\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"Connection closed by proxy server before the response completed\";\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\treason: \"error\",\n\t\t\t\t\terror: partial,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"provider_stream_event\":\n\t\t\treturn undefined;\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\tif (proxyEvent.providerThinkingLevel !== undefined) {\n\t\t\t\tpartial.providerThinkingLevel = proxyEvent.providerThinkingLevel;\n\t\t\t}\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tif (proxyEvent.message) return { type: \"error\", reason: proxyEvent.reason, error: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tif (proxyEvent.providerThinkingLevel !== undefined) {\n\t\t\t\tpartial.providerThinkingLevel = proxyEvent.providerThinkingLevel;\n\t\t\t}\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKN,iCAAiC,EAKjC,uBAAuB,GAEvB,MAAM,uBAAuB,CAAC;AA0D/B;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAS,wBAAwB,CAAC,OAA2B;IAC5D,OAAO;QACN,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,SAAS,EAAE,OAAO,CAAC,S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AAY,CAAC;YAC/C,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;gBACpD,OAAO,CAAC,qBAAqB,GAAG,UAAU,CAAC,qBAAqB,CAAC;YAClE,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n\tToolCallArgumentsStream,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"provider_stream_event\"; data: unknown; model: Model<Api> }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t\t\tdeferred?: AssistantMessage[\"deferred\"];\n\t\t\tmessage?: AssistantMessage;\n\t\t\tproviderThinkingLevel?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tmessage?: AssistantMessage;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t\t\tproviderThinkingLevel?: string;\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"samplingParams\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tsamplingParams: options.samplingParams,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(\n\tmodel: Model<any>,\n\tcontext: TranscriptContext,\n\toptions: ProxyStreamOptions,\n): AssistantMessageEventStream {\n\tconst stream = createAssistantMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"pending\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet sawTerminalEvent = false;\n\t\t\t// Argument streams of open tool calls by content index, kept off the content blocks.\n\t\t\tconst toolArguments = new Map<number, ToolCallArgumentsStream>();\n\n\t\t\tconst processLine = (line: string): void => {\n\t\t\t\tif (!line.startsWith(\"data: \")) return;\n\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\tif (!data) return;\n\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\tconst event = processProxyEvent(proxyEvent, partial, toolArguments);\n\t\t\t\tif (event) {\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") sawTerminalEvent = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tprocessLine(line);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\t// The final event may not be newline-terminated; flush the decoder and\n\t\t\t// process whatever is left in the buffer.\n\t\t\tbuffer += decoder.decode();\n\t\t\tif (buffer) {\n\t\t\t\tprocessLine(buffer);\n\t\t\t}\n\n\t\t\tif (!sawTerminalEvent) {\n\t\t\t\t// A clean EOF without a done/error event means the server dropped the\n\t\t\t\t// response mid-stream. Surface it as an error instead of leaving\n\t\t\t\t// consumers waiting on a result that never arrives.\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"Connection closed by proxy server before the response completed\";\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\treason: \"error\",\n\t\t\t\t\terror: partial,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n\ttoolArguments: Map<number, ToolCallArgumentsStream>,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"provider_stream_event\":\n\t\t\treturn undefined;\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t};\n\t\t\ttoolArguments.set(proxyEvent.contentIndex, new ToolCallArgumentsStream());\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tconst args = toolArguments.get(proxyEvent.contentIndex);\n\t\t\tif (content?.type === \"toolCall\" && args !== undefined) {\n\t\t\t\t// A new block object, so reactive consumers see the change.\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content, arguments: args.append(proxyEvent.delta) };\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tObject.assign(content, proxyEvent.toolCall);\n\t\t\t\ttoolArguments.delete(proxyEvent.contentIndex);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tif (proxyEvent.message) return { type: \"done\", reason: proxyEvent.reason, message: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tpartial.deferred = proxyEvent.deferred;\n\t\t\tif (proxyEvent.providerThinkingLevel !== undefined) {\n\t\t\t\tpartial.providerThinkingLevel = proxyEvent.providerThinkingLevel;\n\t\t\t}\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tif (proxyEvent.message) return { type: \"error\", reason: proxyEvent.reason, error: proxyEvent.message };\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\tif (proxyEvent.providerThinkingLevel !== undefined) {\n\t\t\t\tpartial.providerThinkingLevel = proxyEvent.providerThinkingLevel;\n\t\t\t}\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, ImageContent, JsonValue, Message, Model, SimpleStreamOptions, TextContent, Tool, ToolResultMessage, TranscriptContext, Usage } from "@earendil-works/pi-ai";
|
|
2
|
-
import type { Static
|
|
2
|
+
import type { Static } from "@earendil-works/pi-schema";
|
|
3
3
|
/**
|
|
4
4
|
* Stream function used by the agent loop. `Models.streamSimple` satisfies
|
|
5
5
|
* this shape.
|
|
@@ -405,25 +405,34 @@ export interface AgentToolCallOutcome {
|
|
|
405
405
|
* the tool promise settles are ignored.
|
|
406
406
|
*/
|
|
407
407
|
export type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;
|
|
408
|
-
/**
|
|
409
|
-
|
|
408
|
+
/**
|
|
409
|
+
* The arguments type of a tool with parameter schema `TParameters`: pi-schema's `Static<TParameters>` (the builders'
|
|
410
|
+
* type, TypeBox's for the common TypeBox kinds, else `unknown`), and `any` for `AgentTool<any>`.
|
|
411
|
+
*/
|
|
412
|
+
export type AgentToolParams<TParameters> = IsAny<TParameters> extends true ? any : Static<TParameters>;
|
|
413
|
+
type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false;
|
|
414
|
+
/**
|
|
415
|
+
* Tool definition used by the agent runtime. `parameters` is any JSON Schema object; see {@link AgentToolParams} for
|
|
416
|
+
* the type `execute` receives.
|
|
417
|
+
*/
|
|
418
|
+
export interface AgentTool<TParameters extends object = object, TDetails = any> extends Tool<TParameters> {
|
|
410
419
|
/** Human-readable label for UI display. */
|
|
411
420
|
label: string;
|
|
412
421
|
/**
|
|
413
422
|
* Optional compatibility shim for raw tool-call arguments before schema validation.
|
|
414
423
|
* Must return an object that matches `TParameters`.
|
|
415
424
|
*/
|
|
416
|
-
prepareArguments?: (args: unknown) =>
|
|
425
|
+
prepareArguments?: (args: unknown) => AgentToolParams<TParameters>;
|
|
417
426
|
/**
|
|
418
427
|
* JSON Schema of `structuredContent` in successful results. Tools that declare it should always
|
|
419
428
|
* set `structuredContent`.
|
|
420
429
|
*/
|
|
421
|
-
outputSchema?:
|
|
430
|
+
outputSchema?: object;
|
|
422
431
|
/**
|
|
423
432
|
* Execute the tool call. Throw on failure, or return a result with `isError: true`; do not only
|
|
424
433
|
* describe the failure in `content`.
|
|
425
434
|
*/
|
|
426
|
-
execute: (toolCallId: string, params:
|
|
435
|
+
execute: (toolCallId: string, params: AgentToolParams<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
|
|
427
436
|
/** Recovery policy for an effect whose durable intent exists but whose outcome is unknown. */
|
|
428
437
|
replay?: "never" | "safe";
|
|
429
438
|
/**
|
|
@@ -490,4 +499,5 @@ export type AgentEvent = {
|
|
|
490
499
|
/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */
|
|
491
500
|
durationMs?: number;
|
|
492
501
|
};
|
|
502
|
+
export {};
|
|
493
503
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,2BAA2B,EAC3B,YAAY,EACZ,SAAS,EACT,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,EACL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,2BAA2B,EAC3B,YAAY,EACZ,SAAS,EACT,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,EACL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAExD;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,iBAAiB,EAC1B,OAAO,CAAC,EAAE,mBAAmB,KACzB,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAExE;;;;;;;GAOG;AACH,MAAM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IAAI,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,YAAY,CAAC;IAAC,qBAAqB,EAAE,qBAAqB,CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE,GAE9C;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAE,GACjF;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAC;IAAC,aAAa,EAAE,GAAG,CAAA;CAAE,GACtG;IACA,IAAI,EAAE,oBAAoB,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,wGAAwG;IACxG,UAAU,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tImageContent,\n\tJsonValue,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * The loop passes a normalized transcript: the system prompt and tool\n * declarations are carried by the transcript's system messages, never by\n * `context.systemPrompt` or `context.tools`.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n * - `structuredContent`: if provided, replaces the structured content. If `content` is provided\n * without it, the structured content is dropped, because it may no longer match the content.\n * Return it along with `content` to keep it.\n *\n * Other omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tstructuredContent?: JsonValue;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to completed-turn callbacks. */\nexport interface AgentTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages emitted for the completed turn. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Decision returned by {@link FinishTurn}. Returning undefined preserves normal scheduling. */\nexport type AgentTurnDecision = { action: \"continue\" } | { action: \"end\" };\n\n/**\n * Called after a completed assistant turn and all of its tool-result messages, but before `turn_end`.\n * On a normal turn, `{ action: \"continue\" }` ensures one next provider request. Tool-result, steering, or\n * follow-up scheduling can satisfy that request and adds no extra request; otherwise the loop continues once\n * with the current context. Error and aborted responses remain hard exits.\n */\nexport type FinishTurn = (\n\tturn: AgentTurnContext,\n\tsignal?: AbortSignal,\n) => AgentTurnDecision | void | Promise<AgentTurnDecision | undefined> | Promise<void>;\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Messages to append before the next provider request, with normal lifecycle events. */\n\tmessages?: AgentMessage[];\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/** Runtime state available immediately before a conversational provider request. */\nexport interface PrepareRequestContext {\n\tcontext: AgentContext;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n}\n\n/** Replacement runtime state for the provider request being prepared. */\nexport type AgentRequestUpdate = Omit<AgentLoopTurnUpdate, \"messages\">;\n\n/**\n * Called immediately before every conversational provider request, including the first.\n * Pending messages have already been appended and emitted when this callback runs.\n */\nexport type PrepareRequest = (\n\trequest: PrepareRequestContext,\n\tsignal?: AbortSignal,\n) => AgentRequestUpdate | void | Promise<AgentRequestUpdate | undefined> | Promise<void>;\n\nexport interface PrepareNextTurnContext extends AgentTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a SystemMessage, UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after the assistant message and all tool-result messages have been emitted, immediately before `turn_end`.\n\t * `{ action: \"end\" }` ends the run without polling queues or preparing another request.\n\t * On a normal turn, `{ action: \"continue\" }` ensures one next provider request. Tool-result, steering, or\n\t * follow-up scheduling can satisfy that request and adds no extra request; otherwise the loop continues once\n\t * with the current context. Returning undefined preserves normal scheduling. Error and aborted responses remain\n\t * hard exits.\n\t */\n\tfinishTurn?: FinishTurn;\n\n\t/**\n\t * Called immediately before every conversational provider request, including the first.\n\t * Pending messages have already been appended. The returned context, model, and thinking level\n\t * replace the runtime values for this and later requests in the run. This hook does not poll queues.\n\t */\n\tprepareRequest?: PrepareRequest;\n\n\t/**\n\t * Called after `turn_end` when the loop will continue, immediately before the next turn starts.\n\t * Return replacement context/model/thinking state or messages to append to affect that turn.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `finishTurn` ends the run.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * A blocked result can also set `terminate: true` to participate in the batch early-termination rule.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/**\n\t * Current system prompt, replayed from the transcript's system messages.\n\t *\n\t * Read-only: to change the prompt, append a system message with `content` or `sections`.\n\t * In `initialState`, this seeds the leading system message.\n\t */\n\treadonly systemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/**\n\t * Executable tools. Assigning a new array copies the top-level array.\n\t *\n\t * Differences from the tools declared in the transcript are announced to the model\n\t * with a system message before the next request.\n\t */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/**\n\t * Conversation transcript. Assigning a new array copies the top-level array.\n\t *\n\t * System messages in the transcript carry the prompt and tool declarations.\n\t */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T = JsonValue | undefined> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Machine-readable result matching the tool's `outputSchema`, for programmatic callers. Not sent\n\t * to the model; `content` remains the model-facing result.\n\t */\n\tstructuredContent?: JsonValue;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Report a failure without throwing. The model sees `content` as an error result, like a thrown\n\t * error, but `details` and `structuredContent` are kept for the UI and programmatic callers.\n\t */\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Final outcome of a tool call after hooks ran. */\nexport interface AgentToolCallOutcome {\n\ttoolCall: AgentToolCall;\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\t/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */\n\tdurationMs?: number;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/**\n\t * JSON Schema of `structuredContent` in successful results. Tools that declare it should always\n\t * set `structuredContent`.\n\t */\n\toutputSchema?: TSchema;\n\t/**\n\t * Execute the tool call. Throw on failure, or return a result with `isError: true`; do not only\n\t * describe the failure in `content`.\n\t */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/** Recovery policy for an effect whose durable intent exists but whose outcome is unknown. */\n\treplay?: \"never\" | \"safe\";\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for execution in this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for system, user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */\n\t\t\tdurationMs?: number;\n\t };\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tImageContent,\n\tJsonValue,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static } from \"@earendil-works/pi-schema\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * The loop passes a normalized transcript: the system prompt and tool\n * declarations are carried by the transcript's system messages, never by\n * `context.systemPrompt` or `context.tools`.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n * - `structuredContent`: if provided, replaces the structured content. If `content` is provided\n * without it, the structured content is dropped, because it may no longer match the content.\n * Return it along with `content` to keep it.\n *\n * Other omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tstructuredContent?: JsonValue;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to completed-turn callbacks. */\nexport interface AgentTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages emitted for the completed turn. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Decision returned by {@link FinishTurn}. Returning undefined preserves normal scheduling. */\nexport type AgentTurnDecision = { action: \"continue\" } | { action: \"end\" };\n\n/**\n * Called after a completed assistant turn and all of its tool-result messages, but before `turn_end`.\n * On a normal turn, `{ action: \"continue\" }` ensures one next provider request. Tool-result, steering, or\n * follow-up scheduling can satisfy that request and adds no extra request; otherwise the loop continues once\n * with the current context. Error and aborted responses remain hard exits.\n */\nexport type FinishTurn = (\n\tturn: AgentTurnContext,\n\tsignal?: AbortSignal,\n) => AgentTurnDecision | void | Promise<AgentTurnDecision | undefined> | Promise<void>;\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Messages to append before the next provider request, with normal lifecycle events. */\n\tmessages?: AgentMessage[];\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/** Runtime state available immediately before a conversational provider request. */\nexport interface PrepareRequestContext {\n\tcontext: AgentContext;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n}\n\n/** Replacement runtime state for the provider request being prepared. */\nexport type AgentRequestUpdate = Omit<AgentLoopTurnUpdate, \"messages\">;\n\n/**\n * Called immediately before every conversational provider request, including the first.\n * Pending messages have already been appended and emitted when this callback runs.\n */\nexport type PrepareRequest = (\n\trequest: PrepareRequestContext,\n\tsignal?: AbortSignal,\n) => AgentRequestUpdate | void | Promise<AgentRequestUpdate | undefined> | Promise<void>;\n\nexport interface PrepareNextTurnContext extends AgentTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a SystemMessage, UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after the assistant message and all tool-result messages have been emitted, immediately before `turn_end`.\n\t * `{ action: \"end\" }` ends the run without polling queues or preparing another request.\n\t * On a normal turn, `{ action: \"continue\" }` ensures one next provider request. Tool-result, steering, or\n\t * follow-up scheduling can satisfy that request and adds no extra request; otherwise the loop continues once\n\t * with the current context. Returning undefined preserves normal scheduling. Error and aborted responses remain\n\t * hard exits.\n\t */\n\tfinishTurn?: FinishTurn;\n\n\t/**\n\t * Called immediately before every conversational provider request, including the first.\n\t * Pending messages have already been appended. The returned context, model, and thinking level\n\t * replace the runtime values for this and later requests in the run. This hook does not poll queues.\n\t */\n\tprepareRequest?: PrepareRequest;\n\n\t/**\n\t * Called after `turn_end` when the loop will continue, immediately before the next turn starts.\n\t * Return replacement context/model/thinking state or messages to append to affect that turn.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `finishTurn` ends the run.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * A blocked result can also set `terminate: true` to participate in the batch early-termination rule.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/**\n\t * Current system prompt, replayed from the transcript's system messages.\n\t *\n\t * Read-only: to change the prompt, append a system message with `content` or `sections`.\n\t * In `initialState`, this seeds the leading system message.\n\t */\n\treadonly systemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/**\n\t * Executable tools. Assigning a new array copies the top-level array.\n\t *\n\t * Differences from the tools declared in the transcript are announced to the model\n\t * with a system message before the next request.\n\t */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/**\n\t * Conversation transcript. Assigning a new array copies the top-level array.\n\t *\n\t * System messages in the transcript carry the prompt and tool declarations.\n\t */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T = JsonValue | undefined> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Machine-readable result matching the tool's `outputSchema`, for programmatic callers. Not sent\n\t * to the model; `content` remains the model-facing result.\n\t */\n\tstructuredContent?: JsonValue;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Report a failure without throwing. The model sees `content` as an error result, like a thrown\n\t * error, but `details` and `structuredContent` are kept for the UI and programmatic callers.\n\t */\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Final outcome of a tool call after hooks ran. */\nexport interface AgentToolCallOutcome {\n\ttoolCall: AgentToolCall;\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\t/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */\n\tdurationMs?: number;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/**\n * The arguments type of a tool with parameter schema `TParameters`: pi-schema's `Static<TParameters>` (the builders'\n * type, TypeBox's for the common TypeBox kinds, else `unknown`), and `any` for `AgentTool<any>`.\n */\nexport type AgentToolParams<TParameters> = IsAny<TParameters> extends true ? any : Static<TParameters>;\n\n// `0 extends 1 & T` is resolved too early for a `T` constrained to `object`; this form waits for the argument.\ntype IsAny<T> = boolean extends (T extends never ? true : false) ? true : false;\n\n/**\n * Tool definition used by the agent runtime. `parameters` is any JSON Schema object; see {@link AgentToolParams} for\n * the type `execute` receives.\n */\nexport interface AgentTool<TParameters extends object = object, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => AgentToolParams<TParameters>;\n\t/**\n\t * JSON Schema of `structuredContent` in successful results. Tools that declare it should always\n\t * set `structuredContent`.\n\t */\n\toutputSchema?: object;\n\t/**\n\t * Execute the tool call. Throw on failure, or return a result with `isError: true`; do not only\n\t * describe the failure in `content`.\n\t */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: AgentToolParams<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/** Recovery policy for an effect whose durable intent exists but whose outcome is unknown. */\n\treplay?: \"never\" | \"safe\";\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for execution in this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for system, user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */\n\t\t\tdurationMs?: number;\n\t };\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@averyyy/pi-agent-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0-piclient.2",
|
|
4
4
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"README.md"
|
|
46
46
|
],
|
|
47
47
|
"scripts": {
|
|
48
|
-
"clean": "
|
|
48
|
+
"clean": "node ../../scripts/package-files.mjs clean dist",
|
|
49
49
|
"generate-telemetry-docs": "node scripts/generate-telemetry-docs.ts",
|
|
50
50
|
"check:telemetry-docs": "node scripts/generate-telemetry-docs.ts --check",
|
|
51
51
|
"build": "tsc -p tsconfig.build.json",
|
|
@@ -56,9 +56,10 @@
|
|
|
56
56
|
"prepublishOnly": "npm run build"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@earendil-works/chord": "1.
|
|
60
|
-
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.
|
|
61
|
-
"@earendil-works/pi-
|
|
59
|
+
"@earendil-works/chord": "1.5.0",
|
|
60
|
+
"@earendil-works/pi-ai": "npm:@averyyy/pi-ai@1.5.0-piclient.2",
|
|
61
|
+
"@earendil-works/pi-schema": "1.5.0",
|
|
62
|
+
"@earendil-works/pi-telemetry": "1.5.0",
|
|
62
63
|
"diff": "8.0.4",
|
|
63
64
|
"ignore": "7.0.8",
|
|
64
65
|
"typebox": "1.3.27",
|
|
@@ -83,8 +84,8 @@
|
|
|
83
84
|
},
|
|
84
85
|
"devDependencies": {
|
|
85
86
|
"@types/node": "22.19.19",
|
|
86
|
-
"@vitest/coverage-v8": "4.1.
|
|
87
|
-
"vitest": "4.1.
|
|
87
|
+
"@vitest/coverage-v8": "4.1.12",
|
|
88
|
+
"vitest": "4.1.12"
|
|
88
89
|
},
|
|
89
90
|
"publishConfig": {
|
|
90
91
|
"access": "public"
|