@byok-sdk/bot-collaboration 0.0.0-stage → 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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2075 -2
  3. package/dist/adapter-steps.d.ts +49 -0
  4. package/dist/channel.d.ts +111 -0
  5. package/dist/chunk-33YA66U7.js +7 -0
  6. package/dist/chunk-33YA66U7.js.map +1 -0
  7. package/dist/chunk-6Y2B2XCP.js +12 -0
  8. package/dist/chunk-6Y2B2XCP.js.map +1 -0
  9. package/dist/chunk-QZRWFFHM.js +12 -0
  10. package/dist/chunk-QZRWFFHM.js.map +1 -0
  11. package/dist/chunk-ZX6C5U2S.js +27 -0
  12. package/dist/chunk-ZX6C5U2S.js.map +1 -0
  13. package/dist/coalesce.d.ts +18 -0
  14. package/dist/commit-vectors.test-support.d.ts +173 -0
  15. package/dist/commit.d.ts +53 -0
  16. package/dist/compaction.d.ts +13 -0
  17. package/dist/delegation.d.ts +12 -0
  18. package/dist/delivery-routing.d.ts +63 -0
  19. package/dist/delivery-vectors.test-support.d.ts +78 -0
  20. package/dist/delivery.d.ts +20 -0
  21. package/dist/dream.d.ts +88 -0
  22. package/dist/home-projections.d.ts +5 -0
  23. package/dist/host-kit.d.ts +60 -0
  24. package/dist/host-kit.js +11 -0
  25. package/dist/host-kit.js.map +1 -0
  26. package/dist/host.d.ts +472 -0
  27. package/dist/inbound.d.ts +17 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +19 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/k4-fixtures.test-support.d.ts +10 -0
  32. package/dist/l-test-host.test-support.d.ts +72 -0
  33. package/dist/migration.d.ts +251 -0
  34. package/dist/model.d.ts +89 -0
  35. package/dist/persona.d.ts +2 -0
  36. package/dist/retention-vectors.test-support.d.ts +17 -0
  37. package/dist/retention.d.ts +61 -0
  38. package/dist/rooms.d.ts +22 -0
  39. package/dist/routine-vectors.test-support.d.ts +81 -0
  40. package/dist/routines.d.ts +110 -0
  41. package/dist/rules/autonomy.d.ts +67 -0
  42. package/dist/rules/cards.d.ts +31 -0
  43. package/dist/rules/coalesce.d.ts +111 -0
  44. package/dist/rules/commands.d.ts +306 -0
  45. package/dist/rules/commit.d.ts +82 -0
  46. package/dist/rules/compaction.d.ts +33 -0
  47. package/dist/rules/context.d.ts +484 -0
  48. package/dist/rules/delegation.d.ts +366 -0
  49. package/dist/rules/due.d.ts +15 -0
  50. package/dist/rules/frame.d.ts +4 -0
  51. package/dist/rules/history.d.ts +34 -0
  52. package/dist/rules/inbound.d.ts +53 -0
  53. package/dist/rules/index.d.ts +13 -0
  54. package/dist/rules/index.js +4 -0
  55. package/dist/rules/index.js.map +1 -0
  56. package/dist/rules/message.d.ts +31 -0
  57. package/dist/rules/outcome.d.ts +45 -0
  58. package/dist/rules/priority.d.ts +52 -0
  59. package/dist/rules/rooms.d.ts +187 -0
  60. package/dist/rules/schema.d.ts +110 -0
  61. package/dist/rules/sync.d.ts +157 -0
  62. package/dist/rules/team.d.ts +119 -0
  63. package/dist/rules/turn.d.ts +129 -0
  64. package/dist/schema.d.ts +154 -0
  65. package/dist/store-compatibility.d.ts +3 -0
  66. package/dist/switch.d.ts +53 -0
  67. package/dist/team-model.d.ts +54 -0
  68. package/dist/team.d.ts +56 -0
  69. package/dist/testing.d.ts +6 -0
  70. package/dist/testing.js +20 -0
  71. package/dist/testing.js.map +1 -0
  72. package/dist/toolset-policy.d.ts +2 -0
  73. package/dist/topology.d.ts +49 -0
  74. package/package.json +80 -4
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ import { checkTopology, checkSwitchRecords, wouldDoNeedsMigration, botCompactVeto, dreamPolicy, checkDreamInstruction, deviceRefusal, admitBot, refuseExported, recordDream, writeLedger, echoCandidates, acceptDeliveryEcho, cleanReplyTokens, rememberInbound, rememberFilteredInbound, routeTerminal, runHostIntentHandler, outcomeFailure, IntentOutcomeError, botOutcomePorts, intentRows, admitDevice, promoteStaged, queueDelivery, commitInLedger, resendUnknown, revokePush, enablePush, admitUserInput, commitInRows, inboundDispositionsOf, deviceTopology, switchStep, switchWork, DeviceModeError, switchDrained, SwitchExportError, sealSwitchExport, switchContent, sealLedger, retainInLedger, recoverDelivery, syncHead, reconcileDreamRoutines, advanceRoomsAndTurns, syncTurnInLedger, syncDreams, botDeviceRefusal, settleDelegations, syncTail, callCardsInLedger, readbackDelivery, deliveryRoute, refuseRoute, startDelivery, settleDelivery, unknownDelivery, dreamReads, homeSent, observeDevices } from './chunk-QZRWFFHM.js';
2
+ export { botCompactVeto } from './chunk-QZRWFFHM.js';
3
+ import { stateOf, OldCollaborationStateError, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-6Y2B2XCP.js';
4
+ import { DEVICE_CONCURRENCY, admitDeviceSlot } from './chunk-33YA66U7.js';
5
+ import { admitBotToolsets, HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS, DEFAULT_HANDOFF_BUDGETS, coalescePolicy, outcomeOffer, outcomeSchema, DEFAULT_INSTRUCTION_MAX_BYTES, minimumInstructionBytes, SYSTEM_PROMPT, REPLY_UNCERTAIN_AFTER_MS, DEFAULT_CANCEL_GRACE_MS, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-ZX6C5U2S.js';
6
+ export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-ZX6C5U2S.js';
7
+ import { mkdtempSync, copyFileSync, rmSync, statSync } from 'fs';
8
+ import { tmpdir } from 'os';
9
+ import { resolve, join, basename } from 'path';
10
+ import { HostLedger, hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, WakeDispatchError, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
11
+ import { randomUUID } from 'crypto';
12
+ import { buildHandoffPack, ToolsetIdSchema } from '@byok-sdk/protocol';
13
+ import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
14
+
15
+ function inspectLedger(path,tenant){const file=resolve(path),store="bot-collaboration-ledger";const stat=statOrUndefined(file);if(!stat)return {store,path:file,verdict:"absent",reason:"No ledger file at this path"};if(!stat.isFile())return {store,path:file,verdict:"rejected",reason:"The ledger path is not a regular file"};const directory=mkdtempSync(join(tmpdir(),"byok-ledger-check-"));try{const copy=join(directory,basename(file)),suffixes=["","-wal","-journal"];const fingerprint=suffix=>{const s=statOrUndefined(file+suffix);return s&&`${s.size}:${s.mtimeMs}:${s.ino}`};const before=suffixes.map(fingerprint);suffixes.forEach((suffix,i)=>{if(before[i]!==void 0)copyFileSync(file+suffix,copy+suffix);});if(suffixes.some((suffix,i)=>fingerprint(suffix)!==before[i]))throw new Error(`${file} changed while it was being checked; stop its owner and check again`);try{const{DatabaseSync}=process.getBuiltinModule("node:sqlite");const db=new DatabaseSync(copy,{readOnly:true});try{if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'").get())throw new Error("Not a Host ledger")}finally{db.close();}const ledger=new HostLedger(copy,tenant);try{const state=stateOf(ledger.snapshot().application);checkTopology(state);checkSwitchRecords(state);if(state.switchExport)return {store,path:file,verdict:"accepted",reason:"This build opens the exported ledger; run migrateWouldDo if the switch is aborted"};return wouldDoNeedsMigration(state)?{store,path:file,verdict:"migration-required",reason:"Would-do rows lack turnId; run migrateWouldDo before serving"}:{store,path:file,verdict:"accepted",reason:"This build opens the ledger"}}finally{ledger.close();}}catch(error){const code=error?.code;return {store,path:file,verdict:error instanceof OldCollaborationStateError?"new-path-repair":"rejected",...typeof code==="string"?{code}:{},reason:error instanceof Error?error.message:String(error)}}}finally{rmSync(directory,{recursive:true,force:true});}}function statOrUndefined(file){try{return statSync(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}function ownReadOnlyToolsets(ids=[]){if(!Array.isArray(ids))throw new Error("readOnlyToolsets must be an array of logical toolset IDs");if(ids.length>64||new Set(ids).size!==ids.length)throw new Error("Invalid read-only toolset policy");for(const id of ids)ToolsetIdSchema.parse(id);return Object.freeze([...ids])}async function flushHomes(server,ledger,now){const busy=botId=>Object.values(ledger.snapshot().intents).some(intent=>!intent.conclusion&&intent.execution.payload.agentRef.agentId===botId);const operation=(s,sequence)=>stateOf(s.application).team.homeOperations.find(o=>o.sequence===sequence);const snapshot=stateOf(ledger.snapshot().application),team=snapshot.team;for(const pending of team.homeOperations.filter(o=>o.status==="pending").sort((a,b)=>a.sequence-b.sequence)){const op=homeHead(team,pending.sequence,busy);if(!op)continue;if(deviceRefusal(snapshot,op.request.deviceId)&&!homeSent(op))continue;try{if(!server.enqueueAgentHomeProjection||!server.readAgentHomeProjection)throw new Error("Home projection API required");let terminal;for(const candidate of homeRequests(op)){terminal=checkHomeReadback(candidate,await server.readAgentHomeProjection(candidate.deviceId,candidate.payload.agentRef,candidate.payload.requestId));if(terminal)break}if(!terminal){const request=ledger.transaction(s=>{if(deviceRefusal(stateOf(s.application),op.request.deviceId))return void 0;const row=operation(s,op.sequence);row.sent=true;return planHomeRetry(row,now())});if(!request)continue;await server.enqueueAgentHomeProjection(request);ledger.transaction(s=>homeEnqueued(operation(s,op.sequence),now()));continue}const settled=terminal;ledger.transaction(s=>applyHomeTerminal(stateOf(s.application),operation(s,op.sequence),settled,(id,value)=>project(s,id,value)));}catch(error){ledger.transaction(s=>failHomeFlush(operation(s,op.sequence),error));}}}function hostIntent(state,key){return state.hostIntents&&Object.hasOwn(state.hostIntents,key)?state.hostIntents[key]:void 0}function openIntent(intents,key){const intent=intents[hash(key)];if(!intent)throw new HostIntentError(key,"unknown_intent",`Unknown intent: ${key}`);if(intent.conclusion)throw new HostIntentError(key,"already_settled",`Intent already settled: ${key}`);return intent}function bounded(read,ms){let timer;const late=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("History read timed out")),Math.max(0,ms));});return Promise.race([read,late]).finally(()=>clearTimeout(timer))}function awaitsOffer(ledger,state,turn){const bot=state.team.bots[turn.botId];return !turn.conclusion&&!turn.held&&!ledger.intents[hash(turn.id)]&&turn.status!=="failed"&&!!bot&&!inactive(bot)&&bot.readyRevision===bot.revision}function dispatchRow(state,row){const execution=state.executions[row.taskId];return {id:row.id,agent:row.agent,sequence:row.sequence,phase:row.phase,attempts:row.attempts,source:row.source,deviceId:row.execution.deviceId,occupies:row.phase==="inflight"&&(execution?.submission==="delivered"||execution?.attempt!==void 0||execution?.started===true)}}function admitCommand(state,command){for(const botId of commandBots(state,command))admitBot(state,botId);}function valueOf(result){if(result.disposition.outcome!=="accepted")throw new Error("Unexpected refused command");return result.disposition.value}function turnOf(result){if(result.disposition.outcome!=="accepted"||typeof result.disposition.value!=="string")throw new Error("Input command has no Turn id");return result.disposition.value}var BotCollaboration=class{constructor(server,ledger,options){this.server=server;this.ledger=ledger;this.options=options;if(!options.botId||options.execution.payload.agentRef.agentId!==options.botId)throw new Error("Select this Bot Agent");if(ledger.compactVeto!==botCompactVeto)throw new Error("Open the Host ledger with { compactVeto: botCompactVeto }");options=this.options={...options,execution:structuredClone(options.execution),...options.models===void 0?{}:{models:structuredClone(options.models)},readOnlyToolsets:ownReadOnlyToolsets(options.readOnlyToolsets)};admitBotToolsets(options.execution,options.readOnlyToolsets);for(const model of Object.values(this.models()))admitBotToolsets(model,options.readOnlyToolsets);const persisted=ledger.snapshot(),team=stateOf(persisted.application).team;checkTopology(stateOf(persisted.application));checkSwitchRecords(stateOf(persisted.application));if(options.team==="external"?!team.external&&Object.keys(team.bots).length:team.external){throw new Error(`This ledger has ${team.external?"an external":"a local"} team`)}if(options.persona!==void 0&&(options.persona!=="external"||options.team!=="external")){throw new Error("The Host persona mode needs team: 'external'")}if(team.external&&!!team.external.persona!==(options.persona==="external")){throw new Error(`This ledger has ${team.external.persona?"Host":"K8"} persona projections`)}if(options.rooms!==void 0&&(options.rooms!=="external"||options.team!=="external")){throw new Error("The external rooms mode needs team: 'external'")}if(team.external&&!!team.external.rooms!==(options.rooms==="external")){throw new Error(`This ledger has ${team.external.rooms?"external":"local"} rooms`)}for(const intent of Object.values(persisted.intents)){if(intent.conclusion)continue;admitBotToolsets(intent.execution,options.readOnlyToolsets);const execution=persisted.executions[intent.taskId];if(execution)admitBotToolsets(execution.input,options.readOnlyToolsets);}this.hostIntentHandlers=new Map(Object.entries(options.hostIntents??{}));this.hostIntentMessageHandlers=new Map(Object.entries(options.hostIntentMessages??{}));for(const name of this.hostIntentMessageHandlers.keys()){if(!this.hostIntentHandlers.has(name))throw new Error(`A Host intent message handler needs the Host intent handler ${name}`)}for(const[key,{handler}]of Object.entries(stateOf(persisted.application).hostIntents??{})){const intent=persisted.intents[hash(key)];if(intent&&intent.conclusion===void 0&&!this.hostIntentHandlers.has(handler)){throw new Error(`An open Host intent needs the handler ${handler}`)}if(intent&&intent.conclusion===void 0&&intent.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`An open Host intent needs the message handler ${handler}`)}}this.owner={id:options.owner??"owner",kind:"human"};if(!verified(this.owner))throw new Error("Invalid owner principal");this.now=()=>time((options.now??Date.now)());this.connectorTimeoutMs=time(options.connectorTimeoutMs??3e4);if(this.connectorTimeoutMs<1||this.connectorTimeoutMs>2147483647)throw new Error("Invalid connector timeout");this.deliveryTimeoutMs=time(options.channel?.sendTimeoutMs??15e3);if(this.deliveryTimeoutMs<1||this.deliveryTimeoutMs>2147483647)throw new Error("Invalid delivery timeout");this.historyTimeoutMs=time(options.historyTimeoutMs??1e4);if(this.historyTimeoutMs<1||this.historyTimeoutMs>2147483647)throw new Error("Invalid history timeout");this.contextMaxBytes=time(options.contextMaxBytes??HISTORY_MAX_BYTES);this.contextTurnLimit=time(options.contextTurnLimit??HISTORY_MAX_ITEMS);if(this.contextMaxBytes<1||this.contextTurnLimit<1)throw new Error("Invalid ContextPack limits");this.handoff=options.handoff??DEFAULT_HANDOFF_BUDGETS;buildHandoffPack([],this.handoff);if(options.coalesce)this.coalesce=coalescePolicy(options.coalesce,this.contextMaxBytes);this.offer=outcomeOffer(options.outcome??{});outcomeSchema(options.botId,stateOf({}),void 0,Object.keys(this.models()),[],this.offer);this.instructionMaxBytes=time(options.instructionMaxBytes??DEFAULT_INSTRUCTION_MAX_BYTES);const minimum=minimumInstructionBytes(SYSTEM_PROMPT);if(this.instructionMaxBytes<minimum)throw new Error(`instructionMaxBytes must be at least ${minimum}`);this.dreaming=dreamPolicy(options.dreaming);if(this.dreaming)checkDreamInstruction(this.instructionMaxBytes);this.timers={cancelGraceMs:time(options.cancelGraceMs??DEFAULT_CANCEL_GRACE_MS),uncertainAfterMs:time(options.uncertainAfterMs??REPLY_UNCERTAIN_AFTER_MS)};if(this.timers.cancelGraceMs<1||this.timers.uncertainAfterMs<1)throw new Error("Invalid delegation timers");this.deviceConcurrency=time(options.deviceConcurrency??DEVICE_CONCURRENCY);if(this.deviceConcurrency<1)throw new Error("Invalid device concurrency");this.core=new HostExecutionCore(server,ledger,{now:this.now,reconcileMs:options.reconcileMs??100,nextOccurrence:routineCalendar,hostJobExecution:"fail",executionRoutines:"refuse",...options.hostJobs?{hostJobs:options.hostJobs}:{},...options.onOutbox?{onOutbox:options.onOutbox}:{},occurrenceHooks:{[BOT_ROUTINE]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);this.commitCallback(state,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state,run)});},[BOT_DREAM]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);recordDream(state,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),admitSubmit:(intent,state)=>!deviceRefusal(stateOf(state.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state=stateOf(s.application);if(options.team==="external"){state.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state.team.bots[options.botId]??={id:options.botId,name:"Main Bot",role:"Team owner",persona:"",model:Object.keys(this.models())[0],mainBot:true,archived:false,autonomy:DEFAULT_AUTONOMY,revision:options.execution.payload.agentRef.profileRevision,readyRevision:options.execution.payload.agentRef.profileRevision,execution:structuredClone(options.execution)};}applyModels(state,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;now;connectorTimeoutMs;deliveryTimeoutMs;historyTimeoutMs;contextMaxBytes;contextTurnLimit;handoff;dreaming;instructionMaxBytes;deviceConcurrency;timers;coalesce;offer;owner;unread=new Set;hostIntentHandlers;hostIntentMessageHandlers;intentFailures=new Map;auditedFailures=new Map;models(){return this.options.models??{default:this.options.execution}}setModels(models){return this.exclusive(async()=>{const next=structuredClone(models);outcomeSchema(this.options.botId,stateOf({}),void 0,Object.keys(next),[],this.offer);this.write(s=>applyModels(stateOf(s.application),next,this.options.readOnlyToolsets??[]));this.options.models=next;await this.process();})}snapshot(){return stateOf(this.ledger.snapshot().application)}write(apply){return writeLedger(this.ledger,apply)}exclusive(work){if(this.closed)return Promise.reject(new Error("Bot Host is closed"));const next=this.chain.then(work);this.chain=next.catch(()=>{});return next}input(key,request,botId=this.options.botId,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"input",botId);const result=this.commitOwner(hash(["input",botId,key]),{kind:"input",botId,key,request,sender:principal.id});await this.process();return turnOf(result)})}inputRoot(key,botId=this.options.botId){const id=hash(["input",botId,key]),commands=stateOf(this.ledger.snapshot().application).commands;const record=commands&&Object.hasOwn(commands,id)?commands[id]:this.ledger.transaction((_,rows)=>rows.get("commands",id));return record&&turnOf(record.result)}async receive(message){if(this.closed)throw new Error("Bot Host is closed");const kind=classifyInbound(message,this.owner.id,this.options.channel?.self),{channel,conversation,platformMessageId,sender}=message;if(kind==="echo"){this.write(s=>{const state=stateOf(s.application),matches=echoCandidates(state,message);if(matches.length!==1||!acceptDeliveryEcho(matches[0],platformMessageId))state.audit.push(`Delivery unmatched_echo: ${channel} ${platformMessageId}`.slice(0,1024));cleanReplyTokens(s,state,this.now());});return {kind}}if(kind==="owner_input"||kind==="room_input")return this.exclusive(async()=>{const principal=kind==="owner_input"?this.ownerOnly([sender],"input",conversation.id):this.verifiedOnly(sender,"roomInput",conversation.id);const key=inboundKey(message);const command=kind==="owner_input"?{kind:"receive",inbound:kind,key,botId:conversation.id,request:message.text,sender:principal.id}:{kind:"receive",inbound:kind,key,roomId:conversation.id,text:message.text,mentions:this.seatMentions(conversation.id,principal,message.mentions),from:principal.id};const result=this.commitOwner(hash(["receive",key]),command,(_s,state)=>({remember:root=>rememberInbound(state,message,root)}));await this.process();return {kind,id:turnOf(result)}});if(kind==="bot_background"){return {kind,id:await this.roomInput(inboundKey(message),conversation.id,message.text,message.mentions,sender)}}const who=verified(sender)?` ${sender.kind}:${sender.id}`:"";const filtered=kind==="unverified_sender"||kind==="not_owner"?kind:void 0;await this.exclusive(async()=>this.write(s=>{const state=stateOf(s.application);if(filtered)rememberFilteredInbound(state,message,filtered);state.audit.push(`Inbound ${kind}: ${channel} ${conversation.kind}:${conversation.id} ${platformMessageId}${who}`.slice(0,1024));}));return {kind}}enablePushRoute(conversation,channel,target,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"enablePushRoute",conversation.id);if(!this.options.channel)throw new Error("Channel is not configured");return valueOf(this.commitKeyless({kind:"enable_push_route",conversation,channel,target,owner:principal.id}))})}revokePushRoute(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"revokePushRoute",id);this.commitKeyless({kind:"revoke_push_route",routeId:id});await this.process();})}resendDelivery(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"resendDelivery",id);if(!this.options.channel)throw new Error("Channel is not configured");const next=valueOf(this.commitKeyless({kind:"resend_delivery",deliveryId:id}));await this.process();return next})}audit(line){this.write(s=>{stateOf(s.application).audit.push(line.slice(0,1024));});}verifiedOnly(principal,action,target){if(verified(principal))return principal;this.audit(`Action refused unverified_sender: ${action} ${target}`);throw new Error(`unverified_sender: ${action} needs a verified principal`)}seatMentions(roomId,principal,mentions){if(!principal||isOwner(principal,this.owner.id))return mentions;if(principal.kind==="bot")return [];const room=this.snapshot().team.rooms[roomId];return room&&memberMentions(room)==="ignore"?[]:mentions}ownerOnly(by,action,target){const principal=this.verifiedOnly(by.length?by[0]:this.owner,action,target);if(isOwner(principal,this.owner.id))return principal;this.audit(`Action refused not_owner: ${action} ${target} ${principal.kind}:${principal.id}`);throw new Error(`not_owner: ${action} needs the owner principal`)}applyOutcome(document,tx){const state=stateOf(tx.application),taskId=tx.intent.taskId,key=tx.intent.key;refuseExported(state);try{const route=routeTerminal(state,key,hostIntent(state,key)?.handler);if(route.kind==="host_intent")runHostIntentHandler(key,route.handler,this.hostIntentHandlers.get(route.handler)?.bind(null,document,tx));else if(route.kind==="bot_turn"){try{this.commitBotOutcome(state,key,taskId,document,tx);}catch(cause){throw outcomeFailure(key,cause)}}}catch(error){if(error instanceof IntentOutcomeError)this.intentFailures.set(key,error);throw error}}commitBotOutcome(state,key,taskId,document,tx){this.commitCallback(state,tx.rows,taskId,{kind:"outcome",turnId:key,taskId,document},{publish:tx.publish,...this.deliverPort(state,taskId),outcome:{committed:{intent:key2=>intentRows(this.ledger.snapshot()).intent(key2)},...botOutcomePorts({taskId,routines:tx.routines,roomPosts:!!this.options.roomHistory,manage:(turn,outcome,managed)=>applyManagement(state,turn.botId,taskId,outcome,this.models(),managed,this.options.readOnlyToolsets)})}});}reportIntentFailures(){const failures=[...this.intentFailures.values()],fresh=failures.filter(f=>this.auditedFailures.get(f.key)!==f.message);if(fresh.length){this.write(s=>{const state=stateOf(s.application);for(const f of fresh)state.audit.push(`Intent outcome refused ${f.code}: ${f.key} ${f.message}`.slice(0,1024));});for(const f of fresh)this.auditedFailures.set(f.key,f.message);}return failures[0]}enqueueHostIntent(input,handler){return this.exclusive(async()=>{if(!this.hostIntentHandlers.has(handler))throw new Error(`Unknown Host intent handler: ${handler}`);if(isOccurrenceIntentKey(input.key))throw new Error("Host intent identity conflict: the key is an occurrence");if(input.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`Host intent handler ${handler} has no message handler`)}admitBotToolsets(input.execution,this.options.readOnlyToolsets);this.write(s=>{const state=stateOf(s.application),owner=hostIntent(state,input.key);if(Object.hasOwn(state.turns,input.key))throw new Error("Host intent identity conflict: the key is a Bot Turn");if(owner?owner.handler!==handler:s.intents[hash(input.key)])throw new Error("Host intent identity conflict");if(!owner)admitDevice(state,input.execution.deviceId);enqueue(s,this.ledger.tenant,input);Object.defineProperty(state.hostIntents??={},input.key,{value:{handler},enumerable:true,writable:true,configurable:true});});await this.process();return this.core.intent(input.key)})}cancelHostIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntent",key);const snapshot=this.ledger.snapshot(),state=stateOf(snapshot.application),intent=snapshot.intents[hash(key)];const settled=hostIntentCancelAnswer(key,Object.hasOwn(state.turns,key),hostIntent(state,key)&&intent);if(settled)return {key,...settled};const dispatch=await this.core.cancel(key);try{await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}if(intent.phase==="inflight")return {key,result:"cancel_pending",...dispatch};const conclusion=this.core.intent(key)?.conclusion;return {key,result:"cancelled",...conclusion===void 0?{}:{conclusion},...dispatch}})}cancelHostIntents(keys,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntents",keys.join(" "));const seen=new Set;for(const key of keys){if(seen.has(key))throw new Error(`Duplicate Host intent key: ${key}`);seen.add(key);}return this.write(s=>{const state=stateOf(s.application),rejected=[];for(const key of keys){const intent=s.intents[hash(key)];if(Object.hasOwn(state.turns,key))rejected.push({key,code:"not_host_intent"});else if(!hostIntent(state,key)||!intent)rejected.push({key,code:"unknown_intent"});else if(!intent.conclusion&&intent.phase==="inflight")rejected.push({key,code:"inflight"});}if(rejected.length){const first=rejected[0];const message=first.code==="inflight"?"The intent is in flight: use cancelHostIntent":first.code==="not_host_intent"?"The key is a Bot Turn: use cancelTurn":"No Host intent has this key";throw new HostIntentError(first.key,first.code,message,rejected)}return keys.map(key=>{const intent=s.intents[hash(key)];if(intent.conclusion)return {key,result:"already_settled",conclusion:intent.conclusion};intent.cancelReason="cancelled";settle(s,intent,"cancelled");return {key,result:"cancelled",conclusion:"cancelled"}})})})}failStuckIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"failStuckIntent",key);openIntent(this.ledger.snapshot().intents,key);this.intentFailures.clear();const drained=await this.core.drain().then(()=>void 0,error=>({error}));const refused=this.intentFailures.get(key);this.write(s=>{const intent=openIntent(s.intents,key);if(!refused)throw drained?drained.error:new HostIntentError(key,"not_stuck",`Intent is not stuck: ${key} has no refused terminal`);settle(s,intent,"failed");if(refused.code==="outcome_failed")stateOf(s.application).turns[key].settleCode=refused.code;stateOf(s.application).audit.push(`Intent failed by owner ${refused.code}: ${key} ${refused.message}`.slice(0,1024));});this.intentFailures.delete(key);this.auditedFailures.delete(key);await this.process();})}deliverPort(state,taskId){if(!this.options.channel)return {};return {deliver:(turn,key,text,staged)=>queueDelivery(this.ledger.snapshot(),state,turn,taskId,key,text,this.now(),staged)?.id,promote:id=>promoteStaged(state,id)}}commitOwner(commandId,command,extra){return commitInLedger(this.ledger,{scope:this.ledger.tenant,commandId,command},s=>{const state=stateOf(s.application);return {now:this.now,admit:next=>admitCommand(state,next),publish:(key,value)=>project(s,key,value),intents:intentRows(s),admitInput:fields=>admitUserInput(state,fields,this.coalesce,this.now()),updatePersona:(botId,persona)=>updateBot(state,{botId,persona},this.models(),this.options.readOnlyToolsets),routes:{enable:(conversation,channel,target,owner)=>enablePush(state,conversation,channel,target,owner,this.now()).id,revoke:routeId=>revokePush(state,routeId,this.now()),resend:deliveryId=>resendUnknown(state,deliveryId,this.now()).id},...extra?.(s,state)}})}commitKeyless(command){return this.commitOwner(randomUUID(),command)}commitCallback(state,rows,commandId,command,ports){return commitInRows(state,this.ledger.tenant,{scope:this.ledger.tenant,commandId,command},rows,{now:this.now,...ports})}async consumeMessage(input){if(this.closed)throw new Error("Bot Host is closed");refuseExported(this.snapshot());const result=await this.core.consumeMessage(input);if(result.outcome==="accepted")queueMicrotask(()=>{if(!this.closed)void this.drain().catch(()=>{});});return result}applyMessage(input,tx){const state=stateOf(tx.application);refuseExported(state);const name=hostIntent(state,tx.intent.key)?.handler,handler=name===void 0?void 0:this.hostIntentMessageHandlers.get(name);let disposition;try{({disposition}=this.commitCallback(state,tx.rows,`${input.taskId}:${input.payload.messageId}`,{kind:"message",turnId:tx.intent.key,message:{taskId:input.taskId,payload:input.payload}},{publish:tx.publish,...this.deliverPort(state,input.taskId),...handler?{hostMessage:()=>hostMessageDisposition(handler(input,tx))}:{}}));}catch(cause){if(cause instanceof CommitConflict&&cause.code==="identity_conflict")return {outcome:"refused",reasonCode:"message_conflict"};throw cause}return disposition.outcome==="accepted"?{outcome:"accepted"}:{outcome:"refused",reasonCode:disposition.reasonCode}}cancelDelegation(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelDelegation",id);const settled=delegationCancelAnswer(this.snapshot(),id);if(settled)return {delegationId:id,...settled};await this.settleChain(this.commitKeyless({kind:"cancel_delegation",delegationId:id}));return {delegationId:id,result:"cancelled"}})}abandonDelegation(id,...by){return this.exclusive(()=>{this.ownerOnly(by,"abandonDelegation",id);return this.settleChain(this.commitKeyless({kind:"abandon_delegation",delegationId:id}))})}async settleChain(result){if(valueOf(result).deliver)await this.deliverCancels();await this.process();}admitsDeviceSlot(intent,state){const rows=Object.values(state.intents).map(row=>dispatchRow(state,row));return admitDeviceSlot(rows.find(row=>row.id===intent.id)??dispatchRow(state,intent),rows,this.deviceConcurrency)}async deliverCancels(){for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;const result=await this.core.cancel(d.cancel.targetTurnId);if("drainError"in result)throw result.drainError;this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});}}async personaReady(botId,revision){await this.exclusive(async()=>{this.commitKeyless({kind:"persona_ready",botId,revision});await this.process();});}async retryPersona(botId){await this.exclusive(async()=>{this.commitKeyless({kind:"retry_persona",botId});await this.process();});}async applyTeam(snapshot){await this.exclusive(async()=>{const valid=teamSnapshot(snapshot);const{disposition}=this.commitOwner(hash(["team",valid.revision]),{kind:"team_snapshot",snapshot:valid},(_s,state)=>({teamBot:row=>writeSnapshotBot(state,row,this.models(),this.options.readOnlyToolsets)}));await this.process();if(disposition.outcome==="refused")throw new TeamModeError("stale_team",disposition.reason??"stale_team")});}async setMainBot(botId,mainBot){await this.exclusive(async()=>{this.commitKeyless({kind:"set_main_bot",botId,mainBot});await this.process();});}autonomy(botId){const bots=this.snapshot().team.bots,bot=Object.hasOwn(bots,botId)?bots[botId]:void 0;if(!bot)throw new Error("Bot not found");return autonomyOf(bot)}wouldDoRecords(botId){return wouldDoRows(this.snapshot(),botId)}inboundDispositions(){return inboundDispositionsOf(this.snapshot())}setBotAutonomy(botId,autonomy,...by){return this.exclusive(async()=>{this.ownerOnly(by,"setBotAutonomy",botId);if(autonomy!=="observe"&&autonomy!=="auto")throw new Error("Invalid autonomy");this.commitKeyless({kind:"set_autonomy",botId,autonomy});await this.process();})}async roomInput(key,roomId,text,mentions=[],...by){let id;await this.exclusive(async()=>{const principal=by.length?this.verifiedOnly(by[0],"roomInput",roomId):void 0;const called=this.seatMentions(roomId,principal,mentions);const result=this.commitOwner(hash(["room_input",roomId,key]),{kind:"room_input",key,roomId,text,mentions:called,...principal?{from:principal.id}:{}});id=turnOf(result);await this.process();});return id}async setMemberMentions(roomId,value,...by){await this.exclusive(async()=>{this.ownerOnly(by,"setMemberMentions",roomId);this.commitKeyless({kind:"set_room_member_mentions",roomId,memberMentions:value});await this.process();});}async createRoom(roomId,fields){await this.exclusive(async()=>{this.commitOwner(hash(["create_room",roomId]),{kind:"create_room",roomId,fields});await this.process();});}async updateRoom(roomId,update){await this.exclusive(async()=>{this.commitKeyless({kind:"update_room",roomId,update});await this.process();});}async answer(id,answer,...by){await this.exclusive(async()=>{this.ownerOnly(by,"answer",id);this.commitOwner(hash(["answer",id]),{kind:"answer",questionId:id,answer});await this.process();});}async decide(id,decision,...by){await this.exclusive(async()=>{this.ownerOnly(by,"decide",id);let error;try{const{disposition}=this.commitOwner(hash(["decide",id]),{kind:"decide",cardId:id,decision});if(disposition.outcome==="refused")error=disposition.reason;}catch(cause){if(!(cause instanceof CommitConflict)||cause.code!=="identity_conflict")throw cause;error=cause.message;}await this.process();if(error)throw new Error(error)});}async setRoutineLifecycle(id,value){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.lifecycle(owned(this.routineRows(),this.options.botId,id).definition.id,value);}finally{await this.process();}});}async endRoutine(id){await this.exclusive(async()=>{try{this.commitOwner(randomUUID(),{kind:"end_routine",botId:this.options.botId,routineId:id},s=>({routines:{end:routineId=>setLifecycle(s,endable(Object.values(s.routines),routineId).definition.id,"completed",this.now(),routineCalendar)}}));}finally{await this.process();}});}async updateRoutine(action){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.updateRoutine(updateDefinition(this.routineRows(),this.options.botId,ownerRoutineUpdate(action)));}finally{await this.process();}});}routineRows(){return Object.values(this.ledger.snapshot().routines)}consume=(wake,signal)=>this.exclusive(async()=>{signal.throwIfAborted();this.write((s,rows)=>{this.sync(s,rows);});try{await this.core.consume(wake,signal);}finally{await this.process();}});drain(){return this.exclusive(()=>this.process())}cancelTurn(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelTurn",id);return this.cancelOneTurn(id)})}async cancelOneTurn(id){const snapshot=this.ledger.snapshot(),settled=turnCancelAnswer(stateOf(snapshot.application),intentRows(snapshot),id);if(settled)return {turnId:id,...settled};const result=this.commitKeyless({kind:"cancel_turn",turnId:id});const value=valueOf(result);const dispatch="target"in value&&value.admitted?await this.core.cancel(value.target):{};try{if("deliver"in value)await this.settleChain(result);else await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}return {turnId:id,result:"cancelled",...dispatch}}topology(deviceId){return deviceTopology(this.snapshot(),deviceId)}freezeForSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.write(s=>switchStep(s,deviceId,expectedRevision,"freeze"));return this.topology(deviceId)})}drainForSwitch(deviceId,{cancel=false}={}){return this.exclusive(async()=>{const work=this.write(s=>{if(!deviceTopology(stateOf(s.application),deviceId).switching)throw new Error(`Device ${deviceId} is not switching`);const open=switchWork(s,deviceId);if(cancel)for(const key of open.intents)s.intents[hash(key)].cancelReason??="cancelled";return open});if(cancel){for(const id of [...work.batches,...work.turns])await this.cancelOneTurn(id);await this.process();}return switchWork(this.ledger.snapshot(),deviceId)})}exportForSwitch(devices,exportedAt=this.now()){return this.exclusive(async()=>{const state=this.snapshot();refuseExported(state);for(const{deviceId,expectedRevision}of devices){const 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(!row.switching)throw new Error(`Device ${deviceId} is not switching`);if(!switchDrained(switchWork(this.ledger.snapshot(),deviceId)))throw new Error(`Device ${deviceId} still has open work`)}const header={source:"L",domain:this.ledger.tenant,exportedAt,devices:devices.map(({deviceId,expectedRevision})=>({deviceId,frozenRevision:expectedRevision}))};const dump=this.ledger.dumpForSwitch();const job=Object.values(dump.body.outbox).find(row=>row.kind==="host-job");if(job)throw new SwitchExportError("open_work",`Switch export source: Host job ${job.occurrenceKey} is pending; let it run first`);const document=sealSwitchExport(switchContent(dump,this.ledger.tenant,header));this.ledger.transaction(s=>{stateOf(s.application).switchExport={digest:document.manifest.digest,exportedAt,devices:document.devices.map(device=>({...device}))};});return document})}commitSwitch(deviceId,expectedRevision,receipt){return this.exclusive(async()=>{switchStep(structuredClone(this.ledger.snapshot()),deviceId,expectedRevision,"commit");const mark=this.snapshot().switchExport;if(!mark)throw new Error("This Host has not exported its domain for a switch");if(mark.digest!==receipt)throw new Error(`The receipt ${receipt} is not this Host's export ${mark.digest}`);if(!mark.devices.some(device=>device.deviceId===deviceId&&device.frozenRevision===expectedRevision)){throw new Error(`Device ${deviceId} at revision ${expectedRevision} is not a device of the export`)}const now=sealLedger(this.ledger,{source:"L",domain:this.ledger.tenant,devices:mark.devices,exportedAt:mark.exportedAt});if(now.manifest.digest!==mark.digest)throw new Error(`The ledger changed after its export: ${now.manifest.digest}, not ${mark.digest}`);this.ledger.transaction(s=>{for(const device of mark.devices)switchStep(s,device.deviceId,device.frozenRevision,"commit");});return this.topology(deviceId)})}abortSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.ledger.transaction(s=>{const state=stateOf(s.application),step=switchStep(s,deviceId,expectedRevision,"abort");if(state.switchExport?.devices.some(device=>device.deviceId===deviceId))delete state.switchExport;return step});try{await this.process();}catch(error){return {...this.topology(deviceId),...error instanceof WakeDispatchError?{wakePending:true}:{drainError:error}}}return this.topology(deviceId)})}retain(input){return this.exclusive(async()=>retainInLedger(this.ledger,input,{contextTurnLimit:this.contextTurnLimit,handoff:this.handoff}))}recover(){return this.exclusive(async()=>{this.write((s,rows)=>{for(const row of Object.values(stateOf(s.application).channel?.deliveries??{}))recoverDelivery(row);this.sync(s,rows);});try{await this.core.recover();}finally{await this.process();}})}sync(s,rows,injected){const state=stateOf(s.application);for(const key of Object.keys(state.hostIntents??{})){if(s.intents[hash(key)])continue;delete state.hostIntents[key];for(const[taskId,reply]of Object.entries(state.replies))if(reply.turnId===key)delete state.replies[taskId];}syncHead(state,this.coalesce,this.now());reconcileDreamRoutines(s,this.dreaming,this.models(),this.now());const routines=botRoutines(Object.values(s.routines));const limits={turnLimit:this.contextTurnLimit,contextMaxBytes:this.contextMaxBytes,instructionMaxBytes:this.instructionMaxBytes,handoff:this.handoff};const materialized=advanceRoomsAndTurns(s,state,this.now(),turn=>syncTurnInLedger(this.ledger,s,rows,turn,{now:this.now(),models:Object.keys(this.models()),readOnlyToolsets:this.options.readOnlyToolsets??[],limits,historyMode:!!this.options.history,history:injected?.turns.get(turn.id),roomHistoryMode:!!this.options.roomHistory,roomHistory:injected?.rooms.get(turn.id),routines,offer:this.offer}),(key,value)=>project(s,key,value));const dreamed=syncDreams(s,{tenant:this.ledger.tenant,policy:this.dreaming,models:this.models(),instructionMaxBytes:this.instructionMaxBytes,now:this.now(),refused:botId=>botDeviceRefusal(state,botId)!==void 0,history:injected?.dreams,historyMode:!!this.options.history});settleDelegations(s,state,this.now(),(key,value)=>project(s,key,value),this.timers);reportCardDecisions(state,(key,value)=>project(s,key,value));syncTail(state,s,this.now(),(key,value)=>project(s,key,value));return materialized||dreamed}async flushReplies(){for(const d of Object.values(this.snapshot().delegations)){if(!replyCheckDue(d,this.now()))continue;const intent=this.core.intent(d.chainTurnIds.at(-1));let check={failed:true};if(intent)try{if(!this.server.tasks.agentMessage)throw new Error("Agent message readback API required");check={taskId:intent.taskId,failed:false,readback:await this.server.tasks.agentMessage(intent.taskId,intent.execution.deviceId,intent.execution.payload.agentRef)};}catch{check={taskId:intent.taskId,failed:true};}this.write(s=>{const state=stateOf(s.application);checkReply(state,state.delegations[d.id],check,this.now(),(key,value)=>project(s,key,value),this.timers.uncertainAfterMs);});}}async callConnector(card){const controller=new AbortController;let timer;const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{const error=new Error(CONNECTOR_OUTCOME_UNKNOWN);controller.abort(error);reject(error);},this.connectorTimeoutMs);});try{return await Promise.race([Promise.resolve().then(()=>this.options.connector(card.id,card.action.action,card.action.draft,controller.signal)),deadline])}finally{clearTimeout(timer);}}async flushCards(){await callCardsInLedger(this.ledger,card=>this.callConnector(card));}async flushDeliveries(){const port=this.options.channel?.port;if(!port)return;if(port.readback)for(const old of Object.values(this.snapshot().channel?.deliveries??{}).filter(row=>row.state==="unknown")){try{const result=await port.readback(old.id);this.write(s=>{const row=stateOf(s.application).channel?.deliveries[old.id];if(row)readbackDelivery(row,old.attempts,result,this.now());});}catch{continue}}for(const old of Object.values(this.snapshot().channel?.deliveries??{})){const claim=this.write(s=>{const state=stateOf(s.application),row=state.channel.deliveries[old.id];if(row.state!=="pending"||(row.nextAttemptAt??0)>this.now())return;const route=deliveryRoute(state,row,this.now());if(!route){refuseRoute(state,row);return}if(startDelivery(row,this.now()))return {row,route}});if(!claim)continue;const controller=new AbortController;let timer;const deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>{controller.abort();reject(new Error("delivery_timeout"));},this.deliveryTimeoutMs);});try{const result=await Promise.race([Promise.resolve().then(()=>port.send({deliveryId:claim.row.id,route:claim.route,body:claim.row.body},controller.signal)),deadline]);this.write(s=>settleDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,result,this.now()));}catch{this.write(s=>unknownDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,controller.signal.aborted?"send_timeout":"send_failed"));}finally{clearTimeout(timer);}}this.write(s=>cleanReplyTokens(s,stateOf(s.application),this.now()));}async syncWithHistory(){const injected=await this.readHistory();return this.write((s,rows)=>this.sync(s,rows,injected))}async readHistory(){const read=this.options.history,readRoom=this.options.roomHistory;if(!read&&!readRoom)return void 0;const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const injected={turns:new Map,rooms:new Map,dreams:new Map};for(const turn of Object.values(state.turns)){if(!awaitsOffer(ledger,state,turn)||this.unread.has(turn.id))continue;const seat=turn.source==="room_slot"?state.team.seats[turn.id]:void 0;try{if(seat&&readRoom&&!seat.released){const roomId=state.team.rounds[seat.roundId].roomId;if(Object.values(ledger.outbox).some(row=>row.kind==="projection"&&row.id.startsWith(roomMessageProjection(roomId,""))&&row.value.roomId===roomId)){this.unread.add(turn.id);continue}const ms=Math.min(this.historyTimeoutMs,seat.deadline===void 0?Infinity:seat.deadline-this.now());const rows=roomMessages(await bounded(readRoom({roomId,botId:turn.botId,turnId:turn.id}),ms));injected.rooms.set(turn.id,{rows,digest:hash(canonical(rows))});}else if(turn.source!=="room_slot"&&read){const rows=contextTurns(await bounded(read({botId:turn.botId,turnId:turn.id}),this.historyTimeoutMs));injected.turns.set(turn.id,{rows,digest:hash(canonical(rows))});}}catch{this.unread.add(turn.id);}}if(read)for(const{key,botId,turnId}of dreamReads(state)){injected.dreams.set(key,await bounded(read({botId,turnId}),this.historyTimeoutMs).then(contextTurns).catch(()=>null));}return injected}async process(){try{await this.pass();}finally{this.armTimer();}}async pass(){if(this.snapshot().switchExport)return;this.unread.clear();let failure;let more;do{await this.deliverCancels().catch(()=>{});const admitted=await this.syncWithHistory();await flushHomes(this.server,this.ledger,this.now);this.intentFailures.clear();try{await this.core.drain();}catch(error){failure??={error};}const refused=this.reportIntentFailures();if(refused)failure??={error:refused};await this.deliverCancels().catch(()=>{});let materialized=await this.syncWithHistory();await this.refreshDevices();await this.flushCards();materialized=await this.syncWithHistory()||materialized;await this.flushReplies();materialized=await this.syncWithHistory()||materialized;await this.flushDeliveries();const ledger=this.ledger.snapshot();const state=stateOf(ledger.application);more=admitted||materialized||Object.values(ledger.intents).some(intent=>intent.phase==="queued"&&intent.cancelReason&&!intent.conclusion)||Object.values(state.turns).some(turn=>turn.status!=="blocked"&&awaitsOffer(ledger,state,turn)&&!this.unread.has(turn.id));}while(more&&!failure);if(failure)throw failure.error}armTimer(){clearTimeout(this.timer);if(!this.closed&&!this.snapshot().switchExport){const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const due=[...this.options.channel?Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="pending").map(row=>row.nextAttemptAt??this.now()):[],...Object.values(state.channel?.inbounds??{}).filter(row=>row.reply?.token).map(row=>row.reply.expiresAt),...collaborationDue(state,this.timers),...state.team.homeOperations.filter(op=>op.status==="pending"&&(homeSent(op)||!deviceRefusal(state,op.request.deviceId))).map(op=>Math.max(this.now()+1e3,op.retryAt??0)),...Object.values(state.delegations).filter(d=>d.cancel&&!d.cancel.delivered).map(()=>this.now()+1e3),...this.unread.size?[this.now()+1e3]:[]];if(due.length){this.timer=setTimeout(()=>{void this.drain().catch(()=>{});},Math.max(1,Math.min(6e4,Math.min(...due)-this.now())));this.timer.unref?.();}}}async refreshDevices(){if(!this.server.machines)return;if(!Object.values(this.snapshot().delegations).some(d=>!d.verdict&&!d.cancel&&(d.status==="queued"||d.status==="waiting_device")))return;let devices;let timer;try{devices=await Promise.race([this.server.machines.list(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Device discovery timed out")),1e3);})]);}catch{return}finally{clearTimeout(timer);}this.write(s=>observeDevices(s,stateOf(s.application),new Map(devices.map(d=>[d.deviceId,d.connected])),(key,value)=>project(s,key,value)));}async close(){this.closed=true;clearTimeout(this.timer);await this.chain;clearTimeout(this.timer);await this.core.close();}};function createBotPersonaProjection(){return createAgentHomeProjectionConsumer(async({projection,projectionHash,writeHomeFile})=>{if(!projection||typeof projection!=="object"||!("schemaVersion"in projection)||projection.schemaVersion!=="bot-profile.v1"||!("persona"in projection)||typeof projection.persona!=="string"||projectionHash!==`sha256:${hash(projection)}`)throw new Error("Invalid Bot persona projection");await writeHomeFile("AGENTS.md",projection.persona);})}
16
+
17
+ export { BotCollaboration, createBotPersonaProjection, inspectLedger };
18
+ //# sourceMappingURL=index.js.map
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store-compatibility.ts","../src/toolset-policy.ts","../src/home-projections.ts","../src/host.ts","../src/persona.ts"],"names":["key","project","hash"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,EAC3C,CACA,MAAM,KAAA,EAAuB,CAC3B,KAAK,MAAA,CAAS,IAAA,CAAM,YAAA,CAAa,IAAA,CAAK,KAAK,CAAA,CAAG,MAAM,IAAA,CAAK,KAAA,CAAO,YAAA,CAAa,IAAA,CAAK,KAAK,CAAA,CAAG,MAAM,IAAA,CAAK,IAAA,CAAK,KAAA,GAC5G,CACF,EC3yCO,SAAS,4BAA6B,CAC3C,OAAO,iCAAA,CAAkC,MAAO,CAAE,UAAA,CAAY,eAAgB,aAAc,CAAA,GAAM,CAChG,GAAI,CAAC,UAAA,EAAc,OAAO,UAAA,GAAe,QAAA,EAAY,EAAE,eAAA,GAAmB,UAAA,CAAA,EACrE,UAAA,CAAW,gBAAkB,gBAAA,EAAoB,EAAE,SAAA,GAAa,UAAA,CAAA,EAAe,OAAO,UAAA,CAAW,UAAY,QAAA,EAC7G,cAAA,GAAmB,CAAA,OAAA,EAAUC,IAAAA,CAAK,UAAU,CAAC,GAAI,MAAM,IAAI,KAAA,CAAM,gCAAgC,CAAA,CACtG,MAAM,aAAA,CAAc,WAAA,CAAa,UAAA,CAAW,OAAO,EACrD,CAAC,CACH","file":"index.js","sourcesContent":["import { copyFileSync, mkdtempSync, rmSync, statSync, type Stats } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport { HostLedger } from '@byok-sdk/server/execution-core';\nimport type { StoreCompatibility } from '@byok-sdk/client';\nimport { wouldDoNeedsMigration } from './commit.js';\nimport { OldCollaborationStateError, stateOf } from './model.js';\nimport { checkTopology } from './topology.js';\nimport { checkSwitchRecords } from './switch.js';\n\n/** Inspect a stopped L ledger on a private copy, including its WAL or rollback journal. */\nexport function inspectLedger(path: string, tenant: string): StoreCompatibility {\n const file = resolve(path), store = 'bot-collaboration-ledger' as const;\n const stat = statOrUndefined(file);\n if (!stat) return { store, path: file, verdict: 'absent', reason: 'No ledger file at this path' };\n if (!stat.isFile()) return { store, path: file, verdict: 'rejected', reason: 'The ledger path is not a regular file' };\n const directory = mkdtempSync(join(tmpdir(), 'byok-ledger-check-'));\n try {\n const copy = join(directory, basename(file)), suffixes = ['', '-wal', '-journal'];\n const fingerprint = (suffix: string) => { const s = statOrUndefined(file + suffix); return s && `${s.size}:${s.mtimeMs}:${s.ino}`; };\n const before = suffixes.map(fingerprint);\n suffixes.forEach((suffix, i) => { if (before[i] !== undefined) copyFileSync(file + suffix, copy + suffix); });\n if (suffixes.some((suffix, i) => fingerprint(suffix) !== before[i])) throw new Error(`${file} changed while it was being checked; stop its owner and check again`);\n try {\n const { DatabaseSync } = process.getBuiltinModule('node:sqlite');\n const db = new DatabaseSync(copy, { readOnly: true });\n try {\n if (!db.prepare(\"SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'\").get()) throw new Error('Not a Host ledger');\n } finally { db.close(); }\n const ledger = new HostLedger(copy, tenant);\n try {\n const state = stateOf(ledger.snapshot().application);\n checkTopology(state); checkSwitchRecords(state);\n if (state.switchExport) return { store, path: file, verdict: 'accepted',\n reason: 'This build opens the exported ledger; run migrateWouldDo if the switch is aborted' };\n return wouldDoNeedsMigration(state)\n ? { store, path: file, verdict: 'migration-required', reason: 'Would-do rows lack turnId; run migrateWouldDo before serving' }\n : { store, path: file, verdict: 'accepted', reason: 'This build opens the ledger' };\n } finally { ledger.close(); }\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n return { store, path: file, verdict: error instanceof OldCollaborationStateError ? 'new-path-repair' : 'rejected',\n ...(typeof code === 'string' ? { code } : {}), reason: error instanceof Error ? error.message : String(error) };\n }\n } finally { rmSync(directory, { recursive: true, force: true }); }\n}\n\nfunction statOrUndefined(file: string): Stats | undefined {\n try { return statSync(file); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error; }\n}\n","import { ToolsetIdSchema } from '@byok-sdk/protocol';\n\n/** Host declaration, not a proof about the tools' behavior. Never accept model annotations here. */\nexport function ownReadOnlyToolsets(ids: readonly string[] = []): readonly string[] {\n if (!Array.isArray(ids)) throw new Error('readOnlyToolsets must be an array of logical toolset IDs');\n if (ids.length > 64 || new Set(ids).size !== ids.length) throw new Error('Invalid read-only toolset policy');\n for (const id of ids) ToolsetIdSchema.parse(id);\n return Object.freeze([...ids]);\n}\n","import type { ByokServer } from '@byok-sdk/server';\nimport { HostLedger, project } from '@byok-sdk/server/execution-core';\nimport { stateOf } from './model.js';\nimport { deviceRefusal, homeSent } from './topology.js';\nimport { applyHomeTerminal, checkHomeReadback, failHomeFlush, homeEnqueued, homeHead, homeRequests, planHomeRetry, type HomeReadback } from './team.js';\n\nexport type HomeServer = Partial<Pick<ByokServer, 'enqueueAgentHomeProjection' | 'readAgentHomeProjection'>>;\n\n/** Called only from the Host serial consumer. All delivery ids are durable. */\nexport async function flushHomes(server: HomeServer, ledger: HostLedger, now: () => number): Promise<void> {\n const busy = (botId: string) => Object.values(ledger.snapshot().intents).some(intent => !intent.conclusion\n && intent.execution.payload.agentRef.agentId === botId);\n const operation = (s: Parameters<Parameters<HostLedger['transaction']>[0]>[0], sequence: number) =>\n stateOf(s.application).team.homeOperations.find(o => o.sequence === sequence)!;\n // One snapshot of the team for the pass: each Bot flushes at most its oldest pending operation once.\n const snapshot = stateOf(ledger.snapshot().application), team = snapshot.team;\n for (const pending of team.homeOperations.filter(o => o.status === 'pending').sort((a, b) => a.sequence - b.sequence)) {\n const op = homeHead(team, pending.sequence, busy);\n if (!op) continue;\n // #957: a device frozen for a switch, or owned by H, gets no new home write. A write that was never sent has nothing to\n // read back, so it waits; a sent write is still read back.\n if (deviceRefusal(snapshot, op.request.deviceId) && !homeSent(op)) continue;\n try {\n if (!server.enqueueAgentHomeProjection || !server.readAgentHomeProjection) throw new Error('Home projection API required');\n // A device terminal can precede local writer cleanup. A control that\n // hits that lease stays pending until reconnect. Retry the same desired\n // revision with a new durable delivery id. Read every delivery first.\n let terminal: HomeReadback | undefined;\n for (const candidate of homeRequests(op)) {\n terminal = checkHomeReadback(candidate, await server.readAgentHomeProjection(candidate.deviceId, candidate.payload.agentRef, candidate.payload.requestId));\n if (terminal) break;\n }\n if (!terminal) {\n const request = ledger.transaction(s => {\n if (deviceRefusal(stateOf(s.application), op.request.deviceId)) return undefined;\n const row = operation(s, op.sequence);\n row.sent = true;\n return planHomeRetry(row, now());\n });\n if (!request) continue;\n await server.enqueueAgentHomeProjection(request);\n ledger.transaction(s => homeEnqueued(operation(s, op.sequence), now()));\n continue;\n }\n const settled = terminal;\n ledger.transaction(s => applyHomeTerminal(stateOf(s.application), operation(s, op.sequence), settled, (id, value) => project(s, id, value)));\n } catch (error) {\n ledger.transaction(s => failHomeFlush(operation(s, op.sequence), error));\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { ownReadOnlyToolsets } from './toolset-policy.js';\nimport { admitBotToolsets, inactive } from './rules/team.js';\nimport { buildHandoffPack, type HandoffPackBudgets, type UpdateRoutineAction } from '@byok-sdk/protocol';\nimport type { ByokServer, CreateByokServerOptions, DueWake } from '@byok-sdk/server';\nimport { enqueue, HostExecutionCore, WakeDispatchError, settle, type ExecutionServer, type HostOptions, type Intent, type IntentInput, type OutcomeTransaction,\n type MessageTransaction } from '@byok-sdk/server/execution-core';\nimport type { HostJobHandler, Routine } from '@byok-sdk/server/execution-core';\nimport { HostLedger, type Conclusion } from '@byok-sdk/server/execution-core';\nimport { canonical, hash, isOccurrenceIntentKey, project, setLifecycle, time, type ApplicationRows, type ExecutionTemplate, type Json, type LedgerState } from '@byok-sdk/server/execution-core';\nimport { stateOf, type CollaborationState, type Turn } from './model.js';\nimport { contextTurns, DEFAULT_HANDOFF_BUDGETS, outcomeOffer, outcomeSchema, SYSTEM_PROMPT, type CheckedOffer, type ContextTurn, type OutcomeOffer } from './schema.js';\nimport { DEFAULT_CANCEL_GRACE_MS, DEFAULT_INSTRUCTION_MAX_BYTES,\n intentRows, minimumInstructionBytes, observeDevices, REPLY_UNCERTAIN_AFTER_MS, settleDelegations, type DelegationTimers } from './delegation.js';\nimport { delegationCancelAnswer, hostIntentCancelAnswer, HostIntentError, turnCancelAnswer, type DelegationCancelResult, type IntentCancelResult,\n type TurnCancelResult } from './rules/delegation.js';\nimport { checkReply, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, replyCheckDue, reportCardDecisions,\n commandBots, type Command, type CommandPorts, type KeylessCommand, type ReplyCheck } from './rules/commands.js';\nimport type { CommandRecord } from './rules/commit.js';\nimport { hostMessageDisposition, type MessageDisposition } from './rules/message.js';\nimport { callCardsInLedger, CommitConflict, commitInLedger, commitInRows, retainInLedger, syncTurnInLedger, writeLedger, type CommitResult } from './commit.js';\nimport type { RetentionInput, RetentionResult } from './retention.js';\nimport { BOT_DREAM, BOT_ROUTINE, botRoutines, endable, owned, routineCalendar, routineTurn,\n ownerRoutineUpdate, updateDefinition, type BotRoutineInput } from './routines.js';\nimport { checkDreamInstruction, dreamPolicy, dreamReads, reconcileDreamRoutines, recordDream, syncDreams, type DreamPolicy, type DreamingOptions } from './dream.js';\nimport { DEFAULT_AUTONOMY, autonomyOf, wouldDoRows, type Autonomy, type WouldDo } from './rules/autonomy.js';\nimport { botOutcomePorts, IntentOutcomeError, outcomeFailure, routeTerminal, runHostIntentHandler, syncHead, syncTail } from './adapter-steps.js';\nimport { DEVICE_CONCURRENCY, admitDeviceSlot, type DispatchIntent } from './rules/priority.js';\n\nimport { applyManagement, applyModels, updateBot, writeSnapshotBot } from './team.js';\nimport { botCompactVeto } from './compaction.js';\nimport { teamSnapshot, TeamModeError, type TeamSnapshot } from './rules/team.js';\nimport { advanceRoomsAndTurns, memberMentions, roomMessageProjection, roomMessages, type MemberMentions, type Mentions, type RoomMessage } from './rooms.js';\nimport type { RoomFields } from '@byok-sdk/protocol';\n\nimport { HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS } from './rules/history.js';\nimport { flushHomes, type HomeServer } from './home-projections.js';\nimport { admitBot, admitDevice, botDeviceRefusal, checkTopology, DeviceModeError, deviceRefusal, deviceTopology, homeSent, switchDrained, switchStep, switchWork,\n type DeviceTopology,\n type SwitchWork } from './topology.js';\nimport { checkSwitchRecords, refuseExported, sealLedger, switchContent } from './switch.js';\nimport { sealSwitchExport, SwitchExportError, type SwitchExport, type SwitchHeader } from './migration.js';\nimport { admitUserInput, coalescePolicy, type CoalescePolicy } from './coalesce.js';\nimport { classifyInbound, inboundKey, isOwner, verified, type ChannelOptions, type Conversation, type InboundClass, type InboundMessage, type Principal, type PrincipalArg } from './channel.js';\nimport { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, unknownDelivery } from './delivery.js';\nimport { cleanReplyTokens, deliveryRoute, echoCandidates, enablePush, promoteStaged, queueDelivery, refuseRoute, rememberFilteredInbound, rememberInbound,\n resendUnknown, revokePush } from './delivery-routing.js';\nimport { inboundDispositionsOf } from './inbound.js';\nimport type { InboundDisposition } from './rules/inbound.js';\nexport interface BotOptions {\n botId: string; execution: ExecutionTemplate; now?: () => number;\n /** Owner principal id (#552 R2). Default `owner`. Only the human principal with this id passes the owner checks. */\n owner?: string;\n /** Optional Host IM outbox. Push stays off until an owner enables a route. */\n channel?: ChannelOptions;\n /**\n * Host-owned model templates. New Bots stay on the selected template's device. Construction and `setModels` apply each\n * template by model name to every unarchived Bot. A Bot whose model has none keeps its Turns blocked (`Unavailable model`).\n */\n models?: Record<string, ExecutionTemplate>;\n /** Host-owned read-only toolset IDs. Default empty. The Host's local tool server must enforce read-only behavior. */\n readOnlyToolsets?: readonly string[];\n /** Must deduplicate by id. A committed confirmation can be replayed after a crash. */\n connector: (id: string, action: string, draft: Json, signal: AbortSignal) => Promise<Json>;\n /** The Host also enforces this limit when a connector ignores cancellation. */\n connectorTimeoutMs?: number;\n contextMaxBytes?: number;\n contextTurnLimit?: number;\n /**\n * Bytes of the Bot history in a ContextPack. Default: `DEFAULT_HANDOFF_BUDGETS`. Construction checks it against an empty\n * pack only, so a `totalBytes` that cannot hold the digits of the turn count throws `RangeError` at sync.\n */\n handoff?: HandoffPackBudgets;\n /** UTF-8 bound of a whole bot_request or bot_reply instruction. Construction refuses a value below the proven minimum. */\n instructionMaxBytes?: number;\n /** A cancel with no terminal after this time shows `uncertain` (§8.3). */\n cancelGraceMs?: number;\n /** A claimed chain Turn, or a reply check, with no verdict after this time shows `uncertain` (§8.3). */\n uncertainAfterMs?: number;\n /**\n * Merge consecutive user inputs to a busy Bot into one Turn before K4 enqueue (#551). Absent means off.\n * Defaults: windowMs 10_000, maxItems 8, maxBytes 8192. Construction refuses a value outside\n * windowMs 1000 to 60_000, maxItems 2 to 16, or maxBytes 1024 to contextMaxBytes / 4.\n */\n coalesce?: Partial<CoalescePolicy>;\n /**\n * Handlers for the Host's own K4 Host job routines. They share the core with Bot routines,\n * so their rules use the same calendar: a `RoutineSchedule` whose `tz` is the definition time zone.\n */\n hostJobs?: Readonly<Record<string, HostJobHandler>>;\n /**\n * Handlers of the Host's own K4 intents (#882), by name. `enqueueHostIntent` stores the name with the intent.\n * At a `task.complete` terminal, the handler runs synchronously in the terminal transaction with the result document.\n * An intent whose execution has `messageEgress` also needs a handler of the same name in `hostIntentMessages`.\n */\n hostIntents?: Readonly<Record<string, HostIntentHandler>>;\n /**\n * Agent message handlers of Host intents (#1356), by the `hostIntents` name. The handler runs synchronously in the K4\n * message transaction and decides the message. K8 records an accepted message without its body and does not deliver it.\n * A Host intent whose name has no message handler refuses its messages with `binding_mismatch`.\n */\n hostIntentMessages?: Readonly<Record<string, HostIntentMessageHandler>>;\n /**\n * Dreaming (#1475). Absent: on, one dream per Bot per day that had a completed Turn, at 03:00 local time, on the Bot's own model.\n * `false`: off for the whole Host, and open dream routines end. See the README for the cost.\n */\n dreaming?: DreamingOptions | false;\n /** Passed to the K4 core. Default 100. */\n reconcileMs?: number;\n /** Passed to the K4 core: a coalesced hint after a commit that wrote the outbox. */\n onOutbox?: HostOptions['onOutbox'];\n /**\n * External history authority (#739 Q4). Absent: the ContextPack reads this ledger's Turns.\n * Present: before a Bot Turn freezes its offer, the Host reads the Bot's earlier history here, oldest first,\n * in the ContextPack row shape. The rows replace the stored Turns in that ContextPack and are not stored;\n * the Turn keeps only their hash. Cards, questions and rejected actions stay Host state. Room seats read `roomHistory`.\n * A read that throws, returns another shape or is still open after `historyTimeoutMs` leaves the Turn queued, and the timer\n * tries again. A dream (#1475) reads here too, with `turnId` set to the dream's intent key. A failed read skips that day.\n */\n history?: (input: { botId: string; turnId: string }) => Promise<readonly ContextTurn[]>;\n /**\n * External room history authority (#883). Absent: a seat ContextPack reads the room messages of this ledger.\n * Present: before a seat Turn freezes its offer, the Host reads here the room messages that the seat's Bot can see,\n * oldest first. The authority selects them for that Bot. The rows replace `room.messages` in that ContextPack and are\n * not stored; the seat Turn keeps only their hash. `room.messages` is still written, for the request text and mentions.\n * A read that throws, returns another shape or is still open after `historyTimeoutMs` or at the seat deadline leaves the seat\n * queued, and the timer tries again until the seat deadline.\n */\n roomHistory?: (input: { roomId: string; botId: string; turnId: string }) => Promise<readonly RoomMessage[]>;\n /**\n * How long a `history` or `roomHistory` read may stay open before it counts as failed. The reads run one after another\n * in the Host queue, so this bounds how long a stalled authority holds it. The read is not aborted. Default 10_000.\n */\n historyTimeoutMs?: number;\n /**\n * External team authority (#739 Q4c). Absent: this Host creates the Main Bot and owns its local team.\n * `external`: the constructor creates no Bot. `applyTeam` writes the authority's Bot snapshots, and\n * `setMainBot`, `create_bot`, `update_bot` and `delete_bot` refuse with `external_team`. The mode is stored\n * in the ledger, so a ledger cannot change its mode at a restart.\n */\n team?: 'external';\n /**\n * Host persona mode (#879), only with `team: 'external'`. The Host projects each Bot's Agent home itself. A snapshot\n * Bot carries the Host's `profileRevision`, which becomes its agentRef revision, and K8 queues no persona projection.\n * The Host reports an applied revision with `personaReady`. `retryPersona` refuses with `external_persona`.\n * The ledger stores the mode, so a restart cannot change it.\n */\n persona?: 'external';\n /**\n * External rooms mode (#1321), only with `team: 'external'`. Each team snapshot carries the authority's whole room list,\n * and a room that it no longer lists is archived for good. `createRoom`, `updateRoom`, `setMemberMentions` and the Main Bot's\n * `create_room` and `update_room` refuse with `external_rooms`. The ledger stores the mode, so a restart cannot change it.\n */\n rooms?: 'external';\n /**\n * Outcome offer (#881): allowlists of actions by Turn kind, the IANA time zones of routine actions, and the\n * `confirmable_action` branches. Each field only narrows the default. It applies to Turns frozen after construction.\n */\n outcome?: OutcomeOffer;\n /**\n * The concurrent task limit of each device (#1229 item 1), as the daemon's `maxConcurrentTasks`. Default 8.\n * The Host leaves one slot free for user-source work; submitted work is never cancelled to make room.\n */\n deviceConcurrency?: number;\n}\n/** Synchronous. A throw or a thenable leaves the intent open, and `drain()` rejects. */\nexport type HostIntentHandler = (document: unknown, transaction: OutcomeTransaction) => void;\n/** Synchronous. A throw rolls the message transaction back, and a thenable or another result throws. */\nexport type HostIntentMessageHandler = (input: AgentMessageInput, transaction: MessageTransaction) => MessageDisposition;\n/**\n * The cancel answer of a Host intent (K8 `IntentCancelResult`). `conclusion` is optional: an in-flight intent awaits its\n * terminal, and an unsubmitted intent may await a successful drain after a `drainError` or `wakePending` result.\n */\nexport type HostIntentCancelResult = IntentCancelResult<Conclusion> & { wakePending?: true; drainError?: unknown };\nfunction hostIntent(state: CollaborationState, key: string): { handler: string } | undefined {\n return state.hostIntents && Object.hasOwn(state.hostIntents, key) ? state.hostIntents[key] : undefined;\n}\n/** The open K4 intent of `key`. Refuses an unknown or settled key. */\nfunction openIntent(intents: LedgerState['intents'], key: string): Intent {\n const intent = intents[hash(key)];\n if (!intent) throw new HostIntentError(key, 'unknown_intent', `Unknown intent: ${key}`);\n if (intent.conclusion) throw new HostIntentError(key, 'already_settled', `Intent already settled: ${key}`);\n return intent;\n}\n/** Phase 1 of a history-mode sync: the injected rows of each Turn that can freeze its offer next, by Turn id. */\ninterface InjectedHistory {\n turns: ReadonlyMap<string, { rows: ContextTurn[]; digest: string }>;\n rooms: ReadonlyMap<string, { rows: RoomMessage[]; digest: string }>;\n dreams: ReadonlyMap<string, readonly ContextTurn[] | null>;\n}\n/** Reply readback port (§3.3). The Host acceptance record stays the body authority. */\nexport type MessageServer = { tasks: Partial<Pick<ByokServer['tasks'], 'agentMessage'>> };\nexport type AgentMessageInput = Parameters<NonNullable<CreateByokServerOptions['agentMessage']>['consume']>[0];\n\n/** A history read still open after `ms` counts as a failed read, so a stalled authority cannot hold the Host queue. */\nfunction bounded<T>(read: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('History read timed out')), Math.max(0, ms)); });\n return Promise.race([read, late]).finally(() => clearTimeout(timer));\n}\n/** A Turn that has no offer yet and can freeze one: not concluded, failed or held, and its Bot is active with its profile applied. */\nfunction awaitsOffer(ledger: LedgerState, state: CollaborationState, turn: Turn): boolean {\n const bot = state.team.bots[turn.botId];\n return !turn.conclusion && !turn.held && !ledger.intents[hash(turn.id)] && turn.status !== 'failed' && !!bot && !inactive(bot) && bot.readyRevision === bot.revision;\n}\n/** The slot row of one K4 intent (#1229). An intent holds a slot once it is submitted or has attempt evidence. */\nfunction dispatchRow(state: LedgerState, row: Intent): DispatchIntent {\n const execution = state.executions[row.taskId];\n return { id: row.id, agent: row.agent, sequence: row.sequence, phase: row.phase, attempts: row.attempts, source: row.source,\n deviceId: row.execution.deviceId,\n occupies: row.phase === 'inflight' && (execution?.submission === 'delivered' || execution?.attempt !== undefined || execution?.started === true) };\n}\n/** #957: a new owner command refuses while a device it would create work on is frozen or owned by H (`commandBots`). */\nfunction admitCommand(state: CollaborationState, command: Command): void {\n for (const botId of commandBots(state, command)) admitBot(state, botId);\n}\n/** The value of an accepted disposition. Keyless commands refuse by throwing, so they always accept. */\nfunction valueOf<T>(result: CommitResult): T {\n if (result.disposition.outcome !== 'accepted') throw new Error('Unexpected refused command');\n return result.disposition.value as T;\n}\n/** The Turn or round id of an input command. These commands never refuse; they throw. */\nfunction turnOf(result: CommitResult): string {\n if (result.disposition.outcome !== 'accepted' || typeof result.disposition.value !== 'string') throw new Error('Input command has no Turn id');\n return result.disposition.value;\n}\n/** The local K8 Host. Use one instance per ledger tenant. */\nexport class BotCollaboration {\n readonly core: HostExecutionCore;\n private chain: Promise<unknown> = Promise.resolve();\n private timer?: ReturnType<typeof setTimeout>;\n private closed = false;\n private readonly now: () => number;\n private readonly connectorTimeoutMs: number;\n private readonly deliveryTimeoutMs: number;\n private readonly historyTimeoutMs: number;\n private readonly contextMaxBytes: number;\n private readonly contextTurnLimit: number;\n private readonly handoff: HandoffPackBudgets;\n private readonly dreaming: DreamPolicy | undefined;\n private readonly instructionMaxBytes: number;\n private readonly deviceConcurrency: number;\n private readonly timers: DelegationTimers;\n private readonly coalesce?: CoalescePolicy;\n private readonly offer: CheckedOffer;\n /** The default principal of the owner APIs: the caller that the Host authenticated as the owner. */\n private readonly owner: Principal;\n /** History mode: Turns whose history read failed in this pass. The timer reads them again. */\n private unread = new Set<string>();\n private readonly hostIntentHandlers: ReadonlyMap<string, HostIntentHandler>;\n private readonly hostIntentMessageHandlers: ReadonlyMap<string, HostIntentMessageHandler>;\n /** Terminals that could not apply in the current K4 drain, by intent key. K4 also drains from its own timer. */\n private readonly intentFailures = new Map<string, IntentOutcomeError>();\n /** The last audited reason of each refused key, so a stuck intent adds one audit row and not one per pass. */\n private readonly auditedFailures = new Map<string, string>();\n constructor(readonly server: ExecutionServer & HomeServer & MessageServer & Partial<Pick<ByokServer, 'machines'>>, readonly ledger: HostLedger, private readonly options: BotOptions) {\n if (!options.botId || options.execution.payload.agentRef.agentId !== options.botId) throw new Error('Select this Bot Agent');\n // #816: every compaction of this ledger must ask K8 first.\n if (ledger.compactVeto !== botCompactVeto) throw new Error('Open the Host ledger with { compactVeto: botCompactVeto }');\n options = this.options = { ...options, execution: structuredClone(options.execution),\n ...(options.models === undefined ? {} : { models: structuredClone(options.models) }),\n readOnlyToolsets: ownReadOnlyToolsets(options.readOnlyToolsets) };\n admitBotToolsets(options.execution, options.readOnlyToolsets);\n for (const model of Object.values(this.models())) admitBotToolsets(model, options.readOnlyToolsets);\n const persisted = ledger.snapshot(), team = stateOf(persisted.application).team;\n // #957: the owner records are read before any pass. Each refusal reads them again in the transaction that would write.\n checkTopology(stateOf(persisted.application));\n // #975: an uncommitted import refuses here, before the constructor's own write and before K4 starts.\n checkSwitchRecords(stateOf(persisted.application));\n // The team mode is stored in the ledger. A restart cannot change it.\n if (options.team === 'external' ? !team.external && Object.keys(team.bots).length : team.external) {\n throw new Error(`This ledger has ${team.external ? 'an external' : 'a local'} team`);\n }\n if (options.persona !== undefined && (options.persona !== 'external' || options.team !== 'external')) {\n throw new Error(\"The Host persona mode needs team: 'external'\");\n }\n if (team.external && !!team.external.persona !== (options.persona === 'external')) {\n throw new Error(`This ledger has ${team.external.persona ? 'Host' : 'K8'} persona projections`);\n }\n if (options.rooms !== undefined && (options.rooms !== 'external' || options.team !== 'external')) {\n throw new Error(\"The external rooms mode needs team: 'external'\");\n }\n if (team.external && !!team.external.rooms !== (options.rooms === 'external')) {\n throw new Error(`This ledger has ${team.external.rooms ? 'external' : 'local'} rooms`);\n }\n // Recovery can resubmit a frozen older generation after the Bot changes models.\n // Historical settled executions remain readable; only outstanding work must be admitted.\n for (const intent of Object.values(persisted.intents)) {\n if (intent.conclusion) continue;\n admitBotToolsets(intent.execution, options.readOnlyToolsets);\n const execution = persisted.executions[intent.taskId];\n if (execution) admitBotToolsets(execution.input, options.readOnlyToolsets);\n }\n this.hostIntentHandlers = new Map(Object.entries(options.hostIntents ?? {}));\n this.hostIntentMessageHandlers = new Map(Object.entries(options.hostIntentMessages ?? {}));\n for (const name of this.hostIntentMessageHandlers.keys()) {\n if (!this.hostIntentHandlers.has(name)) throw new Error(`A Host intent message handler needs the Host intent handler ${name}`);\n }\n for (const [key, { handler }] of Object.entries(stateOf(persisted.application).hostIntents ?? {})) {\n // A record whose intent K4 compacted is stale until the next pass. It needs no handler.\n const intent = persisted.intents[hash(key)];\n if (intent && intent.conclusion === undefined && !this.hostIntentHandlers.has(handler)) {\n throw new Error(`An open Host intent needs the handler ${handler}`);\n }\n if (intent && intent.conclusion === undefined && intent.execution.payload.messageEgress && !this.hostIntentMessageHandlers.has(handler)) {\n throw new Error(`An open Host intent needs the message handler ${handler}`);\n }\n }\n this.owner = { id: options.owner ?? 'owner', kind: 'human' };\n if (!verified(this.owner)) throw new Error('Invalid owner principal');\n this.now = () => time((options.now ?? Date.now)());\n this.connectorTimeoutMs = time(options.connectorTimeoutMs ?? 30_000);\n if (this.connectorTimeoutMs < 1 || this.connectorTimeoutMs > 2_147_483_647) throw new Error('Invalid connector timeout');\n this.deliveryTimeoutMs = time(options.channel?.sendTimeoutMs ?? 15_000);\n if (this.deliveryTimeoutMs < 1 || this.deliveryTimeoutMs > 2_147_483_647) throw new Error('Invalid delivery timeout');\n this.historyTimeoutMs = time(options.historyTimeoutMs ?? 10_000);\n if (this.historyTimeoutMs < 1 || this.historyTimeoutMs > 2_147_483_647) throw new Error('Invalid history timeout');\n this.contextMaxBytes = time(options.contextMaxBytes ?? HISTORY_MAX_BYTES);\n this.contextTurnLimit = time(options.contextTurnLimit ?? HISTORY_MAX_ITEMS);\n if (this.contextMaxBytes < 1 || this.contextTurnLimit < 1) throw new Error('Invalid ContextPack limits');\n this.handoff = options.handoff ?? DEFAULT_HANDOFF_BUDGETS;\n buildHandoffPack([], this.handoff);\n if (options.coalesce) this.coalesce = coalescePolicy(options.coalesce, this.contextMaxBytes);\n this.offer = outcomeOffer(options.outcome ?? {});\n // Compose once, so a Host draft outside the protocol limits fails here and not at each Turn.\n outcomeSchema(options.botId, stateOf({}), undefined, Object.keys(this.models()), [], this.offer);\n this.instructionMaxBytes = time(options.instructionMaxBytes ?? DEFAULT_INSTRUCTION_MAX_BYTES);\n // A narrowed prompt (#881) keeps a subset of the SYSTEM_PROMPT sentences, so this minimum bounds it too.\n const minimum = minimumInstructionBytes(SYSTEM_PROMPT);\n if (this.instructionMaxBytes < minimum) throw new Error(`instructionMaxBytes must be at least ${minimum}`);\n this.dreaming = dreamPolicy(options.dreaming);\n if (this.dreaming) checkDreamInstruction(this.instructionMaxBytes);\n this.timers = { cancelGraceMs: time(options.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS), uncertainAfterMs: time(options.uncertainAfterMs ?? REPLY_UNCERTAIN_AFTER_MS) };\n if (this.timers.cancelGraceMs < 1 || this.timers.uncertainAfterMs < 1) throw new Error('Invalid delegation timers');\n this.deviceConcurrency = time(options.deviceConcurrency ?? DEVICE_CONCURRENCY);\n if (this.deviceConcurrency < 1) throw new Error('Invalid device concurrency');\n this.core = new HostExecutionCore(server, ledger, { now: this.now, reconcileMs: options.reconcileMs ?? 100, nextOccurrence: routineCalendar,\n // K8 owns only Turn and Host intents, so no K8 owner could settle an occurrence intent: L concludes a Host job result\n // with `execution` `failed` (#793 K5) and refuses `execution` routines (#954), as H does.\n hostJobExecution: 'fail', executionRoutines: 'refuse',\n ...(options.hostJobs ? { hostJobs: options.hostJobs } : {}), ...(options.onOutbox ? { onOutbox: options.onOutbox } : {}),\n occurrenceHooks: { [BOT_ROUTINE]: (run, tx) => {\n const state = stateOf(tx.application);\n // #957: a slot of a Bot whose device is frozen or owned by H throws, so K4 records neither the slot nor a Turn and the\n // SDK delivers the wake again later. After an abort the slot runs. From the export on (#975) every slot refuses, and\n // the new owner schedules the routine's wakes on its own SDK.\n admitBot(state, (run.input as BotRoutineInput).owner);\n refuseExported(state);\n this.commitCallback(state, tx.rows, run.occurrenceKey, { kind: 'occurrence', key: run.occurrenceKey },\n { publish: tx.publish, occurrence: () => routineTurn(state, run) });\n }, [BOT_DREAM]: (run, tx) => {\n const state = stateOf(tx.application);\n admitBot(state, (run.input as { owner: string }).owner);\n refuseExported(state);\n recordDream(state, run, this.now());\n } },\n applyMessage: (input, tx) => this.applyMessage(input, tx),\n applyOutcome: (document, tx) => this.applyOutcome(document, tx),\n // #957: K4 sends nothing to a device that is frozen or owned by H: not the timer drain, not a `bot.core` call.\n // #1229: the Host also reserves one slot of each device for user-source work.\n admitSubmit: (intent, state) => !deviceRefusal(stateOf(state.application as LedgerState['application']), intent.execution.deviceId)\n && this.admitsDeviceSlot(intent, state) });\n // An exported domain stays as it was exported (#975), also across a restart.\n if (!stateOf(persisted.application).switchExport) ledger.transaction(s => {\n const state = stateOf(s.application);\n if (options.team === 'external') {\n state.team.external ??= { revision: 0, ...(options.persona === 'external' ? { persona: true as const } : {}),\n ...(options.rooms === 'external' ? { rooms: true as const } : {}) };\n } else {\n state.team.bots[options.botId] ??= { id: options.botId, name: 'Main Bot', role: 'Team owner', persona: '',\n model: Object.keys(this.models())[0]!, mainBot: true, archived: false, autonomy: DEFAULT_AUTONOMY,\n revision: options.execution.payload.agentRef.profileRevision, readyRevision: options.execution.payload.agentRef.profileRevision,\n execution: structuredClone(options.execution) };\n }\n // #1357: the stored templates become the Host's current ones. Frozen intents keep the execution they froze with.\n applyModels(state, this.models(), options.readOnlyToolsets ?? []);\n });\n }\n private models(): Record<string, ExecutionTemplate> { return this.options.models ?? { default: this.options.execution }; }\n /**\n * Replaces the Host's model templates at run time (#1357), for example after a device key changed. Each unarchived Bot takes\n * the template of its model; a Turn frozen before keeps its execution. No profile revision, readiness or persona projection\n * changes. A Bot whose model is missing keeps its Turns blocked until a later call provides it. A template that fails the\n * toolset check, or model names that the outcome schema cannot take, refuse the call and change nothing.\n */\n setModels(models: Readonly<Record<string, ExecutionTemplate>>): Promise<void> {\n return this.exclusive(async () => {\n const next = structuredClone(models) as Record<string, ExecutionTemplate>;\n // The model names enter the Main Bot's create_bot and update_bot schemas, as at construction.\n outcomeSchema(this.options.botId, stateOf({}), undefined, Object.keys(next), [], this.offer);\n this.write(s => applyModels(stateOf(s.application), next, this.options.readOnlyToolsets ?? []));\n this.options.models = next;\n await this.process();\n });\n }\n snapshot(): CollaborationState { return stateOf(this.ledger.snapshot().application); }\n /**\n * Every K8 write of this Host, except the switch steps (#975). It refuses while the domain is exported, after the work,\n * so a new command on a frozen or H-owned device still gets its device refusal (`writeLedger` lists the others).\n */\n private write<T>(apply: (state: LedgerState, rows: ApplicationRows) => T): T { return writeLedger(this.ledger, apply); }\n private exclusive<T>(work: () => Promise<T>): Promise<T> {\n if (this.closed) return Promise.reject(new Error('Bot Host is closed'));\n const next = this.chain.then(work);\n this.chain = next.catch(() => {});\n return next;\n }\n /**\n * Returns the id of the Turn that answers this input. With `coalesce`, it is the batch id\n * (the first batched input's id); that Turn appears when the batch seals.\n * Only the owner starts a 1:1 execution (R2).\n */\n input(key: string, request: string, botId = this.options.botId, ...by: PrincipalArg): Promise<string> {\n return this.exclusive(async () => {\n const principal = this.ownerOnly(by, 'input', botId);\n const result = this.commitOwner(hash(['input', botId, key]), { kind: 'input', botId, key, request, sender: principal.id });\n await this.process();\n return turnOf(result);\n });\n }\n /**\n * Read-only (#1407): the id that `input` returned for this key, from its command record, or `undefined` when the\n * input is not committed. It runs no `process()` and changes no ledger state, so a caller can tell whether an `input`\n * that threw on its drain committed. A record that retention moved is read from its K4 row in a transaction that writes\n * nothing new; once that row expires, the key reads as not committed.\n */\n inputRoot(key: string, botId = this.options.botId): string | undefined {\n const id = hash(['input', botId, key]), commands = stateOf(this.ledger.snapshot().application).commands;\n const record = commands && Object.hasOwn(commands, id) ? commands[id]\n : this.ledger.transaction((_, rows) => rows.get('commands', id) as CommandRecord | undefined);\n return record && turnOf(record.result);\n }\n /**\n * IM entry (#552). Classify one message that the channel adapter translated (docs/host-im-adapter.md §3).\n * The input key is `inboundKey(message)`. Only audit rows record a refused or 1:1 bot message.\n * `id` is the Turn id of `owner_input`, or the room input id of `room_input` and `bot_background`.\n */\n async receive(message: InboundMessage): Promise<{ kind: InboundClass; id?: string }> {\n if (this.closed) throw new Error('Bot Host is closed');\n const kind = classifyInbound(message, this.owner.id, this.options.channel?.self), { channel, conversation, platformMessageId, sender } = message;\n if (kind === 'echo') {\n // A send can be waiting for this echo. Do not queue it behind that send.\n this.write(s => {\n const state = stateOf(s.application), matches = echoCandidates(state, message);\n if (matches.length !== 1 || !acceptDeliveryEcho(matches[0]!, platformMessageId)) state.audit.push(`Delivery unmatched_echo: ${channel} ${platformMessageId}`.slice(0, 1024));\n cleanReplyTokens(s, state, this.now());\n });\n return { kind };\n }\n if (kind === 'owner_input' || kind === 'room_input') return this.exclusive(async () => {\n const principal = kind === 'owner_input' ? this.ownerOnly([sender], 'input', conversation.id) : this.verifiedOnly(sender, 'roomInput', conversation.id);\n const key = inboundKey(message);\n const command: Command = kind === 'owner_input'\n ? { kind: 'receive', inbound: kind, key, botId: conversation.id, request: message.text, sender: principal.id }\n : { kind: 'receive', inbound: kind, key, roomId: conversation.id, text: message.text,\n mentions: this.seatMentions(conversation.id, principal, message.mentions), from: principal.id };\n // #1229 item 3: remember every inbound human message, with or without a channel, so the Host UI can project its\n // destination. A room input's root is its round id; the seat Turns carry their own roots.\n const result = this.commitOwner(hash(['receive', key]), command,\n (_s, state) => ({ remember: root => rememberInbound(state, message, root) }));\n await this.process();\n return { kind, id: turnOf(result) };\n });\n if (kind === 'bot_background') {\n return { kind, id: await this.roomInput(inboundKey(message), conversation.id, message.text, message.mentions, sender) };\n }\n const who = verified(sender) ? ` ${sender.kind}:${sender.id}` : '';\n // #1229 item 3: a refused human message gets a durable inbound row too, so it never lacks a destination.\n const filtered = kind === 'unverified_sender' || kind === 'not_owner' ? kind : undefined;\n await this.exclusive(async () => this.write(s => {\n const state = stateOf(s.application);\n if (filtered) rememberFilteredInbound(state, message, filtered);\n state.audit.push(`Inbound ${kind}: ${channel} ${conversation.kind}:${conversation.id} ${platformMessageId}${who}`.slice(0, 1024));\n }));\n return { kind };\n }\n /** Owner opt-in for one canonical conversation. Enabling a replacement revokes its old route. */\n enablePushRoute(conversation: Conversation, channel: string, target: string, ...by: PrincipalArg): Promise<string> {\n return this.exclusive(async () => {\n const principal = this.ownerOnly(by, 'enablePushRoute', conversation.id);\n if (!this.options.channel) throw new Error('Channel is not configured');\n return valueOf<string>(this.commitKeyless({ kind: 'enable_push_route', conversation, channel, target, owner: principal.id }));\n });\n }\n revokePushRoute(id: string, ...by: PrincipalArg): Promise<void> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'revokePushRoute', id);\n this.commitKeyless({ kind: 'revoke_push_route', routeId: id });\n await this.process();\n });\n }\n resendDelivery(id: string, ...by: PrincipalArg): Promise<string> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'resendDelivery', id);\n if (!this.options.channel) throw new Error('Channel is not configured');\n const next = valueOf<string>(this.commitKeyless({ kind: 'resend_delivery', deliveryId: id }));\n await this.process();\n return next;\n });\n }\n /** Adapter data can be unverified, so one row is at most 1024 characters. */\n private audit(line: string): void {\n this.write(s => { stateOf(s.application).audit.push(line.slice(0, 1024)); });\n }\n /** R2: refuse an unverified principal. The audit row commits before the error. */\n private verifiedOnly(principal: Principal | undefined, action: string, target: string): Principal {\n if (verified(principal)) return principal;\n this.audit(`Action refused unverified_sender: ${action} ${target}`);\n throw new Error(`unverified_sender: ${action} needs a verified principal`);\n }\n /**\n * The mention entities that may open seats (#1230). A bot mentions nothing (R5). In a group whose `memberMentions`\n * setting is `ignore`, a human who is not the owner mentions nothing either: the message stays room background, with\n * no seat, no device work and no BYOK key. The owner's mention still selects seats, and an omitted principal is the\n * Host's own call. The setting is read here, so it applies to this inbound message only, never to an open root or seat.\n */\n private seatMentions(roomId: string, principal: Principal | undefined, mentions: Mentions): Mentions {\n if (!principal || isOwner(principal, this.owner.id)) return mentions;\n if (principal.kind === 'bot') return [];\n const room = this.snapshot().team.rooms[roomId];\n return room && memberMentions(room) === 'ignore' ? [] : mentions;\n }\n /** R2: only the owner principal acts. An omitted principal is the owner. A given `undefined` is unverified. */\n private ownerOnly(by: PrincipalArg, action: string, target: string): Principal {\n const principal = this.verifiedOnly(by.length ? by[0] : this.owner, action, target);\n if (isOwner(principal, this.owner.id)) return principal;\n this.audit(`Action refused not_owner: ${action} ${target} ${principal.kind}:${principal.id}`);\n throw new Error(`not_owner: ${action} needs the owner principal`);\n }\n private applyOutcome(document: unknown, tx: OutcomeTransaction): void {\n const state = stateOf(tx.application), taskId = tx.intent.taskId, key = tx.intent.key;\n refuseExported(state);\n try {\n const route = routeTerminal(state, key, hostIntent(state, key)?.handler);\n if (route.kind === 'host_intent') runHostIntentHandler(key, route.handler, this.hostIntentHandlers.get(route.handler)?.bind(null, document, tx));\n else if (route.kind === 'bot_turn') {\n try { this.commitBotOutcome(state, key, taskId, document, tx); } catch (cause) { throw outcomeFailure(key, cause); }\n }\n } catch (error) {\n if (error instanceof IntentOutcomeError) this.intentFailures.set(key, error);\n throw error;\n }\n }\n private commitBotOutcome(state: CollaborationState, key: string, taskId: string, document: unknown, tx: OutcomeTransaction): void {\n this.commitCallback(state, tx.rows, taskId, { kind: 'outcome', turnId: key, taskId, document: document as Json }, {\n publish: tx.publish,\n ...this.deliverPort(state, taskId),\n outcome: {\n // The terminal transaction has not written yet, so a ledger snapshot is the committed state.\n committed: { intent: key => intentRows(this.ledger.snapshot()).intent(key) },\n ...botOutcomePorts({ taskId, routines: tx.routines, roomPosts: !!this.options.roomHistory,\n manage: (turn, outcome, managed) => applyManagement(state, turn.botId, taskId, outcome, this.models(), managed, this.options.readOnlyToolsets) }),\n },\n });\n }\n /** The refused terminals of the last K4 drain: one audit row for each new key and reason, and the error of the pass. */\n private reportIntentFailures(): IntentOutcomeError | undefined {\n const failures = [...this.intentFailures.values()], fresh = failures.filter(f => this.auditedFailures.get(f.key) !== f.message);\n if (fresh.length) {\n this.write(s => {\n const state = stateOf(s.application);\n for (const f of fresh) state.audit.push(`Intent outcome refused ${f.code}: ${f.key} ${f.message}`.slice(0, 1024));\n });\n for (const f of fresh) this.auditedFailures.set(f.key, f.message);\n }\n return failures[0];\n }\n /**\n * Host intent (#882): the Host's own work in this tenant's K4 FIFO, with Host authority. One transaction enqueues the\n * intent and records its handler name. Its outcome goes to that handler, never to a Bot Turn. An exact replay returns\n * the same intent. On a Bot's agentRef, it shares that Bot's FIFO.\n */\n enqueueHostIntent(input: IntentInput, handler: string): Promise<Intent> {\n return this.exclusive(async () => {\n if (!this.hostIntentHandlers.has(handler)) throw new Error(`Unknown Host intent handler: ${handler}`);\n // Only K8's own hooks promote an occurrence.\n if (isOccurrenceIntentKey(input.key)) throw new Error('Host intent identity conflict: the key is an occurrence');\n if (input.execution.payload.messageEgress && !this.hostIntentMessageHandlers.has(handler)) {\n throw new Error(`Host intent handler ${handler} has no message handler`);\n }\n // A restart admits every open intent, so a Host intent passes the same toolset admission as a Bot execution.\n admitBotToolsets(input.execution, this.options.readOnlyToolsets);\n this.write(s => {\n const state = stateOf(s.application), owner = hostIntent(state, input.key);\n if (Object.hasOwn(state.turns, input.key)) throw new Error('Host intent identity conflict: the key is a Bot Turn');\n if (owner ? owner.handler !== handler : s.intents[hash(input.key)]) throw new Error('Host intent identity conflict');\n // #957: a replay keeps its first answer; only a new intent is admitted.\n if (!owner) admitDevice(state, input.execution.deviceId);\n enqueue(s, this.ledger.tenant, input);\n // The key is the Host's string, so it is defined as an own property, never through a setter such as `__proto__`.\n Object.defineProperty(state.hostIntents ??= {}, input.key, { value: { handler }, enumerable: true, writable: true, configurable: true });\n });\n await this.process();\n return this.core.intent(input.key)!;\n });\n }\n /**\n * Owner API (#1320): cancels a Host intent through K4, which records the cancel on the intent row. A settled intent returns\n * `already_settled` and sends nothing, so a replay does not fail. An unsubmitted intent returns `cancelled` once its cancel\n * commits; `conclusion` is absent if a failed drain or process pass leaves settlement unfinished. A later successful\n * drain settles it without running its handler and advances its FIFO. Replay to read `already_settled` with its conclusion,\n * or `cancel_pending` while a submitted intent awaits its terminal. A submitted intent gets an SDK cancel; a\n * `task.complete` that arrived before the cancel still runs the handler once. A `handler_failed` intent stays stuck,\n * because K4 applies its terminal again: `failStuckIntent` settles it. Refuses a Bot Turn key and an unknown key.\n *\n * After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged\n * first drain or process rejection (the whole AggregateError for mixed failures), even if a later pass succeeds.\n * A drain error comes from that same drain, which coalesces with an in-flight drain and may fail on other Host work.\n * Check `'drainError' in result`, report it and retry pending work with `drain()` or recovery. The cancellation\n * committed; reconciliation may be unfinished. Job/outbox retry state is unchanged; explicit drains and wake hooks\n * still reject. Pre-commit failures still reject.\n */\n cancelHostIntent(key: string, ...by: PrincipalArg): Promise<HostIntentCancelResult> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'cancelHostIntent', key);\n const snapshot = this.ledger.snapshot(), state = stateOf(snapshot.application), intent = snapshot.intents[hash(key)];\n const settled = hostIntentCancelAnswer(key, Object.hasOwn(state.turns, key), hostIntent(state, key) && intent);\n if (settled) return { key, ...settled };\n const dispatch = await this.core.cancel(key);\n try { await this.process(); }\n catch (error) {\n if (error instanceof WakeDispatchError) dispatch.wakePending = true;\n else if (!('drainError' in dispatch)) dispatch.drainError = error;\n }\n if (intent!.phase === 'inflight') return { key, result: 'cancel_pending', ...dispatch };\n const conclusion = this.core.intent(key)?.conclusion;\n return { key, result: 'cancelled', ...(conclusion === undefined ? {} : { conclusion }), ...dispatch };\n });\n }\n /**\n * Cancel selected Host intents atomically without a pass. A submitted intent refuses the whole set; after a successful\n * call, successors wait for the next pass, or the Host can call `drain()`. Results keep input order and are replayable.\n */\n cancelHostIntents(keys: readonly string[], ...by: PrincipalArg): Promise<(IntentCancelResult<Conclusion> & { result: 'cancelled' | 'already_settled'; conclusion: Conclusion })[]> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'cancelHostIntents', keys.join(' '));\n const seen = new Set<string>();\n for (const key of keys) { if (seen.has(key)) throw new Error(`Duplicate Host intent key: ${key}`); seen.add(key); }\n return this.write(s => {\n const state = stateOf(s.application), rejected: { key: string; code: HostIntentError['code'] }[] = [];\n for (const key of keys) {\n const intent = s.intents[hash(key)];\n if (Object.hasOwn(state.turns, key)) rejected.push({ key, code: 'not_host_intent' });\n else if (!hostIntent(state, key) || !intent) rejected.push({ key, code: 'unknown_intent' });\n else if (!intent.conclusion && intent.phase === 'inflight') rejected.push({ key, code: 'inflight' });\n }\n if (rejected.length) {\n const first = rejected[0]!;\n const message = first.code === 'inflight' ? 'The intent is in flight: use cancelHostIntent'\n : first.code === 'not_host_intent' ? 'The key is a Bot Turn: use cancelTurn' : 'No Host intent has this key';\n throw new HostIntentError(first.key, first.code, message, rejected);\n }\n return keys.map(key => {\n const intent = s.intents[hash(key)]!;\n if (intent.conclusion) return { key, result: 'already_settled' as const, conclusion: intent.conclusion };\n intent.cancelReason = 'cancelled'; settle(s, intent, 'cancelled');\n return { key, result: 'cancelled' as const, conclusion: 'cancelled' as const };\n });\n });\n });\n }\n /**\n * Owner API (#882): settles as `failed` an open intent whose K4 terminal K8 refuses with `IntentOutcomeError`, so its FIFO\n * moves on. A fresh K4 drain decides that the intent is stuck, so the call also works right after a restart. One transaction\n * settles it and writes the audit row. The settle runs no handler, and the intent records no terminal; the server task\n * keeps it. The drain before the settle applies the terminal once more, so a `handler_failed` handler runs once inside\n * the call. If that drain applies the outcome, the call refuses with `already_settled`. A Bot Turn records the refusal\n * code as its `settleCode`. A Host intent keeps its `hostIntents` record until K4 compacts it, so an exact replay of\n * `enqueueHostIntent` returns the failed intent. Refuses with `HostIntentError`: `unknown_intent`, `already_settled`, and\n * `not_stuck` for an intent whose terminal K8 did not refuse.\n */\n failStuckIntent(key: string, ...by: PrincipalArg): Promise<void> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'failStuckIntent', key);\n openIntent(this.ledger.snapshot().intents, key);\n this.intentFailures.clear();\n // A scan that stopped early may not have reached this key, so its error is the cause when the key has no refusal.\n const drained = await this.core.drain().then(() => undefined, (error: unknown) => ({ error }));\n const refused = this.intentFailures.get(key);\n this.write(s => {\n const intent = openIntent(s.intents, key);\n if (!refused) throw drained ? drained.error : new HostIntentError(key, 'not_stuck', `Intent is not stuck: ${key} has no refused terminal`);\n settle(s, intent, 'failed');\n // Only a Bot Turn's outcome commit refuses with `outcome_failed`, so the key is a Turn.\n if (refused.code === 'outcome_failed') stateOf(s.application).turns[key]!.settleCode = refused.code;\n stateOf(s.application).audit.push(`Intent failed by owner ${refused.code}: ${key} ${refused.message}`.slice(0, 1024));\n });\n this.intentFailures.delete(key);\n this.auditedFailures.delete(key);\n await this.process();\n });\n }\n /** The channel outbox port of a K4 callback. Delivery code reads the committed ledger. */\n private deliverPort(state: CollaborationState, taskId: string): Pick<CommandPorts, 'deliver' | 'promote'> {\n if (!this.options.channel) return {};\n return { deliver: (turn, key, text, staged) => queueDelivery(this.ledger.snapshot(), state, turn, taskId, key, text, this.now(), staged)?.id,\n promote: id => promoteStaged(state, id) };\n }\n /** An owner command in its own ledger transaction. K4 callbacks use `commitCallback` inside the K4 transaction. */\n private commitOwner(commandId: string, command: Command, extra?: (s: LedgerState, state: CollaborationState) => Partial<CommandPorts>): CommitResult {\n return commitInLedger(this.ledger, { scope: this.ledger.tenant, commandId, command }, s => {\n const state = stateOf(s.application);\n return { now: this.now, admit: next => admitCommand(state, next), publish: (key, value) => project(s, key, value), intents: intentRows(s),\n admitInput: fields => admitUserInput(state, fields, this.coalesce, this.now()),\n updatePersona: (botId, persona) => updateBot(state, { botId, persona }, this.models(), this.options.readOnlyToolsets),\n routes: {\n enable: (conversation, channel, target, owner) => enablePush(state, conversation, channel, target, owner, this.now()).id,\n revoke: routeId => revokePush(state, routeId, this.now()),\n resend: deliveryId => resendUnknown(state, deliveryId, this.now()).id,\n }, ...extra?.(s, state) };\n });\n }\n /** A keyless owner command (#739 6a). Its id is new at each call, because the store keeps no record of it. */\n private commitKeyless(command: KeylessCommand): CommitResult { return this.commitOwner(randomUUID(), command); }\n private commitCallback(state: CollaborationState, rows: ApplicationRows, commandId: string, command: Command,\n ports: Omit<CommandPorts, 'now'>): CommitResult {\n return commitInRows(state, this.ledger.tenant, { scope: this.ledger.tenant, commandId, command }, rows, { now: this.now, ...ports });\n }\n\n /**\n * Install as the server's `agentMessage.consume`. One ledger transaction\n * checks the exact binding and records the first acceptance (§3.3).\n */\n async consumeMessage(input: AgentMessageInput): Promise<{ outcome: 'accepted' | 'refused'; reasonCode?: string }> {\n if (this.closed) throw new Error('Bot Host is closed');\n refuseExported(this.snapshot());\n const result = await this.core.consumeMessage(input);\n if (result.outcome === 'accepted') queueMicrotask(() => { if (!this.closed) void this.drain().catch(() => {}); });\n return result;\n }\n private applyMessage(input: AgentMessageInput, tx: MessageTransaction): { outcome: 'accepted' | 'refused'; reasonCode?: string } {\n const state = stateOf(tx.application);\n refuseExported(state);\n const name = hostIntent(state, tx.intent.key)?.handler, handler = name === undefined ? undefined : this.hostIntentMessageHandlers.get(name);\n let disposition;\n try {\n ({ disposition } = this.commitCallback(state, tx.rows, `${input.taskId}:${input.payload.messageId}`,\n { kind: 'message', turnId: tx.intent.key, message: { taskId: input.taskId, payload: input.payload } },\n { publish: tx.publish, ...this.deliverPort(state, input.taskId),\n ...(handler ? { hostMessage: () => hostMessageDisposition(handler(input, tx)) } : {}) }));\n } catch (cause) {\n // Other content for the id of a refused message: the same refusal that K4 gives for an accepted one.\n if (cause instanceof CommitConflict && cause.code === 'identity_conflict') return { outcome: 'refused', reasonCode: 'message_conflict' };\n throw cause;\n }\n return disposition.outcome === 'accepted' ? { outcome: 'accepted' } : { outcome: 'refused', reasonCode: disposition.reasonCode };\n }\n /**\n * Owner API (\"Cancel\", §8.8), from A's delegation chip or from B's `bot_request` Turn. Idempotent (#1405): an earlier cancel\n * gives `cancel_pending` and a verdict `already_settled`, and neither writes or sends. Refuses with `DelegationError`.\n * It rejects when `core.cancel` fails. The cancel fact is already committed, and the timer delivers it later.\n */\n cancelDelegation(id: string, ...by: PrincipalArg): Promise<DelegationCancelResult> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'cancelDelegation', id);\n const settled = delegationCancelAnswer(this.snapshot(), id);\n if (settled) return { delegationId: id, ...settled };\n await this.settleChain(this.commitKeyless({ kind: 'cancel_delegation', delegationId: id }));\n return { delegationId: id, result: 'cancelled' };\n });\n }\n /** Owner API (\"End\", §8.3): close a held reply or an uncertain delegation with `abandoned`. */\n abandonDelegation(id: string, ...by: PrincipalArg): Promise<void> {\n return this.exclusive(() => {\n this.ownerOnly(by, 'abandonDelegation', id);\n return this.settleChain(this.commitKeyless({ kind: 'abandon_delegation', delegationId: id }));\n });\n }\n /** A committed cancel fact is delivered after the commit. */\n private async settleChain(result: CommitResult): Promise<void> {\n if (valueOf<{ deliver: boolean }>(result).deliver) await this.deliverCancels();\n await this.process();\n }\n /** The slot admission of one device (#1229 item 1): user-source work may take the last slot, other work may not. */\n private admitsDeviceSlot(intent: Intent, state: LedgerState): boolean {\n const rows = Object.values(state.intents).map(row => dispatchRow(state, row));\n return admitDeviceSlot(rows.find(row => row.id === intent.id) ?? dispatchRow(state, intent), rows, this.deviceConcurrency);\n }\n /**\n * Deliver each committed cancel to its frozen target (§8.8). A crash before\n * `delivered` leaves the fact for the next pass. It never picks a new Turn.\n */\n private async deliverCancels(): Promise<void> {\n for (const d of Object.values(this.snapshot().delegations)) {\n if (!d.cancel || d.cancel.delivered) continue;\n const result = await this.core.cancel(d.cancel.targetTurnId);\n if ('drainError' in result) throw result.drainError;\n this.write(s => { stateOf(s.application).delegations[d.id]!.cancel!.delivered = true; });\n }\n }\n\n /**\n * Host persona mode (#879): the Host applied `revision` of this Bot's profile to its Agent home. The current revision\n * readies the Bot. An older revision changes nothing, and a newer one refuses.\n */\n async personaReady(botId: string, revision: string): Promise<void> {\n await this.exclusive(async () => {\n this.commitKeyless({ kind: 'persona_ready', botId, revision });\n await this.process();\n });\n }\n /** Owner API. Advance the desired revision after a rejected persona delivery. */\n async retryPersona(botId: string): Promise<void> {\n await this.exclusive(async () => {\n this.commitKeyless({ kind: 'retry_persona', botId });\n await this.process();\n });\n }\n /**\n * External team mode (#739 Q4c): apply the authority's team snapshot. The command id is its team revision,\n * so the same revision with the same Bots replays, and other Bots are an identity conflict. A revision that\n * is not newer, and not applied before, refuses with `stale_team` after the process pass.\n */\n async applyTeam(snapshot: TeamSnapshot): Promise<void> {\n await this.exclusive(async () => {\n const valid = teamSnapshot(snapshot);\n const { disposition } = this.commitOwner(hash(['team', valid.revision]), { kind: 'team_snapshot', snapshot: valid },\n (_s, state) => ({ teamBot: row => writeSnapshotBot(state, row, this.models(), this.options.readOnlyToolsets) }));\n await this.process();\n if (disposition.outcome === 'refused') throw new TeamModeError('stale_team', disposition.reason ?? 'stale_team');\n });\n }\n async setMainBot(botId: string, mainBot: boolean): Promise<void> {\n await this.exclusive(async () => {\n this.commitKeyless({ kind: 'set_main_bot', botId, mainBot });\n await this.process();\n });\n }\n /** The resolved autonomy of one Bot (#1229). A Bot without the field is in observe, the default of a new Bot. */\n autonomy(botId: string): Autonomy {\n const bots = this.snapshot().team.bots, bot = Object.hasOwn(bots, botId) ? bots[botId] : undefined;\n if (!bot) throw new Error('Bot not found');\n return autonomyOf(bot);\n }\n /** The would-do rows of one Bot, or of every Bot, oldest first (#1229). The Host UI lists these for the owner. */\n wouldDoRecords(botId?: string): WouldDo[] { return wouldDoRows(this.snapshot(), botId); }\n /**\n * The destination of every recorded inbound human message (#1229 item 3), oldest first. It is a projection of the\n * inbound, batch and Turn rows: the ledger holds no second disposition.\n */\n inboundDispositions(): InboundDisposition[] { return inboundDispositionsOf(this.snapshot()); }\n /**\n * Owner API (#1229): switch one Bot between observe and auto. Only the owner principal may switch. It applies to\n * outcomes recorded after the switch; a record made in observe is never replayed.\n */\n setBotAutonomy(botId: string, autonomy: Autonomy, ...by: PrincipalArg): Promise<void> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'setBotAutonomy', botId);\n if (autonomy !== 'observe' && autonomy !== 'auto') throw new Error('Invalid autonomy');\n this.commitKeyless({ kind: 'set_autonomy', botId, autonomy });\n await this.process();\n });\n }\n /** Any verified human can post in a room. The room message records the principal id; without one it is from `user`. */\n async roomInput(key: string, roomId: string, text: string, mentions: Mentions = [], ...by: PrincipalArg): Promise<string> {\n let id!: string;\n await this.exclusive(async () => {\n const principal = by.length ? this.verifiedOnly(by[0], 'roomInput', roomId) : undefined;\n // R5 and #1230: a bot message, and an ignored non-owner mention, are room background. They select no seat.\n const called = this.seatMentions(roomId, principal, mentions);\n const result = this.commitOwner(hash(['room_input', roomId, key]),\n { kind: 'room_input', key, roomId, text, mentions: called, ...(principal ? { from: principal.id } : {}) });\n id = turnOf(result);\n await this.process();\n });\n return id;\n }\n /**\n * Owner API (#1230): whether a structured mention from a non-owner human in this group opens seats. Only the owner\n * changes it, and only inbound messages that arrive after it see the new value.\n */\n async setMemberMentions(roomId: string, value: MemberMentions, ...by: PrincipalArg): Promise<void> {\n await this.exclusive(async () => {\n this.ownerOnly(by, 'setMemberMentions', roomId);\n this.commitKeyless({ kind: 'set_room_member_mentions', roomId, memberMentions: value });\n await this.process();\n });\n }\n /**\n * Owner API (#1321): create room `roomId` with no model run. The command id comes from the room id, so the same id with\n * the same fields replays, and other fields are an identity conflict.\n */\n async createRoom(roomId: string, fields: RoomFields): Promise<void> {\n await this.exclusive(async () => {\n this.commitOwner(hash(['create_room', roomId]), { kind: 'create_room', roomId, fields });\n await this.process();\n });\n }\n async updateRoom(roomId: string, update: Partial<RoomFields>): Promise<void> {\n await this.exclusive(async () => {\n this.commitKeyless({ kind: 'update_room', roomId, update });\n await this.process();\n });\n }\n async answer(id: string, answer: string, ...by: PrincipalArg): Promise<void> {\n await this.exclusive(async () => {\n this.ownerOnly(by, 'answer', id);\n this.commitOwner(hash(['answer', id]), { kind: 'answer', questionId: id, answer });\n await this.process();\n });\n }\n /** For IM, call it only from a verified button callback, never for a text command (R2). */\n async decide(id: string, decision: 'confirmed' | 'rejected', ...by: PrincipalArg): Promise<void> {\n await this.exclusive(async () => {\n this.ownerOnly(by, 'decide', id);\n let error: string | undefined;\n try {\n const { disposition } = this.commitOwner(hash(['decide', id]), { kind: 'decide', cardId: id, decision });\n if (disposition.outcome === 'refused') error = disposition.reason;\n } catch (cause) {\n // A different decision for a decided card throws after the process pass, as a refused decision does.\n if (!(cause instanceof CommitConflict) || cause.code !== 'identity_conflict') throw cause;\n error = cause.message;\n }\n await this.process();\n if (error) throw new Error(error);\n });\n }\n /** Owner API for the Main Bot's own routines. */\n async setRoutineLifecycle(id: string, value: Routine['lifecycle']): Promise<void> {\n await this.exclusive(async () => {\n // #975: the K4 core writes this itself, outside the K8 write fence.\n refuseExported(this.snapshot());\n try { await this.core.lifecycle(owned(this.routineRows(), this.options.botId, id).definition.id, value); }\n finally { await this.process(); }\n });\n }\n /** Owner API (§55c): completes any open Bot routine, an archived owner's too, with this Host's Main Bot authority. */\n async endRoutine(id: string): Promise<void> {\n await this.exclusive(async () => {\n try {\n this.commitOwner(randomUUID(), { kind: 'end_routine', botId: this.options.botId, routineId: id }, s => ({ routines: {\n end: routineId => setLifecycle(s, endable(Object.values(s.routines), routineId).definition.id, 'completed', this.now(), routineCalendar) } }));\n } finally { await this.process(); }\n });\n }\n async updateRoutine(action: UpdateRoutineAction): Promise<void> {\n await this.exclusive(async () => {\n refuseExported(this.snapshot());\n try { await this.core.updateRoutine(updateDefinition(this.routineRows(), this.options.botId, ownerRoutineUpdate(action))); }\n finally { await this.process(); }\n });\n }\n private routineRows(): Routine[] { return Object.values(this.ledger.snapshot().routines); }\n /** K4 records routine wakes. The `bot-routine` hook writes the routine Turn in the same commit. */\n readonly consume = (wake: DueWake, signal: AbortSignal): Promise<void> => this.exclusive(async () => {\n signal.throwIfAborted();\n this.write((s, rows) => { this.sync(s, rows); });\n try { await this.core.consume(wake, signal); } finally { await this.process(); }\n });\n drain(): Promise<void> { return this.exclusive(() => this.process()); }\n /**\n * Owner API. Cancels a Turn, an input batch by its id or a member input id, or B's chain Turn through its delegation.\n * Idempotent (#1405): a Turn whose K4 intent already has a cancel gives `cancel_pending`, and an ended Turn\n * `already_settled`; neither writes or calls `core.cancel`.\n * After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged\n * first drain rejection (the whole AggregateError for mixed failures), even if a later pass retries it successfully.\n * Its presence means cancellation committed, not that reconciliation finished. Inspect/report it and retry pending\n * work with `drain()` or recovery, rather than repeating the cancellation. Job/outbox retry state is unchanged;\n * explicit drains and wake hooks still reject. Pre-commit failures still reject.\n */\n cancelTurn(id: string, ...by: PrincipalArg): Promise<TurnCancelResult & { wakePending?: true; drainError?: unknown }> {\n return this.exclusive(async () => {\n this.ownerOnly(by, 'cancelTurn', id);\n return this.cancelOneTurn(id);\n });\n }\n private async cancelOneTurn(id: string): Promise<TurnCancelResult & { wakePending?: true; drainError?: unknown }> {\n // The read and the commit run in one synchronous step, so no K4 transaction lands between them.\n const snapshot = this.ledger.snapshot(), settled = turnCancelAnswer(stateOf(snapshot.application), intentRows(snapshot), id);\n if (settled) return { turnId: id, ...settled };\n const result = this.commitKeyless({ kind: 'cancel_turn', turnId: id });\n const value = valueOf<{ deliver: boolean } | { target: string; admitted: boolean }>(result);\n const dispatch = 'target' in value && value.admitted ? await this.core.cancel(value.target) : {};\n try {\n if ('deliver' in value) await this.settleChain(result);\n else await this.process();\n } catch (error) {\n if (error instanceof WakeDispatchError) dispatch.wakePending = true;\n else if (!('drainError' in dispatch)) dispatch.drainError = error;\n }\n return { turnId: id, result: 'cancelled', ...dispatch };\n }\n /** The L owner record of a device (#957, §4.1). A device with no record is L at revision 0. */\n topology(deviceId: string): DeviceTopology { return deviceTopology(this.snapshot(), deviceId); }\n /**\n * Step 1 of a switch away from L (#957, §4.1): durably freezes new work on the device and returns the record read back\n * from the ledger. From the commit on, each entry that can create execution for the device refuses with\n * `DeviceSwitchingError`, and the sync holds the device's Turns. Raises the revision.\n */\n freezeForSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology> {\n return this.exclusive(async () => {\n this.write(s => switchStep(s, deviceId, expectedRevision, 'freeze'));\n return this.topology(deviceId);\n });\n }\n /**\n * Step 2: the device's open work. With `cancel`, cancels every open intent and every open Turn and input batch, then runs a\n * pass. Returns the work still open: a tried intent stays open until the reconciler reads its terminal. Waits for nothing.\n */\n drainForSwitch(deviceId: string, { cancel = false }: { cancel?: boolean } = {}): Promise<SwitchWork> {\n return this.exclusive(async () => {\n const work = this.write(s => {\n if (!deviceTopology(stateOf(s.application), deviceId).switching) throw new Error(`Device ${deviceId} is not switching`);\n const open = switchWork(s, deviceId);\n if (cancel) for (const key of open.intents) s.intents[hash(key)]!.cancelReason ??= 'cancelled';\n return open;\n });\n if (cancel) {\n for (const id of [...work.batches, ...work.turns]) await this.cancelOneTurn(id);\n await this.process();\n }\n return switchWork(this.ledger.snapshot(), deviceId);\n });\n }\n /**\n * Step 3 (#975): seals the domain's whole state into a switch export, after each of its devices is frozen at the given\n * revision and drained. The export must name every device of a live Bot. From the export on, this Host writes nothing to\n * the ledger, also after a restart, so the commit away can check that the ledger still holds what was exported. Refuses\n * Agent memory, a pending projection (flush them first), and a pending Host job, which K4 would run while the export\n * waits for its commit.\n */\n exportForSwitch(devices: { deviceId: string; expectedRevision: number }[], exportedAt = this.now()): Promise<SwitchExport> {\n return this.exclusive(async () => {\n const state = this.snapshot();\n refuseExported(state);\n for (const { deviceId, expectedRevision } of devices) {\n const row = deviceTopology(state, deviceId);\n if (row.revision !== expectedRevision) {\n throw new CommitConflict('stale_revision', `Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`);\n }\n if (row.mode !== 'L') throw new DeviceModeError(deviceId, row.mode, row.revision);\n if (!row.switching) throw new Error(`Device ${deviceId} is not switching`);\n if (!switchDrained(switchWork(this.ledger.snapshot(), deviceId))) throw new Error(`Device ${deviceId} still has open work`);\n }\n const header: SwitchHeader = { source: 'L', domain: this.ledger.tenant, exportedAt,\n devices: devices.map(({ deviceId, expectedRevision }) => ({ deviceId, frozenRevision: expectedRevision })) };\n // The dump, the seal and the mark run with no await between them, so no other write of this process comes between.\n const dump = this.ledger.dumpForSwitch();\n const job = Object.values(dump.body.outbox).find(row => row.kind === 'host-job');\n if (job) throw new SwitchExportError('open_work', `Switch export source: Host job ${job.occurrenceKey} is pending; let it run first`);\n const document = sealSwitchExport(switchContent(dump, this.ledger.tenant, header));\n this.ledger.transaction(s => {\n stateOf(s.application).switchExport = { digest: document.manifest.digest, exportedAt, devices: document.devices.map(device => ({ ...device })) };\n });\n return document;\n });\n }\n /**\n * Step 5, after the new owner imported and verified the export: L records that the new owner owns the whole domain. Every\n * device of the export moves to H in one transaction, on its frozen revision, only when none has open work and `receipt`\n * is the digest of this Host's export. The ledger is sealed again under the export's header and must give the same\n * digest. `deviceId` and `expectedRevision` name one device of the export, whose record is returned. Every entry then\n * refuses those devices with `DeviceModeError`, also after a restart. The export stays, so this Host keeps writing nothing.\n */\n commitSwitch(deviceId: string, expectedRevision: number, receipt: string): Promise<DeviceTopology> {\n return this.exclusive(async () => {\n // The device checks first, on a copy, so a device that is not ready refuses the same way with or without an export.\n switchStep(structuredClone(this.ledger.snapshot()), deviceId, expectedRevision, 'commit');\n const mark = this.snapshot().switchExport;\n if (!mark) throw new Error('This Host has not exported its domain for a switch');\n if (mark.digest !== receipt) throw new Error(`The receipt ${receipt} is not this Host's export ${mark.digest}`);\n if (!mark.devices.some(device => device.deviceId === deviceId && device.frozenRevision === expectedRevision)) {\n throw new Error(`Device ${deviceId} at revision ${expectedRevision} is not a device of the export`);\n }\n // The fence covers this Host's writes; the K4 core also writes on its own timers. A change to what moves refuses.\n const now = sealLedger(this.ledger, { source: 'L', domain: this.ledger.tenant, devices: mark.devices, exportedAt: mark.exportedAt });\n if (now.manifest.digest !== mark.digest) throw new Error(`The ledger changed after its export: ${now.manifest.digest}, not ${mark.digest}`);\n this.ledger.transaction(s => { for (const device of mark.devices) switchStep(s, device.deviceId, device.frozenRevision, 'commit'); });\n return this.topology(deviceId);\n });\n }\n /**\n * A failed export or check: clears the freeze on the frozen revision, so L owns the device again and held Turns run. An\n * abort of a device of the export ends the export, and the new owner discards its import. After the commit every device\n * of the export is owned by H, so none aborts.\n * After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged\n * process rejection (the whole AggregateError for mixed failures). Its presence means the abort committed, not that\n * reconciliation finished. Inspect/report it and retry pending work with `drain()` or recovery, rather than repeating\n * the abort with its now-stale revision. Job/outbox retry state is unchanged; explicit drains and wake hooks still\n * reject. A failure may concern other work or already be retried before return. Pre-commit failures still reject.\n */\n abortSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology & { wakePending?: true; drainError?: unknown }> {\n return this.exclusive(async () => {\n this.ledger.transaction(s => {\n const state = stateOf(s.application), step = switchStep(s, deviceId, expectedRevision, 'abort');\n if (state.switchExport?.devices.some(device => device.deviceId === deviceId)) delete state.switchExport;\n return step;\n });\n try { await this.process(); }\n catch (error) { return { ...this.topology(deviceId), ...(error instanceof WakeDispatchError ? { wakePending: true as const } : { drainError: error }) }; }\n return this.topology(deviceId);\n });\n }\n /**\n * Explicit retention (#798). Moves every row of each acknowledged settled root out of the state, and retires its ids.\n * A root that is still in use throws `RetentionRefused`, and nothing changes. Never runs on its own.\n */\n retain(input: RetentionInput): Promise<RetentionResult> {\n return this.exclusive(async () => retainInLedger(this.ledger, input, { contextTurnLimit: this.contextTurnLimit, handoff: this.handoff }));\n }\n recover(): Promise<void> {\n return this.exclusive(async () => {\n this.write((s, rows) => {\n for (const row of Object.values(stateOf(s.application).channel?.deliveries ?? {})) recoverDelivery(row);\n this.sync(s, rows);\n });\n try { await this.core.recover(); } finally { await this.process(); }\n });\n }\n private sync(s: LedgerState, rows: ApplicationRows, injected?: InjectedHistory): boolean {\n const state = stateOf(s.application);\n // A Host intent record lives as long as K4 keeps the intent, so a replay stays exact until K4 compacts it.\n // Its accepted message records (#1356) go with it.\n for (const key of Object.keys(state.hostIntents ?? {})) {\n if (s.intents[hash(key)]) continue;\n delete state.hostIntents![key];\n for (const [taskId, reply] of Object.entries(state.replies)) if (reply.turnId === key) delete state.replies[taskId];\n }\n syncHead(state, this.coalesce, this.now());\n reconcileDreamRoutines(s, this.dreaming, this.models(), this.now());\n const routines = botRoutines(Object.values(s.routines));\n const limits = { turnLimit: this.contextTurnLimit, contextMaxBytes: this.contextMaxBytes, instructionMaxBytes: this.instructionMaxBytes, handoff: this.handoff };\n const materialized = advanceRoomsAndTurns(s, state, this.now(), turn => syncTurnInLedger(this.ledger, s, rows, turn, { now: this.now(),\n models: Object.keys(this.models()), readOnlyToolsets: this.options.readOnlyToolsets ?? [], limits, historyMode: !!this.options.history,\n history: injected?.turns.get(turn.id), roomHistoryMode: !!this.options.roomHistory, roomHistory: injected?.rooms.get(turn.id), routines,\n offer: this.offer }), (key, value) => project(s, key, value));\n // After the Turns of this pass, so a dream queues behind them.\n const dreamed = syncDreams(s, { tenant: this.ledger.tenant, policy: this.dreaming, models: this.models(), instructionMaxBytes: this.instructionMaxBytes,\n now: this.now(), refused: botId => botDeviceRefusal(state, botId) !== undefined, history: injected?.dreams, historyMode: !!this.options.history });\n settleDelegations(s, state, this.now(), (key, value) => project(s, key, value), this.timers);\n reportCardDecisions(state, (key, value) => project(s, key, value));\n syncTail(state, s, this.now(), (key, value) => project(s, key, value));\n return materialized || dreamed;\n }\n /** Example reconcile loop (§3.10). K4 arms no scan after a settled intent, so the Host checks replies itself. */\n private async flushReplies(): Promise<void> {\n for (const d of Object.values(this.snapshot().delegations)) {\n if (!replyCheckDue(d, this.now())) continue;\n // A compacted chain intent has no readback evidence. It takes the failed readback path and cannot stop the pass.\n const intent = this.core.intent(d.chainTurnIds.at(-1)!);\n let check: ReplyCheck = { failed: true };\n if (intent) try {\n if (!this.server.tasks.agentMessage) throw new Error('Agent message readback API required');\n check = { taskId: intent.taskId, failed: false,\n readback: await this.server.tasks.agentMessage(intent.taskId, intent.execution.deviceId, intent.execution.payload.agentRef) };\n } catch { check = { taskId: intent.taskId, failed: true }; }\n this.write(s => {\n const state = stateOf(s.application);\n checkReply(state, state.delegations[d.id]!, check, this.now(), (key: string, value: Json) => project(s, key, value), this.timers.uncertainAfterMs);\n });\n }\n }\n private async callConnector(card: CollaborationState['cards'][string]): Promise<unknown> {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new Error(CONNECTOR_OUTCOME_UNKNOWN);\n controller.abort(error);\n reject(error);\n }, this.connectorTimeoutMs);\n });\n try {\n return await Promise.race([\n Promise.resolve().then(() => this.options.connector(card.id, card.action.action, card.action.draft, controller.signal)),\n deadline,\n ]);\n } finally { clearTimeout(timer); }\n }\n private async flushCards(): Promise<void> {\n await callCardsInLedger(this.ledger, card => this.callConnector(card));\n }\n private async flushDeliveries(): Promise<void> {\n const port = this.options.channel?.port;\n if (!port) return;\n if (port.readback) for (const old of Object.values(this.snapshot().channel?.deliveries ?? {}).filter(row => row.state === 'unknown')) {\n try {\n const result = await port.readback(old.id);\n this.write(s => {\n const row = stateOf(s.application).channel?.deliveries[old.id];\n if (row) readbackDelivery(row, old.attempts, result, this.now());\n });\n } catch { continue; } // Missing readback evidence leaves this row unknown.\n }\n for (const old of Object.values(this.snapshot().channel?.deliveries ?? {})) {\n const claim = this.write(s => {\n const state = stateOf(s.application), row = state.channel!.deliveries[old.id]!;\n if (row.state !== 'pending' || (row.nextAttemptAt ?? 0) > this.now()) return;\n const route = deliveryRoute(state, row, this.now());\n if (!route) { refuseRoute(state, row); return; }\n if (startDelivery(row, this.now())) return { row, route };\n });\n if (!claim) continue;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => { controller.abort(); reject(new Error('delivery_timeout')); }, this.deliveryTimeoutMs);\n });\n try {\n const result = await Promise.race([\n Promise.resolve().then(() => port.send({ deliveryId: claim.row.id, route: claim.route, body: claim.row.body }, controller.signal)), deadline,\n ]);\n this.write(s => settleDelivery(stateOf(s.application).channel!.deliveries[claim.row.id]!, claim.row.attempts, result, this.now()));\n } catch {\n // send has started: neither an exception nor a deadline proves absence.\n this.write(s => unknownDelivery(stateOf(s.application).channel!.deliveries[claim.row.id]!, claim.row.attempts,\n controller.signal.aborted ? 'send_timeout' : 'send_failed'));\n } finally { clearTimeout(timer); }\n }\n this.write(s => cleanReplyTokens(s, stateOf(s.application), this.now()));\n }\n /** One sync transaction. In history mode, phase 1 reads the history first, outside the transaction. */\n private async syncWithHistory(): Promise<boolean> {\n const injected = await this.readHistory();\n return this.write((s, rows) => this.sync(s, rows, injected));\n }\n private async readHistory(): Promise<InjectedHistory | undefined> {\n const read = this.options.history, readRoom = this.options.roomHistory;\n if (!read && !readRoom) return undefined;\n const ledger = this.ledger.snapshot(), state = stateOf(ledger.application);\n const injected = { turns: new Map<string, { rows: ContextTurn[]; digest: string }>(), rooms: new Map<string, { rows: RoomMessage[]; digest: string }>(),\n dreams: new Map<string, readonly ContextTurn[] | null>() };\n for (const turn of Object.values(state.turns)) {\n if (!awaitsOffer(ledger, state, turn) || this.unread.has(turn.id)) continue;\n const seat = turn.source === 'room_slot' ? state.team.seats[turn.id] : undefined;\n try {\n if (seat && readRoom && !seat.released) {\n const roomId = state.team.rounds[seat.roundId]!.roomId;\n // Q2 A (#883): the Host writes each post to its authority before the next seat reads it. A seat whose room still has\n // an undelivered post waits like a failed read, so the pass does not spin and the timer looks again.\n if (Object.values(ledger.outbox).some(row => row.kind === 'projection' && row.id.startsWith(roomMessageProjection(roomId, ''))\n && (row.value as { roomId?: unknown }).roomId === roomId)) { this.unread.add(turn.id); continue; }\n // A read still open at the seat deadline fails too, so the sync can expire the seat (#883).\n const ms = Math.min(this.historyTimeoutMs, seat.deadline === undefined ? Infinity : seat.deadline - this.now());\n const rows = roomMessages(await bounded(readRoom({ roomId, botId: turn.botId, turnId: turn.id }), ms));\n injected.rooms.set(turn.id, { rows, digest: hash(canonical(rows)) });\n } else if (turn.source !== 'room_slot' && read) {\n const rows = contextTurns(await bounded(read({ botId: turn.botId, turnId: turn.id }), this.historyTimeoutMs));\n injected.turns.set(turn.id, { rows, digest: hash(canonical(rows)) });\n }\n } catch { this.unread.add(turn.id); }\n }\n if (read) for (const { key, botId, turnId } of dreamReads(state)) {\n injected.dreams.set(key, await bounded(read({ botId, turnId }), this.historyTimeoutMs).then(contextTurns).catch(() => null));\n }\n return injected;\n }\n /** A failed pass still re-arms the timer, so other timer work keeps its times. K4 retries a failed wake call itself. */\n private async process(): Promise<void> {\n try { await this.pass(); } finally { this.armTimer(); }\n }\n /**\n * A failed K4 drain does not stop the rest of the pass, so deliveries and reply checks still move their due times.\n * The pass does not repeat after it, and it rethrows the first drain error for the caller and the SDK hook.\n */\n private async pass(): Promise<void> {\n // An exported domain runs nothing: no sync, send, expiry or K4 drain changes what it holds (#975).\n if (this.snapshot().switchExport) return;\n this.unread.clear();\n let failure: { error: unknown } | undefined;\n let more: boolean;\n do {\n // A failed delivery keeps `delivered = false`. The timer retries it.\n await this.deliverCancels().catch(() => {});\n const admitted = await this.syncWithHistory();\n await flushHomes(this.server, this.ledger, this.now);\n this.intentFailures.clear();\n try { await this.core.drain(); } catch (error) { failure ??= { error }; }\n const refused = this.reportIntentFailures();\n if (refused) failure ??= { error: refused };\n // A Main Bot cancel applied in this drain commits with delivered = false.\n await this.deliverCancels().catch(() => {});\n let materialized = await this.syncWithHistory();\n await this.refreshDevices();\n await this.flushCards();\n materialized = await this.syncWithHistory() || materialized;\n await this.flushReplies();\n materialized = await this.syncWithHistory() || materialized;\n await this.flushDeliveries();\n const ledger = this.ledger.snapshot();\n // An immediate runtime terminal can create another turn on any pass.\n // Drain to a fixed point, so no application-only turn can lose its wake.\n const state = stateOf(ledger.application);\n more = admitted || materialized || Object.values(ledger.intents).some(intent => intent.phase === 'queued' && intent.cancelReason && !intent.conclusion)\n || Object.values(state.turns).some(turn => turn.status !== 'blocked' && awaitsOffer(ledger, state, turn) && !this.unread.has(turn.id));\n } while (more && !failure);\n if (failure) throw failure.error;\n }\n private armTimer(): void {\n clearTimeout(this.timer);\n if (!this.closed && !this.snapshot().switchExport) {\n // Durable state is authority. The timer only retries outbox work, expires cards and seals input batches at their window end.\n const ledger = this.ledger.snapshot(), state = stateOf(ledger.application);\n // K4 retries a failed wake call from its own timer.\n const due = [...(this.options.channel ? Object.values(state.channel?.deliveries ?? {}).filter(row => row.state === 'pending').map(row => row.nextAttemptAt ?? this.now()) : []),\n ...Object.values(state.channel?.inbounds ?? {}).filter(row => row.reply?.token).map(row => row.reply!.expiresAt),\n ...collaborationDue(state, this.timers),\n // #957: a refused device waits only for the readback of a sent write; it never gets a new one.\n ...state.team.homeOperations.filter(op => op.status === 'pending' && (homeSent(op) || !deviceRefusal(state, op.request.deviceId)))\n .map(op => Math.max(this.now() + 1000, op.retryAt ?? 0)),\n ...Object.values(state.delegations).filter(d => d.cancel && !d.cancel.delivered).map(() => this.now() + 1000),\n ...this.unread.size ? [this.now() + 1000] : []];\n if (due.length) {\n this.timer = setTimeout(() => { void this.drain().catch(() => {}); }, Math.max(1, Math.min(60_000, Math.min(...due) - this.now())));\n this.timer.unref?.();\n }\n }\n }\n private async refreshDevices(): Promise<void> {\n if (!this.server.machines) return;\n if (!Object.values(this.snapshot().delegations).some(d => !d.verdict && !d.cancel && (d.status === 'queued' || d.status === 'waiting_device'))) return;\n // A discovery failure must not block execution or invent an offline fact.\n let devices: Awaited<ReturnType<ByokServer['machines']['list']>>;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n devices = await Promise.race([\n this.server.machines.list(),\n new Promise<never>((_resolve, reject) => { timer = setTimeout(() => reject(new Error('Device discovery timed out')), 1000); }),\n ]);\n } catch { return; } finally { clearTimeout(timer); }\n this.write(s => observeDevices(s, stateOf(s.application), new Map(devices.map(d => [d.deviceId, d.connected])),\n (key, value) => project(s, key, value)));\n }\n async close(): Promise<void> {\n this.closed = true; clearTimeout(this.timer); await this.chain; clearTimeout(this.timer); await this.core.close();\n }\n}\n","import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';\nimport { hash } from '@byok-sdk/server/execution-core';\n\n/** Install on the daemon. SDK supplies the canonical home, writer lease and atomic file write. */\nexport function createBotPersonaProjection() {\n return createAgentHomeProjectionConsumer(async ({ projection, projectionHash, writeHomeFile }) => {\n if (!projection || typeof projection !== 'object' || !('schemaVersion' in projection)\n || projection.schemaVersion !== 'bot-profile.v1' || !('persona' in projection) || typeof projection.persona !== 'string'\n || projectionHash !== `sha256:${hash(projection)}`) throw new Error('Invalid Bot persona projection');\n await writeHomeFile('AGENTS.md', projection.persona);\n });\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import type { AgentEgressPolicy } from '@byok-sdk/client';
2
+ import type { ExecutionTemplate } from '@byok-sdk/server/execution-core';
3
+ /**
4
+ * #1845 S1: the K4 test data that K8 reads, owned here so K8 needs no private example to typecheck or to run its
5
+ * vectors. The values are the ones `examples/host-execution-core/src/test-support.ts` uses, so the daemon admits the
6
+ * same egress policy revision and the routine and delivery vectors see the same template.
7
+ * Only types come from the packages, so this module loads wherever the vectors do.
8
+ */
9
+ export declare const policy: AgentEgressPolicy;
10
+ export declare function template(deviceId: string, agentId?: string): ExecutionTemplate;
@@ -0,0 +1,72 @@
1
+ import { type DeviceCredentialBackend, type RuntimeAdapter, type RuntimeAdapterPrepareInput, type RuntimeAdapterPrepareResult, type RuntimeDetectResult, type RuntimeEnvironment, type RuntimeOperationStartInput, type Session } from '@byok-sdk/client';
2
+ import { type CreateByokServerOptions, type DueWake } from '@byok-sdk/server';
3
+ import { HostLedger, type HostLedgerOptions } from '@byok-sdk/server/execution-core';
4
+ /**
5
+ * #1325: a running L Host for the routine and delivery vectors, built only from published packages, so a Host that
6
+ * installs the package runs them too. It is the `externalCore` branch of K4's `openHost`: the caller drives its own core on the
7
+ * returned ledger, so the fixture creates none. The daemon admits only the `policyRevision` of the vectors' `template`,
8
+ * so both come from `./k4-fixtures.test-support` (#1845).
9
+ */
10
+ type Event = Session['events'] extends AsyncIterable<infer E> ? E : never;
11
+ /** A stub runtime session: the test ends it with `finish(document)`, which submits the result document. */
12
+ export declare class ResultStubSession implements Session {
13
+ private readonly input;
14
+ constructor(input: RuntimeOperationStartInput);
15
+ readonly sessionRef: `${string}-${string}-${string}-${string}-${string}`;
16
+ interrupted: boolean;
17
+ closed: boolean;
18
+ steered: number;
19
+ followedUp: number;
20
+ private readonly resultAbort;
21
+ private readonly finishing;
22
+ private closing;
23
+ private pending;
24
+ private failure;
25
+ private wake;
26
+ readonly events: AsyncIterable<Event>;
27
+ emit(event: Event): void;
28
+ /**
29
+ * Resolves after result submission and event injection; failures still travel through events. `text` is the final runtime
30
+ * text, which a required message egress publishes as the Agent message.
31
+ */
32
+ finish(document: unknown, submit?: boolean, text?: string): Promise<void>;
33
+ fail(): void;
34
+ steer(): Promise<void>;
35
+ followUp(): Promise<void>;
36
+ interrupt(): Promise<void>;
37
+ /** Read only for a descriptor that declares `trajectoryEvidence`; the stub drops no runtime output. */
38
+ evidence(): {
39
+ decodeDropped: number;
40
+ unmappedFrames: number;
41
+ syntheticToolResults: number;
42
+ };
43
+ close(): Promise<void>;
44
+ }
45
+ /** A stub `pi` runtime that spawns nothing. `sessions` maps each started task id to its session. */
46
+ export declare class ResultStubAdapter implements RuntimeAdapter {
47
+ readonly descriptor: import("@byok-sdk/client").RuntimeAdapterDescriptor;
48
+ readonly sessions: Map<string, ResultStubSession>;
49
+ readonly starts: RuntimeOperationStartInput[];
50
+ rejectNext: boolean;
51
+ runtimeEnvironment(): Promise<RuntimeEnvironment>;
52
+ detect(): Promise<RuntimeDetectResult>;
53
+ prepare(_input: RuntimeAdapterPrepareInput): Promise<RuntimeAdapterPrepareResult>;
54
+ }
55
+ /** Starts an embedded SQLite server, pairs one daemon that runs `adapter`, and opens the Host ledger. */
56
+ export declare function openLTestHost(options: {
57
+ deviceCredentials: DeviceCredentialBackend;
58
+ consume: (wake: DueWake, signal: AbortSignal) => Promise<void>;
59
+ ledgerOptions?: HostLedgerOptions;
60
+ adapter?: ResultStubAdapter;
61
+ agentMessage?: CreateByokServerOptions['agentMessage'];
62
+ }): Promise<{
63
+ root: string;
64
+ ledgerPath: string;
65
+ server: import("@byok-sdk/server").ByokServer;
66
+ ledger: HostLedger;
67
+ deviceId: string;
68
+ adapter: ResultStubAdapter;
69
+ close(): Promise<void>;
70
+ }>;
71
+ export type LTestHost = Awaited<ReturnType<typeof openLTestHost>>;
72
+ export {};