@byok-sdk/bot-collaboration 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -108,19 +108,36 @@ a compacted Host intent's record also removes its replies.
108
108
 
109
109
  Cancel a Host intent with the owner call `cancelHostIntent(key)` (#1320), not
110
110
  with `bot.core.cancel`. K4 records the cancel on the intent row, so a restart
111
- reads the same fact. An intent that was not submitted settles as `cancelled`
112
- inside the call, which returns `{ result: 'cancelled' }`: its handler does not
113
- run, and its FIFO moves on. A submitted or running intent gets an SDK cancel, and
111
+ reads the same fact. For an intent that was not submitted, `{ result: 'cancelled' }`
112
+ confirms that the cancel committed. Its `conclusion` is optional: if `drainError`
113
+ or `wakePending` accompanies an unfinished settlement, the field is absent until
114
+ a later successful drain settles it as `cancelled`. Its handler does not run,
115
+ and settlement advances its FIFO. A submitted or running intent gets an SDK cancel, and
114
116
  the call returns `{ result: 'cancel_pending' }` at once. K4 then settles it: a
115
117
  cancelled terminal runs no handler, but a `task.complete` that arrived before the
116
118
  cancel still runs the handler once. Read the final conclusion with
117
119
  `bot.core.intent(key)`. A settled intent returns `{ result: 'already_settled' }`
118
- with its conclusion and sends nothing, so a replay does not fail. The call throws
120
+ with its conclusion and sends nothing, so a replay does not fail. After retrying
121
+ pending work with `drain()` or recovery, replay `cancelHostIntent(key)` to obtain
122
+ `already_settled` with the conclusion, or `cancel_pending` while a submitted
123
+ intent awaits its terminal. A queued intent whose settlement still fails can
124
+ again return `cancelled` without a conclusion. Check `'drainError' in result`
125
+ for post-commit failures; the coalesced drain may have failed on other Host work.
126
+ The call throws
119
127
  `HostIntentError` with `unknown_intent` for a key that is not a Host intent and
120
128
  `not_host_intent` for a Bot Turn key; cancel a Bot Turn with `cancelTurn`. A
121
129
  cancel does not release a `handler_failed` intent, because K4 applies its
122
130
  terminal again; `failStuckIntent` below is the way out.
123
131
 
132
+ `cancelHostIntents(keys)` cancels a chosen set atomically without a pass (#2003).
133
+ It refuses the entire set if any key is unknown, a Bot Turn or in flight;
134
+ `HostIntentError.rejected` lists every refused key and code in input order.
135
+ Settled keys return their earlier conclusion. After K4 compacts an intent, a
136
+ replay of that key returns `unknown_intent` instead of `already_settled`.
137
+ No handler runs for cancelled keys.
138
+ Successors wait for a later pass; call `drain()` to start them immediately.
139
+ A frozen device accepts this call. Duplicate keys and non-owner calls are refused.
140
+
124
141
  A K4 terminal that K8 cannot apply leaves its intent open: a key that is neither
125
142
  a Bot Turn nor a Host intent, for example from a direct `bot.core.enqueue`
126
143
  (`unknown_intent`), a Host handler that throws or returns a promise
@@ -1,12 +1,12 @@
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-ZUFZCROA.js';
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
2
  import { hash, canonical, occurrenceIntentKey, occurrenceOfIntentKey, concludeOccurrence, time, MIN_TOMBSTONE_RETENTION_MS } from '@byok-sdk/server/execution-core';
3
3
  import { nextRoutineOccurrence, checkRoutineSchedule, HostOfferSealedPayloadSchema, buildHandoffPack } from '@byok-sdk/protocol';
4
4
 
5
- function emptyTeam(){return {bots:{},rooms:{},rounds:{},seats:{},roots:{},notes:[],homeOperations:[]}}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 Error("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 Error("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");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}
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
6
 
7
7
  Request:
8
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
9
 
10
- export { BOT_DREAM, BOT_ROUTINE, 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-XTZUCECQ.js.map
12
- //# sourceMappingURL=chunk-XTZUCECQ.js.map
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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/team-model.ts","../src/model.ts","../src/channel.ts","../src/routines.ts","../src/retention.ts","../src/schema.ts","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,CAAM,MAAA,CAAO,MAAM,CAAA,CACrC,GAAI,CAAC,IAAA,CAAM,MAAM,IAAI,MAAM,gBAAgB,CAAA,CAC3C,MAAMG,OAAAA,CAAS,CAAE,GAAG,KAAM,GAAG,OAAA,CAAQ,MAAM,CAAE,CAAA,CAC7C,GAAI,CAAC,MAAA,CAAO,KAAA,EAAS,CAACA,OAAAA,CAAO,OAAA,CAAQ,QAAA,CAASA,QAAO,KAAA,EAAS,EAAE,CAAA,CAAG,OAAOA,OAAAA,CAAO,KAAA,CACjF,MAAM,IAAA,CAAO,UAAA,CAAW,IAAA,CAAMA,OAAM,CAAA,CACpC,IAAA,CAAK,YAAc,cAAA,CAAe,IAAA,CAAM,IAAA,CAAK,OAAO,CAAA,CACpD,MAAA,CAAO,OAAO,IAAA,CAAM,IAAI,CAAA,CACxB,GAAI,CAAC,IAAA,CAAK,MAAO,OAAO,IAAA,CAAK,MAC/B,CAAC,CAAC,CAAA,CACF,GAAI,OAAA,CAAQ,SAAA,CAAW,OAAA,CAAQ,WAAA,CAAa,IAAM,CAChD,GAAI,IAAA,CAAK,KAAA,CAAM,MAAA,EAAU,eAAA,CAAiB,MAAM,IAAI,MAAM,uBAAuB,CAAA,CACjF,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,CAAE,GAAIH,IAAAA,CAAK,CAAC,MAAA,CAAQ,WAAW,CAAC,CAAA,CAAG,KAAM,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"]}