@byok-sdk/bot-collaboration 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ import { inboundKey, supersededDeliveryIds, stateOf, dreamTable, routineCalendar, BOT_DREAM, owned, updateDefinition, createDefinition, retainRoots, routineOccurrence, concludeRoutineTurn, ROUTINE_LATE_AFTER_MS } from './chunk-DYQSVSPJ.js';
2
+ import { validateInputImages, admitUserInput, addBatchTurns, addTurn, isAutonomous, inactive, expireCards, observeDevices, settleDelegations, compactVeto, DEVICE_SWITCHING, DEVICE_NOT_BOUND, CommitConflict, refuseUnmigratedWouldDo, commitCommand, refuseRetired, syncTurn, cardCallDue, settleCardCall, CONNECTOR_OUTCOME_UNKNOWN, json, retiredIdentity, handoffFrameBytes, handoffTurn, sealDueBatches, autonomousIntentIds, userFirst, advanceRoomSeats, seatTurn } from './chunk-4HLCBNWV.js';
3
+ import { hash, time, occurrenceIntentKey, setLifecycle, routineCommands, promoteOccurrence, taskId, isOccurrenceIntentKey, routineWakeKey, agentKey, frozenInput, parseRoutineWakeKey, project, enqueue, concludeOccurrence, occurrenceOfIntentKey, validateJson, canonical as canonical$1, validateRetry } from '@byok-sdk/server/execution-core';
4
+ import { checkRoutineSchedule, buildDreamInstruction, buildHandoffPack, targetsPi } from '@byok-sdk/protocol';
5
+ import { canonical, hash as hash$1 } from '@byok-sdk/server/execution-core/canonical';
6
+
7
+ function botFacts(state,botId){const bot=state.team.bots[botId];return bot&&{busy:Object.values(state.turns).some(turn=>turn.botId===botId&&!turn.conclusion&&turn.status!=="blocked"),configKey:[bot.revision,bot.model],archived:bot.archived}}function sealDueBatches2(state,policy,now){const bots={};for(const batch of Object.values(state.inputBatches??{})){const facts=batch.state==="open"?botFacts(state,batch.botId):void 0;if(facts)bots[batch.botId]=facts;}addBatchTurns(state,sealDueBatches(state,bots,policy,now));}function projectInputBatches(state,emit){for(const batch of Object.values(state.inputBatches??{})){const revision=batch.state==="open"?1:2;if((batch.revision??0)>=revision)continue;batch.revision=revision;emit(`input-batch:${batch.id}:${revision}`,json({owner:batch.botId,id:batch.id,revision,state:batch.state,sealReason:batch.sealReason,inputIds:batch.inputIds,openedAt:batch.openedAt,sealAt:batch.sealAt}));}}function admitUserInput2(state,input,policy,now){const fields=validateInputImages(input);const admission=admitUserInput(state,fields,{bot:botFacts(state,fields.botId),turn:state.turns[fields.id]},policy,now);addBatchTurns(state,admission.sealed);if(admission.turn){const{id,request,botId,authority,images}=fields;state.budgets[id]??={continuation:0,delegation:0};addTurn(state,{id,root:id,source:"user",request,botId,hop:0,authority,...images===void 0?{}:{images}});}return admission.id}var MAX_ATTEMPTS=3;var MAX_WAIT_MS=6e4;function deliveryId(taskId2,messageId,route,nonce){const key=route.kind==="reply"?["reply",route.inboundId]:["push",route.pushRouteId];return hash(nonce===void 0?[taskId2,messageId,key]:[taskId2,messageId,key,nonce])}function startDelivery(row,now){if(row.state!=="pending"||row.attempts>=MAX_ATTEMPTS||row.nextAttemptAt!==void 0&&now<row.nextAttemptAt)return false;row.state="sending";row.attempts++;delete row.nextAttemptAt;delete row.code;return true}function currentAttempt(row,attempt){return row.state==="sending"&&row.attempts===attempt}function retryDelivery(row,now,retryAfterMs){const wait=Math.max(retryAfterMs,1e3*2**(row.attempts-1));if(wait>MAX_WAIT_MS){row.state="rejected";return}row.state="pending";row.nextAttemptAt=now+wait;}function settleDelivery(row,attempt,result,now){if(!currentAttempt(row,attempt))return;if(result?.result==="accepted"&&typeof result.platformMessageId==="string"&&result.platformMessageId.length>0){row.state="accepted";row.platformMessageId=result.platformMessageId;delete row.code;return}if(result?.result!=="rejected"||typeof result.code!=="string"||result.code.length===0||typeof result.retryable!=="boolean"){unknownDelivery(row,attempt,"invalid_send_result");return}row.code=result.code;if(!result.retryable||row.attempts>=MAX_ATTEMPTS){row.state="rejected";return}const retryAfter=result.retryAfterMs===void 0?0:result.retryAfterMs;if(!Number.isFinite(retryAfter)||retryAfter<0){row.state="rejected";row.code="invalid_retry_after";return}retryDelivery(row,now,retryAfter);}function unknownDelivery(row,attempt,code){if(!currentAttempt(row,attempt))return;row.state="unknown";row.code=code;delete row.nextAttemptAt;}function recoverDelivery(row){if(row.state==="sending")unknownDelivery(row,row.attempts,"interrupted");}function readbackDelivery(row,attempt,result,now){if(row.state!=="unknown"||row.attempts!==attempt)return;if(result==="accepted"){row.state="accepted";delete row.code;}else if(result==="absent"){if(row.attempts>=MAX_ATTEMPTS){row.state="rejected";row.code="attempts_exhausted";}else {delete row.code;retryDelivery(row,now,0);}}}function acceptDeliveryEcho(row,platformMessageId){if(!platformMessageId)return false;if(row.state==="accepted"){if(row.platformMessageId&&row.platformMessageId!==platformMessageId)return false;row.platformMessageId=platformMessageId;return true}const waitingRetry=row.state==="pending"&&row.attempts>0;if(row.state!=="sending"&&row.state!=="unknown"&&!waitingRetry)return false;row.state="accepted";row.platformMessageId=platformMessageId;delete row.code;delete row.nextAttemptAt;return true}function channelState(state){return state.channel??={inbounds:{},pushRoutes:{},deliveries:{}}}var sameConversation=(a,b)=>a.kind===b.kind&&a.id===b.id;function turnConversation(state,turn){const seat=state.team.seats[turn.id];return seat?{kind:"group",id:state.team.rounds[seat.roundId].roomId}:{kind:"direct",id:turn.botId}}function turnRoot(state,turn){const seat=state.team.seats[turn.id];return seat?state.team.rounds[seat.roundId].root:turn.root}function rootOpen(ledger,state,root,conversation){return Object.values(state.turns).some(turn=>turnRoot(state,turn)===root&&sameConversation(turnConversation(state,turn),conversation)&&!turn.conclusion&&!ledger.intents[hash(turn.id)]?.conclusion&&!["failed","delivered"].includes(turn.status)&&(turn.status!=="blocked"||!state.team.seats[turn.id]))||Object.values(state.inputBatches??{}).some(batch=>batch.id===root&&batch.state==="open")||Object.values(state.team.seats).some(seat=>state.team.rounds[seat.roundId]?.root===root&&!seat.released)}function rememberInbound(state,message,root){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)throw new Error("Invalid inbound identity");const route=message.replyRoute;if(route&&(route.kind!=="reply"||route.channel!==message.channel||route.inboundId!==message.platformMessageId||typeof route.token!=="string"||!route.token||!Number.isSafeInteger(route.expiresAt)||route.expiresAt<0)){throw new Error("Invalid reply route binding")}const channels=channelState(state),id=inboundKey(message);const prior=channels.inbounds[id];if(!prior||prior.filtered!==void 0)channels.inbounds[id]={id,root,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,...route?{reply:{...route}}:{}};}function rememberFilteredInbound(state,message,code){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)return;const channels=channelState(state),id=inboundKey(message);channels.inbounds[id]??={id,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,filtered:code};}function enablePush(state,conversation,channel,target,owner,now){if(!conversation.id||!channel.trim()||!target.trim())throw new Error("Invalid push route");const channels=channelState(state);for(const route2 of Object.values(channels.pushRoutes)){if(sameConversation(route2.conversation,conversation)&&route2.revokedAt===void 0)revokePush(state,route2.id,now);}const id=hash(["push-route",conversation,channel,target,++state.sequence]);const route={kind:"push",id,conversation:{...conversation},channel,target,optedInBy:owner,optedInAt:now};channels.pushRoutes[id]=route;return route}function revokePush(state,id,now){const routes=state.channel?.pushRoutes;const route=routes&&Object.hasOwn(routes,id)?routes[id]:void 0;if(!route)throw new Error("Push route not found");route.revokedAt??=now;for(const delivery of Object.values(state.channel.deliveries)){if(delivery.state==="pending"&&delivery.route.kind==="push"&&delivery.route.pushRouteId===id)refuseRoute(state,delivery);}}function activePush(state,conversation){return Object.values(state.channel?.pushRoutes??{}).find(route=>route.revokedAt===void 0&&sameConversation(route.conversation,conversation))}function insert(state,input,staged=false){const id=deliveryId(input.taskId,input.messageId,input.route);return channelState(state).deliveries[id]??={id,...input,state:staged?"staged":"pending",attempts:0}}function queueDelivery(ledger,state,turn,taskId2,messageId,body,now,staged=false){const conversation=turnConversation(state,turn),root=turnRoot(state,turn);const inbound=Object.values(state.channel?.inbounds??{}).filter(row=>row.root===root&&sameConversation(row.conversation,conversation)).sort((a,b)=>b.sequence-a.sequence)[0];if(inbound?.reply?.token&&inbound.reply.expiresAt>now&&rootOpen(ledger,state,root,conversation)){return insert(state,{taskId:taskId2,turnId:turn.id,messageId,body,conversation,channel:inbound.reply.channel,route:{kind:"reply",inboundId:inbound.id}},staged)}const push=activePush(state,conversation);if(push)return insert(state,{taskId:taskId2,turnId:turn.id,messageId,body,conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}},staged);state.audit.push(`Delivery ${inbound?.reply?"reply_route_expired":"no_push_route"}: ${taskId2} ${messageId}`);return void 0}function promoteStaged(state,taskId2){const rows=Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="staged"&&row.taskId===taskId2);for(const row of rows)row.state="pending";return rows.map(row=>row.id)}function withholdStaged(ledger,state){for(const row of Object.values(state.channel?.deliveries??{})){if(row.state!=="staged"||!ledger.intents[hash(row.turnId)]?.conclusion)continue;row.state="rejected";row.code="outcome_not_applied";state.audit.push(`Delivery outcome_not_applied: ${row.taskId} ${row.messageId}`);}}function deliveryRoute(state,row,now){if(row.route.kind==="push"){const route2=state.channel?.pushRoutes[row.route.pushRouteId];return route2&&route2.revokedAt===void 0&&sameConversation(route2.conversation,row.conversation)?structuredClone(route2):void 0}const stored=state.channel?.inbounds[row.route.inboundId],route=stored?.reply;return route?.token&&route.expiresAt>now&&sameConversation(stored.conversation,row.conversation)?{...route,token:route.token}:void 0}function refuseRoute(state,row){if(row.state!=="pending")return;row.state="rejected";delete row.nextAttemptAt;row.code=row.route.kind==="reply"?"reply_route_expired":"push_route_revoked";state.audit.push(`Delivery ${row.code}: ${row.taskId} ${row.messageId}`);const push=row.route.kind==="reply"?activePush(state,row.conversation):void 0;if(push)insert(state,{taskId:row.taskId,turnId:row.turnId,messageId:row.messageId,body:row.body,conversation:row.conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}});}function cleanReplyTokens(ledger,state,now){const superseded=supersededDeliveryIds(state.channel?.deliveries??{});for(const row of Object.values(state.channel?.inbounds??{})){if(!row.reply?.token||row.root===void 0)continue;const reserved=Object.values(state.channel.deliveries).some(delivery=>delivery.route.kind==="reply"&&delivery.route.inboundId===row.id&&!superseded.has(delivery.id)&&["staged","pending","sending","unknown"].includes(delivery.state));if(now>=row.reply.expiresAt||!reserved&&!rootOpen(ledger,state,row.root,row.conversation))delete row.reply.token;}}function resendUnknown(state,id,now){const deliveries=state.channel?.deliveries;const old=deliveries&&Object.hasOwn(deliveries,id)?deliveries[id]:void 0;if(!old||old.state!=="unknown")throw new Error("Only an unknown delivery can be resent");if(supersededDeliveryIds(deliveries).has(id))throw new Error("Delivery has already been resent");const available=deliveryRoute(state,old,now)??activePush(state,old.conversation);if(!available)throw new Error("No active delivery route");const route=available.kind==="reply"?old.route:{kind:"push",pushRouteId:available.id};const nextId=deliveryId(old.taskId,old.messageId,route,String(++state.sequence));const row={id:nextId,taskId:old.taskId,turnId:old.turnId,messageId:old.messageId,body:old.body,conversation:{...old.conversation},channel:available.channel,route:{...route},state:"pending",attempts:0,resendOf:old.id};state.channel.deliveries[nextId]=row;return row}function echoCandidates(state,message){return Object.values(state.channel?.deliveries??{}).filter(row=>row.channel===message.channel&&sameConversation(row.conversation,message.conversation)&&row.state!=="rejected"&&(message.deliveryId!==void 0?row.id===message.deliveryId:row.platformMessageId===message.platformMessageId))}var ANSWERED=new Set(["succeeded","delivered"]);var FAILED=new Set(["failed","expired","declined","superseded","abandoned"]);function inboundDisposition(state,row){if(row.filtered!==void 0)return {id:row.id,disposition:"filtered",code:row.filtered};const root=row.root;if(root===void 0)return {id:row.id,disposition:"failed",turnId:row.id};const turn=Object.hasOwn(state.turns,root)?state.turns[root]:void 0;if(!turn){const batch=state.inputBatches&&Object.hasOwn(state.inputBatches,root)?state.inputBatches[root]:void 0;return batch?.state==="open"?{id:row.id,disposition:"coalesced",turnId:root}:{id:row.id,disposition:"failed",turnId:root}}const conclusions=[turn.conclusion,turn.status];if(conclusions.includes("cancelled"))return {id:row.id,disposition:"cancelled",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&ANSWERED.has(value)))return {id:row.id,disposition:"answered",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&FAILED.has(value)))return {id:row.id,disposition:"failed",turnId:turn.id};return {id:row.id,disposition:"coalesced",turnId:turn.id}}function inboundDispositions(state){return Object.values(state.channel?.inbounds??{}).filter(row=>row.filtered!==void 0||row.root!==void 0).sort((a,b)=>(a.sequence??0)-(b.sequence??0)||(a.id<b.id?-1:a.id>b.id?1:0)).map(row=>inboundDisposition(state,row))}var DEFAULT_DREAM_MAX_DURATION_MS=9e5;var DREAM_WAIT_MS=36e5;var DREAM_HOUR=3;var MIN_PACK_BYTES=1024;var scheduleIn=tz=>({minute:0,hour:DREAM_HOUR,tz});var localZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone;function dreamPolicy(options){if(options===false)return void 0;const check=checkRoutineSchedule(scheduleIn(options?.timeZone??localZone()));if(!check.ok)throw new Error(`dreaming: ${check.code}: ${check.message}`);const maxDurationMs=time(options?.maxDurationMs??DEFAULT_DREAM_MAX_DURATION_MS);if(maxDurationMs<1)throw new Error("dreaming: maxDurationMs must be positive");return {...options?.timeZone===void 0?{}:{timeZone:options.timeZone},models:[...options?.models??[]],maxDurationMs,nativeSessions:options?.nativeSessions??true}}var ownerOf=routine=>{const spec=routine.definition.hostOccurrence;return spec?.type===BOT_DREAM?spec.input.owner:void 0};function dreamOf(state,intentKey){const key=occurrenceOfIntentKey(intentKey);return key!==void 0&&state.dreams&&Object.hasOwn(state.dreams.open,key)?state.dreams.open[key]:void 0}function dreamIntentIds(state){return Object.keys(state.dreams?.open??{}).map(key=>hash(occurrenceIntentKey(key)))}function dreamYield(state,intentKey){const dream=dreamOf(state,intentKey);return dream&&Object.values(state.turns).some(turn=>turn.botId===dream.botId&&!isAutonomous(turn)&&(turn.status==="queued"||turn.status==="processing"))?"user_input":void 0}function dreamHolds(s){const holds=new Map;for(const[key,run]of Object.entries(stateOf(s.application).dreams?.open??{})){const intent=s.intents[hash(occurrenceIntentKey(key))];if(intent?.phase==="inflight")holds.set(run.botId,intent.execution.payload.limits.maxDurationMs);}return holds}function recordDream(state,run,now){dreamTable(state).open[run.occurrenceKey]={botId:run.input.owner,windowEnd:now};}function reconcileDreamRoutines(s,policy,models,now){const state=stateOf(s.application),rows=Object.values(s.routines).flatMap(row=>{const owner=ownerOf(row);return owner===void 0?[]:[{row,owner}]});const open=new Map;for(const{row,owner}of rows){if(row.lifecycle==="completed")continue;const bot=state.team.bots[owner];if(policy&&bot&&!bot.archived&&!open.has(owner))open.set(owner,row);else setLifecycle(s,row.definition.id,"completed",now,routineCalendar);}if(!policy)return;const commands=routineCommands(s,{now:()=>now,nextTime:routineCalendar,hostJobs:new Map,occurrenceHooks:new Map([[BOT_DREAM,recordDream]]),executionRoutines:"refuse"});const definition2=(id,version,owner,tz)=>({id,version,timeZone:tz,rule:json(scheduleIn(tz)),waitMs:DREAM_WAIT_MS,lateAfterMs:ROUTINE_LATE_AFTER_MS,hostOccurrence:{type:BOT_DREAM,input:{owner}}});for(const bot of Object.values(state.team.bots)){if(bot.archived)continue;const routine=open.get(bot.id),latest=routine?.pending??routine?.definition;if(latest){if(policy.timeZone!==void 0&&latest.timeZone!==policy.timeZone)commands.update(definition2(latest.id,latest.version+1,bot.id,policy.timeZone));}else if(models[bot.model]){commands.create(definition2(`dream:${bot.id}:${rows.filter(row=>row.owner===bot.id).length+1}`,1,bot.id,policy.timeZone??localZone()));dreamTable(state).bots[bot.id]??={since:now};}}}var completed=row=>row.status==="succeeded"||row.status==="delivered";function settledAfter(rows,mark){const after=rows.slice(rows.findIndex(row=>row.id===mark)+1);const open=after.findIndex(row=>row.status==="queued"||row.status==="processing");return open<0?after:after.slice(0,open)}function chooseModel(policy,models,botModel,deviceId){const name=policy.models.find(model=>Object.hasOwn(models,model)&&models[model].deviceId===deviceId);if(name!==void 0)return {template:name,fallback:false,base:models[name]};return models[botModel]?{template:botModel,fallback:true,base:void 0}:void 0}function dreamExecution(base,bot,instruction,maxDurationMs,window,nativeSessions){const{messageEgress:_egress,requiredToolsets:_toolsets,agentMemoryCommit:_commit,homeAccess:_home,preparation:_preparation,nativeSessions:_nativeSessions,...payload}=base.payload;return {deviceId:bot.deviceId,payload:{...payload,instruction,session:{mode:"fresh"},agentRef:bot.payload.agentRef,agentMemory:"none",limits:{maxDurationMs},terminalProjection:{mode:"none"},...nativeSessions&&targetsPi(payload.target)?{nativeSessions:{...window,ifAdvertised:true}}:{}}}}function dreamInstruction(rows,window,maxDurationMs,instructionMaxBytes){const budget={maxDurationMs},frame={omittedTurns:0,earlier:[],recent:[]};const fixed=Buffer.byteLength(buildDreamInstruction({history:frame,window,budget}),"utf8")-Buffer.byteLength(JSON.stringify(frame),"utf8");const totalBytes=Math.max(instructionMaxBytes-fixed,handoffFrameBytes(rows.length));const history=buildHandoffPack(rows.map(handoffTurn),{recentBytes:Math.floor(totalBytes/4*3),earlyBytes:totalBytes,totalBytes});return buildDreamInstruction({history,window,budget})}function checkDreamInstruction(instructionMaxBytes){const room=instructionMaxBytes-Buffer.byteLength(dreamInstruction([],{fromMs:0,toMs:0},1,0),"utf8");if(room<MIN_PACK_BYTES)throw new Error(`instructionMaxBytes leaves a dream ${room} bytes of history, under ${MIN_PACK_BYTES}`)}function syncDreams(s,sync){const state=stateOf(s.application),dreams=state.dreams;if(!dreams)return false;let changed=false;const close=(key,run,outcome,reason)=>{const bot=dreams.bots[run.botId]??={since:run.windowEnd};bot.last={occurrenceKey:key,at:run.windowEnd,outcome,...reason===void 0?{}:{reason},...run.template===void 0?{}:{template:run.template,fallback:run.fallback}};if(reason==="user_input")bot.userInputCancels=(bot.userInputCancels??0)+1;else delete bot.userInputCancels;if(outcome==="succeeded"){bot.since=run.windowEnd;if(run.throughTurn!==void 0)bot.throughTurn=run.throughTurn;}delete dreams.open[key];};const skip=(key,run,reason)=>{const occurrence=s.occurrences[key];if(occurrence&&!occurrence.conclusion){concludeOccurrence(s,key,reason==="superseded"?"superseded":"cancelled");changed=true;}close(key,run,reason==="superseded"?"superseded":"skipped",reason);};for(const[key,run]of Object.entries(dreams.open)){const bot=state.team.bots[run.botId],stopped=!bot?"archived":inactive(bot);if(run.template!==void 0){const intent=s.intents[hash(occurrenceIntentKey(key))];if(!intent)close(key,run,"failed","intent_compacted");else if(intent.conclusion)close(key,run,intent.conclusion,intent.conclusion==="cancelled"&&s.executions[intent.taskId]?.attempt?.cancellation?.reason==="user_input"?"user_input":void 0);else if(stopped&&intent.phase!=="inflight"&&!intent.cancelReason)intent.cancelReason="cancelled";continue}if(s.occurrences[key]?.hook?.executionSuperseded){skip(key,run,"superseded");continue}if(!sync.policy){skip(key,run,"dreaming_off");continue}if(!bot||stopped){skip(key,run,stopped==="suspended"?"bot_suspended":"bot_archived");continue}if(sync.refused(bot.id)){skip(key,run,"device_unavailable");continue}if(bot.readyRevision!==bot.revision){skip(key,run,"bot_not_ready");continue}const record=dreams.bots[bot.id]??={since:run.windowEnd};const settled=settledAfter(Object.values(state.turns).filter(turn=>turn.botId===bot.id),record.throughTurn),fresh=settled.filter(completed);if(!fresh.length){skip(key,run,"no_new_turns");continue}const model=chooseModel(sync.policy,sync.models,bot.model,bot.execution.deviceId);if(!model){skip(key,run,"model_unavailable");continue}let rows=fresh;let throughTurn=settled.at(-1).id;if(sync.historyMode){const read=sync.history?.get(key);if(read===void 0)continue;if(read===null){skip(key,run,"history_unavailable");continue}const readSettled=settledAfter(read,record.throughTurn);rows=readSettled.filter(completed);if(!rows.length){skip(key,run,"no_new_turns");continue}throughTurn=readSettled.at(-1).id;}const window={fromMs:Math.min(record.since,run.windowEnd),toMs:run.windowEnd};const instruction=dreamInstruction(rows,window,sync.policy.maxDurationMs,sync.instructionMaxBytes);Object.assign(run,{template:model.template,fallback:model.fallback,throughTurn});promoteOccurrence(s,sync.tenant,key,dreamExecution(model.base??bot.execution,bot.execution,instruction,sync.policy.maxDurationMs,window,sync.policy.nativeSessions));changed=true;}return changed}function dreamReads(state){return Object.entries(state.dreams?.open??{}).filter(([,run])=>run.template===void 0).map(([key,run])=>({key,botId:run.botId,turnId:occurrenceIntentKey(key)}))}function roundTurn(state,round){const turns=round.seats.map(id=>state.turns[id]).filter(turn=>turn!==void 0);const conclusions=turns.map(turn=>turn.conclusion).filter(value=>value!==void 0);if(turns.some(turn=>turn.status==="succeeded"||turn.conclusion==="succeeded"||turn.conclusion==="delivered")){return {id:round.id,root:round.root,status:"succeeded",conclusion:"succeeded"}}const failed=new Set(["failed","expired","declined","superseded","abandoned","cancelled"]);if(conclusions.some(conclusion=>failed.has(conclusion))||turns.some(turn=>turn.status==="failed")){return {id:round.id,root:round.root,status:"failed",conclusion:"failed"}}return {id:round.id,root:round.root,status:"queued"}}function inboundState(state){const turns={...state.turns};for(const round of Object.values(state.team.rounds))if(round.root===round.id)turns[round.id]??=roundTurn(state,round);return {channel:state.channel,turns,inputBatches:state.inputBatches}}function inboundDispositionsOf(state){if(Object.keys(state.channel?.inbounds??{}).length===0)return [];return inboundDispositions(inboundState(state))}function inboundProjection(disposition){const id=disposition.disposition==="filtered"?`inbound:${disposition.id}:filtered:${disposition.code}`:`inbound:${disposition.id}:${disposition.disposition}:${disposition.turnId}`;return {id,value:json(disposition)}}function projectInboundDispositions(state,emit){for(const disposition of inboundDispositionsOf(state)){const projection=inboundProjection(disposition);emit(projection.id,projection.value);}}var IntentOutcomeError=class extends Error{constructor(key,code,message){super(message);this.key=key;this.code=code;this.name="IntentOutcomeError";}key;code};function routeTerminal(state,key,handler){if(handler!==void 0)return {kind:"host_intent",handler};if(dreamOf(state,key))return {kind:"dream"};if(!Object.hasOwn(state.turns,key))throw new IntentOutcomeError(key,"unknown_intent","No Bot Turn or Host intent has this key");return {kind:"bot_turn"}}function runHostIntentHandler(key,name,run){if(run===void 0)throw new IntentOutcomeError(key,"handler_failed",`Unknown Host intent handler: ${name}`);let result;try{result=run();}catch(cause){throw new IntentOutcomeError(key,"handler_failed",cause instanceof Error?cause.message:String(cause))}if(result&&typeof result.then==="function"){void Promise.resolve(result).catch(()=>{});throw new IntentOutcomeError(key,"handler_failed","Host intent handler must be synchronous")}}function outcomeFailure(key,cause){return new IntentOutcomeError(key,"outcome_failed",cause instanceof Error?cause.message:String(cause))}function botOutcomePorts({taskId:taskId2,routines,manage,roomPosts}){return {manage,createRoutine:(turn,action,index)=>routines.create(createDefinition(routines.list(),turn.botId,taskId2,index,action,turn.authority??"bot")),updateRoutine:(turn,action)=>routines.update(updateDefinition(routines.list(),turn.botId,action)),cancelRoutine:(turn,action)=>routines.lifecycle(owned(routines.list(),turn.botId,action.routineId).definition.id,"completed"),roomPosts}}function syncHead(state,coalesce,now){sealDueBatches2(state,coalesce,now);expireCards(state,now);}function syncTail(state,conclusions,now,emit){if(conclusions!==void 0){withholdStaged(conclusions,state);cleanReplyTokens(conclusions,state,now);}projectInputBatches(state,emit);projectInboundDispositions(state,emit);}function intentFacts(s){const intent=key=>s.intents[hash(key)];return {intent:key=>{const row=intent(key);return row&&{taskId:row.taskId,...row.conclusion?{conclusion:row.conclusion}:{},...row.cancelReason?{cancelReason:row.cancelReason}:{}}},started:key=>{const row=intent(key);return !!row&&Array.from({length:row.generation+1},(_,g)=>s.executions[taskId(key,g)]).some(execution=>execution?.started||execution?.terminal!==void 0&&execution.terminal.envelope.type!=="task.decline")},declineCode:key=>{const row=intent(key),envelope=row&&s.executions[row.taskId]?.terminal?.envelope;return envelope?.type==="task.decline"?envelope.payload.code:void 0},offeredTo:key=>{const row=intent(key),execution=row&&s.executions[row.taskId];return row?.phase==="inflight"&&execution?.submission==="delivered"&&!execution.started&&execution.attempt?.status==="offered"?row.execution.deviceId:void 0}}}function intentRows(s){return {intent:key=>intentFacts({intents:s.intents,executions:{}}).intent(key)}}function observeDevices2(s,state,devices,emit){observeDevices(state,intentFacts(s),devices,emit);}function settleDelegations2(s,state,now,emit,timers){settleDelegations(state,intentFacts(s),now,emit,timers);}function turnIntentRetired(ledger,s,turn,now){return ledger.hasTombstone("intent",turn.id,now)||turn.source==="routine"&&!s.occurrences[routineOccurrence(turn)]}var botCompactVeto=(ledger,key)=>{const state=ledger.application.collaboration;if(state===void 0)return void 0;if(state.switchExport)return "switch_exported";return compactVeto(state,key,{hasIntent:turnId=>!!ledger.intents[hash(turnId)],receipt:taskId2=>ledger.executions[taskId2]?.messageReceipt})};var K8_FORMAT=3;var botLedgerOptions=Object.freeze({compactVeto:botCompactVeto,expectedFormats:Object.freeze({k8:K8_FORMAT})});var SWITCH_EXPORT_VERSION=2;var SWITCH_SECTIONS=["collaboration","archived","intents","routines","occurrences","outbox","tombstones"];function switchAttempts(intent){return intent===void 0||intent.submission==="reserved"?0:intent.generation+1}var SwitchExportError=class extends Error{constructor(reason,message){super(message);this.reason=reason;this.name="SwitchExportError";}reason;code="switch_export_refused"};var IDENTITY={archived:row=>[row.namespace,row.id],intents:row=>row.key,routines:row=>row.id,occurrences:row=>row.key,outbox:row=>[row.kind,row.occurrenceKey],tombstones:row=>[row.kind,row.digest]};var LISTS=SWITCH_SECTIONS.filter(section=>section!=="collaboration");var HEADER=["version","source","domain","devices","exportedAt"];var compare=(a,b)=>a<b?-1:a>b?1:0;function sealSwitchExport(content){checkContent(content,[...HEADER,...SWITCH_SECTIONS]);const sealed=structuredClone(content);sealed.devices.sort((a,b)=>compare(a.deviceId,b.deviceId));for(const section of LISTS){const key=IDENTITY[section];sealed[section].sort((a,b)=>compare(canonical(key(a)),canonical(key(b))));}checkOrder(sealed);return {...sealed,manifest:manifestOf(sealed)}}function verifySwitchExport(document){checkContent(document,[...HEADER,...SWITCH_SECTIONS,"manifest"]);ensure(keys(document.manifest,["counts","digests","digest"])&&keys(document.manifest.counts,SWITCH_SECTIONS)&&keys(document.manifest.digests,SWITCH_SECTIONS),"manifest keys");checkOrder(document);const manifest=manifestOf(document);if(canonical(manifest)!==canonical(document.manifest)){throw new SwitchExportError("manifest",`Switch export manifest does not match its content: ${document.manifest.digest} != ${manifest.digest}`)}return manifest}function manifestOf(content){const counts={},digests={};counts.collaboration=1;digests.collaboration=hash$1(JSON.stringify(content.collaboration));for(const section of LISTS){counts[section]=content[section].length;digests[section]=hash$1(content[section]);}const header={version:content.version,source:content.source,domain:content.domain,devices:content.devices,exportedAt:content.exportedAt};return {counts,digests,digest:hash$1({header,counts,digests})}}function checkOrder(content){for(let i=1;i<content.devices.length;i++){if(compare(content.devices[i-1].deviceId,content.devices[i].deviceId)>0){throw new SwitchExportError("unsorted",`Switch export devices are not in id order at ${content.devices[i].deviceId}`)}}for(const section of LISTS){const key=IDENTITY[section];const ids=content[section].map(row=>canonical(key(row)));for(let i=1;i<ids.length;i++){const order=compare(ids[i-1],ids[i]);if(order===0)throw new SwitchExportError("duplicate",`Switch export ${section} repeats ${ids[i]}`);if(order>0)throw new SwitchExportError("unsorted",`Switch export ${section} is not in identity order at ${ids[i]}`)}}}var object=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);var text=value=>typeof value==="string"&&value.length>0;var time2=value=>Number.isSafeInteger(value)&&value>=0;var digestText=value=>typeof value==="string"&&/^[0-9a-f]{64}$/.test(value);var CONCLUSIONS={succeeded:true,failed:true,declined:true,cancelled:true,expired:true,superseded:true};var conclusionText=value=>typeof value==="string"&&Object.hasOwn(CONCLUSIONS,value);var optional=(value,check)=>value===void 0||check(value);var oneOf=values=>value=>typeof value==="string"&&values.includes(value);function keys(value,required,allowed=[]){return object(value)&&required.every(key=>Object.hasOwn(value,key))&&Object.keys(value).every(key=>required.includes(key)||allowed.includes(key))}var receiptShape=value=>keys(value,["messageId","contentHash"])&&text(value.messageId)&&text(value.contentHash);function json2(value){try{validateJson(value);return true}catch{return false}}function invalid(message){throw new SwitchExportError("invalid",`Invalid switch export: ${message}`)}function ensure(ok,message){if(!ok)invalid(message);}function reference(ok,message){if(!ok)throw new SwitchExportError("reference",`Switch export ${message}`)}function definition(value,id){const runs=["execution","hostJob","hostOccurrence"];if(!keys(value,["id","version","timeZone","rule","waitMs","lateAfterMs"],["retry","endAt",...runs]))return false;const present=runs.filter(run2=>value[run2]!==void 0);if(present.length!==1)return false;const run=value[present[0]];return value.id===id&&time2(value.version)&&value.version>=1&&text(value.timeZone)&&time2(value.waitMs)&&time2(value.lateAfterMs)&&optional(value.endAt,time2)&&optional(value.retry,retryPolicy)&&(present[0]==="execution"?object(run):keys(run,["type","input"])&&text(run.type))}function routineRecord(row){return keys(row,["id","ordinal","definition","lifecycle","status","nextAt"],["pending","calendarErrors","scheduleRetryAt","scheduleRetryCount","lastError"])&&text(row.id)&&time2(row.ordinal)&&definition(row.definition,row.id)&&optional(row.pending,pending=>definition(pending,row.id))&&oneOf(["active","paused","completed"])(row.lifecycle)&&oneOf(["ok","schedule_retrying","no_occurrence_within_horizon","calendar_error"])(row.status)&&(row.nextAt===null||time2(row.nextAt))&&optional(row.calendarErrors,errors=>Array.isArray(errors)&&errors.length>0&&errors.every(error=>keys(error,["at","message"],["wakeKey"])&&time2(error.at)&&typeof error.message==="string"&&optional(error.wakeKey,text)))&&optional(row.scheduleRetryAt,time2)&&optional(row.scheduleRetryCount,count=>time2(count)&&count>=1)&&optional(row.lastError,error=>keys(error,["code","message"])&&text(error.code)&&typeof error.message==="string")}function occurrenceRecord(row){return keys(row,["key","ordinal","routineId","definitionVersion","trigger","recordedAt","nextAt","job","executionSuperseded"],["conclusion","slotReplayCount"])&&text(row.key)&&time2(row.ordinal)&&text(row.routineId)&&time2(row.definitionVersion)&&row.definitionVersion>=1&&keys(row.trigger,["kind","plannedAt"])&&oneOf(["scheduled","catch_up"])(row.trigger.kind)&&time2(row.trigger.plannedAt)&&time2(row.recordedAt)&&(row.nextAt===null||time2(row.nextAt))&&(row.job===null||keys(row.job,["attempts"],["summary"])&&time2(row.job.attempts))&&typeof row.executionSuperseded==="boolean"&&optional(row.conclusion,conclusionText)&&optional(row.slotReplayCount,count=>time2(count)&&count>=1)}function retryPolicy(retry){if(!keys(retry,["maxAttempts","delaysMs","retryFailures"])||!Array.isArray(retry.delaysMs))return false;try{validateRetry(retry);return true}catch{return false}}var executionShape=row=>typeof row.started==="boolean"&&optional(row.attempt,object)&&optional(row.terminal,object)&&optional(row.messageReceipt,receiptShape);function intentRecord(row){return keys(row,["key","source","ordinal","taskId","generation","input","waitUntil","retry","submission","started","earlierExecutions","conclusion"],["handler","attempt","terminal","messageReceipt","preparationError","memoryBlocked","cancelReason","retryUntil"])&&text(row.key)&&oneOf(["user","bot","routine"])(row.source)&&optional(row.handler,text)&&time2(row.ordinal)&&digestText(row.taskId)&&time2(row.generation)&&time2(row.waitUntil)&&keys(row.input,["taskId","deviceId","payload"],["agentMessageContext"])&&text(row.input.deviceId)&&object(row.input.payload)&&object(row.input.payload.agentRef)&&text(row.input.payload.agentRef.agentId)&&retryPolicy(row.retry)&&row.generation<row.retry.maxAttempts&&oneOf(["reserved","uncertain","delivered"])(row.submission)&&executionShape(row)&&(row.submission!=="reserved"||row.generation===0&&!row.started&&row.attempt===void 0&&row.terminal===void 0&&row.messageReceipt===void 0)&&Array.isArray(row.earlierExecutions)&&row.earlierExecutions.length===row.generation&&row.earlierExecutions.every(entry=>keys(entry,["submission","started","attempt","terminal"],["messageReceipt"])&&oneOf(["uncertain","delivered"])(entry.submission)&&executionShape(entry))&&optional(row.preparationError,text)&&optional(row.memoryBlocked,blocked=>keys(blocked,["resume","reason"])&&oneOf(["queued","backoff"])(blocked.resume)&&typeof blocked.reason==="string")&&optional(row.cancelReason,oneOf(["expired","cancelled"]))&&optional(row.retryUntil,time2)&&optional(row.conclusion,conclusionText)}function checkContent(content,top){ensure(keys(content,top),"document keys");ensure(json2(content),"not JSON");ensure(content.version===SWITCH_EXPORT_VERSION,`version ${String(content.version)}`);ensure(content.source==="L"||content.source==="H","source");ensure(text(content.domain),"domain");ensure(time2(content.exportedAt),"exportedAt");ensure(Array.isArray(content.devices)&&content.devices.length>0,"devices");for(const device of content.devices){ensure(keys(device,["deviceId","frozenRevision"])&&text(device.deviceId)&&time2(device.frozenRevision)&&device.frozenRevision>=1,"device");}if(new Set(content.devices.map(device=>device.deviceId)).size!==content.devices.length){throw new SwitchExportError("duplicate","Switch export lists a device twice")}for(const section of LISTS)ensure(Array.isArray(content[section]),section);checkCollaboration(content);for(const row of content.archived){ensure(keys(row,["namespace","id","body"],["expiresAt"])&&text(row.namespace)&&text(row.id)&&optional(row.expiresAt,time2),"archived row");}for(const row of content.intents){if(object(row)&&row.conclusion===void 0)throw new SwitchExportError("open_work",`Switch export has an open intent: ${String(row.key)}`);ensure(intentRecord(row),"intent");}for(const row of content.routines){ensure(routineRecord(row),"routine");if(row.definition.execution!==void 0||row.pending?.execution!==void 0){throw new SwitchExportError("execution_routine",`Switch export has an execution routine, which K8 domains do not run: ${row.id}`)}}for(const row of content.occurrences)ensure(occurrenceRecord(row),"occurrence");for(const row of content.outbox){if(object(row)&&row.kind==="projection"){throw new SwitchExportError("projection_pending",`Switch export has a pending projection; flush it first: ${String(row.id)}`)}ensure(keys(row,["kind","occurrenceKey"])&&row.kind==="host-job"&&text(row.occurrenceKey),"outbox row");}for(const row of content.tombstones){ensure(keys(row,["kind","digest"],["expiresAt"])&&oneOf(["intent","row","slot","application"])(row.kind)&&digestText(row.digest)&&optional(row.expiresAt,time2),"tombstone");}checkReferences(content);}function checkReferences(content){for(const section of ["intents","routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal);if(new Set(ordinals).size!==ordinals.length)throw new SwitchExportError("duplicate",`Switch export ${section} repeats an ordinal`)}for(const section of ["routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal).sort((a,b)=>a-b);ensure(ordinals.every((ordinal,position)=>ordinal===position),`${section} ordinals are not their positions 0 to ${ordinals.length-1}`);}const occurrences=new Map(content.occurrences.map(row=>[row.key,row]));const occurrenceOfIntent=new Map(content.occurrences.map(row=>[occurrenceIntentKey(row.key),row.key]));const promoted=new Set;for(const row of content.intents){reference(row.taskId===taskId(row.key,row.generation),`intent ${row.key} has task id ${row.taskId}, not that of generation ${row.generation}`);ensure(row.input.taskId===row.taskId,`intent ${row.key} input is not frozen for its task id`);if(isOccurrenceIntentKey(row.key)){const key=occurrenceOfIntent.get(row.key);reference(key!==void 0,`intent ${row.key} names no occurrence of the export`);promoted.add(key);}}const routineById=new Map(content.routines.map(row=>[row.id,row]));const pendingJobs=new Set(content.outbox.map(row=>row.occurrenceKey));const slots=new Set;for(const row of content.occurrences){const routine=routineById.get(row.routineId);reference(routine!==void 0,`occurrence ${row.key} names no routine of the export: ${row.routineId}`);reference(row.key===hash$1([row.routineId,row.definitionVersion,row.trigger]),`occurrence ${row.key} is not the key of its routine slot and trigger`);const slot=routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt);if(slots.has(slot))throw new SwitchExportError("duplicate",`Switch export has two occurrences of the slot of ${row.key}`);slots.add(slot);ensure(!(promoted.has(row.key)&&row.conclusion!==void 0),`occurrence ${row.key} has an intent and its own conclusion`);if(routine.definition.hostJob){ensure(row.job!==null&&!promoted.has(row.key)&&pendingJobs.has(row.key)===(row.conclusion===void 0),`Host job occurrence ${row.key} is not promoted, and has a pending job exactly when it is open`);}else ensure(row.job===null,`occurrence ${row.key} has a Host job, but its routine runs a hook`);}const archivedReplies=new Map(content.archived.filter(row=>row.namespace==="replies").map(row=>[row.id,row.body]));const replyOf=taskId2=>content.collaboration.replies[taskId2]??archivedReplies.get(taskId2);for(const row of content.intents){const receipts=[...row.earlierExecutions.map(entry=>entry.messageReceipt),row.messageReceipt];for(let generation=0;generation<=row.generation;generation++){const reply=replyOf(taskId(row.key,generation)),receipt=receipts[generation];const same2=receipt===void 0?reply===void 0:object(reply)&&reply.messageId===receipt.messageId&&reply.contentHash===receipt.contentHash;if(!same2){throw new SwitchExportError("receipt_mismatch",`Switch export intent ${row.key} generation ${generation} has a message receipt that differs from its K8 reply`)}}}for(const row of content.outbox){reference(occurrences.get(row.occurrenceKey)?.job!=null,`Host job ${row.occurrenceKey} names no Host job occurrence`);}}var COLLABORATION_KEYS=["team","turns","budgets","delegations","batches","units","replies","schemas","questions","cards","rejected","audit","sequence"];var COLLABORATION_OPTIONAL=["inputs","inputBatches","channel","revision","commands","cardCalls","wouldDo","dreams"];function checkCollaboration(content){const state=content.collaboration;ensure(object(state),"collaboration state");if(state.topology!==void 0)throw new SwitchExportError("owner_record","Switch export carries the source owner records (topology)");if(state.hostIntents!==void 0)throw new SwitchExportError("owner_record","Switch export carries L hostIntents; each intent carries its handler");if(state.switchExport!==void 0||state.switchImport!==void 0){throw new SwitchExportError("owner_record","Switch export carries an L switch record (switchExport or switchImport)")}ensure(keys(state,COLLABORATION_KEYS,COLLABORATION_OPTIONAL)&&object(state.team)&&object(state.team.bots)&&Array.isArray(state.team.homeOperations)&&object(state.turns)&&optional(state.inputBatches,object)&&optional(state.cardCalls,object)&&optional(state.wouldDo,object),"collaboration state");for(const bot of Object.values(state.team.bots))ensure(object(bot)&&object(bot.execution)&&text(bot.execution.deviceId),"bot");for(const turn of Object.values(state.turns)){ensure(object(turn),"turn");if(turn.source==="routine")ensure(typeof turn.id==="string"&&isOccurrenceIntentKey(turn.id),`routine Turn ${String(turn.id)} names no occurrence`);}for(const batch of Object.values(state.inputBatches??{}))ensure(object(batch),"input batch");for(const row of Object.values(state.wouldDo??{}))ensure(object(row)&&text(row.turnId),"would-do row without turnId");for(const op of state.team.homeOperations)ensure(object(op),"home operation");const devices=new Set(content.devices.map(device=>device.deviceId));for(const bot of Object.values(state.team.bots)){if(!bot.archived&&!devices.has(bot.execution.deviceId)){throw new SwitchExportError("device_missing",`Bot ${bot.id} runs on device ${bot.execution.deviceId}, which the export does not move`)}}for(const turn of Object.values(state.turns)){if(!turn.conclusion)throw new SwitchExportError("open_work",`Switch export has an open Turn: ${turn.id}`)}for(const batch of Object.values(state.inputBatches??{})){if(batch.state==="open")throw new SwitchExportError("open_work",`Switch export has an open input batch: ${batch.id}`)}for(const op of state.team.homeOperations){if(op.status==="pending"&&op.sent===true){throw new SwitchExportError("home_sent",`Switch export has a pending Agent home write that may have been sent: ${op.sequence}`)}}if(Object.keys(state.cardCalls??{}).length)throw new SwitchExportError("card_call","Switch export has a card call in flight")}var SwitchExportedError=class extends Error{constructor(digest){super(`The domain was exported for a switch (${digest}); it writes nothing until the switch is aborted`);this.digest=digest;this.name="SwitchExportedError";}digest;code="switch_exported"};var SwitchImportedError=class extends Error{constructor(digest){super(`The domain holds the switch import ${digest}; commit it or discard it first`);this.digest=digest;this.name="SwitchImportedError";}digest;code="switch_imported"};var DeviceSwitchingError=class extends Error{constructor(deviceId,target,revision){super(`Device ${deviceId} is switching to ${target}`);this.deviceId=deviceId;this.target=target;this.revision=revision;this.name="DeviceSwitchingError";}deviceId;target;revision;code=DEVICE_SWITCHING};function exportMarkOf(value){const mark=value;const valid=typeof value==="object"&&value!==null&&Object.keys(value).sort().join(",")==="devices,digest,exportedAt"&&typeof mark.digest==="string"&&Number.isSafeInteger(mark.exportedAt)&&Array.isArray(mark.devices)&&mark.devices.length>0&&mark.devices.every(device=>!!device&&Object.keys(device).sort().join(",")==="deviceId,frozenRevision"&&typeof device.deviceId==="string"&&Number.isSafeInteger(device.frozenRevision)&&device.frozenRevision>0);if(!valid)throw new Error("Invalid switch export record");return mark}var DeviceModeError=class extends Error{constructor(deviceId,mode,revision){super(`Device ${deviceId} is owned by ${mode}`);this.deviceId=deviceId;this.mode=mode;this.revision=revision;this.name="DeviceModeError";}deviceId;mode;revision;code=DEVICE_NOT_BOUND;reason="mode"};function recordOf(state,deviceId){return state.topology&&Object.hasOwn(state.topology,deviceId)?state.topology[deviceId]:void 0}function deviceTopology(state,deviceId){const row=recordOf(state,deviceId);return row?{...row}:{mode:"L",revision:0}}function deviceRefusal(state,deviceId){const row=recordOf(state,deviceId);return row?.mode==="H"?"mode":row?.switching?"switching":void 0}function botDeviceRefusal(state,botId){const bot=state.team.bots[botId];return bot&&deviceRefusal(state,bot.execution.deviceId)}function admitDevice(state,deviceId){const row=recordOf(state,deviceId);if(row?.mode==="H")throw new DeviceModeError(deviceId,row.mode,row.revision);if(row?.switching)throw new DeviceSwitchingError(deviceId,row.switching,row.revision)}function admitBot(state,botId){const bot=state.team.bots[botId];if(bot)admitDevice(state,bot.execution.deviceId);}function switchWork(s,deviceId){const state=stateOf(s.application),onDevice=botId=>state.team.bots[botId]?.execution.deviceId===deviceId;return {intents:Object.values(s.intents).filter(intent=>!intent.conclusion&&intent.execution.deviceId===deviceId).map(intent=>intent.key),turns:Object.values(state.turns).filter(turn=>!turn.conclusion&&!s.intents[hash(turn.id)]&&onDevice(turn.botId)).map(turn=>turn.id),batches:Object.values(state.inputBatches??{}).filter(batch=>batch.state==="open"&&onDevice(batch.botId)).map(batch=>batch.id),homeOperations:state.team.homeOperations.filter(op=>op.status==="pending"&&homeSent(op)&&op.request.deviceId===deviceId).map(op=>op.sequence)}}function homeSent(op){return op.sent===true}function switchDrained(work){return !work.intents.length&&!work.turns.length&&!work.batches.length&&!work.homeOperations.length}function switchStep(s,deviceId,expectedRevision,step){const state=stateOf(s.application),row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(step==="freeze"?row.switching:!row.switching)throw new Error(`Device ${deviceId} is ${row.switching?"already":"not"} switching`);if(step==="commit"&&!switchDrained(switchWork(s,deviceId)))throw new Error(`Device ${deviceId} still has open work`);const next=step==="freeze"?{mode:"L",revision:row.revision+1,switching:"H"}:{mode:step==="commit"?"H":"L",revision:row.revision+1};Object.defineProperty(state.topology??={},deviceId,{value:next,enumerable:true,writable:true,configurable:true});return {...next}}function checkTopology(state){for(const[deviceId,row]of Object.entries(state.topology??{})){const keys2=Object.keys(row??{}).sort().join(",");const valid=!!row&&(row.mode==="L"||row.mode==="H")&&Number.isSafeInteger(row.revision)&&row.revision>0&&(row.switching===void 0?keys2==="mode,revision":row.switching==="H"&&row.mode==="L"&&keys2==="mode,revision,switching");if(!valid)throw new Error(`Invalid topology record for device ${deviceId}`)}}function refuseExported(state){if(state.switchExport)throw new SwitchExportedError(state.switchExport.digest)}function refuseImported(state){if(state.switchImport)throw new SwitchImportedError(state.switchImport.digest)}function checkSwitchRecords(state){refuseImported(state);if(state.switchExport!==void 0)exportMarkOf(state.switchExport);}var INTENT_KEYS=["id","key","source","execution","waitUntil","retry","agent","sequence","phase","generation","taskId","notBefore","attempts"];var INTENT_OPTIONAL=["memoryBlocked","preparationError","occurrence","retryUntil","cancelReason","conclusion"];var EXECUTION_KEYS=["input","submission","started"];var EXECUTION_OPTIONAL=["messageReceipt","attempt","terminal"];var ROUTINE_KEYS=["definition","lifecycle","status","next"];var ROUTINE_OPTIONAL=["pending","scheduleRetryAt","scheduleRetryCount","lastError","calendarErrors"];var OCCURRENCE_KEYS=["key","routineId","definitionVersion","trigger","wakeKey","recordedAt","nextAt","attempts"];var OCCURRENCE_OPTIONAL=["intentId","job","hook","conclusion","slotReplayCount"];var LEDGER_KEYS=["sequence","scanSequence","intents","executions","routines","occurrences","slots","outbox","applied","application","scanWake"];var LEDGER_OPTIONAL=["memory","ignoredWakes"];function refuse(reason,message){throw new SwitchExportError(reason,`Switch export source: ${message}`)}function derived(ok,message){if(!ok)refuse("reference",message);}function exact(value,required,optional2,what){const own=Object.keys(value);if(!required.every(key=>own.includes(key))||!own.every(key=>required.includes(key)||optional2.includes(key))){refuse("invalid",`${what} has keys ${own.join(", ")}`);}}var same=(a,b)=>canonical$1(a)===canonical$1(b);function defined(source){return Object.fromEntries(Object.entries(source).filter(([,value])=>value!==void 0))}function liveState(state){const live=structuredClone(state);delete live.topology;delete live.hostIntents;delete live.switchExport;delete live.switchImport;return live}function switchContent(dump,tenant,header){const s=dump.body;exact(s,LEDGER_KEYS,LEDGER_OPTIONAL,"The K4 ledger");if(s.memory&&Object.values(s.memory).some(rows=>rows&&Object.keys(rows).length)||dump.memoryTombstones.length){refuse("invalid","the domain has Agent memory state, which a switch does not move");}exact(s.application,["collaboration"],[],"The K4 application state");const state=stateOf(s.application);const handlers=state.hostIntents??{};const intents=[],tasks=new Set,succeeded=new Set;for(const[id,intent]of Object.entries(s.intents)){exact(intent,INTENT_KEYS,INTENT_OPTIONAL,`Intent ${intent.key}`);if(!intent.conclusion||intent.phase!=="settled")refuse("open_work",`intent ${intent.key} is open`);derived(id===hash(intent.key),`intent ${intent.key} is stored under ${id}`);derived(intent.agent===agentKey(tenant,intent.execution),`intent ${intent.key} queues under another tenant`);derived(intent.taskId===taskId(intent.key,intent.generation),`intent ${intent.key} task id is not that of its generation`);derived(isOccurrenceIntentKey(intent.key)?intent.occurrence!==void 0&&intent.key===occurrenceIntentKey(intent.occurrence):intent.occurrence===void 0,`intent ${intent.key} names occurrence ${String(intent.occurrence)}`);const current=s.executions[intent.taskId];if(!current)refuse("reference",`intent ${intent.key} has no execution`);exact(current,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${intent.taskId}`);derived(same(current.input,frozenInput(intent.execution,intent.taskId)),`intent ${intent.key} execution differs from its frozen input`);derived(intent.attempts===switchAttempts({submission:current.submission,generation:intent.generation}),`intent ${intent.key} attempts`);tasks.add(intent.taskId);const earlierExecutions=[];for(let generation=0;generation<intent.generation;generation++){const task=taskId(intent.key,generation),earlier=s.executions[task];if(!earlier)refuse("reference",`intent ${intent.key} has no execution of generation ${generation}`);exact(earlier,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${task}`);derived(same(earlier.input,frozenInput(intent.execution,task)),`intent ${intent.key} generation ${generation} input differs`);if(earlier.submission==="reserved")refuse("invalid",`intent ${intent.key} generation ${generation} was never begun`);earlierExecutions.push(defined({submission:earlier.submission,started:earlier.started,attempt:earlier.attempt,terminal:earlier.terminal,messageReceipt:earlier.messageReceipt}));tasks.add(task);}if(intent.conclusion==="succeeded")succeeded.add(intent.taskId);const handler=Object.hasOwn(handlers,intent.key)?handlers[intent.key].handler:void 0;intents.push(defined({key:intent.key,source:intent.source,handler,ordinal:intent.sequence,taskId:intent.taskId,generation:intent.generation,input:current.input,waitUntil:intent.waitUntil,retry:intent.retry,submission:current.submission,started:current.started,attempt:current.attempt,terminal:current.terminal,messageReceipt:current.messageReceipt,earlierExecutions,preparationError:intent.preparationError,memoryBlocked:intent.memoryBlocked,cancelReason:intent.cancelReason,retryUntil:intent.retryUntil,conclusion:intent.conclusion}));}for(const task of Object.keys(s.executions))derived(tasks.has(task),`execution ${task} belongs to no intent`);for(const key of Object.keys(handlers))derived(!!s.intents[hash(key)],`Host intent ${key} has no K4 intent`);derived(same(Object.keys(s.applied).sort(),[...succeeded].sort()),"K4 applied is not the succeeded current tasks");const routines=Object.entries(s.routines).map(([id,routine],ordinal)=>{exact(routine,ROUTINE_KEYS,ROUTINE_OPTIONAL,`Routine ${routine.definition.id}`);const{definition:definition2}=routine;derived(id===hash(definition2.id),`routine ${definition2.id} is stored under ${id}`);if(routine.next){exact(routine.next,["dedupKey","availableAt"],[],`Routine ${definition2.id} next wake`);const parsed=parseRoutineWakeKey(routine.next.dedupKey);derived(parsed?.id===definition2.id&&parsed.version===definition2.version&&parsed.at===routine.next.availableAt&&routine.next.dedupKey===routineWakeKey(definition2.id,definition2.version,routine.next.availableAt),`routine ${definition2.id} next wake key`);}return defined({id:definition2.id,ordinal,definition:definition2,pending:routine.pending,lifecycle:routine.lifecycle,status:routine.status,nextAt:routine.next?.availableAt??null,calendarErrors:routine.calendarErrors?.length?routine.calendarErrors:void 0,scheduleRetryAt:routine.scheduleRetryAt,scheduleRetryCount:routine.scheduleRetryCount,lastError:routine.lastError})});const slots=new Map,outbox=[];for(const[key,row]of Object.entries(s.outbox)){if(row.kind==="projection")refuse("projection_pending",`projection ${row.id} is not sent; flush it first`);if(row.kind==="intent")refuse("open_work",`intent ${row.intentId} has a pending submit`);if(row.kind!=="host-job")continue;exact(row,["kind","occurrenceKey"],[],`Host job ${row.occurrenceKey}`);derived(key===`host-job:${row.occurrenceKey}`,`Host job row ${key}`);outbox.push({kind:"host-job",occurrenceKey:row.occurrenceKey});}const occurrences=Object.entries(s.occurrences).map(([key,row],ordinal)=>{exact(row,OCCURRENCE_KEYS,OCCURRENCE_OPTIONAL,`Occurrence ${key}`);derived(row.key===key,`occurrence ${row.key} is stored under ${key}`);const parsed=parseRoutineWakeKey(row.wakeKey);derived(parsed?.id===row.routineId&&parsed.version===row.definitionVersion&&parsed.at===row.trigger.plannedAt&&row.wakeKey===routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt),`occurrence ${key} wake key`);slots.set(hash(row.wakeKey),key);const intent=s.intents[hash(occurrenceIntentKey(key))];derived(intent?row.intentId===intent.id:row.intentId===void 0,`occurrence ${key} intent id`);derived(row.attempts===switchAttempts(intent&&{submission:s.executions[intent.taskId].submission,generation:intent.generation}),`occurrence ${key} attempts`);derived(intent?row.conclusion===intent.conclusion:true,`occurrence ${key} conclusion differs from its intent's`);if(row.job===void 0===(row.hook===void 0))refuse("invalid",`occurrence ${key} is not exactly one of a Host job and a hook`);if(row.job)exact(row.job,["attempts"],["summary","executionSuperseded"],`Occurrence ${key} job`);if(row.hook)exact(row.hook,[],["executionSuperseded"],`Occurrence ${key} hook`);return defined({key,ordinal,routineId:row.routineId,definitionVersion:row.definitionVersion,trigger:row.trigger,recordedAt:row.recordedAt,nextAt:row.nextAt,job:row.job?defined({attempts:row.job.attempts,summary:row.job.summary}):null,executionSuperseded:!!(row.job??row.hook).executionSuperseded,conclusion:intent?void 0:row.conclusion,slotReplayCount:row.slotReplayCount})});derived(same(Object.entries(s.slots).sort(),[...slots].sort()),"K4 slots are not one per occurrence");return {version:SWITCH_EXPORT_VERSION,...header,collaboration:liveState(state),archived:dump.rows.map(row=>defined({namespace:row.namespace,id:row.id,body:row.value,expiresAt:row.expiresAt??void 0})),intents,routines,occurrences,outbox,tombstones:dump.tombstones.map(row=>defined({kind:row.kind,digest:row.identity,expiresAt:row.expiresAt??void 0}))}}function sealLedger(ledger,header){return sealSwitchExport(switchContent(ledger.dumpForSwitch(),ledger.tenant,header))}var admitted=new WeakSet;function checkLedgerWouldDo(ledger,state){refuseUnmigratedWouldDo(state);admitted.add(ledger);}function admitLedgerWouldDo(ledger,state){if(!admitted.has(ledger))checkLedgerWouldDo(ledger,state);}function writeLedger(ledger,apply){return ledger.transaction((s,rows)=>{admitLedgerWouldDo(ledger,stateOf(s.application));refuseImported(stateOf(s.application));const result=apply(s,rows);refuseExported(stateOf(s.application));return result})}function commitInLedger(ledger,request,ports){return writeLedger(ledger,(s,rows)=>commitInRows(stateOf(s.application),ledger.tenant,request,rows,ports(s)))}function commitInRows(state,scope,request,rows,ports){let admitted2;const result=commitCommand(state,request,{scope,recordCallbacks:false,archived:id=>rows.get("commands",id),admitted:ids=>{admitted2=ids;}},ports);refuseRetired(admitted2,(namespace,id)=>rows.isRetired(namespace,id));return result}function retainInLedger(ledger,input,limits){return writeLedger(ledger,(s,rows)=>retainRoots(stateOf(s.application),input,limits,{hasIntent:turnId=>!!s.intents[hash(turnId)],occurrenceOpen:turnId=>{const occurrence=s.occurrences[routineOccurrence({id:turnId})];return !!occurrence&&!occurrence.conclusion}},rows))}function prioritiseUser(s,state,user){const autonomous=autonomousIntentIds(Object.values(state.turns),dreamIntentIds(state));const plan=userFirst(Object.values(s.intents),user.id,autonomous,s.sequence);if(!plan)return;for(const{id,sequence}of plan.assignments)s.intents[id].sequence=sequence;s.sequence=plan.sequence;}function syncTurnInLedger(ledger,s,rows,turn,options){const facts={intent:intentFacts(s).intent,executionStarted:id=>{const row=s.intents[hash(id)];return !!row&&!!s.executions[row.taskId]?.started},preparationError:id=>s.intents[hash(id)]?.preparationError,retired:id=>turnIntentRetired(ledger,s,turn,options.now)?"result_retired":retiredIdentity("turn",id,(namespace,row)=>rows.isRetired(namespace,row))?"turn_retired":void 0,deviceRefusal:botId=>botDeviceRefusal(stateOf(s.application),botId),dreamHold:botId=>dreamHolds(s).get(botId)};refuseImported(stateOf(s.application));const step=syncTurn(stateOf(s.application),turn,facts,options,(key,value)=>project(s,key,value));const more=applyStep();refuseExported(stateOf(s.application));return more;function applyStep(){switch(step?.kind){case "freeze":{const intent=enqueue(s,ledger.tenant,step.input);if(step.input.source==="user")prioritiseUser(s,stateOf(s.application),intent);return true}case "routine":promoteOccurrence(s,ledger.tenant,routineOccurrence(turn),step.execution);return true;case "cancel":s.intents[hash(turn.id)].cancelReason="cancelled";return false;case "ended":return turn.source==="routine"&&concludeRoutineTurn(s,turn);default:return false}}}async function callCardsInLedger(ledger,call){for(const old of Object.values(stateOf(ledger.snapshot().application).cards)){if(!cardCallDue(old))continue;const claimed=writeLedger(ledger,s=>{const state=stateOf(s.application),card=state.cards[old.id];if(!card||!cardCallDue(card))return false;const calls=state.cardCalls??={};if(!calls[card.id])return calls[card.id]=true;delete calls[card.id];settleCardCall(card,{error:new Error(CONNECTOR_OUTCOME_UNKNOWN)});return false});if(!claimed)continue;let outcome;try{outcome={result:await call(old)};}catch(error){outcome={error};}writeLedger(ledger,s=>{const state=stateOf(s.application);delete state.cardCalls[old.id];settleCardCall(state.cards[old.id],outcome);});}}function advanceRooms(s,state,now,add,publish){const facts={};for(const id of Object.keys(state.team.seats)){const intent=s.intents[hash(id)],execution=intent&&s.executions[intent.taskId];facts[id]={admitted:!!intent,started:!!execution?.started,conclusion:intent?.conclusion};}for(const seatId of advanceRoomSeats(state,facts,now,add,publish))s.intents[hash(seatId)].cancelReason="cancelled";}function advanceRoomsAndTurns(s,state,now,step,publish){const released=()=>Object.values(state.team.seats).filter(seat=>seat.released).length;let changed=false,before;do{advanceRooms(s,state,now,(id,botId,request)=>addTurn(state,seatTurn(id,botId,request)),publish);before=released();for(const turn of Object.values(state.turns))changed=step(turn)||changed;}while(released()>before);return changed}
8
+
9
+ export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, K8_FORMAT, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitBot, admitDevice, admitUserInput2 as admitUserInput, advanceRoomsAndTurns, botCompactVeto, botDeviceRefusal, botLedgerOptions, botOutcomePorts, callCardsInLedger, checkDreamInstruction, checkLedgerWouldDo, checkSwitchRecords, checkTopology, cleanReplyTokens, commitInLedger, commitInRows, deliveryRoute, deviceRefusal, deviceTopology, dreamHolds, dreamIntentIds, dreamPolicy, dreamReads, dreamYield, echoCandidates, enablePush, exportMarkOf, homeSent, inboundDisposition, inboundDispositions, inboundDispositionsOf, intentRows, observeDevices2 as observeDevices, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseExported, refuseRoute, rememberFilteredInbound, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelegations2 as settleDelegations, settleDelivery, startDelivery, switchAttempts, switchContent, switchDrained, switchStep, switchWork, syncDreams, syncHead, syncTail, syncTurnInLedger, unknownDelivery, verifySwitchExport, writeLedger };
10
+ //# sourceMappingURL=chunk-DDKTPJ7B.js.map
11
+ //# sourceMappingURL=chunk-DDKTPJ7B.js.map