@tangle-network/agent-app 3.0.36 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +11 -0
- package/dist/agent-profiles/index.js +1 -1
- package/dist/chat-routes/index.js +3 -3
- package/dist/chat-routes/native-completion.d.ts +6 -7
- package/dist/{chunk-KYF6YK3C.js → chunk-BRQ2SC6V.js} +17 -9
- package/dist/chunk-BRQ2SC6V.js.map +1 -0
- package/dist/{chunk-X2NXWJ6P.js → chunk-HES3IABJ.js} +6 -60
- package/dist/chunk-HES3IABJ.js.map +1 -0
- package/dist/{chunk-5DG2LO3T.js → chunk-JFBJ7MGK.js} +223 -213
- package/dist/{chunk-5DG2LO3T.js.map → chunk-JFBJ7MGK.js.map} +1 -1
- package/dist/{chunk-VG27P322.js → chunk-JSWBJBPM.js} +2 -2
- package/dist/preset-cloudflare/index.d.ts +1 -1
- package/dist/preset-cloudflare/index.js +79 -10
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/preset-cloudflare/native-completion-owner.d.ts +2 -0
- package/dist/preset-cloudflare/native-completion-workflow.d.ts +26 -4
- package/dist/public-consultation/index.js +2 -2
- package/dist/sandbox/existing-box.d.ts +6 -0
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +3 -1
- package/package.json +1 -1
- package/dist/chunk-KYF6YK3C.js.map +0 -1
- package/dist/chunk-X2NXWJ6P.js.map +0 -1
- /package/dist/{chunk-VG27P322.js.map → chunk-JSWBJBPM.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-profiles/index.ts","../src/agent-profiles/self-management.ts","../src/agent-profiles/release.ts"],"sourcesContent":["/** Chat-owned profile revisions and member/channel bindings. Execution stays in the substrate. */\nimport {\n canonicalAgentProfileDigest,\n diffAgentProfiles,\n snapshotAgentProfile,\n sha256Utf8,\n type AgentProfile,\n type AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport { normalizeProfileName, parseProfileSwitch } from './switch'\nexport { normalizeProfileName, parseProfileSwitch }\nimport type { McpToolDefinition } from '../tools'\n\nexport type ProfileAuthorKind = 'person' | 'agent' | 'optimizer'\nexport type ProfileRevisionState = 'active' | 'candidate' | 'pending-consent'\n\n/** The decision table used by every write path; products may narrow access, never widen it. */\nconst PROFILE_CHANGE_POLICY = {\n textEdit: { admission: 'automatic', conversation: 'same', destructive: false },\n sameAuthoritySwitch: { admission: 'prepare-then-flip', conversation: 'same', destructive: false },\n differentAuthoritySwitch: { admission: 'prepare-then-flip', conversation: 'same', destructive: false },\n authorityEdit: { admission: 'editor-consent', conversation: 'same', destructive: false },\n optimizerRevision: { admission: 'eval-promotion', conversation: 'same', destructive: false },\n destructiveAction: { admission: 'reaper-only', conversation: 'none', destructive: true },\n} as const\n\nexport interface ProfileRevision {\n id: string\n workspaceId: string\n profileId: string\n parentId: string | null\n profile: AgentProfile\n knowledgeText: string\n author: { kind: ProfileAuthorKind; id: string }\n reason: string\n /** `null` means an older stored revision did not record the knowledge delta. */\n knowledgeTextChanged?: boolean | null\n diff: AgentProfileDiff[]\n authorityDigest: string\n /** ADC hash of the public profile plan, without per-turn product attachments. */\n planDigest: string\n state: ProfileRevisionState\n createdAt: number\n}\n\nexport interface ProfileBindingKey {\n workspaceId: string\n memberId: string\n /** `chat`, or a product-scoped phone line and sender key. */\n channel: string\n}\n\nexport interface ProfileBinding extends ProfileBindingKey {\n profileId: string\n pinnedRevisionId: string | null\n authorityDigest: string\n planDigest: string\n version: number\n}\n\nexport interface ProfileTurnPin {\n workspaceId: string\n memberId: string\n channel: string\n messageId: string\n inputHash: string\n profileId: string\n revisionId: string\n authorityDigest: string\n /** Effective ADC plan selected by the executor, including allowed turn attachments. */\n planDigest: string\n}\n\n/** Remove events name only adds they observed; a concurrent add survives. */\nexport interface ProfileKnowledgeEvent {\n id: string\n workspaceId: string\n profileId: string\n documentId: string\n kind: 'add' | 'remove'\n content: string | null\n observedAddIds: string[]\n createdAt: number\n}\n\n\nexport interface ProfileSwitchReceipt {\n key: ProfileBindingKey\n messageId: string\n inputHash: string\n /** Visible conversation that should render this switch marker on reload. */\n conversationId?: string | null\n createdAt?: number\n profileId: string | null\n revisionId: string | null\n /** A rollback binds the previous immutable revision, not the current head. */\n pinnedRevisionId: string | null\n authorityDigest: string | null\n planDigest: string | null\n outcome: 'switched' | 'refused'\n message: string\n /** Workspace resource collisions retain the original and place the profile copy beside it. */\n conflicts: string[]\n}\n\nexport interface ProfileRevisionStore {\n getActiveRevision(workspaceId: string, profileId: string): Promise<ProfileRevision | null>\n getRevision(workspaceId: string, profileId: string, revisionId: string): Promise<ProfileRevision | null>\n /** Append the immutable row and optionally an activation event in one guarded transaction. */\n appendRevision(revision: ProfileRevision, expectedActiveId: string | null, activate: boolean): Promise<boolean>\n /** Promotion appends an activation event; the historical revision remains immutable. */\n promoteRevision(workspaceId: string, profileId: string, revisionId: string, expectedActiveId: string | null): Promise<boolean>\n getBinding(key: ProfileBindingKey): Promise<ProfileBinding | null>\n getSwitchReceipt(key: ProfileBindingKey, messageId: string, inputHash: string): Promise<ProfileSwitchReceipt | null>\n /** Receipt and binding event append atomically; a refusal leaves the binding untouched. */\n recordSwitch(receipt: ProfileSwitchReceipt, expectedVersion: number): Promise<ProfileSwitchReceipt>\n /** Persist one immutable pin under a message id; retries must return the same pin. */\n pinTurn(pin: ProfileTurnPin, expectedBindingVersion: number, options?: { priorChecked?: boolean }): Promise<ProfileTurnPin>\n getTurnPin(key: ProfileBindingKey, messageId: string, inputHash: string): Promise<ProfileTurnPin | null>\n listKnowledgeEvents(workspaceId: string, profileId: string): Promise<ProfileKnowledgeEvent[]>\n appendKnowledgeEvent(event: ProfileKnowledgeEvent): Promise<void>\n /** A revision and its ancestors, newest first, in one read; it ends early at a missing ancestor.\n * Without it, `followProductRelease` reads the history one `getRevision` at a time. */\n readPromptHistory?(workspaceId: string, profileId: string, revisionId: string): Promise<ProfilePromptHistoryEntry[]>\n}\n\n/** One revision of a profile's history, reduced to what decides whether the newest one's system prompt is product\n * text. Prompts are compared where they are stored, so the history carries no prompt text. */\nexport interface ProfilePromptHistoryEntry {\n id: string\n parentId: string | null\n author: ProfileRevision['author']\n /** Its system prompt equals the newest entry's. */\n sameAsNewest: boolean\n /** Its system prompt equals its parent's; `null` when it has no parent row. */\n sameAsParent: boolean | null\n}\n\nexport class ProfileConflictError extends Error {\n constructor(message: string, readonly code?: 'profile_changed') {\n super(message)\n this.name = 'ProfileConflictError'\n }\n}\n\nexport class ProfileAccessError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProfileAccessError'\n }\n}\n\n/** Keep the existing diff column readable while adding the separate knowledge text axis. */\nexport function parseProfileRevisionDiff(value: string): {\n diff: AgentProfileDiff[]; knowledgeTextChanged: boolean | null\n} {\n const parsed: unknown = JSON.parse(value)\n if (Array.isArray(parsed)) return { diff: parsed as AgentProfileDiff[], knowledgeTextChanged: null }\n if (!parsed || typeof parsed !== 'object' || !('profile' in parsed) ||\n !Array.isArray(parsed.profile) || !('knowledgeTextChanged' in parsed) ||\n (parsed.knowledgeTextChanged !== null && typeof parsed.knowledgeTextChanged !== 'boolean')) {\n throw new TypeError('Stored profile revision diff is invalid')\n }\n return { diff: parsed.profile as AgentProfileDiff[],\n knowledgeTextChanged: parsed.knowledgeTextChanged }\n}\n\nexport function serializeProfileRevisionDiff(revision: Pick<ProfileRevision, 'diff' | 'knowledgeTextChanged'>): string {\n return JSON.stringify({ profile: revision.diff, knowledgeTextChanged: revision.knowledgeTextChanged ?? null })\n}\n\n/** Remove exactly the declared text axes. Unknown future fields remain authority. */\nexport function profileAuthority(profile: AgentProfile): AgentProfile {\n const { name: _name, description: _description, prompt, ...authority } = profile\n const { systemPrompt: _systemPrompt, instructions: _instructions, ...promptAuthority } = prompt ?? {}\n return { ...authority, ...(Object.keys(promptAuthority).length ? { prompt: promptAuthority } : {}) }\n}\n\nexport function profileAuthorityDigest(profile: AgentProfile): string {\n return canonicalAgentProfileDigest(profileAuthority(snapshotAgentProfile(profile)))\n}\n\n/** The per-turn text overlay is validated without admitting tools, model, MCP or resources. */\nexport function bindProfileText(consentedBaseline: AgentProfile, selected: AgentProfile): AgentProfile {\n if (profileAuthorityDigest(consentedBaseline) !== profileAuthorityDigest(selected)) {\n throw new ProfileAccessError('Profile authority differs; prepare its managed plan before the next turn')\n }\n // Profiles are digested as RFC 8785 JSON, which has no `undefined`: an\n // absent selected field removes the baseline's value instead of storing it.\n const result: AgentProfile = { ...consentedBaseline, name: selected.name }\n if (selected.description === undefined) delete result.description\n else result.description = selected.description\n const prompt: NonNullable<AgentProfile['prompt']> = { ...consentedBaseline.prompt }\n const { systemPrompt, instructions } = selected.prompt ?? {}\n if (systemPrompt === undefined) delete prompt.systemPrompt\n else prompt.systemPrompt = systemPrompt\n if (instructions === undefined) delete prompt.instructions\n else prompt.instructions = instructions\n if (Object.values(prompt).some(value => value !== undefined)) result.prompt = prompt\n else delete result.prompt\n return snapshotAgentProfile(result)\n}\n\nexport interface ProposeRevisionInput {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n expectedRevisionId: string | null\n profile: AgentProfile\n knowledgeText: string\n /** The exact ADC `hashWorkspacePlan` for this authored snapshot. */\n planDigest: string\n author: ProfileRevision['author']\n /** Trusted role from the authenticated session, never model arguments. */\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n reason: string\n id?: string\n now?: number\n}\n\n/** All authors use one immutable write path. Optimizer and authority edits cannot self-activate. */\nexport async function proposeRevision(input: ProposeRevisionInput): Promise<ProfileRevision> {\n if (input.author.kind !== 'optimizer' && input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can change a profile')\n }\n if (!input.workspaceId || !input.profileId || !input.author.id || !input.reason.trim() ||\n !/^sha256:[a-f0-9]{64}$/.test(input.planDigest)) {\n throw new TypeError('A profile revision needs workspace, profile, author, reason and plan digest')\n }\n const previous = await input.store.getActiveRevision(input.workspaceId, input.profileId)\n if ((previous?.id ?? null) !== input.expectedRevisionId) {\n throw new ProfileConflictError('The profile changed; read its latest revision before saving')\n }\n const profile = snapshotAgentProfile(input.profile)\n const diff = previous ? diffAgentProfiles(previous.profile, profile) : []\n const authorityDigest = profileAuthorityDigest(profile)\n const authorityChanged = !!previous && previous.authorityDigest !== authorityDigest\n const admission = input.author.kind === 'optimizer'\n ? PROFILE_CHANGE_POLICY.optimizerRevision.admission\n : authorityChanged\n ? PROFILE_CHANGE_POLICY.authorityEdit.admission\n : PROFILE_CHANGE_POLICY.textEdit.admission\n const state: ProfileRevisionState = admission === 'eval-promotion' ? 'candidate'\n : admission === 'editor-consent' ? 'pending-consent' : 'active'\n const revision: ProfileRevision = {\n id: input.id ?? crypto.randomUUID(), workspaceId: input.workspaceId, profileId: input.profileId,\n parentId: previous?.id ?? null, profile, knowledgeText: input.knowledgeText,\n author: input.author, reason: input.reason.trim(), diff,\n knowledgeTextChanged: previous ? previous.knowledgeText !== input.knowledgeText : input.knowledgeText.length > 0,\n authorityDigest,\n planDigest: input.planDigest, state, createdAt: input.now ?? Date.now(),\n }\n if (!await input.store.appendRevision(revision, input.expectedRevisionId, state === 'active')) {\n throw new ProfileConflictError('The profile changed while saving')\n }\n return revision\n}\n\nexport interface CreateTextProfileInput {\n store: ProfileRevisionStore\n workspaceId: string\n /** An active profile whose authority the new profile inherits exactly. */\n baselineProfileId: string\n /** Include builtins and user profiles from the authenticated workspace catalog. */\n existingProfiles: readonly { name: string }[]\n name: string\n instructions: string\n authorId: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n /** Product computes ADC's hashWorkspacePlan for the complete authored snapshot. */\n planDigest: (profile: AgentProfile) => string | Promise<string>\n now?: number\n}\n\n/** Create a distinct text persona without granting new model, tool, MCP or secret authority. */\nexport async function createTextProfile(input: CreateTextProfileInput): Promise<ProfileRevision> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can create a profile')\n }\n const name = input.name.trim().replace(/\\s+/g, ' ')\n const normalizedName = normalizeProfileName(name)\n if (!normalizedName) throw new TypeError('A profile needs a name')\n if (input.existingProfiles.some(profile => normalizeProfileName(profile.name) === normalizedName)) {\n throw new ProfileConflictError('A profile with that name already exists')\n }\n const baseline = await input.store.getActiveRevision(input.workspaceId, input.baselineProfileId)\n if (!baseline) throw new ProfileConflictError('The baseline profile is not active')\n // Equal names map to one id, so two concurrent creates cannot create an\n // ambiguous text command even when both read the catalog before either writes.\n const profileId = `custom-${sha256Utf8(`${input.workspaceId}\\0${normalizedName}`).slice(7, 39)}`\n const addedInstruction = input.instructions.trim()\n const profile = bindProfileText(baseline.profile, {\n ...baseline.profile, name,\n prompt: {\n ...baseline.profile.prompt,\n instructions: [...(baseline.profile.prompt?.instructions ?? []),\n ...(addedInstruction ? [addedInstruction] : [])],\n },\n })\n return proposeRevision({\n store: input.store, workspaceId: input.workspaceId, profileId,\n expectedRevisionId: null, profile, knowledgeText: '',\n planDigest: await input.planDigest(profile),\n author: { kind: 'person', id: input.authorId }, actorRole: input.actorRole,\n reason: 'Created a text profile from an approved baseline', now: input.now,\n })\n}\n\nexport async function promoteRevision(input: {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n revisionId: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n /** Verified by the product's consent route; required when authority changes. */\n verifyConsent?: (revision: ProfileRevision) => Promise<boolean>\n}): Promise<ProfileRevision> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can promote a profile')\n }\n const [revision, head] = await Promise.all([\n input.store.getRevision(input.workspaceId, input.profileId, input.revisionId),\n input.store.getActiveRevision(input.workspaceId, input.profileId),\n ])\n if (!revision || revision.parentId !== (head?.id ?? null)) throw new ProfileConflictError('Profile parent changed')\n if (revision.authorityDigest !== head?.authorityDigest &&\n (input.actorRole !== 'owner' || !input.verifyConsent || !await input.verifyConsent(revision))) {\n throw new ProfileAccessError('Authority changes require owner consent')\n }\n if (!await input.store.promoteRevision(input.workspaceId, input.profileId, revision.id, head?.id ?? null)) {\n throw new ProfileConflictError('The profile changed while promoting')\n }\n return revision\n}\n\n/** A source identity joins the command hash without entering the receipt row. */\nfunction profileSwitchInputHashFromContentHash(contentHash: string,\n identityContext?: string): string {\n return identityContext === undefined ? contentHash\n : sha256Utf8(JSON.stringify([identityContext, contentHash]))\n}\n\nexport function profileSwitchInputHash(content: string, identityContext?: string): string {\n return profileSwitchInputHashFromContentHash(sha256Utf8(content), identityContext)\n}\n\nexport interface SwitchableProfile {\n id: string\n name: string\n status: 'active' | 'draft' | 'paused'\n}\n\nexport interface SwitchProfileInput {\n store: ProfileRevisionStore\n key: ProfileBindingKey\n messageId: string\n content: string\n /** Trusted source identity, such as a phone sender; replay must preserve it. */\n identityContext?: string\n conversationId?: string\n choice: { name: string } | { profileId: string }\n profiles: readonly SwitchableProfile[]\n /** Product's role/phone allowlist decision for the authenticated member. */\n canSelect: (profileId: string) => Promise<boolean>\n /** Stage a complete managed plan for the same conversation; never mutate live workspace files. */\n prepareAuthority: (revision: ProfileRevision, key: ProfileBindingKey) => Promise<{\n planDigest: string; healthy: true; conflicts: string[]\n }>\n /** Receives the reason preparation failed; the person sees only a generic refusal.\n * Defaults to one structured `console.error` line so the reason reaches the host's logs. */\n onPrepareFailure?: (error: unknown, profileId: string) => void\n}\n\n/** The picker and deterministic text command converge here. Models cannot call it. */\nfunction logPrepareFailure(error: unknown, profileId: string): void {\n console.error(JSON.stringify({ event: 'profile-switch-prepare-failed', profileId,\n error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) }))\n}\n\nexport async function switchProfile(input: SwitchProfileInput): Promise<ProfileSwitchReceipt> {\n const inputHash = profileSwitchInputHash(input.content, input.identityContext)\n const previousReceipt = await input.store.getSwitchReceipt(input.key, input.messageId, inputHash)\n if (previousReceipt) return previousReceipt\n const binding = await input.store.getBinding(input.key)\n const choice = input.choice\n const matches = 'name' in choice\n ? input.profiles.filter(profile => normalizeProfileName(profile.name) === normalizeProfileName(choice.name))\n : input.profiles.filter(profile => profile.id === choice.profileId)\n const target = matches.length === 1 ? matches[0] : undefined\n let revision: ProfileRevision | null = null\n if (target?.status === 'active' && await input.canSelect(target.id)) {\n revision = await input.store.getActiveRevision(input.key.workspaceId, target.id)\n if (revision && 'name' in choice &&\n normalizeProfileName(revision.profile.name ?? '') !== normalizeProfileName(choice.name)) {\n revision = null\n }\n }\n let outcome: ProfileSwitchReceipt['outcome'] = 'refused'\n let message = matches.length > 1 ? 'That profile name is ambiguous.'\n : target?.status !== 'active' && target ? `${target.name} is not active.`\n : 'That profile is not available for this member.'\n let planDigest: string | null = null\n let conflicts: string[] = []\n if (revision && target) {\n try {\n const prepared = await input.prepareAuthority(revision, input.key)\n if (!prepared.healthy || prepared.planDigest !== revision.planDigest) {\n throw new ProfileConflictError('The managed plan was not prepared for this revision')\n }\n planDigest = prepared.planDigest\n conflicts = prepared.conflicts\n } catch (error) {\n revision = null\n message = `Could not prepare ${target.name}; your current agent is unchanged.`\n ;(input.onPrepareFailure ?? logPrepareFailure)(error, target.id)\n }\n if (revision && planDigest) {\n outcome = 'switched'\n message = `Now talking to ${target.name}`\n }\n }\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: revision?.profileId ?? null, revisionId: revision?.id ?? null,\n pinnedRevisionId: null, authorityDigest: revision?.authorityDigest ?? null,\n planDigest, outcome, message, conflicts }, binding?.version ?? 0)\n}\n\n/** Call before dispatching a chat message; a recognized command is never sent to the model. */\nexport async function handleProfileSwitchText(\n input: Omit<SwitchProfileInput, 'choice'>,\n): Promise<ProfileSwitchReceipt | null> {\n const parsed = parseProfileSwitch(input.content)\n if (!parsed) return null\n if ('name' in parsed) return switchProfile({ ...input, choice: parsed })\n const inputHash = profileSwitchInputHash(input.content, input.identityContext)\n const previous = await input.store.getSwitchReceipt(input.key, input.messageId, inputHash)\n if (previous) return previous\n const binding = await input.store.getBinding(input.key)\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: null, revisionId: null, pinnedRevisionId: null, outcome: 'refused',\n authorityDigest: null, planDigest: null, conflicts: [],\n message: 'Send only “Switch to [agent name]” to change agents.' },\n binding?.version ?? 0)\n}\n\n/**\n * An opaque token for what `readProfileAdmission` read for one message. It carries no data: the values\n * live in this module, cloned when read, so a caller can neither build a token nor change what it stands\n * for. `admitProfileTurn` accepts each token once. The active-revision pointer is never part of it;\n * admission reads that live.\n */\nexport interface ProfileAdmissionRead { readonly [admissionReadBrand]: true }\ndeclare const admissionReadBrand: unique symbol\n\n/** The values a token stands for, as the caller may inspect them. */\nexport interface ProfileAdmissionValues {\n key: ProfileBindingKey\n messageId: string\n inputHash: string\n /** The message's existing pin, when it was already admitted. */\n prior: ProfileTurnPin | null\n binding: ProfileBinding | null\n /** The pinned revision by id (immutable), when the binding pins one. */\n pinnedRevision: ProfileRevision | null\n}\nconst admissionReads = new WeakMap<ProfileAdmissionRead, ProfileAdmissionValues>()\n/** Tokens already presented, so a second use is told apart from one this module never issued. */\nconst spentAdmissionReads = new WeakSet<ProfileAdmissionRead>()\n\n/**\n * Read what admitting a message needs: its prior pin and the binding together, then a pinned revision.\n * Read it where the caller holds its conversation lock (after any switch it records), check the values\n * with `profileAdmissionValues`, and pass the token to `admitProfileTurn`, which then skips re-reading\n * the pin and binding. The pin is still written as a compare-and-set on the binding version, so a\n * binding that moved after this read is refused.\n */\nexport async function readProfileAdmission(store: ProfileRevisionStore, key: ProfileBindingKey,\n messageId: string, content: string): Promise<ProfileAdmissionRead> {\n const inputHash = sha256Utf8(content)\n const [prior, binding] = await Promise.all([store.getTurnPin(key, messageId, inputHash), store.getBinding(key)])\n const pinnedRevision = !prior && binding?.pinnedRevisionId\n ? await store.getRevision(key.workspaceId, binding.profileId, binding.pinnedRevisionId) : null\n const read = Object.freeze(Object.create(null)) as ProfileAdmissionRead\n admissionReads.set(read, structuredClone({ key: { workspaceId: key.workspaceId, memberId: key.memberId, channel: key.channel },\n messageId, inputHash, prior, binding, pinnedRevision }))\n return read\n}\n\n/** A deep copy of what a token stands for; changing the copy changes nothing the token admits. */\nexport function profileAdmissionValues(read: ProfileAdmissionRead): ProfileAdmissionValues {\n const values = admissionReads.get(read)\n if (!values) throw new ProfileAccessError('Unknown or used profile admission read')\n return structuredClone(values)\n}\n\nexport async function admitProfileTurn(input: {\n store: ProfileRevisionStore\n key: ProfileBindingKey\n messageId: string\n content: string\n /** The revision whose prompt this request already dispatched; a different pin is refused before use or write. */\n expectedRevisionId?: string\n /** Effective ADC plan digest selected by the executor for this revision and turn. */\n observedManagedPlanDigest: string\n /** Required if trusted per-turn attachments change the public profile plan. */\n verifyEffectivePlan?: (revision: ProfileRevision, effectivePlanDigest: string,\n key: ProfileBindingKey) => Promise<boolean>\n /** A token from `readProfileAdmission` for this message; its pin and binding are not read again.\n * Each token admits once: after a failed admit, read again before retrying. */\n read?: ProfileAdmissionRead\n}): Promise<ProfileTurnPin> {\n const inputHash = sha256Utf8(input.content)\n // A token is spent when presented, so it admits at most one turn even if this call fails;\n // a retry reads again with `readProfileAdmission`.\n const read = input.read ? admissionReads.get(input.read) : undefined\n if (input.read && !read && spentAdmissionReads.has(input.read)) {\n throw new ProfileConflictError('The admission read was already used; read again')\n }\n if (input.read) { admissionReads.delete(input.read); spentAdmissionReads.add(input.read) }\n if (input.read && (!read || read.messageId !== input.messageId || read.inputHash !== inputHash ||\n read.key.workspaceId !== input.key.workspaceId || read.key.memberId !== input.key.memberId ||\n read.key.channel !== input.key.channel)) {\n throw new ProfileAccessError('The admission read does not belong to this message')\n }\n const assertExpectedRevision = (revisionId: string) => {\n if (input.expectedRevisionId !== undefined && input.expectedRevisionId !== revisionId) {\n throw new ProfileConflictError('The agent profile changed while this turn started. Send the message again.', 'profile_changed')\n }\n }\n const prior = read ? read.prior : await input.store.getTurnPin(input.key, input.messageId, inputHash)\n if (prior) { assertExpectedRevision(prior.revisionId); return prior }\n const binding = read ? read.binding : await input.store.getBinding(input.key)\n if (!binding) throw new ProfileAccessError('Choose a profile before sending a message')\n // The active pointer can move without the binding version changing, so it is always read live.\n const revision = binding.pinnedRevisionId\n ? read?.pinnedRevision ?? await input.store.getRevision(input.key.workspaceId, binding.profileId, binding.pinnedRevisionId)\n : await input.store.getActiveRevision(input.key.workspaceId, binding.profileId)\n if (!revision) throw new ProfileConflictError('The bound profile revision is unavailable')\n assertExpectedRevision(revision.id)\n if (revision.authorityDigest !== binding.authorityDigest ||\n !/^sha256:[a-f0-9]{64}$/.test(input.observedManagedPlanDigest)) {\n throw new ProfileAccessError('The selected managed plan is not active for this turn')\n }\n const planMatches = revision.planDigest === input.observedManagedPlanDigest ||\n (input.verifyEffectivePlan !== undefined &&\n await input.verifyEffectivePlan(revision, input.observedManagedPlanDigest, input.key))\n if (!planMatches) {\n throw new ProfileAccessError('The selected managed plan is not active for this turn')\n }\n return input.store.pinTurn({ ...input.key, messageId: input.messageId, inputHash,\n profileId: revision.profileId, revisionId: revision.id,\n authorityDigest: revision.authorityDigest, planDigest: input.observedManagedPlanDigest }, binding.version,\n // The prior pin was read above (or with the admission read), so the store need not read it again.\n { priorChecked: true })\n}\n\nconst KNOWLEDGE_TEXT_MAX = 32000\nconst textChangeSchema = z.object({\n name: z.string().trim().min(1).max(160).optional(),\n description: z.string().max(2000).nullable().optional(),\n systemPrompt: z.string().max(32000).nullable().optional(),\n instructions: z.array(z.string().max(32000)).max(40).optional(),\n knowledgeText: z.string().max(KNOWLEDGE_TEXT_MAX).optional(),\n}).strict().refine(changes => Object.keys(changes).length > 0)\nconst updateToolSchema = z.object({ expectedRevisionId: z.string().min(1), changes: textChangeSchema }).strict()\nconst rememberToolSchema = z.object({ fact: z.string().trim().min(1).max(1000) }).strict()\n\nfunction profileTextChange(revision: ProfileRevision, changes: z.infer<typeof textChangeSchema>): {\n profile: AgentProfile; knowledgeText: string\n} {\n const profile = structuredClone(revision.profile)\n if (changes.name !== undefined) profile.name = changes.name\n if (changes.description !== undefined) profile.description = changes.description ?? undefined\n if (changes.systemPrompt !== undefined || changes.instructions !== undefined) {\n profile.prompt = { ...profile.prompt,\n ...(changes.systemPrompt !== undefined ? { systemPrompt: changes.systemPrompt ?? undefined } : {}),\n ...(changes.instructions !== undefined ? { instructions: changes.instructions } : {}) }\n }\n return { profile: snapshotAgentProfile(profile), knowledgeText: changes.knowledgeText ?? revision.knowledgeText }\n}\n\nexport interface ProfileToolTurn {\n workspaceId: string; profileId: string; revisionId: string\n memberId: string; role: 'owner' | 'manager' | 'member' | 'viewer'\n}\n\nexport interface ProfileToolContext<TTurn extends ProfileToolTurn = ProfileToolTurn> {\n /** Resolve the running turn from the trusted server session; never from tool arguments. */\n activeTurn(): Promise<TTurn>\n /** Product computes the plan with ADC, returning `hashWorkspacePlan(plan)`. */\n planDigest(profile: AgentProfile, knowledgeText: string): Promise<string>\n store: ProfileRevisionStore\n /** Return a store whose revision append atomically rechecks product turn authority. */\n storeForTurn?(turn: TTurn): ProfileRevisionStore\n /**\n * When set, `profile.remember` writes to this workspace memory store instead\n * of appending a profile revision, so remembered facts never change the\n * hashed profile (or anything that pins its version, such as a phone line).\n * Structurally matches agent-runtime's `WorkspaceStore`.\n */\n memory?: ProfileMemoryStore\n}\n\n/** The subset of agent-runtime's `WorkspaceStore` that `profile.remember` uses. */\nexport interface ProfileMemoryStore {\n list(workspaceId: string, prefix: string): Promise<Array<{ id: string; content?: string }>>\n put(input: { workspaceId: string; path: string; kind: 'fact'; ifRevision: null; actor: string;\n content: string; id?: string }): Promise<{ id: string; revision: number }>\n}\n\n/** Workspace-shared memories live under this prefix in the workspace store. */\nexport const PROFILE_MEMORY_PREFIX = '/memories/workspace/'\n\n/** Shared self-edit tools; only the authenticated active turn can name the profile. */\nexport function profileTools<TTurn extends ProfileToolTurn>(\n context: ProfileToolContext<TTurn>): McpToolDefinition<Record<string, never>>[] {\n return [{\n name: 'profile.read',\n description: 'Read the active agent profile text and revision. Saved text applies on the next message.',\n inputSchema: z.toJSONSchema(z.object({}).strict(), { io: 'input' }) as Record<string, unknown>,\n async run(args) {\n z.object({}).strict().parse(args)\n const turn = await context.activeTurn()\n if (turn.role !== 'owner' && turn.role !== 'manager') throw new ProfileAccessError('Profile management is required')\n const revision = await context.store.getActiveRevision(turn.workspaceId, turn.profileId)\n if (!revision) throw new ProfileConflictError('Profile revision is unavailable')\n return { profileId: turn.profileId, revisionId: revision.id, currentTurnRevisionId: turn.revisionId,\n name: revision.profile.name, description: revision.profile.description ?? null,\n systemPrompt: revision.profile.prompt?.systemPrompt ?? null,\n instructions: revision.profile.prompt?.instructions ?? [], knowledgeText: revision.knowledgeText }\n },\n }, {\n name: 'profile.update',\n description: 'Save a requested owner or manager text change with the revision from profile.read. Applies on the next message.',\n inputSchema: z.toJSONSchema(updateToolSchema, { io: 'input' }) as Record<string, unknown>,\n async run(args) {\n const { expectedRevisionId, changes } = updateToolSchema.parse(args)\n const turn = await context.activeTurn()\n if (turn.role !== 'owner' && turn.role !== 'manager') throw new ProfileAccessError('Profile management is required')\n const current = await context.store.getActiveRevision(turn.workspaceId, turn.profileId)\n if (!current || current.id !== expectedRevisionId) throw new ProfileConflictError('The profile changed; read it again')\n const next = profileTextChange(current, changes)\n const revision = await proposeRevision({ store: context.storeForTurn?.(turn) ?? context.store,\n workspaceId: turn.workspaceId,\n profileId: turn.profileId, expectedRevisionId, ...next,\n planDigest: await context.planDigest(next.profile, next.knowledgeText),\n author: { kind: 'agent', id: turn.memberId }, actorRole: turn.role,\n reason: 'Owner or manager requested a text change during chat' })\n return { profileId: turn.profileId, revisionId: revision.id, state: revision.state,\n canonicalSaved: revision.state === 'active', appliesTo: 'next_message', currentTurn: 'unchanged' }\n },\n }, {\n name: 'profile.remember',\n description: 'Save one durable fact or standing instruction an owner or manager tells you to keep '\n + '(\"remember\", \"note that\", \"from now on\", \"always\", \"never\"). Appends it as one line of the agent\\'s '\n + 'knowledge, which every later conversation reads. Applies on the next message.',\n inputSchema: z.toJSONSchema(rememberToolSchema, { io: 'input' }) as Record<string, unknown>,\n async run(args) {\n const { fact } = rememberToolSchema.parse(args)\n const turn = await context.activeTurn()\n if (turn.role !== 'owner' && turn.role !== 'manager') throw new ProfileAccessError('Profile management is required')\n if (context.memory) {\n const text = fact.replace(/\\s+/g, ' ')\n const known = (await context.memory.list(turn.workspaceId, PROFILE_MEMORY_PREFIX))\n .find(entry => entry.content?.trim() === text)\n if (known) return { memoryId: known.id, saved: true, alreadyKnown: true, line: `- ${text}`, appliesTo: 'next_message' }\n const id = crypto.randomUUID()\n const saved = await context.memory.put({ workspaceId: turn.workspaceId, path: `${PROFILE_MEMORY_PREFIX}${id}`,\n kind: 'fact', ifRevision: null, actor: turn.memberId, content: text, id })\n return { memoryId: saved.id, saved: true, alreadyKnown: false, line: `- ${text}`, appliesTo: 'next_message' }\n }\n const line = `- ${fact.replace(/\\s+/g, ' ')}`\n // One retry covers a concurrent save between the read and the append; the\n // revision chain keeps every earlier line.\n for (let attempt = 0; ; attempt++) {\n const current = await context.store.getActiveRevision(turn.workspaceId, turn.profileId)\n if (!current) throw new ProfileConflictError('Profile revision is unavailable')\n if (current.knowledgeText.split('\\n').some(existing => existing.trim() === line)) {\n return { profileId: turn.profileId, revisionId: current.id, saved: true, alreadyKnown: true,\n line, appliesTo: 'next_message' }\n }\n const knowledgeText = current.knowledgeText.trim() ? `${current.knowledgeText.trimEnd()}\\n${line}` : line\n if (knowledgeText.length > KNOWLEDGE_TEXT_MAX) {\n throw new ProfileConflictError('Knowledge is full; ask the owner to edit it before saving more')\n }\n try {\n const revision = await proposeRevision({ store: context.storeForTurn?.(turn) ?? context.store,\n workspaceId: turn.workspaceId, profileId: turn.profileId, expectedRevisionId: current.id,\n profile: current.profile, knowledgeText,\n planDigest: await context.planDigest(current.profile, knowledgeText),\n author: { kind: 'agent', id: turn.memberId }, actorRole: turn.role,\n reason: 'Owner or manager asked the agent to remember a fact during chat' })\n return { profileId: turn.profileId, revisionId: revision.id, saved: revision.state === 'active',\n state: revision.state, alreadyKnown: false, line, appliesTo: 'next_message' }\n } catch (error) {\n if (!(error instanceof ProfileConflictError) || attempt > 0) throw error\n }\n }\n },\n }]\n}\n\nexport * from './self-management'\nexport * from './release'\n","/**\n * Live profile self-mounting — the safe, immediate subset of agent\n * self-improvement.\n *\n * The revision system ({@link ProfileRevision}, `PROFILE_CHANGE_POLICY`) owns\n * durable profile evolution: authority edits need editor consent, optimizer\n * revisions promote through eval. Self-mounting is the complementary\n * LIVE dimension — the sandboxed agent adjusts its own mounted context\n * (skills today) within a permitted, idempotent, catalog-validated delta.\n * Nothing here touches authority: model, permissions, tools denials and\n * billing identity are not agent-changeable dimensions, and every refusal\n * names the permitted set.\n *\n * One audited verb, not a family: `mount_profile_change` applies a validated\n * delta against a permitted-dimensions allowlist; re-applying the same delta\n * is a no-op; the baseline skill cannot be removed; the mount count is capped\n * because context is a budget.\n *\n * Products wire their own catalog and persistence:\n *\n * ```ts\n * import { createMountProfileChangeTool, createInMemorySelfMountStorage } from '@tangle-network/agent-app/agent-profiles'\n *\n * const mountProfileChange = createMountProfileChangeTool({\n * skills: mySkillRegistry, // { id, description }[]\n * storage: createD1SelfMountStorage(env.DB), // or any { get, set }\n * scopeKey: (ctx) => ctx.threadId ?? ctx.userId, // product's persistence scope\n * baseline: 'cad',\n * })\n * ```\n */\nimport { defineAppTool, type AppToolDefinition } from '../tools/registry'\nimport { ToolInputError } from '../tools/errors'\nimport type { AppToolContext } from '../tools/types'\n\n/** The only profile dimensions an agent may change on its own mounted state.\n * Anything else in a delta is refused with this list — the boundary is the\n * schema, not the verb count. */\nexport const PERMITTED_SELF_MOUNT_DIMENSIONS = ['skills'] as const\n\nexport interface SelfMountSkillEntry {\n /** Registry-unique skill id. */\n id: string\n /** One-line description, surfaced in the tool's catalog. */\n description: string\n}\n\n/** Durable mounted-skill state, keyed by the product's scope. */\nexport interface SelfMountStorage {\n get(scope: string): Promise<readonly string[]>\n set(scope: string, ids: readonly string[]): Promise<void>\n}\n\n/** Non-durable default for tests and single-instance products. */\nexport function createInMemorySelfMountStorage(): SelfMountStorage {\n const state = new Map<string, string[]>()\n return {\n async get(scope) {\n return state.get(scope) ?? []\n },\n async set(scope, ids) {\n state.set(scope, [...new Set(ids)].sort())\n },\n }\n}\n\nexport interface MountProfileChangeDeps {\n /** The product's skill catalog — the only mountable ids. */\n skills: readonly SelfMountSkillEntry[]\n /** Where mounted ids persist, keyed by the product's scope. */\n storage: SelfMountStorage\n /** The persistence scope for a call (project id, thread id, …). */\n scopeKey: (ctx: AppToolContext) => string\n /** Always-mounted skill id that cannot be removed. Default: none. */\n baseline?: string\n /** Upper bound on total mounted skills. Default 12; context is a budget. */\n maxMounted?: number\n /** Tool name override when a product needs a distinct verb. */\n name?: string\n}\n\ninterface SkillsDelta {\n add?: string[]\n remove?: string[]\n}\n\nexport interface MountProfileChangeResult {\n ok: true\n mounted: string[]\n removed: string[]\n effective: string[]\n note: string\n}\n\nfunction catalogLine(skills: readonly SelfMountSkillEntry[]): string {\n return skills.map((s) => `${s.id} (${s.description})`).join('; ')\n}\n\n/**\n * The permitted, idempotent self-mount verb as an app tool. Register it with\n * the product's tool set; the sandboxed agent calls it through the per-turn\n * MCP surface like any other app tool.\n */\nexport function createMountProfileChangeTool(deps: MountProfileChangeDeps): AppToolDefinition<Record<string, unknown>> {\n const { skills, storage, scopeKey } = deps\n const baseline = deps.baseline?.trim() || undefined\n const maxMounted = deps.maxMounted ?? 12\n const known = new Set(skills.map((s) => s.id))\n if (known.size !== skills.length) throw new Error('createMountProfileChangeTool: duplicate skill ids in the catalog')\n if (baseline && !known.has(baseline)) throw new Error(`createMountProfileChangeTool: baseline \"${baseline}\" is not in the catalog`)\n\n return defineAppTool({\n name: deps.name ?? 'mount_profile_change',\n description:\n `Apply a permitted, idempotent change to the mounted skills on this profile. ` +\n `Permitted dimension: skills ({ add: [ids], remove: [ids] }) — anything else is refused. ` +\n `Re-applying the same change is a no-op. Takes effect the next time the profile renders. ` +\n `Catalog: ${catalogLine(skills)}.`,\n parameters: {\n type: 'object',\n properties: {\n changes: {\n type: 'object',\n description: `The profile delta. Permitted dimensions: ${PERMITTED_SELF_MOUNT_DIMENSIONS.join(', ')}.`,\n properties: {\n skills: {\n type: 'object',\n description: 'Skill mounts: catalog ids to add or remove.',\n properties: {\n add: { type: 'array', items: { type: 'string' }, description: 'Catalog skill ids to mount.' },\n remove: { type: 'array', items: { type: 'string' }, description: 'Mounted skill ids to unmount.' },\n },\n additionalProperties: false,\n },\n },\n additionalProperties: false,\n },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n async execute(args: unknown, ctx: AppToolContext): Promise<MountProfileChangeResult | { ok: false; error: string }> {\n const changes = (args as { changes?: Record<string, unknown> }).changes ?? {}\n const unknownDimensions = Object.keys(changes).filter(\n (d) => !(PERMITTED_SELF_MOUNT_DIMENSIONS as readonly string[]).includes(d),\n )\n if (unknownDimensions.length > 0) {\n throw new ToolInputError(\n 'mount_profile_change',\n `dimensions [${unknownDimensions.join(', ')}] are not agent-changeable. Permitted dimensions: ${PERMITTED_SELF_MOUNT_DIMENSIONS.join(', ')}.`,\n )\n }\n const delta = (changes.skills ?? {}) as SkillsDelta\n const add = [...new Set((delta.add ?? []).map((s) => s.trim()).filter(Boolean))]\n const remove = [...new Set((delta.remove ?? []).map((s) => s.trim()).filter(Boolean))]\n if (add.length === 0 && remove.length === 0) {\n throw new ToolInputError('mount_profile_change', 'empty delta: provide skills.add and/or skills.remove')\n }\n const invalid = [...add, ...remove].filter((id) => !known.has(id))\n if (invalid.length > 0) {\n throw new ToolInputError(\n 'mount_profile_change',\n `unknown skill ids: ${invalid.join(', ')}. Catalog: ${[...known].sort().join(', ')}.`)\n }\n if (baseline && remove.includes(baseline)) {\n throw new ToolInputError(\n 'mount_profile_change',\n `refused: \"${baseline}\" is the always-on baseline and cannot be removed`)\n }\n\n const scope = scopeKey(ctx)\n const stored = await storage.get(scope)\n const before = [...new Set([...stored, ...(baseline ? [baseline] : [])])].sort()\n const mounted = new Set(before)\n for (const id of add) mounted.add(id)\n for (const id of remove) mounted.delete(id)\n if (baseline) mounted.add(baseline)\n const effective = [...mounted].sort()\n if (effective.length > maxMounted) {\n throw new ToolInputError(\n 'mount_profile_change',\n `refused: ${effective.length} skills exceeds the ${maxMounted}-skill mount limit`)\n }\n if (JSON.stringify(before) === JSON.stringify(effective)) {\n return { ok: true, mounted: [], removed: [], effective, note: 'no change (already in that state) — idempotent no-op' }\n }\n await storage.set(scope, effective)\n return {\n ok: true,\n mounted: effective.filter((id) => !before.includes(id)),\n removed: before.filter((id) => !effective.includes(id)),\n effective,\n note: 'applied — takes effect the next time the profile renders',\n }\n },\n })\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/** Any drizzle database instance (structural — the adapters only use\n * select/insert with the standard builder chain). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype DrizzleLike = any\n\n// ── Shared storage adapters ────────────────────────────────────────────────\n//\n// Every product's self-mount storage is the same shape: a scope key and a\n// JSON list of mounted skill ids. These adapters mean each product wires\n// the verb in 3 lines instead of hand-writing a drizzle query.\n\nimport type { drizzle as drizzleD1 } from 'drizzle-orm/d1'\nimport { eq } from 'drizzle-orm'\nimport { sqliteTable, text } from 'drizzle-orm/sqlite-core'\n\n/** Create (or use) the standard self-mount table in a drizzle/D1 database. */\nfunction selfMountTable(tableName: string) {\n return sqliteTable(tableName, {\n scope: text('scope').primaryKey(),\n mounted: text('mounted').notNull(),\n })\n}\n\n/** A drizzle-backed SelfMountStorage against any table with the standard\n * shape (scope primary key + mounted JSON text column). Works with the\n * tables every product creates via {@link selfMountTable}. */\nfunction createDrizzleSelfMountStorage(\n db: DrizzleLike,\n table: ReturnType<typeof selfMountTable>,\n baseline: string,\n): SelfMountStorage {\n return {\n async get(scope: string): Promise<readonly string[]> {\n const rows = await db\n .select({ mounted: table.mounted })\n .from(table)\n .where(eq(table.scope, scope))\n .limit(1)\n try {\n return rows[0] ? (JSON.parse(rows[0].mounted) as string[]) : [baseline]\n } catch {\n return [baseline]\n }\n },\n async set(scope: string, ids: readonly string[]): Promise<void> {\n await db\n .insert(table)\n .values({ scope, mounted: JSON.stringify(ids) })\n .onConflictDoUpdate({\n target: table.scope,\n set: { mounted: JSON.stringify(ids) },\n })\n },\n }\n}\n\n/** A KV-backed SelfMountStorage (Cloudflare KV, any namespace). */\nfunction createKVSelfMountStorage(\n kv: { get(key: string): Promise<string | null>; put(key: string, value: string): Promise<void> },\n prefix: string,\n baseline: string,\n): SelfMountStorage {\n const key = (scope: string) => `${prefix}:${scope}`\n return {\n async get(scope: string): Promise<readonly string[]> {\n const raw = await kv.get(key(scope))\n try { return raw ? (JSON.parse(raw) as string[]) : [baseline] } catch { return [baseline] }\n },\n async set(scope: string, ids: readonly string[]): Promise<void> {\n await kv.put(key(scope), JSON.stringify(ids))\n },\n }\n}\n\n/** The one-call product wiring: catalog + storage + baseline + cap. */\nexport interface ProductSelfMountConfig {\n /** The product's skill catalog (id + description per skill). */\n skills: ReadonlyArray<{ id: string; description: string }>\n /** A drizzle/D1 database (uses a self-mount table) or a KV namespace. */\n db?: DrizzleLike\n kv?: { get(key: string): Promise<string | null>; put(key: string, value: string): Promise<void> }\n /** The table name for drizzle storage (default: 'agent_self_mounts'). */\n tableName?: string\n /** KV prefix (default: 'self-mount'). */\n kvPrefix?: string\n /** The skill id that can never be removed. */\n baseline: string\n /** Max simultaneous mounts (default: 12). */\n maxMounted?: number\n}\n\nexport function createProductSelfMount(config: ProductSelfMountConfig) {\n const storage = config.db\n ? createDrizzleSelfMountStorage(config.db, selfMountTable(config.tableName ?? 'agent_self_mounts'), config.baseline)\n : config.kv\n ? createKVSelfMountStorage(config.kv, config.kvPrefix ?? 'self-mount', config.baseline)\n : undefined\n if (!storage) throw new Error('createProductSelfMount needs db or kv')\n return createMountProfileChangeTool({\n skills: config.skills,\n storage,\n scopeKey: (ctx) => ctx.workspaceId ?? ctx.threadId ?? '',\n baseline: config.baseline,\n maxMounted: config.maxMounted ?? 12,\n })\n}\n","/**\n * A stored profile runs the current product release plus its own changes.\n *\n * Revisions are complete AgentProfile snapshots, so a workspace's import carries a copy of the product text current\n * when it was made, and that copy goes stale with the next release. A turn resolves the stored profile over the\n * release serving it: text equal to a version the product shipped (the release's own, or one in the workspace's\n * history) is product text and runs as the release's; text that matches no shipped version is the workspace's own\n * and stays. Nothing stored is rewritten.\n *\n * Only `prompt.systemPrompt` follows a release. No product profile ships `prompt.instructions` (2026-11-15: Creative,\n * Legal, Hardware, Tax and GTM set only the system prompt there); instructions in a stored revision are a person's.\n */\nimport { canonicalCandidateDigest, snapshotAgentProfile, type AgentProfile } from '@tangle-network/agent-interface'\nimport type { ProfilePromptHistoryEntry, ProfileRevision, ProfileRevisionStore } from './index'\n\ntype SkillRef = NonNullable<NonNullable<AgentProfile['resources']>['skills']>[number]\ntype Specialist = NonNullable<AgentProfile['subagents']>[string]\n\n/** How a stored profile's text compares with the current release; `customized` text is the workspace's own and stays. */\nexport interface ProfileReleaseUpdates {\n systemPrompt: 'current' | 'outdated' | 'customized'\n specialists: { updated: string[]; customized: string[] }\n skills: {\n added: string[]\n updated: string[]\n removed: string[]\n /** Built-in skills this workspace edited; they stay as they are. */\n customized: string[]\n }\n}\n\n/** The longest history read; a longer one reads as incomplete, so its prompt is kept. The D1 case in\n * tests/agent-profiles-pin.integration.test.ts reads a history this long with 20 KB prompts. */\nexport const PROFILE_PROMPT_HISTORY_MAX = 1_000\n\nconst skillName = (skill: SkillRef) => skill.name ?? (skill.kind === 'github' ? skill.path : '')\nconst digest = (value: unknown) => canonicalCandidateDigest(value ?? null)\n\n/**\n * The active profile's skills with built-ins brought to the release. A built-in counts as untouched while it\n * matches a version the product shipped (`shipped`); edited built-ins and workspace skills are kept.\n */\nexport function refreshBuiltinSkills(active: AgentProfile, shipped: readonly SkillRef[], release: AgentProfile):\n { skills: SkillRef[]; updates: ProfileReleaseUpdates['skills'] } {\n const current = release.resources?.skills ?? []\n const currentByName = new Map(current.map(skill => [skillName(skill), skill]))\n const shippedNames = new Set(shipped.map(skillName))\n const shippedDigests = new Set(shipped.map(digest))\n const updates: ProfileReleaseUpdates['skills'] = { added: [], updated: [], removed: [], customized: [] }\n const skills: SkillRef[] = []\n for (const skill of active.resources?.skills ?? []) {\n const name = skillName(skill)\n const next = currentByName.get(name)\n const builtin = next !== undefined || shippedNames.has(name)\n if (!builtin || (next && digest(skill) === digest(next))) { skills.push(skill); continue }\n if (!shippedDigests.has(digest(skill))) { updates.customized.push(name); skills.push(skill); continue }\n if (next) { updates.updated.push(name); skills.push(next) } else updates.removed.push(name)\n }\n const present = new Set(skills.map(skillName))\n for (const skill of current) {\n if (present.has(skillName(skill))) continue\n updates.added.push(skillName(skill))\n skills.push(skill)\n }\n return { skills, updates }\n}\n\n/**\n * Resolve a stored profile over the release. `shipped` holds every complete profile the product delivered to this\n * workspace (its import and each release refresh). The system prompt, specialists, built-in skills and every\n * executable control come from the release; the workspace keeps the text it wrote.\n */\nexport function overlayOnRelease(stored: AgentProfile, shipped: readonly AgentProfile[], release: AgentProfile):\n { profile: AgentProfile; updates: ProfileReleaseUpdates } {\n const product = [release, ...shipped]\n const storedPrompt = stored.prompt?.systemPrompt\n const promptCustomized = storedPrompt !== undefined && !product.some(profile => profile.prompt?.systemPrompt === storedPrompt)\n const systemPrompt = promptCustomized ? storedPrompt : release.prompt?.systemPrompt\n const instructions = stored.prompt?.instructions\n\n const subagents: Record<string, Specialist> = { ...release.subagents }\n const specialists: ProfileReleaseUpdates['specialists'] = { updated: [], customized: [] }\n for (const [id, mine] of Object.entries(stored.subagents ?? {})) {\n const versions = product.map(profile => profile.subagents?.[id]).filter((value): value is Specialist => value !== undefined)\n const ownPrompt = mine.prompt !== undefined && !versions.some(version => version.prompt === mine.prompt)\n const ownDescription = mine.description !== undefined && !versions.some(version => version.description === mine.description)\n const next = release.subagents?.[id]\n if (ownPrompt || ownDescription) {\n specialists.customized.push(id)\n subagents[id] = { ...(next ?? mine),\n ...(ownPrompt ? { prompt: mine.prompt } : {}), ...(ownDescription ? { description: mine.description } : {}) }\n } else if (next && (next.prompt !== mine.prompt || next.description !== mine.description)) specialists.updated.push(id)\n }\n\n const { skills, updates: skillUpdates } = refreshBuiltinSkills(stored,\n shipped.flatMap(profile => profile.resources?.skills ?? []), release)\n const releaseFiles = release.resources?.files ?? []\n const releasePaths = new Set(releaseFiles.map(file => file.path))\n const files = [...releaseFiles, ...(stored.resources?.files ?? []).filter(file => !releasePaths.has(file.path))]\n\n const prompt = { ...release.prompt,\n ...(systemPrompt === undefined ? {} : { systemPrompt }), ...(instructions === undefined ? {} : { instructions }) }\n if (systemPrompt === undefined) delete prompt.systemPrompt\n const profile = snapshotAgentProfile({ ...release,\n ...(stored.name === undefined ? {} : { name: stored.name }),\n ...(stored.description === undefined ? {} : { description: stored.description }),\n ...(Object.keys(prompt).length ? { prompt } : {}),\n ...(Object.keys(subagents).length ? { subagents } : {}),\n resources: { ...release.resources, skills, ...(files.length ? { files } : {}) },\n })\n return { profile, updates: {\n systemPrompt: promptCustomized ? 'customized' : storedPrompt === release.prompt?.systemPrompt ? 'current' : 'outdated',\n specialists, skills: skillUpdates,\n } }\n}\n\nasync function promptHistory(store: ProfileRevisionStore, revision: ProfileRevision): Promise<ProfilePromptHistoryEntry[]> {\n if (store.readPromptHistory) return store.readPromptHistory(revision.workspaceId, revision.profileId, revision.id)\n const newest = revision.profile.prompt?.systemPrompt\n const history: ProfilePromptHistoryEntry[] = []\n for (let current: ProfileRevision | null = revision; current && history.length < PROFILE_PROMPT_HISTORY_MAX;) {\n const prompt = current.profile.prompt?.systemPrompt\n const parent: ProfileRevision | null = current.parentId\n ? await store.getRevision(revision.workspaceId, revision.profileId, current.parentId) : null\n history.push({ id: current.id, parentId: current.parentId, author: current.author, sameAsNewest: prompt === newest,\n sameAsParent: parent ? parent.profile.prompt?.systemPrompt === prompt : null })\n current = parent\n }\n return history\n}\n\n/**\n * Whether a revision's system prompt is one the product shipped into its history: some revision by a product author\n * has that prompt and differs from its parent's (an import, or a release refresh). A product revision that carries\n * its parent's prompt forward ships nothing, so a person's text a release copied stays theirs. An incomplete history\n * (a missing ancestor, or a longer one than `PROFILE_PROMPT_HISTORY_MAX`) shows nothing to be the product's.\n */\nexport async function promptShippedByProduct(store: ProfileRevisionStore, revision: ProfileRevision,\n productAuthorIds: readonly string[]): Promise<boolean> {\n const history = await promptHistory(store, revision)\n let shipped = false\n for (const [index, entry] of history.entries()) {\n const parent = history[index + 1]\n if (entry.parentId !== null && parent?.id !== entry.parentId) return false\n if (entry.sameAsNewest && productAuthorIds.includes(entry.author.id) &&\n (entry.parentId === null || entry.sameAsParent === false)) shipped = true\n }\n return shipped\n}\n\n/** Whether a revision's stored prompt is product text, per product author ids. Revisions and their history are\n * immutable, so an answer never changes. */\nconst productPromptRevisions = new Map<string, boolean>()\nconst PRODUCT_PROMPT_REVISIONS_MAX = 10_000\n\n/**\n * The profile a turn runs for `revision`: the stored profile with the release's system prompt where the stored prompt\n * is one the product shipped into its history (`promptShippedByProduct`, revisions whose author id is in\n * `productAuthorIds`) or absent; unchanged, and returned as is, where a person wrote it. Only the system prompt\n * moves; authority, name, description and instructions stay. The history is read once per revision and isolate, in\n * one round trip on the D1 store, and not at all when the stored prompt already is the release's. A plan digest\n * computed from the result moves with each release, so a product's `verifyEffectivePlan` must compute it from this\n * function's result too.\n */\nexport async function followProductRelease(store: ProfileRevisionStore, revision: ProfileRevision,\n release: AgentProfile, productAuthorIds: readonly string[]): Promise<AgentProfile> {\n const stored = revision.profile\n const storedPrompt = stored.prompt?.systemPrompt\n const releasePrompt = release.prompt?.systemPrompt\n if (storedPrompt === releasePrompt) return stored\n if (storedPrompt !== undefined) {\n const key = JSON.stringify([[...productAuthorIds].sort(), revision.workspaceId, revision.profileId, revision.id])\n let product = productPromptRevisions.get(key)\n if (product === undefined) {\n product = await promptShippedByProduct(store, revision, productAuthorIds)\n productPromptRevisions.set(key, product)\n const oldest = productPromptRevisions.keys().next().value\n if (productPromptRevisions.size > PRODUCT_PROMPT_REVISIONS_MAX && oldest !== undefined) productPromptRevisions.delete(oldest)\n }\n if (!product) return stored\n }\n const { systemPrompt: _stored, ...rest } = stored.prompt ?? {}\n const prompt = releasePrompt === undefined ? rest : { ...rest, systemPrompt: releasePrompt }\n const { prompt: _prompt, ...profile } = stored\n return snapshotAgentProfile(Object.keys(prompt).length ? { ...profile, prompt } : profile)\n}\n"],"mappings":";;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA,wBAAAA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,SAAS;;;AC0MlB,SAAS,UAAU;AACnB,SAAS,aAAa,YAAY;AA9K3B,IAAM,kCAAkC,CAAC,QAAQ;AAgBjD,SAAS,iCAAmD;AACjE,QAAM,QAAQ,oBAAI,IAAsB;AACxC,SAAO;AAAA,IACL,MAAM,IAAI,OAAO;AACf,aAAO,MAAM,IAAI,KAAK,KAAK,CAAC;AAAA,IAC9B;AAAA,IACA,MAAM,IAAI,OAAO,KAAK;AACpB,YAAM,IAAI,OAAO,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;AAAA,IAC3C;AAAA,EACF;AACF;AA8BA,SAAS,YAAY,QAAgD;AACnE,SAAO,OAAO,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,EAAE,KAAK,IAAI;AAClE;AAOO,SAAS,6BAA6B,MAA0E;AACrH,QAAM,EAAE,QAAQ,SAAS,SAAS,IAAI;AACtC,QAAM,WAAW,KAAK,UAAU,KAAK,KAAK;AAC1C,QAAM,aAAa,KAAK,cAAc;AACtC,QAAM,QAAQ,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;AAC7C,MAAI,MAAM,SAAS,OAAO,OAAQ,OAAM,IAAI,MAAM,kEAAkE;AACpH,MAAI,YAAY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
{"version":3,"sources":["../src/chat-routes/completed-sandbox-turn.ts","../src/chat-routes/native-completion.ts"],"sourcesContent":["/**\n * Recover a detached Sandbox turn from its durable completed records.\n *\n * A fast detached run can finish before the live event subscriber receives\n * every message-part event. The Sandbox still retains two exact records: a\n * turn-id keyed result cache and the completed assistant message on the\n * session. This adapter joins them without guessing across turns, then returns\n * the same `DetachedTurnFinal` shape `runDetachedTurn` already consumes.\n */\n\nimport { readTokenCostUsd } from '@tangle-network/agent-core/telemetry'\nimport type { SandboxInstance, SessionMessage } from '@tangle-network/sandbox'\nimport {\n asRecord,\n asString,\n collapseRedundantTextParts,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n type JsonRecord,\n} from '../stream/index'\nimport { addStepFinishUsage } from './sandbox-turn-usage'\nimport type { DetachedTurnFinal } from './detached-turn'\nimport type { ChatTurnModelAttribution, ChatTurnUsage } from './turn-routes'\n\n/** The official Sandbox methods needed for completed-turn recovery. */\nexport type CompletedSandboxTurnSource = Pick<\n SandboxInstance,\n 'findCompletedTurn' | 'session'\n>\n\n/** Options for resolving one exact detached turn. */\nexport interface ReadCompletedSandboxTurnOptions {\n turnId: string\n sessionId: string\n /** Read only session messages newer than this Unix-ms time. A long session\n * holds more than one page of messages, oldest first, so an unbounded read\n * both grows with the session and can miss the newest turn. */\n since?: number\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined\n if (typeof value !== 'string' || !value.trim()) return undefined\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction firstNumber(record: JsonRecord | undefined, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = finiteNumber(record?.[key])\n if (value !== undefined) return value\n }\n return undefined\n}\n\n/** @internal Decode a raw runtime result, whose cost is the harness's own report; callers must establish exact turn identity. */\nexport function usageFromResult(result: JsonRecord | undefined): ChatTurnUsage {\n const raw = asRecord(result?.usage) ?? asRecord(result?.tokenUsage)\n const inputTokens = firstNumber(raw, ['inputTokens', 'promptTokens', 'input'])\n const outputTokens = firstNumber(raw, ['outputTokens', 'completionTokens', 'output'])\n const reasoningTokens = firstNumber(raw, ['reasoningTokens', 'reasoning'])\n const cacheReadTokens = firstNumber(raw, [\n 'cacheReadTokens',\n 'cacheReadInputTokens',\n 'cacheRead',\n ])\n const cacheWriteTokens = firstNumber(raw, [\n 'cacheWriteTokens',\n 'cacheCreationInputTokens',\n 'cacheWrite',\n ])\n const harnessCostUsd = result ? readTokenCostUsd(result) : undefined\n\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),\n ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),\n ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),\n ...(harnessCostUsd !== undefined ? { harnessCostUsd } : {}),\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n\n/** @internal Attribution travels with the same validated result as content and usage. */\nexport function attributionFromResult(result: Record<string, unknown> | undefined): Pick<\n ChatTurnModelAttribution,\n 'servedModel' | 'servedProvider' | 'servedSource'\n> {\n const metadata = asRecord(result?.metadata)\n const modelAttribution = asRecord(result?.modelAttribution) ?? asRecord(metadata?.modelAttribution)\n const backend = asRecord(result?.effectiveBackend) ?? asRecord(metadata?.effectiveBackend)\n const source = nonEmptyString(result?.servedSource)\n ?? nonEmptyString(modelAttribution?.servedSource)\n ?? nonEmptyString(backend?.source)\n const servedSource = source === 'request' || source === 'environment' || source === 'profile'\n ? source\n : undefined\n const servedModel = nonEmptyString(result?.servedModel)\n ?? nonEmptyString(modelAttribution?.servedModel)\n ?? nonEmptyString(backend?.model)\n const servedProvider = nonEmptyString(result?.servedProvider)\n ?? nonEmptyString(modelAttribution?.servedProvider)\n ?? nonEmptyString(backend?.provider)\n return {\n ...(servedModel ? { servedModel } : {}),\n ...(servedProvider ? { servedProvider } : {}),\n ...(servedSource ? { servedSource } : {}),\n }\n}\n\nfunction textFromResult(result: JsonRecord | undefined): string | undefined {\n return asString(result?.response)\n ?? asString(result?.finalText)\n ?? asString(result?.text)\n ?? asString(result?.output)\n}\n\nfunction completedMessagesForTurn(\n messages: SessionMessage[],\n turnId: string,\n): SessionMessage[] {\n return messages.filter((message) =>\n message.role === 'assistant'\n && message.metadata?.turnId === turnId\n && message.metadata?.interrupted !== true\n && (\n message.metadata?.completed === true\n || message.metadata?.status === 'completed'\n ),\n )\n}\n\nfunction normalizedMessageParts(\n message: SessionMessage,\n): { parts: JsonRecord[]; usage: ChatTurnUsage; derivedText: string } {\n const normalized: JsonRecord[] = []\n const usage: ChatTurnUsage = {}\n for (const raw of message.parts) {\n const record = asRecord(raw)\n if (!record) continue\n const part = normalizePersistedPart(record)\n if (!part) continue\n normalized.push(part)\n if (part.type === 'step-finish') addStepFinishUsage(part, usage)\n }\n\n const collapsed = collapseRedundantTextParts(normalized)\n const derivedText = collapsed\n .filter((part) => part.type === 'text')\n .map((part) => String(part.text ?? ''))\n .join('')\n return { parts: normalized, usage, derivedText }\n}\n\nfunction projectMessageParts(parts: JsonRecord[], finalText: string): JsonRecord[] {\n const order: string[] = []\n const map = new Map<string, JsonRecord>()\n for (let index = 0; index < parts.length; index += 1) {\n const part = parts[index]!\n const type = String(part.type ?? '')\n // A session's aggregate message contains every step receipt. Preserve each\n // occurrence just as the live producer does; other kinds merge by their\n // canonical identity.\n const key = type === 'step-start' || type === 'step-finish'\n ? `${type}:#${index}`\n : getPartKey(part)\n if (!map.has(key)) order.push(key)\n map.set(key, mergePersistedPart(map.get(key), part))\n }\n return finalizeAssistantParts(order, map, finalText)\n}\n\n/**\n * Recover the durable content a Sandbox recorder attached to one assistant\n * message. The caller is responsible for proving that the message belongs to\n * the exact terminal turn; this projection deliberately makes no conclusion\n * about whether that terminal state was completed or interrupted.\n */\nexport function recoverSandboxAssistantMessage(message: SessionMessage): DetachedTurnFinal {\n const recovered = normalizedMessageParts(message)\n return {\n ...(recovered.derivedText ? { text: recovered.derivedText } : {}),\n ...(hasUsage(recovered.usage) ? { usage: recovered.usage } : {}),\n parts: projectMessageParts(recovered.parts, recovered.derivedText),\n }\n}\n\nfunction hasUsage(usage: ChatTurnUsage): boolean {\n return Object.values(usage).some((value) =>\n typeof value === 'number' && Number.isFinite(value),\n )\n}\n\n/**\n * Read the exact completed turn from its keyed cache and completed message.\n * Never borrow a session-wide aggregate from a concurrently advancing session.\n * Observation failure is retryable and distinct from successful absent reads.\n * Model attribution comes from that same identity-checked cache record, never\n * from a second unchecked lookup that could belong to a different turn.\n */\nexport async function readCompletedSandboxTurn(\n box: CompletedSandboxTurnSource,\n options: ReadCompletedSandboxTurnOptions,\n): Promise<(DetachedTurnFinal & Pick<ChatTurnModelAttribution, 'servedModel' | 'servedProvider' | 'servedSource'>) | null> {\n const { turnId, sessionId, log } = options\n const session = box.session(sessionId)\n const [cacheOutcome, messagesOutcome] = await Promise.allSettled([\n box.findCompletedTurn(turnId, { sessionId }),\n session.messages({ limit: 1_000, ...(options.since !== undefined ? { since: options.since } : {}) }),\n ])\n\n if (cacheOutcome.status === 'rejected') {\n log?.('[chat-routes] completed Sandbox turn cache lookup failed', {\n turnId,\n sessionId,\n error: String(cacheOutcome.reason),\n })\n }\n if (messagesOutcome.status === 'rejected') {\n log?.('[chat-routes] completed Sandbox session message lookup failed', {\n turnId,\n sessionId,\n error: String(messagesOutcome.reason),\n })\n }\n\n const rawCached = cacheOutcome.status === 'fulfilled' ? cacheOutcome.value : null\n const cached = rawCached\n && rawCached.turnId === turnId\n && rawCached.sessionId === sessionId\n ? rawCached\n : null\n if (rawCached && !cached) {\n log?.('[chat-routes] ignored mismatched completed Sandbox turn cache record', {\n turnId,\n sessionId,\n })\n }\n\n const messages = messagesOutcome.status === 'fulfilled'\n ? messagesOutcome.value\n : []\n const matchingMessages = completedMessagesForTurn(messages, turnId)\n const matchingCount = matchingMessages.length\n const message = matchingCount === 1 ? matchingMessages[0]! : null\n if (matchingCount > 1) {\n log?.('[chat-routes] ignored ambiguous completed Sandbox session messages', {\n turnId,\n sessionId,\n matchingCount,\n })\n }\n\n if (!cached && !message) {\n // A failed read is unknown, not proof that the turn is absent. The durable\n // owner must retry observation rather than admit another execution.\n if (cacheOutcome.status === 'rejected' || messagesOutcome.status === 'rejected') {\n throw new Error('Completed Sandbox turn could not be verified; retry the exact read')\n }\n if (rawCached || matchingCount > 1) {\n throw new Error('Completed Sandbox turn identity is inconsistent; reconciliation is required')\n }\n return null\n }\n\n // Only turn-addressed evidence is safe. A newer turn can complete between\n // reading the message list and reading a session-wide aggregate result.\n const result = cached ? asRecord(cached.result) : undefined\n\n const recovered = message ? normalizedMessageParts(message) : null\n const text = textFromResult(result) ?? recovered?.derivedText\n const resultUsage = usageFromResult(result)\n const usage = { ...(recovered?.usage ?? {}), ...resultUsage }\n const resultParts = Array.isArray(result?.parts)\n ? result.parts\n .map((part) => asRecord(part))\n .filter((part): part is JsonRecord => Boolean(part))\n .map((part) => normalizePersistedPart(part))\n .filter((part): part is JsonRecord => Boolean(part))\n : null\n const sourceParts = recovered?.parts ?? resultParts\n const parts = sourceParts\n ? projectMessageParts(sourceParts, text ?? recovered?.derivedText ?? '')\n : undefined\n\n return {\n ...(text !== undefined ? { text } : {}),\n ...(hasUsage(usage) ? { usage } : {}),\n ...(parts ? { parts } : {}),\n ...attributionFromResult(result),\n }\n}\n","/**\n * Exact terminal observation for a native Sandbox execution that another\n * request already admitted. This module never sends a prompt, calls\n * `driveTurn`, or cancels a run.\n */\n\nimport { readTokenCostUsd } from '@tangle-network/agent-core/telemetry'\nimport type { SandboxInstance, SessionInfo, SessionMessage } from '@tangle-network/sandbox'\nimport type { ChatTurnUsage } from './turn-routes'\nimport type { SessionExecutionInfo } from '@tangle-network/sandbox'\nimport {\n attributionFromResult,\n readCompletedSandboxTurn,\n recoverSandboxAssistantMessage,\n usageFromResult,\n} from './completed-sandbox-turn'\nimport { TURN_USAGE_KEYS } from './sandbox-turn-usage'\n\nexport interface NativeCompletionReceipt {\n state: 'completed' | 'failed'\n text: string\n parts: Array<Record<string, unknown>>\n /** An empty object is an unknown usage receipt, never a measured zero. */\n usage: ChatTurnUsage\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n error?: string\n completedTurnIds: string[]\n}\n\nexport interface NativeCompletionAdmission {\n executionId: string\n state: 'open' | 'closed'\n admittedTurnIds: readonly string[]\n ownerLeaseUntil: Date | number\n updatedAt?: Date | number\n closedAt?: Date | number | null\n}\n\n/** Product persistence for the one admission that authorizes this observer. */\nexport interface NativeCompletionAdmissionStore {\n read(executionId: string): Promise<NativeCompletionAdmission | null>\n renew(executionId: string, now: Date): Promise<NativeCompletionAdmission | null>\n closeExpired(executionId: string, now: Date): Promise<NativeCompletionAdmission | null>\n}\n\n/** The official Sandbox reads needed for exact native completion observation. */\nexport type NativeCompletionSessionSource = Pick<SandboxInstance, 'findCompletedTurn' | 'session'>\n\nexport interface NativeCompletionObservationOptions {\n /** Null when the product cannot currently resolve the admitted Sandbox. */\n source: NativeCompletionSessionSource | null\n admissionStore: NativeCompletionAdmissionStore\n executionId: string\n sessionId: string\n turnId: string\n registeredAt: number\n absentDispatchDeadlineMs?: number\n receiptDeadlineMs?: number\n now?: number\n}\n\nexport type NativeCompletionObservation =\n | { state: 'running' }\n | { state: 'completed'; receipt: NativeCompletionReceipt }\n | { state: 'failed'; receipt: NativeCompletionReceipt }\n\n/** One exact turn receipt before an admission's ordered aggregate. */\nexport interface NativeCompletionTurnReceipt {\n turnId: string\n state: 'completed' | 'failed'\n text: string\n parts: Array<Record<string, unknown>>\n usage: ChatTurnUsage\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n error?: string\n}\n\nconst DEFAULT_ABSENT_DISPATCH_DEADLINE_MS = 10 * 60_000\nconst DEFAULT_RECEIPT_DEADLINE_MS = 10 * 60_000\n/** Session messages are read from this long before registration, so clock\n * skew between the product Worker and the Sandbox cannot hide the turn. */\nconst MESSAGE_READ_SKEW_MS = 10 * 60_000\n\n/**\n * Largest interrupted execution whose event stream is replayed for its\n * terminal result. The replay parses every event and re-compares the growing\n * response text on each token, so its CPU grows faster than the run; a longer\n * run takes its receipt from the recorded message and failure reason alone.\n */\nconst INTERRUPTED_RESULT_REPLAY_MAX_EVENTS = 2_000\n/** Bound on the second replay that reads a failed execution's harness cost. */\nconst HARNESS_COST_REPLAY_MS = 10_000\n/**\n * The fixed id of the terminal the sidecar appends when it fails an execution\n * whose runtime restarted before the run ended.\n */\nconst RUNTIME_RESTART_TERMINAL_EVENT_ID = 'interrupted-done'\n/** The sidecar's reason for that terminal, used when the replay is not read. */\nexport const RUNTIME_RESTARTED_ERROR = 'Execution interrupted: the agent runtime restarted before the run produced a terminal event. The run cannot be resumed; retry it.'\n\nfunction replayableExecution(run: Pick<SessionExecutionInfo, 'eventCount'>): boolean {\n return typeof run.eventCount === 'number' && run.eventCount <= INTERRUPTED_RESULT_REPLAY_MAX_EVENTS\n}\n\n/**\n * Serialized UTF-8 budget for one terminal receipt. A Cloudflare Workflow\n * refuses a step result over 1 MiB and D1 refuses a row over 2 MB, and a\n * receipt approaches both as tool payloads accumulate over a long turn.\n */\nexport const NATIVE_COMPLETION_RECEIPT_MAX_BYTES = 900 * 1024\n\n/** Per-string caps tried in order until a receipt fits its budget. */\n// Status, ids and paths stay well under the smallest cap.\nconst RECEIPT_STRING_CAPS = [16_384, 4_096, 1_024, 256] as const\n\nconst encoder = new TextEncoder()\n\nfunction serializedBytes(value: unknown): number {\n return encoder.encode(JSON.stringify(value)).length\n}\n\nfunction capString(value: string, cap: number): string {\n if (value.length <= cap) return value\n return `${value.slice(0, cap)}…[truncated ${value.length - cap} characters; the Sandbox session keeps the full value]`\n}\n\nfunction capStrings(value: unknown, cap: number): unknown {\n if (typeof value === 'string') return capString(value, cap)\n if (Array.isArray(value)) return value.map((item) => capStrings(item, cap))\n const object = record(value)\n if (!object) return value\n return Object.fromEntries(Object.entries(object).map(([key, item]) => [key, capStrings(item, cap)]))\n}\n\n/** Tool payloads and reasoning shrink; the answer text, files and interactions do not. */\nfunction capReceiptPart(part: Record<string, unknown>, cap: number): Record<string, unknown> {\n const type = String(part.type ?? '')\n if (type === 'tool') {\n const state = record(part.state)\n if (!state) return part\n const capped = capStrings(state, cap) as Record<string, unknown>\n if (serializedBytes(capped) === serializedBytes(state)) return part\n return { ...part, state: { ...capped, metadata: { ...record(capped.metadata), receiptTruncated: true } } }\n }\n if (type === 'reasoning' && typeof part.text === 'string' && part.text.length > cap) {\n return { ...part, text: capString(part.text, cap), receiptTruncated: true }\n }\n return part\n}\n\n/** Last resort for a receipt whose part count alone exceeds the budget. */\nfunction skeletonPart(part: Record<string, unknown>): Record<string, unknown> | null {\n const type = String(part.type ?? '')\n if (type === 'reasoning') return null\n if (type !== 'tool') return part\n const state = record(part.state)\n return {\n type: 'tool',\n ...(part.id !== undefined ? { id: part.id } : {}),\n ...(part.tool !== undefined ? { tool: part.tool } : {}),\n state: { status: state?.status ?? 'completed', metadata: { receiptTruncated: true } },\n }\n}\n\n/**\n * Fit a terminal receipt inside {@link NATIVE_COMPLETION_RECEIPT_MAX_BYTES}.\n * A receipt under the budget is returned unchanged. Over it, the longest\n * strings in tool payloads and reasoning are clipped with a marker, at\n * successively smaller caps, so a long turn's answer is always persistable.\n */\nexport function boundNativeCompletionReceipt(\n receipt: NativeCompletionReceipt,\n maxBytes: number = NATIVE_COMPLETION_RECEIPT_MAX_BYTES,\n): NativeCompletionReceipt {\n if (serializedBytes(receipt) <= maxBytes) return receipt\n for (const cap of RECEIPT_STRING_CAPS) {\n const bounded = { ...receipt, parts: receipt.parts.map((part) => capReceiptPart(part, cap)) }\n if (serializedBytes(bounded) <= maxBytes) return bounded\n }\n const skeleton = {\n ...receipt,\n parts: receipt.parts.map(skeletonPart).filter((part): part is Record<string, unknown> => part !== null),\n }\n if (serializedBytes(skeleton) <= maxBytes) return skeleton\n // Only the answer text is left to shrink.\n const textBudget = Math.max(0, Math.floor(maxBytes / 4))\n return {\n ...skeleton,\n text: capString(skeleton.text, textBudget),\n parts: skeleton.parts.map((part) => (part.type === 'text' && typeof part.text === 'string'\n ? { ...part, text: capString(part.text, textBudget) }\n : part)),\n }\n}\n\nfunction terminal(receipt: NativeCompletionReceipt): NativeCompletionObservation {\n const bounded = boundNativeCompletionReceipt(receipt)\n return bounded.state === 'completed'\n ? { state: 'completed', receipt: bounded }\n : { state: 'failed', receipt: bounded }\n}\n\nfunction timestamp(value: Date | number | null | undefined): number | undefined {\n if (value instanceof Date) return value.getTime()\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction isSandboxNotFoundError(value: unknown): boolean {\n const error = record(value)\n return error?.name === 'NotFoundError' || error?.code === 'NOT_FOUND' || error?.status === 404\n}\n\nfunction isCanonicalUserStop(error: unknown): boolean {\n return error === 'Execution cancelled by user' || error === 'Execution cancelled by the user'\n}\n\n/** A terminal receipt is public; runtime stderr stays in the native record. */\nfunction terminalFailureMessage(error: string, provenUserStop: boolean): string {\n if (provenUserStop) return 'Execution cancelled by the user'\n if (/\\bENOSPC\\b|no space left on device/i.test(error)) {\n return 'The Sandbox ran out of disk space before the execution finished.'\n }\n if (error === RUNTIME_RESTARTED_ERROR) return RUNTIME_RESTARTED_ERROR\n if (/\\bcancelled\\b|\\bcanceled\\b/i.test(error)) return 'Native Sandbox execution was cancelled.'\n if (/MCP.*(?:did not become ready|bootstrap)|(?:MCP|runtime) bootstrap failed/i.test(error)) {\n return 'The Sandbox could not start the agent runtime.'\n }\n return 'Native Sandbox execution failed before producing an answer.'\n}\n\n/** The SDK reads this execution's replay; reject contradictory terminal identity. */\nfunction exactFailedResult(value: unknown, turnId: string, sessionId: string): Record<string, unknown> | undefined {\n const result = record(value)\n if (result?.executionId !== turnId || (result.sessionId !== undefined && result.sessionId !== sessionId)) return undefined\n if (result.success !== false || !['error', 'failed', 'cancelled'].includes(String(result.status))) return undefined\n return typeof result.error === 'string' && result.error.trim() ? result : undefined\n}\n\n/**\n * Usage of a failed execution's SDK result. Its `costUsd` is the Platform\n * ledger charge alone (Sandbox 1.0.264), so the harness's own token cost is\n * read from the replayed terminal frames, where the sidecar puts a failure's\n * `totalCostUsd` on `error` and `done`; an unread replay leaves it unknown.\n */\nasync function failedResultUsage(\n session: ReturnType<NativeCompletionSessionSource['session']>, executionId: string, result: Record<string, unknown> | undefined,\n): Promise<ChatTurnUsage> {\n if (!result) return {}\n let harnessCostUsd: number | undefined\n try {\n for await (const event of session.events({ since: '0', executionId, signal: AbortSignal.timeout(HARNESS_COST_REPLAY_MS) })) {\n if (['result', 'error', 'done'].includes(event.type)) harnessCostUsd = readTokenCostUsd(record(event.data) ?? {}) ?? harnessCostUsd\n }\n } catch { /* unknown, never zero */ }\n const ledger = typeof result.costUsd === 'number' && Number.isFinite(result.costUsd) && result.costUsd >= 0 ? result.costUsd : undefined\n return {\n ...usageFromResult({ usage: result.usage }),\n ...(ledger !== undefined ? { costUsd: ledger } : {}),\n ...(harnessCostUsd !== undefined ? { harnessCostUsd } : {}),\n }\n}\n\nfunction interruptedMessages(messages: SessionMessage[], turnId: string): SessionMessage[] {\n return messages.filter((message) =>\n message.role === 'assistant'\n && message.metadata?.turnId === turnId\n && (message.metadata.interrupted === true || message.metadata.status === 'interrupted'),\n )\n}\n\nfunction turnAssistantMessages(messages: SessionMessage[], turnId: string): SessionMessage[] {\n return messages.filter((message) => message.role === 'assistant' && message.metadata?.turnId === turnId)\n}\n\nfunction consistent<T>(values: Array<T | undefined>): T | undefined {\n if (values.length === 0 || values.some((value) => value === undefined)) return undefined\n const first = values[0] as T\n return values.every((value) => value === first) ? first : undefined\n}\n\nfunction sum(values: Array<number | undefined>): number | undefined {\n if (values.some((value) => value === undefined)) return undefined\n return (values as number[]).reduce((total, value) => total + value, 0)\n}\n\n/** Assemble admitted exact receipts in dispatch order. Missing usage stays unknown. */\nexport function aggregateNativeCompletionReceipts(turns: readonly NativeCompletionTurnReceipt[]): NativeCompletionReceipt {\n const failed = turns.some((turn) => turn.state === 'failed')\n const usage: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) {\n const total = sum(turns.map((turn) => turn.usage[key]))\n if (total !== undefined) usage[key] = total\n }\n // A missing exact receipt is the terminal observer failure even when an\n // earlier execution also failed. Preserve that earlier partial transcript,\n // but surface why this aggregate could not be fully reconciled.\n const error = turns.find((turn) =>\n turn.error?.startsWith('Admitted native execution did not produce')\n || turn.error?.startsWith('Native Sandbox execution ledger is missing'),\n )?.error ?? turns.find((turn) => turn.error)?.error\n return {\n state: failed ? 'failed' : 'completed',\n text: turns.map((turn) => turn.text).join(''),\n parts: turns.flatMap((turn) => turn.parts),\n usage,\n ...(consistent(turns.map((turn) => turn.servedModel)) ? { servedModel: consistent(turns.map((turn) => turn.servedModel)) } : {}),\n ...(consistent(turns.map((turn) => turn.servedProvider)) ? { servedProvider: consistent(turns.map((turn) => turn.servedProvider)) } : {}),\n ...(consistent(turns.map((turn) => turn.servedSource)) ? { servedSource: consistent(turns.map((turn) => turn.servedSource)) } : {}),\n ...(error ? { error } : {}),\n completedTurnIds: turns.map((turn) => turn.turnId),\n }\n}\n\n/** The failure a completed run with an aborted tool call settles with. */\nexport const TOOL_ABORTED_ERROR = 'The Sandbox aborted a tool call before the turn finished, as when its runtime restarts mid-turn'\n\n/**\n * The name of a tool whose call the Sandbox aborted, or undefined. OpenCode\n * marks a tool interrupted by a runtime restart with \"Tool execution aborted\";\n * an ordinary tool error (a missing file, an HTTP 403) does not end the turn.\n */\nfunction abortedToolCall(parts: ReadonlyArray<Record<string, unknown>>): string | undefined {\n for (const part of parts) {\n if (part.type !== 'tool') continue\n const state = part.state as { status?: unknown; error?: unknown } | undefined\n if (state?.status === 'error' && /tool execution aborted/i.test(String(state.error ?? ''))) {\n return typeof part.tool === 'string' ? part.tool : 'tool'\n }\n }\n return undefined\n}\n\n/**\n * Whether the session still runs this admission's work, so its lease should be\n * renewed. The session's own status is not enough: it keeps a persisted\n * `running` status when the runtime restarts under it (the sidecar may report\n * that as recovery state `stale`, or not at all), while its execution ledger\n * has already failed the interrupted run. Renewing on status alone observed\n * GTM b81b's restarted completions forever. Live means an\n * admitted turn's execution is active, or not yet recorded while its dispatch\n * can still be on the way.\n */\nfunction admittedWorkIsLive(\n status: SessionInfo,\n runsByTurnId: ReadonlyMap<string, SessionExecutionInfo>,\n admittedTurnIds: readonly string[],\n dispatchMayBePending: boolean,\n): boolean {\n if (status.status !== 'queued' && status.status !== 'running') return false\n if (status.raw?.state === 'stale') return false\n return admittedTurnIds.some((turnId) => {\n const run = runsByTurnId.get(turnId)\n return run ? run.status === 'active' : dispatchMayBePending\n })\n}\n\nfunction missingTurnReceipt(turnId: string, error: string): NativeCompletionTurnReceipt {\n // An execution ledger entry proves this turn reached a terminal state, but\n // not that its terminal transcript was retained. Keep any earlier exact\n // evidence when the bounded wait expires; `{}` means aggregate usage is\n // unknown because this turn has no usage receipt.\n return { turnId, state: 'failed', text: '', parts: [], usage: {}, error }\n}\n\n/**\n * Observe only the turns admitted under `executionId`. Transport failures throw\n * so the durable owner retries. A missing or partial terminal record remains\n * `running` until the configured deadline; it never starts another run.\n */\nexport async function observeNativeCompletion(\n options: NativeCompletionObservationOptions,\n): Promise<NativeCompletionObservation> {\n const now = options.now ?? Date.now()\n let admission = await options.admissionStore.read(options.executionId)\n if (!admission) throw new Error('Native completion admission is missing')\n if (admission.executionId !== options.executionId) throw new Error('Native completion admission identity conflict')\n const leaseUntil = timestamp(admission.ownerLeaseUntil) ?? 0\n const source = options.source\n const session = source?.session(options.sessionId)\n let status: SessionInfo | null\n if (!session) {\n status = null\n } else {\n try {\n status = await session.status()\n } catch (error) {\n if (!isSandboxNotFoundError(error)) throw error\n status = null\n }\n }\n\n if (!status || !session || !source) {\n if (admission.state === 'open' && leaseUntil <= now) {\n admission = await options.admissionStore.closeExpired(options.executionId, new Date(now)) ?? admission\n }\n if (admission.state === 'open' || now - options.registeredAt < (options.absentDispatchDeadlineMs ?? DEFAULT_ABSENT_DISPATCH_DEADLINE_MS)) {\n return { state: 'running' }\n }\n return terminal(aggregateNativeCompletionReceipts([\n missingTurnReceipt(options.turnId, 'Native Sandbox dispatch was not observed before the admission deadline'),\n ]))\n }\n const exactSession = session\n const dispatchMayBePending = now - options.registeredAt < (options.absentDispatchDeadlineMs ?? DEFAULT_ABSENT_DISPATCH_DEADLINE_MS)\n let runsByTurnId: Map<string, SessionExecutionInfo> | undefined\n const readRuns = async () => runsByTurnId ??= new Map((await exactSession.runs()).map((run) => [run.executionId, run]))\n\n if (admission.state === 'open') {\n if (admittedWorkIsLive(status, await readRuns(), admission.admittedTurnIds, dispatchMayBePending)) {\n admission = await options.admissionStore.renew(options.executionId, new Date(now)) ?? admission\n } else if (leaseUntil <= now) {\n admission = await options.admissionStore.closeExpired(options.executionId, new Date(now)) ?? admission\n }\n if (admission.state === 'open') return { state: 'running' }\n }\n // `closeExpired` may return the current row after another owner appended a\n // continuation. Read its full ordered ledger rather than observing the\n // earlier snapshot from before the close attempt.\n const admittedTurnIds = [...admission.admittedTurnIds]\n if (admittedTurnIds.length === 0 || admittedTurnIds[0] !== options.turnId) {\n throw new Error('Native completion admission has an invalid turn sequence')\n }\n\n const ledger = await readRuns()\n const missingExecution = admittedTurnIds.find((turnId) => !ledger.has(turnId))\n if (missingExecution && dispatchMayBePending) return { state: 'running' }\n if (admittedTurnIds.some((turnId) => ledger.get(turnId)?.status === 'active')) return { state: 'running' }\n\n // Completed recovery owns its message read. Load interrupted history only\n // when it is needed, and share that one read across failed continuations.\n // Both reads start shortly before registration, so their size follows this\n // turn rather than the whole session.\n const since = Math.max(0, options.registeredAt - MESSAGE_READ_SKEW_MS)\n let messages: SessionMessage[] | undefined\n const recovered: NativeCompletionTurnReceipt[] = []\n for (const turnId of admittedTurnIds) {\n const run = ledger.get(turnId)\n if (!run) {\n recovered.push(missingTurnReceipt(turnId, 'Native Sandbox execution ledger is missing the admitted turn'))\n continue\n }\n const completed = run.status === 'completed'\n ? await readCompletedSandboxTurn(source, { turnId, sessionId: options.sessionId, since })\n : null\n if (run.status === 'completed' && completed) {\n const aborted = abortedToolCall(completed.parts ?? [])\n recovered.push({\n ...completed,\n turnId,\n // A run the runtime ended while a tool was still running reports\n // completed, but its reply stops mid-work. It is a failed turn.\n state: aborted ? 'failed' : 'completed',\n text: completed.text ?? '',\n parts: completed.parts ?? [],\n usage: completed.usage ?? {},\n ...(aborted ? { error: `${TOOL_ABORTED_ERROR} (${aborted})` } : {}),\n })\n continue\n }\n // The process that would stamp a turn interrupted is gone when its runtime\n // restarts; the sidecar fails the execution on restart, and the turn's own\n // assistant message holds whatever reply it had streamed.\n const restarted = run.status === 'failed' && run.lastEventId === RUNTIME_RESTART_TERMINAL_EVENT_ID\n let interrupted = run.status === 'failed' || run.status === 'cancelled'\n ? interruptedMessages(messages ??= await exactSession.messages({ limit: 1_000, since }), turnId)\n : []\n if (restarted && interrupted.length === 0) interrupted = turnAssistantMessages(messages ?? [], turnId)\n if (restarted && interrupted.length !== 1) {\n recovered.push({ turnId, state: 'failed', text: '', parts: [], usage: {}, error: RUNTIME_RESTARTED_ERROR })\n continue\n }\n // Bootstrap can fail before the runtime creates an assistant message. The\n // terminal execution replay is independent of that transcript projection.\n if ((run.status === 'failed' || run.status === 'cancelled') && interrupted.length === 0\n && turnAssistantMessages(messages ?? [], turnId).length === 0\n && run.sessionId === options.sessionId && replayableExecution(run)) {\n const result = exactFailedResult(await exactSession.result({ executionId: turnId }), turnId, options.sessionId)\n if (result) {\n recovered.push({\n turnId, state: 'failed', text: '', parts: [], usage: await failedResultUsage(exactSession, turnId, result),\n ...attributionFromResult(result), error: terminalFailureMessage(result.error as string, run.status === 'cancelled' && isCanonicalUserStop(result.error)),\n })\n continue\n }\n }\n if ((run.status === 'failed' || run.status === 'cancelled') && interrupted.length === 1) {\n const message = recoverSandboxAssistantMessage(interrupted[0]!)\n const result = replayableExecution(run)\n ? await exactSession.result({ executionId: turnId }) as unknown as Record<string, unknown>\n : undefined\n const provenUserStop = run.status === 'cancelled'\n && (isCanonicalUserStop(interrupted[0]!.metadata?.interruptReason)\n || isCanonicalUserStop(exactFailedResult(result, turnId, options.sessionId)?.error))\n recovered.push({\n turnId,\n state: 'failed',\n text: message.text ?? (typeof result?.response === 'string' ? result.response : undefined) ?? '',\n parts: message.parts ?? [],\n usage: { ...message.usage, ...await failedResultUsage(exactSession, turnId, result) },\n ...attributionFromResult(result),\n error: terminalFailureMessage((typeof result?.error === 'string' ? result.error : undefined)\n ?? interrupted[0]!.metadata?.interruptReason\n ?? (restarted ? RUNTIME_RESTARTED_ERROR : undefined)\n ?? status.failureReason?.message\n ?? 'Native Sandbox execution failed.', provenUserStop),\n })\n continue\n }\n const closedAt = timestamp(admission.closedAt)\n ?? timestamp(admission.updatedAt)\n ?? options.registeredAt\n if (now - closedAt < (options.receiptDeadlineMs ?? DEFAULT_RECEIPT_DEADLINE_MS)) return { state: 'running' }\n recovered.push(missingTurnReceipt(\n turnId,\n `Admitted native execution did not produce an exact completion: ${turnId}`,\n ))\n }\n return terminal(aggregateNativeCompletionReceipts(recovered))\n}\n"],"mappings":";;;;;;;;;;;;;;;AAUA,SAAS,wBAAwB;AAiCjC,SAAS,aAAa,OAAoC;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,EAAG,QAAO;AACvD,QAAM,SAAS,OAAO,KAAK;AAC3B,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;AAEA,SAAS,YAAYA,SAAgC,MAAoC;AACvF,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,aAAaA,UAAS,GA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