@earendil-works/pi-durable 1.5.0 → 1.5.1
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/CHANGELOG.md +18 -0
- package/README.md +17 -4
- package/dist/codemode/codemode.d.ts +2 -1
- package/dist/codemode/codemode.d.ts.map +1 -1
- package/dist/codemode/codemode.js +1 -37
- package/dist/codemode/codemode.js.map +1 -1
- package/dist/codemode/models.d.ts +2 -1
- package/dist/codemode/models.d.ts.map +1 -1
- package/dist/codemode/models.js.map +1 -1
- package/dist/documents.d.ts +1 -1
- package/dist/documents.d.ts.map +1 -1
- package/dist/documents.js +1 -1
- package/dist/documents.js.map +1 -1
- package/dist/entries.d.ts +1 -1
- package/dist/entries.d.ts.map +1 -1
- package/dist/entries.js.map +1 -1
- package/dist/env/index.d.ts +1 -1
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js.map +1 -1
- package/dist/env/node-watch.d.ts +1 -1
- package/dist/env/node-watch.d.ts.map +1 -1
- package/dist/env/node-watch.js.map +1 -1
- package/dist/env/node.d.ts +1 -1
- package/dist/env/node.d.ts.map +1 -1
- package/dist/env/node.js.map +1 -1
- package/dist/harness/agent.d.ts.map +1 -1
- package/dist/harness/agent.js +27 -1
- package/dist/harness/agent.js.map +1 -1
- package/dist/harness/compaction.d.ts +8 -3
- package/dist/harness/compaction.d.ts.map +1 -1
- package/dist/harness/compaction.js +21 -9
- package/dist/harness/compaction.js.map +1 -1
- package/dist/harness/context.d.ts +1 -1
- package/dist/harness/context.d.ts.map +1 -1
- package/dist/harness/context.js.map +1 -1
- package/dist/harness/define.d.ts +1 -1
- package/dist/harness/define.d.ts.map +1 -1
- package/dist/harness/define.js.map +1 -1
- package/dist/harness/generation.d.ts +1 -1
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +6 -4
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts +1 -1
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +2 -1
- package/dist/harness/inbox.d.ts.map +1 -1
- package/dist/harness/inbox.js +1 -1
- package/dist/harness/inbox.js.map +1 -1
- package/dist/harness/json.d.ts +1 -1
- package/dist/harness/json.d.ts.map +1 -1
- package/dist/harness/json.js.map +1 -1
- package/dist/harness/live.d.ts +2 -1
- package/dist/harness/live.d.ts.map +1 -1
- package/dist/harness/live.js.map +1 -1
- package/dist/harness/partial-changes.d.ts +1 -1
- package/dist/harness/partial-changes.d.ts.map +1 -1
- package/dist/harness/partial-changes.js +1 -0
- package/dist/harness/partial-changes.js.map +1 -1
- package/dist/harness/prompt.d.ts +1 -1
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/provider.d.ts +1 -1
- package/dist/harness/provider.d.ts.map +1 -1
- package/dist/harness/provider.js.map +1 -1
- package/dist/harness/registry-reader.d.ts +1 -1
- package/dist/harness/registry-reader.d.ts.map +1 -1
- package/dist/harness/registry-reader.js.map +1 -1
- package/dist/harness/scheduler.d.ts +2 -1
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +42 -13
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +1 -1
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +1 -1
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/task-graph.d.ts +3 -1
- package/dist/harness/task-graph.d.ts.map +1 -1
- package/dist/harness/task-graph.js +1 -1
- package/dist/harness/task-graph.js.map +1 -1
- package/dist/harness/tool.d.ts +1 -1
- package/dist/harness/tool.d.ts.map +1 -1
- package/dist/harness/tool.js +1 -1
- package/dist/harness/tool.js.map +1 -1
- package/dist/harness/transcript.d.ts +1 -1
- package/dist/harness/transcript.d.ts.map +1 -1
- package/dist/harness/transcript.js.map +1 -1
- package/dist/harness/types.d.ts +21 -4
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/usage.d.ts +2 -1
- package/dist/harness/usage.d.ts.map +1 -1
- package/dist/harness/usage.js +1 -1
- package/dist/harness/usage.js.map +1 -1
- package/dist/harness/util.d.ts +1 -1
- package/dist/harness/util.d.ts.map +1 -1
- package/dist/harness/util.js.map +1 -1
- package/dist/harness/view.d.ts +2 -1
- package/dist/harness/view.d.ts.map +1 -1
- package/dist/harness/view.js +1 -1
- package/dist/harness/view.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/session/cached-storage.d.ts +2 -1
- package/dist/session/cached-storage.d.ts.map +1 -1
- package/dist/session/cached-storage.js.map +1 -1
- package/dist/session/forks.d.ts +1 -1
- package/dist/session/forks.d.ts.map +1 -1
- package/dist/session/forks.js.map +1 -1
- package/dist/session/keys.d.ts +2 -1
- package/dist/session/keys.d.ts.map +1 -1
- package/dist/session/keys.js.map +1 -1
- package/dist/session/session.d.ts +3 -1
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +1 -1
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts +4 -3
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +3 -3
- package/dist/session/transaction.js.map +1 -1
- package/dist/session/writer.d.ts +1 -1
- package/dist/session/writer.d.ts.map +1 -1
- package/dist/session/writer.js.map +1 -1
- package/dist/storage/indexeddb.d.ts +2 -1
- package/dist/storage/indexeddb.d.ts.map +1 -1
- package/dist/storage/indexeddb.js.map +1 -1
- package/dist/storage/jsonl/index.d.ts +1 -1
- package/dist/storage/jsonl/index.d.ts.map +1 -1
- package/dist/storage/jsonl/index.js +1 -1
- package/dist/storage/jsonl/index.js.map +1 -1
- package/dist/storage/jsonl/node.d.ts +3 -3
- package/dist/storage/jsonl/node.d.ts.map +1 -1
- package/dist/storage/jsonl/node.js +2 -2
- package/dist/storage/jsonl/node.js.map +1 -1
- package/dist/storage/jsonl/storage.d.ts +32 -3
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/jsonl/storage.js +70 -19
- package/dist/storage/jsonl/storage.js.map +1 -1
- package/dist/storage/memory.d.ts +2 -1
- package/dist/storage/memory.d.ts.map +1 -1
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/sqlite/commit.d.ts +52 -0
- package/dist/storage/sqlite/commit.d.ts.map +1 -0
- package/dist/storage/sqlite/commit.js +371 -0
- package/dist/storage/sqlite/commit.js.map +1 -0
- package/dist/storage/sqlite/rows.d.ts +33 -0
- package/dist/storage/sqlite/rows.d.ts.map +1 -0
- package/dist/storage/sqlite/rows.js +53 -0
- package/dist/storage/sqlite/rows.js.map +1 -0
- package/dist/storage/sqlite/statements.d.ts +13 -0
- package/dist/storage/sqlite/statements.d.ts.map +1 -0
- package/dist/storage/sqlite/statements.js +88 -0
- package/dist/storage/sqlite/statements.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +12 -11
- package/dist/storage/sqlite/storage.d.ts.map +1 -1
- package/dist/storage/sqlite/storage.js +44 -259
- package/dist/storage/sqlite/storage.js.map +1 -1
- package/dist/storage/store/commit.d.ts +2 -2
- package/dist/storage/store/commit.d.ts.map +1 -1
- package/dist/storage/store/commit.js +1 -1
- package/dist/storage/store/commit.js.map +1 -1
- package/dist/storage/store/documents.d.ts +1 -1
- package/dist/storage/store/documents.d.ts.map +1 -1
- package/dist/storage/store/documents.js +1 -1
- package/dist/storage/store/documents.js.map +1 -1
- package/dist/storage/store/queries.d.ts +2 -2
- package/dist/storage/store/queries.d.ts.map +1 -1
- package/dist/storage/store/queries.js.map +1 -1
- package/dist/storage/store/storage.d.ts +3 -2
- package/dist/storage/store/storage.d.ts.map +1 -1
- package/dist/storage/store/storage.js +1 -1
- package/dist/storage/store/storage.js.map +1 -1
- package/dist/storage/store/tables.d.ts +31 -31
- package/dist/storage/store/tables.d.ts.map +1 -1
- package/dist/storage/store/tables.js +1 -1
- package/dist/storage/store/tables.js.map +1 -1
- package/dist/testing/commit-writes.d.ts +1 -1
- package/dist/testing/commit-writes.d.ts.map +1 -1
- package/dist/testing/commit-writes.js.map +1 -1
- package/dist/testing/env-conformance.js.map +1 -1
- package/dist/testing/storage-benchmark.js.map +1 -1
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/tool-search/tool-search.d.ts +2 -2
- package/dist/tool-search/tool-search.d.ts.map +1 -1
- package/dist/tool-search/tool-search.js +18 -6
- package/dist/tool-search/tool-search.js.map +1 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/file-mutation-queue.d.ts +1 -1
- package/dist/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/tools/file-mutation-queue.js.map +1 -1
- package/dist/tools/path-utils.d.ts +1 -1
- package/dist/tools/path-utils.d.ts.map +1 -1
- package/dist/tools/path-utils.js.map +1 -1
- package/dist/tools/read.js.map +1 -1
- package/dist/types.d.ts +6 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEpF,OAAO,EAEN,mBAAmB,EACnB,cAAc,EACd,kBAAkB,GAClB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACN,kBAAkB,EAClB,sBAAsB,EACtB,sBAAsB,GAGtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAqB1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,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,EAAE,cAAc,EAAE,CAAC;QACtC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC7C,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC;QAClG,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACrE,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,mCAAmC,CAAC,CAAC;QAC5F,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC;YACJ,MAAM,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAClC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,8FAA8F;YAC9F,+DAA+D;YAC/D,MAAM,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACjE,MAAM,KAAK,CAAC;QACb,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC;CACD,CAAC","sourcesContent":["import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport { withAbortSignal, withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport type { Models } from \"@earendil-works/pi-ai\";\nimport {\n\ttype ClientIdentity,\n\tmergeClientIdentity,\n\tPI_ATTRIBUTION,\n\twithClientIdentity,\n} from \"@earendil-works/pi-ai/utils/identity\";\nimport {\n\tcreateTypedMetrics,\n\tNOOP_TELEMETRY_CONTEXT,\n\tNOOP_TELEMETRY_METRICS,\n\ttype SpanAttributes,\n\ttype TelemetryContext,\n} from \"@earendil-works/pi-telemetry\";\nimport { ResetEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { contained, SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport { hostTimers } from \"../timers.ts\";\nimport type {\n\tCommitOptions,\n\tConversationId,\n\tConversationOwnership,\n\tConversationRecord,\n\tCursor,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tObservation,\n\tObserver,\n\tPage,\n\tReport,\n\tReportInfo,\n\tStorage,\n\tSubmissionId,\n\tTaskId,\n\tTaskRecord,\n\tTx,\n} from \"../types.ts\";\nimport { ROOT_CONVERSATION_ID } from \"../types.ts\";\nimport { AgentDoc, configure, createAgent, resolveAgent, resolveSettings } from \"./agent.ts\";\nimport { createCompaction } from \"./compaction.ts\";\nimport { readContext } from \"./context.ts\";\nimport { InboxDoc, withdrawQueuedInputs } from \"./inbox.ts\";\nimport { LIMITS_RESTARTS, LiveDoc, settleSchedulerOutcome } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { BUILTIN_TASKS } from \"./registry.ts\";\nimport { type InvocationBinding, TaskScheduler } from \"./scheduler.ts\";\nimport { Submissions } from \"./submissions.ts\";\nimport { type TaskGraph, TaskGraphView, type TaskGraphWatch } from \"./task-graph.ts\";\nimport { DURABLE_TELEMETRY_SCHEMA } from \"./telemetry.ts\";\nimport type {\n\tAgent,\n\tAgentChange,\n\tCompactionResult,\n\tContextView,\n\tConversation,\n\tConversationAbortOptions,\n\tConversationCreateOptions,\n\tConversationHandle,\n\tConversationInit,\n\tConversationWatch,\n\tHarnessInspection,\n\tHarnessOptions,\n\tHarnessSettings,\n\tHarness as HarnessType,\n\tRegistrySnapshot,\n\tSettledTask,\n\tSubmission,\n\tSubmissionDraft,\n\tToolRegistration,\n\tWake,\n} from \"./types.ts\";\nimport { addUsageState, UsageDoc, type UsageState } from \"./usage.ts\";\nimport { conversationEntries, scanAll } from \"./util.ts\";\nimport { type ConversationView, ConversationViews, type ConversationWindow } from \"./view.ts\";\n\nconst SCAN_PAGE_SIZE = 256;\n\ntype CreateTarget =\n\t| { readonly kind: \"root\" }\n\t| { readonly kind: \"independent\"; readonly ownership: ConversationOwnership }\n\t| {\n\t\t\treadonly kind: \"fork\";\n\t\t\treadonly parentId: ConversationId;\n\t\t\treadonly at: EntryId;\n\t\t\treadonly ownership: ConversationOwnership;\n\t };\n\n/** What the conveniences apply in the creating commit, after the creation hook. */\ntype CreateOptions = { readonly agent?: AgentChange; readonly init?: ConversationInit };\n\n/** Harness-private services used by Conversation handles. */\ntype ConversationHost<Tool extends ToolRegistration> = {\n\treadonly harness: HarnessImpl<Tool>;\n\treadonly storage: Storage;\n\treadonly tasks: TaskScheduler;\n\treadonly submissions: Submissions;\n\treadonly views: ConversationViews;\n\treadonly now: () => number;\n\tcreate(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation>;\n};\n\n/** Key of the Harness's internal index-size getter, for tests. */\nexport const SCHEDULER_INDEX_SIZES = Symbol.for(\"pi-durable.schedulerIndexSizes\");\n\n/** Key of the Harness's internal idle-state getter (kept contexts against a full recompute), for tests. */\nexport const SCHEDULER_IDLE_STATE = Symbol.for(\"pi-durable.schedulerIdleState\");\n\nclass ConversationImpl<Tool extends ToolRegistration> implements Conversation {\n\treadonly id: ConversationId;\n\treadonly #host: ConversationHost<Tool>;\n\n\tconstructor(id: ConversationId, host: ConversationHost<Tool>) {\n\t\tthis.id = id;\n\t\tthis.#host = host;\n\t}\n\n\tagent(context: Context): Promise<Agent> {\n\t\treturn this.#host.harness.resolveAgent(this.id, undefined, context);\n\t}\n\n\tconfigure(change: AgentChange, context: Context): Promise<void> {\n\t\treturn this.#host.harness.commitWith((tx) => configure(tx, this.id, change), context);\n\t}\n\n\tsubmit(submission: SubmissionDraft, context: Context): Promise<Submission>;\n\tsubmit(tx: Tx, submission: SubmissionDraft): Promise<SubmissionId>;\n\tsubmit(first: SubmissionDraft | Tx, second: Context | SubmissionDraft): Promise<Submission | SubmissionId> {\n\t\t// The overloads pair a draft with a context, and anything else (a transaction) with a draft.\n\t\tif (\"type\" in first) return this.#host.submissions.submit(this.id, first, second as Context);\n\t\treturn this.#host.submissions.admit(first, this.id, second as SubmissionDraft);\n\t}\n\n\tasync compact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>> {\n\t\tthis.#host.tasks.resume();\n\t\tconst input = { reason: \"manual\", ...(instructions === undefined ? {} : { instructions }) } as const;\n\t\treturn this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context);\n\t}\n\n\tasync reset(handoff: string | undefined, context: Context): Promise<void> {\n\t\tconst model =\n\t\t\thandoff === undefined\n\t\t\t\t? {}\n\t\t\t\t: { model: [{ role: \"user\", content: handoff, timestamp: this.#host.now() } as const] };\n\t\tconst entry = { kind: ResetEntry.kind, head: \"self\", ...model } as const;\n\t\tawait this.#host.submissions.submit(this.id, { type: \"write\", entry }, context);\n\t}\n\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context, options?: CommitOptions): Promise<T> {\n\t\treturn this.#host.harness.commitWith(change, context, { conversationId: this.id }, options);\n\t}\n\n\tcontext(context: Context, options?: { readonly at?: EntryId }): Promise<ContextView> {\n\t\treturn readContext(this.#host.harness, this.#host.storage, this.id, context, options?.at);\n\t}\n\n\tentries(\n\t\tquery: Omit<EntryQuery, \"conversationId\">,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst scan = conversationEntries(this.id, query);\n\t\treturn this.#host.harness.readOnLine((storage) => storage.scanEntries(scan, limit, cursor, context));\n\t}\n\n\tfork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#host.create({ kind: \"fork\", parentId: this.id, at, ownership: options.ownership }, options, context);\n\t}\n\n\tasync abort(context: Context, options?: ConversationAbortOptions): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.abortConversation(this.id, options?.background === true, context);\n\t}\n\n\tasync waitForIdle(context: Context): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.waitForIdle(this.id, context);\n\t}\n\n\twatch(context: Context, window?: ConversationWindow): Promise<ConversationWatch> {\n\t\treturn this.#host.views.watch(this.id, context, window);\n\t}\n}\n\n/** Request identity of a Harness's model requests: pi-ai's defaults with provider attribution to pi. */\nexport const DEFAULT_HARNESS_IDENTITY: ClientIdentity = { attribution: PI_ATTRIBUTION };\n\n/**\n * `HarnessOptions.models` as a function with `HarnessOptions.identity` applied. A plain `Models` is wrapped once; a\n * function's result is wrapped at each call.\n */\nfunction currentModels(models: HarnessOptions[\"models\"], identity: ClientIdentity | undefined): () => Models {\n\tconst merged = mergeClientIdentity(DEFAULT_HARNESS_IDENTITY, identity) ?? DEFAULT_HARNESS_IDENTITY;\n\tif (typeof models === \"function\") return () => withClientIdentity(models(), merged);\n\tconst wrapped = withClientIdentity(models, merged);\n\treturn () => wrapped;\n}\n\n/** `HarnessOptions.settings` as a function: plain settings, or none, are returned at every call. */\nfunction currentSettings(settings: HarnessOptions[\"settings\"]): () => HarnessSettings | undefined {\n\treturn typeof settings === \"function\" ? settings : () => settings;\n}\n\n/** Session kernel extended with conversation handles and a registry. */\nclass HarnessImpl<Tool extends ToolRegistration> extends SessionImpl implements HarnessType {\n\treadonly #options: HarnessOptions<Tool>;\n\treadonly #hostSettings: () => HarnessSettings | undefined;\n\treadonly #report: (error: unknown, info: ReportInfo, context?: Context) => void;\n\treadonly #host: ConversationHost<Tool>;\n\treadonly #tasks: TaskScheduler;\n\treadonly #submissions: Submissions;\n\treadonly #taskGraph: TaskGraphView;\n\n\tconstructor(rawStorage: Storage, options: HarnessOptions<Tool>, context: Context) {\n\t\tconst report = safeReport(options.onReport, options.telemetry ?? NOOP_TELEMETRY_CONTEXT);\n\t\tconst now = safeNow(options.now, report);\n\t\tconst hostSettings = currentSettings(options.settings);\n\t\t// Read at each use, as all settings are, but only these fields: they are read on every commit.\n\t\tsuper(\n\t\t\trawStorage,\n\t\t\tnow,\n\t\t\t() => hostSettings()?.documentRetentionMs,\n\t\t\toptions.setTimer,\n\t\t\toptions.readOnly === true,\n\t\t\t() => hostSettings()?.progress?.persistWithinMs,\n\t\t);\n\t\t// Every component reads and writes through the Session's failure guard: `rawStorage` serves only `super()`.\n\t\tconst storage = this.storage;\n\t\tthis.#options = options;\n\t\tthis.#report = report;\n\t\tthis.#hostSettings = hostSettings;\n\t\tconst settings = () => resolveSettings(hostSettings());\n\t\tthis.#tasks = new TaskScheduler({\n\t\t\ttelemetry: options.telemetry,\n\t\t\tsession: this,\n\t\t\tstorage,\n\t\t\tregistry: options.registry,\n\t\t\tmodels: currentModels(options.models, options.identity),\n\t\t\tagent: (id, snapshot, callContext) => this.resolveAgent(id, snapshot as RegistrySnapshot<Tool>, callContext),\n\t\t\tsettings,\n\t\t\tenv: (id, callContext) => this.buildEnv(id, callContext),\n\t\t\tnow,\n\t\t\tonWake: options.onWake,\n\t\t\ttimers: hostTimers(options.setTimer, (error) => report(error, { kind: \"host_error\", callback: \"setTimer\" })),\n\t\t\twriteAtClose: (writes) => this.writeAtClose(writes),\n\t\t\treport: this.#report,\n\t\t\tlimitsRestarts: (kind) => LIMITS_RESTARTS.has(kind),\n\t\t\tsettleOutcome: settleSchedulerOutcome,\n\t\t\twithdrawInputs: withdrawQueuedInputs,\n\t\t\tconversation: async (id, binding, callContext) => {\n\t\t\t\tconst record = await this.readOnLine((line) => line.conversation(id, callContext));\n\t\t\t\treturn record === undefined ? undefined : boundConversation(id, binding, this.#submissions, this.#tasks);\n\t\t\t},\n\t\t\tcontext: withoutAbortSignal(context),\n\t\t\treadOnly: options.readOnly === true,\n\t\t});\n\t\tthis.#submissions = new Submissions(this, now, settings, () => this.#tasks.resume(), options.telemetry);\n\t\tthis.#taskGraph = new TaskGraphView(this, {\n\t\t\tblocked: (record) => this.#tasks.blockedReason(record),\n\t\t\tsubscribeBlocked: (listener) => this.#tasks.subscribeBlocked(listener),\n\t\t});\n\t\tthis.#host = {\n\t\t\tharness: this,\n\t\t\tstorage,\n\t\t\ttasks: this.#tasks,\n\t\t\tsubmissions: this.#submissions,\n\t\t\tviews: new ConversationViews(this),\n\t\t\tnow,\n\t\t\tcreate: (target, createOptions, context) => this.#create(target, createOptions, context),\n\t\t};\n\t}\n\n\t/** Resolve a conversation's committed `pi.agent` against `snapshot`, or the current one, and the current settings. */\n\tasync resolveAgent(\n\t\tid: ConversationId,\n\t\tsnapshot: RegistrySnapshot<Tool> | undefined,\n\t\tcontext: Context,\n\t): Promise<Agent<Tool>> {\n\t\tconst registry = snapshot ?? this.#options.registry.snapshot();\n\t\tconst state = await this.snapshot(AgentDoc, id, context);\n\t\treturn resolveAgent(state, registry, resolveSettings(this.#hostSettings()), (error, extension) =>\n\t\t\tthis.#report(error, { kind: \"extension_error\", conversationId: id, extension }, context),\n\t\t);\n\t}\n\n\t/** Build a conversation's environment from its current `cwd`; `undefined` without an `env` option. */\n\tasync buildEnv(id: ConversationId, context: Context): Promise<ExecutionEnv | undefined> {\n\t\tconst build = this.#options.env;\n\t\tif (build === undefined) return undefined;\n\t\tconst cwd = (await this.snapshot(AgentDoc, id, context))?.cwd;\n\t\treturn build({ conversationId: id, ...(cwd === undefined ? {} : { cwd }), read: this }, context);\n\t}\n\n\t/** Reconcile surviving `running` tasks to `pending`; part of open. */\n\topenTasks(context: Context): Promise<void> {\n\t\treturn this.#tasks.open(context);\n\t}\n\n\tresume(): void {\n\t\tthis.assertUsable();\n\t\tthis.#tasks.resume();\n\t}\n\n\twake(): Wake {\n\t\tthis.assertUsable();\n\t\treturn this.#tasks.wake();\n\t}\n\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined> {\n\t\treturn this.readOnLine((storage) => storage.task(id, context)) as Promise<\n\t\t\tTaskRecord<JsonValue, JsonValue, R> | undefined\n\t\t>;\n\t}\n\n\t/** Internal, for tests: sizes of the scheduler's ownership indexes. */\n\tget [SCHEDULER_INDEX_SIZES](): TaskScheduler[\"indexSizes\"] {\n\t\treturn this.#tasks.indexSizes;\n\t}\n\n\t/** Internal, for tests: the kept contexts' idle state and its disagreements with a full recompute. */\n\tget [SCHEDULER_IDLE_STATE](): TaskScheduler[\"idleState\"] {\n\t\treturn this.#tasks.idleState;\n\t}\n\n\tinspect(context: Context): Promise<HarnessInspection> {\n\t\treturn this.readOnLine(async (storage) => {\n\t\t\tconst { scheduling, tasks } = await this.#tasks.inspect(this.#options.registry.snapshot());\n\t\t\tconst scan = (status: \"queued\" | \"placed\") =>\n\t\t\t\tscanAll((cursor) => storage.scanSubmissions({ status }, SCAN_PAGE_SIZE, cursor, context));\n\t\t\tconst submissions = [...(await scan(\"queued\")), ...(await scan(\"placed\"))].sort((a, b) => a.id - b.id);\n\t\t\treturn { scheduling, tasks, submissions };\n\t\t});\n\t}\n\n\tsubmission(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\treturn this.#submissions.get(id, context);\n\t}\n\n\tabortSubmission(\n\t\tid: SubmissionId,\n\t\tcontext: Context,\n\t\tconversationId?: ConversationId,\n\t): Promise<\"aborted\" | \"already_placed\" | \"settled\" | \"not_found\"> {\n\t\treturn this.#submissions.abort(id, context, conversationId);\n\t}\n\n\tabortTask(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\treturn this.#tasks.abort(id, context);\n\t}\n\n\tasync waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForTask(id, context) as Promise<SettledTask<R>>;\n\t}\n\n\tasync waitForIdle(context: Context): Promise<void> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForIdle(undefined, context);\n\t}\n\n\t/** Sum every conversation's committed `pi.usage`. Each document is read at its own point; totals only grow. */\n\tasync usage(context: Context): Promise<UsageState> {\n\t\tconst conversations = await this.readOnLine((storage) =>\n\t\t\tscanAll((cursor) => storage.scanConversations({}, SCAN_PAGE_SIZE, cursor, context)),\n\t\t);\n\t\tconst total = UsageDoc.definition.initial();\n\t\tfor (const { id } of conversations) {\n\t\t\tconst state = await this.snapshot(UsageDoc, id, context);\n\t\t\tif (state !== undefined) addUsageState(total, state);\n\t\t}\n\t\treturn total;\n\t}\n\n\twatchTaskGraph(context: Context): Promise<TaskGraphWatch> {\n\t\treturn this.#taskGraph.watch(context);\n\t}\n\n\tasync observeTaskGraph(observer: Observer<TaskGraph>, context: Context): Promise<Observation<TaskGraph>> {\n\t\tthis.assertUsable();\n\t\treturn this.#taskGraph.observe(observer, context);\n\t}\n\n\tasync observeConversation(\n\t\tid: ConversationId,\n\t\tobserver: Observer<ConversationView>,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<Observation<ConversationView>> {\n\t\tthis.assertUsable();\n\t\treturn this.#host.views.observe(id, observer, context, window);\n\t}\n\n\troot(\n\t\tcontext: Context,\n\t\toptions?: { readonly agent?: AgentChange; readonly init?: ConversationInit },\n\t): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"root\" }, options ?? {}, context);\n\t}\n\n\tasync conversation(id: ConversationId, context: Context): Promise<Conversation | undefined> {\n\t\tthis.assertUsable();\n\t\tconst record = await this.readOnLine((storage) => storage.conversation(id, context));\n\t\treturn record === undefined ? undefined : new ConversationImpl(record.id, this.#host);\n\t}\n\n\tcreateConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"independent\", ownership: options.ownership }, options, context);\n\t}\n\n\toverride report(error: unknown, info: ReportInfo = { kind: \"listener_error\" }, context?: Context): void {\n\t\tthis.#report(error, info, context);\n\t}\n\n\t/** The ownership memberships a commit's task changes write, from the scheduler's index. */\n\tprotected override membershipKeys(tx: Transaction): readonly string[] | Promise<readonly string[]> {\n\t\treturn this.#tasks.membershipKeys(tx);\n\t}\n\n\t/** Signal and join task invocations after the close listeners and before Storage closes; writes no task outcome. */\n\tprotected override beforeClose(): Promise<void> {\n\t\treturn this.#tasks.join();\n\t}\n\n\tasync #create(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation> {\n\t\tthis.assertUsable();\n\t\tconst id = await this.commitWith(async (tx) => {\n\t\t\tif (target.kind === \"root\" && (await tx.conversation(ROOT_CONVERSATION_ID)) !== undefined) {\n\t\t\t\treturn ROOT_CONVERSATION_ID;\n\t\t\t}\n\t\t\tconst record =\n\t\t\t\ttarget.kind === \"root\"\n\t\t\t\t\t? await tx.createRootConversation()\n\t\t\t\t\t: target.kind === \"fork\"\n\t\t\t\t\t\t? await tx.forkConversation(target.parentId, target.at, { ownership: target.ownership })\n\t\t\t\t\t\t: await tx.createConversation({ ownership: target.ownership });\n\t\t\tif (options.agent !== undefined) await configure(tx, record.id, options.agent);\n\t\t\tif (options.init !== undefined) await options.init(tx, record.id);\n\t\t\treturn record.id;\n\t\t}, context);\n\t\treturn new ConversationImpl(id, this.#host);\n\t}\n\n\t/**\n\t * The built-in creation hook, in every commit that creates or forks a conversation: empty `pi.live`, `pi.inbox`, and\n\t * `pi.usage`, a fresh `pi.provider`, the conversation's `pi.agent` (see `createAgent()`), then\n\t * `HarnessOptions.conversationCreated`.\n\t */\n\tprotected override async conversationCreated(tx: Transaction, record: ConversationRecord): Promise<void> {\n\t\tawait tx.doc(LiveDoc, record.id);\n\t\tawait tx.doc(InboxDoc, record.id);\n\t\tawait tx.doc(UsageDoc, record.id);\n\t\tawait tx.doc(ProviderDoc, record.id);\n\t\tawait createAgent(tx, record);\n\t\tawait this.#options.conversationCreated?.(tx, record);\n\t}\n}\n\n/**\n * Report to `onReport`, then count it and record its event. Never throws, since reports also come from inside Storage's\n * `adopt`: a throwing `onReport` is dropped, and so is a throwing metric or event, as reporting it would report again.\n */\nfunction safeReport(\n\tonReport: ((report: Report) => void) | undefined,\n\ttelemetry: TelemetryContext,\n): (error: unknown, info: ReportInfo, context?: Context) => void {\n\tconst reports = createTypedMetrics(telemetry.metrics ?? NOOP_TELEMETRY_METRICS, [DURABLE_TELEMETRY_SCHEMA]).counter(\n\t\t\"pi.durable.reports\",\n\t);\n\treturn (error, info, context) => {\n\t\tif (onReport !== undefined) {\n\t\t\tcontained(\n\t\t\t\t() => onReport({ ...info, error }),\n\t\t\t\t() => {},\n\t\t\t);\n\t\t}\n\t\tconst attributes: SpanAttributes = {\n\t\t\ttype: info.kind,\n\t\t};\n\t\tswitch (info.kind) {\n\t\t\tcase \"task_faulted\":\n\t\t\tcase \"task_interrupted\":\n\t\t\tcase \"task_outdated\":\n\t\t\t\tattributes.reason = info.reason;\n\t\t\t\tattributes.extension = info.extension;\n\t\t\t\tattributes[\"task.id\"] = info.task.id;\n\t\t\t\tbreak;\n\t\t\tcase \"migration_failed\":\n\t\t\tcase \"task_error\":\n\t\t\tcase \"extension_error\":\n\t\t\t\tattributes.extension = info.extension;\n\t\t\t\tattributes[\"task.id\"] = info.task?.id;\n\t\t\t\tbreak;\n\t\t\tcase \"host_error\":\n\t\t\t\tattributes[\"task.id\"] = info.task?.id;\n\t\t\t\tbreak;\n\t\t}\n\t\ttry {\n\t\t\treports.add(1, { type: info.kind });\n\t\t\tcontext?.telemetry.addEvent(\"pi.durable.report\", attributes);\n\t\t} catch {\n\t\t\t// Dropped: see above.\n\t\t}\n\t};\n}\n\n/**\n * The host clock, falling back to `Date.now` when it throws: a broken clock must not stop commits. The first throw is\n * reported; the clock is read in every task change, so later ones are not.\n */\nexport function safeNow(\n\tnow: (() => number) | undefined,\n\treport: (error: unknown, info: ReportInfo) => void,\n): () => number {\n\tif (now === undefined) return Date.now;\n\tlet reported = false;\n\treturn () => {\n\t\ttry {\n\t\t\treturn now();\n\t\t} catch (error) {\n\t\t\t// Set first: a report handler that reads the clock again must not report again.\n\t\t\tif (!reported) {\n\t\t\t\treported = true;\n\t\t\t\treport(error, { kind: \"host_error\", callback: \"now\" });\n\t\t\t}\n\t\t\treturn Date.now();\n\t\t}\n\t};\n}\n\n/**\n * Invocation-bound handle for tasks and tools. Every operation, and every operation of a submission it returns, first\n * checks the invocation and runs under its signal, so it rejects once the invocation ends; admitted work stays durable.\n */\nfunction boundConversation(\n\tid: ConversationId,\n\tbinding: InvocationBinding,\n\tsubmissions: Submissions,\n\ttasks: TaskScheduler,\n): ConversationHandle {\n\tconst bind = (context: Context): Context => withAbortSignal(binding.signal, context);\n\tconst bound = <T>(operation: (context: Context) => Promise<T>) => {\n\t\treturn async (context: Context): Promise<T> => {\n\t\t\tbinding.check();\n\t\t\treturn operation(bind(context));\n\t\t};\n\t};\n\tfunction submit(draft: SubmissionDraft, context: Context): Promise<Submission>;\n\tfunction submit(tx: Tx, draft: SubmissionDraft): Promise<SubmissionId>;\n\tasync function submit(\n\t\tfirst: SubmissionDraft | Tx,\n\t\tsecond: Context | SubmissionDraft,\n\t): Promise<Submission | SubmissionId> {\n\t\tbinding.check();\n\t\t// The overloads pair a draft with a context, and anything else (a transaction) with a draft.\n\t\tif (!(\"type\" in first)) {\n\t\t\t// The caller's commit carries its own context, so the invocation's abort is checked here.\n\t\t\tbinding.signal.throwIfAborted();\n\t\t\treturn submissions.admit(first, id, second as SubmissionDraft);\n\t\t}\n\t\tconst submission = await submissions.submit(id, first, bind(second as Context));\n\t\treturn {\n\t\t\tid: submission.id,\n\t\t\tstatus: bound((callContext) => submission.status(callContext)),\n\t\t\twait: bound((callContext) => submission.wait(callContext)),\n\t\t\tabort: bound((callContext) => submission.abort(callContext)),\n\t\t};\n\t}\n\treturn {\n\t\tid,\n\t\tsubmit,\n\t\tabort: async (context, options) => {\n\t\t\tbinding.check();\n\t\t\treturn tasks.abortConversation(id, options?.background === true, bind(context));\n\t\t},\n\t\twaitForIdle: bound((callContext) => tasks.waitForIdle(id, callContext)),\n\t};\n}\n\n/** Durable agent harness over one Session. */\nexport type Harness = HarnessType;\n\nexport const Harness = {\n\t/** Open a Harness over storage. The registry may keep changing while the Harness runs. */\n\tasync open<Tool extends ToolRegistration>(\n\t\tstorage: Storage,\n\t\toptions: HarnessOptions<Tool>,\n\t\tcontext: Context,\n\t): Promise<Harness> {\n\t\tcontext.abortSignal?.throwIfAborted();\n\t\tconst snapshot = options.registry.snapshot();\n\t\tconst missing = BUILTIN_TASKS.filter((task) => snapshot.task(task.definition.name) === undefined);\n\t\tif (missing.length > 0) {\n\t\t\tconst names = missing.map((task) => task.definition.name).join(\", \");\n\t\t\tthrow new Error(`Registry lacks built-in tasks ${names}; create it with createRegistry()`);\n\t\t}\n\t\tconst harness = new HarnessImpl(storage, options, context);\n\t\ttry {\n\t\t\tawait harness.openTasks(context);\n\t\t} catch (error) {\n\t\t\t// The caller's context may be what failed open: close without it, and rethrow the open error.\n\t\t\t// A failing Storage close fails the Session, which reports it.\n\t\t\tawait harness.close(withoutAbortSignal(context)).catch(() => {});\n\t\t\tthrow error;\n\t\t}\n\t\treturn harness;\n\t},\n};\n"]}
|
|
1
|
+
{"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAGpF,OAAO,EAEN,mBAAmB,EACnB,cAAc,EACd,kBAAkB,GAClB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACN,kBAAkB,EAClB,sBAAsB,EACtB,sBAAsB,GAGtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAqB1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,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AE,CAAC;QAC7C,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC;QAClG,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACrE,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,mCAAmC,CAAC,CAAC;QAC5F,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC;YACJ,MAAM,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAClC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,8FAA8F;YAC9F,+DAA+D;YAC/D,MAAM,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACjE,MAAM,KAAK,CAAC;QACb,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC;CACD,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord/context\";\nimport { withAbortSignal, withoutAbortSignal } from \"@earendil-works/chord/context\";\nimport type { JsonValue } from \"@earendil-works/chord/json\";\nimport type { Models } from \"@earendil-works/pi-ai\";\nimport {\n\ttype ClientIdentity,\n\tmergeClientIdentity,\n\tPI_ATTRIBUTION,\n\twithClientIdentity,\n} from \"@earendil-works/pi-ai/utils/identity\";\nimport {\n\tcreateTypedMetrics,\n\tNOOP_TELEMETRY_CONTEXT,\n\tNOOP_TELEMETRY_METRICS,\n\ttype SpanAttributes,\n\ttype TelemetryContext,\n} from \"@earendil-works/pi-telemetry\";\nimport { ResetEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { contained, SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport { hostTimers } from \"../timers.ts\";\nimport type {\n\tCommitOptions,\n\tConversationId,\n\tConversationOwnership,\n\tConversationRecord,\n\tCursor,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tObservation,\n\tObserver,\n\tPage,\n\tReport,\n\tReportInfo,\n\tStorage,\n\tSubmissionId,\n\tTaskId,\n\tTaskRecord,\n\tTx,\n} from \"../types.ts\";\nimport { ROOT_CONVERSATION_ID } from \"../types.ts\";\nimport { AgentDoc, configure, createAgent, resolveAgent, resolveSettings } from \"./agent.ts\";\nimport { createCompaction } from \"./compaction.ts\";\nimport { readContext } from \"./context.ts\";\nimport { InboxDoc, withdrawQueuedInputs } from \"./inbox.ts\";\nimport { LIMITS_RESTARTS, LiveDoc, settleSchedulerOutcome } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { BUILTIN_TASKS } from \"./registry.ts\";\nimport { type InvocationBinding, TaskScheduler } from \"./scheduler.ts\";\nimport { Submissions } from \"./submissions.ts\";\nimport { type TaskGraph, TaskGraphView, type TaskGraphWatch } from \"./task-graph.ts\";\nimport { DURABLE_TELEMETRY_SCHEMA } from \"./telemetry.ts\";\nimport type {\n\tAgent,\n\tAgentChange,\n\tCompactionResult,\n\tContextView,\n\tConversation,\n\tConversationAbortOptions,\n\tConversationCreateOptions,\n\tConversationHandle,\n\tConversationInit,\n\tConversationWatch,\n\tHarnessInspection,\n\tHarnessOptions,\n\tHarnessSettings,\n\tHarness as HarnessType,\n\tRegistrySnapshot,\n\tSettledTask,\n\tSubmission,\n\tSubmissionDraft,\n\tToolRegistration,\n\tWake,\n} from \"./types.ts\";\nimport { addUsageState, UsageDoc, type UsageState } from \"./usage.ts\";\nimport { conversationEntries, scanAll } from \"./util.ts\";\nimport { type ConversationView, ConversationViews, type ConversationWindow } from \"./view.ts\";\n\nconst SCAN_PAGE_SIZE = 256;\n\ntype CreateTarget =\n\t| { readonly kind: \"root\" }\n\t| { readonly kind: \"independent\"; readonly ownership: ConversationOwnership }\n\t| {\n\t\t\treadonly kind: \"fork\";\n\t\t\treadonly parentId: ConversationId;\n\t\t\treadonly at: EntryId;\n\t\t\treadonly ownership: ConversationOwnership;\n\t };\n\n/** What the conveniences apply in the creating commit, after the creation hook. */\ntype CreateOptions = { readonly agent?: AgentChange; readonly init?: ConversationInit };\n\n/** Harness-private services used by Conversation handles. */\ntype ConversationHost<Tool extends ToolRegistration> = {\n\treadonly harness: HarnessImpl<Tool>;\n\treadonly storage: Storage;\n\treadonly tasks: TaskScheduler;\n\treadonly submissions: Submissions;\n\treadonly views: ConversationViews;\n\treadonly now: () => number;\n\tcreate(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation>;\n};\n\n/** Key of the Harness's internal index-size getter, for tests. */\nexport const SCHEDULER_INDEX_SIZES = Symbol.for(\"pi-durable.schedulerIndexSizes\");\n\n/** Key of the Harness's internal idle-state getter (kept contexts against a full recompute), for tests. */\nexport const SCHEDULER_IDLE_STATE = Symbol.for(\"pi-durable.schedulerIdleState\");\n\nclass ConversationImpl<Tool extends ToolRegistration> implements Conversation {\n\treadonly id: ConversationId;\n\treadonly #host: ConversationHost<Tool>;\n\n\tconstructor(id: ConversationId, host: ConversationHost<Tool>) {\n\t\tthis.id = id;\n\t\tthis.#host = host;\n\t}\n\n\tagent(context: Context): Promise<Agent> {\n\t\treturn this.#host.harness.resolveAgent(this.id, undefined, context);\n\t}\n\n\tconfigure(change: AgentChange, context: Context): Promise<void> {\n\t\treturn this.#host.harness.commitWith((tx) => configure(tx, this.id, change), context);\n\t}\n\n\tsubmit(submission: SubmissionDraft, context: Context): Promise<Submission>;\n\tsubmit(tx: Tx, submission: SubmissionDraft): Promise<SubmissionId>;\n\tsubmit(first: SubmissionDraft | Tx, second: Context | SubmissionDraft): Promise<Submission | SubmissionId> {\n\t\t// The overloads pair a draft with a context, and anything else (a transaction) with a draft.\n\t\tif (\"type\" in first) return this.#host.submissions.submit(this.id, first, second as Context);\n\t\treturn this.#host.submissions.admit(first, this.id, second as SubmissionDraft);\n\t}\n\n\tasync compact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>> {\n\t\tthis.#host.tasks.resume();\n\t\tconst input = { reason: \"manual\", ...(instructions === undefined ? {} : { instructions }) } as const;\n\t\treturn this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context);\n\t}\n\n\tasync reset(handoff: string | undefined, context: Context): Promise<void> {\n\t\tconst model =\n\t\t\thandoff === undefined\n\t\t\t\t? {}\n\t\t\t\t: { model: [{ role: \"user\", content: handoff, timestamp: this.#host.now() } as const] };\n\t\tconst entry = { kind: ResetEntry.kind, head: \"self\", ...model } as const;\n\t\tawait this.#host.submissions.submit(this.id, { type: \"write\", entry }, context);\n\t}\n\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context, options?: CommitOptions): Promise<T> {\n\t\treturn this.#host.harness.commitWith(change, context, { conversationId: this.id }, options);\n\t}\n\n\tcontext(context: Context, options?: { readonly at?: EntryId }): Promise<ContextView> {\n\t\treturn readContext(this.#host.harness, this.#host.storage, this.id, context, options?.at);\n\t}\n\n\tentries(\n\t\tquery: Omit<EntryQuery, \"conversationId\">,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst scan = conversationEntries(this.id, query);\n\t\treturn this.#host.harness.readOnLine((storage) => storage.scanEntries(scan, limit, cursor, context));\n\t}\n\n\tfork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#host.create({ kind: \"fork\", parentId: this.id, at, ownership: options.ownership }, options, context);\n\t}\n\n\tasync abort(context: Context, options?: ConversationAbortOptions): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.abortConversation(this.id, options?.background === true, context);\n\t}\n\n\tasync waitForIdle(context: Context): Promise<void> {\n\t\tthis.#host.tasks.resume();\n\t\treturn this.#host.tasks.waitForIdle(this.id, context);\n\t}\n\n\twatch(context: Context, window?: ConversationWindow): Promise<ConversationWatch> {\n\t\treturn this.#host.views.watch(this.id, context, window);\n\t}\n}\n\n/** Request identity of a Harness's model requests: pi-ai's defaults with provider attribution to pi. */\nexport const DEFAULT_HARNESS_IDENTITY: ClientIdentity = { attribution: PI_ATTRIBUTION };\n\n/**\n * `HarnessOptions.models` as a function with `HarnessOptions.identity` applied. A plain `Models` is wrapped once; a\n * function's result is wrapped at each call.\n */\nfunction currentModels(models: HarnessOptions[\"models\"], identity: ClientIdentity | undefined): () => Models {\n\tconst merged = mergeClientIdentity(DEFAULT_HARNESS_IDENTITY, identity) ?? DEFAULT_HARNESS_IDENTITY;\n\tif (typeof models === \"function\") return () => withClientIdentity(models(), merged);\n\tconst wrapped = withClientIdentity(models, merged);\n\treturn () => wrapped;\n}\n\n/** `HarnessOptions.settings` as a function: plain settings, or none, are returned at every call. */\nfunction currentSettings(settings: HarnessOptions[\"settings\"]): () => HarnessSettings | undefined {\n\treturn typeof settings === \"function\" ? settings : () => settings;\n}\n\n/** Session kernel extended with conversation handles and a registry. */\nclass HarnessImpl<Tool extends ToolRegistration> extends SessionImpl implements HarnessType {\n\treadonly #options: HarnessOptions<Tool>;\n\treadonly #hostSettings: () => HarnessSettings | undefined;\n\treadonly #report: (error: unknown, info: ReportInfo, context?: Context) => void;\n\treadonly #host: ConversationHost<Tool>;\n\treadonly #tasks: TaskScheduler;\n\treadonly #submissions: Submissions;\n\treadonly #taskGraph: TaskGraphView;\n\n\tconstructor(rawStorage: Storage, options: HarnessOptions<Tool>, context: Context) {\n\t\tconst report = safeReport(options.onReport, options.telemetry ?? NOOP_TELEMETRY_CONTEXT);\n\t\tconst now = safeNow(options.now, report);\n\t\tconst hostSettings = currentSettings(options.settings);\n\t\t// Read at each use, as all settings are, but only these fields: they are read on every commit.\n\t\tsuper(\n\t\t\trawStorage,\n\t\t\tnow,\n\t\t\t() => hostSettings()?.documentRetentionMs,\n\t\t\toptions.setTimer,\n\t\t\toptions.readOnly === true,\n\t\t\t() => hostSettings()?.progress?.persistWithinMs,\n\t\t);\n\t\t// Every component reads and writes through the Session's failure guard: `rawStorage` serves only `super()`.\n\t\tconst storage = this.storage;\n\t\tthis.#options = options;\n\t\tthis.#report = report;\n\t\tthis.#hostSettings = hostSettings;\n\t\tconst settings = () => resolveSettings(hostSettings());\n\t\tthis.#tasks = new TaskScheduler({\n\t\t\ttelemetry: options.telemetry,\n\t\t\tsession: this,\n\t\t\tstorage,\n\t\t\tregistry: options.registry,\n\t\t\tmodels: currentModels(options.models, options.identity),\n\t\t\tagent: (id, snapshot, callContext) => this.resolveAgent(id, snapshot as RegistrySnapshot<Tool>, callContext),\n\t\t\tsettings,\n\t\t\tenv: (id, callContext) => this.buildEnv(id, callContext),\n\t\t\tnow,\n\t\t\tonWake: options.onWake,\n\t\t\ttimers: hostTimers(options.setTimer, (error) => report(error, { kind: \"host_error\", callback: \"setTimer\" })),\n\t\t\twriteAtClose: (writes) => this.writeAtClose(writes),\n\t\t\treport: this.#report,\n\t\t\tlimitsRestarts: (kind) => LIMITS_RESTARTS.has(kind),\n\t\t\tsettleOutcome: settleSchedulerOutcome,\n\t\t\twithdrawInputs: withdrawQueuedInputs,\n\t\t\tconversation: async (id, binding, callContext) => {\n\t\t\t\tconst record = await this.readOnLine((line) => line.conversation(id, callContext));\n\t\t\t\treturn record === undefined ? undefined : boundConversation(id, binding, this.#submissions, this.#tasks);\n\t\t\t},\n\t\t\tcontext: withoutAbortSignal(context),\n\t\t\treadOnly: options.readOnly === true,\n\t\t});\n\t\tthis.#submissions = new Submissions(this, now, settings, () => this.#tasks.resume(), options.telemetry);\n\t\tthis.#taskGraph = new TaskGraphView(this, {\n\t\t\tblocked: (record) => this.#tasks.blockedReason(record),\n\t\t\tsubscribeBlocked: (listener) => this.#tasks.subscribeBlocked(listener),\n\t\t});\n\t\tthis.#host = {\n\t\t\tharness: this,\n\t\t\tstorage,\n\t\t\ttasks: this.#tasks,\n\t\t\tsubmissions: this.#submissions,\n\t\t\tviews: new ConversationViews(this),\n\t\t\tnow,\n\t\t\tcreate: (target, createOptions, context) => this.#create(target, createOptions, context),\n\t\t};\n\t}\n\n\t/** Resolve a conversation's committed `pi.agent` against `snapshot`, or the current one, and the current settings. */\n\tasync resolveAgent(\n\t\tid: ConversationId,\n\t\tsnapshot: RegistrySnapshot<Tool> | undefined,\n\t\tcontext: Context,\n\t): Promise<Agent<Tool>> {\n\t\tconst registry = snapshot ?? this.#options.registry.snapshot();\n\t\tconst state = await this.snapshot(AgentDoc, id, context);\n\t\treturn resolveAgent(state, registry, resolveSettings(this.#hostSettings()), (error, extension) =>\n\t\t\tthis.#report(error, { kind: \"extension_error\", conversationId: id, extension }, context),\n\t\t);\n\t}\n\n\t/** Build a conversation's environment from its current `cwd`; `undefined` without an `env` option. */\n\tasync buildEnv(id: ConversationId, context: Context): Promise<ExecutionEnv | undefined> {\n\t\tconst build = this.#options.env;\n\t\tif (build === undefined) return undefined;\n\t\tconst cwd = (await this.snapshot(AgentDoc, id, context))?.cwd;\n\t\treturn build({ conversationId: id, ...(cwd === undefined ? {} : { cwd }), read: this }, context);\n\t}\n\n\t/** Reconcile surviving `running` tasks to `pending`; part of open. */\n\topenTasks(context: Context): Promise<void> {\n\t\treturn this.#tasks.open(context);\n\t}\n\n\tresume(): void {\n\t\tthis.assertUsable();\n\t\tthis.#tasks.resume();\n\t}\n\n\twake(): Wake {\n\t\tthis.assertUsable();\n\t\treturn this.#tasks.wake();\n\t}\n\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined> {\n\t\treturn this.readOnLine((storage) => storage.task(id, context)) as Promise<\n\t\t\tTaskRecord<JsonValue, JsonValue, R> | undefined\n\t\t>;\n\t}\n\n\t/** Internal, for tests: sizes of the scheduler's ownership indexes. */\n\tget [SCHEDULER_INDEX_SIZES](): TaskScheduler[\"indexSizes\"] {\n\t\treturn this.#tasks.indexSizes;\n\t}\n\n\t/** Internal, for tests: the kept contexts' idle state and its disagreements with a full recompute. */\n\tget [SCHEDULER_IDLE_STATE](): TaskScheduler[\"idleState\"] {\n\t\treturn this.#tasks.idleState;\n\t}\n\n\tinspect(context: Context): Promise<HarnessInspection> {\n\t\treturn this.readOnLine(async (storage) => {\n\t\t\tconst { scheduling, tasks } = await this.#tasks.inspect(this.#options.registry.snapshot());\n\t\t\tconst scan = (status: \"queued\" | \"placed\") =>\n\t\t\t\tscanAll((cursor) => storage.scanSubmissions({ status }, SCAN_PAGE_SIZE, cursor, context));\n\t\t\tconst submissions = [...(await scan(\"queued\")), ...(await scan(\"placed\"))].sort((a, b) => a.id - b.id);\n\t\t\treturn { scheduling, tasks, submissions };\n\t\t});\n\t}\n\n\tsubmission(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\treturn this.#submissions.get(id, context);\n\t}\n\n\tabortSubmission(\n\t\tid: SubmissionId,\n\t\tcontext: Context,\n\t\tconversationId?: ConversationId,\n\t): Promise<\"aborted\" | \"already_placed\" | \"settled\" | \"not_found\"> {\n\t\treturn this.#submissions.abort(id, context, conversationId);\n\t}\n\n\tabortTask(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\treturn this.#tasks.abort(id, context);\n\t}\n\n\tasync waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForTask(id, context) as Promise<SettledTask<R>>;\n\t}\n\n\tasync waitForIdle(context: Context): Promise<void> {\n\t\tthis.#tasks.resume();\n\t\treturn this.#tasks.waitForIdle(undefined, context);\n\t}\n\n\t/** Sum every conversation's committed `pi.usage`. Each document is read at its own point; totals only grow. */\n\tasync usage(context: Context): Promise<UsageState> {\n\t\tconst conversations = await this.readOnLine((storage) =>\n\t\t\tscanAll((cursor) => storage.scanConversations({}, SCAN_PAGE_SIZE, cursor, context)),\n\t\t);\n\t\tconst total = UsageDoc.definition.initial();\n\t\tfor (const { id } of conversations) {\n\t\t\tconst state = await this.snapshot(UsageDoc, id, context);\n\t\t\tif (state !== undefined) addUsageState(total, state);\n\t\t}\n\t\treturn total;\n\t}\n\n\twatchTaskGraph(context: Context): Promise<TaskGraphWatch> {\n\t\treturn this.#taskGraph.watch(context);\n\t}\n\n\tasync observeTaskGraph(observer: Observer<TaskGraph>, context: Context): Promise<Observation<TaskGraph>> {\n\t\tthis.assertUsable();\n\t\treturn this.#taskGraph.observe(observer, context);\n\t}\n\n\tasync observeConversation(\n\t\tid: ConversationId,\n\t\tobserver: Observer<ConversationView>,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<Observation<ConversationView>> {\n\t\tthis.assertUsable();\n\t\treturn this.#host.views.observe(id, observer, context, window);\n\t}\n\n\troot(\n\t\tcontext: Context,\n\t\toptions?: { readonly agent?: AgentChange; readonly init?: ConversationInit },\n\t): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"root\" }, options ?? {}, context);\n\t}\n\n\tasync conversation(id: ConversationId, context: Context): Promise<Conversation | undefined> {\n\t\tthis.assertUsable();\n\t\tconst record = await this.readOnLine((storage) => storage.conversation(id, context));\n\t\treturn record === undefined ? undefined : new ConversationImpl(record.id, this.#host);\n\t}\n\n\tcreateConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation> {\n\t\treturn this.#create({ kind: \"independent\", ownership: options.ownership }, options, context);\n\t}\n\n\toverride report(error: unknown, info: ReportInfo = { kind: \"listener_error\" }, context?: Context): void {\n\t\tthis.#report(error, info, context);\n\t}\n\n\t/** The ownership memberships a commit's task changes write, from the scheduler's index. */\n\tprotected override membershipKeys(tx: Transaction): readonly string[] | Promise<readonly string[]> {\n\t\treturn this.#tasks.membershipKeys(tx);\n\t}\n\n\t/** Signal and join task invocations after the close listeners and before Storage closes; writes no task outcome. */\n\tprotected override beforeClose(): Promise<void> {\n\t\treturn this.#tasks.join();\n\t}\n\n\tasync #create(target: CreateTarget, options: CreateOptions, context: Context): Promise<Conversation> {\n\t\tthis.assertUsable();\n\t\tconst id = await this.commitWith(async (tx) => {\n\t\t\tif (target.kind === \"root\" && (await tx.conversation(ROOT_CONVERSATION_ID)) !== undefined) {\n\t\t\t\treturn ROOT_CONVERSATION_ID;\n\t\t\t}\n\t\t\tconst record =\n\t\t\t\ttarget.kind === \"root\"\n\t\t\t\t\t? await tx.createRootConversation()\n\t\t\t\t\t: target.kind === \"fork\"\n\t\t\t\t\t\t? await tx.forkConversation(target.parentId, target.at, { ownership: target.ownership })\n\t\t\t\t\t\t: await tx.createConversation({ ownership: target.ownership });\n\t\t\tif (options.agent !== undefined) await configure(tx, record.id, options.agent);\n\t\t\tif (options.init !== undefined) await options.init(tx, record.id);\n\t\t\treturn record.id;\n\t\t}, context);\n\t\treturn new ConversationImpl(id, this.#host);\n\t}\n\n\t/**\n\t * The built-in creation hook, in every commit that creates or forks a conversation: empty `pi.live`, `pi.inbox`, and\n\t * `pi.usage`, a fresh `pi.provider`, the conversation's `pi.agent` (see `createAgent()`), then\n\t * `HarnessOptions.conversationCreated`.\n\t */\n\tprotected override async conversationCreated(tx: Transaction, record: ConversationRecord): Promise<void> {\n\t\tawait tx.doc(LiveDoc, record.id);\n\t\tawait tx.doc(InboxDoc, record.id);\n\t\tawait tx.doc(UsageDoc, record.id);\n\t\tawait tx.doc(ProviderDoc, record.id);\n\t\tawait createAgent(tx, record);\n\t\tawait this.#options.conversationCreated?.(tx, record);\n\t}\n}\n\n/**\n * Report to `onReport`, then count it and record its event. Never throws, since reports also come from inside Storage's\n * `adopt`: a throwing `onReport` is dropped, and so is a throwing metric or event, as reporting it would report again.\n */\nfunction safeReport(\n\tonReport: ((report: Report) => void) | undefined,\n\ttelemetry: TelemetryContext,\n): (error: unknown, info: ReportInfo, context?: Context) => void {\n\tconst reports = createTypedMetrics(telemetry.metrics ?? NOOP_TELEMETRY_METRICS, [DURABLE_TELEMETRY_SCHEMA]).counter(\n\t\t\"pi.durable.reports\",\n\t);\n\treturn (error, info, context) => {\n\t\tif (onReport !== undefined) {\n\t\t\tcontained(\n\t\t\t\t() => onReport({ ...info, error }),\n\t\t\t\t() => {},\n\t\t\t);\n\t\t}\n\t\tconst attributes: SpanAttributes = {\n\t\t\ttype: info.kind,\n\t\t};\n\t\tswitch (info.kind) {\n\t\t\tcase \"task_faulted\":\n\t\t\tcase \"task_interrupted\":\n\t\t\tcase \"task_outdated\":\n\t\t\t\tattributes.reason = info.reason;\n\t\t\t\tattributes.extension = info.extension;\n\t\t\t\tattributes[\"task.id\"] = info.task.id;\n\t\t\t\tbreak;\n\t\t\tcase \"migration_failed\":\n\t\t\tcase \"task_error\":\n\t\t\tcase \"extension_error\":\n\t\t\t\tattributes.extension = info.extension;\n\t\t\t\tattributes[\"task.id\"] = info.task?.id;\n\t\t\t\tbreak;\n\t\t\tcase \"host_error\":\n\t\t\t\tattributes[\"task.id\"] = info.task?.id;\n\t\t\t\tbreak;\n\t\t}\n\t\ttry {\n\t\t\treports.add(1, { type: info.kind });\n\t\t\tcontext?.telemetry.addEvent(\"pi.durable.report\", attributes);\n\t\t} catch {\n\t\t\t// Dropped: see above.\n\t\t}\n\t};\n}\n\n/**\n * The host clock, falling back to `Date.now` when it throws: a broken clock must not stop commits. The first throw is\n * reported; the clock is read in every task change, so later ones are not.\n */\nexport function safeNow(\n\tnow: (() => number) | undefined,\n\treport: (error: unknown, info: ReportInfo) => void,\n): () => number {\n\tif (now === undefined) return Date.now;\n\tlet reported = false;\n\treturn () => {\n\t\ttry {\n\t\t\treturn now();\n\t\t} catch (error) {\n\t\t\t// Set first: a report handler that reads the clock again must not report again.\n\t\t\tif (!reported) {\n\t\t\t\treported = true;\n\t\t\t\treport(error, { kind: \"host_error\", callback: \"now\" });\n\t\t\t}\n\t\t\treturn Date.now();\n\t\t}\n\t};\n}\n\n/**\n * Invocation-bound handle for tasks and tools. Every operation, and every operation of a submission it returns, first\n * checks the invocation and runs under its signal, so it rejects once the invocation ends; admitted work stays durable.\n */\nfunction boundConversation(\n\tid: ConversationId,\n\tbinding: InvocationBinding,\n\tsubmissions: Submissions,\n\ttasks: TaskScheduler,\n): ConversationHandle {\n\tconst bind = (context: Context): Context => withAbortSignal(binding.signal, context);\n\tconst bound = <T>(operation: (context: Context) => Promise<T>) => {\n\t\treturn async (context: Context): Promise<T> => {\n\t\t\tbinding.check();\n\t\t\treturn operation(bind(context));\n\t\t};\n\t};\n\tfunction submit(draft: SubmissionDraft, context: Context): Promise<Submission>;\n\tfunction submit(tx: Tx, draft: SubmissionDraft): Promise<SubmissionId>;\n\tasync function submit(\n\t\tfirst: SubmissionDraft | Tx,\n\t\tsecond: Context | SubmissionDraft,\n\t): Promise<Submission | SubmissionId> {\n\t\tbinding.check();\n\t\t// The overloads pair a draft with a context, and anything else (a transaction) with a draft.\n\t\tif (!(\"type\" in first)) {\n\t\t\t// The caller's commit carries its own context, so the invocation's abort is checked here.\n\t\t\tbinding.signal.throwIfAborted();\n\t\t\treturn submissions.admit(first, id, second as SubmissionDraft);\n\t\t}\n\t\tconst submission = await submissions.submit(id, first, bind(second as Context));\n\t\treturn {\n\t\t\tid: submission.id,\n\t\t\tstatus: bound((callContext) => submission.status(callContext)),\n\t\t\twait: bound((callContext) => submission.wait(callContext)),\n\t\t\tabort: bound((callContext) => submission.abort(callContext)),\n\t\t};\n\t}\n\treturn {\n\t\tid,\n\t\tsubmit,\n\t\tabort: async (context, options) => {\n\t\t\tbinding.check();\n\t\t\treturn tasks.abortConversation(id, options?.background === true, bind(context));\n\t\t},\n\t\twaitForIdle: bound((callContext) => tasks.waitForIdle(id, callContext)),\n\t};\n}\n\n/** Durable agent harness over one Session. */\nexport type Harness = HarnessType;\n\nexport const Harness = {\n\t/** Open a Harness over storage. The registry may keep changing while the Harness runs. */\n\tasync open<Tool extends ToolRegistration>(\n\t\tstorage: Storage,\n\t\toptions: HarnessOptions<Tool>,\n\t\tcontext: Context,\n\t): Promise<Harness> {\n\t\tcontext.abortSignal?.throwIfAborted();\n\t\tconst snapshot = options.registry.snapshot();\n\t\tconst missing = BUILTIN_TASKS.filter((task) => snapshot.task(task.definition.name) === undefined);\n\t\tif (missing.length > 0) {\n\t\t\tconst names = missing.map((task) => task.definition.name).join(\", \");\n\t\t\tthrow new Error(`Registry lacks built-in tasks ${names}; create it with createRegistry()`);\n\t\t}\n\t\tconst harness = new HarnessImpl(storage, options, context);\n\t\ttry {\n\t\t\tawait harness.openTasks(context);\n\t\t} catch (error) {\n\t\t\t// The caller's context may be what failed open: close without it, and rethrow the open error.\n\t\t\t// A failing Storage close fails the Session, which reports it.\n\t\t\tawait harness.close(withoutAbortSignal(context)).catch(() => {});\n\t\t\tthrow error;\n\t\t}\n\t\treturn harness;\n\t},\n};\n"]}
|
package/dist/harness/inbox.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Draft } from "@earendil-works/chord/delta";
|
|
2
|
+
import { type JsonRepresentation } from "@earendil-works/chord/json";
|
|
2
3
|
import type { ConversationId, EntryDraft, EntryId, EntryRecord, JsonObject, SubmissionId, Tx } from "../types.ts";
|
|
3
4
|
import type { InputEntry, QueueMode, Settings, UserInput } from "./types.ts";
|
|
4
5
|
/** A queued submission: user input for a run, with the entry it is placed as when not `pi.user`, or an entry write. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/harness/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/harness/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAY,KAAK,kBAAkB,EAAE,MAAM,4BAA4B,C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K,EAAE,EAAE,CAAC;QACxD,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAE,CAAC;QAC3B,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO;YAAE,SAAS;QACpC,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;QAC/D,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACxB,CAAC;AACF,CAAC","sourcesContent":["import { copyJson, type Draft, type JsonRepresentation } from \"@earendil-works/chord\";\nimport { defineDoc } from \"../documents.ts\";\nimport { UserEntry } from \"../entries.ts\";\nimport type { ConversationId, EntryDraft, EntryId, EntryRecord, JsonObject, SubmissionId, Tx } from \"../types.ts\";\nimport type { InputEntry, QueueMode, Settings, UserInput } from \"./types.ts\";\n\n/** A queued submission: user input for a run, with the entry it is placed as when not `pi.user`, or an entry write. */\nexport type InboxItem =\n\t| {\n\t\t\tid: SubmissionId;\n\t\t\tmode: \"steer\" | \"followUp\";\n\t\t\tcontent: JsonRepresentation<UserInput>;\n\t\t\tentry?: JsonRepresentation<InputEntry>;\n\t }\n\t/** `entry` is an `EntryDraft`, stored as plain JSON. */\n\t| { id: SubmissionId; mode: \"write\"; entry: JsonObject };\n\n/** Built-in queue of one conversation's submissions waiting for a boundary, in ID order. */\nexport type InboxState = { items: InboxItem[] };\n\nexport const InboxDoc = defineDoc<InboxState>({\n\tkind: \"pi.inbox\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ items: [] }),\n\tcheckpointWhen: (value) => value.items.length === 0,\n});\n\n/** The settings a boundary reads, on the Session line. */\nexport type QueueModes = Pick<Settings, \"steeringMode\" | \"followUpMode\">;\n\n/** What a boundary reads before the commit's first table write, and the newest head it has seen so far. */\nexport type Boundary = {\n\treadonly conversationId: ConversationId;\n\treadonly inbox: Draft<InboxState>;\n\treadonly steeringMode: QueueMode;\n\treadonly followUpMode: QueueMode;\n\t/** Start of the active range, the newest head marker's `head`; advanced by heads written in this commit. */\n\thead: EntryId | undefined;\n};\n\n/**\n * Selected user items, in ID order, the first entry the boundary placed, a write's or a user item's (a run it starts\n * begins there, `LiveRun.first`), and whether a `head: \"self\"` write (a reset) was placed.\n */\nexport type BoundaryResult = {\n\treadonly users: SubmissionId[];\n\treadonly first: EntryId | undefined;\n\treadonly reset: boolean;\n};\n\n/**\n * Read what a boundary needs. Table reads must precede the commit's first table write, so callers prepare the\n * boundary at the start of their commit.\n */\nexport async function prepareBoundary(tx: Tx, conversationId: ConversationId, modes: QueueModes): Promise<Boundary> {\n\tconst head = (await tx.latestHeadMarker(conversationId))?.head;\n\tconst inbox = await tx.doc(InboxDoc, conversationId);\n\treturn {\n\t\tconversationId,\n\t\tinbox,\n\t\tsteeringMode: modes.steeringMode,\n\t\tfollowUpMode: modes.followUpMode,\n\t\thead,\n\t};\n}\n\n/**\n * Place the queued items a boundary selects (spec §6): every write, the first or all steers, and at `final` the first\n * or all follow-ups. A selected reset turns a `postTools` boundary into `final`. Writes are placed first and user\n * items after them, each in ID order, so user items queued before a reset run in the new context. A write whose head\n * targets an entry before the active range, including a range started earlier in this commit, is stale. Selected and\n * stale items are removed positionally.\n */\nexport async function applyBoundary(\n\ttx: Tx,\n\tboundary: Boundary,\n\tat: \"postTools\" | \"final\",\n\tnow: number,\n): Promise<BoundaryResult> {\n\tconst { conversationId, inbox } = boundary;\n\tconst items = inbox.items;\n\tconst reset = hasQueuedReset(items);\n\tconst final = at === \"final\" || reset;\n\tconst pick = (mode: \"steer\" | \"followUp\", queueMode: QueueMode): number[] => {\n\t\tconst indexes = items.flatMap((item, index) => (item.mode === mode ? [index] : []));\n\t\treturn queueMode === \"all\" ? indexes : indexes.slice(0, 1);\n\t};\n\tconst writes = items.flatMap((item, index) => (item.mode === \"write\" ? [index] : []));\n\tconst users = [...pick(\"steer\", boundary.steeringMode), ...(final ? pick(\"followUp\", boundary.followUpMode) : [])];\n\tusers.sort((a, b) => a - b);\n\n\t// `appendEntry()` copies the drafts' values; the items are removed only afterwards.\n\tlet first: EntryId | undefined;\n\tfor (const index of writes) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"write\" }>>;\n\t\tconst draft = item.entry as unknown as EntryDraft;\n\t\tif (isStale(boundary, draft)) {\n\t\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason: \"stale\" });\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft);\n\t\tif (draft.head !== undefined) boundary.head = draft.head === \"self\" ? entry.id : draft.head;\n\t\ttx.placeSubmission(item.id, entry.id);\n\t\tfirst ??= entry.id;\n\t}\n\tconst placed: SubmissionId[] = [];\n\tfor (const index of users) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"steer\" | \"followUp\" }>>;\n\t\tconst entry = await appendInput(tx, conversationId, item.content as UserInput, item.entry as InputEntry, now);\n\t\ttx.placeSubmission(item.id, entry.id);\n\t\tplaced.push(item.id);\n\t\tfirst ??= entry.id;\n\t}\n\tconst removed = [...writes, ...users].sort((a, b) => b - a);\n\tfor (const index of removed) items.splice(index, 1);\n\treturn { users: placed, first, reset };\n}\n\n/** Append the entry an input is placed as: `entry`'s kind and data, or `pi.user`, with the user message of `content`. */\nexport function appendInput(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcontent: UserInput,\n\tentry: InputEntry | undefined,\n\tnow: number,\n): Promise<EntryRecord> {\n\tconst message = { role: \"user\", content, timestamp: now } as const;\n\tif (entry === undefined) return tx.appendEntry(UserEntry, conversationId, { model: [message] });\n\treturn tx.appendEntry(conversationId, { ...pickInputEntry(entry), model: [message] });\n}\n\n/** The kind and data of an input's entry as strict JSON, without other fields an untyped caller might pass. */\nexport function pickInputEntry({ kind, data }: InputEntry): JsonRepresentation<InputEntry> {\n\tconst picked = data === undefined ? { kind } : { kind, data };\n\treturn copyJson(picked, { omitUndefinedProperties: true }) as JsonRepresentation<InputEntry>;\n}\n\n/**\n * Whether a write is display-only: it has no `model`, `head`, or `edits` (present counts, even if empty), so it changes\n * nothing the model sees and needs no boundary.\n */\nexport function isDisplayOnly(entry: EntryDraft): boolean {\n\treturn entry.model === undefined && entry.head === undefined && entry.edits === undefined;\n}\n\n/** Whether a reset (`head: \"self\"` write) is queued; entries appended before it leave the active range when it lands. */\nexport function hasQueuedReset(items: readonly InboxItem[]): boolean {\n\treturn items.some((item) => item.mode === \"write\" && item.entry.head === \"self\");\n}\n\n/** Whether a head write targets an entry before the active range, so placing it would bring back cut history. */\nexport function isStale(boundary: Boundary, entry: EntryDraft): boolean {\n\treturn typeof entry.head === \"number\" && boundary.head !== undefined && entry.head < boundary.head;\n}\n\n/** Remove a withdrawn submission's item; the caller settles the submission. */\nexport async function removeInboxItem(tx: Tx, conversationId: ConversationId, id: SubmissionId): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tconst index = items.findIndex((item) => item.id === id);\n\tif (index >= 0) items.splice(index, 1);\n}\n\n/**\n * Withdraw every queued input of a conversation, as `Conversation.abort()` and abort cascades do: each settles\n * `unanswered` with `reason` (default `aborted`) and leaves the inbox; queued writes stay for later placement.\n */\nexport async function withdrawQueuedInputs(tx: Tx, conversationId: ConversationId, reason = \"aborted\"): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tfor (let index = items.length - 1; index >= 0; index--) {\n\t\tconst item = items[index]!;\n\t\tif (item.mode === \"write\") continue;\n\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason });\n\t\titems.splice(index, 1);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"inbox.js","sourceRoot":"","sources":["../../src/harness/inbox.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAA2B,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAA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ACF,CAAC","sourcesContent":["import type { Draft } from \"@earendil-works/chord/delta\";\nimport { copyJson, type JsonRepresentation } from \"@earendil-works/chord/json\";\nimport { defineDoc } from \"../documents.ts\";\nimport { UserEntry } from \"../entries.ts\";\nimport type { ConversationId, EntryDraft, EntryId, EntryRecord, JsonObject, SubmissionId, Tx } from \"../types.ts\";\nimport type { InputEntry, QueueMode, Settings, UserInput } from \"./types.ts\";\n\n/** A queued submission: user input for a run, with the entry it is placed as when not `pi.user`, or an entry write. */\nexport type InboxItem =\n\t| {\n\t\t\tid: SubmissionId;\n\t\t\tmode: \"steer\" | \"followUp\";\n\t\t\tcontent: JsonRepresentation<UserInput>;\n\t\t\tentry?: JsonRepresentation<InputEntry>;\n\t }\n\t/** `entry` is an `EntryDraft`, stored as plain JSON. */\n\t| { id: SubmissionId; mode: \"write\"; entry: JsonObject };\n\n/** Built-in queue of one conversation's submissions waiting for a boundary, in ID order. */\nexport type InboxState = { items: InboxItem[] };\n\nexport const InboxDoc = defineDoc<InboxState>({\n\tkind: \"pi.inbox\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ items: [] }),\n\tcheckpointWhen: (value) => value.items.length === 0,\n});\n\n/** The settings a boundary reads, on the Session line. */\nexport type QueueModes = Pick<Settings, \"steeringMode\" | \"followUpMode\">;\n\n/** What a boundary reads before the commit's first table write, and the newest head it has seen so far. */\nexport type Boundary = {\n\treadonly conversationId: ConversationId;\n\treadonly inbox: Draft<InboxState>;\n\treadonly steeringMode: QueueMode;\n\treadonly followUpMode: QueueMode;\n\t/** Start of the active range, the newest head marker's `head`; advanced by heads written in this commit. */\n\thead: EntryId | undefined;\n};\n\n/**\n * Selected user items, in ID order, the first entry the boundary placed, a write's or a user item's (a run it starts\n * begins there, `LiveRun.first`), and whether a `head: \"self\"` write (a reset) was placed.\n */\nexport type BoundaryResult = {\n\treadonly users: SubmissionId[];\n\treadonly first: EntryId | undefined;\n\treadonly reset: boolean;\n};\n\n/**\n * Read what a boundary needs. Table reads must precede the commit's first table write, so callers prepare the\n * boundary at the start of their commit.\n */\nexport async function prepareBoundary(tx: Tx, conversationId: ConversationId, modes: QueueModes): Promise<Boundary> {\n\tconst head = (await tx.latestHeadMarker(conversationId))?.head;\n\tconst inbox = await tx.doc(InboxDoc, conversationId);\n\treturn {\n\t\tconversationId,\n\t\tinbox,\n\t\tsteeringMode: modes.steeringMode,\n\t\tfollowUpMode: modes.followUpMode,\n\t\thead,\n\t};\n}\n\n/**\n * Place the queued items a boundary selects (spec §6): every write, the first or all steers, and at `final` the first\n * or all follow-ups. A selected reset turns a `postTools` boundary into `final`. Writes are placed first and user\n * items after them, each in ID order, so user items queued before a reset run in the new context. A write whose head\n * targets an entry before the active range, including a range started earlier in this commit, is stale. Selected and\n * stale items are removed positionally.\n */\nexport async function applyBoundary(\n\ttx: Tx,\n\tboundary: Boundary,\n\tat: \"postTools\" | \"final\",\n\tnow: number,\n): Promise<BoundaryResult> {\n\tconst { conversationId, inbox } = boundary;\n\tconst items = inbox.items;\n\tconst reset = hasQueuedReset(items);\n\tconst final = at === \"final\" || reset;\n\tconst pick = (mode: \"steer\" | \"followUp\", queueMode: QueueMode): number[] => {\n\t\tconst indexes = items.flatMap((item, index) => (item.mode === mode ? [index] : []));\n\t\treturn queueMode === \"all\" ? indexes : indexes.slice(0, 1);\n\t};\n\tconst writes = items.flatMap((item, index) => (item.mode === \"write\" ? [index] : []));\n\tconst users = [...pick(\"steer\", boundary.steeringMode), ...(final ? pick(\"followUp\", boundary.followUpMode) : [])];\n\tusers.sort((a, b) => a - b);\n\n\t// `appendEntry()` copies the drafts' values; the items are removed only afterwards.\n\tlet first: EntryId | undefined;\n\tfor (const index of writes) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"write\" }>>;\n\t\tconst draft = item.entry as unknown as EntryDraft;\n\t\tif (isStale(boundary, draft)) {\n\t\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason: \"stale\" });\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft);\n\t\tif (draft.head !== undefined) boundary.head = draft.head === \"self\" ? entry.id : draft.head;\n\t\ttx.placeSubmission(item.id, entry.id);\n\t\tfirst ??= entry.id;\n\t}\n\tconst placed: SubmissionId[] = [];\n\tfor (const index of users) {\n\t\tconst item = items[index] as Draft<Extract<InboxItem, { mode: \"steer\" | \"followUp\" }>>;\n\t\tconst entry = await appendInput(tx, conversationId, item.content as UserInput, item.entry as InputEntry, now);\n\t\ttx.placeSubmission(item.id, entry.id);\n\t\tplaced.push(item.id);\n\t\tfirst ??= entry.id;\n\t}\n\tconst removed = [...writes, ...users].sort((a, b) => b - a);\n\tfor (const index of removed) items.splice(index, 1);\n\treturn { users: placed, first, reset };\n}\n\n/** Append the entry an input is placed as: `entry`'s kind and data, or `pi.user`, with the user message of `content`. */\nexport function appendInput(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcontent: UserInput,\n\tentry: InputEntry | undefined,\n\tnow: number,\n): Promise<EntryRecord> {\n\tconst message = { role: \"user\", content, timestamp: now } as const;\n\tif (entry === undefined) return tx.appendEntry(UserEntry, conversationId, { model: [message] });\n\treturn tx.appendEntry(conversationId, { ...pickInputEntry(entry), model: [message] });\n}\n\n/** The kind and data of an input's entry as strict JSON, without other fields an untyped caller might pass. */\nexport function pickInputEntry({ kind, data }: InputEntry): JsonRepresentation<InputEntry> {\n\tconst picked = data === undefined ? { kind } : { kind, data };\n\treturn copyJson(picked, { omitUndefinedProperties: true }) as JsonRepresentation<InputEntry>;\n}\n\n/**\n * Whether a write is display-only: it has no `model`, `head`, or `edits` (present counts, even if empty), so it changes\n * nothing the model sees and needs no boundary.\n */\nexport function isDisplayOnly(entry: EntryDraft): boolean {\n\treturn entry.model === undefined && entry.head === undefined && entry.edits === undefined;\n}\n\n/** Whether a reset (`head: \"self\"` write) is queued; entries appended before it leave the active range when it lands. */\nexport function hasQueuedReset(items: readonly InboxItem[]): boolean {\n\treturn items.some((item) => item.mode === \"write\" && item.entry.head === \"self\");\n}\n\n/** Whether a head write targets an entry before the active range, so placing it would bring back cut history. */\nexport function isStale(boundary: Boundary, entry: EntryDraft): boolean {\n\treturn typeof entry.head === \"number\" && boundary.head !== undefined && entry.head < boundary.head;\n}\n\n/** Remove a withdrawn submission's item; the caller settles the submission. */\nexport async function removeInboxItem(tx: Tx, conversationId: ConversationId, id: SubmissionId): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tconst index = items.findIndex((item) => item.id === id);\n\tif (index >= 0) items.splice(index, 1);\n}\n\n/**\n * Withdraw every queued input of a conversation, as `Conversation.abort()` and abort cascades do: each settles\n * `unanswered` with `reason` (default `aborted`) and leaves the inbox; queued writes stay for later placement.\n */\nexport async function withdrawQueuedInputs(tx: Tx, conversationId: ConversationId, reason = \"aborted\"): Promise<void> {\n\tconst items = (await tx.doc(InboxDoc, conversationId)).items;\n\tfor (let index = items.length - 1; index >= 0; index--) {\n\t\tconst item = items[index]!;\n\t\tif (item.mode === \"write\") continue;\n\t\ttx.settleSubmission(item.id, { status: \"unanswered\", reason });\n\t\titems.splice(index, 1);\n\t}\n}\n"]}
|
package/dist/harness/json.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { JsonValue } from "@earendil-works/chord";
|
|
1
|
+
import type { JsonValue } from "@earendil-works/chord/json";
|
|
2
2
|
/** How `assignJson()` writes one value instead of assigning it leaf by leaf. */
|
|
3
3
|
export type AssignPlan =
|
|
4
4
|
/** The string grew by `text` since it was last assigned: append it, when the lengths agree. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/harness/json.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/harness/json.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAE5D,gFAAgF;AAChF,MAAM,MAAM,UAAU;AACrB,+FAA+F;AAC7F;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AACpD,sDAAsD;GACpD;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AAC3B,sDAAsD;GACpD;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,GAAG,MAAM,EAAE,UAAU,CAAC,CAAA;CAAE,CAAC;AAE1F;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EACjF,MAAM,EAAE,CAAC,EACT,GAAG,EAAE,CAAC,EACN,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,EACvB,IAAI,CAAC,EAAE,UAAU,GACf,IAAI,CAiCN"}
|
package/dist/harness/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/harness/json.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/harness/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,6BAA6B,CAAC;AAYrE;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,MAAS,EACT,GAAM,EACN,KAAuB,EACvB,IAAiB;IAEjB,IAAI,IAAI,EAAE,IAAI,KAAK,MAAM;QAAE,OAAO;IAClC,sGAAsG;IACtG,MAAM,KAAK,GAAG,MAA4C,CAAC;IAC3D,iHAAiH;IACjH,2FAA2F;IAC3F,MAAM,OAAO,GAA0B,GAAG,KAAK,WAAW,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE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AC;IACD,IACC,IAAI,EAAE,IAAI,KAAK,QAAQ;QACvB,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QACtB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EACjD,CAAC;QACF,+EAA+E;QAC/E,UAAU,CAAC,MAAuC,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5E,OAAO;IACR,CAAC;IACD,IAAI,OAAO,KAAK,KAAK;QAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAC3C,CAAC;AAED,SAAS,QAAQ,CAAC,KAA4B;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { appendText, type Draft } from \"@earendil-works/chord/delta\";\nimport type { JsonValue } from \"@earendil-works/chord/json\";\n\n/** How `assignJson()` writes one value instead of assigning it leaf by leaf. */\nexport type AssignPlan =\n\t/** The string grew by `text` since it was last assigned: append it, when the lengths agree. */\n\t| { readonly kind: \"append\"; readonly text: string }\n\t/** Leave the value as it is; the caller writes it. */\n\t| { readonly kind: \"keep\" }\n\t/** Plans for some members or items of a container. */\n\t| { readonly kind: \"fields\"; readonly fields: ReadonlyMap<string | number, AssignPlan> };\n\n/**\n * Assign `value` at `target[key]` leaf by leaf. Chord records a container assignment as one full set and only emits an\n * append when a string leaf is reassigned with a longer string, so writing the partial whole would store and publish the\n * complete message on every flush. That append costs a compare of the whole string, though; where `plan` says what a\n * string member grew by, and the committed string plus that text has the new string's length, the text is appended\n * with `appendText()` instead.\n */\nexport function assignJson<T extends object, K extends keyof T & (string | number)>(\n\ttarget: T,\n\tkey: K,\n\tvalue: T[K] & JsonValue,\n\tplan?: AssignPlan,\n): void {\n\tif (plan?.kind === \"keep\") return;\n\t// Every target is a document container: JSON members or items, whatever its declared type names them.\n\tconst slots = target as Record<string | number, JsonValue>;\n\t// A `__proto__` member the target lacks reads through to Object.prototype; merging into that would pollute every\n\t// object in the process. Other inherited members are functions, which are not merged into.\n\tconst current: JsonValue | undefined = key === \"__proto__\" && !Object.hasOwn(slots, key) ? undefined : slots[key];\n\tconst fields = plan?.kind === \"fields\" ? plan.fields : undefined;\n\tif (isRecord(current) && isRecord(value)) {\n\t\tfor (const name of Object.keys(current)) if (!Object.hasOwn(value, name)) delete current[name];\n\t\tfor (const [name, child] of Object.entries(value)) assignJson(current, name, child, fields?.get(name));\n\t\treturn;\n\t}\n\tif (Array.isArray(current) && Array.isArray(value) && current.length <= value.length) {\n\t\tconst items = current as JsonValue[];\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tif (index < items.length) assignJson(items, index, value[index]!, fields?.get(index));\n\t\t\telse items.push(value[index]!);\n\t\t}\n\t\treturn;\n\t}\n\tif (\n\t\tplan?.kind === \"append\" &&\n\t\ttypeof current === \"string\" &&\n\t\ttypeof value === \"string\" &&\n\t\t!Array.isArray(target) &&\n\t\tcurrent.length + plan.text.length === value.length\n\t) {\n\t\t// The cast names what the checks above established: `target[key]` is a string.\n\t\tappendText(target as Draft<Record<string, string>>, String(key), plan.text);\n\t\treturn;\n\t}\n\tif (current !== value) slots[key] = value;\n}\n\nfunction isRecord(value: JsonValue | undefined): value is Record<string, JsonValue> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
package/dist/harness/live.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { Draft
|
|
1
|
+
import type { Draft } from "@earendil-works/chord/delta";
|
|
2
|
+
import type { JsonRepresentation, JsonValue } from "@earendil-works/chord/json";
|
|
2
3
|
import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
|
|
3
4
|
import type { Transaction } from "../session/transaction.ts";
|
|
4
5
|
import type { CommitOptions, EntryId, JsonObject, SubmissionId, SubmissionSettlement, TaskId, TaskRecord, Tx } from "../types.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.d.ts","sourceRoot":"","sources":["../../src/harness/live.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"live.d.ts","sourceRoot":"","sources":["../../src/harness/live.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAErE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EACX,aAAa,EACb,OAAO,EACP,UAAU,EACV,YAAY,EACZ,oBAAoB,EACpB,MAAM,EACN,UAAU,EACV,EAAE,EACF,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAErF,mFAAmF;AACnF,KAAK,YAAY,GAAG;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,MAAM,CAAC;IACvC,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8BAA8B;IAC9B,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,uDAAuD;IACvD,WA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AAC,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE;QACjG,CAAC,CAAC;YACA,MAAM,EAAE,YAAY;YACpB,MAAM,EAAE,UAAU;YAClB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,UAAU,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE;SAC5D,CACH,CAAC;AACH,CAAC","sourcesContent":["import type { Draft, JsonRepresentation, JsonValue } from \"@earendil-works/chord\";\nimport type { AssistantMessage, Usage } from \"@earendil-works/pi-ai\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tCommitOptions,\n\tEntryId,\n\tJsonObject,\n\tSubmissionId,\n\tSubmissionSettlement,\n\tTaskId,\n\tTaskRecord,\n\tTx,\n} from \"../types.ts\";\nimport { convertPartial } from \"./generation.ts\";\nimport type { SchedulerOutcome } from \"./scheduler.ts\";\nimport type { CompactionReason, CompactionResult, ToolDiagnostic } from \"./types.ts\";\n\n/** What a running tool call publishes, shared by model-issued and nested calls. */\ntype SlotProgress = {\n\tcallId: string;\n\tname: string;\n\tstatus: \"pending\" | \"running\" | \"done\";\n\t/** Retained running output and what the bounds dropped. */\n\toutput?: string;\n\tdroppedBytes?: number;\n\tdroppedLines?: number;\n\t/** Last `details()` value. */\n\tdetails?: JsonValue;\n\t/** Diagnostics recorded through `api.diagnostic()`. */\n\tdiagnostics?: ToolDiagnostic[];\n};\n\n/** Presentation of one tool call of the current round. */\nexport type ToolSlot = SlotProgress & {\n\t/** Absent for a call not started yet (sequential round). */\n\ttaskId?: TaskId;\n\t/** A call to a tool its request did not offer: its task settles `tool_unavailable` without running anything. */\n\tunoffered?: true;\n\t/** Result entry once done; absent when the tool task faulted or was orphaned. */\n\tentry?: EntryId;\n};\n\n/**\n * Presentation of one nested call: a call a running tool made through `executeTool()`. `callId` is\n * `<parentCallId>/<key>`, the call's ID, unique because keys contain no `/`. The Harness relates\n * slots by task ID: `taskId` is the call's tool task, `parentTaskId` the calling one, model-issued or nested.\n */\nexport type NestedToolSlot = SlotProgress & {\n\tparentCallId: string;\n\tparentTaskId: TaskId;\n\ttaskId: TaskId;\n\t/**\n\t * What the call was made with, replaced by the arguments it runs with, after repair, `beforeTool`, and coercion,\n\t * once it starts executing. A model-issued call's arguments are in its assistant entry instead.\n\t */\n\targuments: JsonObject;\n\t/** Once done: how the call ended, for a status line. The result itself is in the caller's `NestedCallDoc`. */\n\tsummary?: NestedToolSummary;\n};\n\n/** How a nested call ended: an error flag, its execution time, its spend, and up to 500 characters of error text. */\nexport type NestedToolSummary = {\n\tisError: boolean;\n\tdurationMs?: number;\n\tusage?: JsonRepresentation<Usage>;\n\terror?: string;\n};\n\n/** Presentation of one live compaction task (spec §8.7). */\nexport type CompactionStatus = {\n\ttaskId: TaskId<CompactionResult>;\n\t/** What started it: `compact()`, a threshold, or a context overflow. */\n\ttrigger: CompactionReason;\n\t/** Whether a generation waits for it: a compaction the generation owns. */\n\tblocking: boolean;\n\tattempt: number;\n\t/** Durable backoff before the next summarization attempt. */\n\tretry?: { at: number; error: string };\n};\n\n/** The newest compaction that failed since a compaction last produced a summary (spec §8.7). */\nexport type CompactionFailure = {\n\ttaskId: TaskId<CompactionResult>;\n\t/** What started the compaction that failed. */\n\ttrigger: CompactionReason;\n\t/** The failed or faulted outcome's error message, or why the scheduler orphaned the task. */\n\terror: string;\n};\n\n/**\n * Why a run ended without an answer:\n * - `model_error`: the model's response failed, after any retries, or the compaction a request needed failed;\n * - `no_model`: no model is configured, or the configured one is not available;\n * - `aborted`: the run was aborted (`Conversation.abort()`, `abortTask()`); `detail` says when its abort handler was\n * cut off `settings.restartLimit` times and did not finish;\n * - `reset`: a queued reset started a new context at the post-tools boundary, before an answer (a tool's handoff\n * continues the run);\n * - `faulted`: the run's task threw where it cannot recover, or storage rejected its commit;\n * - `orphaned`: the run's task was aborted while no registered definition could take it;\n * - `interrupted`: the host stopped while the model was answering, more often than `settings.retry` retries;\n * - `restart_limit`: the run's generation was cut off `settings.restartLimit` times in a row; a request or poll it was\n * cut off during counts as a failed attempt first, so this ends one whose charge itself keeps failing;\n * - `nothing_to_answer`: the context did not end in a user message or tool results (empty, or ending in an answer), so\n * no request was sent, as for a continue after an answer;\n * - `turn_limit`: a tool round reached the conversation's `maxTurns`; a continue resumes on its results.\n */\nexport type RunFailureReason =\n\t| \"model_error\"\n\t| \"no_model\"\n\t| \"aborted\"\n\t| \"reset\"\n\t| \"faulted\"\n\t| \"orphaned\"\n\t| \"interrupted\"\n\t| \"restart_limit\"\n\t| \"nothing_to_answer\"\n\t| \"turn_limit\";\n\n/** The newest run that ended without an answer (spec §8.2). */\nexport type RunFailure = {\n\t/** The task that ended the run: the run's task at its end. */\n\ttaskId: TaskId;\n\t/** The run's inputs, settled `unanswered`. */\n\tinputs: SubmissionId[];\n\treason: RunFailureReason;\n\t/**\n\t * `model_error`: the error text; `no_model`: which model is missing; `faulted`: the error message; `orphaned`: why\n\t * the task could not run (`missing_task`, `task_too_old`, `migration_failed`); `interrupted` and `restart_limit`: what\n\t * was cut off, and how often; `turn_limit`: the tool rounds the run took, `\"1 turn\"` or `\"N turns\"`.\n\t */\n\tdetail?: string;\n\t/** The failed run's `run.first`, so a continue's `afterRun` hooks see its history too. */\n\tfirst?: EntryId;\n};\n\n/** Run control (spec §8.2). */\nexport type LiveRun = {\n\t/** The task that settles the run's inputs: its generation, handed from one to the next. */\n\ttaskId: TaskId;\n\t/** The run's placed inputs, settled when it ends; `[]` once it answered and runs only its `afterRun` tasks. */\n\tinputs: SubmissionId[];\n\t/** Tool rounds so far, which `AgentState.maxTurns` bounds; an `onYield` continuation starts the count over. */\n\tturns: number;\n\t/**\n\t * The run's first entry: the first one the boundary that started it placed, a continue's the failed run's it\n\t * continues; otherwise its first tool-calling answer. A run started before it was recorded may lack it; `afterRun`\n\t * hooks then get the answer as the first entry.\n\t */\n\tfirst?: EntryId;\n\t/**\n\t * Present once the run answered and its generation waits for the tasks `afterRun` hooks asked for, listed once\n\t * created: queued items stay queued until they are terminal, and the run then ends without a failure.\n\t */\n\tafterRun?: { tasks?: TaskId[] };\n};\n\n/** Built-in live conversation state: run control and presentation of the current generation and tool round. */\nexport type LiveState = {\n\t/** Run control; present exactly while busy, also while a run that answered runs its `afterRun` tasks. */\n\trun?: LiveRun;\n\t/** Presentation of the current generation attempt. */\n\tgeneration?: {\n\t\tattempt: number;\n\t\t/** Committed throttled partial of the in-flight response. */\n\t\tmessage?: JsonRepresentation<AssistantMessage>;\n\t\t/** Durable backoff before the next attempt. */\n\t\tretry?: { at: number; error: string };\n\t\t/** Provider-side deferred response being polled. */\n\t\tdeferred?: { pollAt: number };\n\t};\n\t/** The current tool round in call order, from the tool-calling answer until the generation's `tools` phase ends it. */\n\ttools?: ToolSlot[];\n\t/**\n\t * Nested calls of running tool calls, in creation order, so a parent precedes its children and task IDs ascend. A\n\t * call's nested slots are removed when the call settles.\n\t */\n\tnestedTools?: NestedToolSlot[];\n\t/** Live compaction tasks in task ID order; absent when none. */\n\tcompactions?: CompactionStatus[];\n\t/**\n\t * The newest compaction failure, so a client can show it after the task ended. A compaction that produces a summary\n\t * removes it; one that is aborted or finds nothing to compact leaves it.\n\t */\n\tcompactionFailure?: CompactionFailure;\n\t/**\n\t * Why the newest run ended without an answer, so a client can show it after the run ended. Set in the commit that\n\t * ends the run; removed when a later commit starts a run. A run started in the same commit, by\n\t * `afterFailedRun: \"continue\"` or after a reset, keeps it.\n\t */\n\trunFailure?: RunFailure;\n};\n\nexport const LiveDoc = defineDoc<LiveState>({\n\tkind: \"pi.live\",\n\tversion: 3,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({}),\n\t// Version 1 named a compaction's trigger `reason`, in `compactions` and `compactionFailure`. Versions 1 and 2 (as\n\t// builds before `run.turns` stored it) may lack `run.turns`: a run in flight across the upgrade counts its turns\n\t// from 0. Version 2 already names the trigger `trigger`, so renaming leaves it alone.\n\tmigrate: (value) => {\n\t\tconst live = value as { run?: JsonObject; compactions?: JsonObject[]; compactionFailure?: JsonObject };\n\t\tconst { run, compactions, compactionFailure } = live;\n\t\treturn {\n\t\t\t...value,\n\t\t\t...(run === undefined ? {} : { run: { ...run, turns: typeof run.turns === \"number\" ? run.turns : 0 } }),\n\t\t\t...(compactions === undefined ? {} : { compactions: compactions.map(renameReason) }),\n\t\t\t...(compactionFailure === undefined ? {} : { compactionFailure: renameReason(compactionFailure) }),\n\t\t} as LiveState;\n\t},\n\t// REMINDER: a complete base whenever nothing runs (spec §8.2): no generation and no running tool slot. That holds\n\t// while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain\n\t// spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while\n\t// running, so every base is small; a nested call's result lives in its caller's task documents, never here. Do not\n\t// add a delta-count bound; the tool output benchmark checks this rule.\n\tcheckpointWhen: (value) =>\n\t\tvalue.generation === undefined &&\n\t\t!(value.tools ?? []).some((slot) => slot.status === \"running\") &&\n\t\t!(value.nestedTools ?? []).some((slot) => slot.status === \"running\"),\n});\n\n/** A copy of a version 1 compaction status or failure with `reason` renamed `trigger`, its keys in their order. */\nfunction renameReason(value: JsonObject): JsonObject {\n\treturn Object.fromEntries(Object.entries(value).map(([key, field]) => [key === \"reason\" ? \"trigger\" : key, field]));\n}\n\n/**\n * How the progress throttles commit a partial answer and running tool output into `pi.live`: deferred, so storage gets\n * them together, at the next commit that reads or writes `pi.live` or after `settings.progress.persistWithinMs`. Every\n * commit that consumes or clears streamed fields reads `pi.live`, so it stores them with its own changes (spec §8.2).\n */\nexport const PROGRESS_COMMIT: CommitOptions = { persistence: { kind: \"deferred\" } };\n\n/** Built-in task kinds that can own `pi.live.run`. */\nconst RUN_TASK_KINDS: ReadonlySet<string> = new Set([\"pi.generation\"]);\nconst TOOL_TASK_KIND = \"pi.tool\";\nconst COMPACTION_TASK_KIND = \"pi.compaction\";\n\n/**\n * Built-in task kinds that end themselves once cut off `settings.restartLimit` times (`TaskRecord.restarts`); the\n * scheduler faults a task of any other kind instead (spec §5.4).\n */\nexport const LIMITS_RESTARTS: ReadonlySet<string> = new Set([...RUN_TASK_KINDS, TOOL_TASK_KIND, COMPACTION_TASK_KIND]);\n\n/** Whether `task` was cut off `settings.restartLimit` times in a row, so its phase ends it instead of running. */\nexport function cutOffTooOften(\n\ttask: { readonly restarts?: number },\n\truntime: { readonly settings: { readonly restartLimit: number } },\n): boolean {\n\t// The settings are read only for a task that was cut off at all, so the normal path resolves nothing more.\n\treturn task.restarts !== undefined && task.restarts >= runtime.settings.restartLimit;\n}\n\n/**\n * Whether a task at the limit may still do the cleanup it does when it ends, such as converting a partial: only at the\n * limit. Past it, that cleanup may be what cut the task off, so the task ends without it.\n */\nexport function salvageable(\n\ttask: { readonly restarts?: number },\n\truntime: { readonly settings: { readonly restartLimit: number } },\n): boolean {\n\treturn (task.restarts ?? 0) <= runtime.settings.restartLimit;\n}\n\n/** How often a task was cut off, for a message: \"once\", or \"3 times in a row\". */\nexport function cutOffCount(task: { readonly restarts?: number }): string {\n\tconst restarts = task.restarts ?? 0;\n\treturn restarts === 1 ? \"once\" : `${restarts} times in a row`;\n}\n\n/** How a run ends: with an answer, or without one, settling its inputs `unanswered` and recording why. */\nexport type RunEnd =\n\t| { readonly status: \"done\"; readonly answer: EntryId }\n\t| {\n\t\t\treadonly status: \"unanswered\";\n\t\t\treadonly reason: RunFailureReason;\n\t\t\treadonly detail?: string;\n\t\t\t/** The inputs' settlement; default `unanswered` with `reason` and `detail`. */\n\t\t\treadonly settlement?: SubmissionSettlement;\n\t };\n\n/**\n * End the run owned by `taskId`: settle each of its inputs, remove `run`, and, without an answer, record\n * `runFailure`. A run that answered already, and runs only its `afterRun` tasks, records no failure, however it ends.\n * Always removes `generation`, `tools`, and `nestedTools`, whose presentation belongs to the ending run.\n */\nexport function endRun(tx: Tx, live: Draft<LiveState>, taskId: TaskId, end: RunEnd): void {\n\tif (live.run?.taskId === taskId) {\n\t\tconst inputs = [...live.run.inputs];\n\t\tconst { first } = live.run;\n\t\tif (end.status === \"done\") {\n\t\t\tfor (const id of inputs) tx.settleSubmission(id, { status: \"done\", answer: end.answer });\n\t\t} else if (live.run.afterRun === undefined) {\n\t\t\tconst { reason, detail } = end;\n\t\t\tconst settlement = end.settlement ?? {\n\t\t\t\tstatus: \"unanswered\",\n\t\t\t\treason,\n\t\t\t\t...(detail === undefined ? {} : { detail }),\n\t\t\t};\n\t\t\tfor (const id of inputs) tx.settleSubmission(id, settlement);\n\t\t\tlive.runFailure = {\n\t\t\t\ttaskId,\n\t\t\t\tinputs,\n\t\t\t\treason,\n\t\t\t\t...(detail === undefined ? {} : { detail }),\n\t\t\t\t...(first === undefined ? {} : { first }),\n\t\t\t};\n\t\t}\n\t\tdelete live.run;\n\t}\n\tdelete live.generation;\n\tdelete live.tools;\n\tdelete live.nestedTools;\n}\n\n/** Add the status of a compaction task created in this commit; statuses stay in task ID order. */\nexport function addCompactionStatus(live: Draft<LiveState>, status: CompactionStatus): void {\n\tlive.compactions ??= [];\n\tlive.compactions.push(status);\n}\n\n/** The status of compaction task `taskId`, if listed. */\nexport function compactionStatus(live: Draft<LiveState>, taskId: TaskId): Draft<CompactionStatus> | undefined {\n\treturn live.compactions?.find((status) => status.taskId === taskId);\n}\n\n/** Remove the status of compaction task `taskId`, and the list once empty. */\nexport function removeCompactionStatus(live: Draft<LiveState>, taskId: TaskId): void {\n\tconst statuses = live.compactions;\n\tif (statuses === undefined) return;\n\tconst index = statuses.findIndex((status) => status.taskId === taskId);\n\tif (index >= 0) statuses.splice(index, 1);\n\tif (statuses.length === 0) delete live.compactions;\n}\n\n/** Remove the status of compaction task `taskId` and record that it failed with `error`. */\nexport function failCompactionStatus(live: Draft<LiveState>, taskId: TaskId, error: string): void {\n\tconst status = compactionStatus(live, taskId);\n\tif (status !== undefined) live.compactionFailure = { taskId: status.taskId, trigger: status.trigger, error };\n\tremoveCompactionStatus(live, taskId);\n}\n\n/**\n * The slot of tool task `taskId`, model-issued or nested, if `pi.live` still lists it. Nested slots are found by binary\n * search: a tool may make thousands of nested calls, each of which looks up its slot in several commits, and every\n * element a search reads costs a node in the draft's change tracker. Their task IDs ascend: each slot is appended in\n * the commit that creates its task, task IDs ascend in commit order, and removal keeps the order.\n */\nexport function toolSlot(live: Draft<LiveState>, taskId: TaskId): Draft<ToolSlot | NestedToolSlot> | undefined {\n\tconst slot = live.tools?.find((each) => each.taskId === taskId);\n\tif (slot !== undefined || live.nestedTools === undefined) return slot;\n\tconst nested = live.nestedTools;\n\tlet low = 0;\n\tlet high = nested.length - 1;\n\twhile (low <= high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tconst candidate = nested[middle]!;\n\t\tif (candidate.taskId === taskId) return candidate;\n\t\tif (candidate.taskId < taskId) low = middle + 1;\n\t\telse high = middle - 1;\n\t}\n\treturn undefined;\n}\n\n/**\n * Mark a slot done and clear its running output; the caller sets a model-issued call's result `entry`, or a nested\n * call's `summary`. Neither is set when the task faulted or was orphaned.\n */\nexport function finishSlot(slot: Draft<ToolSlot | NestedToolSlot>): void {\n\tslot.status = \"done\";\n\tclearProgress(slot);\n}\n\n/** Remove the nested slots below tool task `taskId`, transitively; the list holds parents before their children. */\nexport function removeNestedSlots(live: Draft<LiveState>, taskId: TaskId): void {\n\tconst nested = live.nestedTools;\n\tif (nested === undefined) return;\n\tconst removed = new Set<TaskId>([taskId]);\n\tfor (const slot of nested) if (removed.has(slot.parentTaskId)) removed.add(slot.taskId);\n\tfor (let index = nested.length - 1; index >= 0; index--) {\n\t\tif (removed.has(nested[index]!.parentTaskId)) nested.splice(index, 1);\n\t}\n\tif (nested.length === 0) delete live.nestedTools;\n}\n\n/** Remove what a tool published while running; its result entry or a rerun replaces it. */\nexport function clearProgress(slot: Draft<SlotProgress>): void {\n\tdelete slot.output;\n\tdelete slot.droppedBytes;\n\tdelete slot.droppedLines;\n\tdelete slot.details;\n\tdelete slot.diagnostics;\n}\n\n/**\n * Harness cleanup for a terminal outcome the scheduler writes itself (`faulted` or `orphaned`). A run task ends its\n * run; a tool task's slot is marked done without an entry, and context derivation synthesizes the missing result; a\n * compaction task's status is removed and its failure recorded.\n * Ignores other kinds so it never creates `pi.live` elsewhere. The scheduler calls this without knowing task kinds;\n * the Harness passes it in (spec §5.4).\n * REMINDER: a committed generation partial becomes an aborted assistant entry here, exactly as in the generation abort\n * handler, so the transcript keeps what the model produced and `pi.usage` counts its spend. The scheduler's commit has\n * no task scope, so that entry has no `byTaskId`. Faults come from task bugs\n * or malformed provider data (a non-JSON value in a response), or a commit the Storage rejected without effect; an\n * uncertain storage failure poisons the Session instead and writes no outcome.\n */\nexport async function settleSchedulerOutcome(\n\ttx: Transaction,\n\trecord: TaskRecord<JsonValue, JsonValue, JsonValue>,\n\toutcome: SchedulerOutcome,\n): Promise<void> {\n\tif (record.kind === TOOL_TASK_KIND) {\n\t\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\t\tconst slot = toolSlot(live, record.id);\n\t\tif (slot !== undefined) finishSlot(slot);\n\t\tremoveNestedSlots(live, record.id);\n\t\treturn;\n\t}\n\t// Only an abort handler is faulted for the limit here (the built-in phases end themselves): the task was aborted,\n\t// and keeps that meaning. Its run ends `aborted`, with the limit as detail, and an aborted compaction is no failure.\n\tconst detail = outcome.status === \"faulted\" ? outcome.error.detail : undefined;\n\tconst cutOff =\n\t\ttypeof detail === \"object\" && detail !== null && \"reason\" in detail && detail.reason === \"restart_limit\";\n\tif (record.kind === COMPACTION_TASK_KIND) {\n\t\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\t\tif (cutOff) removeCompactionStatus(live, record.id);\n\t\telse failCompactionStatus(live, record.id, outcome.status === \"faulted\" ? outcome.error.message : outcome.reason);\n\t\treturn;\n\t}\n\tif (!RUN_TASK_KINDS.has(record.kind)) return;\n\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\tif (live.run?.taskId !== record.id) return;\n\t// Cut off, the abort handler may have died converting the partial: the run ends without it.\n\tif (!cutOff) await convertPartial(tx, live, record.conversationId);\n\tendRun(\n\t\ttx,\n\t\tlive,\n\t\trecord.id,\n\t\toutcome.status === \"faulted\"\n\t\t\t? { status: \"unanswered\", reason: cutOff ? \"aborted\" : \"faulted\", detail: outcome.error.message }\n\t\t\t: {\n\t\t\t\t\tstatus: \"unanswered\",\n\t\t\t\t\treason: \"orphaned\",\n\t\t\t\t\tdetail: outcome.reason,\n\t\t\t\t\tsettlement: { status: \"unanswered\", reason: outcome.reason },\n\t\t\t\t},\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"live.js","sourceRoot":"","sources":["../../src/harness/live.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAY5C,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAmLjD,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,CAAY;IAC3C,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,CAAC;IACV,KAAK,EAAE,cAAc;IACrB,OAAO,EAAE,QAAQ;IACjB,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;IACnB,kHAAkH;IAClH,iHAAiH;IACjH,sFAAsF;IACtF,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAClB,MAAM,IAAI,GAAG,KAAyF,CAAC;QACvG,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;QACrD,OAAO;YACN,GAAG,KAAK;YACR,GAAG,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,GAAG,GAAG,EAAE,KAAK,EAAE,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAA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MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,UAAU,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE;SAC5D,CACH,CAAC;AACH,CAAC","sourcesContent":["import type { Draft } from \"@earendil-works/chord/delta\";\nimport type { JsonRepresentation, JsonValue } from \"@earendil-works/chord/json\";\nimport type { AssistantMessage, Usage } from \"@earendil-works/pi-ai\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tCommitOptions,\n\tEntryId,\n\tJsonObject,\n\tSubmissionId,\n\tSubmissionSettlement,\n\tTaskId,\n\tTaskRecord,\n\tTx,\n} from \"../types.ts\";\nimport { convertPartial } from \"./generation.ts\";\nimport type { SchedulerOutcome } from \"./scheduler.ts\";\nimport type { CompactionReason, CompactionResult, ToolDiagnostic } from \"./types.ts\";\n\n/** What a running tool call publishes, shared by model-issued and nested calls. */\ntype SlotProgress = {\n\tcallId: string;\n\tname: string;\n\tstatus: \"pending\" | \"running\" | \"done\";\n\t/** Retained running output and what the bounds dropped. */\n\toutput?: string;\n\tdroppedBytes?: number;\n\tdroppedLines?: number;\n\t/** Last `details()` value. */\n\tdetails?: JsonValue;\n\t/** Diagnostics recorded through `api.diagnostic()`. */\n\tdiagnostics?: ToolDiagnostic[];\n};\n\n/** Presentation of one tool call of the current round. */\nexport type ToolSlot = SlotProgress & {\n\t/** Absent for a call not started yet (sequential round). */\n\ttaskId?: TaskId;\n\t/** A call to a tool its request did not offer: its task settles `tool_unavailable` without running anything. */\n\tunoffered?: true;\n\t/** Result entry once done; absent when the tool task faulted or was orphaned. */\n\tentry?: EntryId;\n};\n\n/**\n * Presentation of one nested call: a call a running tool made through `executeTool()`. `callId` is\n * `<parentCallId>/<key>`, the call's ID, unique because keys contain no `/`. The Harness relates\n * slots by task ID: `taskId` is the call's tool task, `parentTaskId` the calling one, model-issued or nested.\n */\nexport type NestedToolSlot = SlotProgress & {\n\tparentCallId: string;\n\tparentTaskId: TaskId;\n\ttaskId: TaskId;\n\t/**\n\t * What the call was made with, replaced by the arguments it runs with, after repair, `beforeTool`, and coercion,\n\t * once it starts executing. A model-issued call's arguments are in its assistant entry instead.\n\t */\n\targuments: JsonObject;\n\t/** Once done: how the call ended, for a status line. The result itself is in the caller's `NestedCallDoc`. */\n\tsummary?: NestedToolSummary;\n};\n\n/** How a nested call ended: an error flag, its execution time, its spend, and up to 500 characters of error text. */\nexport type NestedToolSummary = {\n\tisError: boolean;\n\tdurationMs?: number;\n\tusage?: JsonRepresentation<Usage>;\n\terror?: string;\n};\n\n/** Presentation of one live compaction task (spec §8.7). */\nexport type CompactionStatus = {\n\ttaskId: TaskId<CompactionResult>;\n\t/** What started it: `compact()`, a threshold, or a context overflow. */\n\ttrigger: CompactionReason;\n\t/** Whether a generation waits for it: a compaction the generation owns. */\n\tblocking: boolean;\n\tattempt: number;\n\t/** Durable backoff before the next summarization attempt. */\n\tretry?: { at: number; error: string };\n};\n\n/** The newest compaction that failed since a compaction last produced a summary (spec §8.7). */\nexport type CompactionFailure = {\n\ttaskId: TaskId<CompactionResult>;\n\t/** What started the compaction that failed. */\n\ttrigger: CompactionReason;\n\t/** The failed or faulted outcome's error message, or why the scheduler orphaned the task. */\n\terror: string;\n};\n\n/**\n * Why a run ended without an answer:\n * - `model_error`: the model's response failed, after any retries, or the compaction a request needed failed;\n * - `no_model`: no model is configured, or the configured one is not available;\n * - `aborted`: the run was aborted (`Conversation.abort()`, `abortTask()`); `detail` says when its abort handler was\n * cut off `settings.restartLimit` times and did not finish;\n * - `reset`: a queued reset started a new context at the post-tools boundary, before an answer (a tool's handoff\n * continues the run);\n * - `faulted`: the run's task threw where it cannot recover, or storage rejected its commit;\n * - `orphaned`: the run's task was aborted while no registered definition could take it;\n * - `interrupted`: the host stopped while the model was answering, more often than `settings.retry` retries;\n * - `restart_limit`: the run's generation was cut off `settings.restartLimit` times in a row; a request or poll it was\n * cut off during counts as a failed attempt first, so this ends one whose charge itself keeps failing;\n * - `nothing_to_answer`: the context did not end in a user message or tool results (empty, or ending in an answer), so\n * no request was sent, as for a continue after an answer;\n * - `turn_limit`: a tool round reached the conversation's `maxTurns`; a continue resumes on its results.\n */\nexport type RunFailureReason =\n\t| \"model_error\"\n\t| \"no_model\"\n\t| \"aborted\"\n\t| \"reset\"\n\t| \"faulted\"\n\t| \"orphaned\"\n\t| \"interrupted\"\n\t| \"restart_limit\"\n\t| \"nothing_to_answer\"\n\t| \"turn_limit\";\n\n/** The newest run that ended without an answer (spec §8.2). */\nexport type RunFailure = {\n\t/** The task that ended the run: the run's task at its end. */\n\ttaskId: TaskId;\n\t/** The run's inputs, settled `unanswered`. */\n\tinputs: SubmissionId[];\n\treason: RunFailureReason;\n\t/**\n\t * `model_error`: the error text; `no_model`: which model is missing; `faulted`: the error message; `orphaned`: why\n\t * the task could not run (`missing_task`, `task_too_old`, `migration_failed`); `interrupted` and `restart_limit`: what\n\t * was cut off, and how often; `turn_limit`: the tool rounds the run took, `\"1 turn\"` or `\"N turns\"`.\n\t */\n\tdetail?: string;\n\t/** The failed run's `run.first`, so a continue's `afterRun` hooks see its history too. */\n\tfirst?: EntryId;\n};\n\n/** Run control (spec §8.2). */\nexport type LiveRun = {\n\t/** The task that settles the run's inputs: its generation, handed from one to the next. */\n\ttaskId: TaskId;\n\t/** The run's placed inputs, settled when it ends; `[]` once it answered and runs only its `afterRun` tasks. */\n\tinputs: SubmissionId[];\n\t/** Tool rounds so far, which `AgentState.maxTurns` bounds; an `onYield` continuation starts the count over. */\n\tturns: number;\n\t/**\n\t * The run's first entry: the first one the boundary that started it placed, a continue's the failed run's it\n\t * continues; otherwise its first tool-calling answer. A run started before it was recorded may lack it; `afterRun`\n\t * hooks then get the answer as the first entry.\n\t */\n\tfirst?: EntryId;\n\t/**\n\t * Present once the run answered and its generation waits for the tasks `afterRun` hooks asked for, listed once\n\t * created: queued items stay queued until they are terminal, and the run then ends without a failure.\n\t */\n\tafterRun?: { tasks?: TaskId[] };\n};\n\n/** Built-in live conversation state: run control and presentation of the current generation and tool round. */\nexport type LiveState = {\n\t/** Run control; present exactly while busy, also while a run that answered runs its `afterRun` tasks. */\n\trun?: LiveRun;\n\t/** Presentation of the current generation attempt. */\n\tgeneration?: {\n\t\tattempt: number;\n\t\t/** Committed throttled partial of the in-flight response. */\n\t\tmessage?: JsonRepresentation<AssistantMessage>;\n\t\t/** Durable backoff before the next attempt. */\n\t\tretry?: { at: number; error: string };\n\t\t/** Provider-side deferred response being polled. */\n\t\tdeferred?: { pollAt: number };\n\t};\n\t/** The current tool round in call order, from the tool-calling answer until the generation's `tools` phase ends it. */\n\ttools?: ToolSlot[];\n\t/**\n\t * Nested calls of running tool calls, in creation order, so a parent precedes its children and task IDs ascend. A\n\t * call's nested slots are removed when the call settles.\n\t */\n\tnestedTools?: NestedToolSlot[];\n\t/** Live compaction tasks in task ID order; absent when none. */\n\tcompactions?: CompactionStatus[];\n\t/**\n\t * The newest compaction failure, so a client can show it after the task ended. A compaction that produces a summary\n\t * removes it; one that is aborted or finds nothing to compact leaves it.\n\t */\n\tcompactionFailure?: CompactionFailure;\n\t/**\n\t * Why the newest run ended without an answer, so a client can show it after the run ended. Set in the commit that\n\t * ends the run; removed when a later commit starts a run. A run started in the same commit, by\n\t * `afterFailedRun: \"continue\"` or after a reset, keeps it.\n\t */\n\trunFailure?: RunFailure;\n};\n\nexport const LiveDoc = defineDoc<LiveState>({\n\tkind: \"pi.live\",\n\tversion: 3,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({}),\n\t// Version 1 named a compaction's trigger `reason`, in `compactions` and `compactionFailure`. Versions 1 and 2 (as\n\t// builds before `run.turns` stored it) may lack `run.turns`: a run in flight across the upgrade counts its turns\n\t// from 0. Version 2 already names the trigger `trigger`, so renaming leaves it alone.\n\tmigrate: (value) => {\n\t\tconst live = value as { run?: JsonObject; compactions?: JsonObject[]; compactionFailure?: JsonObject };\n\t\tconst { run, compactions, compactionFailure } = live;\n\t\treturn {\n\t\t\t...value,\n\t\t\t...(run === undefined ? {} : { run: { ...run, turns: typeof run.turns === \"number\" ? run.turns : 0 } }),\n\t\t\t...(compactions === undefined ? {} : { compactions: compactions.map(renameReason) }),\n\t\t\t...(compactionFailure === undefined ? {} : { compactionFailure: renameReason(compactionFailure) }),\n\t\t} as LiveState;\n\t},\n\t// REMINDER: a complete base whenever nothing runs (spec §8.2): no generation and no running tool slot. That holds\n\t// while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain\n\t// spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while\n\t// running, so every base is small; a nested call's result lives in its caller's task documents, never here. Do not\n\t// add a delta-count bound; the tool output benchmark checks this rule.\n\tcheckpointWhen: (value) =>\n\t\tvalue.generation === undefined &&\n\t\t!(value.tools ?? []).some((slot) => slot.status === \"running\") &&\n\t\t!(value.nestedTools ?? []).some((slot) => slot.status === \"running\"),\n});\n\n/** A copy of a version 1 compaction status or failure with `reason` renamed `trigger`, its keys in their order. */\nfunction renameReason(value: JsonObject): JsonObject {\n\treturn Object.fromEntries(Object.entries(value).map(([key, field]) => [key === \"reason\" ? \"trigger\" : key, field]));\n}\n\n/**\n * How the progress throttles commit a partial answer and running tool output into `pi.live`: deferred, so storage gets\n * them together, at the next commit that reads or writes `pi.live` or after `settings.progress.persistWithinMs`. Every\n * commit that consumes or clears streamed fields reads `pi.live`, so it stores them with its own changes (spec §8.2).\n */\nexport const PROGRESS_COMMIT: CommitOptions = { persistence: { kind: \"deferred\" } };\n\n/** Built-in task kinds that can own `pi.live.run`. */\nconst RUN_TASK_KINDS: ReadonlySet<string> = new Set([\"pi.generation\"]);\nconst TOOL_TASK_KIND = \"pi.tool\";\nconst COMPACTION_TASK_KIND = \"pi.compaction\";\n\n/**\n * Built-in task kinds that end themselves once cut off `settings.restartLimit` times (`TaskRecord.restarts`); the\n * scheduler faults a task of any other kind instead (spec §5.4).\n */\nexport const LIMITS_RESTARTS: ReadonlySet<string> = new Set([...RUN_TASK_KINDS, TOOL_TASK_KIND, COMPACTION_TASK_KIND]);\n\n/** Whether `task` was cut off `settings.restartLimit` times in a row, so its phase ends it instead of running. */\nexport function cutOffTooOften(\n\ttask: { readonly restarts?: number },\n\truntime: { readonly settings: { readonly restartLimit: number } },\n): boolean {\n\t// The settings are read only for a task that was cut off at all, so the normal path resolves nothing more.\n\treturn task.restarts !== undefined && task.restarts >= runtime.settings.restartLimit;\n}\n\n/**\n * Whether a task at the limit may still do the cleanup it does when it ends, such as converting a partial: only at the\n * limit. Past it, that cleanup may be what cut the task off, so the task ends without it.\n */\nexport function salvageable(\n\ttask: { readonly restarts?: number },\n\truntime: { readonly settings: { readonly restartLimit: number } },\n): boolean {\n\treturn (task.restarts ?? 0) <= runtime.settings.restartLimit;\n}\n\n/** How often a task was cut off, for a message: \"once\", or \"3 times in a row\". */\nexport function cutOffCount(task: { readonly restarts?: number }): string {\n\tconst restarts = task.restarts ?? 0;\n\treturn restarts === 1 ? \"once\" : `${restarts} times in a row`;\n}\n\n/** How a run ends: with an answer, or without one, settling its inputs `unanswered` and recording why. */\nexport type RunEnd =\n\t| { readonly status: \"done\"; readonly answer: EntryId }\n\t| {\n\t\t\treadonly status: \"unanswered\";\n\t\t\treadonly reason: RunFailureReason;\n\t\t\treadonly detail?: string;\n\t\t\t/** The inputs' settlement; default `unanswered` with `reason` and `detail`. */\n\t\t\treadonly settlement?: SubmissionSettlement;\n\t };\n\n/**\n * End the run owned by `taskId`: settle each of its inputs, remove `run`, and, without an answer, record\n * `runFailure`. A run that answered already, and runs only its `afterRun` tasks, records no failure, however it ends.\n * Always removes `generation`, `tools`, and `nestedTools`, whose presentation belongs to the ending run.\n */\nexport function endRun(tx: Tx, live: Draft<LiveState>, taskId: TaskId, end: RunEnd): void {\n\tif (live.run?.taskId === taskId) {\n\t\tconst inputs = [...live.run.inputs];\n\t\tconst { first } = live.run;\n\t\tif (end.status === \"done\") {\n\t\t\tfor (const id of inputs) tx.settleSubmission(id, { status: \"done\", answer: end.answer });\n\t\t} else if (live.run.afterRun === undefined) {\n\t\t\tconst { reason, detail } = end;\n\t\t\tconst settlement = end.settlement ?? {\n\t\t\t\tstatus: \"unanswered\",\n\t\t\t\treason,\n\t\t\t\t...(detail === undefined ? {} : { detail }),\n\t\t\t};\n\t\t\tfor (const id of inputs) tx.settleSubmission(id, settlement);\n\t\t\tlive.runFailure = {\n\t\t\t\ttaskId,\n\t\t\t\tinputs,\n\t\t\t\treason,\n\t\t\t\t...(detail === undefined ? {} : { detail }),\n\t\t\t\t...(first === undefined ? {} : { first }),\n\t\t\t};\n\t\t}\n\t\tdelete live.run;\n\t}\n\tdelete live.generation;\n\tdelete live.tools;\n\tdelete live.nestedTools;\n}\n\n/** Add the status of a compaction task created in this commit; statuses stay in task ID order. */\nexport function addCompactionStatus(live: Draft<LiveState>, status: CompactionStatus): void {\n\tlive.compactions ??= [];\n\tlive.compactions.push(status);\n}\n\n/** The status of compaction task `taskId`, if listed. */\nexport function compactionStatus(live: Draft<LiveState>, taskId: TaskId): Draft<CompactionStatus> | undefined {\n\treturn live.compactions?.find((status) => status.taskId === taskId);\n}\n\n/** Remove the status of compaction task `taskId`, and the list once empty. */\nexport function removeCompactionStatus(live: Draft<LiveState>, taskId: TaskId): void {\n\tconst statuses = live.compactions;\n\tif (statuses === undefined) return;\n\tconst index = statuses.findIndex((status) => status.taskId === taskId);\n\tif (index >= 0) statuses.splice(index, 1);\n\tif (statuses.length === 0) delete live.compactions;\n}\n\n/** Remove the status of compaction task `taskId` and record that it failed with `error`. */\nexport function failCompactionStatus(live: Draft<LiveState>, taskId: TaskId, error: string): void {\n\tconst status = compactionStatus(live, taskId);\n\tif (status !== undefined) live.compactionFailure = { taskId: status.taskId, trigger: status.trigger, error };\n\tremoveCompactionStatus(live, taskId);\n}\n\n/**\n * The slot of tool task `taskId`, model-issued or nested, if `pi.live` still lists it. Nested slots are found by binary\n * search: a tool may make thousands of nested calls, each of which looks up its slot in several commits, and every\n * element a search reads costs a node in the draft's change tracker. Their task IDs ascend: each slot is appended in\n * the commit that creates its task, task IDs ascend in commit order, and removal keeps the order.\n */\nexport function toolSlot(live: Draft<LiveState>, taskId: TaskId): Draft<ToolSlot | NestedToolSlot> | undefined {\n\tconst slot = live.tools?.find((each) => each.taskId === taskId);\n\tif (slot !== undefined || live.nestedTools === undefined) return slot;\n\tconst nested = live.nestedTools;\n\tlet low = 0;\n\tlet high = nested.length - 1;\n\twhile (low <= high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tconst candidate = nested[middle]!;\n\t\tif (candidate.taskId === taskId) return candidate;\n\t\tif (candidate.taskId < taskId) low = middle + 1;\n\t\telse high = middle - 1;\n\t}\n\treturn undefined;\n}\n\n/**\n * Mark a slot done and clear its running output; the caller sets a model-issued call's result `entry`, or a nested\n * call's `summary`. Neither is set when the task faulted or was orphaned.\n */\nexport function finishSlot(slot: Draft<ToolSlot | NestedToolSlot>): void {\n\tslot.status = \"done\";\n\tclearProgress(slot);\n}\n\n/** Remove the nested slots below tool task `taskId`, transitively; the list holds parents before their children. */\nexport function removeNestedSlots(live: Draft<LiveState>, taskId: TaskId): void {\n\tconst nested = live.nestedTools;\n\tif (nested === undefined) return;\n\tconst removed = new Set<TaskId>([taskId]);\n\tfor (const slot of nested) if (removed.has(slot.parentTaskId)) removed.add(slot.taskId);\n\tfor (let index = nested.length - 1; index >= 0; index--) {\n\t\tif (removed.has(nested[index]!.parentTaskId)) nested.splice(index, 1);\n\t}\n\tif (nested.length === 0) delete live.nestedTools;\n}\n\n/** Remove what a tool published while running; its result entry or a rerun replaces it. */\nexport function clearProgress(slot: Draft<SlotProgress>): void {\n\tdelete slot.output;\n\tdelete slot.droppedBytes;\n\tdelete slot.droppedLines;\n\tdelete slot.details;\n\tdelete slot.diagnostics;\n}\n\n/**\n * Harness cleanup for a terminal outcome the scheduler writes itself (`faulted` or `orphaned`). A run task ends its\n * run; a tool task's slot is marked done without an entry, and context derivation synthesizes the missing result; a\n * compaction task's status is removed and its failure recorded.\n * Ignores other kinds so it never creates `pi.live` elsewhere. The scheduler calls this without knowing task kinds;\n * the Harness passes it in (spec §5.4).\n * REMINDER: a committed generation partial becomes an aborted assistant entry here, exactly as in the generation abort\n * handler, so the transcript keeps what the model produced and `pi.usage` counts its spend. The scheduler's commit has\n * no task scope, so that entry has no `byTaskId`. Faults come from task bugs\n * or malformed provider data (a non-JSON value in a response), or a commit the Storage rejected without effect; an\n * uncertain storage failure poisons the Session instead and writes no outcome.\n */\nexport async function settleSchedulerOutcome(\n\ttx: Transaction,\n\trecord: TaskRecord<JsonValue, JsonValue, JsonValue>,\n\toutcome: SchedulerOutcome,\n): Promise<void> {\n\tif (record.kind === TOOL_TASK_KIND) {\n\t\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\t\tconst slot = toolSlot(live, record.id);\n\t\tif (slot !== undefined) finishSlot(slot);\n\t\tremoveNestedSlots(live, record.id);\n\t\treturn;\n\t}\n\t// Only an abort handler is faulted for the limit here (the built-in phases end themselves): the task was aborted,\n\t// and keeps that meaning. Its run ends `aborted`, with the limit as detail, and an aborted compaction is no failure.\n\tconst detail = outcome.status === \"faulted\" ? outcome.error.detail : undefined;\n\tconst cutOff =\n\t\ttypeof detail === \"object\" && detail !== null && \"reason\" in detail && detail.reason === \"restart_limit\";\n\tif (record.kind === COMPACTION_TASK_KIND) {\n\t\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\t\tif (cutOff) removeCompactionStatus(live, record.id);\n\t\telse failCompactionStatus(live, record.id, outcome.status === \"faulted\" ? outcome.error.message : outcome.reason);\n\t\treturn;\n\t}\n\tif (!RUN_TASK_KINDS.has(record.kind)) return;\n\tconst live = await tx.doc(LiveDoc, record.conversationId);\n\tif (live.run?.taskId !== record.id) return;\n\t// Cut off, the abort handler may have died converting the partial: the run ends without it.\n\tif (!cutOff) await convertPartial(tx, live, record.conversationId);\n\tendRun(\n\t\ttx,\n\t\tlive,\n\t\trecord.id,\n\t\toutcome.status === \"faulted\"\n\t\t\t? { status: \"unanswered\", reason: cutOff ? \"aborted\" : \"faulted\", detail: outcome.error.message }\n\t\t\t: {\n\t\t\t\t\tstatus: \"unanswered\",\n\t\t\t\t\treason: \"orphaned\",\n\t\t\t\t\tdetail: outcome.reason,\n\t\t\t\t\tsettlement: { status: \"unanswered\", reason: outcome.reason },\n\t\t\t\t},\n\t);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { JsonRepresentation } from "@earendil-works/chord";
|
|
2
1
|
import { type Draft } from "@earendil-works/chord/delta";
|
|
2
|
+
import type { JsonRepresentation } from "@earendil-works/chord/json";
|
|
3
3
|
import type { AssistantMessage, AssistantMessageEvent, ToolCall } from "@earendil-works/pi-ai";
|
|
4
4
|
import { type JsonChange } from "@earendil-works/pi-ai/utils/streaming-json";
|
|
5
5
|
import { type AssignPlan } from "./json.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"partial-changes.d.ts","sourceRoot":"","sources":["../../src/harness/partial-changes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"partial-changes.d.ts","sourceRoot":"","sources":["../../src/harness/partial-changes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAc,KAAK,KAAK,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAAa,MAAM,4BAA4B,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAC/F,OAAO,EAAE,KAAK,UAAU,EAAuB,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,KAAK,UAAU,EAAc,MAAM,WAAW,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAI3C,kEAAkE;AAClE,MAAM,MAAM,cAAc,GAAG,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;AAElE,mDAAmD;AACnD,KAAK,SAAS,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC,CAAC;AAE3D,uGAAuG;AACvG,MAAM,MAAM,aAAa,GAAG;IAC3B,+GAA+G;IAC/G,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,uHAAuH;IACvH,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAC;CACnH,CAAC;AAKF;;;;;;;;;;;;GAYG;AACH,qBAAa,cAAc;;IAI1B,mCAAmC;IACnC,OAAO,CAAC,KAAK,EAAE,qBAAqB,GAAG,IAAI,CAsC1C;IAED;;;OAGG;IACH,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,aAAa,CAoB3C;IAED;;;;;OAKG;IACH,MAAM,CACL,UAAU,EAAE,KAAK,CAAC,WAAW,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,EACvD,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,aAAa,GACnB,IAAI,CAuBN;IAED,+EAA+E;IAC/E,OAAO,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CAKnC;CACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// What a streamed answer changed in its partial message between two partial commits, so a commit costs the new text.
|
|
1
2
|
import { appendText } from "@earendil-works/chord/delta";
|
|
2
3
|
import { StreamingJsonParser } from "@earendil-works/pi-ai/utils/streaming-json";
|
|
3
4
|
import { assignJson } from "./json.js";
|