@byok-sdk/bot-collaboration 0.43.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byok-sdk/bot-collaboration",
3
- "version": "0.43.0",
3
+ "version": "0.44.1",
4
4
  "description": "K8 Bot collaboration for BYOK Hosts: the local Host, the modules a Host composes, the pure rules and shared test vectors, on the K4 execution core.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,9 +54,9 @@
54
54
  "clean": "rm -rf dist"
55
55
  },
56
56
  "dependencies": {
57
- "@byok-sdk/client": "0.43.0",
58
- "@byok-sdk/protocol": "0.43.0",
59
- "@byok-sdk/server": "0.43.0"
57
+ "@byok-sdk/client": "0.44.1",
58
+ "@byok-sdk/protocol": "0.44.1",
59
+ "@byok-sdk/server": "0.44.1"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "@hono/node-server": "^2.1.6",
@@ -71,8 +71,8 @@
71
71
  }
72
72
  },
73
73
  "devDependencies": {
74
- "@byok-sdk/cloud": "0.43.0",
75
- "@byok-sdk/core": "0.43.0",
74
+ "@byok-sdk/cloud": "0.44.1",
75
+ "@byok-sdk/core": "0.44.1",
76
76
  "@byok-sdk/example-host-execution-core": "0.0.1",
77
77
  "@hono/node-server": "^2.1.6",
78
78
  "@types/node": "^24",
@@ -1,7 +0,0 @@
1
- import { hash } from '@byok-sdk/server/execution-core/canonical';
2
-
3
- function autonomousIntentIds(turns,dreams){return new Set(turns.filter(turn=>turn.source==="routine"||turn.source==="bot_request").map(turn=>hash(turn.id)).concat(dreams))}var DEVICE_CONCURRENCY=8;var USER_RESERVED_SLOTS=1;function isUnsubmitted(row){return row.phase==="queued"&&row.attempts===0}function userFirst(rows,userIntentId,autonomous,next){const user=rows.find(row=>row.id===userIntentId);if(!user||!isUnsubmitted(user))return void 0;const queued=rows.filter(row=>row.agent===user.agent&&isUnsubmitted(row)).sort((a,b)=>a.sequence-b.sequence||(a.id<b.id?-1:a.id>b.id?1:0));const order=[...queued.filter(row=>!autonomous.has(row.id)),...queued.filter(row=>autonomous.has(row.id))];if(order.every((row,index)=>row.id===queued[index].id))return void 0;let base=next;for(const row of rows)if(row.sequence>base)base=row.sequence;return {assignments:order.map((row,index)=>({id:row.id,sequence:base+1+index})),sequence:base+order.length}}function admitDeviceSlot(intent,rows,limit=DEVICE_CONCURRENCY){if(!Number.isSafeInteger(limit)||limit<1)throw new Error("A device concurrency limit is a positive safe integer");const reserved=Math.min(USER_RESERVED_SLOTS,limit-1);let occupied=0;for(const row of rows)if(row.id!==intent.id&&row.deviceId===intent.deviceId&&row.occupies)occupied++;return occupied<limit-(intent.source==="user"?0:reserved)}
4
-
5
- export { DEVICE_CONCURRENCY, admitDeviceSlot, autonomousIntentIds, userFirst };
6
- //# sourceMappingURL=chunk-33YA66U7.js.map
7
- //# sourceMappingURL=chunk-33YA66U7.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rules/priority.ts"],"names":[],"mappings":";;AAIO,SAAS,mBAAA,CAAoB,KAAA,CAA+C,MAAA,CAAwC,CACzH,OAAO,IAAI,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,IAAA,EAAQ,KAAK,MAAA,GAAW,SAAA,EAAa,IAAA,CAAK,MAAA,GAAW,aAAa,CAAA,CAAE,GAAA,CAAI,IAAA,EAAQ,IAAA,CAAK,IAAA,CAAK,EAAE,CAAC,CAAA,CAAE,MAAA,CAAO,MAAM,CAAC,CAC3I,CASO,IAAM,kBAAA,CAAqB,EAE3B,IAAM,mBAAA,CAAsB,CAAA,CAa5B,SAAS,aAAA,CAAc,GAAA,CAAwD,CACpF,OAAO,IAAI,KAAA,GAAU,QAAA,EAAY,GAAA,CAAI,QAAA,GAAa,CACpD,CASO,SAAS,SAAA,CAAU,IAAA,CAA+B,YAAA,CAAsB,UAAA,CAC7E,IAAA,CAAwC,CACxC,MAAM,KAAO,IAAA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,IAAA,CAAO,KAAA,CAAM,MAAO,CAC/H,CAOO,SAAS,eAAA,CAAgB,MAAA,CAAwB,IAAA,CAAgC,KAAA,CAAQ,kBAAA,CAA6B,CAC3H,GAAI,CAAC,OAAO,aAAA,CAAc,KAAK,CAAA,EAAK,KAAA,CAAQ,CAAA,CAAG,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CACtH,MAAM,QAAA,CAAW,IAAA,CAAK,GAAA,CAAI,oBAAqB,KAAA,CAAQ,CAAC,CAAA,CACxD,IAAI,QAAA,CAAW,CAAA,CACf,IAAA,MAAW,GAAA,IAAO,IAAA,CAAM,GAAI,GAAA,CAAI,EAAA,GAAO,MAAA,CAAO,EAAA,EAAM,GAAA,CAAI,QAAA,GAAa,MAAA,CAAO,QAAA,EAAY,GAAA,CAAI,QAAA,CAAU,QAAA,EAAA,CACtG,OAAO,QAAA,CAAW,KAAA,EAAS,MAAA,CAAO,MAAA,GAAW,MAAA,CAAS,CAAA,CAAI,QAAA,CAC5D","file":"chunk-33YA66U7.js","sourcesContent":["import { hash } from '@byok-sdk/server/execution-core/canonical';\nimport type { Turn } from './turn.js';\n\n/** The background intents that user input overtakes; dream ids already use the ledger's hashed identity. */\nexport function autonomousIntentIds(turns: readonly Pick<Turn, 'id' | 'source'>[], dreams: readonly string[]): Set<string> {\n return new Set(turns.filter(turn => turn.source === 'routine' || turn.source === 'bot_request').map(turn => hash(turn.id)).concat(dreams));\n}\n\n/**\n * The reference Host's explicit work priority as pure rules (#1229 item 1). The K4 FIFO keeps its order: one queue per\n * Agent, the lowest sequence is the head, and a submitted execution keeps its taskId generation\n * (docs/host-execution-core.md section 3). These rules change only the sequence of queued, never-submitted intents and\n * the dispatch decision of one device.\n */\n/** The concurrent task limit of a device, as the daemon maxConcurrentTasks default (#1121). */\nexport const DEVICE_CONCURRENCY = 8;\n/** The slots of a device that autonomous work may not take, so user input always has one. */\nexport const USER_RESERVED_SLOTS = 1;\n/** The intent fields that the priority rules read. K4 owns every other field. */\nexport interface QueuedIntent {\n readonly id: string; readonly agent: string; readonly sequence: number; readonly phase: string; readonly attempts: number;\n}\n/** A dispatched intent: the fields of the device reservation, and whether it currently occupies a slot of its device. */\nexport interface DispatchIntent extends QueuedIntent {\n readonly source: 'user' | 'bot' | 'routine';\n readonly deviceId: string;\n /** The intent is submitted or has attempt evidence, so it holds a device slot until its terminal. */\n readonly occupies: boolean;\n}\n/** A queued intent that never reached the SDK: the only rows that a priority rule may move. */\nexport function isUnsubmitted(row: Pick<QueuedIntent, 'phase' | 'attempts'>): boolean {\n return row.phase === 'queued' && row.attempts === 0;\n}\n/** The new sequence values of one Agent FIFO, and the counter value after them. */\nexport interface SequencePlan { assignments: Array<{ id: string; sequence: number }>; sequence: number }\n/**\n * Puts the queued, never-submitted intents of the user intent's Agent FIFO in priority order: every non-autonomous\n * intent keeps its arrival order, then the autonomous ones (the ids in the set) keep theirs.\n * Returns undefined when the user intent is not queued and unsubmitted, or the order already holds.\n * The new values are one block above every current sequence, so a submitted or in-flight intent is never moved.\n */\nexport function userFirst(rows: readonly QueuedIntent[], userIntentId: string, autonomous: ReadonlySet<string>,\n next: number): SequencePlan | undefined {\n const user = rows.find(row => row.id === userIntentId);\n if (!user || !isUnsubmitted(user)) return undefined;\n const queued = rows.filter(row => row.agent === user.agent && isUnsubmitted(row))\n .sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n const order = [...queued.filter(row => !autonomous.has(row.id)), ...queued.filter(row => autonomous.has(row.id))];\n if (order.every((row, index) => row.id === queued[index]!.id)) return undefined;\n let base = next;\n for (const row of rows) if (row.sequence > base) base = row.sequence;\n return { assignments: order.map((row, index) => ({ id: row.id, sequence: base + 1 + index })), sequence: base + order.length };\n}\n/**\n * Whether the Host may begin the intent on its device now. User-source work may use every slot; other work leaves\n * USER_RESERVED_SLOTS free (none when the limit is 1, which has no spare slot). The rows hold the open intents of every\n * Agent on the device; the intent itself is not counted, so the check gives the same answer before and after the intent\n * becomes in-flight.\n */\nexport function admitDeviceSlot(intent: DispatchIntent, rows: Iterable<DispatchIntent>, limit = DEVICE_CONCURRENCY): boolean {\n if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('A device concurrency limit is a positive safe integer');\n const reserved = Math.min(USER_RESERVED_SLOTS, limit - 1);\n let occupied = 0;\n for (const row of rows) if (row.id !== intent.id && row.deviceId === intent.deviceId && row.occupies) occupied++;\n return occupied < limit - (intent.source === 'user' ? 0 : reserved);\n}\n"]}
@@ -1,12 +0,0 @@
1
- import { json, SYSTEM_PROMPT, addTurn, refuseUnmigratedWouldDo, contextPack, activeBot, admitBotToolsets, DEFAULT_AUTONOMY, requireMain, refuseExternalTeam, refuseExternalRooms, archiveBot, NEW_ROOMS, roomFields, roomVisibility, handoffFrameBytes, handoffTurn, profileProjection, NEW_BOTS, TEAM_BOT_LIMIT, DEFAULT_CONTEXT_TURN_LIMIT } from './chunk-ZX6C5U2S.js';
2
- import { hash, canonical, occurrenceIntentKey, occurrenceOfIntentKey, concludeOccurrence, time, MIN_TOMBSTONE_RETENTION_MS } from '@byok-sdk/server/execution-core';
3
- import { nextRoutineOccurrence, checkRoutineSchedule, HostOfferSealedPayloadSchema, buildHandoffPack } from '@byok-sdk/protocol';
4
-
5
- function emptyTeam(){return {bots:{},rooms:{},rounds:{},seats:{},roots:{},notes:[],homeOperations:[]}}var OldCollaborationStateError=class extends Error{constructor(foundVersion,message){super(message);this.foundVersion=foundVersion;this.name="OldCollaborationStateError";}foundVersion;code="collaboration_state_unsupported_old"};function stateOf(application){if(application.collaboration===void 0)application.collaboration=json({version:3,team:emptyTeam(),turns:{},budgets:{},delegations:{},batches:{},units:{},replies:{},schemas:{},questions:{},cards:{},rejected:[],audit:[],sequence:0});const version=application.collaboration?.version;if(version===1)throw new OldCollaborationStateError(version,"Bot collaboration state version 1 is not supported. Bot routines moved to K4 routines. Restore a ledger backup made before this change, or start a new ledger.");if(version===2)throw new OldCollaborationStateError(version,"Bot collaboration state version 2 is not supported. Retention moved settled rows out of the state. Restore a ledger backup made before this change, or start a new ledger.");if(version!==3)throw new Error(`Unsupported Bot collaboration state version: ${String(version)}`);return application.collaboration}function verified(sender){return typeof sender?.id==="string"&&sender.id.length>0&&(sender.kind==="human"||sender.kind==="bot")}function isOwner(principal,owner){return principal.kind==="human"&&principal.id===owner}function classifyInbound(message,owner,self){const sender=message.sender;if(!verified(sender))return "unverified_sender";const selfBots=self&&Object.hasOwn(self,message.channel)?self[message.channel]:void 0;if(sender.kind==="bot"&&selfBots?.includes(sender.id))return "echo";const direct=message.conversation.kind==="direct";if(sender.kind==="bot")return direct?"bot_audit":"bot_background";if(!direct)return "room_input";return isOwner(sender,owner)?"owner_input":"not_owner"}function inboundKey(message){return hash([message.channel,message.conversation.id,message.platformMessageId])}var BOT_ROUTINE="bot-routine";var BOT_DREAM="bot-dream";var ROUTINE_WAIT_MS=3e5;var ROUTINE_LATE_AFTER_MS=6e4;var sealedOf=input=>"sealed"in input?input.sealed:void 0;var SealedRoutineVersionError=class extends Error{constructor(expected){super(`Seal the template for version ${expected}`);this.expected=expected;this.name="SealedRoutineVersionError";}expected;code="sealed_routine_version"};var SEALED_ROUTINE_CATEGORIES=["task-input"];var dreamTable=state=>state.dreams??={bots:{},open:{}};var routineCalendar=(definition2,after)=>{const schedule=definition2.rule;if(!schedule||typeof schedule!=="object"||Array.isArray(schedule)||schedule.tz!==definition2.timeZone){throw new Error("A routine rule is a RoutineSchedule in the definition time zone")}return nextRoutineOccurrence(schedule,after)};function fields(routine){const spec=routine.definition.hostOccurrence;return spec?.type===BOT_ROUTINE?spec.input:void 0}function definition(id,version,schedule,input){return {id,version,timeZone:schedule.tz,rule:json(schedule),waitMs:ROUTINE_WAIT_MS,lateAfterMs:ROUTINE_LATE_AFTER_MS,hostOccurrence:{type:BOT_ROUTINE,input:json(input)}}}function scheduled(schedule){const check=checkRoutineSchedule(schedule);if(!check.ok)throw new Error(`${check.code}: ${check.message}`);return schedule}function ownerRoutineUpdate(action){if(action.schedule===void 0&&action.prompt===void 0)throw new Error("An update must change schedule or prompt");if(action.schedule!==void 0)scheduled(action.schedule);return action}function botRoutines(routines){const views=[];for(const routine of routines){const input=fields(routine);if(!input)continue;const{id,version,rule}=routine.definition;views.push({id,owner:input.owner,current:version,pending:routine.pending?.version??null,lifecycle:routine.lifecycle,status:routine.status,definition:{version,schedule:rule,..."sealed"in input?{sealed:true}:{prompt:input.prompt},target:input.owner},...routine.calendarErrors?.length?{lastError:routine.calendarErrors.at(-1)}:{}});}return views}function createDefinition(routines,owner,taskId,index,action,authority){if(action.target!==void 0)throw new Error("An ordinary Bot cannot supply target");if(routines.filter(routine=>fields(routine)?.owner===owner&&routine.lifecycle!=="completed").length>=8)throw new Error("Routine limit is 8");return definition(hash([taskId,"create_routine",index]),1,action.schedule,{owner,authority,prompt:action.prompt})}function owned(routines,owner,id){const routine=routines.find(row=>row.definition.id===id);if(!routine||fields(routine)?.owner!==owner||routine.lifecycle==="completed")throw new Error("Routine is unavailable to this Bot");return routine}function endable(routines,id){const routine=routines.find(row=>row.definition.id===id);if(!routine||!fields(routine)||routine.lifecycle==="completed")throw new Error("No open Bot routine has this id");return routine}function updateDefinition(routines,owner,action){const routine=owned(routines,owner,action.routineId);const prior=routine.pending??routine.definition,input=prior.hostOccurrence.input;if("sealed"in input)throw new Error("A sealed routine changes only through resealRoutine");return definition(prior.id,prior.version+1,action.schedule??prior.rule,{...input,prompt:action.prompt??input.prompt})}function sealedRoutineInstruction(prompt){return `${SYSTEM_PROMPT}
6
-
7
- Request:
8
- ${prompt}`}function checkSealed(id,version,sealed,execution){if(canonical(sealed.sealing.categories)!==canonical(SEALED_ROUTINE_CATEGORIES))throw new Error("A sealed routine seals task-input only");const{agentRef}=execution.payload;if(canonical(sealed.agentRef)!==canonical({agentId:agentRef.agentId,profileRevision:agentRef.profileRevision})){throw new Error("The template is sealed for another Agent revision")}const{instruction:_,...plain}=execution.payload;const offer={...plain,sealing:sealed.sealing,sealed:sealed.template,routineRef:{routineId:id,definitionVersion:version,notAfter:sealed.notAfter}};if(!HostOfferSealedPayloadSchema.safeParse(offer).success)throw new Error("Supply a valid sealed template");if("ciphertextRef"in sealed.template)throw new Error("A sealed routine template must be inline")}function sealedDefinition(routines,owner,action,execution){if(action.definitionVersion!==1)throw new SealedRoutineVersionError(1);const next=definition(action.routineId,1,scheduled(action.schedule),{owner,authority:"owner",sealed:action.sealed});const existing=routines.find(routine=>routine.definition.id===action.routineId);if(existing){if(canonical(existing.definition)===canonical(next))return next;throw new Error("A routine already has this id")}if(routines.filter(routine=>fields(routine)?.owner===owner&&routine.lifecycle!=="completed").length>=8)throw new Error("Routine limit is 8");checkSealed(action.routineId,1,action.sealed,execution);return next}function resealDefinition(routines,owner,action,execution){const version=action.definitionVersion;const routine=owned(routines,owner,action.routineId);const prior=routine.pending??routine.definition,input=prior.hostOccurrence.input;if(!("sealed"in input))throw new Error("Only a sealed routine takes a new template");const next=definition(action.routineId,version,scheduled(action.schedule),{owner:input.owner,authority:input.authority,sealed:action.sealed});if([routine.definition,routine.pending].some(row=>canonical(row)===canonical(next)))return next;if(version!==prior.version+1)throw new SealedRoutineVersionError(prior.version+1);checkSealed(action.routineId,version,action.sealed,execution);return next}function sealedTemplate(routines,ref){for(const routine of routines){for(const row of [routine.definition,routine.pending]){if(row?.id===ref.routineId&&row.version===ref.definitionVersion){const input=fields({...routine,definition:row});return input&&sealedOf(input)}}}return void 0}function routineTurn(state,run){const input=run.input,id=occurrenceIntentKey(run.occurrenceKey);addTurn(state,{id,root:id,source:"routine",botId:input.owner,hop:0,authority:input.authority,..."sealed"in input?{request:"",sealedRoutine:{routineId:run.routineId,definitionVersion:run.definitionVersion}}:{request:input.prompt}});}function routineOccurrence(turn){const key=occurrenceOfIntentKey(turn.id);if(key===void 0)throw new Error(`Routine Turn ${turn.id} names no occurrence`);return key}function concludeRoutineTurn(s,turn){const key=routineOccurrence(turn),occurrence=s.occurrences[key];if(!occurrence?.hook||occurrence.intentId||occurrence.conclusion)return false;concludeOccurrence(s,key,"cancelled");return true}var RetentionRefused=class extends Error{constructor(code,root,reason,roundRoot){super(`Retention refused: ${reason}`);this.code=code;this.root=root;this.roundRoot=roundRoot;this.name="RetentionRefused";}code;root;roundRoot};var OPEN_DELIVERY=new Set(["staged","pending","sending","unknown"]);var values=rows=>Object.values(rows??{});var own=(rows,id)=>rows&&Object.hasOwn(rows,id)?rows[id]:void 0;function contextWindow(state,limit,handoff){const kept=new Set,byBot=new Map;const of=botId=>{let rows2=byBot.get(botId);if(!rows2)byBot.set(botId,rows2={turns:[],cards:[],questions:[]});return rows2};for(const turn of values(state.turns))if(turn.conclusion||turn.status==="processing")of(turn.botId).turns.push(turn);for(const card of values(state.cards)){const turn=own(state.turns,card.turnId);if(turn)of(turn.botId).cards.push(card.turnId);}for(const question of values(state.questions)){const turn=own(state.turns,question.turnId);if(turn)of(turn.botId).questions.push(question.turnId);}const rows=Math.min(limit,DEFAULT_CONTEXT_TURN_LIMIT);for(const bot of byBot.values()){const totalBytes=Math.max(handoff.totalBytes,handoff.recentBytes+handoff.earlyBytes+handoffFrameBytes(bot.turns.length));const pack=buildHandoffPack(bot.turns.map(handoffTurn),{...handoff,totalBytes});const oldest=pack.omittedTurns-(pack.recent.length?0:1);for(const turn of bot.turns.slice(oldest))kept.add(turn.id);for(const id of [...bot.cards.slice(-rows),...bot.questions.slice(-rows)])kept.add(id);}return kept}function members(state,root){const rounds=values(state.team.rounds).filter(round=>round.root===root);const seats=rounds.flatMap(round=>round.seats),roots=new Set([root,...seats]);const turns=values(state.turns).filter(turn=>roots.has(turn.root)),ids=new Set(turns.map(turn=>turn.id));const delegations=values(state.delegations).filter(d=>roots.has(d.root)).map(d=>d.id),chained=new Set(delegations);const replies=Object.entries(state.replies).filter(([,reply])=>ids.has(reply.turnId)).map(([taskId])=>taskId);const batch=own(state.inputBatches,root);return {turns,roots,delegations,replies,rounds:rounds.map(round=>round.id),seats,batches:values(state.batches).filter(row=>row.delegationIds.some(id=>chained.has(id))).map(row=>row.id),units:values(state.units).filter(unit=>roots.has(unit.root)).map(unit=>unit.id),cards:values(state.cards).filter(card=>ids.has(card.turnId)).map(card=>card.id),questions:values(state.questions).filter(question=>ids.has(question.turnId)).map(question=>question.id),...batch?{batch:batch.id}:{},inputs:batch?[...batch.inputIds]:[],inbounds:values(state.channel?.inbounds).filter(row=>row.root!==void 0&&roots.has(row.root)).map(row=>row.id),deliveries:values(state.channel?.deliveries).filter(row=>ids.has(row.turnId)).map(row=>row.id),wouldDo:values(state.wouldDo).filter(row=>ids.has(row.turnId)).map(row=>row.id)}}function protection(state,m,facts,window,now){for(const turn of m.turns){if(!turn.conclusion)return "A Turn of the root is not concluded";if(facts.hasIntent(turn.id)&&!turn.reported)return "A Turn of the root is not reported";if(turn.source==="routine"&&facts.occurrenceOpen(turn.id))return "A routine occurrence of the root is open"}for(const id of m.delegations){const d=state.delegations[id];if(!d.verdict||d.lateTurnId||d.cancel&&!d.cancel.delivered)return "A delegation of the root is unresolved"}if(m.batches.some(id=>!state.batches[id].released))return "A delegation batch of the root is not released";if(m.units.some(id=>state.units[id].state==="reserved"))return "A budget unit of the root is reserved";for(const id of m.cards){const card=state.cards[id];if(card.state==="pending"||card.state==="confirmed"&&card.result===void 0&&card.error===void 0||!card.decisionReported){return "A card of the root is not settled"}}if(m.questions.some(id=>state.questions[id].answer===void 0))return "A question of the root is unanswered";const batch=m.batch===void 0?void 0:state.inputBatches[m.batch];if(batch&&(batch.state==="open"||batch.revision!==2))return "The input batch of the root is not settled";if(m.rounds.some(id=>!state.team.rounds[id].closed))return "A round of the root is open";if(m.seats.some(id=>!state.team.seats[id]?.released))return "A room seat of the root is not released";if(m.deliveries.some(id=>OPEN_DELIVERY.has(state.channel.deliveries[id].state)))return "A delivery of the root is not settled";if(m.inbounds.some(id=>{const reply=state.channel.inbounds[id].reply;return !!reply?.token&&reply.expiresAt>now})){return "An inbound reply route of the root is live"}if(m.turns.some(turn=>window.has(turn.id)))return "The root is in the ContextPack window of its Bot";return void 0}function move(store,namespace,rows,ids){if(!rows)return 0;for(const id of ids){store.put(namespace,id,rows[id]);delete rows[id];}return ids.length}var bytes=state=>Buffer.byteLength(JSON.stringify(state));function retainRoots(state,input,limits,facts,store){const now=time(input.now),retention=time(input.retentionMs);if(retention<MIN_TOMBSTONE_RETENTION_MS)throw new Error("Retention must be at least seven days");const expiresAt=time(now+retention);if(!Array.isArray(input.acknowledgedRoots))throw new Error("Acknowledged roots must be an array");const roots=[...new Set(input.acknowledgedRoots)];if(roots.some(root=>typeof root!=="string"||!root))throw new Error("Invalid acknowledged root");if(!Number.isSafeInteger(limits.contextTurnLimit)||limits.contextTurnLimit<1)throw new Error("Invalid ContextPack limits");refuseUnmigratedWouldDo(state);const result={archivedRoots:0,alreadyArchivedRoots:0,archivedRows:0,archivedCommands:0,expiredCommands:store.expire("commands",now),beforeBytes:bytes(state),afterBytes:0};const window=contextWindow(state,limits.contextTurnLimit,limits.handoff),selected=[];for(const root of roots){const seat=own(state.team.seats,root);if(seat){const roundRoot=state.team.rounds[seat.roundId]?.root??seat.roundId;throw new RetentionRefused("seat_root",root,`The Turn is a room seat of root ${roundRoot}`,roundRoot)}const m=members(state,root);if(!m.turns.length&&!m.rounds.length&&m.batch===void 0&&!own(state.budgets,root)){if(!store.isRetired("root",root))throw new Error("Acknowledged root not found");result.alreadyArchivedRoots++;continue}const reason=protection(state,m,facts,window,now);if(reason)throw new RetentionRefused("protected_root",root,reason);selected.push(m);}for(const m of selected){const turnIds=m.turns.map(turn=>turn.id),consumed=new Set(turnIds);result.archivedRows+=move(store,"turns",state.turns,turnIds)+move(store,"schemas",state.schemas,turnIds.filter(id=>own(state.schemas,id)))+move(store,"budgets",state.budgets,[...m.roots].filter(id=>own(state.budgets,id)))+move(store,"delegations",state.delegations,m.delegations)+move(store,"batches",state.batches,m.batches)+move(store,"units",state.units,m.units)+move(store,"replies",state.replies,m.replies)+move(store,"cards",state.cards,m.cards)+move(store,"questions",state.questions,m.questions)+move(store,"inputs",state.inputs,m.inputs)+move(store,"inputBatches",state.inputBatches,m.batch===void 0?[]:[m.batch])+move(store,"rounds",state.team.rounds,m.rounds)+move(store,"seats",state.team.seats,m.seats)+move(store,"roots",state.team.roots,[...m.roots].filter(id=>own(state.team.roots,id)))+move(store,"inbounds",state.channel?.inbounds,m.inbounds)+move(store,"deliveries",state.channel?.deliveries,m.deliveries)+move(store,"wouldDo",state.wouldDo,m.wouldDo);const rejected=state.rejected.filter(row=>row.consumedBy!==void 0&&consumed.has(row.consumedBy));for(const row of rejected)store.put("rejected",hash(["rejected",row]),row);state.rejected=state.rejected.filter(row=>!rejected.includes(row));result.archivedRows+=rejected.length;for(const id of turnIds)store.retire("turn",id);for(const id of m.inputs)store.retire("input",id);for(const id of m.rounds)store.retire("round",id);for(const root of m.roots)store.retire("root",root);result.archivedRoots++;}result.archivedRows+=retainRoomMessages(state,store,limits.contextTurnLimit)+retainRootless(state,store);for(const[id,record]of Object.entries(state.commands??{})){if(record.root!==void 0&&!store.isRetired("root",record.root))continue;store.put("commands",id,record,expiresAt);delete state.commands[id];result.archivedCommands++;}result.afterBytes=bytes(state);return result}function retainRoomMessages(state,store,limit){let count=0;for(const room of values(state.team.rooms)){const window=room.messages.length-limit;const moved=room.messages.map((message,index)=>index<window&&!own(state.team.rounds,message.id)&&!own(state.team.seats,message.id));if(!moved.includes(true))continue;for(const[botId,from]of Object.entries(room.visibleFrom))room.visibleFrom[botId]=from-moved.slice(0,from).filter(Boolean).length;room.messages.forEach((message,index)=>{if(moved[index])store.put("roomMessages",message.id,message);});room.messages=room.messages.filter((_,index)=>!moved[index]);count+=moved.filter(Boolean).length;}return count}function retainRootless(state,store){let count=0;if(state.audit.length){store.put("audit",hash(["audit",state.revision??0,state.audit]),state.audit);count+=state.audit.length;state.audit=[];}const routes=state.channel?.pushRoutes??{},used=new Set(values(state.channel?.deliveries).map(row=>row.route.kind==="push"?row.route.pushRouteId:""));count+=move(store,"pushRoutes",routes,Object.keys(routes).filter(id=>routes[id].revokedAt!==void 0&&!used.has(id)));const newest=new Map;for(const op of state.team.homeOperations)if(op.status==="applied")newest.set(op.botId,Math.max(newest.get(op.botId)??0,op.sequence));const settled=state.team.homeOperations.filter(op=>op.status==="applied"?newest.get(op.botId)!==op.sequence:op.status==="failed"&&op.request.payload.agentRef.profileRevision!==state.team.bots[op.botId]?.revision);for(const op of settled)store.put("homeOperations",String(op.sequence),op);state.team.homeOperations=state.team.homeOperations.filter(op=>!settled.includes(op));return count+settled.length}function ledgerHistory(state){return {turns:Object.values(state.turns),cards:Object.values(state.cards),questions:Object.values(state.questions),rejected:state.rejected}}function contextPack2(state,turnLimit,currentTurnId,maxBytes,separateRequest,shared,fit,routines=[],handoff){return contextPack(ledgerHistory(state),turnLimit,currentTurnId,maxBytes,separateRequest,shared,fit,routines,handoff)}var TEAM_NOTE_LIMIT=20;function projectionRequestId(value){const digest=hash(value);return `${digest.slice(0,8)}-${digest.slice(8,12)}-4${digest.slice(13,16)}-a${digest.slice(17,20)}-${digest.slice(20,32)}`}function homeHead(team,sequence,busy){const op=team.homeOperations.find(row=>row.sequence===sequence);if(!op||op.status!=="pending")return void 0;const oldest=team.homeOperations.filter(row=>row.botId===op.botId&&row.status==="pending").reduce((a,b)=>a.sequence<=b.sequence?a:b);return oldest===op&&!busy(op.botId)?op:void 0}var homeRequests=op=>[op.request,...op.retries];function checkHomeReadback(request,read){if(!read)return void 0;const payload=request.payload;if(read.deviceId!==request.deviceId||!same(read.agentRef,payload.agentRef)||read.requestId!==payload.requestId||read.projectionHash!==payload.projectionHash)throw new Error("Home readback identity conflict");return read.status!=="pending"?read:void 0}function planHomeRetry(op,now){if(op.retryAt!==void 0&&now>=op.retryAt){const retry=structuredClone(op.request);retry.payload.requestId=projectionRequestId([op.request.payload.requestId,op.retries.length+1]);op.retries.push(retry);op.retryAt=now+Math.min(6e4,1e3*2**Math.min(op.retries.length,6));}return op.retries.at(-1)??op.request}function homeEnqueued(op,now){op.retryAt??=now+1e3;}function applyHomeTerminal(state,op,terminal,publish){if(terminal.status==="applied"||terminal.status==="idempotent"){op.status="applied";const bot=state.team.bots[op.botId];if(bot.revision===op.request.payload.agentRef.profileRevision)bot.readyRevision=bot.revision;}else {op.status="failed";op.error=terminal.status;publish(`persona-failed:${op.sequence}`,json({owner:op.botId,revision:op.request.payload.agentRef.profileRevision,reason:op.error,recoverable:true}));}}function failHomeFlush(op,error){op.error=String(error instanceof Error?error.message:error);}function projection(state,bot){const value=profileProjection(bot);const requestId=projectionRequestId([bot.id,bot.revision]);state.team.homeOperations.push({sequence:++state.sequence,botId:bot.id,status:"pending",retries:[],request:{deviceId:bot.execution.deviceId,payload:{requestId,agentRef:{agentId:bot.id,profileRevision:bot.revision},projectionHash:`sha256:${hash(value)}`,projection:value}}});}function createBot(state,taskId,action,models,readOnlyToolsets=[]){if(!NEW_BOTS.includes(action.localId))throw new Error("Unknown local Bot slot");if(Object.values(state.team.bots).filter(b=>!b.archived).length>=TEAM_BOT_LIMIT)throw new Error(`Team Bot limit is ${TEAM_BOT_LIMIT}`);const base=models[action.model];if(!base)throw new Error("Unavailable model");admitBotToolsets(base,readOnlyToolsets);const id=hash([taskId,action.localId]);const execution=structuredClone(base);execution.payload.agentRef={agentId:id,profileRevision:"1"};const bot={id,name:action.name,role:action.role,persona:action.persona,model:action.model,mainBot:false,archived:false,revision:"1",readyRevision:null,autonomy:DEFAULT_AUTONOMY,execution};state.team.bots[id]=bot;projection(state,bot);return bot}function updateBot(state,action,models,readOnlyToolsets=[]){const bot=activeBot(state.team,action.botId);const model=action.model??bot.model,base=models[model];if(base)admitBotToolsets(base,readOnlyToolsets);const revision=(BigInt(bot.revision)+1n).toString();if(BigInt(revision)>9223372036854775807n)throw new Error("Profile revision limit");const execution=structuredClone(base??bot.execution);execution.deviceId=bot.execution.deviceId;execution.payload.agentRef={agentId:bot.id,profileRevision:revision};Object.assign(bot,{name:action.name??bot.name,role:action.role??bot.role,persona:action.persona??bot.persona,model,revision,readyRevision:null,execution});projection(state,bot);}function writeSnapshotBot(state,row,models,readOnlyToolsets=[]){const bot=state.team.bots[row.id];if(state.team.external?.persona){writeHostProfile(state,bot,row,models,readOnlyToolsets);return}if(bot){if(bot.name!==row.name||bot.role!==row.role||bot.persona!==row.persona||bot.model!==row.model){updateBot(state,{botId:row.id,name:row.name,role:row.role,persona:row.persona,model:row.model},models,readOnlyToolsets);}return}const base=models[row.model];if(!base)throw new Error("Unavailable model");admitBotToolsets(base,readOnlyToolsets);const execution=structuredClone(base);execution.payload.agentRef={agentId:row.id,profileRevision:"1"};const created={id:row.id,name:row.name,role:row.role,persona:row.persona,model:row.model,mainBot:false,archived:false,revision:"1",readyRevision:null,autonomy:DEFAULT_AUTONOMY,execution};state.team.bots[row.id]=created;projection(state,created);}function applyModels(state,models,readOnlyToolsets){for(const model of Object.values(models))admitBotToolsets(model,readOnlyToolsets);for(const bot of Object.values(state.team.bots)){const base=models[bot.model];if(bot.archived||!base)continue;const execution=structuredClone(base);execution.deviceId=bot.execution.deviceId;execution.payload.agentRef={agentId:bot.id,profileRevision:bot.revision};bot.execution=execution;}}function writeHostProfile(state,bot,row,models,readOnlyToolsets){const revision=row.profileRevision;if(bot){const changed=bot.name!==row.name||bot.role!==row.role||bot.persona!==row.persona||bot.model!==row.model;if(BigInt(revision)<BigInt(bot.revision))throw new Error(`Profile revision ${revision} of ${row.id} is older than ${bot.revision}`);if(revision===bot.revision){if(changed)throw new Error(`A profile change of ${row.id} needs a newer profile revision`);return}}const base=models[row.model];if(base)admitBotToolsets(base,readOnlyToolsets);else if(!bot)throw new Error("Unavailable model");const execution=structuredClone(base??bot.execution);if(bot)execution.deviceId=bot.execution.deviceId;execution.payload.agentRef={agentId:row.id,profileRevision:revision};const fields2={name:row.name,role:row.role,persona:row.persona,model:row.model,revision,execution};if(bot)Object.assign(bot,fields2);else state.team.bots[row.id]={id:row.id,...fields2,mainBot:false,archived:false,readyRevision:null,autonomy:DEFAULT_AUTONOMY};}function applyManagement(state,actor,taskId,outcome,models,accept,readOnlyToolsets=[]){const team=state.team,local={};const managed=(kind,work)=>accept(kind,()=>{requireMain(team,actor);work();});const bots=(kind,work)=>managed(kind,()=>{refuseExternalTeam(team,kind);work();});const rooms=(kind,work)=>managed(kind,()=>{refuseExternalRooms(team,kind);work();});outcome.create_bot?.forEach(action=>bots("create_bot",()=>{local[action.localId]=createBot(state,taskId,action,models,readOnlyToolsets).id;}));outcome.update_bot?.forEach(action=>bots("update_bot",()=>updateBot(state,action,models,readOnlyToolsets)));outcome.delete_bot?.forEach(action=>bots("delete_bot",()=>archiveBot(team,action.botId)));const resolve=fields2=>({...fields2,...fields2.members?{members:fields2.members.map(id=>local[id]??id)}:{},...fields2.admin?{admin:local[fields2.admin]??fields2.admin}:{}});outcome.create_room?.forEach(action=>rooms("create_room",()=>{if(!NEW_ROOMS.includes(action.localId))throw new Error("Unknown local room slot");const id=hash([taskId,action.localId]);if(team.rooms[id])throw new Error("Duplicate local room slot");team.rooms[id]={id,...roomFields(team,resolve(action)),messages:[]};}));outcome.update_room?.forEach(action=>rooms("update_room",()=>{const room=team.rooms[action.roomId];if(!room)throw new Error("Room not found");const fields2={...room,...resolve(action)};if(!action.admin&&!fields2.members.includes(fields2.admin??""))delete fields2.admin;const next=roomFields(team,fields2);next.visibleFrom=roomVisibility(room,next.members);Object.assign(room,next);if(!next.admin)delete room.admin;}));if(outcome.team_note)managed("team_note",()=>{if(team.notes.length>=TEAM_NOTE_LIMIT)throw new Error("Team note limit is 20");team.notes.push({id:hash([taskId,"team_note"]),text:outcome.team_note.text});});}function same(value,other){return canonical(value)===canonical(other)}
9
-
10
- export { BOT_DREAM, BOT_ROUTINE, OldCollaborationStateError, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, RetentionRefused, SealedRoutineVersionError, TEAM_NOTE_LIMIT, applyHomeTerminal, applyManagement, applyModels, botRoutines, checkHomeReadback, classifyInbound, concludeRoutineTurn, contextPack2 as contextPack, createDefinition, dreamTable, endable, failHomeFlush, homeEnqueued, homeHead, homeRequests, inboundKey, isOwner, owned, ownerRoutineUpdate, planHomeRetry, projectionRequestId, resealDefinition, retainRoots, routineCalendar, routineOccurrence, routineTurn, sealedDefinition, sealedRoutineInstruction, sealedTemplate, stateOf, updateBot, updateDefinition, verified, writeSnapshotBot };
11
- //# sourceMappingURL=chunk-6Y2B2XCP.js.map
12
- //# sourceMappingURL=chunk-6Y2B2XCP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/team-model.ts","../src/model.ts","../src/channel.ts","../src/routines.ts","../src/retention.ts","../src/schema.ts","../src/team.ts"],"names":["definition","hash","rows","contextPack","fields","canonical"],"mappings":";;;;AAkCO,SAAS,WAAuB,CACrC,OAAO,CAAE,IAAA,CAAM,GAAI,KAAA,CAAO,GAAI,MAAA,CAAQ,GAAI,KAAA,CAAO,GAAI,KAAA,CAAO,GAAI,KAAA,CAAO,GAAI,cAAA,CAAgB,EAAG,CAChG,KCmCa,0BAAA,CAAN,cAAyC,KAAM,CAEpD,WAAA,CAAqB,aAAqB,OAAA,CAAiB,CAAE,MAAM,OAAO,CAAA,CAArD,+BAAwD,IAAA,CAAK,IAAA,CAAO,6BAA8B,CAAlG,YAAA,CADZ,IAAA,CAAO,qCAElB,EACO,SAAS,OAAA,CAAQ,YAAuD,CAC7E,GAAI,YAAY,aAAA,GAAkB,MAAA,CAAW,YAAY,aAAA,CAAgB,IAAA,CAAK,CAC5E,OAAA,CAAS,CAAA,CAAG,KAAM,SAAA,EAAU,CAAG,MAAO,EAAC,CAAG,QAAS,EAAC,CAAG,YAAa,EAAC,CAAG,QAAS,EAAC,CAAG,MAAO,EAAC,CAAG,QAAS,EAAC,CAAG,QAAS,EAAC,CAAG,UAAW,EAAC,CAAG,MAAO,EAAC,CACjJ,QAAA,CAAU,GAAI,KAAA,CAAO,GAAI,QAAA,CAAU,CACrC,CAAC,CAAA,CAED,MAAM,QAAW,WAAA,CAAY,aAAA,EAA2D,QAExF,GAAI,OAAA,GAA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,OAAA,CAAQ,SAAA,CAAW,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-6Y2B2XCP.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 * Version 3 (#798): retention moves settled rows out of this state into K4 application rows, so a version 2 writer\n * would read archived evidence as absent. Bot routines are K4 routines with the `bot-routine` occurrence hook.\n */\nexport interface CollaborationState extends AutonomyState {\n version: 3; 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/** A state version this build cannot adopt without a new ledger. */\nexport class OldCollaborationStateError extends Error {\n readonly code = 'collaboration_state_unsupported_old' as const;\n constructor(readonly foundVersion: 1 | 2, message: string) { super(message); this.name = 'OldCollaborationStateError'; }\n}\nexport function stateOf(application: Record<string, Json>): CollaborationState {\n if (application.collaboration === undefined) application.collaboration = json({\n version: 3, team: emptyTeam(), turns: {}, budgets: {}, delegations: {}, batches: {}, units: {}, replies: {}, schemas: {}, questions: {}, cards: {},\n rejected: [], audit: [], sequence: 0,\n });\n // SAFETY: Stored JSON may have any shape; optional access checks its version before it is treated as collaboration state.\n const version = (application.collaboration as unknown as { version?: unknown } | null)?.version;\n // No migration: version 1 kept Bot routines in this state, and K4 owns them now.\n if (version === 1) throw new OldCollaborationStateError(version, 'Bot collaboration state version 1 is not supported. Bot routines moved to K4 routines. '\n + 'Restore a ledger backup made before this change, or start a new ledger.');\n // No migration: a version 2 writer cannot read archived rows, so the two versions never share a ledger.\n if (version === 2) throw new OldCollaborationStateError(version, 'Bot collaboration state version 2 is not supported. Retention moved settled rows out of the state. '\n + 'Restore a ledger backup made before this change, or start a new ledger.');\n if (version !== 3) throw new Error(`Unsupported Bot collaboration state version: ${String(version)}`);\n // SAFETY: The stored version was checked above; version 3 is the collaboration 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.id, message.platformMessageId]);\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 { SYSTEM_PROMPT } from './rules/schema.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 * The member side of a sealed Bot routine: the whole Turn instruction it seals. It is the K8 Bot Turn frame with every\n * action and no ContextPack, because v1 has no plaintext field for Host content next to a sealed instruction. The Turn's\n * frozen outcome schema stays the authority on which actions the Bot may take.\n */\nexport function sealedRoutineInstruction(prompt: string): string { return `${SYSTEM_PROMPT}\\n\\nRequest:\\n${prompt}`; }\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';\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>, 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 => 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 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, 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,12 +0,0 @@
1
- import { inboundKey, dreamTable, stateOf, routineCalendar, BOT_DREAM, owned, updateDefinition, createDefinition, retainRoots, routineOccurrence, concludeRoutineTurn, ROUTINE_LATE_AFTER_MS } from './chunk-6Y2B2XCP.js';
2
- import { autonomousIntentIds, userFirst } from './chunk-33YA66U7.js';
3
- import { admitUserInput, addBatchTurns, addTurn, inactive, expireCards, observeDevices, settleDelegations, compactVeto, DEVICE_SWITCHING, DEVICE_NOT_BOUND, CommitConflict, commitCommand, refuseRetired, syncTurn, cardCallDue, settleCardCall, CONNECTOR_OUTCOME_UNKNOWN, json, retiredIdentity, handoffFrameBytes, handoffTurn, sealDueBatches, advanceRoomSeats, seatTurn } from './chunk-ZX6C5U2S.js';
4
- import { hash, time, occurrenceIntentKey, setLifecycle, routineCommands, promoteOccurrence, taskId, isOccurrenceIntentKey, routineWakeKey, agentKey, frozenInput, parseRoutineWakeKey, project, enqueue, concludeOccurrence, occurrenceOfIntentKey, validateJson, canonical as canonical$1, validateRetry } from '@byok-sdk/server/execution-core';
5
- import { checkRoutineSchedule, buildDreamInstruction, buildHandoffPack } from '@byok-sdk/protocol';
6
- import { canonical, hash as hash$1 } from '@byok-sdk/server/execution-core/canonical';
7
-
8
- function botFacts(state,botId){const bot=state.team.bots[botId];return bot&&{busy:Object.values(state.turns).some(turn=>turn.botId===botId&&!turn.conclusion&&turn.status!=="blocked"),configKey:[bot.revision,bot.model],archived:bot.archived}}function sealDueBatches2(state,policy,now){const bots={};for(const batch of Object.values(state.inputBatches??{})){const facts=batch.state==="open"?botFacts(state,batch.botId):void 0;if(facts)bots[batch.botId]=facts;}addBatchTurns(state,sealDueBatches(state,bots,policy,now));}function projectInputBatches(state,emit){for(const batch of Object.values(state.inputBatches??{})){const revision=batch.state==="open"?1:2;if((batch.revision??0)>=revision)continue;batch.revision=revision;emit(`input-batch:${batch.id}:${revision}`,json({owner:batch.botId,id:batch.id,revision,state:batch.state,sealReason:batch.sealReason,inputIds:batch.inputIds,openedAt:batch.openedAt,sealAt:batch.sealAt}));}}function admitUserInput2(state,input,policy,now){const admission=admitUserInput(state,input,{bot:botFacts(state,input.botId),turn:state.turns[input.id]},policy,now);addBatchTurns(state,admission.sealed);if(admission.turn){state.budgets[input.id]??={continuation:0,delegation:0};addTurn(state,{id:input.id,root:input.id,source:"user",request:input.request,botId:input.botId,hop:0,authority:input.authority});}return admission.id}var MAX_ATTEMPTS=3;var MAX_WAIT_MS=6e4;function deliveryId(taskId3,messageId,route,nonce){const key=route.kind==="reply"?["reply",route.inboundId]:["push",route.pushRouteId];return hash(nonce===void 0?[taskId3,messageId,key]:[taskId3,messageId,key,nonce])}function startDelivery(row,now){if(row.state!=="pending"||row.attempts>=MAX_ATTEMPTS||row.nextAttemptAt!==void 0&&now<row.nextAttemptAt)return false;row.state="sending";row.attempts++;delete row.nextAttemptAt;delete row.code;return true}function currentAttempt(row,attempt){return row.state==="sending"&&row.attempts===attempt}function retryDelivery(row,now,retryAfterMs){const wait=Math.max(retryAfterMs,1e3*2**(row.attempts-1));if(wait>MAX_WAIT_MS){row.state="rejected";return}row.state="pending";row.nextAttemptAt=now+wait;}function settleDelivery(row,attempt,result,now){if(!currentAttempt(row,attempt))return;if(result?.result==="accepted"&&typeof result.platformMessageId==="string"&&result.platformMessageId.length>0){row.state="accepted";row.platformMessageId=result.platformMessageId;delete row.code;return}if(result?.result!=="rejected"||typeof result.code!=="string"||result.code.length===0||typeof result.retryable!=="boolean"){unknownDelivery(row,attempt,"invalid_send_result");return}row.code=result.code;if(!result.retryable||row.attempts>=MAX_ATTEMPTS){row.state="rejected";return}const retryAfter=result.retryAfterMs===void 0?0:result.retryAfterMs;if(!Number.isFinite(retryAfter)||retryAfter<0){row.state="rejected";row.code="invalid_retry_after";return}retryDelivery(row,now,retryAfter);}function unknownDelivery(row,attempt,code){if(!currentAttempt(row,attempt))return;row.state="unknown";row.code=code;delete row.nextAttemptAt;}function recoverDelivery(row){if(row.state==="sending")unknownDelivery(row,row.attempts,"interrupted");}function readbackDelivery(row,attempt,result,now){if(row.state!=="unknown"||row.attempts!==attempt)return;if(result==="accepted"){row.state="accepted";delete row.code;}else if(result==="absent"){if(row.attempts>=MAX_ATTEMPTS){row.state="rejected";row.code="attempts_exhausted";}else {delete row.code;retryDelivery(row,now,0);}}}function acceptDeliveryEcho(row,platformMessageId){if(!platformMessageId)return false;if(row.state==="accepted"){if(row.platformMessageId&&row.platformMessageId!==platformMessageId)return false;row.platformMessageId=platformMessageId;return true}const waitingRetry=row.state==="pending"&&row.attempts>0;if(row.state!=="sending"&&row.state!=="unknown"&&!waitingRetry)return false;row.state="accepted";row.platformMessageId=platformMessageId;delete row.code;delete row.nextAttemptAt;return true}function channelState(state){return state.channel??={inbounds:{},pushRoutes:{},deliveries:{}}}var sameConversation=(a,b)=>a.kind===b.kind&&a.id===b.id;function turnConversation(state,turn){const seat=state.team.seats[turn.id];return seat?{kind:"group",id:state.team.rounds[seat.roundId].roomId}:{kind:"direct",id:turn.botId}}function turnRoot(state,turn){const seat=state.team.seats[turn.id];return seat?state.team.rounds[seat.roundId].root:turn.root}function rootOpen(ledger,state,root,conversation){return Object.values(state.turns).some(turn=>turnRoot(state,turn)===root&&sameConversation(turnConversation(state,turn),conversation)&&!turn.conclusion&&!ledger.intents[hash(turn.id)]?.conclusion&&!["blocked","failed","delivered"].includes(turn.status))||Object.values(state.inputBatches??{}).some(batch=>batch.id===root&&batch.state==="open")||Object.values(state.team.seats).some(seat=>state.team.rounds[seat.roundId]?.root===root&&!seat.released)}function rememberInbound(state,message,root){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)throw new Error("Invalid inbound identity");const route=message.replyRoute;if(route&&(route.kind!=="reply"||route.channel!==message.channel||route.inboundId!==message.platformMessageId||typeof route.token!=="string"||!route.token||!Number.isSafeInteger(route.expiresAt)||route.expiresAt<0)){throw new Error("Invalid reply route binding")}const channels=channelState(state),id=inboundKey(message);channels.inbounds[id]??={id,root,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,...route?{reply:{...route}}:{}};}function rememberFilteredInbound(state,message,code){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)return;const channels=channelState(state),id=inboundKey(message);channels.inbounds[id]??={id,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,filtered:code};}function enablePush(state,conversation,channel,target,owner,now){if(!conversation.id||!channel.trim()||!target.trim())throw new Error("Invalid push route");const channels=channelState(state);for(const route2 of Object.values(channels.pushRoutes)){if(sameConversation(route2.conversation,conversation)&&route2.revokedAt===void 0)revokePush(state,route2.id,now);}const id=hash(["push-route",conversation,channel,target,++state.sequence]);const route={kind:"push",id,conversation:{...conversation},channel,target,optedInBy:owner,optedInAt:now};channels.pushRoutes[id]=route;return route}function revokePush(state,id,now){const routes=state.channel?.pushRoutes;const route=routes&&Object.hasOwn(routes,id)?routes[id]:void 0;if(!route)throw new Error("Push route not found");route.revokedAt??=now;for(const delivery of Object.values(state.channel.deliveries)){if(delivery.state==="pending"&&delivery.route.kind==="push"&&delivery.route.pushRouteId===id)refuseRoute(state,delivery);}}function activePush(state,conversation){return Object.values(state.channel?.pushRoutes??{}).find(route=>route.revokedAt===void 0&&sameConversation(route.conversation,conversation))}function insert(state,input,staged=false){const id=deliveryId(input.taskId,input.messageId,input.route);return channelState(state).deliveries[id]??={id,...input,state:staged?"staged":"pending",attempts:0}}function queueDelivery(ledger,state,turn,taskId3,messageId,body,now,staged=false){const conversation=turnConversation(state,turn),root=turnRoot(state,turn);const inbound=Object.values(state.channel?.inbounds??{}).filter(row=>row.root===root&&sameConversation(row.conversation,conversation)).sort((a,b)=>b.sequence-a.sequence)[0];if(inbound?.reply?.token&&inbound.reply.expiresAt>now&&rootOpen(ledger,state,root,conversation)){return insert(state,{taskId:taskId3,turnId:turn.id,messageId,body,conversation,channel:inbound.reply.channel,route:{kind:"reply",inboundId:inbound.id}},staged)}const push=activePush(state,conversation);if(push)return insert(state,{taskId:taskId3,turnId:turn.id,messageId,body,conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}},staged);state.audit.push(`Delivery ${inbound?.reply?"reply_route_expired":"no_push_route"}: ${taskId3} ${messageId}`);return void 0}function promoteStaged(state,taskId3){const rows=Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="staged"&&row.taskId===taskId3);for(const row of rows)row.state="pending";return rows.map(row=>row.id)}function withholdStaged(ledger,state){for(const row of Object.values(state.channel?.deliveries??{})){if(row.state!=="staged"||!ledger.intents[hash(row.turnId)]?.conclusion)continue;row.state="rejected";row.code="outcome_not_applied";state.audit.push(`Delivery outcome_not_applied: ${row.taskId} ${row.messageId}`);}}function deliveryRoute(state,row,now){if(row.route.kind==="push"){const route2=state.channel?.pushRoutes[row.route.pushRouteId];return route2&&route2.revokedAt===void 0&&sameConversation(route2.conversation,row.conversation)?structuredClone(route2):void 0}const stored=state.channel?.inbounds[row.route.inboundId],route=stored?.reply;return route?.token&&route.expiresAt>now&&sameConversation(stored.conversation,row.conversation)?{...route,token:route.token}:void 0}function refuseRoute(state,row){if(row.state!=="pending")return;row.state="rejected";delete row.nextAttemptAt;row.code=row.route.kind==="reply"?"reply_route_expired":"push_route_revoked";state.audit.push(`Delivery ${row.code}: ${row.taskId} ${row.messageId}`);const push=row.route.kind==="reply"?activePush(state,row.conversation):void 0;if(push)insert(state,{taskId:row.taskId,turnId:row.turnId,messageId:row.messageId,body:row.body,conversation:row.conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}});}function cleanReplyTokens(ledger,state,now){for(const row of Object.values(state.channel?.inbounds??{})){if(!row.reply?.token||row.root===void 0)continue;const reserved=Object.values(state.channel.deliveries).some(delivery=>delivery.route.kind==="reply"&&delivery.route.inboundId===row.id&&["staged","pending","sending","unknown"].includes(delivery.state));if(now>=row.reply.expiresAt||!reserved&&!rootOpen(ledger,state,row.root,row.conversation))delete row.reply.token;}}function resendUnknown(state,id,now){const deliveries=state.channel?.deliveries;const old=deliveries&&Object.hasOwn(deliveries,id)?deliveries[id]:void 0;if(!old||old.state!=="unknown")throw new Error("Only an unknown delivery can be resent");const available=deliveryRoute(state,old,now)??activePush(state,old.conversation);if(!available)throw new Error("No active delivery route");const route=available.kind==="reply"?old.route:{kind:"push",pushRouteId:available.id};const nextId=deliveryId(old.taskId,old.messageId,route,String(++state.sequence));const row={id:nextId,taskId:old.taskId,turnId:old.turnId,messageId:old.messageId,body:old.body,conversation:{...old.conversation},channel:available.channel,route:{...route},state:"pending",attempts:0,resendOf:old.id};state.channel.deliveries[nextId]=row;return row}function echoCandidates(state,message){return Object.values(state.channel?.deliveries??{}).filter(row=>row.channel===message.channel&&sameConversation(row.conversation,message.conversation)&&row.state!=="rejected"&&(message.deliveryId!==void 0?row.id===message.deliveryId:row.platformMessageId===message.platformMessageId))}var ANSWERED=new Set(["succeeded","delivered"]);var FAILED=new Set(["failed","expired","declined","superseded","abandoned"]);function inboundDisposition(state,row){if(row.filtered!==void 0)return {id:row.id,disposition:"filtered",code:row.filtered};const root=row.root;if(root===void 0)return {id:row.id,disposition:"failed",turnId:row.id};const turn=Object.hasOwn(state.turns,root)?state.turns[root]:void 0;if(!turn){const batch=state.inputBatches&&Object.hasOwn(state.inputBatches,root)?state.inputBatches[root]:void 0;return batch?.state==="open"?{id:row.id,disposition:"coalesced",turnId:root}:{id:row.id,disposition:"failed",turnId:root}}const conclusions=[turn.conclusion,turn.status];if(conclusions.includes("cancelled"))return {id:row.id,disposition:"cancelled",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&ANSWERED.has(value)))return {id:row.id,disposition:"answered",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&FAILED.has(value)))return {id:row.id,disposition:"failed",turnId:turn.id};return {id:row.id,disposition:"coalesced",turnId:turn.id}}function inboundDispositions(state){return Object.values(state.channel?.inbounds??{}).filter(row=>row.filtered!==void 0||row.root!==void 0).sort((a,b)=>(a.sequence??0)-(b.sequence??0)||(a.id<b.id?-1:a.id>b.id?1:0)).map(row=>inboundDisposition(state,row))}var DEFAULT_DREAM_MAX_DURATION_MS=9e5;var DREAM_WAIT_MS=36e5;var DREAM_HOUR=3;var MIN_PACK_BYTES=1024;var scheduleIn=tz=>({minute:0,hour:DREAM_HOUR,tz});var localZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone;function dreamPolicy(options){if(options===false)return void 0;const check=checkRoutineSchedule(scheduleIn(options?.timeZone??localZone()));if(!check.ok)throw new Error(`dreaming: ${check.code}: ${check.message}`);const maxDurationMs=time(options?.maxDurationMs??DEFAULT_DREAM_MAX_DURATION_MS);if(maxDurationMs<1)throw new Error("dreaming: maxDurationMs must be positive");return {...options?.timeZone===void 0?{}:{timeZone:options.timeZone},models:[...options?.models??[]],maxDurationMs,nativeSessions:options?.nativeSessions??true}}var ownerOf=routine=>{const spec=routine.definition.hostOccurrence;return spec?.type===BOT_DREAM?spec.input.owner:void 0};function dreamOf(state,intentKey){const key=occurrenceOfIntentKey(intentKey);return key!==void 0&&state.dreams&&Object.hasOwn(state.dreams.open,key)?state.dreams.open[key]:void 0}function dreamIntentIds(state){return Object.keys(state.dreams?.open??{}).map(key=>hash(occurrenceIntentKey(key)))}function recordDream(state,run,now){dreamTable(state).open[run.occurrenceKey]={botId:run.input.owner,windowEnd:now};}function reconcileDreamRoutines(s,policy,models,now){const state=stateOf(s.application),rows=Object.values(s.routines).flatMap(row=>{const owner=ownerOf(row);return owner===void 0?[]:[{row,owner}]});const open=new Map;for(const{row,owner}of rows){if(row.lifecycle==="completed")continue;const bot=state.team.bots[owner];if(policy&&bot&&!bot.archived&&!open.has(owner))open.set(owner,row);else setLifecycle(s,row.definition.id,"completed",now,routineCalendar);}if(!policy)return;const commands=routineCommands(s,{now:()=>now,nextTime:routineCalendar,hostJobs:new Map,occurrenceHooks:new Map([[BOT_DREAM,recordDream]]),executionRoutines:"refuse"});const definition2=(id,version,owner,tz)=>({id,version,timeZone:tz,rule:json(scheduleIn(tz)),waitMs:DREAM_WAIT_MS,lateAfterMs:ROUTINE_LATE_AFTER_MS,hostOccurrence:{type:BOT_DREAM,input:{owner}}});for(const bot of Object.values(state.team.bots)){if(bot.archived)continue;const routine=open.get(bot.id),latest=routine?.pending??routine?.definition;if(latest){if(policy.timeZone!==void 0&&latest.timeZone!==policy.timeZone)commands.update(definition2(latest.id,latest.version+1,bot.id,policy.timeZone));}else if(models[bot.model]){commands.create(definition2(`dream:${bot.id}:${rows.filter(row=>row.owner===bot.id).length+1}`,1,bot.id,policy.timeZone??localZone()));dreamTable(state).bots[bot.id]??={since:now};}}}var completed=row=>row.status==="succeeded"||row.status==="delivered";function settledAfter(rows,mark){const after=rows.slice(rows.findIndex(row=>row.id===mark)+1);const open=after.findIndex(row=>row.status==="queued"||row.status==="processing");return open<0?after:after.slice(0,open)}function chooseModel(policy,models,botModel,deviceId){const name=policy.models.find(model=>Object.hasOwn(models,model)&&models[model].deviceId===deviceId);if(name!==void 0)return {template:name,fallback:false,base:models[name]};return models[botModel]?{template:botModel,fallback:true,base:void 0}:void 0}function dreamExecution(base,bot,instruction,maxDurationMs,window,nativeSessions){const{messageEgress:_egress,requiredToolsets:_toolsets,agentMemoryCommit:_commit,homeAccess:_home,preparation:_preparation,nativeSessions:_nativeSessions,...payload}=base.payload;return {deviceId:bot.deviceId,payload:{...payload,instruction,session:{mode:"fresh"},agentRef:bot.payload.agentRef,agentMemory:"none",limits:{...payload.limits,maxDurationMs},terminalProjection:{mode:"none"},...nativeSessions&&payload.harnessId===void 0?{nativeSessions:{...window,ifAdvertised:true}}:{}}}}function dreamInstruction(rows,window,maxDurationMs,instructionMaxBytes){const budget={maxDurationMs},frame={omittedTurns:0,earlier:[],recent:[]};const fixed=Buffer.byteLength(buildDreamInstruction({history:frame,window,budget}),"utf8")-Buffer.byteLength(JSON.stringify(frame),"utf8");const totalBytes=Math.max(instructionMaxBytes-fixed,handoffFrameBytes(rows.length));const history=buildHandoffPack(rows.map(handoffTurn),{recentBytes:Math.floor(totalBytes/4*3),earlyBytes:totalBytes,totalBytes});return buildDreamInstruction({history,window,budget})}function checkDreamInstruction(instructionMaxBytes){const room=instructionMaxBytes-Buffer.byteLength(dreamInstruction([],{fromMs:0,toMs:0},1,0),"utf8");if(room<MIN_PACK_BYTES)throw new Error(`instructionMaxBytes leaves a dream ${room} bytes of history, under ${MIN_PACK_BYTES}`)}function syncDreams(s,sync){const state=stateOf(s.application),dreams=state.dreams;if(!dreams)return false;let changed=false;const close=(key,run,outcome,reason)=>{const bot=dreams.bots[run.botId]??={since:run.windowEnd};bot.last={occurrenceKey:key,at:run.windowEnd,outcome,...reason===void 0?{}:{reason},...run.template===void 0?{}:{template:run.template,fallback:run.fallback}};if(outcome==="succeeded"){bot.since=run.windowEnd;if(run.throughTurn!==void 0)bot.throughTurn=run.throughTurn;}delete dreams.open[key];};const skip=(key,run,reason)=>{const occurrence=s.occurrences[key];if(occurrence&&!occurrence.conclusion){concludeOccurrence(s,key,reason==="superseded"?"superseded":"cancelled");changed=true;}close(key,run,reason==="superseded"?"superseded":"skipped",reason);};for(const[key,run]of Object.entries(dreams.open)){const bot=state.team.bots[run.botId],stopped=!bot?"archived":inactive(bot);if(run.template!==void 0){const intent=s.intents[hash(occurrenceIntentKey(key))];if(!intent)close(key,run,"failed","intent_compacted");else if(intent.conclusion)close(key,run,intent.conclusion);else if(stopped&&intent.phase!=="inflight"&&!intent.cancelReason)intent.cancelReason="cancelled";continue}if(s.occurrences[key]?.hook?.executionSuperseded){skip(key,run,"superseded");continue}if(!sync.policy){skip(key,run,"dreaming_off");continue}if(!bot||stopped){skip(key,run,stopped==="suspended"?"bot_suspended":"bot_archived");continue}if(sync.refused(bot.id)){skip(key,run,"device_unavailable");continue}if(bot.readyRevision!==bot.revision){skip(key,run,"bot_not_ready");continue}const record=dreams.bots[bot.id]??={since:run.windowEnd};const settled=settledAfter(Object.values(state.turns).filter(turn=>turn.botId===bot.id),record.throughTurn),fresh=settled.filter(completed);if(!fresh.length){skip(key,run,"no_new_turns");continue}const model=chooseModel(sync.policy,sync.models,bot.model,bot.execution.deviceId);if(!model){skip(key,run,"model_unavailable");continue}let rows=fresh;let throughTurn=settled.at(-1).id;if(sync.historyMode){const read=sync.history?.get(key);if(read===void 0)continue;if(read===null){skip(key,run,"history_unavailable");continue}const readSettled=settledAfter(read,record.throughTurn);rows=readSettled.filter(completed);if(!rows.length){skip(key,run,"no_new_turns");continue}throughTurn=readSettled.at(-1).id;}const window={fromMs:Math.min(record.since,run.windowEnd),toMs:run.windowEnd};const instruction=dreamInstruction(rows,window,sync.policy.maxDurationMs,sync.instructionMaxBytes);Object.assign(run,{template:model.template,fallback:model.fallback,throughTurn});promoteOccurrence(s,sync.tenant,key,dreamExecution(model.base??bot.execution,bot.execution,instruction,sync.policy.maxDurationMs,window,sync.policy.nativeSessions));changed=true;}return changed}function dreamReads(state){return Object.entries(state.dreams?.open??{}).filter(([,run])=>run.template===void 0).map(([key,run])=>({key,botId:run.botId,turnId:occurrenceIntentKey(key)}))}function roundTurn(state,round){const turns=round.seats.map(id=>state.turns[id]).filter(turn=>turn!==void 0);const conclusions=turns.map(turn=>turn.conclusion).filter(value=>value!==void 0);if(conclusions.includes("cancelled"))return {id:round.id,root:round.root,status:"failed",conclusion:"cancelled"};if(turns.some(turn=>turn.status==="succeeded"||turn.conclusion==="succeeded"||turn.conclusion==="delivered")){return {id:round.id,root:round.root,status:"succeeded",conclusion:"succeeded"}}const failed=new Set(["failed","expired","declined","superseded","abandoned"]);if(conclusions.some(conclusion=>failed.has(conclusion))||turns.some(turn=>turn.status==="failed")){return {id:round.id,root:round.root,status:"failed",conclusion:"failed"}}return {id:round.id,root:round.root,status:"queued"}}function inboundState(state){const turns={...state.turns};for(const round of Object.values(state.team.rounds))if(round.root===round.id)turns[round.id]??=roundTurn(state,round);return {channel:state.channel,turns,inputBatches:state.inputBatches}}function inboundDispositionsOf(state){if(Object.keys(state.channel?.inbounds??{}).length===0)return [];return inboundDispositions(inboundState(state))}function inboundProjection(disposition){const id=disposition.disposition==="filtered"?`inbound:${disposition.id}:filtered:${disposition.code}`:`inbound:${disposition.id}:${disposition.disposition}:${disposition.turnId}`;return {id,value:json(disposition)}}function projectInboundDispositions(state,emit){for(const disposition of inboundDispositionsOf(state)){const projection=inboundProjection(disposition);emit(projection.id,projection.value);}}var IntentOutcomeError=class extends Error{constructor(key,code,message){super(message);this.key=key;this.code=code;this.name="IntentOutcomeError";}key;code};function routeTerminal(state,key,handler){if(handler!==void 0)return {kind:"host_intent",handler};if(dreamOf(state,key))return {kind:"dream"};if(!Object.hasOwn(state.turns,key))throw new IntentOutcomeError(key,"unknown_intent","No Bot Turn or Host intent has this key");return {kind:"bot_turn"}}function runHostIntentHandler(key,name,run){if(run===void 0)throw new IntentOutcomeError(key,"handler_failed",`Unknown Host intent handler: ${name}`);let result;try{result=run();}catch(cause){throw new IntentOutcomeError(key,"handler_failed",cause instanceof Error?cause.message:String(cause))}if(result&&typeof result.then==="function"){void Promise.resolve(result).catch(()=>{});throw new IntentOutcomeError(key,"handler_failed","Host intent handler must be synchronous")}}function outcomeFailure(key,cause){return new IntentOutcomeError(key,"outcome_failed",cause instanceof Error?cause.message:String(cause))}function botOutcomePorts({taskId:taskId3,routines,manage,roomPosts}){return {manage,createRoutine:(turn,action,index)=>routines.create(createDefinition(routines.list(),turn.botId,taskId3,index,action,turn.authority??"bot")),updateRoutine:(turn,action)=>routines.update(updateDefinition(routines.list(),turn.botId,action)),cancelRoutine:(turn,action)=>routines.lifecycle(owned(routines.list(),turn.botId,action.routineId).definition.id,"completed"),roomPosts}}function syncHead(state,coalesce,now){sealDueBatches2(state,coalesce,now);expireCards(state,now);}function syncTail(state,conclusions,now,emit){if(conclusions!==void 0){withholdStaged(conclusions,state);cleanReplyTokens(conclusions,state,now);}projectInputBatches(state,emit);projectInboundDispositions(state,emit);}function intentFacts(s){const intent=key=>s.intents[hash(key)];return {intent:key=>{const row=intent(key);return row&&{taskId:row.taskId,...row.conclusion?{conclusion:row.conclusion}:{},...row.cancelReason?{cancelReason:row.cancelReason}:{}}},started:key=>{const row=intent(key);return !!row&&Array.from({length:row.generation+1},(_,g)=>s.executions[taskId(key,g)]).some(execution=>execution?.started||execution?.terminal!==void 0&&execution.terminal.envelope.type!=="task.decline")},declineCode:key=>{const row=intent(key),envelope=row&&s.executions[row.taskId]?.terminal?.envelope;return envelope?.type==="task.decline"?envelope.payload.code:void 0},offeredTo:key=>{const row=intent(key),execution=row&&s.executions[row.taskId];return row?.phase==="inflight"&&execution?.submission==="delivered"&&!execution.started&&execution.attempt?.status==="offered"?row.execution.deviceId:void 0}}}function intentRows(s){return {intent:key=>intentFacts({intents:s.intents,executions:{}}).intent(key)}}function observeDevices2(s,state,devices,emit){observeDevices(state,intentFacts(s),devices,emit);}function settleDelegations2(s,state,now,emit,timers){settleDelegations(state,intentFacts(s),now,emit,timers);}function turnIntentRetired(ledger,s,turn,now){return ledger.hasTombstone("intent",turn.id,now)||turn.source==="routine"&&!s.occurrences[routineOccurrence(turn)]}var botCompactVeto=(ledger,key)=>{const state=ledger.application.collaboration;if(state===void 0)return void 0;if(state.version!==3)return "Unsupported Bot collaboration state version";if(state.switchExport)return "switch_exported";return compactVeto(state,key,{hasIntent:turnId=>!!ledger.intents[hash(turnId)],receipt:taskId3=>ledger.executions[taskId3]?.messageReceipt})};var SWITCH_EXPORT_VERSION=1;var SWITCH_SECTIONS=["collaboration","archived","intents","routines","occurrences","outbox","tombstones"];function switchAttempts(intent){return intent===void 0||intent.submission==="reserved"?0:intent.generation+1}var SwitchExportError=class extends Error{constructor(reason,message){super(message);this.reason=reason;this.name="SwitchExportError";}reason;code="switch_export_refused"};var IDENTITY={archived:row=>[row.namespace,row.id],intents:row=>row.key,routines:row=>row.id,occurrences:row=>row.key,outbox:row=>[row.kind,row.occurrenceKey],tombstones:row=>[row.kind,row.digest]};var LISTS=SWITCH_SECTIONS.filter(section=>section!=="collaboration");var HEADER=["version","source","domain","devices","exportedAt"];var compare=(a,b)=>a<b?-1:a>b?1:0;function sealSwitchExport(content){checkContent(content,[...HEADER,...SWITCH_SECTIONS]);const sealed=structuredClone(content);sealed.devices.sort((a,b)=>compare(a.deviceId,b.deviceId));for(const section of LISTS){const key=IDENTITY[section];sealed[section].sort((a,b)=>compare(canonical(key(a)),canonical(key(b))));}checkOrder(sealed);return {...sealed,manifest:manifestOf(sealed)}}function verifySwitchExport(document){checkContent(document,[...HEADER,...SWITCH_SECTIONS,"manifest"]);ensure(keys(document.manifest,["counts","digests","digest"])&&keys(document.manifest.counts,SWITCH_SECTIONS)&&keys(document.manifest.digests,SWITCH_SECTIONS),"manifest keys");checkOrder(document);const manifest=manifestOf(document);if(canonical(manifest)!==canonical(document.manifest)){throw new SwitchExportError("manifest",`Switch export manifest does not match its content: ${document.manifest.digest} != ${manifest.digest}`)}return manifest}function manifestOf(content){const counts={},digests={};counts.collaboration=1;digests.collaboration=hash$1(JSON.stringify(content.collaboration));for(const section of LISTS){counts[section]=content[section].length;digests[section]=hash$1(content[section]);}const header={version:content.version,source:content.source,domain:content.domain,devices:content.devices,exportedAt:content.exportedAt};return {counts,digests,digest:hash$1({header,counts,digests})}}function checkOrder(content){for(let i=1;i<content.devices.length;i++){if(compare(content.devices[i-1].deviceId,content.devices[i].deviceId)>0){throw new SwitchExportError("unsorted",`Switch export devices are not in id order at ${content.devices[i].deviceId}`)}}for(const section of LISTS){const key=IDENTITY[section];const ids=content[section].map(row=>canonical(key(row)));for(let i=1;i<ids.length;i++){const order=compare(ids[i-1],ids[i]);if(order===0)throw new SwitchExportError("duplicate",`Switch export ${section} repeats ${ids[i]}`);if(order>0)throw new SwitchExportError("unsorted",`Switch export ${section} is not in identity order at ${ids[i]}`)}}}var object=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);var text=value=>typeof value==="string"&&value.length>0;var time2=value=>Number.isSafeInteger(value)&&value>=0;var digestText=value=>typeof value==="string"&&/^[0-9a-f]{64}$/.test(value);var CONCLUSIONS={succeeded:true,failed:true,declined:true,cancelled:true,expired:true,superseded:true};var conclusionText=value=>typeof value==="string"&&Object.hasOwn(CONCLUSIONS,value);var optional=(value,check)=>value===void 0||check(value);var oneOf=values=>value=>typeof value==="string"&&values.includes(value);function keys(value,required,allowed=[]){return object(value)&&required.every(key=>Object.hasOwn(value,key))&&Object.keys(value).every(key=>required.includes(key)||allowed.includes(key))}var receiptShape=value=>keys(value,["messageId","contentHash"])&&text(value.messageId)&&text(value.contentHash);function json2(value){try{validateJson(value);return true}catch{return false}}function invalid(message){throw new SwitchExportError("invalid",`Invalid switch export: ${message}`)}function ensure(ok,message){if(!ok)invalid(message);}function reference(ok,message){if(!ok)throw new SwitchExportError("reference",`Switch export ${message}`)}function definition(value,id){const runs=["execution","hostJob","hostOccurrence"];if(!keys(value,["id","version","timeZone","rule","waitMs","lateAfterMs"],["retry","endAt",...runs]))return false;const present=runs.filter(run2=>value[run2]!==void 0);if(present.length!==1)return false;const run=value[present[0]];return value.id===id&&time2(value.version)&&value.version>=1&&text(value.timeZone)&&time2(value.waitMs)&&time2(value.lateAfterMs)&&optional(value.endAt,time2)&&optional(value.retry,retryPolicy)&&(present[0]==="execution"?object(run):keys(run,["type","input"])&&text(run.type))}function routineRecord(row){return keys(row,["id","ordinal","definition","lifecycle","status","nextAt"],["pending","calendarErrors","scheduleRetryAt","scheduleRetryCount","lastError"])&&text(row.id)&&time2(row.ordinal)&&definition(row.definition,row.id)&&optional(row.pending,pending=>definition(pending,row.id))&&oneOf(["active","paused","completed"])(row.lifecycle)&&oneOf(["ok","schedule_retrying","no_occurrence_within_horizon","calendar_error"])(row.status)&&(row.nextAt===null||time2(row.nextAt))&&optional(row.calendarErrors,errors=>Array.isArray(errors)&&errors.length>0&&errors.every(error=>keys(error,["at","message"],["wakeKey"])&&time2(error.at)&&typeof error.message==="string"&&optional(error.wakeKey,text)))&&optional(row.scheduleRetryAt,time2)&&optional(row.scheduleRetryCount,count=>time2(count)&&count>=1)&&optional(row.lastError,error=>keys(error,["code","message"])&&text(error.code)&&typeof error.message==="string")}function occurrenceRecord(row){return keys(row,["key","ordinal","routineId","definitionVersion","trigger","recordedAt","nextAt","job","executionSuperseded"],["conclusion","slotReplayCount"])&&text(row.key)&&time2(row.ordinal)&&text(row.routineId)&&time2(row.definitionVersion)&&row.definitionVersion>=1&&keys(row.trigger,["kind","plannedAt"])&&oneOf(["scheduled","catch_up"])(row.trigger.kind)&&time2(row.trigger.plannedAt)&&time2(row.recordedAt)&&(row.nextAt===null||time2(row.nextAt))&&(row.job===null||keys(row.job,["attempts"],["summary"])&&time2(row.job.attempts))&&typeof row.executionSuperseded==="boolean"&&optional(row.conclusion,conclusionText)&&optional(row.slotReplayCount,count=>time2(count)&&count>=1)}function retryPolicy(retry){if(!keys(retry,["maxAttempts","delaysMs","retryFailures"])||!Array.isArray(retry.delaysMs))return false;try{validateRetry(retry);return true}catch{return false}}var executionShape=row=>typeof row.started==="boolean"&&optional(row.attempt,object)&&optional(row.terminal,object)&&optional(row.messageReceipt,receiptShape);function intentRecord(row){return keys(row,["key","source","ordinal","taskId","generation","input","waitUntil","retry","submission","started","earlierExecutions","conclusion"],["handler","attempt","terminal","messageReceipt","preparationError","memoryBlocked","cancelReason","retryUntil"])&&text(row.key)&&oneOf(["user","bot","routine"])(row.source)&&optional(row.handler,text)&&time2(row.ordinal)&&digestText(row.taskId)&&time2(row.generation)&&time2(row.waitUntil)&&keys(row.input,["taskId","deviceId","payload"],["agentMessageContext"])&&text(row.input.deviceId)&&object(row.input.payload)&&object(row.input.payload.agentRef)&&text(row.input.payload.agentRef.agentId)&&retryPolicy(row.retry)&&row.generation<row.retry.maxAttempts&&oneOf(["reserved","uncertain","delivered"])(row.submission)&&executionShape(row)&&(row.submission!=="reserved"||row.generation===0&&!row.started&&row.attempt===void 0&&row.terminal===void 0&&row.messageReceipt===void 0)&&Array.isArray(row.earlierExecutions)&&row.earlierExecutions.length===row.generation&&row.earlierExecutions.every(entry=>keys(entry,["submission","started","attempt","terminal"],["messageReceipt"])&&oneOf(["uncertain","delivered"])(entry.submission)&&executionShape(entry))&&optional(row.preparationError,text)&&optional(row.memoryBlocked,blocked=>keys(blocked,["resume","reason"])&&oneOf(["queued","backoff"])(blocked.resume)&&typeof blocked.reason==="string")&&optional(row.cancelReason,oneOf(["expired","cancelled"]))&&optional(row.retryUntil,time2)&&optional(row.conclusion,conclusionText)}function checkContent(content,top){ensure(keys(content,top),"document keys");ensure(json2(content),"not JSON");ensure(content.version===SWITCH_EXPORT_VERSION,`version ${String(content.version)}`);ensure(content.source==="L"||content.source==="H","source");ensure(text(content.domain),"domain");ensure(time2(content.exportedAt),"exportedAt");ensure(Array.isArray(content.devices)&&content.devices.length>0,"devices");for(const device of content.devices){ensure(keys(device,["deviceId","frozenRevision"])&&text(device.deviceId)&&time2(device.frozenRevision)&&device.frozenRevision>=1,"device");}if(new Set(content.devices.map(device=>device.deviceId)).size!==content.devices.length){throw new SwitchExportError("duplicate","Switch export lists a device twice")}for(const section of LISTS)ensure(Array.isArray(content[section]),section);checkCollaboration(content);for(const row of content.archived){ensure(keys(row,["namespace","id","body"],["expiresAt"])&&text(row.namespace)&&text(row.id)&&optional(row.expiresAt,time2),"archived row");}for(const row of content.intents){if(object(row)&&row.conclusion===void 0)throw new SwitchExportError("open_work",`Switch export has an open intent: ${String(row.key)}`);ensure(intentRecord(row),"intent");}for(const row of content.routines){ensure(routineRecord(row),"routine");if(row.definition.execution!==void 0||row.pending?.execution!==void 0){throw new SwitchExportError("execution_routine",`Switch export has an execution routine, which K8 domains do not run: ${row.id}`)}}for(const row of content.occurrences)ensure(occurrenceRecord(row),"occurrence");for(const row of content.outbox){if(object(row)&&row.kind==="projection"){throw new SwitchExportError("projection_pending",`Switch export has a pending projection; flush it first: ${String(row.id)}`)}ensure(keys(row,["kind","occurrenceKey"])&&row.kind==="host-job"&&text(row.occurrenceKey),"outbox row");}for(const row of content.tombstones){ensure(keys(row,["kind","digest"],["expiresAt"])&&oneOf(["intent","row","slot","application"])(row.kind)&&digestText(row.digest)&&optional(row.expiresAt,time2),"tombstone");}checkReferences(content);}function checkReferences(content){for(const section of ["intents","routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal);if(new Set(ordinals).size!==ordinals.length)throw new SwitchExportError("duplicate",`Switch export ${section} repeats an ordinal`)}for(const section of ["routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal).sort((a,b)=>a-b);ensure(ordinals.every((ordinal,position)=>ordinal===position),`${section} ordinals are not their positions 0 to ${ordinals.length-1}`);}const occurrences=new Map(content.occurrences.map(row=>[row.key,row]));const occurrenceOfIntent=new Map(content.occurrences.map(row=>[occurrenceIntentKey(row.key),row.key]));const promoted=new Set;for(const row of content.intents){reference(row.taskId===taskId(row.key,row.generation),`intent ${row.key} has task id ${row.taskId}, not that of generation ${row.generation}`);ensure(row.input.taskId===row.taskId,`intent ${row.key} input is not frozen for its task id`);if(isOccurrenceIntentKey(row.key)){const key=occurrenceOfIntent.get(row.key);reference(key!==void 0,`intent ${row.key} names no occurrence of the export`);promoted.add(key);}}const routineById=new Map(content.routines.map(row=>[row.id,row]));const pendingJobs=new Set(content.outbox.map(row=>row.occurrenceKey));const slots=new Set;for(const row of content.occurrences){const routine=routineById.get(row.routineId);reference(routine!==void 0,`occurrence ${row.key} names no routine of the export: ${row.routineId}`);reference(row.key===hash$1([row.routineId,row.definitionVersion,row.trigger]),`occurrence ${row.key} is not the key of its routine slot and trigger`);const slot=routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt);if(slots.has(slot))throw new SwitchExportError("duplicate",`Switch export has two occurrences of the slot of ${row.key}`);slots.add(slot);ensure(!(promoted.has(row.key)&&row.conclusion!==void 0),`occurrence ${row.key} has an intent and its own conclusion`);if(routine.definition.hostJob){ensure(row.job!==null&&!promoted.has(row.key)&&pendingJobs.has(row.key)===(row.conclusion===void 0),`Host job occurrence ${row.key} is not promoted, and has a pending job exactly when it is open`);}else ensure(row.job===null,`occurrence ${row.key} has a Host job, but its routine runs a hook`);}const archivedReplies=new Map(content.archived.filter(row=>row.namespace==="replies").map(row=>[row.id,row.body]));const replyOf=taskId3=>content.collaboration.replies[taskId3]??archivedReplies.get(taskId3);for(const row of content.intents){const receipts=[...row.earlierExecutions.map(entry=>entry.messageReceipt),row.messageReceipt];for(let generation=0;generation<=row.generation;generation++){const reply=replyOf(taskId(row.key,generation)),receipt=receipts[generation];const same2=receipt===void 0?reply===void 0:object(reply)&&reply.messageId===receipt.messageId&&reply.contentHash===receipt.contentHash;if(!same2){throw new SwitchExportError("receipt_mismatch",`Switch export intent ${row.key} generation ${generation} has a message receipt that differs from its K8 reply`)}}}for(const row of content.outbox){reference(occurrences.get(row.occurrenceKey)?.job!=null,`Host job ${row.occurrenceKey} names no Host job occurrence`);}}var COLLABORATION_KEYS=["version","team","turns","budgets","delegations","batches","units","replies","schemas","questions","cards","rejected","audit","sequence"];var COLLABORATION_OPTIONAL=["inputs","inputBatches","channel","revision","commands","cardCalls","wouldDo","dreams"];function checkCollaboration(content){const state=content.collaboration;ensure(object(state),"collaboration state");if(state.topology!==void 0)throw new SwitchExportError("owner_record","Switch export carries the source owner records (topology)");if(state.hostIntents!==void 0)throw new SwitchExportError("owner_record","Switch export carries L hostIntents; each intent carries its handler");if(state.switchExport!==void 0||state.switchImport!==void 0){throw new SwitchExportError("owner_record","Switch export carries an L switch record (switchExport or switchImport)")}ensure(keys(state,COLLABORATION_KEYS,COLLABORATION_OPTIONAL)&&state.version===3&&object(state.team)&&object(state.team.bots)&&Array.isArray(state.team.homeOperations)&&object(state.turns)&&optional(state.inputBatches,object)&&optional(state.cardCalls,object)&&optional(state.wouldDo,object),"collaboration state");for(const bot of Object.values(state.team.bots))ensure(object(bot)&&object(bot.execution)&&text(bot.execution.deviceId),"bot");for(const turn of Object.values(state.turns)){ensure(object(turn),"turn");if(turn.source==="routine")ensure(typeof turn.id==="string"&&isOccurrenceIntentKey(turn.id),`routine Turn ${String(turn.id)} names no occurrence`);}for(const batch of Object.values(state.inputBatches??{}))ensure(object(batch),"input batch");for(const row of Object.values(state.wouldDo??{}))ensure(object(row)&&text(row.turnId),"would-do row without turnId");for(const op of state.team.homeOperations)ensure(object(op),"home operation");const devices=new Set(content.devices.map(device=>device.deviceId));for(const bot of Object.values(state.team.bots)){if(!bot.archived&&!devices.has(bot.execution.deviceId)){throw new SwitchExportError("device_missing",`Bot ${bot.id} runs on device ${bot.execution.deviceId}, which the export does not move`)}}for(const turn of Object.values(state.turns)){if(!turn.conclusion)throw new SwitchExportError("open_work",`Switch export has an open Turn: ${turn.id}`)}for(const batch of Object.values(state.inputBatches??{})){if(batch.state==="open")throw new SwitchExportError("open_work",`Switch export has an open input batch: ${batch.id}`)}for(const op of state.team.homeOperations){if(op.status==="pending"&&op.sent===true){throw new SwitchExportError("home_sent",`Switch export has a pending Agent home write that may have been sent: ${op.sequence}`)}}if(Object.keys(state.cardCalls??{}).length)throw new SwitchExportError("card_call","Switch export has a card call in flight")}var SwitchExportedError=class extends Error{constructor(digest){super(`The domain was exported for a switch (${digest}); it writes nothing until the switch is aborted`);this.digest=digest;this.name="SwitchExportedError";}digest;code="switch_exported"};var SwitchImportedError=class extends Error{constructor(digest){super(`The domain holds the switch import ${digest}; commit it or discard it first`);this.digest=digest;this.name="SwitchImportedError";}digest;code="switch_imported"};var DeviceSwitchingError=class extends Error{constructor(deviceId,target,revision){super(`Device ${deviceId} is switching to ${target}`);this.deviceId=deviceId;this.target=target;this.revision=revision;this.name="DeviceSwitchingError";}deviceId;target;revision;code=DEVICE_SWITCHING};function exportMarkOf(value){const mark=value;const valid=typeof value==="object"&&value!==null&&Object.keys(value).sort().join(",")==="devices,digest,exportedAt"&&typeof mark.digest==="string"&&Number.isSafeInteger(mark.exportedAt)&&Array.isArray(mark.devices)&&mark.devices.length>0&&mark.devices.every(device=>!!device&&Object.keys(device).sort().join(",")==="deviceId,frozenRevision"&&typeof device.deviceId==="string"&&Number.isSafeInteger(device.frozenRevision)&&device.frozenRevision>0);if(!valid)throw new Error("Invalid switch export record");return mark}var DeviceModeError=class extends Error{constructor(deviceId,mode,revision){super(`Device ${deviceId} is owned by ${mode}`);this.deviceId=deviceId;this.mode=mode;this.revision=revision;this.name="DeviceModeError";}deviceId;mode;revision;code=DEVICE_NOT_BOUND;reason="mode"};function recordOf(state,deviceId){return state.topology&&Object.hasOwn(state.topology,deviceId)?state.topology[deviceId]:void 0}function deviceTopology(state,deviceId){const row=recordOf(state,deviceId);return row?{...row}:{mode:"L",revision:0}}function deviceRefusal(state,deviceId){const row=recordOf(state,deviceId);return row?.mode==="H"?"mode":row?.switching?"switching":void 0}function botDeviceRefusal(state,botId){const bot=state.team.bots[botId];return bot&&deviceRefusal(state,bot.execution.deviceId)}function admitDevice(state,deviceId){const row=recordOf(state,deviceId);if(row?.mode==="H")throw new DeviceModeError(deviceId,row.mode,row.revision);if(row?.switching)throw new DeviceSwitchingError(deviceId,row.switching,row.revision)}function admitBot(state,botId){const bot=state.team.bots[botId];if(bot)admitDevice(state,bot.execution.deviceId);}function switchWork(s,deviceId){const state=stateOf(s.application),onDevice=botId=>state.team.bots[botId]?.execution.deviceId===deviceId;return {intents:Object.values(s.intents).filter(intent=>!intent.conclusion&&intent.execution.deviceId===deviceId).map(intent=>intent.key),turns:Object.values(state.turns).filter(turn=>!turn.conclusion&&!s.intents[hash(turn.id)]&&onDevice(turn.botId)).map(turn=>turn.id),batches:Object.values(state.inputBatches??{}).filter(batch=>batch.state==="open"&&onDevice(batch.botId)).map(batch=>batch.id),homeOperations:state.team.homeOperations.filter(op=>op.status==="pending"&&homeSent(op)&&op.request.deviceId===deviceId).map(op=>op.sequence)}}function homeSent(op){return op.sent===true}function switchDrained(work){return !work.intents.length&&!work.turns.length&&!work.batches.length&&!work.homeOperations.length}function switchStep(s,deviceId,expectedRevision,step){const state=stateOf(s.application),row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(step==="freeze"?row.switching:!row.switching)throw new Error(`Device ${deviceId} is ${row.switching?"already":"not"} switching`);if(step==="commit"&&!switchDrained(switchWork(s,deviceId)))throw new Error(`Device ${deviceId} still has open work`);const next=step==="freeze"?{mode:"L",revision:row.revision+1,switching:"H"}:{mode:step==="commit"?"H":"L",revision:row.revision+1};Object.defineProperty(state.topology??={},deviceId,{value:next,enumerable:true,writable:true,configurable:true});return {...next}}function checkTopology(state){for(const[deviceId,row]of Object.entries(state.topology??{})){const keys2=Object.keys(row??{}).sort().join(",");const valid=!!row&&(row.mode==="L"||row.mode==="H")&&Number.isSafeInteger(row.revision)&&row.revision>0&&(row.switching===void 0?keys2==="mode,revision":row.switching==="H"&&row.mode==="L"&&keys2==="mode,revision,switching");if(!valid)throw new Error(`Invalid topology record for device ${deviceId}`)}}function refuseExported(state){if(state.switchExport)throw new SwitchExportedError(state.switchExport.digest)}function refuseImported(state){if(state.switchImport)throw new SwitchImportedError(state.switchImport.digest)}function checkSwitchRecords(state){refuseImported(state);if(state.switchExport!==void 0)exportMarkOf(state.switchExport);}var INTENT_KEYS=["id","key","source","execution","waitUntil","retry","agent","sequence","phase","generation","taskId","notBefore","attempts"];var INTENT_OPTIONAL=["memoryBlocked","preparationError","occurrence","retryUntil","cancelReason","conclusion"];var EXECUTION_KEYS=["input","submission","started"];var EXECUTION_OPTIONAL=["messageReceipt","attempt","terminal"];var ROUTINE_KEYS=["definition","lifecycle","status","next"];var ROUTINE_OPTIONAL=["pending","scheduleRetryAt","scheduleRetryCount","lastError","calendarErrors"];var OCCURRENCE_KEYS=["key","routineId","definitionVersion","trigger","wakeKey","recordedAt","nextAt","attempts"];var OCCURRENCE_OPTIONAL=["intentId","job","hook","conclusion","slotReplayCount"];var LEDGER_KEYS=["version","sequence","scanSequence","intents","executions","routines","occurrences","slots","outbox","applied","application","scanWake"];var LEDGER_OPTIONAL=["memory","ignoredWakes"];function refuse(reason,message){throw new SwitchExportError(reason,`Switch export source: ${message}`)}function derived(ok,message){if(!ok)refuse("reference",message);}function exact(value,required,optional2,what){const own=Object.keys(value);if(!required.every(key=>own.includes(key))||!own.every(key=>required.includes(key)||optional2.includes(key))){refuse("invalid",`${what} has keys ${own.join(", ")}`);}}var same=(a,b)=>canonical$1(a)===canonical$1(b);function defined(source){return Object.fromEntries(Object.entries(source).filter(([,value])=>value!==void 0))}function liveState(state){const live=structuredClone(state);delete live.topology;delete live.hostIntents;delete live.switchExport;delete live.switchImport;return live}function switchContent(dump,tenant,header){const s=dump.body;exact(s,LEDGER_KEYS,LEDGER_OPTIONAL,"The K4 ledger");if(s.memory&&Object.values(s.memory).some(rows=>rows&&Object.keys(rows).length)||dump.memoryTombstones.length){refuse("invalid","the domain has Agent memory state, which a switch does not move");}exact(s.application,["collaboration"],[],"The K4 application state");const state=stateOf(s.application);const handlers=state.hostIntents??{};const intents=[],tasks=new Set,succeeded=new Set;for(const[id,intent]of Object.entries(s.intents)){exact(intent,INTENT_KEYS,INTENT_OPTIONAL,`Intent ${intent.key}`);if(!intent.conclusion||intent.phase!=="settled")refuse("open_work",`intent ${intent.key} is open`);derived(id===hash(intent.key),`intent ${intent.key} is stored under ${id}`);derived(intent.agent===agentKey(tenant,intent.execution),`intent ${intent.key} queues under another tenant`);derived(intent.taskId===taskId(intent.key,intent.generation),`intent ${intent.key} task id is not that of its generation`);derived(isOccurrenceIntentKey(intent.key)?intent.occurrence!==void 0&&intent.key===occurrenceIntentKey(intent.occurrence):intent.occurrence===void 0,`intent ${intent.key} names occurrence ${String(intent.occurrence)}`);const current=s.executions[intent.taskId];if(!current)refuse("reference",`intent ${intent.key} has no execution`);exact(current,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${intent.taskId}`);derived(same(current.input,frozenInput(intent.execution,intent.taskId)),`intent ${intent.key} execution differs from its frozen input`);derived(intent.attempts===switchAttempts({submission:current.submission,generation:intent.generation}),`intent ${intent.key} attempts`);tasks.add(intent.taskId);const earlierExecutions=[];for(let generation=0;generation<intent.generation;generation++){const task=taskId(intent.key,generation),earlier=s.executions[task];if(!earlier)refuse("reference",`intent ${intent.key} has no execution of generation ${generation}`);exact(earlier,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${task}`);derived(same(earlier.input,frozenInput(intent.execution,task)),`intent ${intent.key} generation ${generation} input differs`);if(earlier.submission==="reserved")refuse("invalid",`intent ${intent.key} generation ${generation} was never begun`);earlierExecutions.push(defined({submission:earlier.submission,started:earlier.started,attempt:earlier.attempt,terminal:earlier.terminal,messageReceipt:earlier.messageReceipt}));tasks.add(task);}if(intent.conclusion==="succeeded")succeeded.add(intent.taskId);const handler=Object.hasOwn(handlers,intent.key)?handlers[intent.key].handler:void 0;intents.push(defined({key:intent.key,source:intent.source,handler,ordinal:intent.sequence,taskId:intent.taskId,generation:intent.generation,input:current.input,waitUntil:intent.waitUntil,retry:intent.retry,submission:current.submission,started:current.started,attempt:current.attempt,terminal:current.terminal,messageReceipt:current.messageReceipt,earlierExecutions,preparationError:intent.preparationError,memoryBlocked:intent.memoryBlocked,cancelReason:intent.cancelReason,retryUntil:intent.retryUntil,conclusion:intent.conclusion}));}for(const task of Object.keys(s.executions))derived(tasks.has(task),`execution ${task} belongs to no intent`);for(const key of Object.keys(handlers))derived(!!s.intents[hash(key)],`Host intent ${key} has no K4 intent`);derived(same(Object.keys(s.applied).sort(),[...succeeded].sort()),"K4 applied is not the succeeded current tasks");const routines=Object.entries(s.routines).map(([id,routine],ordinal)=>{exact(routine,ROUTINE_KEYS,ROUTINE_OPTIONAL,`Routine ${routine.definition.id}`);const{definition:definition2}=routine;derived(id===hash(definition2.id),`routine ${definition2.id} is stored under ${id}`);if(routine.next){exact(routine.next,["dedupKey","availableAt"],[],`Routine ${definition2.id} next wake`);const parsed=parseRoutineWakeKey(routine.next.dedupKey);derived(parsed?.id===definition2.id&&parsed.version===definition2.version&&parsed.at===routine.next.availableAt&&routine.next.dedupKey===routineWakeKey(definition2.id,definition2.version,routine.next.availableAt),`routine ${definition2.id} next wake key`);}return defined({id:definition2.id,ordinal,definition:definition2,pending:routine.pending,lifecycle:routine.lifecycle,status:routine.status,nextAt:routine.next?.availableAt??null,calendarErrors:routine.calendarErrors?.length?routine.calendarErrors:void 0,scheduleRetryAt:routine.scheduleRetryAt,scheduleRetryCount:routine.scheduleRetryCount,lastError:routine.lastError})});const slots=new Map,outbox=[];for(const[key,row]of Object.entries(s.outbox)){if(row.kind==="projection")refuse("projection_pending",`projection ${row.id} is not sent; flush it first`);if(row.kind==="intent")refuse("open_work",`intent ${row.intentId} has a pending submit`);if(row.kind!=="host-job")continue;exact(row,["kind","occurrenceKey"],[],`Host job ${row.occurrenceKey}`);derived(key===`host-job:${row.occurrenceKey}`,`Host job row ${key}`);outbox.push({kind:"host-job",occurrenceKey:row.occurrenceKey});}const occurrences=Object.entries(s.occurrences).map(([key,row],ordinal)=>{exact(row,OCCURRENCE_KEYS,OCCURRENCE_OPTIONAL,`Occurrence ${key}`);derived(row.key===key,`occurrence ${row.key} is stored under ${key}`);const parsed=parseRoutineWakeKey(row.wakeKey);derived(parsed?.id===row.routineId&&parsed.version===row.definitionVersion&&parsed.at===row.trigger.plannedAt&&row.wakeKey===routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt),`occurrence ${key} wake key`);slots.set(hash(row.wakeKey),key);const intent=s.intents[hash(occurrenceIntentKey(key))];derived(intent?row.intentId===intent.id:row.intentId===void 0,`occurrence ${key} intent id`);derived(row.attempts===switchAttempts(intent&&{submission:s.executions[intent.taskId].submission,generation:intent.generation}),`occurrence ${key} attempts`);derived(intent?row.conclusion===intent.conclusion:true,`occurrence ${key} conclusion differs from its intent's`);if(row.job===void 0===(row.hook===void 0))refuse("invalid",`occurrence ${key} is not exactly one of a Host job and a hook`);if(row.job)exact(row.job,["attempts"],["summary","executionSuperseded"],`Occurrence ${key} job`);if(row.hook)exact(row.hook,[],["executionSuperseded"],`Occurrence ${key} hook`);return defined({key,ordinal,routineId:row.routineId,definitionVersion:row.definitionVersion,trigger:row.trigger,recordedAt:row.recordedAt,nextAt:row.nextAt,job:row.job?defined({attempts:row.job.attempts,summary:row.job.summary}):null,executionSuperseded:!!(row.job??row.hook).executionSuperseded,conclusion:intent?void 0:row.conclusion,slotReplayCount:row.slotReplayCount})});derived(same(Object.entries(s.slots).sort(),[...slots].sort()),"K4 slots are not one per occurrence");return {version:1,...header,collaboration:liveState(state),archived:dump.rows.map(row=>defined({namespace:row.namespace,id:row.id,body:row.value,expiresAt:row.expiresAt??void 0})),intents,routines,occurrences,outbox,tombstones:dump.tombstones.map(row=>defined({kind:row.kind,digest:row.identity,expiresAt:row.expiresAt??void 0}))}}function switchDump(content,tenant,owner){const byOrdinal=rows=>[...rows].sort((a,b)=>a.ordinal-b.ordinal);const records=new Map(content.intents.map(row=>[row.key,row]));const s={version:1,sequence:Math.max(0,...content.intents.map(row=>row.ordinal)),scanSequence:0,intents:{},executions:{},routines:{},occurrences:{},slots:{},outbox:{},applied:{},application:{},scanWake:null};const hostIntents={};for(const row of byOrdinal(content.intents)){const{taskId:_task,...execution}=row.input;const intent=defined({key:row.key,source:row.source,execution,waitUntil:row.waitUntil,retry:row.retry,id:hash(row.key),agent:agentKey(tenant,execution),sequence:row.ordinal,phase:"settled",generation:row.generation,taskId:row.taskId,notBefore:0,attempts:switchAttempts(row),memoryBlocked:row.memoryBlocked,preparationError:row.preparationError,retryUntil:row.retryUntil,cancelReason:row.cancelReason,conclusion:row.conclusion});s.intents[intent.id]=intent;s.executions[row.taskId]=defined({input:row.input,submission:row.submission,started:row.started,attempt:row.attempt,terminal:row.terminal,messageReceipt:row.messageReceipt});row.earlierExecutions.forEach((earlier,generation)=>{const task=taskId(row.key,generation);s.executions[task]=defined({input:frozenInput(execution,task),...earlier});});if(row.conclusion==="succeeded")s.applied[row.taskId]=true;if(row.handler!==void 0)Object.defineProperty(hostIntents,row.key,{value:{handler:row.handler},enumerable:true,writable:true,configurable:true});}for(const row of byOrdinal(content.routines)){s.routines[hash(row.id)]=defined({definition:row.definition,pending:row.pending,lifecycle:row.lifecycle,status:row.status,next:row.nextAt===null?null:{dedupKey:routineWakeKey(row.id,row.definition.version,row.nextAt),availableAt:row.nextAt},calendarErrors:row.calendarErrors,scheduleRetryAt:row.scheduleRetryAt,scheduleRetryCount:row.scheduleRetryCount,lastError:row.lastError});}for(const row of byOrdinal(content.occurrences)){const wakeKey=routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt);const intent=s.intents[hash(occurrenceIntentKey(row.key))];if(intent)intent.occurrence=row.key;const superseded=row.executionSuperseded?{executionSuperseded:true}:{};s.occurrences[row.key]=defined({key:row.key,routineId:row.routineId,definitionVersion:row.definitionVersion,trigger:row.trigger,wakeKey,recordedAt:row.recordedAt,nextAt:row.nextAt,intentId:intent?.id,job:row.job?{...row.job,...superseded}:void 0,hook:row.job?void 0:superseded,attempts:switchAttempts(records.get(occurrenceIntentKey(row.key))),conclusion:intent?intent.conclusion:row.conclusion,slotReplayCount:row.slotReplayCount});s.slots[hash(wakeKey)]=row.key;}for(const row of content.outbox)s.outbox[`host-job:${row.occurrenceKey}`]={kind:"host-job",occurrenceKey:row.occurrenceKey};s.application.collaboration={...structuredClone(content.collaboration),...Object.keys(hostIntents).length?{hostIntents}:{},...defined(owner)};return {version:1,body:s,memoryTombstones:[],tombstones:content.tombstones.map(row=>({kind:row.kind,identity:row.digest,expiresAt:row.expiresAt??null})),rows:content.archived.map(row=>({namespace:row.namespace,id:row.id,value:row.body,expiresAt:row.expiresAt??null}))}}var headerOf=document=>({source:document.source,domain:document.domain,devices:document.devices,exportedAt:document.exportedAt});function sealLedger(ledger,header){return sealSwitchExport(switchContent(ledger.dumpForSwitch(),ledger.tenant,header))}var importOf=state=>{if(!state.switchImport)throw new Error("This ledger holds no switch import record");return state.switchImport};function importForSwitch(ledger,document){const manifest=verifySwitchExport(document);if(document.source!=="H")throw new SwitchExportError("invalid",`An L owner imports only an H export, not one from ${document.source}`);const devices=document.devices.map(device=>device.deviceId);const topology={};for(const id of devices)Object.defineProperty(topology,id,{value:{mode:"H",revision:1},enumerable:true,writable:true,configurable:true});ledger.loadForSwitch(switchDump(document,ledger.tenant,{topology,switchImport:{digest:manifest.digest,devices}}),readBack=>{const back=sealSwitchExport(switchContent(readBack,ledger.tenant,headerOf(document))).manifest.digest;if(back!==manifest.digest)throw new SwitchExportError("manifest",`The imported ledger reads back as ${back}, not ${manifest.digest}`)});return {digest:manifest.digest,devices}}function commitImport(ledger,digest){ledger.transaction(s=>{const state=stateOf(s.application),record=importOf(state);if(record.discarding)throw new Error("The switch import is being discarded");if(record.digest!==digest)throw new Error(`The switch import is ${record.digest}, not ${digest}`);for(const id of record.devices){const row=state.topology&&Object.hasOwn(state.topology,id)?state.topology[id]:void 0;if(row?.mode!=="H"||row.revision!==1||row.switching)throw new Error(`Device ${id} is not an imported device`);state.topology[id]={mode:"L",revision:2};}delete state.switchImport;});}function discardImport(ledger){ledger.transaction(s=>{importOf(stateOf(s.application)).discarding=true;});ledger.discard();}function writeLedger(ledger,apply){return ledger.transaction((s,rows)=>{refuseImported(stateOf(s.application));const result=apply(s,rows);refuseExported(stateOf(s.application));return result})}function commitInLedger(ledger,request,ports){return writeLedger(ledger,(s,rows)=>commitInRows(stateOf(s.application),ledger.tenant,request,rows,ports(s)))}function commitInRows(state,scope,request,rows,ports){let admitted;const result=commitCommand(state,request,{scope,recordCallbacks:false,archived:id=>rows.get("commands",id),admitted:ids=>{admitted=ids;}},ports);refuseRetired(admitted,(namespace,id)=>rows.isRetired(namespace,id));return result}function retainInLedger(ledger,input,limits){return writeLedger(ledger,(s,rows)=>retainRoots(stateOf(s.application),input,limits,{hasIntent:turnId=>!!s.intents[hash(turnId)],occurrenceOpen:turnId=>{const occurrence=s.occurrences[routineOccurrence({id:turnId})];return !!occurrence&&!occurrence.conclusion}},rows))}var wouldDoRowNeedsMigration=row=>row.turnId===void 0;function wouldDoNeedsMigration(state){return Object.values(state.wouldDo??{}).some(wouldDoRowNeedsMigration)}function migrateWouldDo(ledger){return writeLedger(ledger,(s,rows)=>{const state=stateOf(s.application),owners=new Map,result={backfilled:0,archived:0};for(const intent of Object.values(s.intents)){if(!Object.hasOwn(state.turns,intent.key))continue;for(let generation=0;generation<=intent.generation;generation++)owners.set(taskId(intent.key,generation),intent.key);}for(const row of Object.values(state.wouldDo??{})){if(!wouldDoRowNeedsMigration(row))continue;const turnId=owners.get(row.taskId);if(turnId!==void 0){row.turnId=turnId;result.backfilled++;continue}rows.put("wouldDo",row.id,row);delete state.wouldDo[row.id];result.archived++;}return result})}function prioritiseUser(s,state,user){const autonomous=autonomousIntentIds(Object.values(state.turns),dreamIntentIds(state));const plan=userFirst(Object.values(s.intents),user.id,autonomous,s.sequence);if(!plan)return;for(const{id,sequence}of plan.assignments)s.intents[id].sequence=sequence;s.sequence=plan.sequence;}function syncTurnInLedger(ledger,s,rows,turn,options){const facts={intent:intentFacts(s).intent,executionStarted:id=>{const row=s.intents[hash(id)];return !!row&&!!s.executions[row.taskId]?.started},retired:id=>turnIntentRetired(ledger,s,turn,options.now)?"result_retired":retiredIdentity("turn",id,(namespace,row)=>rows.isRetired(namespace,row))?"turn_retired":void 0,deviceRefusal:botId=>botDeviceRefusal(stateOf(s.application),botId)};refuseImported(stateOf(s.application));const step=syncTurn(stateOf(s.application),turn,facts,options,(key,value)=>project(s,key,value));const more=applyStep();refuseExported(stateOf(s.application));return more;function applyStep(){switch(step?.kind){case "freeze":{const intent=enqueue(s,ledger.tenant,step.input);if(step.input.source==="user")prioritiseUser(s,stateOf(s.application),intent);return true}case "routine":promoteOccurrence(s,ledger.tenant,routineOccurrence(turn),step.execution);return true;case "cancel":s.intents[hash(turn.id)].cancelReason="cancelled";return false;case "ended":return turn.source==="routine"&&concludeRoutineTurn(s,turn);default:return false}}}async function callCardsInLedger(ledger,call){for(const old of Object.values(stateOf(ledger.snapshot().application).cards)){if(!cardCallDue(old))continue;const claimed=writeLedger(ledger,s=>{const state=stateOf(s.application),card=state.cards[old.id];if(!card||!cardCallDue(card))return false;const calls=state.cardCalls??={};if(!calls[card.id])return calls[card.id]=true;delete calls[card.id];settleCardCall(card,{error:new Error(CONNECTOR_OUTCOME_UNKNOWN)});return false});if(!claimed)continue;let outcome;try{outcome={result:await call(old)};}catch(error){outcome={error};}writeLedger(ledger,s=>{const state=stateOf(s.application);delete state.cardCalls[old.id];settleCardCall(state.cards[old.id],outcome);});}}function advanceRooms(s,state,now,add,publish){const facts={};for(const id of Object.keys(state.team.seats)){const intent=s.intents[hash(id)],execution=intent&&s.executions[intent.taskId];facts[id]={admitted:!!intent,started:!!execution?.started,conclusion:intent?.conclusion};}for(const seatId of advanceRoomSeats(state,facts,now,add,publish))s.intents[hash(seatId)].cancelReason="cancelled";}function advanceRoomsAndTurns(s,state,now,step,publish){const released=()=>Object.values(state.team.seats).filter(seat=>seat.released).length;let changed=false,before;do{advanceRooms(s,state,now,(id,botId,request)=>addTurn(state,seatTurn(id,botId,request)),publish);before=released();for(const turn of Object.values(state.turns))changed=step(turn)||changed;}while(released()>before);return changed}
9
-
10
- export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitBot, admitDevice, admitUserInput2 as admitUserInput, advanceRoomsAndTurns, botCompactVeto, botDeviceRefusal, botOutcomePorts, callCardsInLedger, checkDreamInstruction, checkSwitchRecords, checkTopology, cleanReplyTokens, commitImport, commitInLedger, commitInRows, deliveryRoute, deviceRefusal, deviceTopology, discardImport, dreamIntentIds, dreamPolicy, dreamReads, echoCandidates, enablePush, exportMarkOf, homeSent, importForSwitch, inboundDisposition, inboundDispositions, inboundDispositionsOf, intentRows, migrateWouldDo, observeDevices2 as observeDevices, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseExported, refuseRoute, rememberFilteredInbound, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelegations2 as settleDelegations, settleDelivery, startDelivery, switchAttempts, switchContent, switchDrained, switchStep, switchWork, syncDreams, syncHead, syncTail, syncTurnInLedger, unknownDelivery, verifySwitchExport, wouldDoNeedsMigration, writeLedger };
11
- //# sourceMappingURL=chunk-QZRWFFHM.js.map
12
- //# sourceMappingURL=chunk-QZRWFFHM.js.map