@robota-sdk/agent-session 3.0.6 → 3.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-claims-D-Azmxq6.js","names":["#live","#lent","#words","#ownProcess","#heldRefusal"],"sources":["../src/session-record-codec/decode-outcome.ts","../src/session-record-codec/scalars.ts","../src/session-record-codec/pending-execution-decoder.ts","../src/session-record-codec/message-decoders.ts","../src/session-record-codec/background-task-members.ts","../src/session-record-codec/background-group-decoders.ts","../src/session-record-codec/background-task-decoders.ts","../src/session-record-codec/background-task-event-decoders.ts","../src/session-record-codec/event-decoders.ts","../src/session-record-codec/goal-plan-branch-decoders.ts","../src/session-record-codec/session-loop-decoders.ts","../src/session-record-codec/tool-schema-decoders.ts","../src/session-record-codec/record-optional-members.ts","../src/session-record-codec/record-decoder.ts","../src/session-id.ts","../src/session-log-events.ts","../src/session-log-sinks.ts","../src/session-log-codec/field-decoders.ts","../src/session-log-codec/payload-shapes.ts","../src/session-log-codec/index.ts","../src/external-payload-resolution-contracts.ts","../src/sealed-session-refusal.ts","../src/session-claims.ts"],"sourcesContent":["/**\n * TRANS-005 (#2081) — the outcome vocabulary the session-record decoder answers in.\n *\n * ## Why an outcome and not an exception or `undefined`\n *\n * The defect this codec replaces is a store that answers \"is this a valid record?\" by returning\n * `undefined`, which its caller then reads as \"no such session\" and repairs by replaying a partial\n * reconstruction. Corruption and absence became the same answer, and the repair silently dropped\n * fields. A type that cannot spell that confusion is the fix: this outcome distinguishes a value\n * that failed to decode (`corrupt`) from one written by a build this one does not implement\n * (`unsupported`), and deliberately has NO `missing` member.\n *\n * `missing` is a property of a STORE, not of a value — a file that is not there never reaches a\n * decoder. The store composes its own `missing` with these three.\n */\n\nimport type {\n IInteractiveSessionRecord,\n ISessionRecordDecodeIssue,\n} from '@robota-sdk/agent-interface-session';\n\n/**\n * What a decode of a persisted session record can conclude.\n *\n * `corrupt` and `unsupported` carry an optional `cwd`: a best-effort, untyped read of the raw value\n * for a plain `cwd` string, taken even though the rest of the value failed full decode. It exists so\n * a caller that only wants to know which workspace an unreadable record belongs to — never its\n * content — is not forced to treat every one of them as workspace-unknown.\n */\nexport type TSessionRecordDecodeOutcome =\n | { readonly status: 'valid'; readonly record: IInteractiveSessionRecord }\n | {\n readonly status: 'corrupt';\n readonly issues: readonly ISessionRecordDecodeIssue[];\n readonly cwd?: string;\n }\n | { readonly status: 'unsupported'; readonly schemaVersion: number | undefined; readonly cwd?: string };\n\n/**\n * Re-stated for readers of this module: `ISessionRecordDecodeIssue` is declared with the record it\n * describes, in the contract package (TRANS-007). The TYPE is a contract; this module owns the\n * MECHANISM that produces it.\n */\n\n/**\n * The accumulator a decode pass writes into.\n *\n * Every decoder takes it and appends; none of them returns early on the first failure, so one call\n * reports the whole shape of the damage rather than the first symptom of it.\n */\nexport type TDecodeIssues = ISessionRecordDecodeIssue[];\n\n/** `messages` + `id` → `messages.id`; a root-level key keeps its bare name. */\nexport function atKey(parent: string, key: string): string {\n return parent.length === 0 ? key : `${parent}.${key}`;\n}\n\n/** `messages` + `2` → `messages[2]`. */\nexport function atIndex(parent: string, index: number): string {\n return `${parent}[${index}]`;\n}\n\nexport function addIssue(issues: TDecodeIssues, path: string, message: string): void {\n issues.push({ path, message });\n}\n\n/**\n * A short, non-throwing description of what was actually found, for the human half of an issue.\n *\n * It names the KIND rather than printing the value: a session record carries prompts and tool\n * output, and an error string is exactly the kind of thing that ends up in a log.\n */\nexport function describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n if (value instanceof Date) return 'a Date';\n switch (typeof value) {\n case 'undefined':\n return 'nothing';\n case 'string':\n return 'a string';\n case 'number':\n return 'a number';\n case 'boolean':\n return 'a boolean';\n case 'object':\n return 'an object';\n default:\n return `a ${typeof value}`;\n }\n}\n\n/**\n * Assign an optional member only when it decoded to a value.\n *\n * Writing `undefined` instead would make an absent member present-and-undefined, which survives\n * `JSON.stringify` as an omission but not as an identity — a decoded record must be the same shape\n * as the one that was persisted, not a wider one.\n */\nexport function setOptional<TTarget extends object, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined,\n): void {\n if (value !== undefined) target[key] = value;\n}\n","/**\n * TRANS-005 (#2081) — the leaf decoders every nested session-record decoder is built from.\n *\n * Each one takes the raw value, the path it sits at, and the issue accumulator; each returns the\n * decoded value or `undefined` after recording why. `undefined` is NOT \"the field was absent\" — an\n * absent optional member is handled by {@link decodeOptional}, and the caller decides validity by\n * asking whether any issue was recorded, never by testing a return value.\n */\n\nimport { addIssue, atIndex, atKey, describeValue } from './decode-outcome.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\nimport type { TBackgroundPrimitive } from '@robota-sdk/agent-interface-execution';\n\n/** Decode an optional member: absent stays absent, present is decoded, `null` is a defect. */\nexport function decodeOptional<TValue>(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n decode: (value: unknown, path: string, issues: TDecodeIssues) => TValue | undefined,\n): TValue | undefined {\n if (value === undefined) return undefined;\n return decode(value, path, issues);\n}\n\nexport function decodeString(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): string | undefined {\n if (typeof value === 'string') return value;\n addIssue(issues, path, `expected a string, received ${describeValue(value)}`);\n return undefined;\n}\n\nexport function decodeNumber(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n addIssue(issues, path, `expected a finite number, received ${describeValue(value)}`);\n return undefined;\n}\n\nexport function decodeInteger(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): number | undefined {\n if (typeof value === 'number' && Number.isInteger(value)) return value;\n addIssue(issues, path, `expected an integer, received ${describeValue(value)}`);\n return undefined;\n}\n\nexport function decodeBoolean(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): boolean | undefined {\n if (typeof value === 'boolean') return value;\n addIssue(issues, path, `expected a boolean, received ${describeValue(value)}`);\n return undefined;\n}\n\n/** Decode a flag the contract declares as the literal `true`: present means true, `false` is a defect. */\nexport function decodeTrue(value: unknown, path: string, issues: TDecodeIssues): true | undefined {\n if (value === true) return true;\n addIssue(issues, path, `expected true, received ${describeValue(value)}`);\n return undefined;\n}\n\n/** Decode a member of a string-literal union, naming the permitted members when it is not one. */\nexport function decodeLiteral<TLiteral extends string>(\n value: unknown,\n allowed: readonly TLiteral[],\n path: string,\n issues: TDecodeIssues,\n): TLiteral | undefined {\n if (typeof value === 'string' && (allowed as readonly string[]).includes(value)) {\n return value as TLiteral;\n }\n addIssue(\n issues,\n path,\n `expected one of ${allowed.join(' | ')}, received ${describeValue(value)}`,\n );\n return undefined;\n}\n\n/**\n * Decode a member the contract declares `string` but means as an instant.\n *\n * It stays a string — the contract says so — but must be one a date can be read from, because the\n * session list is ordered by `new Date(updatedAt).getTime()` and an unparseable string sorts as\n * `NaN`, which is an unstable order rather than an error anyone sees.\n *\n * ## The limit, stated because a caller will otherwise over-read it\n *\n * This accepts whatever `Date.parse` accepts, which is wider than ISO-8601: `'2026'` parses, and so\n * do several implementation-defined forms. So the guarantee is exactly \"a date can be read from\n * this\", NOT \"this is a well-formed instant\" — a record carrying `'2026'` decodes, and reads back as\n * midnight on the first of January.\n *\n * Tightening it to strict ISO-8601 is deliberately NOT done here: the contract these members belong\n * to declares them `string` and says nothing about their format, and a decoder that refuses a value\n * its own contract permits is inventing a stricter contract than the one it decodes. A consumer that\n * needs a well-formed instant validates for itself; this one guarantees only that ordering by date\n * will not silently produce `NaN`.\n */\nexport function decodeTimestampString(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): string | undefined {\n if (typeof value !== 'string') {\n addIssue(\n issues,\n path,\n `expected an ISO-8601 timestamp string, received ${describeValue(value)}`,\n );\n return undefined;\n }\n if (Number.isNaN(Date.parse(value))) {\n addIssue(issues, path, 'expected a timestamp a date can be parsed from');\n return undefined;\n }\n return value;\n}\n\n/**\n * Decode a member the contract declares `Date`.\n *\n * JSON has no date type, so a persisted `Date` arrives as a string and every consumer that calls a\n * `Date` method on it fails at the call rather than at the load. This is the one place that gap is\n * closed: an ISO-8601 string OR a live `Date` decodes to a `Date`, and nothing else does.\n */\nexport function decodeDate(value: unknown, path: string, issues: TDecodeIssues): Date | undefined {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n addIssue(issues, path, 'expected a valid Date, received an invalid one');\n return undefined;\n }\n return value;\n }\n if (typeof value === 'string' && !Number.isNaN(Date.parse(value))) return new Date(value);\n addIssue(\n issues,\n path,\n `expected a Date or an ISO-8601 timestamp string, received ${describeValue(value)}`,\n );\n return undefined;\n}\n\n/** Decode an array, decoding each element at its own indexed path. */\nexport function decodeArray<TItem>(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n decodeItem: (value: unknown, path: string, issues: TDecodeIssues) => TItem | undefined,\n): TItem[] | undefined {\n if (!Array.isArray(value)) {\n addIssue(issues, path, `expected an array, received ${describeValue(value)}`);\n return undefined;\n }\n const decoded: TItem[] = [];\n value.forEach((item, index) => {\n const element = decodeItem(item, atIndex(path, index), issues);\n if (element !== undefined) decoded.push(element);\n });\n return decoded;\n}\n\nexport function decodeStringArray(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): string[] | undefined {\n return decodeArray(value, path, issues, decodeString);\n}\n\n/**\n * Decode an object whose members are DECLARED, rejecting any key the contract does not name.\n *\n * A persisted record is written by this build's own code at a known version, so an unrecognised key\n * means the shape drifted — which is what the envelope version exists to report. Silently ignoring\n * it is how a field goes missing without anyone learning that it did.\n */\nexport function decodeDeclaredObject(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n declaredKeys: readonly string[],\n): Record<string, unknown> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n addIssue(issues, path, `expected an object, received ${describeValue(value)}`);\n return undefined;\n }\n const record = value as Record<string, unknown>;\n const declared = new Set(declaredKeys);\n for (const key of Object.keys(record)) {\n if (!declared.has(key)) {\n addIssue(issues, atKey(path, key), 'unknown key; the record contract does not declare it');\n }\n }\n return record;\n}\n\n/**\n * Decode a map the contract leaves OPEN — `metadata`, `data`, a schema's `properties`.\n *\n * The key set is the author's, not the contract's, so an unrecognised key here is data rather than\n * drift. Only the VALUES are constrained.\n */\nexport function decodeOpenMap<TValue>(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n decodeValue: (value: unknown, path: string, issues: TDecodeIssues) => TValue | undefined,\n): Record<string, TValue> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n addIssue(issues, path, `expected an object, received ${describeValue(value)}`);\n return undefined;\n }\n const decoded: Record<string, TValue> = {};\n for (const [key, member] of Object.entries(value as Record<string, unknown>)) {\n const element = decodeValue(member, atKey(path, key), issues);\n if (element !== undefined) Object.defineProperty(decoded, key, { value: element, enumerable: true, writable: true, configurable: true });\n }\n return decoded;\n}\n\n/**\n * Decode a value on the universal payload axis.\n *\n * `TUniversalValue` admits `Date`, and inside an open map a persisted date is a string that cannot\n * be told from any other string. Reviving by shape would turn a user's date-like text into a `Date`,\n * so this decoder does not revive: through persistence, that member of the axis is unreachable. A\n * live `Date` handed in from memory is still accepted.\n */\nexport function decodeUniversalValue(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TUniversalValue | undefined {\n if (value === null || value instanceof Date) return value;\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n if (Array.isArray(value)) {\n const decoded: TUniversalValue[] = [];\n value.forEach((item, index) => {\n const element = decodeUniversalValue(item, atIndex(path, index), issues);\n if (element !== undefined) decoded.push(element);\n });\n return decoded;\n }\n if (typeof value === 'object') {\n return decodeOpenMap(value, path, issues, decodeUniversalValue);\n }\n addIssue(issues, path, `expected a JSON-compatible value, received ${describeValue(value)}`);\n return undefined;\n}\n\nexport function decodeBackgroundPrimitive(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundPrimitive | undefined {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n addIssue(issues, path, `expected a string, number or boolean, received ${describeValue(value)}`);\n return undefined;\n}\n","import type { ISessionPendingExecution } from '@robota-sdk/agent-interface-session';\nimport type { IToolWaitRequest, TToolParameters, TUniversalMessage } from '@robota-sdk/agent-core';\nimport { addIssue, atKey } from './decode-outcome.js';\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport {\n decodeArray,\n decodeDeclaredObject,\n decodeOpenMap,\n decodeString,\n decodeUniversalValue,\n} from './scalars.js';\n\nfunction nonempty(value: unknown, path: string, issues: TDecodeIssues): string | undefined {\n const text = decodeString(value, path, issues);\n if (text !== undefined && text.trim().length > 0) return text;\n if (text !== undefined) addIssue(issues, path, 'expected a nonempty identity');\n return undefined;\n}\nfunction finiteJson(value: unknown, seen = new Set<object>()): boolean {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object' || value instanceof Date || seen.has(value)) return false;\n if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;\n seen.add(value);\n const valid = (Array.isArray(value) ? value : Object.values(value)).every((child) =>\n finiteJson(child, seen),\n );\n seen.delete(value);\n return valid;\n}\nfunction decodeWait(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IToolWaitRequest | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'executionId',\n 'actionId',\n 'parentCallId',\n 'toolCallId',\n 'toolName',\n 'requestId',\n 'kind',\n 'data',\n ]);\n if (!raw) return undefined;\n const executionId = nonempty(raw.executionId, atKey(path, 'executionId'), issues);\n const actionId = nonempty(raw.actionId, atKey(path, 'actionId'), issues);\n const parentCallId = nonempty(raw.parentCallId, atKey(path, 'parentCallId'), issues);\n const toolCallId = nonempty(raw.toolCallId, atKey(path, 'toolCallId'), issues);\n const toolName = nonempty(raw.toolName, atKey(path, 'toolName'), issues);\n const requestId = nonempty(raw.requestId, atKey(path, 'requestId'), issues);\n const kind = nonempty(raw.kind, atKey(path, 'kind'), issues);\n if (!finiteJson(raw.data)) {\n addIssue(issues, atKey(path, 'data'), 'expected finite JSON');\n return undefined;\n }\n const data: TToolParameters | undefined = decodeOpenMap(\n raw.data,\n atKey(path, 'data'),\n issues,\n decodeUniversalValue,\n );\n if (\n executionId === undefined ||\n actionId === undefined ||\n parentCallId === undefined ||\n toolCallId === undefined ||\n toolName === undefined ||\n requestId === undefined ||\n kind === undefined ||\n data === undefined\n )\n return undefined;\n return { executionId, actionId, parentCallId, toolCallId, toolName, requestId, kind, data };\n}\nexport function decodePendingExecution(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): ISessionPendingExecution | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['executionId', 'requests']);\n if (!raw) return undefined;\n const executionId = nonempty(raw.executionId, atKey(path, 'executionId'), issues);\n const requests = decodeArray(raw.requests, atKey(path, 'requests'), issues, decodeWait);\n if (executionId === undefined || requests === undefined) return undefined;\n return { executionId, requests };\n}\n/** Validate discovery against the terminal open round; this grants no journal authority. */\nexport function validatePendingExecution(\n pending: ISessionPendingExecution,\n messages: readonly TUniversalMessage[],\n issues: TDecodeIssues,\n path = 'pendingExecution',\n): void {\n const index = messages.findLastIndex((message) => message.role === 'assistant');\n const assistant = messages[index];\n if (\n assistant?.role !== 'assistant' ||\n assistant.metadata?.executionId !== pending.executionId ||\n !messages.slice(index + 1).every((message) => message.role === 'tool')\n ) {\n addIssue(issues, path, 'pending execution must match the terminal assistant round');\n return;\n }\n const calls = new Map((assistant.toolCalls ?? []).map((call) => [call.id, call]));\n if (calls.size !== assistant.toolCalls?.length) addIssue(issues, path, 'tool call identities must be unique within a round');\n const receipts = messages.slice(index + 1).flatMap((message) => message.role === 'tool' ? [message] : []);\n const receiptIds = new Set<string>();\n for (const message of receipts) {\n const call = calls.get(message.toolCallId);\n if (!call || receiptIds.has(message.toolCallId) || (message.name !== undefined && message.name !== call.function.name)) addIssue(issues, path, 'terminal receipts must uniquely bind this round');\n receiptIds.add(message.toolCallId);\n }\n const answered = new Set(\n messages\n .slice(index + 1)\n .flatMap((message) => (message.role === 'tool' ? [message.toolCallId] : [])),\n );\n const open = new Map(\n (assistant.toolCalls ?? [])\n .filter((call) => !answered.has(call.id))\n .map((call) => [call.id, call]),\n );\n if (open.size === 0) addIssue(issues, path, 'pending execution requires unanswered calls');\n const ids = new Set<string>();\n const actions = new Map<string, string>();\n const callActions = new Map<string, string>();\n for (const request of pending.requests) {\n const call = open.get(request.toolCallId);\n const binding = JSON.stringify([request.parentCallId, request.toolCallId, request.toolName]);\n if (\n ids.has(request.requestId) ||\n request.executionId !== pending.executionId ||\n request.parentCallId !== assistant.metadata?.providerCallId ||\n !call ||\n call.function.name !== request.toolName ||\n (actions.has(request.actionId) && actions.get(request.actionId) !== binding) ||\n (callActions.has(request.toolCallId) && callActions.get(request.toolCallId) !== request.actionId)\n ) {\n addIssue(issues, path, 'wait identities must uniquely bind an open tool action');\n }\n ids.add(request.requestId);\n actions.set(request.actionId, binding);\n callActions.set(request.toolCallId, request.actionId);\n }\n}\n","/**\n * TRANS-005 (#2081) — decoders for the conversation half of a persisted session record:\n * message parts, tool calls, the four `TUniversalMessage` variants, and history entries.\n *\n * The message variants are discriminated by `role`, and each variant declares its OWN key set — a\n * `toolCallId` on a user message is a defect, not a spare field, because only the tool variant\n * declares one.\n */\n\nimport { addIssue, atKey, describeValue, setOptional } from './decode-outcome.js';\nimport {\n decodeArray,\n decodeDate,\n decodeLiteral,\n decodeDeclaredObject,\n decodeOpenMap,\n decodeOptional,\n decodeNumber,\n decodeString,\n decodeUniversalValue,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IHistoryEntry,\n ISystemMessage,\n IToolCall,\n IUserMessage,\n TMessageState,\n TUniversalMessage,\n TUniversalMessageMetadata,\n TUniversalMessagePart,\n} from '@robota-sdk/agent-core';\n\nconst MESSAGE_STATES = ['complete', 'interrupted'] as const satisfies readonly TMessageState[];\n\nconst BASE_MESSAGE_KEYS = ['id', 'timestamp', 'state', 'metadata', 'role', 'content', 'parts'];\n\nconst MESSAGE_KEYS_BY_ROLE: Record<TUniversalMessage['role'], readonly string[]> = {\n user: [...BASE_MESSAGE_KEYS, 'name'],\n assistant: [...BASE_MESSAGE_KEYS, 'toolCalls'],\n system: [...BASE_MESSAGE_KEYS, 'name'],\n tool: [...BASE_MESSAGE_KEYS, 'toolCallId', 'name'],\n};\n\n/**\n * A metadata value: the declared union, checked member by member.\n *\n * `string[]`, `number[]` and `Record<string, number>` are distinguished by their contents rather\n * than by a tag, so a mixed array is a defect — the union has no member for it.\n */\nfunction decodeMetadataValue(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TUniversalMessageMetadata[string] | undefined {\n if (value instanceof Date) return value;\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n if (Array.isArray(value)) {\n if (value.every((item) => typeof item === 'string')) return value as string[];\n if (value.every((item) => typeof item === 'number')) return value as number[];\n addIssue(issues, path, 'expected an array of only strings or only numbers');\n return undefined;\n }\n if (typeof value === 'object' && value !== null) {\n return decodeOpenMap(value, path, issues, (member, memberPath, sink) => {\n if (typeof member === 'number') return member;\n addIssue(sink, memberPath, `expected a number, received ${describeValue(member)}`);\n return undefined;\n });\n }\n addIssue(issues, path, `expected a metadata value, received ${describeValue(value)}`);\n return undefined;\n}\n\nfunction decodeMetadata(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TUniversalMessageMetadata | undefined {\n return decodeOpenMap(value, path, issues, decodeMetadataValue);\n}\n\nfunction decodeMessagePart(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TUniversalMessagePart | undefined {\n const kind = decodeLiteral(\n (value as { type?: unknown } | null)?.type,\n ['text', 'image_inline', 'image_uri', 'audio_inline', 'resource_link', 'resource_embedded'],\n atKey(path, 'type'),\n issues,\n );\n if (kind === undefined) return undefined;\n\n if (kind === 'text') {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'text']);\n if (raw === undefined) return undefined;\n const text = decodeString(raw['text'], atKey(path, 'text'), issues);\n return text === undefined ? undefined : { type: 'text', text };\n }\n\n if (kind === 'image_inline' || kind === 'audio_inline') {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'mimeType', 'data']);\n if (raw === undefined) return undefined;\n const mimeType = decodeString(raw['mimeType'], atKey(path, 'mimeType'), issues);\n const data = decodeString(raw['data'], atKey(path, 'data'), issues);\n if (mimeType === undefined || data === undefined) return undefined;\n return { type: kind, mimeType, data };\n }\n\n if (kind === 'resource_link') {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'uri',\n 'name',\n 'mimeType',\n 'title',\n 'description',\n 'size',\n ]);\n if (raw === undefined) return undefined;\n const uri = decodeString(raw['uri'], atKey(path, 'uri'), issues);\n const name = decodeString(raw['name'], atKey(path, 'name'), issues);\n if (uri === undefined || name === undefined) return undefined;\n const part: Extract<TUniversalMessagePart, { type: 'resource_link' }> = {\n type: kind,\n uri,\n name,\n };\n for (const key of ['mimeType', 'title', 'description'] as const) {\n setOptional(part, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n const size = decodeOptional(raw['size'], atKey(path, 'size'), issues, decodeNumber);\n if (size !== undefined && (!Number.isSafeInteger(size) || size < 0)) {\n addIssue(issues, atKey(path, 'size'), 'expected a nonnegative safe integer');\n }\n setOptional(part, 'size', size);\n return part;\n }\n\n if (kind === 'resource_embedded') {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'uri',\n 'mimeType',\n 'text',\n 'blob',\n ]);\n if (raw === undefined) return undefined;\n const uri = decodeString(raw['uri'], atKey(path, 'uri'), issues);\n const mimeType = decodeOptional(raw['mimeType'], atKey(path, 'mimeType'), issues, decodeString);\n if (uri === undefined) return undefined;\n const identity = { type: kind, uri, ...(mimeType !== undefined ? { mimeType } : {}) };\n if (raw['text'] !== undefined && raw['blob'] === undefined) {\n const text = decodeString(raw['text'], atKey(path, 'text'), issues);\n return text === undefined ? undefined : { ...identity, text };\n }\n if (raw['blob'] !== undefined && raw['text'] === undefined) {\n const blob = decodeString(raw['blob'], atKey(path, 'blob'), issues);\n return blob === undefined ? undefined : { ...identity, blob };\n }\n addIssue(issues, path, 'expected exactly one text or blob payload');\n return undefined;\n }\n\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'uri', 'mimeType']);\n if (raw === undefined) return undefined;\n const uri = decodeString(raw['uri'], atKey(path, 'uri'), issues);\n if (uri === undefined) return undefined;\n const part: TUniversalMessagePart = { type: 'image_uri', uri };\n setOptional(\n part,\n 'mimeType',\n decodeOptional(raw['mimeType'], atKey(path, 'mimeType'), issues, decodeString),\n );\n return part;\n}\n\nfunction decodeToolCall(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IToolCall | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['id', 'type', 'function']);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const type = decodeLiteral(raw['type'], ['function'], atKey(path, 'type'), issues);\n const fnPath = atKey(path, 'function');\n const fn = decodeDeclaredObject(raw['function'], fnPath, issues, ['name', 'arguments']);\n const name =\n fn === undefined ? undefined : decodeString(fn['name'], atKey(fnPath, 'name'), issues);\n const args =\n fn === undefined\n ? undefined\n : decodeString(fn['arguments'], atKey(fnPath, 'arguments'), issues);\n if (id === undefined || type === undefined || name === undefined || args === undefined) {\n return undefined;\n }\n return { id, type, function: { name, arguments: args } };\n}\n\n/** Decode the members every message variant shares, into a partial the variant completes. */\nfunction decodeMessageBase(\n raw: Record<string, unknown>,\n path: string,\n issues: TDecodeIssues,\n): { id: string; timestamp: Date; state: TMessageState } | undefined {\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const timestamp = decodeDate(raw['timestamp'], atKey(path, 'timestamp'), issues);\n const state = decodeLiteral(raw['state'], MESSAGE_STATES, atKey(path, 'state'), issues);\n if (id === undefined || timestamp === undefined || state === undefined) return undefined;\n return { id, timestamp, state };\n}\n\nfunction applySharedOptionalMembers(\n message: TUniversalMessage,\n raw: Record<string, unknown>,\n path: string,\n issues: TDecodeIssues,\n): void {\n setOptional(\n message,\n 'metadata',\n decodeOptional(raw['metadata'], atKey(path, 'metadata'), issues, decodeMetadata),\n );\n setOptional(\n message,\n 'parts',\n decodeOptional(raw['parts'], atKey(path, 'parts'), issues, (value, partsPath, sink) =>\n decodeArray(value, partsPath, sink, decodeMessagePart),\n ),\n );\n}\n\nexport function decodeMessage(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TUniversalMessage | undefined {\n const role = decodeLiteral(\n (value as { role?: unknown } | null)?.role,\n ['user', 'assistant', 'system', 'tool'],\n atKey(path, 'role'),\n issues,\n );\n if (role === undefined) return undefined;\n\n const raw = decodeDeclaredObject(value, path, issues, MESSAGE_KEYS_BY_ROLE[role]);\n if (raw === undefined) return undefined;\n const base = decodeMessageBase(raw, path, issues);\n if (base === undefined) return undefined;\n const contentPath = atKey(path, 'content');\n\n if (role === 'assistant') {\n // The one variant whose content is nullable: an assistant turn that only calls tools has none.\n const content =\n raw['content'] === null ? null : decodeString(raw['content'], contentPath, issues);\n if (content === undefined) return undefined;\n const message: TUniversalMessage = { ...base, role, content };\n applySharedOptionalMembers(message, raw, path, issues);\n setOptional(\n message,\n 'toolCalls',\n decodeOptional(raw['toolCalls'], atKey(path, 'toolCalls'), issues, (value, callsPath, sink) =>\n decodeArray(value, callsPath, sink, decodeToolCall),\n ),\n );\n return message;\n }\n\n const content = decodeString(raw['content'], contentPath, issues);\n if (content === undefined) return undefined;\n\n if (role === 'tool') {\n const toolCallId = decodeString(raw['toolCallId'], atKey(path, 'toolCallId'), issues);\n if (toolCallId === undefined) return undefined;\n const message: TUniversalMessage = { ...base, role, content, toolCallId };\n applySharedOptionalMembers(message, raw, path, issues);\n setOptional(\n message,\n 'name',\n decodeOptional(raw['name'], atKey(path, 'name'), issues, decodeString),\n );\n return message;\n }\n\n // `role` is narrowed to `'user' | 'system'` here, and both variants declare `name` — the union of\n // the two is what makes that assignment checkable rather than a cast through the wider union.\n const message: IUserMessage | ISystemMessage = { ...base, role, content };\n applySharedOptionalMembers(message, raw, path, issues);\n setOptional(\n message,\n 'name',\n decodeOptional(raw['name'], atKey(path, 'name'), issues, decodeString),\n );\n return message;\n}\n\n/**\n * A history entry. `data` is declared `unknown` by the contract, so it is checked only for being a\n * JSON-compatible value — its key set belongs to whatever wrote the entry, not to this contract.\n */\nexport function decodeHistoryEntry(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IHistoryEntry | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'id',\n 'timestamp',\n 'category',\n 'type',\n 'data',\n ]);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const timestamp = decodeDate(raw['timestamp'], atKey(path, 'timestamp'), issues);\n const category = decodeString(raw['category'], atKey(path, 'category'), issues);\n const type = decodeString(raw['type'], atKey(path, 'type'), issues);\n if (id === undefined || timestamp === undefined || category === undefined || type === undefined) {\n return undefined;\n }\n const entry: IHistoryEntry = { id, timestamp, category, type };\n setOptional(\n entry,\n 'data',\n decodeOptional(raw['data'], atKey(path, 'data'), issues, decodeUniversalValue),\n );\n return entry;\n}\n","/**\n * TRANS-005 (#2081) — the member contracts a background-task state is built from: the literal\n * unions it selects from, its error, its result (with token usage), and its schedule.\n *\n * They live beside the state decoder rather than inside it because the task EVENT union carries the\n * same members, and one decoder per contract is the property this codec exists to establish.\n */\n\nimport { addIssue, atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeBackgroundPrimitive,\n decodeBoolean,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeOpenMap,\n decodeOptional,\n decodeString,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type { ITokenUsage } from '@robota-sdk/agent-core';\nimport type {\n IAgentBackgroundTaskResult,\n IBackgroundTaskDeniedToolCalls,\n IBackgroundTaskError,\n IBackgroundTaskResult,\n IBackgroundTaskSchedule,\n IProcessBackgroundTaskResult,\n IScheduledBackgroundTaskResult,\n IToolInvocationBackgroundTaskResult,\n TBackgroundPrimitive,\n TBackgroundTaskErrorCategory,\n TBackgroundTaskIsolation,\n TBackgroundTaskKind,\n TBackgroundTaskMode,\n TBackgroundTaskPermissionDenialReason,\n TBackgroundTaskStatus,\n TBackgroundTaskTimeoutReason,\n} from '@robota-sdk/agent-interface-execution';\n\nexport const TASK_KINDS = [\n 'agent',\n 'process',\n 'scheduled',\n // Contained — DATA-010.\n 'tool-invocation',\n] as const satisfies readonly TBackgroundTaskKind[];\nexport const TASK_MODES = [\n 'foreground',\n 'background',\n] as const satisfies readonly TBackgroundTaskMode[];\nexport const TASK_ISOLATIONS = [\n 'none',\n 'worktree',\n] as const satisfies readonly TBackgroundTaskIsolation[];\nexport const TASK_STATUSES = [\n 'queued',\n 'running',\n 'waiting_permission',\n 'sleeping',\n 'paused',\n 'completed',\n 'failed',\n 'cancelled',\n] as const satisfies readonly TBackgroundTaskStatus[];\nexport const TASK_TIMEOUT_REASONS = [\n 'idle',\n 'max_runtime',\n 'output_limit',\n 'repetition',\n 'stale_worker',\n] as const satisfies readonly TBackgroundTaskTimeoutReason[];\nconst TASK_ERROR_CATEGORIES = [\n 'validation',\n 'capacity',\n 'permission',\n 'timeout',\n 'runner',\n 'crash',\n 'provider',\n 'process',\n] as const satisfies readonly TBackgroundTaskErrorCategory[];\n/** Issue #3288 §1: mirrors the SSOT `TBackgroundTaskPermissionDenialReason` (`agent-interface-execution`). */\nconst TASK_PERMISSION_DENIAL_REASONS = [\n 'denied-by-person',\n 'no-approver',\n 'approver-error',\n 'cancelled',\n] as const satisfies readonly TBackgroundTaskPermissionDenialReason[];\n\nexport function decodePrimitiveMap(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): Record<string, TBackgroundPrimitive> | undefined {\n return decodeOpenMap(value, path, issues, decodeBackgroundPrimitive);\n}\n\nfunction decodeStringMap(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): Record<string, string> | undefined {\n return decodeOpenMap(value, path, issues, decodeString);\n}\n\nexport function decodeBackgroundTaskError(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundTaskError | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['category', 'message', 'recoverable']);\n if (raw === undefined) return undefined;\n const category = decodeLiteral(\n raw['category'],\n TASK_ERROR_CATEGORIES,\n atKey(path, 'category'),\n issues,\n );\n const message = decodeString(raw['message'], atKey(path, 'message'), issues);\n const recoverable = decodeBoolean(raw['recoverable'], atKey(path, 'recoverable'), issues);\n if (category === undefined || message === undefined || recoverable === undefined)\n return undefined;\n return { category, message, recoverable };\n}\n\nfunction decodeTokenUsage(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): ITokenUsage | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'promptTokens',\n 'completionTokens',\n 'totalTokens',\n ]);\n if (raw === undefined) return undefined;\n const promptTokens = decodeInteger(raw['promptTokens'], atKey(path, 'promptTokens'), issues);\n const completionTokens = decodeInteger(\n raw['completionTokens'],\n atKey(path, 'completionTokens'),\n issues,\n );\n const totalTokens = decodeInteger(raw['totalTokens'], atKey(path, 'totalTokens'), issues);\n if (promptTokens === undefined || completionTokens === undefined || totalTokens === undefined) {\n return undefined;\n }\n return { promptTokens, completionTokens, totalTokens };\n}\n\n/**\n * Issue #3288 §1: how many of a task's tool calls were refused, and why. Every reason key is\n * required — `child-process-subagent-runner-result.ts` always serializes the full count map, zeros\n * included, so a persisted `deniedToolCalls` missing one is drift, not an author's choice to omit it.\n */\nfunction decodeDeniedToolCalls(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundTaskDeniedToolCalls | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['total', 'byReason']);\n if (raw === undefined) return undefined;\n const total = decodeInteger(raw['total'], atKey(path, 'total'), issues);\n const byReasonPath = atKey(path, 'byReason');\n const byReasonRaw = decodeDeclaredObject(\n raw['byReason'],\n byReasonPath,\n issues,\n TASK_PERMISSION_DENIAL_REASONS,\n );\n if (total === undefined || byReasonRaw === undefined) return undefined;\n const byReason = {} as Record<TBackgroundTaskPermissionDenialReason, number>;\n let byReasonOk = true;\n for (const reason of TASK_PERMISSION_DENIAL_REASONS) {\n const count = decodeInteger(byReasonRaw[reason], atKey(byReasonPath, reason), issues);\n if (count === undefined) {\n byReasonOk = false;\n continue;\n }\n byReason[reason] = count;\n }\n if (!byReasonOk) return undefined;\n return { total, byReason };\n}\n\nexport function decodeBackgroundTaskResult(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundTaskResult | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'taskId',\n 'kind',\n 'output',\n 'exitCode',\n 'signalCode',\n 'metadata',\n 'usage',\n 'deniedToolCalls',\n ]);\n if (raw === undefined) return undefined;\n const taskId = decodeString(raw['taskId'], atKey(path, 'taskId'), issues);\n const kind = decodeLiteral(raw['kind'], TASK_KINDS, atKey(path, 'kind'), issues);\n const output = decodeString(raw['output'], atKey(path, 'output'), issues);\n if (taskId === undefined || kind === undefined || output === undefined) return undefined;\n const exitCode = decodeOptional(raw['exitCode'], atKey(path, 'exitCode'), issues, decodeInteger);\n const signalCode = decodeOptional(\n raw['signalCode'],\n atKey(path, 'signalCode'),\n issues,\n decodeString,\n );\n const metadata = decodeOptional(\n raw['metadata'],\n atKey(path, 'metadata'),\n issues,\n decodePrimitiveMap,\n );\n const usage = decodeOptional(raw['usage'], atKey(path, 'usage'), issues, decodeTokenUsage);\n const deniedToolCalls = decodeOptional(\n raw['deniedToolCalls'],\n atKey(path, 'deniedToolCalls'),\n issues,\n decodeDeniedToolCalls,\n );\n // #2079: `exitCode`/`signalCode` are process-only and `usage`/`deniedToolCalls` are agent-only — a\n // persisted result carrying a field outside its own kind is corrupt, reported the same way the\n // #3041 taskId/kind identity check is: an issue at the offending field's own path, not a thrown\n // error. The switch below then builds only the fields that belong to the decoded `kind`, so a\n // foreign field never reaches the returned object even though it was read (and flagged) above.\n if (kind !== 'process' && exitCode !== undefined) {\n addIssue(issues, atKey(path, 'exitCode'), `must not be set for a '${kind}' result`);\n }\n if (kind !== 'process' && signalCode !== undefined) {\n addIssue(issues, atKey(path, 'signalCode'), `must not be set for a '${kind}' result`);\n }\n if (kind !== 'agent' && usage !== undefined) {\n addIssue(issues, atKey(path, 'usage'), `must not be set for a '${kind}' result`);\n }\n if (kind !== 'agent' && deniedToolCalls !== undefined) {\n addIssue(issues, atKey(path, 'deniedToolCalls'), `must not be set for a '${kind}' result`);\n }\n switch (kind) {\n case 'process': {\n const result: IProcessBackgroundTaskResult = { taskId, kind, output };\n setOptional(result, 'exitCode', exitCode);\n setOptional(result, 'signalCode', signalCode);\n setOptional(result, 'metadata', metadata);\n return result;\n }\n case 'agent': {\n const result: IAgentBackgroundTaskResult = { taskId, kind, output };\n setOptional(result, 'metadata', metadata);\n setOptional(result, 'usage', usage);\n setOptional(result, 'deniedToolCalls', deniedToolCalls);\n return result;\n }\n case 'scheduled': {\n const result: IScheduledBackgroundTaskResult = { taskId, kind, output };\n setOptional(result, 'metadata', metadata);\n return result;\n }\n case 'tool-invocation': {\n const result: IToolInvocationBackgroundTaskResult = { taskId, kind, output };\n setOptional(result, 'metadata', metadata);\n return result;\n }\n }\n}\n\nexport function decodeBackgroundTaskSchedule(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundTaskSchedule | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'cronExpression',\n 'agentInstruction',\n 'command',\n 'shell',\n 'env',\n ]);\n if (raw === undefined) return undefined;\n const cronExpression = decodeString(raw['cronExpression'], atKey(path, 'cronExpression'), issues);\n if (cronExpression === undefined) return undefined;\n const schedule: IBackgroundTaskSchedule = { cronExpression };\n for (const key of ['agentInstruction', 'command', 'shell'] as const) {\n setOptional(schedule, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n setOptional(\n schedule,\n 'env',\n decodeOptional(raw['env'], atKey(path, 'env'), issues, decodeStringMap),\n );\n return schedule;\n}\n","/**\n * TRANS-005 (#2081) — the job-group half of the persisted background state: a group, the per-task\n * result envelopes it collects, and the three-variant group event union.\n *\n * A group's `results` are decoded even when the group is still `running`, because the array is\n * present from creation and a half-filled one is normal rather than a defect.\n */\n\nimport { TASK_STATUSES, decodeBackgroundTaskError } from './background-task-members.js';\nimport { atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeArray,\n decodeDeclaredObject,\n decodeLiteral,\n decodeOptional,\n decodeString,\n decodeStringArray,\n decodeTimestampString,\n decodeTrue,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IBackgroundJobGroupState,\n IBackgroundJobResultEnvelope,\n TBackgroundJobGroupEvent,\n TBackgroundJobGroupStatus,\n TBackgroundJobWaitPolicy,\n} from '@robota-sdk/agent-interface-execution';\n\nconst WAIT_POLICIES = [\n 'detached',\n 'wait_all',\n 'wait_any',\n 'manual',\n] as const satisfies readonly TBackgroundJobWaitPolicy[];\n\nconst GROUP_STATUSES = [\n 'running',\n 'completed',\n] as const satisfies readonly TBackgroundJobGroupStatus[];\n\nconst GROUP_EVENT_TYPES = [\n 'background_job_group_created',\n 'background_job_group_updated',\n 'background_job_group_completed',\n] as const;\n\nfunction decodeJobResultEnvelope(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundJobResultEnvelope | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'taskId',\n 'label',\n 'status',\n 'summary',\n 'outputRef',\n 'transcriptSealed',\n 'error',\n 'startedAt',\n 'completedAt',\n ]);\n if (raw === undefined) return undefined;\n const taskId = decodeString(raw['taskId'], atKey(path, 'taskId'), issues);\n const label = decodeString(raw['label'], atKey(path, 'label'), issues);\n const status = decodeLiteral(raw['status'], TASK_STATUSES, atKey(path, 'status'), issues);\n if (taskId === undefined || label === undefined || status === undefined) return undefined;\n const envelope: IBackgroundJobResultEnvelope = { taskId, label, status };\n for (const key of ['summary', 'outputRef'] as const) {\n setOptional(envelope, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n for (const key of ['startedAt', 'completedAt'] as const) {\n setOptional(\n envelope,\n key,\n decodeOptional(raw[key], atKey(path, key), issues, decodeTimestampString),\n );\n }\n setOptional(\n envelope,\n 'transcriptSealed',\n decodeOptional(raw['transcriptSealed'], atKey(path, 'transcriptSealed'), issues, decodeTrue),\n );\n setOptional(\n envelope,\n 'error',\n decodeOptional(raw['error'], atKey(path, 'error'), issues, decodeBackgroundTaskError),\n );\n return envelope;\n}\n\nexport function decodeJobGroupState(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundJobGroupState | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'id',\n 'parentSessionId',\n 'waitPolicy',\n 'taskIds',\n 'status',\n 'createdAt',\n 'updatedAt',\n 'label',\n 'completedAt',\n 'results',\n ]);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const parentSessionId = decodeString(\n raw['parentSessionId'],\n atKey(path, 'parentSessionId'),\n issues,\n );\n const waitPolicy = decodeLiteral(\n raw['waitPolicy'],\n WAIT_POLICIES,\n atKey(path, 'waitPolicy'),\n issues,\n );\n const taskIds = decodeStringArray(raw['taskIds'], atKey(path, 'taskIds'), issues);\n const status = decodeLiteral(raw['status'], GROUP_STATUSES, atKey(path, 'status'), issues);\n const createdAt = decodeTimestampString(raw['createdAt'], atKey(path, 'createdAt'), issues);\n const updatedAt = decodeTimestampString(raw['updatedAt'], atKey(path, 'updatedAt'), issues);\n const results = decodeArray(\n raw['results'],\n atKey(path, 'results'),\n issues,\n decodeJobResultEnvelope,\n );\n if (\n id === undefined ||\n parentSessionId === undefined ||\n waitPolicy === undefined ||\n taskIds === undefined ||\n status === undefined ||\n createdAt === undefined ||\n updatedAt === undefined ||\n results === undefined\n ) {\n return undefined;\n }\n const group: IBackgroundJobGroupState = {\n id,\n parentSessionId,\n waitPolicy,\n taskIds,\n status,\n createdAt,\n updatedAt,\n results,\n };\n setOptional(\n group,\n 'label',\n decodeOptional(raw['label'], atKey(path, 'label'), issues, decodeString),\n );\n setOptional(\n group,\n 'completedAt',\n decodeOptional(raw['completedAt'], atKey(path, 'completedAt'), issues, decodeTimestampString),\n );\n return group;\n}\n\nexport function decodeBackgroundJobGroupEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundJobGroupEvent | undefined {\n const type = decodeLiteral(\n (value as { type?: unknown } | null)?.type,\n GROUP_EVENT_TYPES,\n atKey(path, 'type'),\n issues,\n );\n if (type === undefined) return undefined;\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'group']);\n if (raw === undefined) return undefined;\n const group = decodeJobGroupState(raw['group'], atKey(path, 'group'), issues);\n return group === undefined ? undefined : { type, group };\n}\n","/**\n * TRANS-005 (#2081) — the background-task state decoder.\n *\n * The state carries thirteen optional plain-string members and four optional timestamp members.\n * They are decoded from key tables rather than written out one call at a time: a table is checked\n * against the contract by the key-parity test, whereas seventeen near-identical statements are\n * checked by whoever reads them.\n */\n\nimport {\n TASK_ISOLATIONS,\n TASK_KINDS,\n TASK_MODES,\n TASK_STATUSES,\n TASK_TIMEOUT_REASONS,\n decodeBackgroundTaskError,\n decodeBackgroundTaskResult,\n decodeBackgroundTaskSchedule,\n decodePrimitiveMap,\n} from './background-task-members.js';\nimport { addIssue, atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeBoolean,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeOptional,\n decodeString,\n decodeTimestampString,\n decodeTrue,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IAgentBackgroundTaskState,\n IBackgroundTaskState,\n IProcessBackgroundTaskState,\n IScheduledBackgroundTaskState,\n IToolInvocationBackgroundTaskState,\n} from '@robota-sdk/agent-interface-execution';\n\n/**\n * #2079: the base members shared by every kind — identical across the four discriminated members,\n * so `IAgentBackgroundTaskState` (any one member would do) is the source for their shape here.\n */\ntype TBaseBackgroundTaskState = Pick<\n IAgentBackgroundTaskState,\n | 'id'\n | 'label'\n | 'status'\n | 'mode'\n | 'parentSessionId'\n | 'parentTaskId'\n | 'depth'\n | 'cwd'\n | 'pid'\n | 'startedAt'\n | 'updatedAt'\n | 'lastActivityAt'\n | 'completedAt'\n | 'currentAction'\n | 'unread'\n | 'error'\n | 'logPath'\n | 'transcriptPath'\n | 'transcriptSealed'\n | 'timeoutReason'\n | 'metadata'\n>;\n\n/** Base string members every kind may carry (#2079: `logPath`/`transcriptPath`/`pid` are shared — see contracts). */\nconst BASE_OPTIONAL_STRING_KEYS = ['parentTaskId', 'currentAction', 'logPath', 'transcriptPath'] as const;\n/** #2079: agent-only string members — a value here on a non-agent task is a corrupt cross-kind field. */\nconst AGENT_OPTIONAL_STRING_KEYS = [\n 'agentType',\n 'resumeSessionId',\n 'promptPreview',\n 'worktreePath',\n 'branchName',\n 'worktreeStatus',\n 'worktreeNextAction',\n 'worktreeBaseRevision',\n 'parentWorktreeStatus',\n] as const;\n/** #2079: produced by every runner except the agent one (a process command, an MCP tool summary, a schedule's shell command / wake instruction). */\nconst NON_AGENT_OPTIONAL_STRING_KEYS = ['commandPreview'] as const;\n\nconst OPTIONAL_TIMESTAMP_KEYS = ['startedAt', 'lastActivityAt', 'completedAt'] as const;\n\nconst TASK_STATE_KEYS: readonly string[] = [\n 'id',\n 'kind',\n 'label',\n 'status',\n 'mode',\n 'parentSessionId',\n 'depth',\n 'cwd',\n 'pid',\n 'updatedAt',\n 'isolation',\n 'unread',\n 'result',\n 'error',\n 'timeoutReason',\n 'transcriptSealed',\n 'schedule',\n 'nextFireAt',\n 'metadata',\n ...BASE_OPTIONAL_STRING_KEYS,\n ...AGENT_OPTIONAL_STRING_KEYS,\n ...NON_AGENT_OPTIONAL_STRING_KEYS,\n ...OPTIONAL_TIMESTAMP_KEYS,\n];\n\n/**\n * TRANS-005 (#2081), discriminated by kind (#2079): the persisted state carries base members every\n * kind may set, plus a set of kind-exclusive members — agent-only (`agentType`, `isolation`,\n * `resumeSessionId`, `promptPreview`, the worktree-isolation fields), scheduled-only (`schedule`,\n * `nextFireAt`), or produced by every runner except the agent one (`commandPreview`). A value on a\n * field outside its own kind is reported as corrupt at that field's own path — exactly how\n * `decodeBackgroundTaskResult` (#2079) and the pre-existing `result.kind` check just below already\n * treat a cross-kind field — and the switch below then builds only the fields that belong to the\n * decoded `kind`, so a foreign field never reaches the returned object even though it was read (and\n * flagged) above.\n */\nexport function decodeBackgroundTaskState(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IBackgroundTaskState | undefined {\n const raw = decodeDeclaredObject(value, path, issues, TASK_STATE_KEYS);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const kind = decodeLiteral(raw['kind'], TASK_KINDS, atKey(path, 'kind'), issues);\n const label = decodeString(raw['label'], atKey(path, 'label'), issues);\n const status = decodeLiteral(raw['status'], TASK_STATUSES, atKey(path, 'status'), issues);\n const mode = decodeLiteral(raw['mode'], TASK_MODES, atKey(path, 'mode'), issues);\n const parentSessionId = decodeString(\n raw['parentSessionId'],\n atKey(path, 'parentSessionId'),\n issues,\n );\n const depth = decodeInteger(raw['depth'], atKey(path, 'depth'), issues);\n const cwd = decodeString(raw['cwd'], atKey(path, 'cwd'), issues);\n const updatedAt = decodeTimestampString(raw['updatedAt'], atKey(path, 'updatedAt'), issues);\n const unread = decodeBoolean(raw['unread'], atKey(path, 'unread'), issues);\n if (\n id === undefined ||\n kind === undefined ||\n label === undefined ||\n status === undefined ||\n mode === undefined ||\n parentSessionId === undefined ||\n depth === undefined ||\n cwd === undefined ||\n updatedAt === undefined ||\n unread === undefined\n ) {\n return undefined;\n }\n\n const base: TBaseBackgroundTaskState = {\n id,\n label,\n status,\n mode,\n parentSessionId,\n depth,\n cwd,\n updatedAt,\n unread,\n };\n for (const key of BASE_OPTIONAL_STRING_KEYS) {\n setOptional(base, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n for (const key of OPTIONAL_TIMESTAMP_KEYS) {\n setOptional(base, key, decodeOptional(raw[key], atKey(path, key), issues, decodeTimestampString));\n }\n setOptional(base, 'pid', decodeOptional(raw['pid'], atKey(path, 'pid'), issues, decodeInteger));\n setOptional(\n base,\n 'transcriptSealed',\n decodeOptional(raw['transcriptSealed'], atKey(path, 'transcriptSealed'), issues, decodeTrue),\n );\n setOptional(\n base,\n 'timeoutReason',\n decodeOptional(\n raw['timeoutReason'],\n atKey(path, 'timeoutReason'),\n issues,\n (member, memberPath, sink) => decodeLiteral(member, TASK_TIMEOUT_REASONS, memberPath, sink),\n ),\n );\n setOptional(\n base,\n 'metadata',\n decodeOptional(raw['metadata'], atKey(path, 'metadata'), issues, decodePrimitiveMap),\n );\n setOptional(\n base,\n 'error',\n decodeOptional(raw['error'], atKey(path, 'error'), issues, decodeBackgroundTaskError),\n );\n\n const result = decodeOptional(raw['result'], atKey(path, 'result'), issues, decodeBackgroundTaskResult);\n if (result !== undefined) {\n if (result.taskId !== id) {\n addIssue(issues, atKey(atKey(path, 'result'), 'taskId'), 'must match the task ID');\n }\n if (result.kind !== kind) {\n addIssue(issues, atKey(atKey(path, 'result'), 'kind'), 'must match the task kind');\n }\n }\n\n const agentType = decodeOptional(raw['agentType'], atKey(path, 'agentType'), issues, decodeString);\n const resumeSessionId = decodeOptional(\n raw['resumeSessionId'],\n atKey(path, 'resumeSessionId'),\n issues,\n decodeString,\n );\n const promptPreview = decodeOptional(\n raw['promptPreview'],\n atKey(path, 'promptPreview'),\n issues,\n decodeString,\n );\n const isolation = decodeOptional(\n raw['isolation'],\n atKey(path, 'isolation'),\n issues,\n (member, memberPath, sink) => decodeLiteral(member, TASK_ISOLATIONS, memberPath, sink),\n );\n const worktreeFields: Record<string, string | undefined> = {};\n for (const key of [\n 'worktreePath',\n 'branchName',\n 'worktreeStatus',\n 'worktreeNextAction',\n 'worktreeBaseRevision',\n 'parentWorktreeStatus',\n ] as const) {\n worktreeFields[key] = decodeOptional(raw[key], atKey(path, key), issues, decodeString);\n }\n for (const key of AGENT_OPTIONAL_STRING_KEYS) {\n const decodedValue =\n key === 'agentType'\n ? agentType\n : key === 'resumeSessionId'\n ? resumeSessionId\n : key === 'promptPreview'\n ? promptPreview\n : worktreeFields[key];\n if (kind !== 'agent' && decodedValue !== undefined) {\n addIssue(issues, atKey(path, key), `must not be set for a '${kind}' task`);\n }\n }\n if (kind !== 'agent' && isolation !== undefined) {\n addIssue(issues, atKey(path, 'isolation'), `must not be set for a '${kind}' task`);\n }\n\n const commandPreview = decodeOptional(\n raw['commandPreview'],\n atKey(path, 'commandPreview'),\n issues,\n decodeString,\n );\n if (kind === 'agent' && commandPreview !== undefined) {\n addIssue(issues, atKey(path, 'commandPreview'), `must not be set for a '${kind}' task`);\n }\n\n const schedule = decodeOptional(\n raw['schedule'],\n atKey(path, 'schedule'),\n issues,\n decodeBackgroundTaskSchedule,\n );\n const nextFireAt = decodeOptional(\n raw['nextFireAt'],\n atKey(path, 'nextFireAt'),\n issues,\n decodeTimestampString,\n );\n if (kind !== 'scheduled' && schedule !== undefined) {\n addIssue(issues, atKey(path, 'schedule'), `must not be set for a '${kind}' task`);\n }\n if (kind !== 'scheduled' && nextFireAt !== undefined) {\n addIssue(issues, atKey(path, 'nextFireAt'), `must not be set for a '${kind}' task`);\n }\n\n switch (kind) {\n case 'agent': {\n const correlatedResult = result?.kind === 'agent' ? result : undefined;\n const task: IAgentBackgroundTaskState = { ...base, kind };\n setOptional(task, 'result', correlatedResult);\n setOptional(task, 'agentType', agentType);\n setOptional(task, 'resumeSessionId', resumeSessionId);\n setOptional(task, 'promptPreview', promptPreview);\n setOptional(task, 'isolation', isolation);\n setOptional(task, 'worktreePath', worktreeFields['worktreePath']);\n setOptional(task, 'branchName', worktreeFields['branchName']);\n setOptional(task, 'worktreeStatus', worktreeFields['worktreeStatus']);\n setOptional(task, 'worktreeNextAction', worktreeFields['worktreeNextAction']);\n setOptional(task, 'worktreeBaseRevision', worktreeFields['worktreeBaseRevision']);\n setOptional(task, 'parentWorktreeStatus', worktreeFields['parentWorktreeStatus']);\n return task;\n }\n case 'process': {\n const correlatedResult = result?.kind === 'process' ? result : undefined;\n const task: IProcessBackgroundTaskState = { ...base, kind };\n setOptional(task, 'result', correlatedResult);\n setOptional(task, 'commandPreview', commandPreview);\n return task;\n }\n case 'tool-invocation': {\n const correlatedResult = result?.kind === 'tool-invocation' ? result : undefined;\n const task: IToolInvocationBackgroundTaskState = { ...base, kind };\n setOptional(task, 'result', correlatedResult);\n setOptional(task, 'commandPreview', commandPreview);\n return task;\n }\n case 'scheduled': {\n const correlatedResult = result?.kind === 'scheduled' ? result : undefined;\n const task: IScheduledBackgroundTaskState = { ...base, kind };\n setOptional(task, 'result', correlatedResult);\n setOptional(task, 'commandPreview', commandPreview);\n setOptional(task, 'schedule', schedule);\n setOptional(task, 'nextFireAt', nextFireAt);\n return task;\n }\n }\n}\n","/**\n * TRANS-005 (#2081) — the twelve-variant persisted background-task event union.\n *\n * The union is discriminated by `type`, and the discriminant is read FIRST: it selects the key set\n * the variant declares, so an event that names the wrong members fails on the members rather than on\n * the union. An unrecognised `type` is reported once, at `type`, instead of as a pile of\n * missing-member issues from whichever variant happened to be tried.\n */\n\nimport { decodeBackgroundTaskState } from './background-task-decoders.js';\nimport { decodePrimitiveMap } from './background-task-members.js';\nimport { atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeBoolean,\n decodeDeclaredObject,\n decodeLiteral,\n decodeOptional,\n decodeString,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type { TBackgroundTaskEvent } from '@robota-sdk/agent-interface-execution';\n\n/** The task-event variants whose entire payload is a task state. */\nconst TASK_CARRYING_EVENTS = [\n 'background_task_created',\n 'background_task_started',\n 'background_task_updated',\n 'background_task_completed',\n 'background_task_failed',\n 'background_task_cancelled',\n] as const;\n\nconst TASK_EVENT_TYPES = [\n ...TASK_CARRYING_EVENTS,\n 'background_task_text_delta',\n 'background_task_tool_start',\n 'background_task_tool_end',\n 'background_task_permission_request',\n 'background_task_closed',\n 'background_task_waking',\n] as const;\n\n/** Every variant but the six task-carrying ones names the task by id rather than by value. */\nfunction taskIdOf(\n raw: Record<string, unknown>,\n path: string,\n issues: TDecodeIssues,\n): string | undefined {\n return decodeString(raw['taskId'], atKey(path, 'taskId'), issues);\n}\n\ntype TTaskEventType = (typeof TASK_EVENT_TYPES)[number];\n\nfunction decodeTextDeltaEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'taskId', 'delta']);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n const delta = decodeString(raw['delta'], atKey(path, 'delta'), issues);\n if (taskId === undefined || delta === undefined) return undefined;\n return { type: 'background_task_text_delta', taskId, delta };\n}\n\nfunction decodeToolStartEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'taskId', 'toolName', 'firstArg']);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n const toolName = decodeString(raw['toolName'], atKey(path, 'toolName'), issues);\n if (taskId === undefined || toolName === undefined) return undefined;\n const event: TBackgroundTaskEvent = { type: 'background_task_tool_start', taskId, toolName };\n setOptional(\n event,\n 'firstArg',\n decodeOptional(raw['firstArg'], atKey(path, 'firstArg'), issues, decodeString),\n );\n return event;\n}\n\nfunction decodeToolEndEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'taskId',\n 'toolName',\n 'success',\n 'error',\n ]);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n const toolName = decodeString(raw['toolName'], atKey(path, 'toolName'), issues);\n const success = decodeBoolean(raw['success'], atKey(path, 'success'), issues);\n if (taskId === undefined || toolName === undefined || success === undefined) return undefined;\n const event: TBackgroundTaskEvent = {\n type: 'background_task_tool_end',\n taskId,\n toolName,\n success,\n };\n setOptional(\n event,\n 'error',\n decodeOptional(raw['error'], atKey(path, 'error'), issues, decodeString),\n );\n return event;\n}\n\nfunction decodePermissionRequestEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'taskId',\n 'requestId',\n 'toolName',\n 'toolArgs',\n ]);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n const requestId = decodeString(raw['requestId'], atKey(path, 'requestId'), issues);\n const toolName = decodeString(raw['toolName'], atKey(path, 'toolName'), issues);\n const toolArgs = decodePrimitiveMap(raw['toolArgs'], atKey(path, 'toolArgs'), issues);\n if (\n taskId === undefined ||\n requestId === undefined ||\n toolName === undefined ||\n toolArgs === undefined\n ) {\n return undefined;\n }\n return { type: 'background_task_permission_request', taskId, requestId, toolName, toolArgs };\n}\n\nfunction decodeClosedEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'taskId']);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n return taskId === undefined ? undefined : { type: 'background_task_closed', taskId };\n}\n\nfunction decodeWakingEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'taskId', 'instruction']);\n if (raw === undefined) return undefined;\n const taskId = taskIdOf(raw, path, issues);\n if (taskId === undefined) return undefined;\n const event: TBackgroundTaskEvent = { type: 'background_task_waking', taskId };\n setOptional(\n event,\n 'instruction',\n decodeOptional(raw['instruction'], atKey(path, 'instruction'), issues, decodeString),\n );\n return event;\n}\n\n/** A task-carrying variant: `{ type, task }`, where `task` is a whole task state. */\nfunction decodeTaskCarryingEvent(\n type: TTaskEventType,\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['type', 'task']);\n if (raw === undefined) return undefined;\n const task = decodeBackgroundTaskState(raw['task'], atKey(path, 'task'), issues);\n if (task === undefined) return undefined;\n return { type, task } as TBackgroundTaskEvent;\n}\n\n/** The variant decoders, keyed by discriminant — the dispatcher stays a lookup, not a ladder. */\nconst VARIANT_DECODERS: Partial<\n Record<\n TTaskEventType,\n (value: unknown, path: string, issues: TDecodeIssues) => TBackgroundTaskEvent | undefined\n >\n> = {\n background_task_text_delta: decodeTextDeltaEvent,\n background_task_tool_start: decodeToolStartEvent,\n background_task_tool_end: decodeToolEndEvent,\n background_task_permission_request: decodePermissionRequestEvent,\n background_task_closed: decodeClosedEvent,\n background_task_waking: decodeWakingEvent,\n};\n\nexport function decodeBackgroundTaskEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TBackgroundTaskEvent | undefined {\n const type = decodeLiteral(\n (value as { type?: unknown } | null)?.type,\n TASK_EVENT_TYPES,\n atKey(path, 'type'),\n issues,\n );\n if (type === undefined) return undefined;\n const decodeVariant = VARIANT_DECODERS[type];\n return decodeVariant === undefined\n ? decodeTaskCarryingEvent(type, value, path, issues)\n : decodeVariant(value, path, issues);\n}\n","/**\n * TRANS-005 (#2081) — decoders for the session-event payloads a record persists: skill activation,\n * automatic-memory events and their references, and context references.\n *\n * These contracts spell their instants as `string`, not `Date`, so they stay strings here — but they\n * are still checked as instants, because a member that reads as a timestamp and cannot be parsed as\n * one is a defect that only surfaces later, as an ordering that is quietly wrong.\n */\n\nimport { atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeBoolean,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeNumber,\n decodeOpenMap,\n decodeOptional,\n decodeString,\n decodeTimestampString,\n decodeUniversalValue,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IContextReferenceItem,\n IMemoryEvent,\n IMemoryReference,\n ISkillActivationEvent,\n TContextReferenceLoadType,\n TContextReferenceStatus,\n TSkillActivationInvocation,\n TSkillActivationMode,\n TSkillActivationSource,\n TSkillActivationStatus,\n} from '@robota-sdk/agent-interface-session';\n\nconst SKILL_SOURCES = ['skill', 'plugin'] as const satisfies readonly TSkillActivationSource[];\nconst SKILL_INVOCATIONS = [\n 'user-slash',\n 'model-tool',\n] as const satisfies readonly TSkillActivationInvocation[];\nconst SKILL_MODES = ['inject', 'fork'] as const satisfies readonly TSkillActivationMode[];\nconst SKILL_STATUSES = [\n 'started',\n 'completed',\n 'failed',\n] as const satisfies readonly TSkillActivationStatus[];\n\nconst MEMORY_EVENT_TYPES = [\n 'memory_candidate_extracted',\n 'memory_candidate_queued',\n 'memory_candidate_saved',\n 'memory_candidate_skipped',\n 'memory_candidate_approved',\n 'memory_candidate_rejected',\n 'memory_retrieved',\n] as const satisfies readonly IMemoryEvent['type'][];\n\nconst CONTEXT_LOAD_TYPES = [\n 'manual',\n 'prompt-reference',\n 'system',\n] as const satisfies readonly TContextReferenceLoadType[];\n\nconst CONTEXT_STATUSES = [\n 'active',\n 'observed',\n] as const satisfies readonly TContextReferenceStatus[];\n\nexport function decodeSkillActivationEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): ISkillActivationEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'skillName',\n 'source',\n 'invocation',\n 'mode',\n 'status',\n 'timestamp',\n 'qualifiedName',\n 'error',\n ]);\n if (raw === undefined) return undefined;\n const type = decodeLiteral(raw['type'], ['skill-activation'], atKey(path, 'type'), issues);\n const skillName = decodeString(raw['skillName'], atKey(path, 'skillName'), issues);\n const source = decodeLiteral(raw['source'], SKILL_SOURCES, atKey(path, 'source'), issues);\n const invocation = decodeLiteral(\n raw['invocation'],\n SKILL_INVOCATIONS,\n atKey(path, 'invocation'),\n issues,\n );\n const mode = decodeLiteral(raw['mode'], SKILL_MODES, atKey(path, 'mode'), issues);\n const status = decodeLiteral(raw['status'], SKILL_STATUSES, atKey(path, 'status'), issues);\n const timestamp = decodeTimestampString(raw['timestamp'], atKey(path, 'timestamp'), issues);\n if (\n type === undefined ||\n skillName === undefined ||\n source === undefined ||\n invocation === undefined ||\n mode === undefined ||\n status === undefined ||\n timestamp === undefined\n ) {\n return undefined;\n }\n const qualifiedName = decodeOptional(\n raw['qualifiedName'],\n atKey(path, 'qualifiedName'),\n issues,\n decodeString,\n );\n const error = decodeOptional(raw['error'], atKey(path, 'error'), issues, decodeString);\n // Every member is `readonly`, so the optional ones are spread in rather than assigned after.\n return {\n type,\n skillName,\n source,\n invocation,\n mode,\n status,\n timestamp,\n ...(qualifiedName === undefined ? {} : { qualifiedName }),\n ...(error === undefined ? {} : { error }),\n };\n}\n\nexport function decodeMemoryReference(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IMemoryReference | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['topic', 'path', 'score', 'truncated']);\n if (raw === undefined) return undefined;\n const topic = decodeString(raw['topic'], atKey(path, 'topic'), issues);\n const referencePath = decodeString(raw['path'], atKey(path, 'path'), issues);\n const score = decodeNumber(raw['score'], atKey(path, 'score'), issues);\n const truncated = decodeBoolean(raw['truncated'], atKey(path, 'truncated'), issues);\n if (\n topic === undefined ||\n referencePath === undefined ||\n score === undefined ||\n truncated === undefined\n ) {\n return undefined;\n }\n return { topic, path: referencePath, score, truncated };\n}\n\nexport function decodeMemoryEvent(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IMemoryEvent | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'type',\n 'at',\n 'candidateId',\n 'topic',\n 'reason',\n 'data',\n ]);\n if (raw === undefined) return undefined;\n const type = decodeLiteral(raw['type'], MEMORY_EVENT_TYPES, atKey(path, 'type'), issues);\n const at = decodeTimestampString(raw['at'], atKey(path, 'at'), issues);\n if (type === undefined || at === undefined) return undefined;\n const event: IMemoryEvent = { type, at };\n for (const key of ['candidateId', 'topic', 'reason'] as const) {\n setOptional(event, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n setOptional(\n event,\n 'data',\n decodeOptional(raw['data'], atKey(path, 'data'), issues, (member, memberPath, sink) =>\n decodeOpenMap(member, memberPath, sink, decodeUniversalValue),\n ),\n );\n return event;\n}\n\nexport function decodeContextReferenceItem(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IContextReferenceItem | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'id',\n 'sourcePath',\n 'relativePath',\n 'originalReference',\n 'loadType',\n 'status',\n 'byteLength',\n 'loadedAt',\n 'lastUsedAt',\n ]);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const sourcePath = decodeString(raw['sourcePath'], atKey(path, 'sourcePath'), issues);\n const relativePath = decodeString(raw['relativePath'], atKey(path, 'relativePath'), issues);\n const originalReference = decodeString(\n raw['originalReference'],\n atKey(path, 'originalReference'),\n issues,\n );\n const loadType = decodeLiteral(\n raw['loadType'],\n CONTEXT_LOAD_TYPES,\n atKey(path, 'loadType'),\n issues,\n );\n const status = decodeLiteral(raw['status'], CONTEXT_STATUSES, atKey(path, 'status'), issues);\n const byteLength = decodeInteger(raw['byteLength'], atKey(path, 'byteLength'), issues);\n const loadedAt = decodeTimestampString(raw['loadedAt'], atKey(path, 'loadedAt'), issues);\n if (\n id === undefined ||\n sourcePath === undefined ||\n relativePath === undefined ||\n originalReference === undefined ||\n loadType === undefined ||\n status === undefined ||\n byteLength === undefined ||\n loadedAt === undefined\n ) {\n return undefined;\n }\n const item: IContextReferenceItem = {\n id,\n sourcePath,\n relativePath,\n originalReference,\n loadType,\n status,\n byteLength,\n loadedAt,\n };\n setOptional(\n item,\n 'lastUsedAt',\n decodeOptional(raw['lastUsedAt'], atKey(path, 'lastUsedAt'), issues, decodeTimestampString),\n );\n return item;\n}\n","/**\n * TRANS-005 (#2081) — decoders for the three in-flight artifacts a session record persists so they\n * survive a resume: the autonomous goal, the plan artifact, and the active-branch pointer.\n *\n * The branch pointer is pure data by design — it names a `branchId`/`checkpointId` that live in a\n * separate manifest store, and a pointer into a manifest that no longer holds them is a RESUME\n * concern, not a decode one. This decoder therefore validates the pointer's shape and says nothing\n * about whether it resolves. A `null` `checkpointId` is a head cleared on purpose.\n */\n\nimport { atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeArray,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeOptional,\n decodeString,\n decodeTimestampString,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IActiveBranchPointer,\n IGoalProgressEntry,\n IGoalState,\n IPlanArtifact,\n IPlanStep,\n TGoalStatus,\n TGoalStopReason,\n TPlanPhase,\n TPlanStepStatus,\n} from '@robota-sdk/agent-interface-session';\n\nconst GOAL_STATUSES = ['active', 'satisfied', 'stopped'] as const satisfies readonly TGoalStatus[];\n\nconst GOAL_STOP_REASONS = [\n 'satisfied',\n 'max-iterations',\n 'cancelled',\n 'no-progress',\n] as const satisfies readonly TGoalStopReason[];\n\nconst GOAL_SIGNALS = [\n 'continue',\n 'satisfied',\n] as const satisfies readonly IGoalProgressEntry['signal'][];\n\nconst PLAN_STEP_STATUSES = [\n 'pending',\n 'in-progress',\n 'done',\n] as const satisfies readonly TPlanStepStatus[];\n\nconst PLAN_PHASES = [\n 'planning',\n 'awaiting-approval',\n 'executing',\n 'completed',\n] as const satisfies readonly TPlanPhase[];\n\nfunction decodeGoalProgressEntry(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IGoalProgressEntry | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['iteration', 'signal', 'reason']);\n if (raw === undefined) return undefined;\n const iteration = decodeInteger(raw['iteration'], atKey(path, 'iteration'), issues);\n const signal = decodeLiteral(raw['signal'], GOAL_SIGNALS, atKey(path, 'signal'), issues);\n const reason = decodeString(raw['reason'], atKey(path, 'reason'), issues);\n if (iteration === undefined || signal === undefined || reason === undefined) return undefined;\n return { iteration, signal, reason };\n}\n\nexport function decodeGoalState(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IGoalState | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'id',\n 'objective',\n 'status',\n 'stopReason',\n 'iterations',\n 'maxIterations',\n 'startedAt',\n 'progress',\n ]);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const objective = decodeString(raw['objective'], atKey(path, 'objective'), issues);\n const status = decodeLiteral(raw['status'], GOAL_STATUSES, atKey(path, 'status'), issues);\n const iterations = decodeInteger(raw['iterations'], atKey(path, 'iterations'), issues);\n const maxIterations = decodeInteger(raw['maxIterations'], atKey(path, 'maxIterations'), issues);\n const startedAt = decodeTimestampString(raw['startedAt'], atKey(path, 'startedAt'), issues);\n const progress = decodeArray(\n raw['progress'],\n atKey(path, 'progress'),\n issues,\n decodeGoalProgressEntry,\n );\n if (\n id === undefined ||\n objective === undefined ||\n status === undefined ||\n iterations === undefined ||\n maxIterations === undefined ||\n startedAt === undefined ||\n progress === undefined\n ) {\n return undefined;\n }\n const goal: IGoalState = {\n id,\n objective,\n status,\n iterations,\n maxIterations,\n startedAt,\n progress,\n };\n setOptional(\n goal,\n 'stopReason',\n decodeOptional(\n raw['stopReason'],\n atKey(path, 'stopReason'),\n issues,\n (member, memberPath, sink) => decodeLiteral(member, GOAL_STOP_REASONS, memberPath, sink),\n ),\n );\n return goal;\n}\n\nfunction decodePlanStep(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IPlanStep | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['id', 'description', 'status']);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const description = decodeString(raw['description'], atKey(path, 'description'), issues);\n const status = decodeLiteral(raw['status'], PLAN_STEP_STATUSES, atKey(path, 'status'), issues);\n if (id === undefined || description === undefined || status === undefined) return undefined;\n return { id, description, status };\n}\n\nexport function decodePlanArtifact(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IPlanArtifact | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'id',\n 'objective',\n 'steps',\n 'phase',\n 'createdAt',\n 'approvedAt',\n ]);\n if (raw === undefined) return undefined;\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const objective = decodeString(raw['objective'], atKey(path, 'objective'), issues);\n const steps = decodeArray(raw['steps'], atKey(path, 'steps'), issues, decodePlanStep);\n const phase = decodeLiteral(raw['phase'], PLAN_PHASES, atKey(path, 'phase'), issues);\n const createdAt = decodeTimestampString(raw['createdAt'], atKey(path, 'createdAt'), issues);\n if (\n id === undefined ||\n objective === undefined ||\n steps === undefined ||\n phase === undefined ||\n createdAt === undefined\n ) {\n return undefined;\n }\n const plan: IPlanArtifact = { id, objective, steps, phase, createdAt };\n setOptional(\n plan,\n 'approvedAt',\n decodeOptional(raw['approvedAt'], atKey(path, 'approvedAt'), issues, decodeTimestampString),\n );\n return plan;\n}\n\nexport function decodeActiveBranchPointer(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IActiveBranchPointer | undefined {\n const raw = decodeDeclaredObject(value, path, issues, ['branchId', 'checkpointId']);\n if (raw === undefined) return undefined;\n const branchId = decodeString(raw['branchId'], atKey(path, 'branchId'), issues);\n // `null` is a head cleared on purpose (a rollback through the first checkpoint), not an absence.\n const checkpointId =\n raw['checkpointId'] === null\n ? null\n : decodeString(raw['checkpointId'], atKey(path, 'checkpointId'), issues);\n if (branchId === undefined || checkpointId === undefined) return undefined;\n return { branchId, checkpointId };\n}\n","/** Total decoding for session-owned self-paced loops. */\n\nimport { addIssue, atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeBoolean,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeOptional,\n decodeString,\n decodeTimestampString,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type { ISessionLoopState, TSessionLoopPhase } from '@robota-sdk/agent-interface-session';\n\nconst PHASES: readonly TSessionLoopPhase[] = [\n 'waiting',\n 'pending',\n 'running',\n 'stopped',\n 'expired',\n];\n\nconst KEYS = [\n 'loopId',\n 'instruction',\n 'useDefaultPrompt',\n 'createdAt',\n 'expiresAt',\n 'revision',\n 'generation',\n 'phase',\n 'nextAllowedAt',\n 'delaySeconds',\n 'reason',\n 'fallbackUsed',\n 'terminalReason',\n] as const;\n\nexport function decodeSessionLoopState(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): ISessionLoopState | undefined {\n const raw = decodeDeclaredObject(value, path, issues, KEYS);\n if (!raw) return undefined;\n const loopId = decodeString(raw['loopId'], atKey(path, 'loopId'), issues);\n const instruction = decodeString(raw['instruction'], atKey(path, 'instruction'), issues);\n const useDefaultPrompt = decodeOptional(\n raw['useDefaultPrompt'], atKey(path, 'useDefaultPrompt'), issues, decodeBoolean,\n );\n const createdAt = decodeTimestampString(raw['createdAt'], atKey(path, 'createdAt'), issues);\n const expiresAt = decodeTimestampString(raw['expiresAt'], atKey(path, 'expiresAt'), issues);\n const revision = decodeInteger(raw['revision'], atKey(path, 'revision'), issues);\n const generation = decodeInteger(raw['generation'], atKey(path, 'generation'), issues);\n const phase = decodeLiteral(raw['phase'], PHASES, atKey(path, 'phase'), issues);\n const fallbackUsed = decodeBoolean(raw['fallbackUsed'], atKey(path, 'fallbackUsed'), issues);\n const nextAllowedAt = decodeOptional(\n raw['nextAllowedAt'],\n atKey(path, 'nextAllowedAt'),\n issues,\n decodeTimestampString,\n );\n const delaySeconds = decodeOptional(\n raw['delaySeconds'],\n atKey(path, 'delaySeconds'),\n issues,\n decodeInteger,\n );\n const reason = decodeOptional(raw['reason'], atKey(path, 'reason'), issues, decodeString);\n const terminalReason = decodeOptional(\n raw['terminalReason'],\n atKey(path, 'terminalReason'),\n issues,\n decodeString,\n );\n\n if (revision !== undefined && (!Number.isSafeInteger(revision) || revision < 0)) {\n addIssue(issues, atKey(path, 'revision'), 'expected a non-negative safe integer');\n }\n if (generation !== undefined && (!Number.isSafeInteger(generation) || generation < 0)) {\n addIssue(issues, atKey(path, 'generation'), 'expected a non-negative safe integer');\n }\n if (delaySeconds !== undefined && (delaySeconds < 60 || delaySeconds > 3600)) {\n addIssue(issues, atKey(path, 'delaySeconds'), 'expected a delay between 60 and 3600 seconds');\n }\n if (loopId !== undefined && !loopId.trim()) {\n addIssue(issues, atKey(path, 'loopId'), 'expected a non-empty loop ID');\n }\n if (instruction !== undefined && !instruction.trim()) {\n addIssue(issues, atKey(path, 'instruction'), 'expected a non-empty instruction');\n }\n if (phase === 'waiting' && nextAllowedAt === undefined && raw['nextAllowedAt'] === undefined) {\n addIssue(issues, atKey(path, 'nextAllowedAt'), 'waiting loop needs a next wake time');\n }\n if (\n loopId === undefined ||\n instruction === undefined ||\n createdAt === undefined ||\n expiresAt === undefined ||\n revision === undefined ||\n generation === undefined ||\n phase === undefined ||\n fallbackUsed === undefined\n ) {\n return undefined;\n }\n const state: ISessionLoopState = {\n loopId,\n instruction,\n createdAt,\n expiresAt,\n revision,\n generation,\n phase,\n fallbackUsed,\n };\n setOptional(state, 'useDefaultPrompt', useDefaultPrompt);\n setOptional(state, 'nextAllowedAt', nextAllowedAt);\n setOptional(state, 'delaySeconds', delaySeconds);\n setOptional(state, 'reason', reason);\n setOptional(state, 'terminalReason', terminalReason);\n return state;\n}\n","/**\n * TRANS-005 (#2081) — decoders for the tool schemas a session record persists.\n *\n * `IParameterSchema` is the universal JSON-schema subset, and it is recursive: `items`, `properties`\n * and `anyOf` all carry the same node type. `properties` is an OPEN map — its keys are the tool\n * author's parameter names, not contract members — while every node's own member set is declared.\n */\n\nimport { addIssue, atKey, describeValue, setOptional } from './decode-outcome.js';\nimport {\n decodeArray,\n decodeDeclaredObject,\n decodeLiteral,\n decodeNumber,\n decodeOpenMap,\n decodeOptional,\n decodeString,\n decodeStringArray,\n} from './scalars.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type {\n IObjectParameterSchema,\n IParameterSchema,\n IToolSchema,\n TJSONSchemaEnum,\n TJSONSchemaKind,\n TParameterDefaultValue,\n} from '@robota-sdk/agent-core';\n\nconst SCHEMA_KINDS = [\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'object',\n 'null',\n] as const satisfies readonly TJSONSchemaKind[];\n\nconst SIZE_BOUND_KEYS = [\n 'minLength',\n 'maxLength',\n 'minItems',\n 'maxItems',\n 'minProperties',\n 'maxProperties',\n] as const;\n\nconst PARAMETER_SCHEMA_KEYS = [\n 'type',\n 'description',\n 'enum',\n 'items',\n 'properties',\n 'required',\n 'anyOf',\n 'additionalProperties',\n 'minimum',\n 'maximum',\n ...SIZE_BOUND_KEYS,\n 'pattern',\n 'format',\n 'default',\n];\n\nfunction decodeEnumMember(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): string | number | boolean | undefined {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n addIssue(issues, path, `expected a string, number or boolean, received ${describeValue(value)}`);\n return undefined;\n}\n\nfunction decodeDefaultValue(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): TParameterDefaultValue | undefined {\n if (value === null) return null;\n return decodeEnumMember(value, path, issues);\n}\n\n/** JSON Schema declares every size bound a non-negative integer: it counts something. */\nfunction decodeSizeBound(value: unknown, path: string, issues: TDecodeIssues): number | undefined {\n if (typeof value === 'number' && Number.isInteger(value) && value >= 0) return value;\n addIssue(issues, path, `expected a non-negative integer, received ${describeValue(value)}`);\n return undefined;\n}\n\n/**\n * `additionalProperties` is either a closure flag or a schema for the properties not named — the\n * two are told apart by JavaScript type, which is how JSON Schema itself spells it.\n */\nfunction decodeAdditionalProperties(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): boolean | IParameterSchema | undefined {\n if (typeof value === 'boolean') return value;\n return decodeParameterSchema(value, path, issues);\n}\n\nfunction decodeParameterSchema(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IParameterSchema | undefined {\n const raw = decodeDeclaredObject(value, path, issues, PARAMETER_SCHEMA_KEYS);\n if (raw === undefined) return undefined;\n\n const schema: IParameterSchema = {};\n setOptional(\n schema,\n 'type',\n decodeOptional(raw['type'], atKey(path, 'type'), issues, (member, memberPath, sink) =>\n decodeLiteral(member, SCHEMA_KINDS, memberPath, sink),\n ),\n );\n setOptional(\n schema,\n 'description',\n decodeOptional(raw['description'], atKey(path, 'description'), issues, decodeString),\n );\n setOptional(\n schema,\n 'enum',\n decodeOptional(raw['enum'], atKey(path, 'enum'), issues, (member, memberPath, sink) => {\n const decoded = decodeArray(member, memberPath, sink, decodeEnumMember);\n return decoded as TJSONSchemaEnum | undefined;\n }),\n );\n setOptional(\n schema,\n 'items',\n decodeOptional(raw['items'], atKey(path, 'items'), issues, decodeParameterSchema),\n );\n setOptional(\n schema,\n 'properties',\n decodeOptional(\n raw['properties'],\n atKey(path, 'properties'),\n issues,\n (member, memberPath, sink) => decodeOpenMap(member, memberPath, sink, decodeParameterSchema),\n ),\n );\n setOptional(\n schema,\n 'required',\n decodeOptional(raw['required'], atKey(path, 'required'), issues, decodeStringArray),\n );\n setOptional(\n schema,\n 'anyOf',\n decodeOptional(raw['anyOf'], atKey(path, 'anyOf'), issues, (member, memberPath, sink) =>\n decodeArray(member, memberPath, sink, decodeParameterSchema),\n ),\n );\n setOptional(\n schema,\n 'additionalProperties',\n decodeOptional(\n raw['additionalProperties'],\n atKey(path, 'additionalProperties'),\n issues,\n decodeAdditionalProperties,\n ),\n );\n setOptional(\n schema,\n 'minimum',\n decodeOptional(raw['minimum'], atKey(path, 'minimum'), issues, decodeNumber),\n );\n setOptional(\n schema,\n 'maximum',\n decodeOptional(raw['maximum'], atKey(path, 'maximum'), issues, decodeNumber),\n );\n for (const key of SIZE_BOUND_KEYS) {\n setOptional(schema, key, decodeOptional(raw[key], atKey(path, key), issues, decodeSizeBound));\n }\n setOptional(\n schema,\n 'pattern',\n decodeOptional(raw['pattern'], atKey(path, 'pattern'), issues, decodeString),\n );\n setOptional(\n schema,\n 'format',\n decodeOptional(raw['format'], atKey(path, 'format'), issues, decodeString),\n );\n setOptional(\n schema,\n 'default',\n decodeOptional(raw['default'], atKey(path, 'default'), issues, decodeDefaultValue),\n );\n return schema;\n}\n\n/** The root of a tool's parameters: an object node that NAMES its properties. */\nfunction decodeObjectParameterSchema(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IObjectParameterSchema | undefined {\n const schema = decodeParameterSchema(value, path, issues);\n if (schema === undefined) return undefined;\n if (schema.type !== 'object') {\n addIssue(issues, atKey(path, 'type'), \"expected the root parameter schema to be type 'object'\");\n return undefined;\n }\n if (schema.properties === undefined) {\n addIssue(\n issues,\n atKey(path, 'properties'),\n 'expected the root parameter schema to name its properties',\n );\n return undefined;\n }\n return { ...schema, type: 'object', properties: schema.properties };\n}\n\nexport function decodeToolSchema(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IToolSchema | undefined {\n const raw = decodeDeclaredObject(value, path, issues, [\n 'name',\n 'description',\n 'parameters',\n 'outputSchema',\n ]);\n if (raw === undefined) return undefined;\n const name = decodeString(raw['name'], atKey(path, 'name'), issues);\n const description = decodeString(raw['description'], atKey(path, 'description'), issues);\n const parameters = decodeObjectParameterSchema(\n raw['parameters'],\n atKey(path, 'parameters'),\n issues,\n );\n if (name === undefined || description === undefined || parameters === undefined) return undefined;\n const schema: IToolSchema = { name, description, parameters };\n setOptional(\n schema,\n 'outputSchema',\n decodeOptional(raw['outputSchema'], atKey(path, 'outputSchema'), issues, decodeParameterSchema),\n );\n return schema;\n}\n","import { decodePendingExecution } from './pending-execution-decoder.js';\n/**\n * TRANS-005 (#2081) — the optional members of a persisted session record.\n *\n * Written out one member at a time rather than driven from a key→decoder table. A table would be\n * shorter, but its entries decode to a union of every member type, so the assignment back onto the\n * record needs a cast — and a cast is what this whole codec exists to remove. Each statement below\n * is checked by the compiler against the contract member it fills.\n */\n\nimport { decodeBackgroundJobGroupEvent, decodeJobGroupState } from './background-group-decoders.js';\nimport { decodeBackgroundTaskState } from './background-task-decoders.js';\nimport { decodeBackgroundTaskEvent } from './background-task-event-decoders.js';\nimport { atKey, setOptional } from './decode-outcome.js';\nimport {\n decodeContextReferenceItem,\n decodeMemoryEvent,\n decodeMemoryReference,\n decodeSkillActivationEvent,\n} from './event-decoders.js';\nimport {\n decodeActiveBranchPointer,\n decodeGoalState,\n decodePlanArtifact,\n} from './goal-plan-branch-decoders.js';\nimport { decodeHistoryEntry } from './message-decoders.js';\nimport { decodeSessionLoopState } from './session-loop-decoders.js';\nimport { decodeArray, decodeOptional, decodeString } from './scalars.js';\nimport { decodeToolSchema } from './tool-schema-decoders.js';\n\nimport type { TDecodeIssues } from './decode-outcome.js';\nimport type { IInteractiveSessionRecord } from '@robota-sdk/agent-interface-session';\n\n/** Decode an optional array member: absent stays absent, present is decoded element by element. */\nfunction optionalArray<TItem>(\n raw: Record<string, unknown>,\n key: string,\n path: string,\n issues: TDecodeIssues,\n decodeItem: (value: unknown, path: string, issues: TDecodeIssues) => TItem | undefined,\n): TItem[] | undefined {\n return decodeOptional(raw[key], atKey(path, key), issues, (member, memberPath, sink) =>\n decodeArray(member, memberPath, sink, decodeItem),\n );\n}\n\n/** Fill in every optional member of `record` from `raw`, recording any defect it finds. */\nexport function applyOptionalRecordMembers(\n record: IInteractiveSessionRecord,\n raw: Record<string, unknown>,\n path: string,\n issues: TDecodeIssues,\n): void {\n setOptional(\n record,\n 'pendingExecution',\n decodeOptional(\n raw['pendingExecution'],\n atKey(path, 'pendingExecution'),\n issues,\n decodePendingExecution,\n ),\n );\n for (const key of ['name', 'systemPrompt', 'sandboxSnapshotId'] as const) {\n setOptional(record, key, decodeOptional(raw[key], atKey(path, key), issues, decodeString));\n }\n\n setOptional(record, 'history', optionalArray(raw, 'history', path, issues, decodeHistoryEntry));\n setOptional(\n record,\n 'toolSchemas',\n optionalArray(raw, 'toolSchemas', path, issues, decodeToolSchema),\n );\n setOptional(\n record,\n 'backgroundTasks',\n optionalArray(raw, 'backgroundTasks', path, issues, decodeBackgroundTaskState),\n );\n setOptional(\n record,\n 'backgroundTaskEvents',\n optionalArray(raw, 'backgroundTaskEvents', path, issues, decodeBackgroundTaskEvent),\n );\n setOptional(\n record,\n 'backgroundJobGroups',\n optionalArray(raw, 'backgroundJobGroups', path, issues, decodeJobGroupState),\n );\n setOptional(\n record,\n 'backgroundJobGroupEvents',\n optionalArray(raw, 'backgroundJobGroupEvents', path, issues, decodeBackgroundJobGroupEvent),\n );\n setOptional(\n record,\n 'sessionLoops',\n optionalArray(raw, 'sessionLoops', path, issues, decodeSessionLoopState),\n );\n setOptional(\n record,\n 'skillActivationEvents',\n optionalArray(raw, 'skillActivationEvents', path, issues, decodeSkillActivationEvent),\n );\n setOptional(\n record,\n 'memoryEvents',\n optionalArray(raw, 'memoryEvents', path, issues, decodeMemoryEvent),\n );\n setOptional(\n record,\n 'usedMemoryReferences',\n optionalArray(raw, 'usedMemoryReferences', path, issues, decodeMemoryReference),\n );\n setOptional(\n record,\n 'contextReferences',\n optionalArray(raw, 'contextReferences', path, issues, decodeContextReferenceItem),\n );\n\n setOptional(\n record,\n 'goal',\n decodeOptional(raw['goal'], atKey(path, 'goal'), issues, decodeGoalState),\n );\n setOptional(\n record,\n 'plan',\n decodeOptional(raw['plan'], atKey(path, 'plan'), issues, decodePlanArtifact),\n );\n setOptional(\n record,\n 'activeBranch',\n decodeOptional(\n raw['activeBranch'],\n atKey(path, 'activeBranch'),\n issues,\n decodeActiveBranchPointer,\n ),\n );\n}\n","import { validatePendingExecution } from './pending-execution-decoder.js';\n/**\n * TRANS-005 (#2081) — the total decoder for a persisted interactive-session record, and the\n * versioned envelope that carries one.\n *\n * ## Why the version is in an envelope and not in the record\n *\n * `IInteractiveSessionRecord` has no version member, and this codec does not add one. A REQUIRED\n * member would oblige every producer to set it, and migrating producers is another leaf's work; an\n * OPTIONAL one would mean absent-is-acceptable, which is the permissive reader this codec exists to\n * remove. An envelope keeps the version mandatory exactly where it is checked, and leaves every\n * producer untouched until the leaf that migrates it.\n */\n\nimport { atKey } from './decode-outcome.js';\nimport { decodeMessage } from './message-decoders.js';\nimport { applyOptionalRecordMembers } from './record-optional-members.js';\nimport {\n decodeArray,\n decodeDeclaredObject,\n decodeString,\n decodeTimestampString,\n} from './scalars.js';\n\nimport type { TDecodeIssues, TSessionRecordDecodeOutcome } from './decode-outcome.js';\nimport type { IInteractiveSessionRecord } from '@robota-sdk/agent-interface-session';\n\n/**\n * The version of the persisted record envelope this build reads and writes.\n *\n * Bump it when the shape changes in a way an older reader would decode WRONGLY rather than not at\n * all. A reader that meets a version it does not implement reports `unsupported` and stops — it does\n * not decode the members it recognises, because a partially decoded session is the silent\n * field-loss this codec replaces.\n *\n * ONE concept, not two (issue #2185): the envelope `{ schemaVersion, record }` and the record it\n * wraps version together — a change to either shape bumps this number, and every consumer of the\n * envelope reads it: the portable session artifact (`serializeSessionArtifact`) and the session\n * store (`NodeSessionStore.save`, `WorkspaceSessionStore`). Two constants would let an envelope-only\n * change reject records that are fine, and the two shapes have never moved apart. The constant is\n * therefore named for the pair it versions, not for its first consumer: TRANS-006 kept the\n * incumbent `SESSION_ARTIFACT_SCHEMA_VERSION` (published, written by the producing path) over the\n * duplicate TRANS-005 introduced, and #2185 renamed it here — prerelease, so no alias.\n *\n * Its DECLARATION lives here rather than beside the artifact functions because `session-artifact.ts`\n * imports this module; declaring it there and importing it back would be a module cycle. The export\n * from the package barrel is unchanged.\n */\nexport const SESSION_RECORD_ENVELOPE_VERSION = 2;\n\n/** A persisted record with the version of the shape it was written in. */\nexport interface IVersionedInteractiveSessionRecord {\n schemaVersion: number;\n record: IInteractiveSessionRecord;\n}\n\n/**\n * Every key the record contract declares.\n *\n * Exported so a test can compare it against `keyof IInteractiveSessionRecord`: a member added to the\n * contract without a branch below then fails that comparison rather than being silently dropped by\n * a decoder that never heard of it.\n */\nexport const INTERACTIVE_SESSION_RECORD_KEYS: readonly string[] = [\n 'id',\n 'name',\n 'cwd',\n 'createdAt',\n 'updatedAt',\n 'messages',\n 'pendingExecution',\n 'history',\n 'systemPrompt',\n 'toolSchemas',\n 'backgroundTasks',\n 'backgroundTaskEvents',\n 'backgroundJobGroups',\n 'backgroundJobGroupEvents',\n 'sessionLoops',\n 'skillActivationEvents',\n 'memoryEvents',\n 'usedMemoryReferences',\n 'contextReferences',\n 'sandboxSnapshotId',\n 'goal',\n 'plan',\n 'activeBranch',\n];\n\n/**\n * Decode a bare persisted record.\n *\n * The value is decoded, never cast: what comes back is either a record every member of which was\n * checked, or the list of every place it failed — not the first place.\n */\nexport function decodeInteractiveSessionRecord(value: unknown): TSessionRecordDecodeOutcome {\n const issues: TDecodeIssues = [];\n const record = decodeRecordInto(value, '', issues);\n if (record === undefined || issues.length > 0) {\n return { status: 'corrupt', issues };\n }\n return { status: 'valid', record };\n}\n\n/**\n * A best-effort, untyped `cwd` read off a value this build could not fully decode — tolerant of any\n * shape, so it works on both the current envelope (`{ record: { cwd } }`) and a pre-envelope legacy\n * record (`{ cwd }` at the root). It exists only to answer \"which workspace\", never to stand in for\n * the decoded record itself.\n */\nfunction peekCwd(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const root = value as Record<string, unknown>;\n if (typeof root['cwd'] === 'string') return root['cwd'];\n const nested = root['record'];\n if (typeof nested === 'object' && nested !== null) {\n const nestedCwd = (nested as Record<string, unknown>)['cwd'];\n if (typeof nestedCwd === 'string') return nestedCwd;\n }\n return undefined;\n}\n\n/** `{ cwd }` when one was found, an empty object otherwise — spread onto an outcome literal. */\nfunction cwdField(cwd: string | undefined): { cwd: string } | Record<string, never> {\n return cwd !== undefined ? { cwd } : {};\n}\n\n/**\n * Decode a versioned envelope.\n *\n * The version is read BEFORE the record, and a version this build does not implement returns\n * `unsupported` WITHOUT nested issues: reporting field defects against a shape from another version\n * describes the reader's expectations, not the data's condition, and a caller cannot act on it.\n */\nexport function decodeVersionedInteractiveSessionRecord(\n value: unknown,\n): TSessionRecordDecodeOutcome {\n const issues: TDecodeIssues = [];\n const envelope = decodeDeclaredObject(value, '', issues, ['schemaVersion', 'record']);\n if (envelope === undefined) return { status: 'corrupt', issues, ...cwdField(peekCwd(value)) };\n\n const declaredVersion = envelope['schemaVersion'];\n if (typeof declaredVersion !== 'number' || !Number.isFinite(declaredVersion)) {\n return { status: 'unsupported', schemaVersion: undefined, ...cwdField(peekCwd(value)) };\n }\n if (declaredVersion !== 1 && declaredVersion !== SESSION_RECORD_ENVELOPE_VERSION) {\n return { status: 'unsupported', schemaVersion: declaredVersion, ...cwdField(peekCwd(value)) };\n }\n\n if (\n declaredVersion === 1 &&\n typeof envelope.record === 'object' &&\n envelope.record !== null &&\n 'pendingExecution' in envelope.record\n ) {\n issues.push({\n path: 'record.pendingExecution',\n message: 'pending execution requires schema version 2',\n });\n }\n const record = decodeRecordInto(envelope['record'], 'record', issues);\n if (record === undefined || issues.length > 0) {\n return { status: 'corrupt', issues, ...cwdField(peekCwd(value)) };\n }\n return { status: 'valid', record };\n}\n\n/** The record decode itself, at whatever path it sits (the root, or `record` inside an envelope). */\nfunction decodeRecordInto(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IInteractiveSessionRecord | undefined {\n const raw = decodeDeclaredObject(value, path, issues, INTERACTIVE_SESSION_RECORD_KEYS);\n if (raw === undefined) return undefined;\n\n const id = decodeString(raw['id'], atKey(path, 'id'), issues);\n const cwd = decodeString(raw['cwd'], atKey(path, 'cwd'), issues);\n const createdAt = decodeTimestampString(raw['createdAt'], atKey(path, 'createdAt'), issues);\n const updatedAt = decodeTimestampString(raw['updatedAt'], atKey(path, 'updatedAt'), issues);\n // `messages` is the one required array. An absent one reaches `decodeArray` as `undefined` and is\n // reported there like any other non-array, so it needs no case of its own.\n const messages = decodeArray(raw['messages'], atKey(path, 'messages'), issues, decodeMessage);\n\n if (\n id === undefined ||\n cwd === undefined ||\n createdAt === undefined ||\n updatedAt === undefined ||\n messages === undefined\n ) {\n return undefined;\n }\n\n const record: IInteractiveSessionRecord = { id, cwd, createdAt, updatedAt, messages };\n applyOptionalRecordMembers(record, raw, path, issues);\n if (record.pendingExecution)\n validatePendingExecution(\n record.pendingExecution,\n record.messages,\n issues,\n atKey(path, 'pendingExecution'),\n );\n return record;\n}\n","import { randomId } from '@robota-sdk/agent-core';\n\n/**\n * SEC-006 — session ids are used as PATH SEGMENTS (`<baseDir>/<id>.json`, `<logDir>/<id>.jsonl`,\n * `<rootDir>/<id>/` for checkpoints), and a host may take one from an untrusted source such as an HTTP\n * request body. Without a guard, an id of `../../x` escapes the store directory on both read and write.\n *\n * The guard lives at the id boundary rather than at each `join()` so every sink inherits it — the store,\n * the JSONL logger and the replay-log reader are three separate sinks on the same value.\n *\n * REJECT rather than sanitize: silently rewriting `../x` to `__x` would alias two distinct ids onto one\n * file, quietly cross-linking sessions. A malformed id is a bug or an attack; both should be loud.\n */\n\n/** Ids the app generates: `session_<uuid>`. This matches the path-component guard below. */\nconst SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** Generous, but bounded well under every filesystem's per-component limit (255 bytes). */\nconst MAX_SESSION_ID_LENGTH = 128;\n\n/** Generate a fresh session id for callers that do not provide one explicitly. */\nexport function createSessionId(): string {\n return `session_${randomId()}`;\n}\n\n/**\n * Whether `id` is safe to interpolate into a filesystem path as a single component.\n *\n * The pattern admits no `/`, no `\\` and no `:`, so the value cannot introduce a path separator or a\n * Windows drive qualifier; and because it must start with an alphanumeric, it can be neither `.` nor\n * `..`. With no separator available, an embedded `..` cannot form a traversal component.\n */\nexport function isSafeSessionId(id: string): boolean {\n return id.length > 0 && id.length <= MAX_SESSION_ID_LENGTH && SAFE_SESSION_ID.test(id);\n}\n\n/** Throw unless `id` is safe to use as a path component. */\nexport function assertSafeSessionId(id: string): void {\n if (!isSafeSessionId(id)) {\n throw new Error(\n `Invalid session id: ${JSON.stringify(id)}. A session id must be 1-${MAX_SESSION_ID_LENGTH} ` +\n 'characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.',\n );\n }\n}\n","/**\n * INFRA-017: typed contract for session-log event names + replay keys (SSOT).\n *\n * `FileSessionLogger` owns the `{ schemaVersion, timestamp, sessionId, event }` JSONL envelope.\n * This module owns its version and event vocabulary; `session-log-codec` validates each payload\n * before replay or completeness checks.\n *\n * The **replay substrate** is the provider/tool execution layer, keyed deterministically:\n * a `provider_request` (executionId + round) is answered by its recorded\n * `provider_native_raw_payload` / `provider_response_normalized`; a `tool_execution_request`\n * (executionId + toolCallId) by its `tool_execution_result`. `validateSessionReplayLogEntries`\n * proves a log carries all of these (i.e. is replay-complete).\n */\n\n/** Supported persisted session-log envelope version. */\nexport const SESSION_LOG_SCHEMA_VERSION = 1;\n\n/** Canonical session-log event names. */\nexport const SESSION_LOG_EVENT = {\n // Session lifecycle / context\n sessionInit: 'session_init',\n sessionShutdown: 'session_shutdown',\n sessionShutdownStepError: 'session_shutdown_step_error',\n context: 'context',\n contextCompact: 'context_compact',\n error: 'error',\n\n // Canonical conversation substrate (resume): history mutations append messages.\n historyMutation: 'history_mutation',\n\n // Provider replay substrate (keyed by executionId + round).\n providerRequest: 'provider_request',\n providerNativeRawPayload: 'provider_native_raw_payload',\n providerStreamRawDelta: 'provider_stream_raw_delta',\n providerResponseRaw: 'provider_response_raw',\n providerResponseNormalized: 'provider_response_normalized',\n /**\n * CORE-043: which transport actually carried a structured-output schema on this request, and\n * whether the schema had to be stated in the prompt instead. Diagnostic, not replay substrate — a\n * replay answers a `provider_request` from its recorded response, and this line explains why that\n * request looked the way it did.\n */\n structuredOutputTransport: 'structured_output_transport',\n /**\n * A request moved to another model because the one it was on failed. Diagnostic, not replay\n * substrate: the `provider_request` announced for the new model is what a replay answers.\n */\n providerFallback: 'provider_fallback',\n assistantMessageCommitted: 'assistant_message_committed',\n\n // Tool replay substrate (keyed by executionId + toolCallId).\n toolExecutionRequest: 'tool_execution_request',\n toolExecutionResult: 'tool_execution_result',\n toolBatchStarted: 'tool_batch_started',\n toolMessageCommitted: 'tool_message_committed',\n\n // Runtime state persisted beside the conversation substrate.\n backgroundTaskEvent: 'background_task_event',\n backgroundJobGroupEvent: 'background_job_group_event',\n memoryEvent: 'memory_event',\n\n // Observability (display/debug; not the replay substrate).\n user: 'user',\n preRun: 'pre_run',\n textDelta: 'text_delta',\n assistant: 'assistant',\n toolCall: 'tool_call',\n toolResult: 'tool_result',\n toolBlocked: 'tool_blocked',\n toolDenied: 'tool_denied',\n serverTool: 'server_tool',\n} as const;\n\nexport type TSessionLogEventName = (typeof SESSION_LOG_EVENT)[keyof typeof SESSION_LOG_EVENT];\n\n/** Common envelope written for every line by `FileSessionLogger`. */\nexport interface ISessionLogLine {\n readonly timestamp: string;\n readonly sessionId: string;\n readonly event: string;\n readonly [key: string]: unknown;\n}\n\n/** Replay correlation key for a provider call. */\nexport interface IProviderEventKey {\n readonly executionId: string;\n readonly round: number;\n}\n\n/** Replay correlation key for a tool execution. */\nexport interface IToolEventKey {\n readonly executionId: string;\n readonly toolCallId: string;\n}\n\n/** Narrow a raw log line to a specific event name. */\nexport function isSessionLogEvent<TName extends TSessionLogEventName>(\n line: ISessionLogLine,\n name: TName,\n): line is ISessionLogLine & { event: TName } {\n return line.event === name;\n}\n","import { sha256Hex, utf8ByteLength } from '@robota-sdk/agent-core';\n\nimport { assertSafeSessionId } from './session-id.js';\n\nimport type { IExternalPayloadReference } from './session-log-reference-types.js';\n\nconst SHA256_PATTERN = /^[0-9a-f]{64}$/;\n\nfunction assertContentAddress(sha256: string, serialized: string): void {\n const actualSha256 = sha256Hex(serialized);\n if (!SHA256_PATTERN.test(sha256) || sha256 !== actualSha256) {\n throw new Error('Invalid sha256: external JSON payloads require their exact content digest.');\n }\n}\n\n/** Canonical validation and construction for every session-log external-payload reference. */\nexport function createSessionLogExternalPayloadReference(\n sessionId: string,\n sha256: string,\n serialized: string,\n): IExternalPayloadReference {\n assertSafeSessionId(sessionId);\n assertContentAddress(sha256, serialized);\n return {\n kind: 'external-payload',\n encoding: 'json',\n sha256,\n byteLength: utf8ByteLength(serialized),\n // Always `/`: the reference is read back on any platform, and every reader accepts either slash.\n relativePath: `${sessionId}.payloads/${sha256}.json`,\n };\n}\n\n/** Workspace-neutral sink for content-addressed external JSON payloads. */\nexport interface IExternalPayloadSink {\n writeJson(sessionId: string, sha256: string, serialized: string): IExternalPayloadReference;\n}\n\n/** Workspace-neutral append sink for session-log bytes. */\nexport interface ISessionLogSink {\n append(sessionId: string, text: string): void;\n readonly externalPayloadSink?: IExternalPayloadSink;\n}\n","import { atIndex, atKey, describeValue } from '../session-record-codec/decode-outcome.js';\nimport { decodeMessage } from '../session-record-codec/message-decoders.js';\nimport {\n decodeArray,\n decodeBoolean,\n decodeDeclaredObject,\n decodeInteger,\n decodeLiteral,\n decodeNumber,\n decodeString,\n} from '../session-record-codec/scalars.js';\nimport { decodeToolSchema } from '../session-record-codec/tool-schema-decoders.js';\n\nimport type { TDecodeIssues } from '../session-record-codec/decode-outcome.js';\nimport type { IContextWindowState, TUniversalValue } from '@robota-sdk/agent-core';\n\nexport type TFieldDecoder = (value: unknown, path: string, issues: TDecodeIssues) => unknown;\nexport type TPayloadShape = Readonly<Record<string, { decode: TFieldDecoder; optional?: boolean }>>;\n\nexport const required = (decode: TFieldDecoder): { decode: TFieldDecoder } => ({ decode });\nexport const optional = (decode: TFieldDecoder): { decode: TFieldDecoder; optional: true } => ({\n decode,\n optional: true,\n});\nexport const strings = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n decodeArray(value, path, issues, decodeString);\nexport const messages = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n decodeArray(value, path, issues, decodeMessage);\nexport const schemas = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n decodeArray(value, path, issues, decodeToolSchema);\nexport const committedAssistant = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n typeof value === 'string' ? value : decodeMessage(value, path, issues);\nexport const nonNegativeInteger = (\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): unknown => {\n const decoded = decodeInteger(value, path, issues);\n if (decoded !== undefined && decoded < 0)\n issues.push({ path, message: 'expected a non-negative integer' });\n return decoded;\n};\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function record(value: unknown, path: string, issues: TDecodeIssues): unknown {\n if (!isPlainRecord(value)) {\n issues.push({ path, message: `expected an object, received ${describeValue(value)}` });\n return undefined;\n }\n for (const [key, member] of Object.entries(value)) json(member, atKey(path, key), issues);\n return value;\n}\n\n// IContextWindowState is the producer's four-field snapshot contract.\nconst CONTEXT_STATE_KEYS = [\n 'maxTokens',\n 'usedTokens',\n 'usedPercentage',\n 'remainingPercentage',\n] as const satisfies readonly (keyof IContextWindowState)[];\n\nexport function contextState(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n): IContextWindowState | undefined {\n const raw = decodeDeclaredObject(value, path, issues, CONTEXT_STATE_KEYS);\n if (raw === undefined) return undefined;\n const maxTokens = decodeNumber(raw['maxTokens'], atKey(path, 'maxTokens'), issues);\n const usedTokens = decodeNumber(raw['usedTokens'], atKey(path, 'usedTokens'), issues);\n const usedPercentage = decodeNumber(raw['usedPercentage'], atKey(path, 'usedPercentage'), issues);\n const remainingPercentage = decodeNumber(\n raw['remainingPercentage'],\n atKey(path, 'remainingPercentage'),\n issues,\n );\n if (\n maxTokens === undefined ||\n usedTokens === undefined ||\n usedPercentage === undefined ||\n remainingPercentage === undefined\n )\n return undefined;\n return { maxTokens, usedTokens, usedPercentage, remainingPercentage };\n}\n\n// IOwnerPathSegment is owned by agent-core's event service: exactly { type, id }.\nexport const ownerPath = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n decodeArray(value, path, issues, (segment, segmentPath, sink) => {\n const raw = decodeDeclaredObject(segment, segmentPath, sink, ['type', 'id']);\n if (raw === undefined) return undefined;\n const type = decodeString(raw['type'], atKey(segmentPath, 'type'), sink);\n const id = decodeString(raw['id'], atKey(segmentPath, 'id'), sink);\n return type === undefined || id === undefined ? undefined : { type, id };\n });\n\n// Provider-native payloads and tool result data have no provider-neutral member schema.\nexport function json(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n seen = new WeakSet<object>(),\n): TUniversalValue | undefined {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value !== 'object' || value instanceof Date) {\n issues.push({\n path,\n message: `expected a JSON-compatible value, received ${describeValue(value)}`,\n });\n return undefined;\n }\n if (!Array.isArray(value) && !isPlainRecord(value)) {\n issues.push({\n path,\n message: `expected a JSON-compatible object, received ${describeValue(value)}`,\n });\n return undefined;\n }\n if (seen.has(value)) {\n issues.push({ path, message: 'expected an acyclic JSON-compatible value' });\n return undefined;\n }\n seen.add(value);\n if (Array.isArray(value))\n for (let index = 0; index < value.length; index++)\n json(value[index], atIndex(path, index), issues, seen);\n else\n for (const [key, member] of Object.entries(value)) json(member, atKey(path, key), issues, seen);\n seen.delete(value);\n return value as TUniversalValue;\n}\n\n/** Structural preflight before calling recursive record decoders. */\nexport function checkContainerIntegrity(\n value: unknown,\n path: string,\n issues: TDecodeIssues,\n seen = new WeakSet<object>(),\n): void {\n if (typeof value !== 'object' || value === null || value instanceof Date) return;\n if (seen.has(value)) {\n issues.push({ path, message: 'expected an acyclic value' });\n return;\n }\n seen.add(value);\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index++) {\n if (!Object.hasOwn(value, index))\n issues.push({\n path: atIndex(path, index),\n message: 'expected an array element, received nothing',\n });\n else checkContainerIntegrity(value[index], atIndex(path, index), issues, seen);\n }\n } else {\n for (const [key, member] of Object.entries(value))\n checkContainerIntegrity(member, atKey(path, key), issues, seen);\n }\n seen.delete(value);\n}\n\nexport const literal =\n <T extends string>(...values: readonly T[]): TFieldDecoder =>\n (value, path, issues) =>\n decodeLiteral(value, values, path, issues);\n\nexport const historyStructure = (value: unknown, path: string, issues: TDecodeIssues): unknown =>\n decodeArray(value, path, issues, (item, itemPath, sink) => {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) {\n sink.push({ path: itemPath, message: `expected an object, received ${describeValue(item)}` });\n return undefined;\n }\n const entry = item as Record<string, unknown>;\n decodeLiteral(\n entry['role'],\n ['user', 'assistant', 'system', 'tool'],\n atKey(itemPath, 'role'),\n sink,\n );\n nonNegativeInteger(entry['contentLength'], atKey(itemPath, 'contentLength'), sink);\n decodeBoolean(entry['hasToolCalls'], atKey(itemPath, 'hasToolCalls'), sink);\n strings(entry['toolCallNames'], atKey(itemPath, 'toolCallNames'), sink);\n if (entry['metadata'] !== undefined)\n record(entry['metadata'], atKey(itemPath, 'metadata'), sink);\n for (const key of Object.keys(entry))\n if (!['role', 'contentLength', 'hasToolCalls', 'toolCallNames', 'metadata'].includes(key))\n sink.push({ path: atKey(itemPath, key), message: 'unknown history structure field' });\n return entry;\n });\n","import {\n committedAssistant,\n contextState,\n historyStructure,\n json,\n literal,\n messages,\n nonNegativeInteger,\n optional,\n ownerPath,\n record,\n required,\n schemas,\n strings,\n} from './field-decoders.js';\nimport { decodeBackgroundJobGroupEvent } from '../session-record-codec/background-group-decoders.js';\nimport { decodeBackgroundTaskEvent } from '../session-record-codec/background-task-event-decoders.js';\nimport { decodeMemoryEvent } from '../session-record-codec/event-decoders.js';\nimport { decodeMessage } from '../session-record-codec/message-decoders.js';\nimport { decodeBoolean, decodeNumber, decodeString } from '../session-record-codec/scalars.js';\n\nimport type { TSessionLogEventName } from '../session-log-events.js';\nimport type { TPayloadShape } from './field-decoders.js';\n\n// The required members are drawn from production emitters; optional members include values\n// omitted by the logger when a producer supplies undefined.\nexport const PAYLOADS = {\n session_init: {\n cwd: required(decodeString),\n systemPromptLength: required(nonNegativeInteger),\n systemPrompt: required(decodeString),\n toolSchemas: required(schemas),\n model: required(decodeString),\n provider: required(decodeString),\n },\n session_shutdown: { reason: required(decodeString) },\n session_shutdown_step_error: { step: required(decodeString), error: required(decodeString) },\n context: {\n maxTokens: required(decodeNumber),\n usedTokens: required(decodeNumber),\n usedPercentage: required(decodeNumber),\n remainingPercentage: required(decodeNumber),\n },\n context_compact: {\n trigger: required(decodeString),\n before: required(contextState),\n after: required(contextState),\n },\n error: {\n message: required(decodeString),\n stack: required(decodeString),\n historyLength: required(nonNegativeInteger),\n },\n history_mutation: {\n executionId: optional(decodeString),\n conversationId: optional(decodeString),\n round: optional(nonNegativeInteger),\n batchId: optional(decodeString),\n usageObservationId: optional(decodeString),\n providerId: optional(decodeString),\n modelId: optional(decodeString),\n providerError: optional(decodeBoolean),\n contextOverflow: optional(decodeBoolean),\n mutation: required(literal('append_message')),\n index: required(nonNegativeInteger),\n message: required(decodeMessage),\n },\n provider_request: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n provider: required(decodeString),\n model: required(decodeString),\n effort: optional(decodeString),\n forcedSummary: optional(decodeBoolean),\n messages: required(messages),\n tools: optional(schemas),\n },\n provider_native_raw_payload: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n provider: required(decodeString),\n apiSurface: optional(decodeString),\n payloadKind: required(literal('request', 'response', 'stream_event')),\n sequence: required(nonNegativeInteger),\n payload: optional(json),\n metadata: optional(record),\n },\n provider_stream_raw_delta: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n sequence: required(nonNegativeInteger),\n delta: required(decodeString),\n },\n provider_response_raw: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n effort: optional(decodeString),\n response: required(decodeMessage),\n responseKind: required(decodeString),\n },\n provider_response_normalized: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n response: required(decodeMessage),\n toolCallsCount: optional(nonNegativeInteger),\n },\n structured_output_transport: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n provider: required(decodeString),\n model: required(decodeString),\n mechanism: required(literal('response_schema', 'json_object', 'none')),\n provenance: required(literal('catalog', 'vendor-default', 'undeclared', 'unverified-endpoint')),\n sent: required(decodeBoolean),\n schemaInPrompt: required(decodeBoolean),\n reason: optional(decodeString),\n },\n provider_fallback: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n fromProvider: required(decodeString),\n fromModel: required(decodeString),\n toProvider: required(decodeString),\n toModel: required(decodeString),\n reason: required(decodeString),\n },\n assistant_message_committed: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n message: required(committedAssistant),\n },\n tool_execution_request: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n batchId: optional(decodeString),\n index: optional(nonNegativeInteger),\n toolName: required(decodeString),\n toolCallId: required(decodeString),\n parameters: required(record),\n ownerPath: optional(ownerPath),\n },\n tool_execution_result: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n batchId: optional(decodeString),\n index: optional(nonNegativeInteger),\n toolName: optional(decodeString),\n toolCallId: optional(decodeString),\n success: required(decodeBoolean),\n result: optional(json),\n error: optional(decodeString),\n metadata: optional(record),\n },\n tool_batch_started: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n batchId: optional(decodeString),\n mode: required(literal('parallel', 'sequential')),\n maxConcurrency: required(nonNegativeInteger),\n requestCount: required(nonNegativeInteger),\n tools: required(strings),\n },\n tool_message_committed: {\n executionId: required(decodeString),\n conversationId: optional(decodeString),\n round: required(nonNegativeInteger),\n batchId: optional(decodeString),\n index: optional(nonNegativeInteger),\n message: required(decodeMessage),\n },\n background_task_event: {\n backgroundEventType: optional(decodeString),\n backgroundEvent: optional(decodeBackgroundTaskEvent),\n data: optional(decodeBackgroundTaskEvent),\n taskId: optional(decodeString),\n originToolCallId: optional(decodeString),\n },\n background_job_group_event: {\n backgroundJobGroupEvent: optional(decodeBackgroundJobGroupEvent),\n data: optional(decodeBackgroundJobGroupEvent),\n },\n memory_event: { memoryEvent: optional(decodeMemoryEvent), data: optional(decodeMemoryEvent) },\n user: { content: required(decodeString) },\n pre_run: {\n historyLength: required(nonNegativeInteger),\n historyChars: required(nonNegativeInteger),\n historyEstTokens: required(nonNegativeInteger),\n input: required(decodeString),\n history: required(messages),\n model: required(decodeString),\n provider: required(decodeString),\n maxTokens: required(decodeNumber),\n nativeWebSearchSupported: required(decodeBoolean),\n nativeWebSearchEnabled: required(decodeBoolean),\n nativeWebFetchSupported: required(decodeBoolean),\n nativeWebFetchEnabled: required(decodeBoolean),\n },\n text_delta: { delta: required(decodeString) },\n assistant: {\n content: required(decodeString),\n historyLength: required(nonNegativeInteger),\n estimatedChars: required(nonNegativeInteger),\n history: required(messages),\n historyStructure: required(historyStructure),\n },\n tool_call: { tool: required(decodeString), args: required(record) },\n tool_result: {\n tool: required(decodeString),\n success: required(decodeBoolean),\n dataChars: required(nonNegativeInteger),\n truncated: required(decodeBoolean),\n },\n tool_blocked: { tool: required(decodeString), reason: required(decodeString) },\n tool_denied: { tool: required(decodeString), reason: required(decodeString) },\n server_tool: { tool: required(decodeString) },\n} satisfies Record<TSessionLogEventName, TPayloadShape>;\n","import { SESSION_LOG_EVENT, SESSION_LOG_SCHEMA_VERSION } from '../session-log-events.js';\nimport { checkContainerIntegrity, isPlainRecord, json } from './field-decoders.js';\nimport { PAYLOADS } from './payload-shapes.js';\nimport { atKey, describeValue } from '../session-record-codec/decode-outcome.js';\nimport { decodeString, decodeTimestampString } from '../session-record-codec/scalars.js';\n\nimport type { TSessionLogEventName } from '../session-log-events.js';\nimport type { ISessionLogEntry } from '../session-log-entry-types.js';\nimport type { TPayloadShape } from './field-decoders.js';\nimport type { TDecodeIssues } from '../session-record-codec/decode-outcome.js';\nimport type { TUniversalMessage, TUniversalValue } from '@robota-sdk/agent-core';\nimport type { ISessionRecordDecodeIssue } from '@robota-sdk/agent-interface-session';\n\nexport { SESSION_LOG_SCHEMA_VERSION } from '../session-log-events.js';\n\nexport type TSessionLogDecodeErrorCode = 'INVALID_JSON' | 'INVALID_EVENT' | 'UNSUPPORTED_VERSION';\n\ntype TDecodedEvent<TName extends TSessionLogEventName> = ISessionLogEntry & { event: TName };\nexport type TDecodedSessionLogEntry =\n | (TDecodedEvent<'provider_response_normalized'> & { response: TUniversalMessage })\n | (TDecodedEvent<'history_mutation'> & { mutation: 'append_message'; message: TUniversalMessage })\n | (TDecodedEvent<'assistant_message_committed'> & { message: TUniversalMessage | string })\n | (TDecodedEvent<'tool_message_committed'> & { message: TUniversalMessage })\n | (TDecodedEvent<'background_task_event'> & { backgroundEvent?: object; data?: object })\n | (TDecodedEvent<'background_job_group_event'> & {\n backgroundJobGroupEvent?: object;\n data?: object;\n })\n | (TDecodedEvent<'memory_event'> & { memoryEvent?: object; data?: object })\n | TDecodedEvent<\n Exclude<\n TSessionLogEventName,\n | 'provider_response_normalized'\n | 'history_mutation'\n | 'assistant_message_committed'\n | 'tool_message_committed'\n | 'background_task_event'\n | 'background_job_group_event'\n | 'memory_event'\n >\n >;\n\nexport class SessionLogDecodeError extends Error {\n readonly code: TSessionLogDecodeErrorCode;\n readonly issues: readonly ISessionRecordDecodeIssue[];\n readonly schemaVersion?: number;\n\n constructor(\n code: TSessionLogDecodeErrorCode,\n issues: readonly ISessionRecordDecodeIssue[],\n options: { schemaVersion?: number; cause?: unknown } = {},\n ) {\n super(\n `Session log decode failed: ${code}${issues[0] ? ` at ${issues[0].path}: ${issues[0].message}` : ''}`,\n { cause: options.cause },\n );\n this.name = 'SessionLogDecodeError';\n this.code = code;\n this.issues = issues;\n if (options.schemaVersion !== undefined) this.schemaVersion = options.schemaVersion;\n }\n}\n\ninterface IEntryDecodeResult {\n entry?: TDecodedSessionLogEntry;\n unsupported?: number;\n}\n\ninterface IEnvelopeDecodeResult {\n output: Record<string, TUniversalValue>;\n event?: TSessionLogEventName;\n unsupported?: number;\n}\n\nconst EVENTS = new Set<string>(Object.values(SESSION_LOG_EVENT));\n\n/** Validate the full input before returning any entry to replay consumers. */\nexport function decodeSessionLogEntries(\n entries: unknown,\n options: { lineNumbers?: readonly number[] } = {},\n): TDecodedSessionLogEntry[] {\n if (!Array.isArray(entries))\n throw new SessionLogDecodeError('INVALID_EVENT', [\n { path: 'entries', message: `expected an array, received ${describeValue(entries)}` },\n ]);\n const issues: TDecodeIssues = [];\n const decoded: TDecodedSessionLogEntry[] = [];\n let unsupported: number | undefined;\n for (const [index, value] of entries.entries()) {\n const path =\n options.lineNumbers?.[index] === undefined\n ? `[${index}]`\n : `line ${options.lineNumbers[index]}`;\n const result = decodeEntry(value, path, issues);\n if (result.entry !== undefined) decoded.push(result.entry);\n unsupported ??= result.unsupported;\n }\n if (issues.length > 0)\n throw new SessionLogDecodeError(\n unsupported === undefined ? 'INVALID_EVENT' : 'UNSUPPORTED_VERSION',\n issues,\n { schemaVersion: unsupported },\n );\n return decoded;\n}\n\nfunction decodeEntry(value: unknown, path: string, issues: TDecodeIssues): IEntryDecodeResult {\n if (!isPlainRecord(value)) {\n issues.push({ path, message: `expected an object, received ${describeValue(value)}` });\n return {};\n }\n const issuesBeforeIntegrity = issues.length;\n checkContainerIntegrity(value, path, issues);\n // Recursive record decoders may not carry a cycle guard. Never enter them after this preflight fails.\n if (issues.length !== issuesBeforeIntegrity) return {};\n const envelope = decodeEnvelope(value, path, issues);\n if (envelope.event === undefined) return { unsupported: envelope.unsupported };\n decodePayload(value, envelope.event, path, envelope.output, issues);\n return { entry: envelope.output as TDecodedSessionLogEntry, unsupported: envelope.unsupported };\n}\n\nfunction decodeEnvelope(\n raw: Record<string, unknown>,\n path: string,\n issues: TDecodeIssues,\n): IEnvelopeDecodeResult {\n const output: Record<string, TUniversalValue> = { schemaVersion: SESSION_LOG_SCHEMA_VERSION };\n let unsupported: number | undefined;\n if (raw['schemaVersion'] !== SESSION_LOG_SCHEMA_VERSION) {\n const version = raw['schemaVersion'];\n if (typeof version === 'number' && Number.isSafeInteger(version) && version >= 0) {\n unsupported = version;\n issues.push({ path: atKey(path, 'schemaVersion'), message: 'unsupported schema version' });\n } else {\n issues.push({\n path: atKey(path, 'schemaVersion'),\n message: `expected schema version 1, received ${describeValue(version)}`,\n });\n }\n }\n const timestamp = decodeTimestampString(raw['timestamp'], atKey(path, 'timestamp'), issues);\n if (timestamp !== undefined) output['timestamp'] = timestamp;\n const sessionId = decodeString(raw['sessionId'], atKey(path, 'sessionId'), issues);\n if (sessionId === '')\n issues.push({ path: atKey(path, 'sessionId'), message: 'expected a non-empty session ID' });\n if (sessionId !== undefined) output['sessionId'] = sessionId;\n const event = raw['event'];\n if (typeof event !== 'string' || !EVENTS.has(event)) {\n issues.push({\n path: atKey(path, 'event'),\n message: `expected a declared event name, received ${describeValue(event)}`,\n });\n return { output, unsupported };\n }\n output['event'] = event;\n return { output, event: event as TSessionLogEventName, unsupported };\n}\n\nfunction decodePayload(\n raw: Record<string, unknown>,\n event: TSessionLogEventName,\n path: string,\n output: Record<string, TUniversalValue>,\n issues: TDecodeIssues,\n): void {\n const shape: TPayloadShape = PAYLOADS[event];\n for (const [key, field] of Object.entries(shape)) {\n if (!Object.hasOwn(raw, key) && field.optional) continue;\n const member = field.decode(raw[key], atKey(path, key), issues);\n if (member !== undefined) output[key] = member as TUniversalValue;\n }\n for (const key of Object.keys(raw)) {\n if (['schemaVersion', 'timestamp', 'sessionId', 'event', ...Object.keys(shape)].includes(key))\n continue;\n if (event !== 'server_tool') {\n issues.push({ path: atKey(path, key), message: 'unknown event payload field' });\n continue;\n }\n const member = json(raw[key], atKey(path, key), issues);\n if (member !== undefined) output[key] = member;\n }\n requireAuxiliaryPayload(raw, event, path, issues);\n}\n\nfunction requireAuxiliaryPayload(\n raw: Record<string, unknown>,\n event: TSessionLogEventName,\n path: string,\n issues: TDecodeIssues,\n): void {\n if (\n event === 'background_task_event' &&\n raw['backgroundEvent'] === undefined &&\n raw['data'] === undefined\n )\n issues.push({ path, message: 'expected a background task event payload' });\n if (\n event === 'background_job_group_event' &&\n raw['backgroundJobGroupEvent'] === undefined &&\n raw['data'] === undefined\n )\n issues.push({ path, message: 'expected a background job group event payload' });\n if (event === 'memory_event' && raw['memoryEvent'] === undefined && raw['data'] === undefined)\n issues.push({ path, message: 'expected a memory event payload' });\n}\n","import type { IExternalPayloadSource } from './external-payload-source-types.js';\n\nexport type TSessionLogPayloadResolutionErrorCode =\n | 'INVALID_LIMIT'\n | 'INVALID_REFERENCE'\n | 'UNRESOLVED_REFERENCE'\n | 'OUTSIDE_ROOT'\n | 'PAYLOAD_NOT_FOUND'\n | 'STABLE_PAYLOAD_READ_UNAVAILABLE'\n | 'PAYLOAD_UNREADABLE'\n | 'BYTE_LENGTH_MISMATCH'\n | 'SHA256_MISMATCH'\n | 'INVALID_JSON'\n | 'MAX_DEPTH_EXCEEDED'\n | 'MAX_TOTAL_BYTES_EXCEEDED'\n | 'CIRCULAR_REFERENCE';\n\nexport interface ISessionLogPayloadResolutionOptions {\n readonly source?: IExternalPayloadSource;\n readonly maxDepth?: number;\n readonly maxTotalBytes?: number;\n}\n\nexport interface ISessionLogPayloadResolutionErrorMetadata {\n readonly relativePath?: string;\n readonly resolvedPath?: string;\n readonly depth?: number;\n readonly expected?: string | number;\n readonly actual?: string | number;\n}\n\nexport class SessionLogPayloadResolutionError extends Error {\n readonly code: TSessionLogPayloadResolutionErrorCode;\n readonly metadata: Readonly<ISessionLogPayloadResolutionErrorMetadata>;\n\n constructor(\n code: TSessionLogPayloadResolutionErrorCode,\n message: string,\n metadata: ISessionLogPayloadResolutionErrorMetadata = {},\n cause?: unknown,\n ) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'SessionLogPayloadResolutionError';\n this.code = code;\n this.metadata = metadata;\n }\n}\n","/**\n * Why a store refused to replace the file at a session's path: each reason is something the store\n * saw, not a guess about who wrote what. Fixed text and the session id only.\n */\n\n/** Why a save was refused. */\nexport type TSealedSessionRefusal =\n /** A sealed file it cannot open while the keys are locked, and has no proof it wrote or holds. */\n | 'locked'\n /** A sealed file that does not open here: damaged, or sealed with other keys that may still open it. */\n | 'does-not-open'\n /** A sealed file it cannot open, and different from the bytes it last wrote or held. */\n | 'changed'\n /** A file it could not read, or one too large for it to read back. */\n | 'unreadable'\n /** A file sealed in a framing version this build does not open, so written by a newer one. */\n | 'newer-format'\n /** A sealed file, and this store seals nothing, so this process has no keys for it at all. */\n | 'no-keys';\n\nfunction refusalMessage(sessionId: string, reason: TSealedSessionRefusal): string {\n switch (reason) {\n case 'locked':\n return `Session ${sessionId} is sealed and locked, so it was not overwritten; unlock to open it.`;\n case 'does-not-open':\n return `Session ${sessionId} holds a sealed record that does not open for this session, so it was not overwritten.`;\n case 'changed':\n return `Session ${sessionId} changed on disk since this process last wrote or read it, so it was not overwritten.`;\n case 'unreadable':\n return `Session ${sessionId} could not be read, so it was not overwritten.`;\n case 'newer-format':\n return `Session ${sessionId} was sealed by a newer build, so it was not overwritten.`;\n case 'no-keys':\n return `Session ${sessionId} is sealed and this process has no keys that open it, so it was not overwritten.`;\n }\n}\n\n/**\n * Thrown by a store's `save` when the file already at that id may be a session nobody here can\n * read: sealed and not openable by this store, not provably what this store wrote or holds, not\n * readable at all, or sealed by a newer build. Overwriting would destroy what may be the only copy\n * of a session — `locked` is intact and a later unlock reads it, and a sealed file that does not open\n * here may open under other keys — so the save is refused and the file is left exactly as it was.\n */\nexport class SealedSessionUnreadableError extends Error {\n readonly code = 'SESSION_SEALED_UNREADABLE' as const;\n readonly sessionId: string;\n readonly reason: TSealedSessionRefusal;\n\n constructor(sessionId: string, reason: TSealedSessionRefusal) {\n super(refusalMessage(sessionId, reason));\n this.name = 'SealedSessionUnreadableError';\n this.sessionId = sessionId;\n this.reason = reason;\n }\n}\n\n/**\n * Whether `error` is a {@link SealedSessionUnreadableError}, by `code`: this package ships an ES and\n * a CommonJS build, and a process that loads both has two classes an `instanceof` cannot match across.\n */\nexport function isSealedSessionUnreadableError(\n error: unknown,\n): error is SealedSessionUnreadableError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { readonly code?: unknown }).code === 'SESSION_SEALED_UNREADABLE'\n );\n}\n","/**\n * Claims and lends of session ids: the ids a session in this process runs or hands to another\n * process, and the refusal a second writer meets.\n *\n * A claim is exclusive across every process and store instance over the same files, because each\n * one holds the id's writer marker (`IProcessMarkers`, kept in `claims/` beside the records); within\n * one store it is also kept here, released by its own handle only, and it fences saves: a save of a\n * claimed id must carry the live claim, and one carrying a claim that has ended, or whose marker is no\n * longer its own, is refused, so a session that outlived its claim (a shutdown that timed out, a\n * marker another process broke) cannot overwrite the writer that holds the id after it. A lend\n * publishes the marker with a lease digest for another process to take over, and counts as a writer\n * here until it ends; a refusal of a lent id names the process it went to once that took the marker\n * over, and says a subagent this process started holds it before. Every store keeps them, sealing or\n * not, so no store lets a session run unclaimed.\n */\n\nimport type {\n IProcessMarkerHandle,\n IProcessMarkerHolder,\n TProcessOwnerLiveness,\n} from '@robota-sdk/agent-core';\nimport type { ISessionClaim, TSessionLoadOutcome } from '@robota-sdk/agent-interface-session';\n\n/** Why a claim, a lend or a write was refused. */\nexport type TSessionClaimRefusal =\n /**\n * Another writer holds the id: a session of this or another store instance, a process it is lent\n * to, or another process. The refusal names who, as far as it can tell.\n */\n | 'has_writer'\n /**\n * What it was done under has ended: a save under a claim that is not the id's live one (it ended,\n * it is another id's, or its marker is no longer its own), or a claim under a lease that ended.\n */\n | 'released';\n\n/** Who holds a session's writer marker, as a refusal names it. */\nexport interface ISessionWriterHolder {\n readonly pid?: number;\n readonly hostname?: string;\n /** The holder's start time, where the platform reads one. */\n readonly startTime?: string;\n /** This process holds it: a session of this store running or closing here, or a lend not yet taken over. */\n readonly self: boolean;\n readonly liveness: TProcessOwnerLiveness;\n /** The id is lent: the holder is the subagent this process started, or this process until it takes over. */\n readonly lent?: true;\n}\n\n/** How a store words its refusals: the command that releases a marker whose holder is not running. */\nexport interface ISessionClaimRefusalWords {\n readonly releaseCommand?: (sessionId: string) => string;\n}\n\n/**\n * The process a store runs in, as a refusal names it: the Node store states it, because this module\n * is neutral and reads no process. A refusal from a store with none names no pid and adds no\n * platform sentence.\n */\nexport interface ISessionClaimProcess {\n readonly pid: number;\n /** Windows reads no start time, so a holder that crashed may still be shown as holding the id. */\n readonly windows: boolean;\n}\n\n/** What a refusal carries beside its reason. */\nexport interface ISessionClaimRefusalDetails extends ISessionClaimRefusalWords {\n readonly holder?: ISessionWriterHolder;\n /** A `released` refusal of a claim under a lease, not of a save. */\n readonly lease?: true;\n /** The process the refusing store runs in. */\n readonly ownProcess?: ISessionClaimProcess;\n}\n\n/** The holder this process is, for a refusal of an id it claims or lends itself. */\nfunction selfWriterHolder(ownProcess: ISessionClaimProcess | undefined): ISessionWriterHolder {\n return {\n ...(ownProcess === undefined ? {} : { pid: ownProcess.pid }),\n self: true,\n liveness: 'alive',\n };\n}\n\n/** A marker's holder as a refusal names it. */\nexport function writerHolderOf(holder: IProcessMarkerHolder): ISessionWriterHolder {\n const owner = holder.owner;\n return {\n ...(owner === undefined ? {} : { pid: owner.pid }),\n ...(owner?.hostname === undefined ? {} : { hostname: owner.hostname }),\n ...(owner?.startTime === undefined ? {} : { startTime: owner.startTime }),\n self: holder.self,\n liveness: holder.liveness,\n };\n}\n\nfunction holderText(holder: ISessionWriterHolder): string {\n const parts = [holder.pid === undefined ? 'a process this one cannot read' : `pid ${holder.pid}`];\n if (holder.hostname !== undefined) parts.push(`on ${holder.hostname}`);\n if (holder.startTime !== undefined) parts.push(`started ${holder.startTime}`);\n return parts.join(' ');\n}\n\nfunction hasWriterMessage(sessionId: string, details: ISessionClaimRefusalDetails): string {\n const holder = details.holder ?? selfWriterHolder(details.ownProcess);\n if (holder.lent === true) {\n // The lend ends when the subagent has exited, so nothing here is released by hand.\n return holder.self\n ? `Session ${sessionId} is lent to a subagent this process started, which has not taken it up ` +\n 'yet; try again once that subagent has finished.'\n : `Session ${sessionId} is lent to a subagent this process started (${holderText(holder)}), ` +\n 'which writes it; try again once that subagent has finished.';\n }\n if (holder.self) {\n const pid = details.ownProcess === undefined ? '' : ` (pid ${details.ownProcess.pid})`;\n return (\n `Session ${sessionId} is already open in this process${pid}: a session ` +\n 'running or still closing here. Try again once that has ended.'\n );\n }\n const release = details.releaseCommand?.(sessionId);\n if (holder.liveness === 'gone') {\n return (\n `Session ${sessionId} is held by a process that is no longer running (${holderText(holder)}), ` +\n `and another process is releasing it now. Try again${release === undefined ? '' : `, or run: ${release}`}.`\n );\n }\n const where =\n holder.liveness === 'alive' ? 'is open in another process' : 'may be open in another process';\n let message =\n `Session ${sessionId} ${where} (${holderText(holder)}), which writes it; close it there first.` +\n (release === undefined\n ? ''\n : ` If that process is no longer running, release the session with: ${release}`);\n // Windows reads no start time, so a pid reused after a crash keeps the marker standing.\n if (details.ownProcess?.windows === true) {\n message += ' On Windows, a process that crashed may still be shown as holding it.';\n }\n return message;\n}\n\nfunction claimRefusalMessage(\n sessionId: string,\n reason: TSessionClaimRefusal,\n details: ISessionClaimRefusalDetails,\n): string {\n switch (reason) {\n case 'has_writer':\n return hasWriterMessage(sessionId, details);\n case 'released':\n return details.lease === true\n ? `Session ${sessionId} was not opened: the lease it was handed over with has ended.`\n : `Session ${sessionId} was not saved: the claim it was saved under has ended or no longer ` +\n 'holds its writer marker.';\n }\n}\n\n/** A claim, a lend or a write the store refused. Fixed text, the session id and the holder only. */\nexport class SessionClaimedError extends Error {\n readonly code = 'SESSION_CLAIMED' as const;\n readonly sessionId: string;\n readonly reason: TSessionClaimRefusal;\n /** Who holds the id, for a `has_writer` refusal. */\n readonly holder: ISessionWriterHolder | undefined;\n /**\n * A session of this process holds the id and has not let its claim go, so a caller may try again\n * once it has. Not so for a lend, which runs until its subagent has exited, nor for another process.\n */\n readonly closing: boolean;\n\n constructor(\n sessionId: string,\n reason: TSessionClaimRefusal,\n details: ISessionClaimRefusalDetails = {},\n ) {\n super(claimRefusalMessage(sessionId, reason, details));\n this.name = 'SessionClaimedError';\n this.sessionId = sessionId;\n this.reason = reason;\n this.holder =\n reason === 'has_writer'\n ? (details.holder ?? selfWriterHolder(details.ownProcess))\n : undefined;\n this.closing = this.holder?.self === true && this.holder.lent !== true;\n }\n}\n\n/**\n * Whether `error` is a {@link SessionClaimedError}, by `code`: this package ships an ES and a CommonJS\n * build, and the framework and a host that load one each see two classes no `instanceof` matches across.\n */\nexport function isSessionClaimedError(error: unknown): error is SessionClaimedError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { readonly code?: unknown }).code === 'SESSION_CLAIMED'\n );\n}\n\n/** One lend: the id's marker's holder now, which is the subagent once it took the marker over. */\ninterface ILend {\n readonly holder: () => IProcessMarkerHolder | undefined;\n}\n\n/** One live claim: its handle once the claim's own read is done, and its writer marker. */\ninterface IClaimState {\n handle?: ISessionClaim;\n /** Absent for a copy's read, which takes no marker. */\n readonly marker: IProcessMarkerHandle | undefined;\n}\n\n/** The live claims and lends of one store, by id. */\nexport class SessionClaims {\n readonly #live = new Map<string, IClaimState>();\n readonly #lent = new Map<string, ILend>();\n readonly #words: ISessionClaimRefusalWords;\n readonly #ownProcess: ISessionClaimProcess | undefined;\n\n constructor(words: ISessionClaimRefusalWords = {}, ownProcess?: ISessionClaimProcess) {\n this.#words = words;\n this.#ownProcess = ownProcess;\n }\n\n /** Whether `id` is claimed in this store. */\n has(id: string): boolean {\n return this.#live.has(id);\n }\n\n /** Whether `id` is lent from this store. */\n isLent(id: string): boolean {\n return this.#lent.has(id);\n }\n\n /** A refusal in this store's words. */\n refusal(\n id: string,\n reason: TSessionClaimRefusal,\n details: Omit<ISessionClaimRefusalDetails, 'releaseCommand'> = {},\n ): SessionClaimedError {\n return new SessionClaimedError(id, reason, {\n ...this.#words,\n ...(this.#ownProcess === undefined ? {} : { ownProcess: this.#ownProcess }),\n ...details,\n });\n }\n\n /** Throws `has_writer` when `id` is claimed or lent in this store already. */\n assertUnclaimed(id: string): void {\n if (this.#live.has(id) || this.#lent.has(id)) throw this.#heldRefusal(id);\n }\n\n /**\n * `has_writer` for an id this store claims or lends. A claim is a session of this process, running\n * or closing; a lend names the process it went to once that took the marker over, and says a\n * subagent this process started holds it before.\n */\n #heldRefusal(id: string): SessionClaimedError {\n const lend = this.#lent.get(id);\n if (lend === undefined) return this.refusal(id, 'has_writer');\n const marker = lend.holder();\n const holder =\n marker === undefined || marker.self\n ? selfWriterHolder(this.#ownProcess)\n : writerHolderOf(marker);\n return this.refusal(id, 'has_writer', { holder: { ...holder, lent: true } });\n }\n\n /**\n * Claims `id` holding `marker`, with `read` as the claim's own read. A `fresh` claim is in place\n * before its read, so the read is answered as a claimed id's is (nothing on disk is taken for a new\n * session); any other claim reads first, as an ordinary hold read, and is in place before anything\n * else can read. A read that throws leaves nothing claimed and releases the marker. The caller\n * checked that `id` is unclaimed.\n */\n open(\n id: string,\n fresh: boolean,\n marker: IProcessMarkerHandle | undefined,\n read: () => TSessionLoadOutcome,\n ): ISessionClaim {\n const state: IClaimState = { marker };\n const end = (): void => {\n if (this.#live.get(id) === state) this.#live.delete(id);\n marker?.release();\n };\n if (fresh) this.#live.set(id, state);\n let outcome: TSessionLoadOutcome;\n try {\n outcome = read();\n } catch (error) {\n end();\n throw error;\n }\n this.#live.set(id, state);\n let released = false;\n const handle: ISessionClaim = Object.freeze({\n outcome,\n release: (): void => {\n if (released) return;\n released = true;\n end();\n },\n });\n state.handle = handle;\n return handle;\n }\n\n /**\n * The writer marker a save of `id` holds, after the checks a save must pass: a claimed or lent id is\n * saved only under its live claim (`has_writer` without one), a claim that is not the id's live one\n * is `released`, and so is one whose marker another process took. `undefined` for an id this store\n * does not claim, and for a claim that took no marker (a copy's read): the save takes one itself.\n */\n markerForSave(id: string, claim: ISessionClaim | undefined): IProcessMarkerHandle | undefined {\n const live = this.#live.get(id);\n if (claim !== undefined) {\n if (live === undefined || live.handle !== claim) throw this.refusal(id, 'released');\n if (live.marker !== undefined && !live.marker.holds()) throw this.refusal(id, 'released');\n return live.marker;\n }\n if (live !== undefined || this.#lent.has(id)) throw this.#heldRefusal(id);\n return undefined;\n }\n\n /**\n * The marker a write of `id` that carries no claim (an adopt, a tag at unlock) holds when this store\n * claims the id: the live claim's, while it is still its own. `has_writer` for an id this store lent\n * or whose claim lost its marker; `undefined` for an id this store does not claim.\n */\n markerForWrite(id: string): IProcessMarkerHandle | undefined {\n if (this.#lent.has(id)) throw this.#heldRefusal(id);\n const live = this.#live.get(id);\n if (live === undefined) return undefined;\n if (live.marker === undefined || !live.marker.holds()) throw this.refusal(id, 'has_writer');\n return live.marker;\n }\n\n /**\n * Records `id` as lent until the returned end runs; the caller checked that it is unclaimed.\n * `holder` reads the id's marker, which a refusal of the lent id names.\n */\n lend(id: string, holder: () => IProcessMarkerHolder | undefined): () => void {\n const lend: ILend = { holder };\n this.#lent.set(id, lend);\n return () => {\n if (this.#lent.get(id) === lend) this.#lent.delete(id);\n };\n }\n}\n"],"mappings":"qFAqDA,SAAgB,EAAM,EAAgB,EAAqB,CACzD,OAAO,EAAO,SAAW,EAAI,EAAM,GAAG,EAAO,GAAG,GAClD,CAGA,SAAgB,EAAQ,EAAgB,EAAuB,CAC7D,MAAO,GAAG,EAAO,GAAG,EAAM,EAC5B,CAEA,SAAgB,EAAS,EAAuB,EAAc,EAAuB,CACnF,EAAO,KAAK,CAAE,OAAM,SAAQ,CAAC,CAC/B,CAQA,SAAgB,EAAc,EAAwB,CACpD,GAAI,IAAU,KAAM,MAAO,OAC3B,GAAI,MAAM,QAAQ,CAAK,EAAG,MAAO,WACjC,GAAI,aAAiB,KAAM,MAAO,SAClC,OAAQ,OAAO,EAAf,CACE,IAAK,YACH,MAAO,UACT,IAAK,SACH,MAAO,WACT,IAAK,SACH,MAAO,WACT,IAAK,UACH,MAAO,YACT,IAAK,SACH,MAAO,YACT,QACE,MAAO,KAAK,OAAO,GACvB,CACF,CASA,SAAgB,E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