@byok-sdk/bot-collaboration 0.44.1 → 0.45.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/team-model.ts","../src/model.ts","../src/channel.ts","../src/delivery-superseded.ts","../src/routines.ts","../src/retention.ts","../src/schema.ts","../src/team.ts"],"names":["definition","hash","rows","contextPack","fields","canonical"],"mappings":";;;;AAkCO,SAAS,SAAA,EAAuB,CACrC,OAAO,CAAE,IAAA,CAAM,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,MAAA,CAAQ,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,cAAA,CAAgB,EAAG,CAChG,CCqCO,SAAS,QAAQ,WAAA,CAAuD,CAC7E,GAAI,WAAA,CAAY,aAAA,GAAkB,MAAA,CAAW,WAAA,CAAY,aAAA,CAAgB,IAAA,CAAK,CAC5E,IAAA,CAAM,SAAA,EAAU,CAAG,KAAA,CAAO,EAAC,CAAG,QAAS,EAAC,CAAG,WAAA,CAAa,EAAC,CAAG,OAAA,CAAS,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,OAAA,CAAS,EAAC,CAAG,OAAA,CAAS,GAAI,SAAA,CAAW,EAAC,CAAG,KAAA,CAAO,EAAC,CACrI,QAAA,CAAU,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,QAAA,CAAU,CACrC,CAAC,CAAA,CAGD,OAAO,WAAA,CAAY,aACrB,CChBO,SAAS,QAAA,CAAS,MAAA,CAAoD,CAC3E,OAAO,OAAO,MAAA,EAAQ,EAAA,GAAO,QAAA,EAAY,MAAA,CAAO,GAAG,MAAA,CAAS,CAAA,GAAM,MAAA,CAAO,IAAA,GAAS,OAAA,EAAW,MAAA,CAAO,IAAA,GAAS,KAAA,CAC/G,CAEO,SAAS,OAAA,CAAQ,SAAA,CAAsB,KAAA,CAAwB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,OAAO,IAAA,CAAK,MAC/B,CAAC,CAAC,CAAA,CACF,GAAI,OAAA,CAAQ,SAAA,CAAW,OAAA,CAAQ,WAAA,CAAa,IAAM,CAChD,GAAI,IAAA,CAAK,KAAA,CAAM,MAAA,EAAU,eAAA,CAAiB,MAAM,IAAI,KAAA,CAAM,uBAAuB,CAAA,CACjF,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,CAAE,EAAA,CAAIH,IAAAA,CAAK,CAAC,MAAA,CAAQ,WAAW,CAAC,CAAA,CAAG,IAAA,CAAM,OAAA,CAAQ,UAAW,IAAK,CAAC,EACpF,CAAC,EACH,CACO,SAAS,IAAA,CAAK,KAAA,CAAgB,KAAA,CAAyB,CAAE,OAAOI,SAAAA,CAAU,KAAK,CAAA,GAAMA,SAAAA,CAAU,KAAK,CAAG","file":"chunk-6X7ARUDF.js","sourcesContent":["import type { AgentHomeProjectionRequest } from '@byok-sdk/server';\nimport type { ExecutionTemplate } from '@byok-sdk/server/execution-core';\nimport type { Room, Round, Seat } from './rules/rooms.js';\nimport type { Autonomy } from './rules/autonomy.js';\nimport type { ExternalTeam } from './rules/team.js';\n\nexport type { Room, Round, Seat };\nexport interface BotProfile {\n id: string; name: string; role: string; persona: string; model: string;\n mainBot: boolean; archived: boolean; revision: string; readyRevision: string | null;\n /**\n * Host autonomy policy (#1229). Absent reads as `observe`, the default of a new Bot: each create_routine, cross-Bot\n * delegate and room_call is recorded as would-do until the owner switches this Bot to `auto`. Host state, never wire.\n */\n autonomy?: Autonomy;\n /** #1319: the team authority suspended this Bot. It stays a member and takes no new work. Absent: participating. */\n participation?: 'suspended';\n execution: ExecutionTemplate;\n}\nexport interface HomeOperation {\n sequence: number; botId: string; request: AgentHomeProjectionRequest;\n retries: AgentHomeProjectionRequest[]; retryAt?: number;\n status: 'pending' | 'applied' | 'failed'; error?: string;\n /** Set in the transaction before the first write is sent (#957), so a crash or a failed send still counts it as sent. */\n sent?: true;\n}\nexport interface TeamState {\n bots: Record<string, BotProfile>; rooms: Record<string, Room>; rounds: Record<string, Round>;\n seats: Record<string, Seat>; roots: Record<string, { autonomous: number; late: number }>;\n notes: Array<{ id: string; text: string }>;\n homeOperations: HomeOperation[];\n /** External team mode (#739 Q4c). Absent: this Host owns its local team. */\n external?: ExternalTeam;\n}\nexport function emptyTeam(): TeamState {\n return { bots: {}, rooms: {}, rounds: {}, seats: {}, roots: {}, notes: [], homeOperations: [] };\n}\n","import type { ResultSchema } from '@byok-sdk/protocol';\nimport { emptyTeam, type TeamState } from './team-model.js';\nimport type { Json } from '@byok-sdk/server/execution-core';\nimport type { ChannelState } from './delivery-routing.js';\nimport type { InputBatch, UserInput } from './rules/coalesce.js';\nimport { json, type Budget, type Card, type Question, type Rejection, type Turn } from './rules/turn.js';\nimport type { AcceptedReply, Batch, Delegation, Unit } from './rules/delegation.js';\nimport type { CommandRecord } from './rules/commit.js';\nimport type { DeviceTopology } from './topology.js';\nimport type { SwitchExportMark } from './migration.js';\nimport type { SwitchImport } from './switch.js';\nimport type { AutonomyState, WouldDo } from './rules/autonomy.js';\nimport type { DreamState } from './dream.js';\n\nexport type { Authority, InputBatch, SealReason, UserInput } from './rules/coalesce.js';\nexport { addBatchTurns, addTurn, json } from './rules/turn.js';\nexport type { Budget, Card, Question, Rejection, ReplyEntry, Turn, TurnFields, Verdict } from './rules/turn.js';\nexport type { AcceptedReply, Batch, Delegation, DelegationCancel, Unit } from './rules/delegation.js';\n\n/**\n * The K8 state. A Host ledger keeps it in its application body, and the ledger's `k8` format row (`botLedgerOptions`) is\n * its format.\n * Retention keeps settled rows in K4 application rows (#798). Bot routines are K4 routines with the `bot-routine`\n * occurrence hook.\n */\nexport interface CollaborationState extends AutonomyState {\n team: TeamState; turns: Record<string, Turn>; budgets: Record<string, Budget>;\n delegations: Record<string, Delegation>; batches: Record<string, Batch>; units: Record<string, Unit>;\n replies: Record<string, AcceptedReply>;\n schemas: Record<string, ResultSchema>; questions: Record<string, Question>; cards: Record<string, Card>;\n rejected: Rejection[]; audit: string[]; sequence: number;\n /** Input coalescing. Both appear at the first coalesced input. */\n inputs?: Record<string, UserInput>; inputBatches?: Record<string, InputBatch>;\n /** Host-only routes and final-content outbox. Never included in ContextPack or projections. */\n channel?: ChannelState;\n /**\n * Commit contract (#739 D1). Both appear at the first commit; a state without them is at revision 0.\n * `commands` holds the dedup evidence of owner commands. K4 deduplicates terminals and messages itself.\n */\n revision?: number; commands?: Record<string, CommandRecord>;\n /**\n * Host intents (#882): the handler name of each Host-owned K4 intent, by intent key. A record lives as long as K4\n * keeps its intent. It appears at the first Host intent, so an older ledger reads an empty table.\n */\n hostIntents?: Record<string, { handler: string }>;\n /**\n * L card call claims (#958): a card id is here from the transaction before its connector call until the one that settles\n * it. It appears at the first claim, so an older ledger reads an empty table. Never in ContextPack or projections.\n */\n cardCalls?: Record<string, true>;\n /**\n * L owner records by device id (#957, §4.1), from `topology.ts`. A device appears at its first switch step, so an older\n * ledger reads every device as L at revision 0. Never in ContextPack or projections.\n */\n topology?: Record<string, DeviceTopology>;\n /**\n * L switch records (#975), from `switch.ts`. `switchExport` appears at the export of an old owner and stays; while it is\n * here the Host writes nothing. `switchImport` is here from the load of a new owner until its commit toward L. Neither\n * moves in an export, and neither is in ContextPack or projections.\n */\n switchExport?: SwitchExportMark; switchImport?: SwitchImport;\n /**\n * Would-do rows of observing Bots (#1229), keyed by `wouldDoId(taskId, action, index)`. They appear at the first\n * observed action, so an older ledger reads none. They are Host UI history, never part of the Bot's ContextPack or wire.\n */\n wouldDo?: Record<string, WouldDo>;\n /**\n * Dreaming (#1475), from `dream.ts`: the owner of each dream intent and the last result of each Bot. It appears at the first\n * dream routine, so an older ledger reads none. Never in ContextPack or projections.\n */\n dreams?: DreamState;\n}\n/** The K8 state of an application body, created empty at its first use. */\nexport function stateOf(application: Record<string, Json>): CollaborationState {\n if (application.collaboration === undefined) application.collaboration = json({\n team: emptyTeam(), turns: {}, budgets: {}, delegations: {}, batches: {}, units: {}, replies: {}, schemas: {}, questions: {}, cards: {},\n rejected: [], audit: [], sequence: 0,\n });\n // SAFETY: The store that holds this body admitted its format when it opened (a Host ledger's `k8` row), so the value is\n // the state this build writes.\n return application.collaboration as unknown as CollaborationState;\n}\n","import { hash } from '@byok-sdk/server/execution-core';\nimport type { Mentions } from './rooms.js';\n\n/** A sender that the channel adapter took from authenticated platform data (docs/host-im-adapter.md R2). */\nexport interface Principal { id: string; kind: 'human' | 'bot' }\nexport interface Conversation { kind: 'direct' | 'group'; id: string }\nexport interface ReplyRoute {\n kind: 'reply'; channel: string; inboundId: string; token: string; expiresAt: number;\n}\nexport interface PushRoute {\n kind: 'push'; id: string; conversation: Conversation; channel: string; target: string;\n optedInBy: string; optedInAt: number; revokedAt?: number;\n}\n/**\n * `staged`: a Bot reply accepted before its Turn outcome committed (#1762). No sender takes it. The outcome transaction\n * promotes it to `pending`; a Turn whose intent concludes otherwise rejects it as `outcome_not_applied`.\n */\nexport type DeliveryState = 'staged' | 'pending' | 'sending' | 'accepted' | 'rejected' | 'unknown';\n/** `turnId` is the Turn that queued the delivery. Retention keeps the delivery with that Turn's root. */\nexport interface Delivery {\n id: string; taskId: string; turnId: string; messageId: string; body: string;\n conversation: Conversation; channel: string;\n route: { kind: 'reply'; inboundId: string } | { kind: 'push'; pushRouteId: string };\n state: DeliveryState; attempts: number; nextAttemptAt?: number;\n platformMessageId?: string; code?: string; resendOf?: string;\n}\n/** A rejection is authoritative. An exception leaves delivery acceptance unknown. */\nexport interface ChannelPort {\n send(input: { deliveryId: string; route: ReplyRoute | PushRoute; body: string }, signal: AbortSignal): Promise<\n | { result: 'accepted'; platformMessageId: string }\n | { result: 'rejected'; code: string; retryable: boolean; retryAfterMs?: number }>;\n readback?(deliveryId: string): Promise<'accepted' | 'absent' | 'unsupported'>;\n}\nexport interface ChannelOptions {\n port: ChannelPort;\n /** Verified platform bot principal ids. These ids are scoped to their channel. */\n self?: Record<string, readonly string[]>;\n /** Business send deadline. The default is 15 seconds. */\n sendTimeoutMs?: number;\n}\n/**\n * Optional last argument of the owner APIs and `roomInput`. Its length tells an omitted principal\n * from a given `undefined`, because JavaScript applies a default parameter to both.\n */\nexport type PrincipalArg = [principal?: Principal];\n/**\n * One inbound IM message after the adapter's translation. The adapter maps the platform chat\n * to a Host conversation: a Bot id for `direct`, a room id for `group`.\n */\nexport interface InboundMessage {\n channel: string; platformMessageId: string;\n conversation: Conversation;\n /** Absent when the adapter cannot verify the sender. */\n sender?: Principal;\n text: string;\n /** Bot ids from the platform's mention entities (R6). The Host never scans `text`. */\n mentions: Mentions;\n replyRoute?: ReplyRoute;\n deliveryId?: string;\n receivedAt?: number;\n}\n/** Echo candidates only reconcile exact delivery identities. They never create input. */\nexport type InboundClass = 'unverified_sender' | 'echo' | 'bot_audit' | 'bot_background' | 'owner_input' | 'not_owner' | 'room_input';\n\n/** A principal needs a non-empty id and a known kind. */\nexport function verified(sender: Principal | undefined): sender is Principal {\n return typeof sender?.id === 'string' && sender.id.length > 0 && (sender.kind === 'human' || sender.kind === 'bot');\n}\n/** Only the human principal with the owner id. A bot account never has owner authority. */\nexport function isOwner(principal: Principal, owner: string): boolean {\n return principal.kind === 'human' && principal.id === owner;\n}\n/** The guide's §3 order. The first match wins. */\nexport function classifyInbound(message: InboundMessage, owner: string, self?: Record<string, readonly string[]>): InboundClass {\n const sender = message.sender;\n if (!verified(sender)) return 'unverified_sender';\n const selfBots = self && Object.hasOwn(self, message.channel) ? self[message.channel] : undefined;\n if (sender.kind === 'bot' && selfBots?.includes(sender.id)) return 'echo';\n const direct = message.conversation.kind === 'direct';\n if (sender.kind === 'bot') return direct ? 'bot_audit' : 'bot_background';\n if (!direct) return 'room_input';\n return isOwner(sender, owner) ? 'owner_input' : 'not_owner';\n}\n/** A redelivered platform event maps to the same input. A platform message id can be unique only within one chat. */\nexport function inboundKey(message: InboundMessage): string {\n return hash([message.channel, message.conversation.kind, message.conversation.id, message.platformMessageId]);\n}\n","import type { Delivery } from './channel.js';\n/** Manual replacements keep their predecessors as history, with acceptance still unknown. */\nexport function supersededDeliveryIds(deliveries: Readonly<Record<string, Delivery>>): Set<string> {\n return new Set(Object.values(deliveries).flatMap(row => row.resendOf === undefined ? [] : [row.resendOf]));\n}\n","import { checkRoutineSchedule, nextRoutineOccurrence, HostOfferSealedPayloadSchema, type CreateRoutineAction, type RoutineSchedule, type RoutineScheduleFields,\n type UpdateRoutineAction } from '@byok-sdk/protocol';\nimport { canonical, concludeOccurrence, hash, occurrenceIntentKey, occurrenceOfIntentKey, type ExecutionTemplate, type HostOccurrenceRoutineDefinition, type HostOccurrenceRun, type LedgerState,\n type NextOccurrence, type Routine } from '@byok-sdk/server/execution-core';\nimport { addTurn, json, type Authority, type CollaborationState, type Turn } from './model.js';\nimport type { SealedRoutineTemplate } from './rules/sync.js';\nimport type { SealedRoutineRef } from './rules/turn.js';\nimport type { DreamState } from './dream.js';\n\nexport type { SealedRoutineTemplate } from './rules/sync.js';\n\n// Bot policy over K4 routines. K4 owns the routine rows, versions, slots, occurrences and wakes.\n\n/** The K4 occurrence hook of Bot routines. Other K4 routines of the Host are not Bot routines. */\nexport const BOT_ROUTINE = 'bot-routine';\n/** The K4 occurrence hook of dream routines (`dream.ts`). Bot policy never reads these rows. */\nexport const BOT_DREAM = 'bot-dream';\n/** A routine Turn expires this long after K4 records its occurrence. */\nexport const ROUTINE_WAIT_MS = 300_000;\n/** A delivery later than this after its planned time is a catch-up. */\nexport const ROUTINE_LATE_AFTER_MS = 60_000;\n\n/** Fixed at creation. Owner and authority never change between versions, and a routine stays plain or sealed. */\nexport type BotRoutineInput = { owner: string; authority: Authority; prompt: string }\n | { owner: string; authority: 'owner'; sealed: SealedRoutineTemplate };\nconst sealedOf = (input: BotRoutineInput): SealedRoutineTemplate | undefined => 'sealed' in input ? input.sealed : undefined;\n/**\n * What the owner's member endpoint sends to create or reseal a routine: the schedule and one template, sealed for routine\n * `routineId` version `definitionVersion`.\n */\nexport interface SealedRoutineAction { routineId: string; definitionVersion: number; schedule: RoutineScheduleFields; sealed: SealedRoutineTemplate }\n/** The member sealed for another version than the one this command stages. Nothing is written; read the routine again. */\nexport class SealedRoutineVersionError extends Error {\n readonly code = 'sealed_routine_version';\n constructor(readonly expected: number) { super(`Seal the template for version ${expected}`); this.name = 'SealedRoutineVersionError'; }\n}\n/** A sealed routine allows only `task-input`: K8 reads the Bot outcome to settle the Turn, so the output stays plaintext. */\nconst SEALED_ROUTINE_CATEGORIES = ['task-input'];\n/** The ContextPack view of one Bot routine. */\nexport interface BotRoutine {\n id: string; owner: string; current: number; pending: number | null; lifecycle: Routine['lifecycle']; status: Routine['status'];\n /** A sealed routine has no `prompt` and shows nothing else of its template: the view goes into each ContextPack. */\n definition: { version: number; schedule: RoutineScheduleFields; prompt?: string; sealed?: true; target: string };\n lastError?: { at: number; message: string; wakeKey?: string };\n}\n\nexport const dreamTable = (state: CollaborationState): DreamState => state.dreams ??= { bots: {}, open: {} };\n/** The K4 calendar of the Bot Host core. A rule is a `RoutineSchedule` whose `tz` is the definition time zone. */\nexport const routineCalendar: NextOccurrence = (definition, after) => {\n const schedule = definition.rule;\n if (!schedule || typeof schedule !== 'object' || Array.isArray(schedule) || schedule.tz !== definition.timeZone) {\n throw new Error('A routine rule is a RoutineSchedule in the definition time zone');\n }\n return nextRoutineOccurrence(schedule as unknown as RoutineSchedule, after);\n};\nfunction fields(routine: Routine): BotRoutineInput | undefined {\n const spec = routine.definition.hostOccurrence;\n return spec?.type === BOT_ROUTINE ? spec.input as unknown as BotRoutineInput : undefined;\n}\nfunction definition(id: string, version: number, schedule: RoutineScheduleFields, input: BotRoutineInput): HostOccurrenceRoutineDefinition {\n return { id, version, timeZone: schedule.tz, rule: json(schedule), waitMs: ROUTINE_WAIT_MS, lateAfterMs: ROUTINE_LATE_AFTER_MS,\n hostOccurrence: { type: BOT_ROUTINE, input: json(input) } };\n}\n/**\n * A schedule from an owner or member command. The bot-turn-outcome.v1 contract checks the schedules of an outcome, so\n * only these entries check here.\n */\nfunction scheduled(schedule: RoutineScheduleFields): RoutineScheduleFields {\n const check = checkRoutineSchedule(schedule);\n if (!check.ok) throw new Error(`${check.code}: ${check.message}`);\n return schedule;\n}\n/** The owner `updateRoutine` API. An outcome's update_routine passed the contract, which refuses the same as this. */\nexport function ownerRoutineUpdate(action: UpdateRoutineAction): UpdateRoutineAction {\n if (action.schedule === undefined && action.prompt === undefined) throw new Error('An update must change schedule or prompt');\n if (action.schedule !== undefined) scheduled(action.schedule);\n return action;\n}\n/** The Bot routines among the Host's K4 routine rows. */\nexport function botRoutines(routines: Iterable<Routine>): BotRoutine[] {\n const views: BotRoutine[] = [];\n for (const routine of routines) {\n const input = fields(routine);\n if (!input) continue;\n const { id, version, rule } = routine.definition;\n views.push({ id, owner: input.owner, current: version, pending: routine.pending?.version ?? null, lifecycle: routine.lifecycle, status: routine.status,\n definition: { version, schedule: rule as unknown as RoutineScheduleFields,\n ...('sealed' in input ? { sealed: true as const } : { prompt: input.prompt }), target: input.owner },\n ...(routine.calendarErrors?.length ? { lastError: routine.calendarErrors.at(-1)! } : {}) });\n }\n return views;\n}\n/** The definition for `RoutineCommands.create`. Each owner has at most 8 routines that are not completed. */\nexport function createDefinition(routines: readonly Routine[], owner: string, taskId: string, index: number, action: CreateRoutineAction,\n authority: Authority): HostOccurrenceRoutineDefinition {\n if (action.target !== undefined) throw new Error('An ordinary Bot cannot supply target');\n if (routines.filter(routine => fields(routine)?.owner === owner && routine.lifecycle !== 'completed').length >= 8) throw new Error('Routine limit is 8');\n return definition(hash([taskId, 'create_routine', index]), 1, action.schedule, { owner, authority, prompt: action.prompt });\n}\nexport function owned(routines: readonly Routine[], owner: string, id: string): Routine {\n const routine = routines.find(row => row.definition.id === id);\n if (!routine || fields(routine)?.owner !== owner || routine.lifecycle === 'completed') throw new Error('Routine is unavailable to this Bot');\n return routine;\n}\n/**\n * The routine that `end_routine` completes (§55c): any Bot routine that is open, whatever its owner, so the Main Bot can end\n * the routine of an archived Bot. The command checks the Main Bot role.\n */\nexport function endable(routines: readonly Routine[], id: string): Routine {\n const routine = routines.find(row => row.definition.id === id);\n if (!routine || !fields(routine) || routine.lifecycle === 'completed') throw new Error('No open Bot routine has this id');\n return routine;\n}\n/** The next version for `RoutineCommands.update`. It builds on `pending` when one is staged. */\nexport function updateDefinition(routines: readonly Routine[], owner: string, action: UpdateRoutineAction): HostOccurrenceRoutineDefinition {\n const routine = owned(routines, owner, action.routineId);\n const prior = routine.pending ?? routine.definition, input = prior.hostOccurrence!.input as unknown as BotRoutineInput;\n // Only the member can seal a new version, so neither a Bot nor an owner prompt edit reaches a sealed routine.\n if ('sealed' in input) throw new Error('A sealed routine changes only through resealRoutine');\n return definition(prior.id, prior.version + 1, action.schedule ?? prior.rule as unknown as RoutineScheduleFields,\n { ...input, prompt: action.prompt ?? input.prompt });\n}\n\n/**\n * Checks one sealed template for routine `id` version `version` of a Bot with execution template `execution`: the\n * categories, the Agent, and the offer that each occurrence will carry. It runs at create and at reseal.\n */\nfunction checkSealed(id: string, version: number, sealed: SealedRoutineTemplate, execution: ExecutionTemplate): void {\n if (canonical(sealed.sealing.categories) !== canonical(SEALED_ROUTINE_CATEGORIES)) throw new Error('A sealed routine seals task-input only');\n const { agentRef } = execution.payload;\n if (canonical(sealed.agentRef) !== canonical({ agentId: agentRef.agentId, profileRevision: agentRef.profileRevision })) {\n throw new Error('The template is sealed for another Agent revision');\n }\n const { instruction: _, ...plain } = execution.payload;\n const offer = { ...plain, sealing: sealed.sealing, sealed: sealed.template, routineRef: { routineId: id, definitionVersion: version, notAfter: sealed.notAfter } };\n if (!HostOfferSealedPayloadSchema.safeParse(offer).success) throw new Error('Supply a valid sealed template');\n if ('ciphertextRef' in sealed.template) throw new Error('A sealed routine template must be inline');\n}\n/**\n * The definition of a new sealed routine. The member picks `routineId` (a fresh UUID), because the template binds it, and\n * seals version 1. An id that any routine row already has is refused, whatever its lifecycle, except an exact retry: the\n * version 1 that the same command made, which K4 `create` takes as a no-op. It counts toward the limit of 8 open routines\n * of the owner.\n */\nexport function sealedDefinition(routines: readonly Routine[], owner: string, action: SealedRoutineAction,\n execution: ExecutionTemplate): HostOccurrenceRoutineDefinition {\n if (action.definitionVersion !== 1) throw new SealedRoutineVersionError(1);\n const next = definition(action.routineId, 1, scheduled(action.schedule), { owner, authority: 'owner', sealed: action.sealed });\n const existing = routines.find(routine => routine.definition.id === action.routineId);\n // A member retry after a lost response resends the same bytes.\n if (existing) {\n if (canonical(existing.definition) === canonical(next)) return next;\n throw new Error('A routine already has this id');\n }\n if (routines.filter(routine => fields(routine)?.owner === owner && routine.lifecycle !== 'completed').length >= 8) throw new Error('Routine limit is 8');\n checkSealed(action.routineId, 1, action.sealed, execution);\n return next;\n}\n/**\n * The next version of a sealed routine, with a new template. Only a routine that is already sealed takes one, and it keeps\n * its owner and authority. The template must be sealed for `max(current, pending) + 1`, else `SealedRoutineVersionError`.\n * A retry resends the same template bytes; K4 treats the same definition as a no-op.\n */\nexport function resealDefinition(routines: readonly Routine[], owner: string, action: SealedRoutineAction,\n execution: ExecutionTemplate): HostOccurrenceRoutineDefinition {\n const version = action.definitionVersion;\n const routine = owned(routines, owner, action.routineId);\n const prior = routine.pending ?? routine.definition, input = prior.hostOccurrence!.input as unknown as BotRoutineInput;\n if (!('sealed' in input)) throw new Error('Only a sealed routine takes a new template');\n const next = definition(action.routineId, version, scheduled(action.schedule), { owner: input.owner, authority: input.authority, sealed: action.sealed });\n // A member retry resends the same bytes: the current or staged version it made already is a K4 no-op.\n if ([routine.definition, routine.pending].some(row => canonical(row) === canonical(next))) return next;\n if (version !== prior.version + 1) throw new SealedRoutineVersionError(prior.version + 1);\n checkSealed(action.routineId, version, action.sealed, execution);\n return next;\n}\n/** The sealed template of one routine version: the K8 `sealedTemplate` lookup of a Host sync. */\nexport function sealedTemplate(routines: Iterable<Routine>, ref: SealedRoutineRef): SealedRoutineTemplate | undefined {\n for (const routine of routines) {\n for (const row of [routine.definition, routine.pending]) {\n if (row?.id === ref.routineId && row.version === ref.definitionVersion) {\n const input = fields({ ...routine, definition: row });\n return input && sealedOf(input);\n }\n }\n }\n return undefined;\n}\n/** The `bot-routine` occurrence hook. It writes the routine Turn in the occurrence commit. `sync` promotes it. */\nexport function routineTurn(state: CollaborationState, run: HostOccurrenceRun): void {\n const input = run.input as unknown as BotRoutineInput, id = occurrenceIntentKey(run.occurrenceKey);\n // A sealed routine Turn names its routine version; the sync freezes that version's template, and the Host keeps no request.\n addTurn(state, { id, root: id, source: 'routine', botId: input.owner, hop: 0, authority: input.authority,\n ...('sealed' in input ? { request: '', sealedRoutine: { routineId: run.routineId, definitionVersion: run.definitionVersion } } : { request: input.prompt }) });\n}\n/** A routine Turn id is its K4 intent key, `occurrenceIntentKey(<occurrence key>)`. */\nexport function routineOccurrence(turn: Pick<Turn, 'id'>): string {\n const key = occurrenceOfIntentKey(turn.id);\n if (key === undefined) throw new Error(`Routine Turn ${turn.id} names no occurrence`);\n return key;\n}\n/**\n * A routine Turn that ends without an intent concludes its open occurrence.\n * Then a staged version can switch, and `compact` can remove the row.\n */\nexport function concludeRoutineTurn(s: LedgerState, turn: Turn): boolean {\n const key = routineOccurrence(turn), occurrence = s.occurrences[key];\n if (!occurrence?.hook || occurrence.intentId || occurrence.conclusion) return false;\n concludeOccurrence(s, key, 'cancelled');\n return true;\n}\n","import { buildHandoffPack, type HandoffPackBudgets } from '@byok-sdk/protocol';\nimport { hash, MIN_TOMBSTONE_RETENTION_MS, time, type Json } from '@byok-sdk/server/execution-core';\nimport { DEFAULT_CONTEXT_TURN_LIMIT, handoffFrameBytes, handoffTurn } from './rules/context.js';\nimport type { CollaborationState, Turn } from './model.js';\nimport { refuseUnmigratedWouldDo } from './rules/autonomy.js';\nimport { supersededDeliveryIds } from './delivery-superseded.js';\n\n/**\n * Explicit retention (#798). The Host acknowledges settled roots. One call moves every row of each root out of the\n * state into per-id rows, and retires the root's Turn, input and round ids for good. It never runs on its own.\n * Command records answer replays for `retentionMs` after they move; the other rows stay.\n */\nexport interface RetentionInput {\n /**\n * Root ids: the `root` field of a Turn projection, or the round root that `roomInput` and a room `receive` return.\n * A room seat Turn shows its seat id as `root`; it is refused with `seat_root` and its `roundRoot`.\n * A root that is already archived counts again harmlessly.\n */\n acknowledgedRoots: readonly string[];\n now: number;\n /** At least seven days: the replay window of the moved command records. */\n retentionMs: number;\n}\n/** The ContextPack limits of the Host. Rows in the window of a Bot stay in the state. */\nexport interface RetentionLimits {\n contextTurnLimit: number;\n /** The budgets of the Bot history: the ones the Host freezes with, so its Turns read only what stays. */\n handoff: HandoffPackBudgets;\n}\n/** K4 facts by Turn id. */\nexport interface RetentionFacts {\n /** The Turn still has its K4 intent. */\n hasIntent(turnId: string): boolean;\n /** The routine occurrence of a routine Turn is not concluded yet. */\n occurrenceOpen(turnId: string): boolean;\n}\n/** Where retention writes, in the same transaction as the state. L: the K4 application row port. */\nexport interface RetentionStore {\n put(namespace: string, id: string, value: Json, expiresAt?: number): void;\n expire(namespace: string, now: number): number;\n retire(namespace: string, id: string): void;\n isRetired(namespace: string, id: string): boolean;\n}\nexport interface RetentionResult {\n archivedRoots: number; alreadyArchivedRoots: number; archivedRows: number;\n archivedCommands: number; expiredCommands: number; beforeBytes: number; afterBytes: number;\n}\n/**\n * The whole call changes nothing. `protected_root`: the root is still in use; acknowledge it again after it settles.\n * `seat_root`: the id is a room seat Turn, which belongs to its round's root. Acknowledge `roundRoot` instead; a retry of\n * the seat id fails the same way each time.\n */\nexport type RetentionRefusedCode = 'protected_root' | 'seat_root';\nexport class RetentionRefused extends Error {\n constructor(readonly code: RetentionRefusedCode, readonly root: string, reason: string, readonly roundRoot?: string) {\n super(`Retention refused: ${reason}`); this.name = 'RetentionRefused';\n }\n}\nconst OPEN_DELIVERY = new Set(['staged', 'pending', 'sending', 'unknown']);\nconst values = <T>(rows: Record<string, T> | undefined): T[] => Object.values(rows ?? {});\nconst own = <T>(rows: Record<string, T> | undefined, id: string): T | undefined => rows && Object.hasOwn(rows, id) ? rows[id] : undefined;\n\n/**\n * The ids that a Bot's next ContextPacks can still read: the turns of its handoff pack, up to its newest, and its last\n * cards and questions. The pack leaves out the Turns that can still freeze, and its total always gives `earlier` all of\n * `earlyBytes`. A freeze has no more than that, a Cross-Bot Turn often less, and its extra Turns only start `earlier` at a\n * newer turn. So no freeze reads a turn older than this pack.\n */\nfunction contextWindow(state: CollaborationState, limit: number, handoff: HandoffPackBudgets): Set<string> {\n const kept = new Set<string>(), byBot = new Map<string, { turns: Turn[]; cards: string[]; questions: string[] }>();\n const of = (botId: string) => {\n let rows = byBot.get(botId);\n if (!rows) byBot.set(botId, rows = { turns: [], cards: [], questions: [] });\n return rows;\n };\n // A frozen Turn is `processing` (its offer is in K4) or concluded. Queued and blocked Turns can still freeze.\n for (const turn of values(state.turns)) if (turn.conclusion || turn.status === 'processing') of(turn.botId).turns.push(turn);\n for (const card of values(state.cards)) { const turn = own(state.turns, card.turnId); if (turn) of(turn.botId).cards.push(card.turnId); }\n for (const question of values(state.questions)) { const turn = own(state.turns, question.turnId); if (turn) of(turn.botId).questions.push(question.turnId); }\n const rows = Math.min(limit, DEFAULT_CONTEXT_TURN_LIMIT);\n for (const bot of byBot.values()) {\n const totalBytes = Math.max(handoff.totalBytes, handoff.recentBytes + handoff.earlyBytes + handoffFrameBytes(bot.turns.length));\n const pack = buildHandoffPack(bot.turns.map(handoffTurn), { ...handoff, totalBytes });\n // `omittedTurns` counts the older turns, and a newest turn that did not fit, which an empty `recent` shows.\n const oldest = pack.omittedTurns - (pack.recent.length ? 0 : 1);\n for (const turn of bot.turns.slice(oldest)) kept.add(turn.id);\n for (const id of [...bot.cards.slice(-rows), ...bot.questions.slice(-rows)]) kept.add(id);\n }\n return kept;\n}\ninterface Members {\n turns: Turn[]; roots: Set<string>; delegations: string[]; batches: string[]; units: string[]; replies: string[];\n cards: string[]; questions: string[]; inputs: string[]; batch?: string; rounds: string[]; seats: string[]; inbounds: string[]; deliveries: string[]; wouldDo: string[];\n}\n/** Every row of root `root`. A round's seat Turns have their own root, so they join the round's root. */\nfunction members(state: CollaborationState, root: string): Members {\n const rounds = values(state.team.rounds).filter(round => round.root === root);\n const seats = rounds.flatMap(round => round.seats), roots = new Set([root, ...seats]);\n const turns = values(state.turns).filter(turn => roots.has(turn.root)), ids = new Set(turns.map(turn => turn.id));\n const delegations = values(state.delegations).filter(d => roots.has(d.root)).map(d => d.id), chained = new Set(delegations);\n const replies = Object.entries(state.replies).filter(([, reply]) => ids.has(reply.turnId)).map(([taskId]) => taskId);\n const batch = own(state.inputBatches, root);\n return {\n turns, roots, delegations, replies, rounds: rounds.map(round => round.id), seats,\n batches: values(state.batches).filter(row => row.delegationIds.some(id => chained.has(id))).map(row => row.id),\n units: values(state.units).filter(unit => roots.has(unit.root)).map(unit => unit.id),\n cards: values(state.cards).filter(card => ids.has(card.turnId)).map(card => card.id),\n questions: values(state.questions).filter(question => ids.has(question.turnId)).map(question => question.id),\n ...(batch ? { batch: batch.id } : {}), inputs: batch ? [...batch.inputIds] : [],\n // A filtered inbound has no root (#1229), so a root acknowledgement does not move it; it stays with its audit row.\n inbounds: values(state.channel?.inbounds).filter(row => row.root !== undefined && roots.has(row.root)).map(row => row.id),\n deliveries: values(state.channel?.deliveries).filter(row => ids.has(row.turnId)).map(row => row.id),\n wouldDo: values(state.wouldDo).filter(row => ids.has(row.turnId)).map(row => row.id),\n };\n}\n/** The first reason that the root is still in use, or `undefined`. */\nfunction protection(state: CollaborationState, m: Members, facts: RetentionFacts, window: Set<string>, superseded: ReadonlySet<string>, now: number): string | undefined {\n for (const turn of m.turns) {\n if (!turn.conclusion) return 'A Turn of the root is not concluded';\n if (facts.hasIntent(turn.id) && !turn.reported) return 'A Turn of the root is not reported';\n if (turn.source === 'routine' && facts.occurrenceOpen(turn.id)) return 'A routine occurrence of the root is open';\n }\n for (const id of m.delegations) {\n const d = state.delegations[id]!;\n if (!d.verdict || d.lateTurnId || d.cancel && !d.cancel.delivered) return 'A delegation of the root is unresolved';\n }\n if (m.batches.some(id => !state.batches[id]!.released)) return 'A delegation batch of the root is not released';\n if (m.units.some(id => state.units[id]!.state === 'reserved')) return 'A budget unit of the root is reserved';\n for (const id of m.cards) {\n const card = state.cards[id]!;\n if (card.state === 'pending' || card.state === 'confirmed' && card.result === undefined && card.error === undefined || !card.decisionReported) {\n return 'A card of the root is not settled';\n }\n }\n if (m.questions.some(id => state.questions[id]!.answer === undefined)) return 'A question of the root is unanswered';\n const batch = m.batch === undefined ? undefined : state.inputBatches![m.batch]!;\n if (batch && (batch.state === 'open' || batch.revision !== 2)) return 'The input batch of the root is not settled';\n if (m.rounds.some(id => !state.team.rounds[id]!.closed)) return 'A round of the root is open';\n if (m.seats.some(id => !state.team.seats[id]?.released)) return 'A room seat of the root is not released';\n if (m.deliveries.some(id => !superseded.has(id) && OPEN_DELIVERY.has(state.channel!.deliveries[id]!.state))) return 'A delivery of the root is not settled';\n if (m.inbounds.some(id => { const reply = state.channel!.inbounds[id]!.reply; return !!reply?.token && reply.expiresAt > now; })) {\n return 'An inbound reply route of the root is live';\n }\n if (m.turns.some(turn => window.has(turn.id))) return 'The root is in the ContextPack window of its Bot';\n return undefined;\n}\n/** Moves rows of one map. */\nfunction move<T>(store: RetentionStore, namespace: string, rows: Record<string, T> | undefined, ids: readonly string[]): number {\n if (!rows) return 0;\n for (const id of ids) { store.put(namespace, id, rows[id] as unknown as Json); delete rows[id]; }\n return ids.length;\n}\n/** Bytes of the state, for the result. */\nconst bytes = (state: CollaborationState) => Buffer.byteLength(JSON.stringify(state));\n\nexport function retainRoots(state: CollaborationState, input: RetentionInput, limits: RetentionLimits, facts: RetentionFacts,\n store: RetentionStore): RetentionResult {\n const now = time(input.now), retention = time(input.retentionMs);\n if (retention < MIN_TOMBSTONE_RETENTION_MS) throw new Error('Retention must be at least seven days');\n const expiresAt = time(now + retention);\n if (!Array.isArray(input.acknowledgedRoots)) throw new Error('Acknowledged roots must be an array');\n const roots = [...new Set(input.acknowledgedRoots)];\n if (roots.some(root => typeof root !== 'string' || !root)) throw new Error('Invalid acknowledged root');\n if (!Number.isSafeInteger(limits.contextTurnLimit) || limits.contextTurnLimit < 1) throw new Error('Invalid ContextPack limits');\n refuseUnmigratedWouldDo(state);\n const result: RetentionResult = { archivedRoots: 0, alreadyArchivedRoots: 0, archivedRows: 0, archivedCommands: 0,\n expiredCommands: store.expire('commands', now), beforeBytes: bytes(state), afterBytes: 0 };\n // Decide every root on the state before this call, then move. A refusal throws before any move.\n const window = contextWindow(state, limits.contextTurnLimit, limits.handoff), selected: Members[] = [];\n const superseded = supersededDeliveryIds(state.channel?.deliveries ?? {});\n for (const root of roots) {\n const seat = own(state.team.seats, root);\n if (seat) {\n const roundRoot = state.team.rounds[seat.roundId]?.root ?? seat.roundId;\n throw new RetentionRefused('seat_root', root, `The Turn is a room seat of root ${roundRoot}`, roundRoot);\n }\n const m = members(state, root);\n if (!m.turns.length && !m.rounds.length && m.batch === undefined && !own(state.budgets, root)) {\n if (!store.isRetired('root', root)) throw new Error('Acknowledged root not found');\n result.alreadyArchivedRoots++; continue;\n }\n const reason = protection(state, m, facts, window, superseded, now);\n if (reason) throw new RetentionRefused('protected_root', root, reason);\n selected.push(m);\n }\n for (const m of selected) {\n const turnIds = m.turns.map(turn => turn.id), consumed = new Set(turnIds);\n result.archivedRows += move(store, 'turns', state.turns, turnIds) + move(store, 'schemas', state.schemas, turnIds.filter(id => own(state.schemas, id)))\n + move(store, 'budgets', state.budgets, [...m.roots].filter(id => own(state.budgets, id)))\n + move(store, 'delegations', state.delegations, m.delegations) + move(store, 'batches', state.batches, m.batches)\n + move(store, 'units', state.units, m.units) + move(store, 'replies', state.replies, m.replies)\n + move(store, 'cards', state.cards, m.cards) + move(store, 'questions', state.questions, m.questions)\n + move(store, 'inputs', state.inputs, m.inputs) + move(store, 'inputBatches', state.inputBatches, m.batch === undefined ? [] : [m.batch])\n + move(store, 'rounds', state.team.rounds, m.rounds) + move(store, 'seats', state.team.seats, m.seats)\n + move(store, 'roots', state.team.roots, [...m.roots].filter(id => own(state.team.roots, id)))\n + move(store, 'inbounds', state.channel?.inbounds, m.inbounds) + move(store, 'deliveries', state.channel?.deliveries, m.deliveries)\n + move(store, 'wouldDo', state.wouldDo, m.wouldDo);\n // A rejection has no id. Its hash is its id; equal rows are equal evidence.\n const rejected = state.rejected.filter(row => row.consumedBy !== undefined && consumed.has(row.consumedBy));\n for (const row of rejected) store.put('rejected', hash(['rejected', row]), row as unknown as Json);\n state.rejected = state.rejected.filter(row => !rejected.includes(row));\n result.archivedRows += rejected.length;\n for (const id of turnIds) store.retire('turn', id);\n for (const id of m.inputs) store.retire('input', id);\n for (const id of m.rounds) store.retire('round', id);\n for (const root of m.roots) store.retire('root', root);\n result.archivedRoots++;\n }\n result.archivedRows += retainRoomMessages(state, store, limits.contextTurnLimit) + retainRootless(state, store);\n // A record moves when its root has moved, or when it has no root. It then answers replays until it expires.\n for (const [id, record] of Object.entries(state.commands ?? {})) {\n if (record.root !== undefined && !store.isRetired('root', record.root)) continue;\n store.put('commands', id, record as unknown as Json, expiresAt);\n delete state.commands![id];\n result.archivedCommands++;\n }\n result.afterBytes = bytes(state);\n return result;\n}\n/**\n * Room messages of archived roots (#1394). A message's id is its round root (a room input) or its seat (a post), so a message\n * whose id is in neither `team.rounds` nor `team.seats` belongs to an archived root. It moves unless it is one of the last\n * `limit` messages of its room: a seat ContextPack reads at most that many, newest last. `visibleFrom` then counts in the\n * kept list, so each member sees the same kept messages as before.\n */\nfunction retainRoomMessages(state: CollaborationState, store: RetentionStore, limit: number): number {\n let count = 0;\n for (const room of values(state.team.rooms)) {\n const window = room.messages.length - limit;\n const moved = room.messages.map((message, index) => index < window && !own(state.team.rounds, message.id) && !own(state.team.seats, message.id));\n if (!moved.includes(true)) continue;\n for (const [botId, from] of Object.entries(room.visibleFrom)) room.visibleFrom[botId] = from - moved.slice(0, from).filter(Boolean).length;\n room.messages.forEach((message, index) => { if (moved[index]) store.put('roomMessages', message.id, message as unknown as Json); });\n room.messages = room.messages.filter((_, index) => !moved[index]);\n count += moved.filter(Boolean).length;\n }\n return count;\n}\n/** Rows outside any root: audit lines, revoked push routes and settled persona deliveries. They stay as history. */\nfunction retainRootless(state: CollaborationState, store: RetentionStore): number {\n let count = 0;\n if (state.audit.length) {\n store.put('audit', hash(['audit', state.revision ?? 0, state.audit]), state.audit);\n count += state.audit.length; state.audit = [];\n }\n const routes = state.channel?.pushRoutes ?? {}, used = new Set(values(state.channel?.deliveries).map(row => row.route.kind === 'push' ? row.route.pushRouteId : ''));\n count += move(store, 'pushRoutes', routes, Object.keys(routes).filter(id => routes[id]!.revokedAt !== undefined && !used.has(id)));\n // Keep pending work, the newest applied delivery of each Bot (it proves that a persona was applied) and failures of the current revision.\n const newest = new Map<string, number>();\n for (const op of state.team.homeOperations) if (op.status === 'applied') newest.set(op.botId, Math.max(newest.get(op.botId) ?? 0, op.sequence));\n const settled = state.team.homeOperations.filter(op => op.status === 'applied' ? newest.get(op.botId) !== op.sequence\n : op.status === 'failed' && op.request.payload.agentRef.profileRevision !== state.team.bots[op.botId]?.revision);\n for (const op of settled) store.put('homeOperations', String(op.sequence), op as unknown as Json);\n state.team.homeOperations = state.team.homeOperations.filter(op => !settled.includes(op));\n return count + settled.length;\n}\n","import type { HandoffPackBudgets } from '@byok-sdk/protocol';\nimport type { CollaborationState, Turn } from './model.js';\nimport type { BotRoutine } from './routines.js';\nimport * as rules from './rules/context.js';\nimport { HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS } from './rules/history.js';\n\n// K8 adapter for the pure schema and ContextPack rules in `rules/`. The device ledger is the history authority here.\nexport { CONFIRMABLE_MAX, DEFAULT_CONFIRMABLE, DEFAULT_TIME_ZONES, MAIN_ACTIONS, NEW_BOTS, NEW_ROOMS, outcomeOffer, outcomeSchema, ROOM_SYSTEM_PROMPT, SYSTEM_PROMPT, TIME_ZONES_MAX,\n TURN_ACTIONS, type CheckedOffer, type ConfirmableSpec, type MainAction, type OutcomeOffer, type TurnAction } from './rules/schema.js';\nexport { contextTurns, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, type ContextHistory, type ContextTurn, type InstructionLimits } from './rules/context.js';\n\n/** Every stored Turn and its rows, in ledger order. */\nfunction ledgerHistory(state: CollaborationState): rules.ContextHistory {\n return { turns: Object.values(state.turns), cards: Object.values(state.cards), questions: Object.values(state.questions), rejected: state.rejected };\n}\n/** `crossRequest` is the framed Request section of a Cross-Bot Turn; its background is trimmed too (§3.7). */\nexport function turnContext(state: CollaborationState, turn: Turn, turnLimit = HISTORY_MAX_ITEMS, maxBytes = HISTORY_MAX_BYTES, crossRequest?: string,\n routines: readonly BotRoutine[] = [], handoff?: HandoffPackBudgets) {\n return rules.turnContext(state, rules.botHistory(state, turn), turn, turnLimit, maxBytes, crossRequest, routines, handoff);\n}\n/** Snapshot views include the candidate. Frozen turn views keep it in Request. */\nexport function contextPack<T extends object = Record<never, never>>(state: CollaborationState, turnLimit?: number, currentTurnId?: string,\n maxBytes?: number, separateRequest?: boolean, shared?: T, fit?: { request?: string; background?: unknown[][] }, routines: readonly BotRoutine[] = [],\n handoff?: HandoffPackBudgets) {\n return rules.contextPack(ledgerHistory(state), turnLimit, currentTurnId, maxBytes, separateRequest, shared, fit, routines, handoff);\n}\n","import type { AgentHomeProjectionReadback, BotTurnOutcome, CreateBotAction, RoomFields, UpdateBotAction } from '@byok-sdk/protocol';\nimport { hash, canonical, type ExecutionTemplate } from '@byok-sdk/server/execution-core';\nimport { json, type CollaborationState } from './model.js';\nimport type { BotProfile, HomeOperation, Room, TeamState } from './team-model.js';\nimport type { Publish } from './rules/delegation.js';\nimport { roomFields, roomVisibility } from './rules/rooms.js';\n\nimport { NEW_BOTS, NEW_ROOMS } from './rules/schema.js';\nimport { DEFAULT_AUTONOMY } from './rules/autonomy.js';\nimport { activeBot, admitBotToolsets, archiveBot, inactive, profileProjection, refuseExternalRooms, refuseExternalTeam, requireMain, TEAM_BOT_LIMIT, type TeamSnapshotBot } from './rules/team.js';\n\nexport { activeBot, admitBotToolsets, inactive, NEW_BOTS, NEW_ROOMS, requireMain, roomFields };\nexport const TEAM_NOTE_LIMIT = 20;\nexport function projectionRequestId(value: unknown): string {\n const digest = hash(value);\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-a${digest.slice(17, 20)}-${digest.slice(20, 32)}`;\n}\n/**\n * The Agent home flush rules (#793 S13), the pure part of L's `flushHomes`; each Host runs its own I/O around them.\n * `homeHead` gives the pending operation `sequence` when it is its Bot's oldest pending one and the Bot is free\n * (`busy(botId)`: the Bot has an intent with no conclusion). Only a head is flushed.\n */\nexport function homeHead(team: Pick<TeamState, 'homeOperations'>, sequence: number, busy: (botId: string) => boolean): HomeOperation | undefined {\n const op = team.homeOperations.find(row => row.sequence === sequence);\n if (!op || op.status !== 'pending') return undefined;\n const oldest = team.homeOperations.filter(row => row.botId === op.botId && row.status === 'pending').reduce((a, b) => a.sequence <= b.sequence ? a : b);\n return oldest === op && !busy(op.botId) ? op : undefined;\n}\n/** The requests of an operation in the order a flush reads them back: the first, then each retry. */\nexport const homeRequests = (op: HomeOperation) => [op.request, ...op.retries];\nexport type HomeReadback = Pick<AgentHomeProjectionReadback, 'deviceId' | 'agentRef' | 'requestId' | 'projectionHash' | 'status'>;\n/**\n * Checks the readback of one request of the operation. A readback for another device, Agent, request or projection throws\n * `Home readback identity conflict`. Returns it when it is terminal (not `pending`); the flush reads no later request then.\n */\nexport function checkHomeReadback(request: HomeOperation['request'], read: HomeReadback | undefined): HomeReadback | undefined {\n if (!read) return undefined;\n const payload = request.payload;\n if (read.deviceId !== request.deviceId || !same(read.agentRef, payload.agentRef)\n || read.requestId !== payload.requestId || read.projectionHash !== payload.projectionHash) throw new Error('Home readback identity conflict');\n return read.status !== 'pending' ? read : undefined;\n}\n/**\n * No request is terminal. Once `retryAt` has passed, adds a retry of the same desired revision with the next durable request\n * id and a backoff (min(60 s, 1 s × 2^n)). Returns the request to enqueue: the latest.\n */\nexport function planHomeRetry(op: HomeOperation, now: number): HomeOperation['request'] {\n if (op.retryAt !== undefined && now >= op.retryAt) {\n const retry = structuredClone(op.request);\n retry.payload.requestId = projectionRequestId([op.request.payload.requestId, op.retries.length + 1]);\n op.retries.push(retry);\n op.retryAt = now + Math.min(60_000, 1000 * 2 ** Math.min(op.retries.length, 6));\n }\n return op.retries.at(-1) ?? op.request;\n}\n/** The enqueue of the latest request succeeded: the first retry is due a second later. */\nexport function homeEnqueued(op: HomeOperation, now: number): void {\n op.retryAt ??= now + 1000;\n}\n/**\n * Settles the operation with a terminal readback: `applied` or `idempotent` applies it and readies its Bot at that revision;\n * any other status fails it and publishes `persona-failed:<sequence>`.\n */\nexport function applyHomeTerminal(state: CollaborationState, op: HomeOperation, terminal: HomeReadback, publish: Publish): void {\n if (terminal.status === 'applied' || terminal.status === 'idempotent') {\n op.status = 'applied';\n const bot = state.team.bots[op.botId]!;\n if (bot.revision === op.request.payload.agentRef.profileRevision) bot.readyRevision = bot.revision;\n } else {\n op.status = 'failed'; op.error = terminal.status;\n publish(`persona-failed:${op.sequence}`, json({ owner: op.botId, revision: op.request.payload.agentRef.profileRevision, reason: op.error, recoverable: true }));\n }\n}\n/** A flush step threw: the operation keeps `pending` with the error. */\nexport function failHomeFlush(op: HomeOperation, error: unknown): void {\n op.error = String(error instanceof Error ? error.message : error);\n}\nfunction projection(state: CollaborationState, bot: BotProfile): void {\n const value = profileProjection(bot);\n const requestId = projectionRequestId([bot.id, bot.revision]);\n state.team.homeOperations.push({ sequence: ++state.sequence, botId: bot.id, status: 'pending', retries: [], request: {\n deviceId: bot.execution.deviceId, payload: { requestId,\n agentRef: { agentId: bot.id, profileRevision: bot.revision }, projectionHash: `sha256:${hash(value)}`, projection: value },\n } });\n}\nexport function createBot(state: CollaborationState, taskId: string, action: CreateBotAction, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): BotProfile {\n if (!NEW_BOTS.includes(action.localId as typeof NEW_BOTS[number])) throw new Error('Unknown local Bot slot');\n if (Object.values(state.team.bots).filter(b => !b.archived).length >= TEAM_BOT_LIMIT) throw new Error(`Team Bot limit is ${TEAM_BOT_LIMIT}`);\n const base = models[action.model];\n if (!base) throw new Error('Unavailable model');\n admitBotToolsets(base, readOnlyToolsets);\n const id = hash([taskId, action.localId]);\n const execution = structuredClone(base);\n execution.payload.agentRef = { agentId: id, profileRevision: '1' };\n // A new Bot starts in observe (#1229, owner ruling): the owner sees what it would do before it does it.\n const bot: BotProfile = { id, name: action.name, role: action.role, persona: action.persona, model: action.model,\n mainBot: false, archived: false, revision: '1', readyRevision: null, autonomy: DEFAULT_AUTONOMY, execution };\n state.team.bots[id] = bot;\n projection(state, bot);\n return bot;\n}\nexport function updateBot(state: CollaborationState, action: UpdateBotAction, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): void {\n const bot = activeBot(state.team, action.botId);\n const model = action.model ?? bot.model, base = models[model];\n if (base) admitBotToolsets(base, readOnlyToolsets);\n const revision = (BigInt(bot.revision) + 1n).toString();\n if (BigInt(revision) > 9223372036854775807n) throw new Error('Profile revision limit');\n // #1357: without a template the Bot keeps its stored one, and the freeze holds its Turns until the Host provides one.\n const execution = structuredClone(base ?? bot.execution);\n // Model selection cannot move the Bot home to another device.\n execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: bot.id, profileRevision: revision };\n Object.assign(bot, { name: action.name ?? bot.name, role: action.role ?? bot.role, persona: action.persona ?? bot.persona,\n model, revision, readyRevision: null, execution });\n projection(state, bot);\n}\n/**\n * The `teamBot` port of a team snapshot (#739 Q4c). A new Bot gets the snapshot id and its first projection.\n * A profile change takes the `update_bot` path, so it queues the same persona projection (T4).\n * Host persona mode (#879): the Bot takes the Host's profile revision and no projection is queued.\n */\nexport function writeSnapshotBot(state: CollaborationState, row: TeamSnapshotBot, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): void {\n const bot = state.team.bots[row.id];\n if (state.team.external?.persona) { writeHostProfile(state, bot, row, models, readOnlyToolsets); return; }\n if (bot) {\n if (bot.name !== row.name || bot.role !== row.role || bot.persona !== row.persona || bot.model !== row.model) {\n updateBot(state, { botId: row.id, name: row.name, role: row.role, persona: row.persona, model: row.model }, models, readOnlyToolsets);\n }\n return;\n }\n const base = models[row.model];\n if (!base) throw new Error('Unavailable model');\n admitBotToolsets(base, readOnlyToolsets);\n const execution = structuredClone(base);\n execution.payload.agentRef = { agentId: row.id, profileRevision: '1' };\n const created: BotProfile = { id: row.id, name: row.name, role: row.role, persona: row.persona, model: row.model,\n mainBot: false, archived: false, revision: '1', readyRevision: null, autonomy: DEFAULT_AUTONOMY, execution };\n state.team.bots[row.id] = created;\n projection(state, created);\n}\n/**\n * Re-projects the Host's execution templates onto each unarchived Bot, a suspended one too (#1357). A Bot keeps its device,\n * and its agentRef follows its profile. A Bot whose model has no template keeps its stored one, and the freeze holds its Turns\n * with `Unavailable model` until the Host provides it. No profile field changes and no persona projection is queued.\n * A template that fails the toolset check refuses the whole call before any write.\n */\nexport function applyModels(state: CollaborationState, models: Readonly<Record<string, ExecutionTemplate>>, readOnlyToolsets: readonly string[]): void {\n for (const model of Object.values(models)) admitBotToolsets(model, readOnlyToolsets);\n for (const bot of Object.values(state.team.bots)) {\n const base = models[bot.model];\n if (bot.archived || !base) continue;\n const execution = structuredClone(base);\n execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: bot.id, profileRevision: bot.revision };\n bot.execution = execution;\n }\n}\n/**\n * Host persona mode (#879). The revision never goes back, and a profile change needs a newer revision. A newer revision\n * keeps `readyRevision` at the last revision that the Host reported ready: the Bot stays a delegate target, and its\n * Turns wait for `persona_ready` of the new revision.\n */\nfunction writeHostProfile(state: CollaborationState, bot: BotProfile | undefined, row: TeamSnapshotBot, models: Record<string, ExecutionTemplate>,\n readOnlyToolsets: readonly string[]): void {\n const revision = row.profileRevision!;\n if (bot) {\n const changed = bot.name !== row.name || bot.role !== row.role || bot.persona !== row.persona || bot.model !== row.model;\n if (BigInt(revision) < BigInt(bot.revision)) throw new Error(`Profile revision ${revision} of ${row.id} is older than ${bot.revision}`);\n if (revision === bot.revision) {\n if (changed) throw new Error(`A profile change of ${row.id} needs a newer profile revision`);\n return;\n }\n }\n // A new Bot needs a template: its device comes from it. An existing Bot keeps its stored one, as in `updateBot` (#1357).\n const base = models[row.model];\n if (base) admitBotToolsets(base, readOnlyToolsets);\n else if (!bot) throw new Error('Unavailable model');\n const execution = structuredClone(base ?? bot!.execution);\n // Model selection cannot move the Bot home to another device.\n if (bot) execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: row.id, profileRevision: revision };\n const fields = { name: row.name, role: row.role, persona: row.persona, model: row.model, revision, execution };\n if (bot) Object.assign(bot, fields);\n else state.team.bots[row.id] = { id: row.id, ...fields, mainBot: false, archived: false, readyRevision: null, autonomy: DEFAULT_AUTONOMY };\n}\nexport function applyManagement(state: CollaborationState, actor: string, taskId: string, outcome: BotTurnOutcome,\n models: Record<string, ExecutionTemplate>, accept: (action: string, work: () => void) => void, readOnlyToolsets: readonly string[] = []): void {\n const team = state.team, local: Record<string, string> = {};\n const managed = (kind: string, work: () => void) => accept(kind, () => { requireMain(team, actor); work(); });\n // T3: the team authority owns the Bots. Team notes stay local, and rooms too unless it owns them (#1321).\n const bots = (kind: string, work: () => void) => managed(kind, () => { refuseExternalTeam(team, kind); work(); });\n const rooms = (kind: string, work: () => void) => managed(kind, () => { refuseExternalRooms(team, kind); work(); });\n outcome.create_bot?.forEach(action => bots('create_bot', () => { local[action.localId] = createBot(state, taskId, action, models, readOnlyToolsets).id; }));\n outcome.update_bot?.forEach(action => bots('update_bot', () => updateBot(state, action, models, readOnlyToolsets)));\n outcome.delete_bot?.forEach(action => bots('delete_bot', () => archiveBot(team, action.botId)));\n const resolve = (fields: Partial<RoomFields>) => ({ ...fields,\n ...(fields.members ? { members: fields.members.map(id => local[id] ?? id) } : {}),\n ...(fields.admin ? { admin: local[fields.admin] ?? fields.admin } : {}),\n });\n outcome.create_room?.forEach(action => rooms('create_room', () => {\n if (!NEW_ROOMS.includes(action.localId as typeof NEW_ROOMS[number])) throw new Error('Unknown local room slot');\n const id = hash([taskId, action.localId]);\n if (team.rooms[id]) throw new Error('Duplicate local room slot');\n team.rooms[id] = { id, ...roomFields(team, resolve(action) as RoomFields), messages: [] };\n }));\n outcome.update_room?.forEach(action => rooms('update_room', () => {\n const room = team.rooms[action.roomId];\n if (!room) throw new Error('Room not found');\n const fields = { ...room, ...resolve(action) };\n if (!action.admin && !fields.members.includes(fields.admin ?? '')) delete fields.admin;\n const next = roomFields(team, fields);\n next.visibleFrom = roomVisibility(room, next.members);\n Object.assign(room, next);\n if (!next.admin) delete room.admin;\n }));\n if (outcome.team_note) managed('team_note', () => {\n if (team.notes.length >= TEAM_NOTE_LIMIT) throw new Error('Team note limit is 20');\n team.notes.push({ id: hash([taskId, 'team_note']), text: outcome.team_note!.text });\n });\n}\nexport function same(value: unknown, other: unknown): boolean { return canonical(value) === canonical(other); }\n"]}
1
+ {"version":3,"sources":["../src/team-model.ts","../src/model.ts","../src/channel.ts","../src/delivery-superseded.ts","../src/routines.ts","../src/retention.ts","../src/schema.ts","../src/team.ts"],"names":["definition","hash","rows","contextPack","fields","canonical"],"mappings":";;;;AAkCO,SAAS,SAAA,EAAuB,CACrC,OAAO,CAAE,IAAA,CAAM,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,MAAA,CAAQ,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,KAAA,CAAO,EAAC,CAAG,cAAA,CAAgB,EAAG,CAChG,CCqCO,SAAS,QAAQ,WAAA,CAAuD,CAC7E,GAAI,WAAA,CAAY,aAAA,GAAkB,MAAA,CAAW,WAAA,CAAY,aAAA,CAAgB,IAAA,CAAK,CAC5E,IAAA,CAAM,SAAA,EAAU,CAAG,KAAA,CAAO,EAAC,CAAG,QAAS,EAAC,CAAG,WAAA,CAAa,EAAC,CAAG,OAA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M,IAAI,KAAA,CAAM,gBAAgB,CAAA,CAC3C,MAAMG,OAAAA,CAAS,CAAE,GAAG,IAAA,CAAM,GAAG,OAAA,CAAQ,MAAM,CAAE,CAAA,CAC7C,GAAI,CAAC,MAAA,CAAO,KAAA,EAAS,CAACA,QAAO,OAAA,CAAQ,QAAA,CAASA,OAAAA,CAAO,KAAA,EAAS,EAAE,CAAA,CAAG,OAAOA,OAAAA,CAAO,KAAA,CACjF,MAAM,IAAA,CAAO,UAAA,CAAW,IAAA,CAAMA,OAAM,CAAA,CACpC,IAAA,CAAK,YAAc,cAAA,CAAe,IAAA,CAAM,IAAA,CAAK,OAAO,CAAA,CACpD,MAAA,CAAO,MAAA,CAAO,IAAA,CAAM,IAAI,CAAA,CACxB,GAAI,CAAC,IAAA,CAAK,KAAA,CAAO,OAAO,IAAA,CAAK,MAC/B,CAAC,CAAC,CAAA,CACF,GAAI,OAAA,CAAQ,SAAA,CAAW,OAAA,CAAQ,WAAA,CAAa,IAAM,CAChD,GAAI,IAAA,CAAK,KAAA,CAAM,MAAA,EAAU,eAAA,CAAiB,MAAM,IAAI,KAAA,CAAM,uBAAuB,CAAA,CACjF,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,CAAE,EAAA,CAAIH,IAAAA,CAAK,CAAC,MAAA,CAAQ,WAAW,CAAC,CAAA,CAAG,IAAA,CAAM,OAAA,CAAQ,UAAW,IAAK,CAAC,EACpF,CAAC,EACH,CACO,SAAS,IAAA,CAAK,KAAA,CAAgB,KAAA,CAAyB,CAAE,OAAOI,SAAAA,CAAU,KAAK,CAAA,GAAMA,SAAAA,CAAU,KAAK,CAAG","file":"chunk-DYQSVSPJ.js","sourcesContent":["import type { AgentHomeProjectionRequest } from '@byok-sdk/server';\nimport type { ExecutionTemplate } from '@byok-sdk/server/execution-core';\nimport type { Room, Round, Seat } from './rules/rooms.js';\nimport type { Autonomy } from './rules/autonomy.js';\nimport type { ExternalTeam } from './rules/team.js';\n\nexport type { Room, Round, Seat };\nexport interface BotProfile {\n id: string; name: string; role: string; persona: string; model: string;\n mainBot: boolean; archived: boolean; revision: string; readyRevision: string | null;\n /**\n * Host autonomy policy (#1229). Absent reads as `observe`, the default of a new Bot: each create_routine, cross-Bot\n * delegate and room_call is recorded as would-do until the owner switches this Bot to `auto`. Host state, never wire.\n */\n autonomy?: Autonomy;\n /** #1319: the team authority suspended this Bot. It stays a member and takes no new work. Absent: participating. */\n participation?: 'suspended';\n execution: ExecutionTemplate;\n}\nexport interface HomeOperation {\n sequence: number; botId: string; request: AgentHomeProjectionRequest;\n retries: AgentHomeProjectionRequest[]; retryAt?: number;\n status: 'pending' | 'applied' | 'failed'; error?: string;\n /** Set in the transaction before the first write is sent (#957), so a crash or a failed send still counts it as sent. */\n sent?: true;\n}\nexport interface TeamState {\n bots: Record<string, BotProfile>; rooms: Record<string, Room>; rounds: Record<string, Round>;\n seats: Record<string, Seat>; roots: Record<string, { autonomous: number; late: number }>;\n notes: Array<{ id: string; text: string }>;\n homeOperations: HomeOperation[];\n /** External team mode (#739 Q4c). Absent: this Host owns its local team. */\n external?: ExternalTeam;\n}\nexport function emptyTeam(): TeamState {\n return { bots: {}, rooms: {}, rounds: {}, seats: {}, roots: {}, notes: [], homeOperations: [] };\n}\n","import type { ResultSchema } from '@byok-sdk/protocol';\nimport { emptyTeam, type TeamState } from './team-model.js';\nimport type { Json } from '@byok-sdk/server/execution-core';\nimport type { ChannelState } from './delivery-routing.js';\nimport type { InputBatch, UserInput } from './rules/coalesce.js';\nimport { json, type Budget, type Card, type Question, type Rejection, type Turn } from './rules/turn.js';\nimport type { AcceptedReply, Batch, Delegation, Unit } from './rules/delegation.js';\nimport type { CommandRecord } from './rules/commit.js';\nimport type { DeviceTopology } from './topology.js';\nimport type { SwitchExportMark } from './migration.js';\nimport type { SwitchImport } from './switch.js';\nimport type { AutonomyState, WouldDo } from './rules/autonomy.js';\nimport type { DreamState } from './dream.js';\n\nexport type { Authority, InputBatch, SealReason, UserInput } from './rules/coalesce.js';\nexport { addBatchTurns, addTurn, json } from './rules/turn.js';\nexport type { Budget, Card, Question, Rejection, ReplyEntry, Turn, TurnFields, Verdict } from './rules/turn.js';\nexport type { AcceptedReply, Batch, Delegation, DelegationCancel, Unit } from './rules/delegation.js';\n\n/**\n * The K8 state. A Host ledger keeps it in its application body, and the ledger's `k8` format row (`botLedgerOptions`) is\n * its format.\n * Retention keeps settled rows in K4 application rows (#798). Bot routines are K4 routines with the `bot-routine`\n * occurrence hook.\n */\nexport interface CollaborationState extends AutonomyState {\n team: TeamState; turns: Record<string, Turn>; budgets: Record<string, Budget>;\n delegations: Record<string, Delegation>; batches: Record<string, Batch>; units: Record<string, Unit>;\n replies: Record<string, AcceptedReply>;\n schemas: Record<string, ResultSchema>; questions: Record<string, Question>; cards: Record<string, Card>;\n rejected: Rejection[]; audit: string[]; sequence: number;\n /** Input coalescing. Both appear at the first coalesced input. */\n inputs?: Record<string, UserInput>; inputBatches?: Record<string, InputBatch>;\n /** Host-only routes and final-content outbox. Never included in ContextPack or projections. */\n channel?: ChannelState;\n /**\n * Commit contract (#739 D1). Both appear at the first commit; a state without them is at revision 0.\n * `commands` holds the dedup evidence of owner commands. K4 deduplicates terminals and messages itself.\n */\n revision?: number; commands?: Record<string, CommandRecord>;\n /**\n * Host intents (#882): the handler name of each Host-owned K4 intent, by intent key. A record lives as long as K4\n * keeps its intent. It appears at the first Host intent, so an older ledger reads an empty table.\n */\n hostIntents?: Record<string, { handler: string }>;\n /**\n * L card call claims (#958): a card id is here from the transaction before its connector call until the one that settles\n * it. It appears at the first claim, so an older ledger reads an empty table. Never in ContextPack or projections.\n */\n cardCalls?: Record<string, true>;\n /**\n * L owner records by device id (#957, §4.1), from `topology.ts`. A device appears at its first switch step, so an older\n * ledger reads every device as L at revision 0. Never in ContextPack or projections.\n */\n topology?: Record<string, DeviceTopology>;\n /**\n * L switch records (#975), from `switch.ts`. `switchExport` appears at the export of an old owner and stays; while it is\n * here the Host writes nothing. `switchImport` is here from the load of a new owner until its commit toward L. Neither\n * moves in an export, and neither is in ContextPack or projections.\n */\n switchExport?: SwitchExportMark; switchImport?: SwitchImport;\n /**\n * Would-do rows of observing Bots (#1229), keyed by `wouldDoId(taskId, action, index)`. They appear at the first\n * observed action, so an older ledger reads none. They are Host UI history, never part of the Bot's ContextPack or wire.\n */\n wouldDo?: Record<string, WouldDo>;\n /**\n * Dreaming (#1475), from `dream.ts`: the owner of each dream intent and the last result of each Bot. It appears at the first\n * dream routine, so an older ledger reads none. Never in ContextPack or projections.\n */\n dreams?: DreamState;\n}\n/** The K8 state of an application body, created empty at its first use. */\nexport function stateOf(application: Record<string, Json>): CollaborationState {\n if (application.collaboration === undefined) application.collaboration = json({\n team: emptyTeam(), turns: {}, budgets: {}, delegations: {}, batches: {}, units: {}, replies: {}, schemas: {}, questions: {}, cards: {},\n rejected: [], audit: [], sequence: 0,\n });\n // SAFETY: The store that holds this body admitted its format when it opened (a Host ledger's `k8` row), so the value is\n // the state this build writes.\n return application.collaboration as unknown as CollaborationState;\n}\n","import { hash } from '@byok-sdk/server/execution-core';\nimport type { Mentions } from './rooms.js';\n\n/** A sender that the channel adapter took from authenticated platform data (docs/host-im-adapter.md R2). */\nexport interface Principal { id: string; kind: 'human' | 'bot' }\nexport interface Conversation { kind: 'direct' | 'group'; id: string }\nexport interface ReplyRoute {\n kind: 'reply'; channel: string; inboundId: string; token: string; expiresAt: number;\n}\nexport interface PushRoute {\n kind: 'push'; id: string; conversation: Conversation; channel: string; target: string;\n optedInBy: string; optedInAt: number; revokedAt?: number;\n}\n/**\n * `staged`: a Bot reply accepted before its Turn outcome committed (#1762). No sender takes it. The outcome transaction\n * promotes it to `pending`; a Turn whose intent concludes otherwise rejects it as `outcome_not_applied`.\n */\nexport type DeliveryState = 'staged' | 'pending' | 'sending' | 'accepted' | 'rejected' | 'unknown';\n/** `turnId` is the Turn that queued the delivery. Retention keeps the delivery with that Turn's root. */\nexport interface Delivery {\n id: string; taskId: string; turnId: string; messageId: string; body: string;\n conversation: Conversation; channel: string;\n route: { kind: 'reply'; inboundId: string } | { kind: 'push'; pushRouteId: string };\n state: DeliveryState; attempts: number; nextAttemptAt?: number;\n platformMessageId?: string; code?: string; resendOf?: string;\n}\n/** A rejection is authoritative. An exception leaves delivery acceptance unknown. */\nexport interface ChannelPort {\n send(input: { deliveryId: string; route: ReplyRoute | PushRoute; body: string }, signal: AbortSignal): Promise<\n | { result: 'accepted'; platformMessageId: string }\n | { result: 'rejected'; code: string; retryable: boolean; retryAfterMs?: number }>;\n readback?(deliveryId: string): Promise<'accepted' | 'absent' | 'unsupported'>;\n}\nexport interface ChannelOptions {\n port: ChannelPort;\n /** Verified platform bot principal ids. These ids are scoped to their channel. */\n self?: Record<string, readonly string[]>;\n /** Business send deadline. The default is 15 seconds. */\n sendTimeoutMs?: number;\n}\n/**\n * Optional last argument of the owner APIs and `roomInput`. Its length tells an omitted principal\n * from a given `undefined`, because JavaScript applies a default parameter to both.\n */\nexport type PrincipalArg = [principal?: Principal];\n/**\n * One inbound IM message after the adapter's translation. The adapter maps the platform chat\n * to a Host conversation: a Bot id for `direct`, a room id for `group`.\n */\nexport interface InboundMessage {\n channel: string; platformMessageId: string;\n conversation: Conversation;\n /** Absent when the adapter cannot verify the sender. */\n sender?: Principal;\n text: string;\n /** Bot ids from the platform's mention entities (R6). The Host never scans `text`. */\n mentions: Mentions;\n replyRoute?: ReplyRoute;\n deliveryId?: string;\n receivedAt?: number;\n}\n/** Echo candidates only reconcile exact delivery identities. They never create input. */\nexport type InboundClass = 'unverified_sender' | 'echo' | 'bot_audit' | 'bot_background' | 'owner_input' | 'not_owner' | 'room_input';\n\n/** A principal needs a non-empty id and a known kind. */\nexport function verified(sender: Principal | undefined): sender is Principal {\n return typeof sender?.id === 'string' && sender.id.length > 0 && (sender.kind === 'human' || sender.kind === 'bot');\n}\n/** Only the human principal with the owner id. A bot account never has owner authority. */\nexport function isOwner(principal: Principal, owner: string): boolean {\n return principal.kind === 'human' && principal.id === owner;\n}\n/** The guide's §3 order. The first match wins. */\nexport function classifyInbound(message: InboundMessage, owner: string, self?: Record<string, readonly string[]>): InboundClass {\n const sender = message.sender;\n if (!verified(sender)) return 'unverified_sender';\n const selfBots = self && Object.hasOwn(self, message.channel) ? self[message.channel] : undefined;\n if (sender.kind === 'bot' && selfBots?.includes(sender.id)) return 'echo';\n const direct = message.conversation.kind === 'direct';\n if (sender.kind === 'bot') return direct ? 'bot_audit' : 'bot_background';\n if (!direct) return 'room_input';\n return isOwner(sender, owner) ? 'owner_input' : 'not_owner';\n}\n/** A redelivered platform event maps to the same input. A platform message id can be unique only within one chat. */\nexport function inboundKey(message: InboundMessage): string {\n return hash([message.channel, message.conversation.kind, message.conversation.id, message.platformMessageId]);\n}\n","import type { Delivery } from './channel.js';\n/** Manual replacements keep their predecessors as history, with acceptance still unknown. */\nexport function supersededDeliveryIds(deliveries: Readonly<Record<string, Delivery>>): Set<string> {\n return new Set(Object.values(deliveries).flatMap(row => row.resendOf === undefined ? [] : [row.resendOf]));\n}\n","import { checkRoutineSchedule, nextRoutineOccurrence, HostOfferSealedPayloadSchema, type CreateRoutineAction, type RoutineSchedule, type RoutineScheduleFields,\n type UpdateRoutineAction } from '@byok-sdk/protocol';\nimport { canonical, concludeOccurrence, hash, occurrenceIntentKey, occurrenceOfIntentKey, type ExecutionTemplate, type HostOccurrenceRoutineDefinition, type HostOccurrenceRun, type LedgerState,\n type NextOccurrence, type Routine } from '@byok-sdk/server/execution-core';\nimport { addTurn, json, type Authority, type CollaborationState, type Turn } from './model.js';\nimport type { SealedRoutineTemplate } from './rules/sync.js';\nimport type { SealedRoutineRef } from './rules/turn.js';\nimport type { DreamState } from './dream.js';\n\nexport type { SealedRoutineTemplate } from './rules/sync.js';\n\n// Bot policy over K4 routines. K4 owns the routine rows, versions, slots, occurrences and wakes.\n\n/** The K4 occurrence hook of Bot routines. Other K4 routines of the Host are not Bot routines. */\nexport const BOT_ROUTINE = 'bot-routine';\n/** The K4 occurrence hook of dream routines (`dream.ts`). Bot policy never reads these rows. */\nexport const BOT_DREAM = 'bot-dream';\n/** A routine Turn expires this long after K4 records its occurrence. */\nexport const ROUTINE_WAIT_MS = 300_000;\n/** A delivery later than this after its planned time is a catch-up. */\nexport const ROUTINE_LATE_AFTER_MS = 60_000;\n\n/** Fixed at creation. Owner and authority never change between versions, and a routine stays plain or sealed. */\nexport type BotRoutineInput = { owner: string; authority: Authority; prompt: string }\n | { owner: string; authority: 'owner'; sealed: SealedRoutineTemplate };\nconst sealedOf = (input: BotRoutineInput): SealedRoutineTemplate | undefined => 'sealed' in input ? input.sealed : undefined;\n/**\n * What the owner's member endpoint sends to create or reseal a routine: the schedule and one template, sealed for routine\n * `routineId` version `definitionVersion`.\n */\nexport interface SealedRoutineAction { routineId: string; definitionVersion: number; schedule: RoutineScheduleFields; sealed: SealedRoutineTemplate }\n/** The member sealed for another version than the one this command stages. Nothing is written; read the routine again. */\nexport class SealedRoutineVersionError extends Error {\n readonly code = 'sealed_routine_version';\n constructor(readonly expected: number) { super(`Seal the template for version ${expected}`); this.name = 'SealedRoutineVersionError'; }\n}\n/** A sealed routine allows only `task-input`: K8 reads the Bot outcome to settle the Turn, so the output stays plaintext. */\nconst SEALED_ROUTINE_CATEGORIES = ['task-input'];\n/** The ContextPack view of one Bot routine. */\nexport interface BotRoutine {\n id: string; owner: string; current: number; pending: number | null; lifecycle: Routine['lifecycle']; status: Routine['status'];\n /** A sealed routine has no `prompt` and shows nothing else of its template: the view goes into each ContextPack. */\n definition: { version: number; schedule: RoutineScheduleFields; prompt?: string; sealed?: true; target: string };\n lastError?: { at: number; message: string; wakeKey?: string };\n}\n\nexport const dreamTable = (state: CollaborationState): DreamState => state.dreams ??= { bots: {}, open: {} };\n/** The K4 calendar of the Bot Host core. A rule is a `RoutineSchedule` whose `tz` is the definition time zone. */\nexport const routineCalendar: NextOccurrence = (definition, after) => {\n const schedule = definition.rule;\n if (!schedule || typeof schedule !== 'object' || Array.isArray(schedule) || schedule.tz !== definition.timeZone) {\n throw new Error('A routine rule is a RoutineSchedule in the definition time zone');\n }\n return nextRoutineOccurrence(schedule as unknown as RoutineSchedule, after);\n};\nfunction fields(routine: Routine): BotRoutineInput | undefined {\n const spec = routine.definition.hostOccurrence;\n return spec?.type === BOT_ROUTINE ? spec.input as unknown as BotRoutineInput : undefined;\n}\nfunction definition(id: string, version: number, schedule: RoutineScheduleFields, input: BotRoutineInput): HostOccurrenceRoutineDefinition {\n return { id, version, timeZone: schedule.tz, rule: json(schedule), waitMs: ROUTINE_WAIT_MS, lateAfterMs: ROUTINE_LATE_AFTER_MS,\n hostOccurrence: { type: BOT_ROUTINE, input: json(input) } };\n}\n/**\n * A schedule from an owner or member command. The bot-turn-outcome.v1 contract checks the schedules of an outcome, so\n * only these entries check here.\n */\nfunction scheduled(schedule: RoutineScheduleFields): RoutineScheduleFields {\n const check = checkRoutineSchedule(schedule);\n if (!check.ok) throw new Error(`${check.code}: ${check.message}`);\n return schedule;\n}\n/** The owner `updateRoutine` API. An outcome's update_routine passed the contract, which refuses the same as this. */\nexport function ownerRoutineUpdate(action: UpdateRoutineAction): UpdateRoutineAction {\n if (action.schedule === undefined && action.prompt === undefined) throw new Error('An update must change schedule or prompt');\n if (action.schedule !== undefined) scheduled(action.schedule);\n return action;\n}\n/** The Bot routines among the Host's K4 routine rows. */\nexport function botRoutines(routines: Iterable<Routine>): BotRoutine[] {\n const views: BotRoutine[] = [];\n for (const routine of routines) {\n const input = fields(routine);\n if (!input) continue;\n const { id, version, rule } = routine.definition;\n views.push({ id, owner: input.owner, current: version, pending: routine.pending?.version ?? null, lifecycle: routine.lifecycle, status: routine.status,\n definition: { version, schedule: rule as unknown as RoutineScheduleFields,\n ...('sealed' in input ? { sealed: true as const } : { prompt: input.prompt }), target: input.owner },\n ...(routine.calendarErrors?.length ? { lastError: routine.calendarErrors.at(-1)! } : {}) });\n }\n return views;\n}\n/** The definition for `RoutineCommands.create`. Each owner has at most 8 routines that are not completed. */\nexport function createDefinition(routines: readonly Routine[], owner: string, taskId: string, index: number, action: CreateRoutineAction,\n authority: Authority): HostOccurrenceRoutineDefinition {\n if (action.target !== undefined) throw new Error('An ordinary Bot cannot supply target');\n if (routines.filter(routine => fields(routine)?.owner === owner && routine.lifecycle !== 'completed').length >= 8) throw new Error('Routine limit is 8');\n return definition(hash([taskId, 'create_routine', index]), 1, action.schedule, { owner, authority, prompt: action.prompt });\n}\nexport function owned(routines: readonly Routine[], owner: string, id: string): Routine {\n const routine = routines.find(row => row.definition.id === id);\n if (!routine || fields(routine)?.owner !== owner || routine.lifecycle === 'completed') throw new Error('Routine is unavailable to this Bot');\n return routine;\n}\n/**\n * The routine that `end_routine` completes (§55c): any Bot routine that is open, whatever its owner, so the Main Bot can end\n * the routine of an archived Bot. The command checks the Main Bot role.\n */\nexport function endable(routines: readonly Routine[], id: string): Routine {\n const routine = routines.find(row => row.definition.id === id);\n if (!routine || !fields(routine) || routine.lifecycle === 'completed') throw new Error('No open Bot routine has this id');\n return routine;\n}\n/** The next version for `RoutineCommands.update`. It builds on `pending` when one is staged. */\nexport function updateDefinition(routines: readonly Routine[], owner: string, action: UpdateRoutineAction): HostOccurrenceRoutineDefinition {\n const routine = owned(routines, owner, action.routineId);\n const prior = routine.pending ?? routine.definition, input = prior.hostOccurrence!.input as unknown as BotRoutineInput;\n // Only the member can seal a new version, so neither a Bot nor an owner prompt edit reaches a sealed routine.\n if ('sealed' in input) throw new Error('A sealed routine changes only through resealRoutine');\n return definition(prior.id, prior.version + 1, action.schedule ?? prior.rule as unknown as RoutineScheduleFields,\n { ...input, prompt: action.prompt ?? input.prompt });\n}\n\n/**\n * Checks one sealed template for routine `id` version `version` of a Bot with execution template `execution`: the\n * categories, the Agent, and the offer that each occurrence will carry. It runs at create and at reseal.\n */\nfunction checkSealed(id: string, version: number, sealed: SealedRoutineTemplate, execution: ExecutionTemplate): void {\n if (canonical(sealed.sealing.categories) !== canonical(SEALED_ROUTINE_CATEGORIES)) throw new Error('A sealed routine seals task-input only');\n const { agentRef } = execution.payload;\n if (canonical(sealed.agentRef) !== canonical({ agentId: agentRef.agentId, profileRevision: agentRef.profileRevision })) {\n throw new Error('The template is sealed for another Agent revision');\n }\n const { instruction: _, ...plain } = execution.payload;\n const offer = { ...plain, sealing: sealed.sealing, sealed: sealed.template, routineRef: { routineId: id, definitionVersion: version, notAfter: sealed.notAfter } };\n if (!HostOfferSealedPayloadSchema.safeParse(offer).success) throw new Error('Supply a valid sealed template');\n if ('ciphertextRef' in sealed.template) throw new Error('A sealed routine template must be inline');\n}\n/**\n * The definition of a new sealed routine. The member picks `routineId` (a fresh UUID), because the template binds it, and\n * seals version 1. An id that any routine row already has is refused, whatever its lifecycle, except an exact retry: the\n * version 1 that the same command made, which K4 `create` takes as a no-op. It counts toward the limit of 8 open routines\n * of the owner.\n */\nexport function sealedDefinition(routines: readonly Routine[], owner: string, action: SealedRoutineAction,\n execution: ExecutionTemplate): HostOccurrenceRoutineDefinition {\n if (action.definitionVersion !== 1) throw new SealedRoutineVersionError(1);\n const next = definition(action.routineId, 1, scheduled(action.schedule), { owner, authority: 'owner', sealed: action.sealed });\n const existing = routines.find(routine => routine.definition.id === action.routineId);\n // A member retry after a lost response resends the same bytes.\n if (existing) {\n if (canonical(existing.definition) === canonical(next)) return next;\n throw new Error('A routine already has this id');\n }\n if (routines.filter(routine => fields(routine)?.owner === owner && routine.lifecycle !== 'completed').length >= 8) throw new Error('Routine limit is 8');\n checkSealed(action.routineId, 1, action.sealed, execution);\n return next;\n}\n/**\n * The next version of a sealed routine, with a new template. Only a routine that is already sealed takes one, and it keeps\n * its owner and authority. The template must be sealed for `max(current, pending) + 1`, else `SealedRoutineVersionError`.\n * A retry resends the same template bytes; K4 treats the same definition as a no-op.\n */\nexport function resealDefinition(routines: readonly Routine[], owner: string, action: SealedRoutineAction,\n execution: ExecutionTemplate): HostOccurrenceRoutineDefinition {\n const version = action.definitionVersion;\n const routine = owned(routines, owner, action.routineId);\n const prior = routine.pending ?? routine.definition, input = prior.hostOccurrence!.input as unknown as BotRoutineInput;\n if (!('sealed' in input)) throw new Error('Only a sealed routine takes a new template');\n const next = definition(action.routineId, version, scheduled(action.schedule), { owner: input.owner, authority: input.authority, sealed: action.sealed });\n // A member retry resends the same bytes: the current or staged version it made already is a K4 no-op.\n if ([routine.definition, routine.pending].some(row => canonical(row) === canonical(next))) return next;\n if (version !== prior.version + 1) throw new SealedRoutineVersionError(prior.version + 1);\n checkSealed(action.routineId, version, action.sealed, execution);\n return next;\n}\n/** The sealed template of one routine version: the K8 `sealedTemplate` lookup of a Host sync. */\nexport function sealedTemplate(routines: Iterable<Routine>, ref: SealedRoutineRef): SealedRoutineTemplate | undefined {\n for (const routine of routines) {\n for (const row of [routine.definition, routine.pending]) {\n if (row?.id === ref.routineId && row.version === ref.definitionVersion) {\n const input = fields({ ...routine, definition: row });\n return input && sealedOf(input);\n }\n }\n }\n return undefined;\n}\n/** The `bot-routine` occurrence hook. It writes the routine Turn in the occurrence commit. `sync` promotes it. */\nexport function routineTurn(state: CollaborationState, run: HostOccurrenceRun): void {\n const input = run.input as unknown as BotRoutineInput, id = occurrenceIntentKey(run.occurrenceKey);\n // A sealed routine Turn names its routine version; the sync freezes that version's template, and the Host keeps no request.\n addTurn(state, { id, root: id, source: 'routine', botId: input.owner, hop: 0, authority: input.authority,\n ...('sealed' in input ? { request: '', sealedRoutine: { routineId: run.routineId, definitionVersion: run.definitionVersion } } : { request: input.prompt }) });\n}\n/** A routine Turn id is its K4 intent key, `occurrenceIntentKey(<occurrence key>)`. */\nexport function routineOccurrence(turn: Pick<Turn, 'id'>): string {\n const key = occurrenceOfIntentKey(turn.id);\n if (key === undefined) throw new Error(`Routine Turn ${turn.id} names no occurrence`);\n return key;\n}\n/**\n * A routine Turn that ends without an intent concludes its open occurrence.\n * Then a staged version can switch, and `compact` can remove the row.\n */\nexport function concludeRoutineTurn(s: LedgerState, turn: Turn): boolean {\n const key = routineOccurrence(turn), occurrence = s.occurrences[key];\n if (!occurrence?.hook || occurrence.intentId || occurrence.conclusion) return false;\n concludeOccurrence(s, key, 'cancelled');\n return true;\n}\n","import { buildHandoffPack, type HandoffPackBudgets } from '@byok-sdk/protocol';\nimport { hash, MIN_TOMBSTONE_RETENTION_MS, time, type Json } from '@byok-sdk/server/execution-core';\nimport { DEFAULT_CONTEXT_TURN_LIMIT, handoffFrameBytes, handoffTurn } from './rules/context.js';\nimport type { CollaborationState, Turn } from './model.js';\nimport { refuseUnmigratedWouldDo } from './rules/autonomy.js';\nimport { supersededDeliveryIds } from './delivery-superseded.js';\n\n/**\n * Explicit retention (#798). The Host acknowledges settled roots. One call moves every row of each root out of the\n * state into per-id rows, and retires the root's Turn, input and round ids for good. It never runs on its own.\n * Command records answer replays for `retentionMs` after they move; the other rows stay.\n */\nexport interface RetentionInput {\n /**\n * Root ids: the `root` field of a Turn projection, or the round root that `roomInput` and a room `receive` return.\n * A room seat Turn shows its seat id as `root`; it is refused with `seat_root` and its `roundRoot`.\n * A root that is already archived counts again harmlessly.\n */\n acknowledgedRoots: readonly string[];\n now: number;\n /** At least seven days: the replay window of the moved command records. */\n retentionMs: number;\n}\n/** The ContextPack limits of the Host. Rows in the window of a Bot stay in the state. */\nexport interface RetentionLimits {\n contextTurnLimit: number;\n /** The budgets of the Bot history: the ones the Host freezes with, so its Turns read only what stays. */\n handoff: HandoffPackBudgets;\n}\n/** K4 facts by Turn id. */\nexport interface RetentionFacts {\n /** The Turn still has its K4 intent. */\n hasIntent(turnId: string): boolean;\n /** The routine occurrence of a routine Turn is not concluded yet. */\n occurrenceOpen(turnId: string): boolean;\n}\n/** Where retention writes, in the same transaction as the state. L: the K4 application row port. */\nexport interface RetentionStore {\n put(namespace: string, id: string, value: Json, expiresAt?: number): void;\n expire(namespace: string, now: number): number;\n retire(namespace: string, id: string): void;\n isRetired(namespace: string, id: string): boolean;\n}\nexport interface RetentionResult {\n archivedRoots: number; alreadyArchivedRoots: number; archivedRows: number;\n archivedCommands: number; expiredCommands: number; beforeBytes: number; afterBytes: number;\n}\n/**\n * The whole call changes nothing. `protected_root`: the root is still in use; acknowledge it again after it settles.\n * `seat_root`: the id is a room seat Turn, which belongs to its round's root. Acknowledge `roundRoot` instead; a retry of\n * the seat id fails the same way each time.\n */\nexport type RetentionRefusedCode = 'protected_root' | 'seat_root';\nexport class RetentionRefused extends Error {\n constructor(readonly code: RetentionRefusedCode, readonly root: string, reason: string, readonly roundRoot?: string) {\n super(`Retention refused: ${reason}`); this.name = 'RetentionRefused';\n }\n}\nconst OPEN_DELIVERY = new Set(['staged', 'pending', 'sending', 'unknown']);\nconst values = <T>(rows: Record<string, T> | undefined): T[] => Object.values(rows ?? {});\nconst own = <T>(rows: Record<string, T> | undefined, id: string): T | undefined => rows && Object.hasOwn(rows, id) ? rows[id] : undefined;\n\n/**\n * The ids that a Bot's next ContextPacks can still read: the turns of its handoff pack, up to its newest, and its last\n * cards and questions. The pack leaves out the Turns that can still freeze, and its total always gives `earlier` all of\n * `earlyBytes`. A freeze has no more than that, a Cross-Bot Turn often less, and its extra Turns only start `earlier` at a\n * newer turn. So no freeze reads a turn older than this pack.\n */\nfunction contextWindow(state: CollaborationState, limit: number, handoff: HandoffPackBudgets): Set<string> {\n const kept = new Set<string>(), byBot = new Map<string, { turns: Turn[]; cards: string[]; questions: string[] }>();\n const of = (botId: string) => {\n let rows = byBot.get(botId);\n if (!rows) byBot.set(botId, rows = { turns: [], cards: [], questions: [] });\n return rows;\n };\n // A frozen Turn is `processing` (its offer is in K4) or concluded. Queued and blocked Turns can still freeze.\n for (const turn of values(state.turns)) if (turn.conclusion || turn.status === 'processing') of(turn.botId).turns.push(turn);\n for (const card of values(state.cards)) { const turn = own(state.turns, card.turnId); if (turn) of(turn.botId).cards.push(card.turnId); }\n for (const question of values(state.questions)) { const turn = own(state.turns, question.turnId); if (turn) of(turn.botId).questions.push(question.turnId); }\n const rows = Math.min(limit, DEFAULT_CONTEXT_TURN_LIMIT);\n for (const bot of byBot.values()) {\n const totalBytes = Math.max(handoff.totalBytes, handoff.recentBytes + handoff.earlyBytes + handoffFrameBytes(bot.turns.length));\n const pack = buildHandoffPack(bot.turns.map(handoffTurn), { ...handoff, totalBytes });\n // `omittedTurns` counts the older turns, and a newest turn that did not fit, which an empty `recent` shows.\n const oldest = pack.omittedTurns - (pack.recent.length ? 0 : 1);\n for (const turn of bot.turns.slice(oldest)) kept.add(turn.id);\n for (const id of [...bot.cards.slice(-rows), ...bot.questions.slice(-rows)]) kept.add(id);\n }\n return kept;\n}\ninterface Members {\n turns: Turn[]; roots: Set<string>; delegations: string[]; batches: string[]; units: string[]; replies: string[];\n cards: string[]; questions: string[]; inputs: string[]; batch?: string; rounds: string[]; seats: string[]; inbounds: string[]; deliveries: string[]; wouldDo: string[];\n}\n/** Every row of root `root`. A round's seat Turns have their own root, so they join the round's root. */\nfunction members(state: CollaborationState, root: string): Members {\n const rounds = values(state.team.rounds).filter(round => round.root === root);\n const seats = rounds.flatMap(round => round.seats), roots = new Set([root, ...seats]);\n const turns = values(state.turns).filter(turn => roots.has(turn.root)), ids = new Set(turns.map(turn => turn.id));\n const delegations = values(state.delegations).filter(d => roots.has(d.root)).map(d => d.id), chained = new Set(delegations);\n const replies = Object.entries(state.replies).filter(([, reply]) => ids.has(reply.turnId)).map(([taskId]) => taskId);\n const batch = own(state.inputBatches, root);\n return {\n turns, roots, delegations, replies, rounds: rounds.map(round => round.id), seats,\n batches: values(state.batches).filter(row => row.delegationIds.some(id => chained.has(id))).map(row => row.id),\n units: values(state.units).filter(unit => roots.has(unit.root)).map(unit => unit.id),\n cards: values(state.cards).filter(card => ids.has(card.turnId)).map(card => card.id),\n questions: values(state.questions).filter(question => ids.has(question.turnId)).map(question => question.id),\n ...(batch ? { batch: batch.id } : {}), inputs: batch ? [...batch.inputIds] : [],\n // A filtered inbound has no root (#1229), so a root acknowledgement does not move it; it stays with its audit row.\n inbounds: values(state.channel?.inbounds).filter(row => row.root !== undefined && roots.has(row.root)).map(row => row.id),\n deliveries: values(state.channel?.deliveries).filter(row => ids.has(row.turnId)).map(row => row.id),\n wouldDo: values(state.wouldDo).filter(row => ids.has(row.turnId)).map(row => row.id),\n };\n}\n/** The first reason that the root is still in use, or `undefined`. */\nfunction protection(state: CollaborationState, m: Members, facts: RetentionFacts, window: Set<string>, superseded: ReadonlySet<string>, now: number): string | undefined {\n for (const turn of m.turns) {\n if (!turn.conclusion) return 'A Turn of the root is not concluded';\n if (facts.hasIntent(turn.id) && !turn.reported) return 'A Turn of the root is not reported';\n if (turn.source === 'routine' && facts.occurrenceOpen(turn.id)) return 'A routine occurrence of the root is open';\n }\n for (const id of m.delegations) {\n const d = state.delegations[id]!;\n if (!d.verdict || d.lateTurnId || d.cancel && !d.cancel.delivered) return 'A delegation of the root is unresolved';\n }\n if (m.batches.some(id => !state.batches[id]!.released)) return 'A delegation batch of the root is not released';\n if (m.units.some(id => state.units[id]!.state === 'reserved')) return 'A budget unit of the root is reserved';\n for (const id of m.cards) {\n const card = state.cards[id]!;\n if (card.state === 'pending' || card.state === 'confirmed' && card.result === undefined && card.error === undefined || !card.decisionReported) {\n return 'A card of the root is not settled';\n }\n }\n if (m.questions.some(id => state.questions[id]!.answer === undefined)) return 'A question of the root is unanswered';\n const batch = m.batch === undefined ? undefined : state.inputBatches![m.batch]!;\n if (batch && (batch.state === 'open' || batch.revision !== 2)) return 'The input batch of the root is not settled';\n if (m.rounds.some(id => !state.team.rounds[id]!.closed)) return 'A round of the root is open';\n if (m.seats.some(id => !state.team.seats[id]?.released)) return 'A room seat of the root is not released';\n if (m.deliveries.some(id => !superseded.has(id) && OPEN_DELIVERY.has(state.channel!.deliveries[id]!.state))) return 'A delivery of the root is not settled';\n if (m.inbounds.some(id => { const reply = state.channel!.inbounds[id]!.reply; return !!reply?.token && reply.expiresAt > now; })) {\n return 'An inbound reply route of the root is live';\n }\n if (m.turns.some(turn => window.has(turn.id))) return 'The root is in the ContextPack window of its Bot';\n return undefined;\n}\n/** Moves rows of one map. */\nfunction move<T>(store: RetentionStore, namespace: string, rows: Record<string, T> | undefined, ids: readonly string[]): number {\n if (!rows) return 0;\n for (const id of ids) { store.put(namespace, id, rows[id] as unknown as Json); delete rows[id]; }\n return ids.length;\n}\n/** Bytes of the state, for the result. */\nconst bytes = (state: CollaborationState) => Buffer.byteLength(JSON.stringify(state));\n\nexport function retainRoots(state: CollaborationState, input: RetentionInput, limits: RetentionLimits, facts: RetentionFacts,\n store: RetentionStore): RetentionResult {\n const now = time(input.now), retention = time(input.retentionMs);\n if (retention < MIN_TOMBSTONE_RETENTION_MS) throw new Error('Retention must be at least seven days');\n const expiresAt = time(now + retention);\n if (!Array.isArray(input.acknowledgedRoots)) throw new Error('Acknowledged roots must be an array');\n const roots = [...new Set(input.acknowledgedRoots)];\n if (roots.some(root => typeof root !== 'string' || !root)) throw new Error('Invalid acknowledged root');\n if (!Number.isSafeInteger(limits.contextTurnLimit) || limits.contextTurnLimit < 1) throw new Error('Invalid ContextPack limits');\n refuseUnmigratedWouldDo(state);\n const result: RetentionResult = { archivedRoots: 0, alreadyArchivedRoots: 0, archivedRows: 0, archivedCommands: 0,\n expiredCommands: store.expire('commands', now), beforeBytes: bytes(state), afterBytes: 0 };\n // Decide every root on the state before this call, then move. A refusal throws before any move.\n const window = contextWindow(state, limits.contextTurnLimit, limits.handoff), selected: Members[] = [];\n const superseded = supersededDeliveryIds(state.channel?.deliveries ?? {});\n for (const root of roots) {\n const seat = own(state.team.seats, root);\n if (seat) {\n const roundRoot = state.team.rounds[seat.roundId]?.root ?? seat.roundId;\n throw new RetentionRefused('seat_root', root, `The Turn is a room seat of root ${roundRoot}`, roundRoot);\n }\n const m = members(state, root);\n if (!m.turns.length && !m.rounds.length && m.batch === undefined && !own(state.budgets, root)) {\n if (!store.isRetired('root', root)) throw new Error('Acknowledged root not found');\n result.alreadyArchivedRoots++; continue;\n }\n const reason = protection(state, m, facts, window, superseded, now);\n if (reason) throw new RetentionRefused('protected_root', root, reason);\n selected.push(m);\n }\n for (const m of selected) {\n const turnIds = m.turns.map(turn => turn.id), consumed = new Set(turnIds);\n result.archivedRows += move(store, 'turns', state.turns, turnIds) + move(store, 'schemas', state.schemas, turnIds.filter(id => own(state.schemas, id)))\n + move(store, 'budgets', state.budgets, [...m.roots].filter(id => own(state.budgets, id)))\n + move(store, 'delegations', state.delegations, m.delegations) + move(store, 'batches', state.batches, m.batches)\n + move(store, 'units', state.units, m.units) + move(store, 'replies', state.replies, m.replies)\n + move(store, 'cards', state.cards, m.cards) + move(store, 'questions', state.questions, m.questions)\n + move(store, 'inputs', state.inputs, m.inputs) + move(store, 'inputBatches', state.inputBatches, m.batch === undefined ? [] : [m.batch])\n + move(store, 'rounds', state.team.rounds, m.rounds) + move(store, 'seats', state.team.seats, m.seats)\n + move(store, 'roots', state.team.roots, [...m.roots].filter(id => own(state.team.roots, id)))\n + move(store, 'inbounds', state.channel?.inbounds, m.inbounds) + move(store, 'deliveries', state.channel?.deliveries, m.deliveries)\n + move(store, 'wouldDo', state.wouldDo, m.wouldDo);\n // A rejection has no id. Its hash is its id; equal rows are equal evidence.\n const rejected = state.rejected.filter(row => row.consumedBy !== undefined && consumed.has(row.consumedBy));\n for (const row of rejected) store.put('rejected', hash(['rejected', row]), row as unknown as Json);\n state.rejected = state.rejected.filter(row => !rejected.includes(row));\n result.archivedRows += rejected.length;\n for (const id of turnIds) store.retire('turn', id);\n for (const id of m.inputs) store.retire('input', id);\n for (const id of m.rounds) store.retire('round', id);\n for (const root of m.roots) store.retire('root', root);\n result.archivedRoots++;\n }\n result.archivedRows += retainRoomMessages(state, store, limits.contextTurnLimit) + retainRootless(state, store);\n // A record moves when its root has moved, or when it has no root. It then answers replays until it expires.\n for (const [id, record] of Object.entries(state.commands ?? {})) {\n if (record.root !== undefined && !store.isRetired('root', record.root)) continue;\n store.put('commands', id, record as unknown as Json, expiresAt);\n delete state.commands![id];\n result.archivedCommands++;\n }\n result.afterBytes = bytes(state);\n return result;\n}\n/**\n * Room messages of archived roots (#1394). A message's id is its round root (a room input) or its seat (a post), so a message\n * whose id is in neither `team.rounds` nor `team.seats` belongs to an archived root. It moves unless it is one of the last\n * `limit` messages of its room: a seat ContextPack reads at most that many, newest last. `visibleFrom` then counts in the\n * kept list, so each member sees the same kept messages as before.\n */\nfunction retainRoomMessages(state: CollaborationState, store: RetentionStore, limit: number): number {\n let count = 0;\n for (const room of values(state.team.rooms)) {\n const window = room.messages.length - limit;\n const moved = room.messages.map((message, index) => index < window && !own(state.team.rounds, message.id) && !own(state.team.seats, message.id));\n if (!moved.includes(true)) continue;\n for (const [botId, from] of Object.entries(room.visibleFrom)) room.visibleFrom[botId] = from - moved.slice(0, from).filter(Boolean).length;\n room.messages.forEach((message, index) => { if (moved[index]) store.put('roomMessages', message.id, message as unknown as Json); });\n room.messages = room.messages.filter((_, index) => !moved[index]);\n count += moved.filter(Boolean).length;\n }\n return count;\n}\n/** Rows outside any root: audit lines, revoked push routes and settled persona deliveries. They stay as history. */\nfunction retainRootless(state: CollaborationState, store: RetentionStore): number {\n let count = 0;\n if (state.audit.length) {\n store.put('audit', hash(['audit', state.revision ?? 0, state.audit]), state.audit);\n count += state.audit.length; state.audit = [];\n }\n const routes = state.channel?.pushRoutes ?? {}, used = new Set(values(state.channel?.deliveries).map(row => row.route.kind === 'push' ? row.route.pushRouteId : ''));\n count += move(store, 'pushRoutes', routes, Object.keys(routes).filter(id => routes[id]!.revokedAt !== undefined && !used.has(id)));\n // Keep pending work, the newest applied delivery of each Bot (it proves that a persona was applied) and failures of the current revision.\n const newest = new Map<string, number>();\n for (const op of state.team.homeOperations) if (op.status === 'applied') newest.set(op.botId, Math.max(newest.get(op.botId) ?? 0, op.sequence));\n const settled = state.team.homeOperations.filter(op => op.status === 'applied' ? newest.get(op.botId) !== op.sequence\n : op.status === 'failed' && op.request.payload.agentRef.profileRevision !== state.team.bots[op.botId]?.revision);\n for (const op of settled) store.put('homeOperations', String(op.sequence), op as unknown as Json);\n state.team.homeOperations = state.team.homeOperations.filter(op => !settled.includes(op));\n return count + settled.length;\n}\n","import type { HandoffPackBudgets } from '@byok-sdk/protocol';\nimport type { CollaborationState, Turn } from './model.js';\nimport type { BotRoutine } from './routines.js';\nimport * as rules from './rules/context.js';\nimport { HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS } from './rules/history.js';\n\n// K8 adapter for the pure schema and ContextPack rules in `rules/`. The device ledger is the history authority here.\nexport { CONFIRMABLE_MAX, DEFAULT_CONFIRMABLE, DEFAULT_TIME_ZONES, MAIN_ACTIONS, NEW_BOTS, NEW_ROOMS, outcomeOffer, outcomeSchema, ROOM_SYSTEM_PROMPT, SYSTEM_PROMPT, TIME_ZONES_MAX,\n TURN_ACTIONS, type CheckedOffer, type ConfirmableSpec, type MainAction, type OutcomeOffer, type TurnAction } from './rules/schema.js';\nexport { contextTurns, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, type ContextHistory, type ContextTurn, type InstructionLimits } from './rules/context.js';\n\n/** Every stored Turn and its rows, in ledger order. */\nfunction ledgerHistory(state: CollaborationState): rules.ContextHistory {\n return { turns: Object.values(state.turns), cards: Object.values(state.cards), questions: Object.values(state.questions), rejected: state.rejected };\n}\n/** `crossRequest` is the framed Request section of a Cross-Bot Turn; its background is trimmed too (§3.7). */\nexport function turnContext(state: CollaborationState, turn: Turn, turnLimit = HISTORY_MAX_ITEMS, maxBytes = HISTORY_MAX_BYTES, crossRequest?: string,\n routines: readonly BotRoutine[] = [], handoff?: HandoffPackBudgets) {\n return rules.turnContext(state, rules.botHistory(state, turn), turn, turnLimit, maxBytes, crossRequest, routines, handoff);\n}\n/** Snapshot views include the candidate. Frozen turn views keep it in Request. */\nexport function contextPack<T extends object = Record<never, never>>(state: CollaborationState, turnLimit?: number, currentTurnId?: string,\n maxBytes?: number, separateRequest?: boolean, shared?: T, fit?: { request?: string; background?: unknown[][] }, routines: readonly BotRoutine[] = [],\n handoff?: HandoffPackBudgets) {\n return rules.contextPack(ledgerHistory(state), turnLimit, currentTurnId, maxBytes, separateRequest, shared, fit, routines, handoff);\n}\n","import type { AgentHomeProjectionReadback, BotTurnOutcome, CreateBotAction, RoomFields, UpdateBotAction } from '@byok-sdk/protocol';\nimport { hash, canonical, type ExecutionTemplate } from '@byok-sdk/server/execution-core';\nimport { json, type CollaborationState } from './model.js';\nimport type { BotProfile, HomeOperation, Room, TeamState } from './team-model.js';\nimport type { Publish } from './rules/delegation.js';\nimport { roomFields, roomVisibility } from './rules/rooms.js';\n\nimport { NEW_BOTS, NEW_ROOMS } from './rules/schema.js';\nimport { DEFAULT_AUTONOMY } from './rules/autonomy.js';\nimport { activeBot, admitBotToolsets, archiveBot, inactive, profileProjection, refuseExternalRooms, refuseExternalTeam, requireMain, TEAM_BOT_LIMIT, type TeamSnapshotBot } from './rules/team.js';\n\nexport { activeBot, admitBotToolsets, inactive, NEW_BOTS, NEW_ROOMS, requireMain, roomFields };\nexport const TEAM_NOTE_LIMIT = 20;\nexport function projectionRequestId(value: unknown): string {\n const digest = hash(value);\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-a${digest.slice(17, 20)}-${digest.slice(20, 32)}`;\n}\n/**\n * The Agent home flush rules (#793 S13), the pure part of L's `flushHomes`; each Host runs its own I/O around them.\n * `homeHead` gives the pending operation `sequence` when it is its Bot's oldest pending one and the Bot is free\n * (`busy(botId)`: the Bot has an intent with no conclusion). Only a head is flushed.\n */\nexport function homeHead(team: Pick<TeamState, 'homeOperations'>, sequence: number, busy: (botId: string) => boolean): HomeOperation | undefined {\n const op = team.homeOperations.find(row => row.sequence === sequence);\n if (!op || op.status !== 'pending') return undefined;\n const oldest = team.homeOperations.filter(row => row.botId === op.botId && row.status === 'pending').reduce((a, b) => a.sequence <= b.sequence ? a : b);\n return oldest === op && !busy(op.botId) ? op : undefined;\n}\n/** The requests of an operation in the order a flush reads them back: the first, then each retry. */\nexport const homeRequests = (op: HomeOperation) => [op.request, ...op.retries];\nexport type HomeReadback = Pick<AgentHomeProjectionReadback, 'deviceId' | 'agentRef' | 'requestId' | 'projectionHash' | 'status'>;\n/**\n * Checks the readback of one request of the operation. A readback for another device, Agent, request or projection throws\n * `Home readback identity conflict`. Returns it when it is terminal (not `pending`); the flush reads no later request then.\n */\nexport function checkHomeReadback(request: HomeOperation['request'], read: HomeReadback | undefined): HomeReadback | undefined {\n if (!read) return undefined;\n const payload = request.payload;\n if (read.deviceId !== request.deviceId || !same(read.agentRef, payload.agentRef)\n || read.requestId !== payload.requestId || read.projectionHash !== payload.projectionHash) throw new Error('Home readback identity conflict');\n return read.status !== 'pending' ? read : undefined;\n}\n/**\n * No request is terminal. Once `retryAt` has passed, adds a retry of the same desired revision with the next durable request\n * id and a backoff (min(60 s, 1 s × 2^n)). Returns the request to enqueue: the latest.\n */\nexport function planHomeRetry(op: HomeOperation, now: number): HomeOperation['request'] {\n if (op.retryAt !== undefined && now >= op.retryAt) {\n const retry = structuredClone(op.request);\n retry.payload.requestId = projectionRequestId([op.request.payload.requestId, op.retries.length + 1]);\n op.retries.push(retry);\n op.retryAt = now + Math.min(60_000, 1000 * 2 ** Math.min(op.retries.length, 6));\n }\n return op.retries.at(-1) ?? op.request;\n}\n/** The enqueue of the latest request succeeded: the first retry is due a second later. */\nexport function homeEnqueued(op: HomeOperation, now: number): void {\n op.retryAt ??= now + 1000;\n}\n/**\n * Settles the operation with a terminal readback: `applied` or `idempotent` applies it and readies its Bot at that revision;\n * any other status fails it and publishes `persona-failed:<sequence>`.\n */\nexport function applyHomeTerminal(state: CollaborationState, op: HomeOperation, terminal: HomeReadback, publish: Publish): void {\n if (terminal.status === 'applied' || terminal.status === 'idempotent') {\n op.status = 'applied';\n const bot = state.team.bots[op.botId]!;\n if (bot.revision === op.request.payload.agentRef.profileRevision) bot.readyRevision = bot.revision;\n } else {\n op.status = 'failed'; op.error = terminal.status;\n publish(`persona-failed:${op.sequence}`, json({ owner: op.botId, revision: op.request.payload.agentRef.profileRevision, reason: op.error, recoverable: true }));\n }\n}\n/** A flush step threw: the operation keeps `pending` with the error. */\nexport function failHomeFlush(op: HomeOperation, error: unknown): void {\n op.error = String(error instanceof Error ? error.message : error);\n}\nfunction projection(state: CollaborationState, bot: BotProfile): void {\n const value = profileProjection(bot);\n const requestId = projectionRequestId([bot.id, bot.revision]);\n state.team.homeOperations.push({ sequence: ++state.sequence, botId: bot.id, status: 'pending', retries: [], request: {\n deviceId: bot.execution.deviceId, payload: { requestId,\n agentRef: { agentId: bot.id, profileRevision: bot.revision }, projectionHash: `sha256:${hash(value)}`, projection: value },\n } });\n}\nexport function createBot(state: CollaborationState, taskId: string, action: CreateBotAction, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): BotProfile {\n if (!NEW_BOTS.includes(action.localId as typeof NEW_BOTS[number])) throw new Error('Unknown local Bot slot');\n if (Object.values(state.team.bots).filter(b => !b.archived).length >= TEAM_BOT_LIMIT) throw new Error(`Team Bot limit is ${TEAM_BOT_LIMIT}`);\n const base = models[action.model];\n if (!base) throw new Error('Unavailable model');\n admitBotToolsets(base, readOnlyToolsets);\n const id = hash([taskId, action.localId]);\n const execution = structuredClone(base);\n execution.payload.agentRef = { agentId: id, profileRevision: '1' };\n // A new Bot starts in observe (#1229, owner ruling): the owner sees what it would do before it does it.\n const bot: BotProfile = { id, name: action.name, role: action.role, persona: action.persona, model: action.model,\n mainBot: false, archived: false, revision: '1', readyRevision: null, autonomy: DEFAULT_AUTONOMY, execution };\n state.team.bots[id] = bot;\n projection(state, bot);\n return bot;\n}\nexport function updateBot(state: CollaborationState, action: UpdateBotAction, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): void {\n const bot = activeBot(state.team, action.botId);\n const model = action.model ?? bot.model, base = models[model];\n if (base) admitBotToolsets(base, readOnlyToolsets);\n const revision = (BigInt(bot.revision) + 1n).toString();\n if (BigInt(revision) > 9223372036854775807n) throw new Error('Profile revision limit');\n // #1357: without a template the Bot keeps its stored one, and the freeze holds its Turns until the Host provides one.\n const execution = structuredClone(base ?? bot.execution);\n // Model selection cannot move the Bot home to another device.\n execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: bot.id, profileRevision: revision };\n Object.assign(bot, { name: action.name ?? bot.name, role: action.role ?? bot.role, persona: action.persona ?? bot.persona,\n model, revision, readyRevision: null, execution });\n projection(state, bot);\n}\n/**\n * The `teamBot` port of a team snapshot (#739 Q4c). A new Bot gets the snapshot id and its first projection.\n * A profile change takes the `update_bot` path, so it queues the same persona projection (T4).\n * Host persona mode (#879): the Bot takes the Host's profile revision and no projection is queued.\n */\nexport function writeSnapshotBot(state: CollaborationState, row: TeamSnapshotBot, models: Record<string, ExecutionTemplate>, readOnlyToolsets: readonly string[] = []): void {\n const bot = state.team.bots[row.id];\n if (state.team.external?.persona) { writeHostProfile(state, bot, row, models, readOnlyToolsets); return; }\n if (bot) {\n if (bot.name !== row.name || bot.role !== row.role || bot.persona !== row.persona || bot.model !== row.model) {\n updateBot(state, { botId: row.id, name: row.name, role: row.role, persona: row.persona, model: row.model }, models, readOnlyToolsets);\n }\n return;\n }\n const base = models[row.model];\n if (!base) throw new Error('Unavailable model');\n admitBotToolsets(base, readOnlyToolsets);\n const execution = structuredClone(base);\n execution.payload.agentRef = { agentId: row.id, profileRevision: '1' };\n const created: BotProfile = { id: row.id, name: row.name, role: row.role, persona: row.persona, model: row.model,\n mainBot: false, archived: false, revision: '1', readyRevision: null, autonomy: DEFAULT_AUTONOMY, execution };\n state.team.bots[row.id] = created;\n projection(state, created);\n}\n/**\n * Re-projects the Host's execution templates onto each unarchived Bot, a suspended one too (#1357). A Bot keeps its device,\n * and its agentRef follows its profile. A Bot whose model has no template keeps its stored one, and the freeze holds its Turns\n * with `Unavailable model` until the Host provides it. No profile field changes and no persona projection is queued.\n * A template that fails the toolset check refuses the whole call before any write.\n */\nexport function applyModels(state: CollaborationState, models: Readonly<Record<string, ExecutionTemplate>>, readOnlyToolsets: readonly string[]): void {\n for (const model of Object.values(models)) admitBotToolsets(model, readOnlyToolsets);\n for (const bot of Object.values(state.team.bots)) {\n const base = models[bot.model];\n if (bot.archived || !base) continue;\n const execution = structuredClone(base);\n execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: bot.id, profileRevision: bot.revision };\n bot.execution = execution;\n }\n}\n/**\n * Host persona mode (#879). The revision never goes back, and a profile change needs a newer revision. A newer revision\n * keeps `readyRevision` at the last revision that the Host reported ready: the Bot stays a delegate target, and its\n * Turns wait for `persona_ready` of the new revision.\n */\nfunction writeHostProfile(state: CollaborationState, bot: BotProfile | undefined, row: TeamSnapshotBot, models: Record<string, ExecutionTemplate>,\n readOnlyToolsets: readonly string[]): void {\n const revision = row.profileRevision!;\n if (bot) {\n const changed = bot.name !== row.name || bot.role !== row.role || bot.persona !== row.persona || bot.model !== row.model;\n if (BigInt(revision) < BigInt(bot.revision)) throw new Error(`Profile revision ${revision} of ${row.id} is older than ${bot.revision}`);\n if (revision === bot.revision) {\n if (changed) throw new Error(`A profile change of ${row.id} needs a newer profile revision`);\n return;\n }\n }\n // A new Bot needs a template: its device comes from it. An existing Bot keeps its stored one, as in `updateBot` (#1357).\n const base = models[row.model];\n if (base) admitBotToolsets(base, readOnlyToolsets);\n else if (!bot) throw new Error('Unavailable model');\n const execution = structuredClone(base ?? bot!.execution);\n // Model selection cannot move the Bot home to another device.\n if (bot) execution.deviceId = bot.execution.deviceId;\n execution.payload.agentRef = { agentId: row.id, profileRevision: revision };\n const fields = { name: row.name, role: row.role, persona: row.persona, model: row.model, revision, execution };\n if (bot) Object.assign(bot, fields);\n else state.team.bots[row.id] = { id: row.id, ...fields, mainBot: false, archived: false, readyRevision: null, autonomy: DEFAULT_AUTONOMY };\n}\nexport function applyManagement(state: CollaborationState, actor: string, taskId: string, outcome: BotTurnOutcome,\n models: Record<string, ExecutionTemplate>, accept: (action: string, work: () => void) => void, readOnlyToolsets: readonly string[] = []): void {\n const team = state.team, local: Record<string, string> = {};\n const managed = (kind: string, work: () => void) => accept(kind, () => { requireMain(team, actor); work(); });\n // T3: the team authority owns the Bots. Team notes stay local, and rooms too unless it owns them (#1321).\n const bots = (kind: string, work: () => void) => managed(kind, () => { refuseExternalTeam(team, kind); work(); });\n const rooms = (kind: string, work: () => void) => managed(kind, () => { refuseExternalRooms(team, kind); work(); });\n outcome.create_bot?.forEach(action => bots('create_bot', () => { local[action.localId] = createBot(state, taskId, action, models, readOnlyToolsets).id; }));\n outcome.update_bot?.forEach(action => bots('update_bot', () => updateBot(state, action, models, readOnlyToolsets)));\n outcome.delete_bot?.forEach(action => bots('delete_bot', () => archiveBot(team, action.botId)));\n const resolve = (fields: Partial<RoomFields>) => ({ ...fields,\n ...(fields.members ? { members: fields.members.map(id => local[id] ?? id) } : {}),\n ...(fields.admin ? { admin: local[fields.admin] ?? fields.admin } : {}),\n });\n outcome.create_room?.forEach(action => rooms('create_room', () => {\n if (!NEW_ROOMS.includes(action.localId as typeof NEW_ROOMS[number])) throw new Error('Unknown local room slot');\n const id = hash([taskId, action.localId]);\n if (team.rooms[id]) throw new Error('Duplicate local room slot');\n team.rooms[id] = { id, ...roomFields(team, resolve(action) as RoomFields), messages: [] };\n }));\n outcome.update_room?.forEach(action => rooms('update_room', () => {\n const room = team.rooms[action.roomId];\n if (!room) throw new Error('Room not found');\n const fields = { ...room, ...resolve(action) };\n if (!action.admin && !fields.members.includes(fields.admin ?? '')) delete fields.admin;\n const next = roomFields(team, fields);\n next.visibleFrom = roomVisibility(room, next.members);\n Object.assign(room, next);\n if (!next.admin) delete room.admin;\n }));\n if (outcome.team_note) managed('team_note', () => {\n if (team.notes.length >= TEAM_NOTE_LIMIT) throw new Error('Team note limit is 20');\n team.notes.push({ id: hash([taskId, 'team_note']), text: outcome.team_note!.text });\n });\n}\nexport function same(value: unknown, other: unknown): boolean { return canonical(value) === canonical(other); }\n"]}
@@ -1,3 +1,4 @@
1
+ import type { VectorTestApi } from './vector-test-api.js';
1
2
  import { type ExecutionTemplate } from '@byok-sdk/server/execution-core';
2
3
  import type { CollaborationState } from './model.js';
3
4
  import { type CommitRequest, type CommitResult } from './rules/commit.js';
@@ -29,7 +30,7 @@ export declare const VECTOR_NOW = 1000;
29
30
  */
30
31
  export type SeedTeam = 'local' | 'external' | 'rooms';
31
32
  export declare function seedCollaboration(state: CollaborationState, team?: SeedTeam): void;
32
- export declare function commitVectors(name: string, open: (team?: SeedTeam) => CommitSubject | Promise<CommitSubject>): void;
33
+ export declare function commitVectors({ describe, it, expect }: VectorTestApi, name: string, open: (team?: SeedTeam) => CommitSubject | Promise<CommitSubject>): void;
33
34
  /**
34
35
  * #793 D2b: the sync step as a store operation. The store runs `syncTurn` for each stored Turn, in insertion order, in one
35
36
  * transaction under the same scope lock as `commit`, with the options below. It writes each returned step: a `freeze` stores
@@ -55,12 +56,12 @@ export type SyncIntentRecord = Extract<SyncStep<unknown>, {
55
56
  }>['input'];
56
57
  /** The sync options of the vectors. A Bot with an undeclared connector toolset cannot freeze. */
57
58
  export declare const SYNC_OPTIONS: SyncOptions<never>;
58
- export declare function syncVectors(name: string, open: () => SyncSubject | Promise<SyncSubject>): void;
59
+ export declare function syncVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => SyncSubject | Promise<SyncSubject>): void;
59
60
  /**
60
61
  * The sync vector of a stored template that differs from the Host's (#1358): only L keeps such a template at freeze time,
61
62
  * since H re-projects the scope config's templates at each sync.
62
63
  */
63
- export declare function staleTemplateSyncVectors(name: string, open: () => SyncSubject | Promise<SyncSubject>): void;
64
+ export declare function staleTemplateSyncVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => SyncSubject | Promise<SyncSubject>): void;
64
65
  /**
65
66
  * #793 D2f-5: the delegation settlement of the Host sync. `settle` is one Host sync: the per-Turn steps of the sync contract,
66
67
  * then K8 `settleDelegations` on the store's own intent facts, as L's sync runs it after the Turn steps. A store may run more
@@ -79,7 +80,7 @@ export interface SettlementSubject extends SyncSubject {
79
80
  /** A test edit: the intent concludes, with the K4 cancel reason when one is given. */
80
81
  conclude(turnId: string, conclusion: Conclusion, cancelReason?: 'cancelled' | 'expired'): void | Promise<void>;
81
82
  }
82
- export declare function settlementVectors(name: string, open: () => SettlementSubject | Promise<SettlementSubject>): void;
83
+ export declare function settlementVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => SettlementSubject | Promise<SettlementSubject>): void;
83
84
  /** A reply readback through the SDK `tasks.agentMessage`, as the Host binds it. */
84
85
  export type ReplyRead = (taskId: string, deviceId: string, agentRef: ExecutionTemplate['payload']['agentRef']) => Promise<ReplyReadback>;
85
86
  /**
@@ -90,7 +91,7 @@ export type ReplyRead = (taskId: string, deviceId: string, agentRef: ExecutionTe
90
91
  export interface ReplySubject extends SettlementSubject {
91
92
  checkReplies(now: number, read: ReplyRead, timers?: DelegationTimers): void | Promise<void>;
92
93
  }
93
- export declare function replyVectors(name: string, open: () => ReplySubject | Promise<ReplySubject>): void;
94
+ export declare function replyVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => ReplySubject | Promise<ReplySubject>): void;
94
95
  /**
95
96
  * #793 H batch seal: input coalescing in the Host sync. `open(policy)` opens a store whose input admission uses `policy`, or
96
97
  * no coalescing without one. `sync(now)` is one Host sync at `now`: K8 `sealDueBatches` first, then the Turn steps, then
@@ -99,7 +100,7 @@ export declare function replyVectors(name: string, open: () => ReplySubject | Pr
99
100
  export interface CoalesceSubject extends Omit<SyncSubject, 'sync'> {
100
101
  sync(now: number): void | Promise<void>;
101
102
  }
102
- export declare function coalesceVectors(name: string, open: (policy?: CoalescePolicy) => CoalesceSubject | Promise<CoalesceSubject>): void;
103
+ export declare function coalesceVectors({ describe, it, expect }: VectorTestApi, name: string, open: (policy?: CoalescePolicy) => CoalesceSubject | Promise<CoalesceSubject>): void;
103
104
  /**
104
105
  * #793 S5: the card steps of the Host sync. `sync(now)` is one Host sync at `now`, in L's order: K8 `expireCards`, the Turn
105
106
  * steps of the sync contract, then K8 `reportCardDecisions`. A store may run more rounds in one sync.
@@ -107,7 +108,7 @@ export declare function coalesceVectors(name: string, open: (policy?: CoalescePo
107
108
  export interface CardSubject extends Omit<SyncSubject, 'sync'> {
108
109
  sync(now: number): void | Promise<void>;
109
110
  }
110
- export declare function cardVectors(name: string, open: () => CardSubject | Promise<CardSubject>): void;
111
+ export declare function cardVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => CardSubject | Promise<CardSubject>): void;
111
112
  /**
112
113
  * #793 S6: the room step of the Host sync. `sync(now)` is one Host sync at `now`, in L's order: the room step (K8
113
114
  * `advanceRoomSeats` on the seat facts of the K4 intents), then the Turn steps of the sync contract. When a Turn step releases
@@ -125,7 +126,7 @@ export { ROOM_GRACE_MS };
125
126
  * `r` with both. An owner message mentions `b`, then `main`, so its round has `b`'s seat first.
126
127
  */
127
128
  export declare function seedRoom(state: CollaborationState): void;
128
- export declare function roomVectors(name: string, open: () => RoomSubject | Promise<RoomSubject>): void;
129
+ export declare function roomVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => RoomSubject | Promise<RoomSubject>): void;
129
130
  /**
130
131
  * #793 S11 device observation. `observeDevices(devices)` is the Host's device step, as L's `refreshDevices` runs it after its
131
132
  * discovery read: K8 `observeDevices` on the store's intent facts, in one transaction. `devices` maps a device id to its
@@ -140,7 +141,7 @@ export interface DeviceSubject extends SettlementSubject {
140
141
  */
141
142
  deliver(turnId: string, status?: 'offered' | 'running'): void | Promise<void>;
142
143
  }
143
- export declare function deviceVectors(name: string, open: () => DeviceSubject | Promise<DeviceSubject>): void;
144
+ export declare function deviceVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => DeviceSubject | Promise<DeviceSubject>): void;
144
145
  /** The Host connector of a confirmed card, as L's `HostOptions.connector`. */
145
146
  export type CardConnector = (id: string, action: string, draft: Json, signal: AbortSignal) => Promise<unknown>;
146
147
  /**
@@ -153,7 +154,7 @@ export type CardConnector = (id: string, action: string, draft: Json, signal: Ab
153
154
  export interface CardCallSubject extends CardSubject {
154
155
  callCards(connector: CardConnector): void | Promise<void>;
155
156
  }
156
- export declare function cardCallVectors(name: string, open: () => CardCallSubject | Promise<CardCallSubject>): void;
157
+ export declare function cardCallVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => CardCallSubject | Promise<CardCallSubject>): void;
157
158
  /** The SDK Agent home calls of a Host flush, as L binds `readAgentHomeProjection` and `enqueueAgentHomeProjection`. */
158
159
  export interface HomeCalls {
159
160
  read(request: HomeOperation['request']): Promise<HomeReadback | undefined>;
@@ -170,4 +171,4 @@ export interface HomeCalls {
170
171
  export interface HomeSubject extends SyncSubject {
171
172
  flushHomes(now: number, calls: HomeCalls): void | Promise<void>;
172
173
  }
173
- export declare function homeVectors(name: string, open: () => HomeSubject | Promise<HomeSubject>): void;
174
+ export declare function homeVectors({ describe, it, expect }: VectorTestApi, name: string, open: () => HomeSubject | Promise<HomeSubject>): void;
@@ -1,3 +1,4 @@
1
+ import type { VectorTestApi } from './vector-test-api.js';
1
2
  import type { Json } from '@byok-sdk/server/execution-core';
2
3
  import { type ChannelPort, type Delivery } from './channel.js';
3
4
  import type { CollaborationState } from './model.js';
@@ -75,4 +76,4 @@ export interface DeliverySubject {
75
76
  export declare const FINAL_BODY = "Final answer";
76
77
  /** The reply route token of owner message `key`. */
77
78
  export declare const replyToken: (key: string) => string;
78
- export declare function deliveryVectors(name: string, open: (port: ChannelPort) => Promise<DeliverySubject>): void;
79
+ export declare function deliveryVectors({ describe, it, expect }: VectorTestApi, name: string, open: (port: ChannelPort) => Promise<DeliverySubject>): void;