@byok-sdk/bot-collaboration 0.44.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -13
- package/dist/chunk-4HLCBNWV.js +29 -0
- package/dist/chunk-4HLCBNWV.js.map +1 -0
- package/dist/chunk-DDKTPJ7B.js +11 -0
- package/dist/chunk-DDKTPJ7B.js.map +1 -0
- package/dist/{chunk-6X7ARUDF.js → chunk-DYQSVSPJ.js} +3 -3
- package/dist/{chunk-6X7ARUDF.js.map → chunk-DYQSVSPJ.js.map} +1 -1
- package/dist/commit-vectors.test-support.d.ts +12 -11
- package/dist/delivery-vectors.test-support.d.ts +2 -1
- package/dist/host-kit.js +4 -4
- package/dist/host.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +9 -9
- package/dist/index.js.map +1 -1
- package/dist/persona.d.ts +36 -2
- package/dist/retention-vectors.test-support.d.ts +2 -1
- package/dist/routine-vectors.test-support.d.ts +2 -1
- package/dist/rules/coalesce.d.ts +10 -12
- package/dist/rules/commands.d.ts +3 -7
- package/dist/rules/index.js +1 -1
- package/dist/rules/schema.d.ts +2 -0
- package/dist/rules/sync.d.ts +2 -0
- package/dist/rules/turn.d.ts +5 -4
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +3 -4
- package/dist/testing.js.map +1 -1
- package/dist/vector-test-api.d.ts +35 -0
- package/package.json +7 -11
- package/dist/chunk-BGGEZHPC.js +0 -27
- package/dist/chunk-BGGEZHPC.js.map +0 -1
- package/dist/chunk-UXEHG75I.js +0 -11
- package/dist/chunk-UXEHG75I.js.map +0 -1
package/dist/host-kit.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitUserInput, botOutcomePorts, checkDreamInstruction, cleanReplyTokens, commitInLedger, deliveryRoute, dreamHolds, dreamIntentIds, dreamPolicy, dreamYield, echoCandidates, enablePush, exportMarkOf, inboundDisposition, inboundDispositions, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseRoute, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelivery, startDelivery, switchAttempts, syncDreams, syncHead, syncTail, unknownDelivery, verifySwitchExport } from './chunk-
|
|
2
|
-
export { BOT_DREAM, BOT_ROUTINE, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, RetentionRefused, SealedRoutineVersionError, TEAM_NOTE_LIMIT, applyHomeTerminal, applyManagement, applyModels, botRoutines, checkHomeReadback, classifyInbound, concludeRoutineTurn, contextPack, createDefinition, endable, failHomeFlush, homeEnqueued, homeHead, homeRequests, inboundKey, isOwner, owned, planHomeRetry, resealDefinition, retainRoots, routineCalendar, routineOccurrence, routineTurn, sealedDefinition, sealedTemplate, stateOf, supersededDeliveryIds, updateBot, updateDefinition, verified, writeSnapshotBot } from './chunk-
|
|
3
|
-
import { outcomeSchema, botTurnInstruction, promptActions } from './chunk-
|
|
4
|
-
export { BOT_REPLY_MAX_BYTES, CommitConflict, DEFAULT_AUTONOMY, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, DEFAULT_INSTRUCTION_MAX_BYTES, DEFAULT_MEMBER_MENTIONS, DEVICE_CONCURRENCY, DelegationError, HostIntentError, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, ROOM_GRACE_MS, RetiredIdentityError, SYSTEM_PROMPT, autonomyOf, contextTurns, historyRowFromTurn, memberMentions, minimumInstructionBytes, outcomeOffer, outcomeSchema, refuseRetired, retiredIdentity, revisionOf, wouldDoRows } from './chunk-
|
|
1
|
+
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitUserInput, botOutcomePorts, checkDreamInstruction, cleanReplyTokens, commitInLedger, deliveryRoute, dreamHolds, dreamIntentIds, dreamPolicy, dreamYield, echoCandidates, enablePush, exportMarkOf, inboundDisposition, inboundDispositions, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseRoute, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelivery, startDelivery, switchAttempts, syncDreams, syncHead, syncTail, unknownDelivery, verifySwitchExport } from './chunk-DDKTPJ7B.js';
|
|
2
|
+
export { BOT_DREAM, BOT_ROUTINE, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, RetentionRefused, SealedRoutineVersionError, TEAM_NOTE_LIMIT, applyHomeTerminal, applyManagement, applyModels, botRoutines, checkHomeReadback, classifyInbound, concludeRoutineTurn, contextPack, createDefinition, endable, failHomeFlush, homeEnqueued, homeHead, homeRequests, inboundKey, isOwner, owned, planHomeRetry, resealDefinition, retainRoots, routineCalendar, routineOccurrence, routineTurn, sealedDefinition, sealedTemplate, stateOf, supersededDeliveryIds, updateBot, updateDefinition, verified, writeSnapshotBot } from './chunk-DYQSVSPJ.js';
|
|
3
|
+
import { outcomeSchema, botTurnInstruction, promptActions } from './chunk-4HLCBNWV.js';
|
|
4
|
+
export { BOT_REPLY_MAX_BYTES, CommitConflict, DEFAULT_AUTONOMY, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, DEFAULT_INSTRUCTION_MAX_BYTES, DEFAULT_MEMBER_MENTIONS, DEVICE_CONCURRENCY, DelegationError, HostIntentError, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, ROOM_GRACE_MS, RetiredIdentityError, SYSTEM_PROMPT, autonomyOf, contextTurns, historyRowFromTurn, memberMentions, minimumInstructionBytes, outcomeOffer, outcomeSchema, refuseRetired, retiredIdentity, revisionOf, wouldDoRows } from './chunk-4HLCBNWV.js';
|
|
5
5
|
|
|
6
6
|
function botTurnInstruction2(options){const routines=options.routines??[];const schema=outcomeSchema(options.turn.botId,options.state,options.turn,options.models,routines,options.offer);const{instruction}=botTurnInstruction(options.state,options.turn,options.limits,routines,options.injected,options.room,promptActions(schema,options.offer));return {instruction}}
|
|
7
7
|
|
package/dist/host.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ import type { RoomFields } from '@byok-sdk/protocol';
|
|
|
17
17
|
import { type HomeServer } from './home-projections.js';
|
|
18
18
|
import { type DeviceTopology, type SwitchWork } from './topology.js';
|
|
19
19
|
import { type SwitchExport } from './migration.js';
|
|
20
|
-
import { type CoalescePolicy } from './coalesce.js';
|
|
20
|
+
import { type CoalescePolicy, type InputFields } from './coalesce.js';
|
|
21
21
|
import { type ChannelOptions, type Conversation, type InboundClass, type InboundMessage, type PrincipalArg } from './channel.js';
|
|
22
22
|
import type { InboundDisposition } from './rules/inbound.js';
|
|
23
23
|
export interface BotOptions {
|
|
@@ -216,7 +216,7 @@ export declare class BotCollaboration {
|
|
|
216
216
|
* (the first batched input's id); that Turn appears when the batch seals.
|
|
217
217
|
* Only the owner starts a 1:1 execution (R2).
|
|
218
218
|
*/
|
|
219
|
-
input(key: string,
|
|
219
|
+
input(key: string, input: string | Pick<InputFields, 'request' | 'images'>, botId?: string, ...by: PrincipalArg): Promise<string>;
|
|
220
220
|
/**
|
|
221
221
|
* Read-only (#1407): the id that `input` returned for this key, from its command record, or `undefined` when the
|
|
222
222
|
* input is not committed. It runs no `process()` and changes no ledger state, so a caller can tell whether an `input`
|
package/dist/index.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ export { BotCollaboration } from './host.js';
|
|
|
3
3
|
export { botCompactVeto, botLedgerOptions } from './compaction.js';
|
|
4
4
|
export type { AgentMessageInput, BotOptions, HostIntentCancelResult, HostIntentHandler, HostIntentMessageHandler, MessageServer } from './host.js';
|
|
5
5
|
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot, type TeamModeCode, type TeamSnapshot, type TeamSnapshotBot, type TeamSnapshotRoom } from './rules/team.js';
|
|
6
|
-
export { createBotPersonaProjection } from './persona.js';
|
|
6
|
+
export { createBotPersonaProjection, type BotPersonaProjectionContext, type BotPersonaProjectionOptions } from './persona.js';
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import { botLedgerOptions, checkTopology, checkSwitchRecords, botCompactVeto, K8_FORMAT, checkLedgerWouldDo, dreamPolicy, checkDreamInstruction, dreamYield, 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-
|
|
2
|
-
export { botCompactVeto, botLedgerOptions } from './chunk-
|
|
3
|
-
import { stateOf, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, supersededDeliveryIds, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-
|
|
4
|
-
import { refuseUnmigratedWouldDo, 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, DEVICE_CONCURRENCY, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, admitDeviceSlot, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-
|
|
5
|
-
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
1
|
+
import { botLedgerOptions, checkTopology, checkSwitchRecords, botCompactVeto, K8_FORMAT, checkLedgerWouldDo, dreamPolicy, checkDreamInstruction, dreamYield, 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-DDKTPJ7B.js';
|
|
2
|
+
export { botCompactVeto, botLedgerOptions } from './chunk-DDKTPJ7B.js';
|
|
3
|
+
import { stateOf, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, supersededDeliveryIds, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-DYQSVSPJ.js';
|
|
4
|
+
import { refuseUnmigratedWouldDo, 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, DEVICE_CONCURRENCY, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, admitDeviceSlot, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-4HLCBNWV.js';
|
|
5
|
+
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-4HLCBNWV.js';
|
|
6
|
+
import { statSync } from 'fs';
|
|
7
|
+
import { resolve } from 'path';
|
|
8
|
+
import { readSqliteSnapshot, SqliteSnapshotError } from '@byok-sdk/core/sqlite-node';
|
|
9
9
|
import { HostLedger, hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, WakeDispatchError, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
|
|
10
10
|
import { randomUUID } from 'crypto';
|
|
11
11
|
import { buildHandoffPack, ToolsetIdSchema } from '@byok-sdk/protocol';
|
|
12
12
|
import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
|
|
13
13
|
|
|
14
|
-
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);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,botLedgerOptions);try{const state=stateOf(ledger.snapshot().application);refuseUnmigratedWouldDo(state);checkTopology(state);checkSwitchRecords(state);return {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:"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||ledger.formats.k8!==K8_FORMAT)throw new Error("Open the Host ledger with botLedgerOptions");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(),state=stateOf(persisted.application),team=state.team;checkLedgerWouldDo(ledger,state);checkTopology(state);checkSwitchRecords(state);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 state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);this.commitCallback(state2,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state2,run)});},[BOT_DREAM]:(run,tx)=>{const state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);recordDream(state2,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),onSettled:()=>this.schedulePass(),admitSubmit:(intent,state2)=>!deviceRefusal(stateOf(state2.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state2),yieldUnclaimed:(state2,intent)=>dreamYield(stateOf(state2.application),intent.key)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state2=stateOf(s.application);if(options.team==="external"){state2.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state2.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(state2,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;passQueued=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")this.schedulePass();return result}schedulePass(){if(this.closed||this.passQueued)return;this.passQueued=true;queueMicrotask(()=>{void this.exclusive(async()=>{this.passQueued=false;await this.process();}).catch(()=>{});});}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(){let failure;for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;try{const target=this.core.intent(d.cancel.targetTurnId);const result=target&&!target.conclusion?await this.core.cancel(d.cancel.targetTurnId):{};this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});if("drainError"in result)throw result.drainError}catch(error){failure??={error};}}if(failure)throw failure.error}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;const deliveries=this.snapshot().channel?.deliveries??{},superseded=supersededDeliveryIds(deliveries);if(port.readback)for(const old of Object.values(deliveries).filter(row=>row.state==="unknown"&&!superseded.has(row.id))){try{const result=await port.readback(old.id);this.write(s=>{const current=stateOf(s.application).channel?.deliveries??{},row=current[old.id];if(row&&!supersededDeliveryIds(current).has(row.id))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);})}
|
|
14
|
+
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"};try{return readSqliteSnapshot(file,(db,copy)=>{try{if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'").get())throw new Error("Not a Host ledger");const ledger=new HostLedger(copy,tenant,botLedgerOptions);try{const state=stateOf(ledger.snapshot().application);refuseUnmigratedWouldDo(state);checkTopology(state);checkSwitchRecords(state);return {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:"rejected",...typeof code==="string"?{code}:{},reason:error instanceof Error?error.message:String(error)}}})??{store,path:file,verdict:"rejected",reason:"Not a Host ledger"}}catch(error){if(error instanceof SqliteSnapshotError&&error.reason==="changed")throw error;return {store,path:file,verdict:"rejected",reason:error instanceof Error?error.message:String(error)}}}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||ledger.formats.k8!==K8_FORMAT)throw new Error("Open the Host ledger with botLedgerOptions");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(),state=stateOf(persisted.application),team=state.team;checkLedgerWouldDo(ledger,state);checkTopology(state);checkSwitchRecords(state);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 state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);this.commitCallback(state2,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state2,run)});},[BOT_DREAM]:(run,tx)=>{const state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);recordDream(state2,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),onSettled:()=>this.schedulePass(),admitSubmit:(intent,state2)=>!deviceRefusal(stateOf(state2.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state2),yieldUnclaimed:(state2,intent)=>dreamYield(stateOf(state2.application),intent.key)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state2=stateOf(s.application);if(options.team==="external"){state2.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state2.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(state2,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;passQueued=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,input,botId=this.options.botId,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"input",botId);const{request,images}=typeof input==="string"?{request:input}:input;const result=this.commitOwner(hash(["input",botId,key]),{kind:"input",botId,key,request,sender:principal.id,...images===void 0?{}:{images}});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")this.schedulePass();return result}schedulePass(){if(this.closed||this.passQueued)return;this.passQueued=true;queueMicrotask(()=>{void this.exclusive(async()=>{this.passQueued=false;await this.process();}).catch(()=>{});});}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(){let failure;for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;try{const target=this.core.intent(d.cancel.targetTurnId);const result=target&&!target.conclusion?await this.core.cancel(d.cancel.targetTurnId):{};this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});if("drainError"in result)throw result.drainError}catch(error){failure??={error};}}if(failure)throw failure.error}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;const deliveries=this.snapshot().channel?.deliveries??{},superseded=supersededDeliveryIds(deliveries);if(port.readback)for(const old of Object.values(deliveries).filter(row=>row.state==="unknown"&&!superseded.has(row.id))){try{const result=await port.readback(old.id);this.write(s=>{const current=stateOf(s.application).channel?.deliveries??{},row=current[old.id];if(row&&!supersededDeliveryIds(current).has(row.id))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(options={}){return createAgentHomeProjectionConsumer(async({projection,projectionHash,writeHomeFile,agentRef,canonicalHome,requestId})=>{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");const context={agentRef,canonicalHome,requestId,projectionHash,projection};const files=options.renderAdditionalFiles?await options.renderAdditionalFiles(context):[];if(files.some(file=>file.name.toLowerCase()==="agents.md"))throw new Error("AGENTS.md is reserved for the Bot persona");await writeHomeFile("AGENTS.md",projection.persona);for(const file of files)await writeHomeFile(file.name,file.body);if(options.afterWrite)await options.afterWrite(context);})}
|
|
15
15
|
|
|
16
16
|
export { BotCollaboration, createBotPersonaProjection, inspectLedger };
|
|
17
17
|
//# sourceMappingURL=index.js.map
|