@byok-sdk/bot-collaboration 0.0.0-stage → 0.42.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/LICENSE +21 -0
- package/README.md +2058 -2
- package/dist/adapter-steps.d.ts +49 -0
- package/dist/channel.d.ts +111 -0
- package/dist/chunk-33YA66U7.js +7 -0
- package/dist/chunk-33YA66U7.js.map +1 -0
- package/dist/chunk-5J5SOWWI.js +12 -0
- package/dist/chunk-5J5SOWWI.js.map +1 -0
- package/dist/chunk-XTZUCECQ.js +12 -0
- package/dist/chunk-XTZUCECQ.js.map +1 -0
- package/dist/chunk-ZUFZCROA.js +27 -0
- package/dist/chunk-ZUFZCROA.js.map +1 -0
- package/dist/coalesce.d.ts +18 -0
- package/dist/commit-vectors.test-support.d.ts +173 -0
- package/dist/commit.d.ts +52 -0
- package/dist/compaction.d.ts +13 -0
- package/dist/delegation.d.ts +12 -0
- package/dist/delivery-routing.d.ts +63 -0
- package/dist/delivery-vectors.test-support.d.ts +78 -0
- package/dist/delivery.d.ts +20 -0
- package/dist/dream.d.ts +88 -0
- package/dist/home-projections.d.ts +5 -0
- package/dist/host-kit.d.ts +40 -0
- package/dist/host-kit.js +6 -0
- package/dist/host-kit.js.map +1 -0
- package/dist/host.d.ts +433 -0
- package/dist/inbound.d.ts +17 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/k4-fixtures.test-support.d.ts +10 -0
- package/dist/l-test-host.test-support.d.ts +72 -0
- package/dist/migration.d.ts +251 -0
- package/dist/model.d.ts +83 -0
- package/dist/persona.d.ts +2 -0
- package/dist/retention-vectors.test-support.d.ts +17 -0
- package/dist/retention.d.ts +61 -0
- package/dist/rooms.d.ts +22 -0
- package/dist/routine-vectors.test-support.d.ts +81 -0
- package/dist/routines.d.ts +110 -0
- package/dist/rules/autonomy.d.ts +67 -0
- package/dist/rules/cards.d.ts +31 -0
- package/dist/rules/coalesce.d.ts +111 -0
- package/dist/rules/commands.d.ts +306 -0
- package/dist/rules/commit.d.ts +82 -0
- package/dist/rules/compaction.d.ts +33 -0
- package/dist/rules/context.d.ts +484 -0
- package/dist/rules/delegation.d.ts +353 -0
- package/dist/rules/due.d.ts +15 -0
- package/dist/rules/frame.d.ts +4 -0
- package/dist/rules/history.d.ts +34 -0
- package/dist/rules/inbound.d.ts +53 -0
- package/dist/rules/index.d.ts +13 -0
- package/dist/rules/index.js +4 -0
- package/dist/rules/index.js.map +1 -0
- package/dist/rules/message.d.ts +31 -0
- package/dist/rules/outcome.d.ts +45 -0
- package/dist/rules/priority.d.ts +52 -0
- package/dist/rules/rooms.d.ts +187 -0
- package/dist/rules/schema.d.ts +110 -0
- package/dist/rules/sync.d.ts +157 -0
- package/dist/rules/team.d.ts +119 -0
- package/dist/rules/turn.d.ts +129 -0
- package/dist/schema.d.ts +154 -0
- package/dist/switch.d.ts +53 -0
- package/dist/team-model.d.ts +54 -0
- package/dist/team.d.ts +56 -0
- package/dist/testing.d.ts +6 -0
- package/dist/testing.js +20 -0
- package/dist/testing.js.map +1 -0
- package/dist/toolset-policy.d.ts +2 -0
- package/dist/topology.d.ts +49 -0
- package/package.json +80 -4
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { RoutineCommands } from '@byok-sdk/server/execution-core';
|
|
2
|
+
import { type CoalescePolicy } from './coalesce.js';
|
|
3
|
+
import { type IntentConclusions } from './delivery-routing.js';
|
|
4
|
+
import type { Publish } from './rules/delegation.js';
|
|
5
|
+
import type { CollaborationState } from './model.js';
|
|
6
|
+
import type { CommandPorts } from './rules/commands.js';
|
|
7
|
+
/**
|
|
8
|
+
* A K4 terminal that K8 cannot apply (#882 Q6f): its key is neither a Bot Turn nor a Host intent, its Host handler
|
|
9
|
+
* failed, or the outcome commit of its Bot Turn threw. The intent stays open at the head of its FIFO, and each pass rejects
|
|
10
|
+
* with this error, until the outcome applies or the owner calls `failStuckIntent`.
|
|
11
|
+
*/
|
|
12
|
+
export declare class IntentOutcomeError extends Error {
|
|
13
|
+
readonly key: string;
|
|
14
|
+
readonly code: 'unknown_intent' | 'handler_failed' | 'outcome_failed';
|
|
15
|
+
constructor(key: string, code: 'unknown_intent' | 'handler_failed' | 'outcome_failed', message: string);
|
|
16
|
+
}
|
|
17
|
+
type OutcomePorts = NonNullable<CommandPorts['outcome']>;
|
|
18
|
+
/** Routes a success terminal to a Host intent handler, a dream (closed by sync), or a Bot Turn outcome. */
|
|
19
|
+
export declare function routeTerminal(state: CollaborationState, key: string, handler: string | undefined): {
|
|
20
|
+
kind: 'host_intent';
|
|
21
|
+
handler: string;
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'dream';
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'bot_turn';
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Runs a Host intent handler in the terminal transaction. `run` is undefined when no handler has this name.
|
|
29
|
+
* L rejects missing handlers at startup; H has no startup check across every scope, so the terminal fails closed here.
|
|
30
|
+
*/
|
|
31
|
+
export declare function runHostIntentHandler(key: string, name: string, run: (() => unknown) | undefined): void;
|
|
32
|
+
/** The refusal of a Bot Turn whose outcome commit threw. */
|
|
33
|
+
export declare function outcomeFailure(key: string, cause: unknown): IntentOutcomeError;
|
|
34
|
+
/** The outcome ports shared by L, H and their vector subjects. The caller adds `committed`. */
|
|
35
|
+
export declare function botOutcomePorts({ taskId, routines, manage, roomPosts }: {
|
|
36
|
+
taskId: string;
|
|
37
|
+
routines: RoutineCommands;
|
|
38
|
+
manage: OutcomePorts['manage'];
|
|
39
|
+
roomPosts: boolean;
|
|
40
|
+
}): Omit<OutcomePorts, 'committed'>;
|
|
41
|
+
/** Seals due batches and expires cards before the sync freezes any new ContextPack. */
|
|
42
|
+
export declare function syncHead(state: CollaborationState, coalesce: CoalescePolicy | undefined, now: number): void;
|
|
43
|
+
/**
|
|
44
|
+
* Withholds the staged replies of concluded intents, cleans reply tokens and projects every input batch and inbound destination after the sync's Turn steps.
|
|
45
|
+
* H's finishDelivery also cleans reply tokens, corresponding to L's cleanup in each flush pass.
|
|
46
|
+
* #1229 item 3: one projection per destination; an unchanged destination keeps the same projection id and value.
|
|
47
|
+
*/
|
|
48
|
+
export declare function syncTail(state: CollaborationState, conclusions: IntentConclusions | undefined, now: number, emit: Publish): void;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { Mentions } from './rooms.js';
|
|
2
|
+
/** A sender that the channel adapter took from authenticated platform data (docs/host-im-adapter.md R2). */
|
|
3
|
+
export interface Principal {
|
|
4
|
+
id: string;
|
|
5
|
+
kind: 'human' | 'bot';
|
|
6
|
+
}
|
|
7
|
+
export interface Conversation {
|
|
8
|
+
kind: 'direct' | 'group';
|
|
9
|
+
id: string;
|
|
10
|
+
}
|
|
11
|
+
export interface ReplyRoute {
|
|
12
|
+
kind: 'reply';
|
|
13
|
+
channel: string;
|
|
14
|
+
inboundId: string;
|
|
15
|
+
token: string;
|
|
16
|
+
expiresAt: number;
|
|
17
|
+
}
|
|
18
|
+
export interface PushRoute {
|
|
19
|
+
kind: 'push';
|
|
20
|
+
id: string;
|
|
21
|
+
conversation: Conversation;
|
|
22
|
+
channel: string;
|
|
23
|
+
target: string;
|
|
24
|
+
optedInBy: string;
|
|
25
|
+
optedInAt: number;
|
|
26
|
+
revokedAt?: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* `staged`: a Bot reply accepted before its Turn outcome committed (#1762). No sender takes it. The outcome transaction
|
|
30
|
+
* promotes it to `pending`; a Turn whose intent concludes otherwise rejects it as `outcome_not_applied`.
|
|
31
|
+
*/
|
|
32
|
+
export type DeliveryState = 'staged' | 'pending' | 'sending' | 'accepted' | 'rejected' | 'unknown';
|
|
33
|
+
/** `turnId` is the Turn that queued the delivery. Retention keeps the delivery with that Turn's root. */
|
|
34
|
+
export interface Delivery {
|
|
35
|
+
id: string;
|
|
36
|
+
taskId: string;
|
|
37
|
+
turnId: string;
|
|
38
|
+
messageId: string;
|
|
39
|
+
body: string;
|
|
40
|
+
conversation: Conversation;
|
|
41
|
+
channel: string;
|
|
42
|
+
route: {
|
|
43
|
+
kind: 'reply';
|
|
44
|
+
inboundId: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'push';
|
|
47
|
+
pushRouteId: string;
|
|
48
|
+
};
|
|
49
|
+
state: DeliveryState;
|
|
50
|
+
attempts: number;
|
|
51
|
+
nextAttemptAt?: number;
|
|
52
|
+
platformMessageId?: string;
|
|
53
|
+
code?: string;
|
|
54
|
+
resendOf?: string;
|
|
55
|
+
}
|
|
56
|
+
/** A rejection is authoritative. An exception leaves delivery acceptance unknown. */
|
|
57
|
+
export interface ChannelPort {
|
|
58
|
+
send(input: {
|
|
59
|
+
deliveryId: string;
|
|
60
|
+
route: ReplyRoute | PushRoute;
|
|
61
|
+
body: string;
|
|
62
|
+
}, signal: AbortSignal): Promise<{
|
|
63
|
+
result: 'accepted';
|
|
64
|
+
platformMessageId: string;
|
|
65
|
+
} | {
|
|
66
|
+
result: 'rejected';
|
|
67
|
+
code: string;
|
|
68
|
+
retryable: boolean;
|
|
69
|
+
retryAfterMs?: number;
|
|
70
|
+
}>;
|
|
71
|
+
readback?(deliveryId: string): Promise<'accepted' | 'absent' | 'unsupported'>;
|
|
72
|
+
}
|
|
73
|
+
export interface ChannelOptions {
|
|
74
|
+
port: ChannelPort;
|
|
75
|
+
/** Verified platform bot principal ids. These ids are scoped to their channel. */
|
|
76
|
+
self?: Record<string, readonly string[]>;
|
|
77
|
+
/** Business send deadline. The default is 15 seconds. */
|
|
78
|
+
sendTimeoutMs?: number;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Optional last argument of the owner APIs and `roomInput`. Its length tells an omitted principal
|
|
82
|
+
* from a given `undefined`, because JavaScript applies a default parameter to both.
|
|
83
|
+
*/
|
|
84
|
+
export type PrincipalArg = [principal?: Principal];
|
|
85
|
+
/**
|
|
86
|
+
* One inbound IM message after the adapter's translation. The adapter maps the platform chat
|
|
87
|
+
* to a Host conversation: a Bot id for `direct`, a room id for `group`.
|
|
88
|
+
*/
|
|
89
|
+
export interface InboundMessage {
|
|
90
|
+
channel: string;
|
|
91
|
+
platformMessageId: string;
|
|
92
|
+
conversation: Conversation;
|
|
93
|
+
/** Absent when the adapter cannot verify the sender. */
|
|
94
|
+
sender?: Principal;
|
|
95
|
+
text: string;
|
|
96
|
+
/** Bot ids from the platform's mention entities (R6). The Host never scans `text`. */
|
|
97
|
+
mentions: Mentions;
|
|
98
|
+
replyRoute?: ReplyRoute;
|
|
99
|
+
deliveryId?: string;
|
|
100
|
+
receivedAt?: number;
|
|
101
|
+
}
|
|
102
|
+
/** Echo candidates only reconcile exact delivery identities. They never create input. */
|
|
103
|
+
export type InboundClass = 'unverified_sender' | 'echo' | 'bot_audit' | 'bot_background' | 'owner_input' | 'not_owner' | 'room_input';
|
|
104
|
+
/** A principal needs a non-empty id and a known kind. */
|
|
105
|
+
export declare function verified(sender: Principal | undefined): sender is Principal;
|
|
106
|
+
/** Only the human principal with the owner id. A bot account never has owner authority. */
|
|
107
|
+
export declare function isOwner(principal: Principal, owner: string): boolean;
|
|
108
|
+
/** The guide's §3 order. The first match wins. */
|
|
109
|
+
export declare function classifyInbound(message: InboundMessage, owner: string, self?: Record<string, readonly string[]>): InboundClass;
|
|
110
|
+
/** A redelivered platform event maps to the same input. A platform message id can be unique only within one chat. */
|
|
111
|
+
export declare function inboundKey(message: InboundMessage): string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { hash } from '@byok-sdk/server/execution-core/canonical';
|
|
2
|
+
|
|
3
|
+
function autonomousIntentIds(turns,dreams){return new Set(turns.filter(turn=>turn.source==="routine"||turn.source==="bot_request").map(turn=>hash(turn.id)).concat(dreams))}var DEVICE_CONCURRENCY=8;var USER_RESERVED_SLOTS=1;function isUnsubmitted(row){return row.phase==="queued"&&row.attempts===0}function userFirst(rows,userIntentId,autonomous,next){const user=rows.find(row=>row.id===userIntentId);if(!user||!isUnsubmitted(user))return void 0;const queued=rows.filter(row=>row.agent===user.agent&&isUnsubmitted(row)).sort((a,b)=>a.sequence-b.sequence||(a.id<b.id?-1:a.id>b.id?1:0));const order=[...queued.filter(row=>!autonomous.has(row.id)),...queued.filter(row=>autonomous.has(row.id))];if(order.every((row,index)=>row.id===queued[index].id))return void 0;let base=next;for(const row of rows)if(row.sequence>base)base=row.sequence;return {assignments:order.map((row,index)=>({id:row.id,sequence:base+1+index})),sequence:base+order.length}}function admitDeviceSlot(intent,rows,limit=DEVICE_CONCURRENCY){if(!Number.isSafeInteger(limit)||limit<1)throw new Error("A device concurrency limit is a positive safe integer");const reserved=Math.min(USER_RESERVED_SLOTS,limit-1);let occupied=0;for(const row of rows)if(row.id!==intent.id&&row.deviceId===intent.deviceId&&row.occupies)occupied++;return occupied<limit-(intent.source==="user"?0:reserved)}
|
|
4
|
+
|
|
5
|
+
export { DEVICE_CONCURRENCY, admitDeviceSlot, autonomousIntentIds, userFirst };
|
|
6
|
+
//# sourceMappingURL=chunk-33YA66U7.js.map
|
|
7
|
+
//# sourceMappingURL=chunk-33YA66U7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rules/priority.ts"],"names":[],"mappings":";;AAIO,SAAS,mBAAA,CAAoB,KAAA,CAA+C,MAAA,CAAwC,CACzH,OAAO,IAAI,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,IAAA,EAAQ,KAAK,MAAA,GAAW,SAAA,EAAa,IAAA,CAAK,MAAA,GAAW,aAAa,CAAA,CAAE,GAAA,CAAI,IAAA,EAAQ,IAAA,CAAK,IAAA,CAAK,EAAE,CAAC,CAAA,CAAE,MAAA,CAAO,MAAM,CAAC,CAC3I,CASO,IAAM,kBAAA,CAAqB,EAE3B,IAAM,mBAAA,CAAsB,CAAA,CAa5B,SAAS,aAAA,CAAc,GAAA,CAAwD,CACpF,OAAO,IAAI,KAAA,GAAU,QAAA,EAAY,GAAA,CAAI,QAAA,GAAa,CACpD,CASO,SAAS,SAAA,CAAU,IAAA,CAA+B,YAAA,CAAsB,UAAA,CAC7E,IAAA,CAAwC,CACxC,MAAM,KAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAO,GAAA,CAAI,EAAA,GAAO,YAAY,CAAA,CACrD,GAAI,CAAC,IAAA,EAAQ,CAAC,aAAA,CAAc,IAAI,CAAA,CAAG,OAAO,MAAA,CAC1C,MAAM,MAAA,CAAS,IAAA,CAAK,MAAA,CAAO,GAAA,EAAO,GAAA,CAAI,KAAA,GAAU,IAAA,CAAK,KAAA,EAAS,aAAA,CAAc,GAAG,CAAC,CAAA,CAC7E,KAAK,CAAC,CAAA,CAAG,CAAA,GAAM,CAAA,CAAE,QAAA,CAAW,CAAA,CAAE,QAAA,GAAa,CAAA,CAAE,EAAA,CAAK,CAAA,CAAE,EAAA,CAAK,EAAA,CAAK,CAAA,CAAE,EAAA,CAAK,CAAA,CAAE,EAAA,CAAK,CAAA,CAAI,CAAA,CAAE,CAAA,CACrF,MAAM,KAAA,CAAQ,CAAC,GAAG,MAAA,CAAO,MAAA,CAAO,GAAA,EAAO,CAAC,UAAA,CAAW,GAAA,CAAI,GAAA,CAAI,EAAE,CAAC,CAAA,CAAG,GAAG,MAAA,CAAO,MAAA,CAAO,GAAA,EAAO,UAAA,CAAW,GAAA,CAAI,GAAA,CAAI,EAAE,CAAC,CAAC,CAAA,CAChH,GAAI,MAAM,KAAA,CAAM,CAAC,GAAA,CAAK,KAAA,GAAU,GAAA,CAAI,EAAA,GAAO,MAAA,CAAO,KAAK,CAAA,CAAG,EAAE,CAAA,CAAG,OAAO,MAAA,CACtE,IAAI,KAAO,IAAA,CACX,IAAA,MAAW,GAAA,IAAO,IAAA,CAAM,GAAI,GAAA,CAAI,QAAA,CAAW,IAAA,CAAM,IAAA,CAAO,GAAA,CAAI,QAAA,CAC5D,OAAO,CAAE,WAAA,CAAa,MAAM,GAAA,CAAI,CAAC,GAAA,CAAK,KAAA,IAAW,CAAE,EAAA,CAAI,GAAA,CAAI,EAAA,CAAI,QAAA,CAAU,IAAA,CAAO,CAAA,CAAI,KAAM,CAAA,CAAE,CAAA,CAAG,SAAU,IAAA,CAAO,KAAA,CAAM,MAAO,CAC/H,CAOO,SAAS,eAAA,CAAgB,MAAA,CAAwB,IAAA,CAAgC,KAAA,CAAQ,kBAAA,CAA6B,CAC3H,GAAI,CAAC,OAAO,aAAA,CAAc,KAAK,CAAA,EAAK,KAAA,CAAQ,CAAA,CAAG,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CACtH,MAAM,QAAA,CAAW,IAAA,CAAK,GAAA,CAAI,oBAAqB,KAAA,CAAQ,CAAC,CAAA,CACxD,IAAI,QAAA,CAAW,CAAA,CACf,IAAA,MAAW,GAAA,IAAO,IAAA,CAAM,GAAI,GAAA,CAAI,EAAA,GAAO,MAAA,CAAO,EAAA,EAAM,GAAA,CAAI,QAAA,GAAa,MAAA,CAAO,QAAA,EAAY,GAAA,CAAI,QAAA,CAAU,QAAA,EAAA,CACtG,OAAO,QAAA,CAAW,KAAA,EAAS,MAAA,CAAO,MAAA,GAAW,MAAA,CAAS,CAAA,CAAI,QAAA,CAC5D","file":"chunk-33YA66U7.js","sourcesContent":["import { hash } from '@byok-sdk/server/execution-core/canonical';\nimport type { Turn } from './turn.js';\n\n/** The background intents that user input overtakes; dream ids already use the ledger's hashed identity. */\nexport function autonomousIntentIds(turns: readonly Pick<Turn, 'id' | 'source'>[], dreams: readonly string[]): Set<string> {\n return new Set(turns.filter(turn => turn.source === 'routine' || turn.source === 'bot_request').map(turn => hash(turn.id)).concat(dreams));\n}\n\n/**\n * The reference Host's explicit work priority as pure rules (#1229 item 1). The K4 FIFO keeps its order: one queue per\n * Agent, the lowest sequence is the head, and a submitted execution keeps its taskId generation\n * (docs/host-execution-core.md section 3). These rules change only the sequence of queued, never-submitted intents and\n * the dispatch decision of one device.\n */\n/** The concurrent task limit of a device, as the daemon maxConcurrentTasks default (#1121). */\nexport const DEVICE_CONCURRENCY = 8;\n/** The slots of a device that autonomous work may not take, so user input always has one. */\nexport const USER_RESERVED_SLOTS = 1;\n/** The intent fields that the priority rules read. K4 owns every other field. */\nexport interface QueuedIntent {\n readonly id: string; readonly agent: string; readonly sequence: number; readonly phase: string; readonly attempts: number;\n}\n/** A dispatched intent: the fields of the device reservation, and whether it currently occupies a slot of its device. */\nexport interface DispatchIntent extends QueuedIntent {\n readonly source: 'user' | 'bot' | 'routine';\n readonly deviceId: string;\n /** The intent is submitted or has attempt evidence, so it holds a device slot until its terminal. */\n readonly occupies: boolean;\n}\n/** A queued intent that never reached the SDK: the only rows that a priority rule may move. */\nexport function isUnsubmitted(row: Pick<QueuedIntent, 'phase' | 'attempts'>): boolean {\n return row.phase === 'queued' && row.attempts === 0;\n}\n/** The new sequence values of one Agent FIFO, and the counter value after them. */\nexport interface SequencePlan { assignments: Array<{ id: string; sequence: number }>; sequence: number }\n/**\n * Puts the queued, never-submitted intents of the user intent's Agent FIFO in priority order: every non-autonomous\n * intent keeps its arrival order, then the autonomous ones (the ids in the set) keep theirs.\n * Returns undefined when the user intent is not queued and unsubmitted, or the order already holds.\n * The new values are one block above every current sequence, so a submitted or in-flight intent is never moved.\n */\nexport function userFirst(rows: readonly QueuedIntent[], userIntentId: string, autonomous: ReadonlySet<string>,\n next: number): SequencePlan | undefined {\n const user = rows.find(row => row.id === userIntentId);\n if (!user || !isUnsubmitted(user)) return undefined;\n const queued = rows.filter(row => row.agent === user.agent && isUnsubmitted(row))\n .sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n const order = [...queued.filter(row => !autonomous.has(row.id)), ...queued.filter(row => autonomous.has(row.id))];\n if (order.every((row, index) => row.id === queued[index]!.id)) return undefined;\n let base = next;\n for (const row of rows) if (row.sequence > base) base = row.sequence;\n return { assignments: order.map((row, index) => ({ id: row.id, sequence: base + 1 + index })), sequence: base + order.length };\n}\n/**\n * Whether the Host may begin the intent on its device now. User-source work may use every slot; other work leaves\n * USER_RESERVED_SLOTS free (none when the limit is 1, which has no spare slot). The rows hold the open intents of every\n * Agent on the device; the intent itself is not counted, so the check gives the same answer before and after the intent\n * becomes in-flight.\n */\nexport function admitDeviceSlot(intent: DispatchIntent, rows: Iterable<DispatchIntent>, limit = DEVICE_CONCURRENCY): boolean {\n if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('A device concurrency limit is a positive safe integer');\n const reserved = Math.min(USER_RESERVED_SLOTS, limit - 1);\n let occupied = 0;\n for (const row of rows) if (row.id !== intent.id && row.deviceId === intent.deviceId && row.occupies) occupied++;\n return occupied < limit - (intent.source === 'user' ? 0 : reserved);\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { inboundKey, dreamTable, stateOf, routineCalendar, BOT_DREAM, owned, updateDefinition, createDefinition, retainRoots, routineOccurrence, concludeRoutineTurn, ROUTINE_LATE_AFTER_MS } from './chunk-XTZUCECQ.js';
|
|
2
|
+
import { autonomousIntentIds, userFirst } from './chunk-33YA66U7.js';
|
|
3
|
+
import { admitUserInput, addBatchTurns, addTurn, inactive, expireCards, observeDevices, settleDelegations, compactVeto, DEVICE_SWITCHING, DEVICE_NOT_BOUND, CommitConflict, commitCommand, refuseRetired, syncTurn, cardCallDue, settleCardCall, CONNECTOR_OUTCOME_UNKNOWN, json, retiredIdentity, handoffFrameBytes, handoffTurn, sealDueBatches, advanceRoomSeats, seatTurn } from './chunk-ZUFZCROA.js';
|
|
4
|
+
import { hash, time, occurrenceIntentKey, setLifecycle, routineCommands, promoteOccurrence, taskId, isOccurrenceIntentKey, routineWakeKey, agentKey, frozenInput, parseRoutineWakeKey, project, enqueue, concludeOccurrence, occurrenceOfIntentKey, validateJson, canonical as canonical$1, validateRetry } from '@byok-sdk/server/execution-core';
|
|
5
|
+
import { checkRoutineSchedule, buildDreamInstruction, buildHandoffPack } from '@byok-sdk/protocol';
|
|
6
|
+
import { canonical, hash as hash$1 } from '@byok-sdk/server/execution-core/canonical';
|
|
7
|
+
|
|
8
|
+
function botFacts(state,botId){const bot=state.team.bots[botId];return bot&&{busy:Object.values(state.turns).some(turn=>turn.botId===botId&&!turn.conclusion&&turn.status!=="blocked"),configKey:[bot.revision,bot.model],archived:bot.archived}}function sealDueBatches2(state,policy,now){const bots={};for(const batch of Object.values(state.inputBatches??{})){const facts=batch.state==="open"?botFacts(state,batch.botId):void 0;if(facts)bots[batch.botId]=facts;}addBatchTurns(state,sealDueBatches(state,bots,policy,now));}function projectInputBatches(state,emit){for(const batch of Object.values(state.inputBatches??{})){const revision=batch.state==="open"?1:2;if((batch.revision??0)>=revision)continue;batch.revision=revision;emit(`input-batch:${batch.id}:${revision}`,json({owner:batch.botId,id:batch.id,revision,state:batch.state,sealReason:batch.sealReason,inputIds:batch.inputIds,openedAt:batch.openedAt,sealAt:batch.sealAt}));}}function admitUserInput2(state,input,policy,now){const admission=admitUserInput(state,input,{bot:botFacts(state,input.botId),turn:state.turns[input.id]},policy,now);addBatchTurns(state,admission.sealed);if(admission.turn){state.budgets[input.id]??={continuation:0,delegation:0};addTurn(state,{id:input.id,root:input.id,source:"user",request:input.request,botId:input.botId,hop:0,authority:input.authority});}return admission.id}var MAX_ATTEMPTS=3;var MAX_WAIT_MS=6e4;function deliveryId(taskId3,messageId,route,nonce){const key=route.kind==="reply"?["reply",route.inboundId]:["push",route.pushRouteId];return hash(nonce===void 0?[taskId3,messageId,key]:[taskId3,messageId,key,nonce])}function startDelivery(row,now){if(row.state!=="pending"||row.attempts>=MAX_ATTEMPTS||row.nextAttemptAt!==void 0&&now<row.nextAttemptAt)return false;row.state="sending";row.attempts++;delete row.nextAttemptAt;delete row.code;return true}function currentAttempt(row,attempt){return row.state==="sending"&&row.attempts===attempt}function retryDelivery(row,now,retryAfterMs){const wait=Math.max(retryAfterMs,1e3*2**(row.attempts-1));if(wait>MAX_WAIT_MS){row.state="rejected";return}row.state="pending";row.nextAttemptAt=now+wait;}function settleDelivery(row,attempt,result,now){if(!currentAttempt(row,attempt))return;if(result?.result==="accepted"&&typeof result.platformMessageId==="string"&&result.platformMessageId.length>0){row.state="accepted";row.platformMessageId=result.platformMessageId;delete row.code;return}if(result?.result!=="rejected"||typeof result.code!=="string"||result.code.length===0||typeof result.retryable!=="boolean"){unknownDelivery(row,attempt,"invalid_send_result");return}row.code=result.code;if(!result.retryable||row.attempts>=MAX_ATTEMPTS){row.state="rejected";return}const retryAfter=result.retryAfterMs===void 0?0:result.retryAfterMs;if(!Number.isFinite(retryAfter)||retryAfter<0){row.state="rejected";row.code="invalid_retry_after";return}retryDelivery(row,now,retryAfter);}function unknownDelivery(row,attempt,code){if(!currentAttempt(row,attempt))return;row.state="unknown";row.code=code;delete row.nextAttemptAt;}function recoverDelivery(row){if(row.state==="sending")unknownDelivery(row,row.attempts,"interrupted");}function readbackDelivery(row,attempt,result,now){if(row.state!=="unknown"||row.attempts!==attempt)return;if(result==="accepted"){row.state="accepted";delete row.code;}else if(result==="absent"){if(row.attempts>=MAX_ATTEMPTS){row.state="rejected";row.code="attempts_exhausted";}else {delete row.code;retryDelivery(row,now,0);}}}function acceptDeliveryEcho(row,platformMessageId){if(!platformMessageId)return false;if(row.state==="accepted"){if(row.platformMessageId&&row.platformMessageId!==platformMessageId)return false;row.platformMessageId=platformMessageId;return true}const waitingRetry=row.state==="pending"&&row.attempts>0;if(row.state!=="sending"&&row.state!=="unknown"&&!waitingRetry)return false;row.state="accepted";row.platformMessageId=platformMessageId;delete row.code;delete row.nextAttemptAt;return true}function channelState(state){return state.channel??={inbounds:{},pushRoutes:{},deliveries:{}}}var sameConversation=(a,b)=>a.kind===b.kind&&a.id===b.id;function turnConversation(state,turn){const seat=state.team.seats[turn.id];return seat?{kind:"group",id:state.team.rounds[seat.roundId].roomId}:{kind:"direct",id:turn.botId}}function turnRoot(state,turn){const seat=state.team.seats[turn.id];return seat?state.team.rounds[seat.roundId].root:turn.root}function rootOpen(ledger,state,root,conversation){return Object.values(state.turns).some(turn=>turnRoot(state,turn)===root&&sameConversation(turnConversation(state,turn),conversation)&&!turn.conclusion&&!ledger.intents[hash(turn.id)]?.conclusion&&!["blocked","failed","delivered"].includes(turn.status))||Object.values(state.inputBatches??{}).some(batch=>batch.id===root&&batch.state==="open")||Object.values(state.team.seats).some(seat=>state.team.rounds[seat.roundId]?.root===root&&!seat.released)}function rememberInbound(state,message,root){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)throw new Error("Invalid inbound identity");const route=message.replyRoute;if(route&&(route.kind!=="reply"||route.channel!==message.channel||route.inboundId!==message.platformMessageId||typeof route.token!=="string"||!route.token||!Number.isSafeInteger(route.expiresAt)||route.expiresAt<0)){throw new Error("Invalid reply route binding")}const channels=channelState(state),id=inboundKey(message);channels.inbounds[id]??={id,root,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,...route?{reply:{...route}}:{}};}function rememberFilteredInbound(state,message,code){if(typeof message.channel!=="string"||!message.channel.trim()||typeof message.platformMessageId!=="string"||!message.platformMessageId)return;const channels=channelState(state),id=inboundKey(message);channels.inbounds[id]??={id,conversation:{...message.conversation},channel:message.channel,sequence:++state.sequence,filtered:code};}function enablePush(state,conversation,channel,target,owner,now){if(!conversation.id||!channel.trim()||!target.trim())throw new Error("Invalid push route");const channels=channelState(state);for(const route2 of Object.values(channels.pushRoutes)){if(sameConversation(route2.conversation,conversation)&&route2.revokedAt===void 0)revokePush(state,route2.id,now);}const id=hash(["push-route",conversation,channel,target,++state.sequence]);const route={kind:"push",id,conversation:{...conversation},channel,target,optedInBy:owner,optedInAt:now};channels.pushRoutes[id]=route;return route}function revokePush(state,id,now){const routes=state.channel?.pushRoutes;const route=routes&&Object.hasOwn(routes,id)?routes[id]:void 0;if(!route)throw new Error("Push route not found");route.revokedAt??=now;for(const delivery of Object.values(state.channel.deliveries)){if(delivery.state==="pending"&&delivery.route.kind==="push"&&delivery.route.pushRouteId===id)refuseRoute(state,delivery);}}function activePush(state,conversation){return Object.values(state.channel?.pushRoutes??{}).find(route=>route.revokedAt===void 0&&sameConversation(route.conversation,conversation))}function insert(state,input,staged=false){const id=deliveryId(input.taskId,input.messageId,input.route);return channelState(state).deliveries[id]??={id,...input,state:staged?"staged":"pending",attempts:0}}function queueDelivery(ledger,state,turn,taskId3,messageId,body,now,staged=false){const conversation=turnConversation(state,turn),root=turnRoot(state,turn);const inbound=Object.values(state.channel?.inbounds??{}).filter(row=>row.root===root&&sameConversation(row.conversation,conversation)).sort((a,b)=>b.sequence-a.sequence)[0];if(inbound?.reply?.token&&inbound.reply.expiresAt>now&&rootOpen(ledger,state,root,conversation)){return insert(state,{taskId:taskId3,turnId:turn.id,messageId,body,conversation,channel:inbound.reply.channel,route:{kind:"reply",inboundId:inbound.id}},staged)}const push=activePush(state,conversation);if(push)return insert(state,{taskId:taskId3,turnId:turn.id,messageId,body,conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}},staged);state.audit.push(`Delivery ${inbound?.reply?"reply_route_expired":"no_push_route"}: ${taskId3} ${messageId}`);return void 0}function promoteStaged(state,taskId3){const rows=Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="staged"&&row.taskId===taskId3);for(const row of rows)row.state="pending";return rows.map(row=>row.id)}function withholdStaged(ledger,state){for(const row of Object.values(state.channel?.deliveries??{})){if(row.state!=="staged"||!ledger.intents[hash(row.turnId)]?.conclusion)continue;row.state="rejected";row.code="outcome_not_applied";state.audit.push(`Delivery outcome_not_applied: ${row.taskId} ${row.messageId}`);}}function deliveryRoute(state,row,now){if(row.route.kind==="push"){const route2=state.channel?.pushRoutes[row.route.pushRouteId];return route2&&route2.revokedAt===void 0&&sameConversation(route2.conversation,row.conversation)?structuredClone(route2):void 0}const stored=state.channel?.inbounds[row.route.inboundId],route=stored?.reply;return route?.token&&route.expiresAt>now&&sameConversation(stored.conversation,row.conversation)?{...route,token:route.token}:void 0}function refuseRoute(state,row){if(row.state!=="pending")return;row.state="rejected";delete row.nextAttemptAt;row.code=row.route.kind==="reply"?"reply_route_expired":"push_route_revoked";state.audit.push(`Delivery ${row.code}: ${row.taskId} ${row.messageId}`);const push=row.route.kind==="reply"?activePush(state,row.conversation):void 0;if(push)insert(state,{taskId:row.taskId,turnId:row.turnId,messageId:row.messageId,body:row.body,conversation:row.conversation,channel:push.channel,route:{kind:"push",pushRouteId:push.id}});}function cleanReplyTokens(ledger,state,now){for(const row of Object.values(state.channel?.inbounds??{})){if(!row.reply?.token||row.root===void 0)continue;const reserved=Object.values(state.channel.deliveries).some(delivery=>delivery.route.kind==="reply"&&delivery.route.inboundId===row.id&&["staged","pending","sending","unknown"].includes(delivery.state));if(now>=row.reply.expiresAt||!reserved&&!rootOpen(ledger,state,row.root,row.conversation))delete row.reply.token;}}function resendUnknown(state,id,now){const deliveries=state.channel?.deliveries;const old=deliveries&&Object.hasOwn(deliveries,id)?deliveries[id]:void 0;if(!old||old.state!=="unknown")throw new Error("Only an unknown delivery can be resent");const available=deliveryRoute(state,old,now)??activePush(state,old.conversation);if(!available)throw new Error("No active delivery route");const route=available.kind==="reply"?old.route:{kind:"push",pushRouteId:available.id};const nextId=deliveryId(old.taskId,old.messageId,route,String(++state.sequence));const row={id:nextId,taskId:old.taskId,turnId:old.turnId,messageId:old.messageId,body:old.body,conversation:{...old.conversation},channel:available.channel,route:{...route},state:"pending",attempts:0,resendOf:old.id};state.channel.deliveries[nextId]=row;return row}function echoCandidates(state,message){return Object.values(state.channel?.deliveries??{}).filter(row=>row.channel===message.channel&&sameConversation(row.conversation,message.conversation)&&row.state!=="rejected"&&(message.deliveryId!==void 0?row.id===message.deliveryId:row.platformMessageId===message.platformMessageId))}var ANSWERED=new Set(["succeeded","delivered"]);var FAILED=new Set(["failed","expired","declined","superseded","abandoned"]);function inboundDisposition(state,row){if(row.filtered!==void 0)return {id:row.id,disposition:"filtered",code:row.filtered};const root=row.root;if(root===void 0)return {id:row.id,disposition:"failed",turnId:row.id};const turn=Object.hasOwn(state.turns,root)?state.turns[root]:void 0;if(!turn){const batch=state.inputBatches&&Object.hasOwn(state.inputBatches,root)?state.inputBatches[root]:void 0;return batch?.state==="open"?{id:row.id,disposition:"coalesced",turnId:root}:{id:row.id,disposition:"failed",turnId:root}}const conclusions=[turn.conclusion,turn.status];if(conclusions.includes("cancelled"))return {id:row.id,disposition:"cancelled",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&ANSWERED.has(value)))return {id:row.id,disposition:"answered",turnId:turn.id};if(conclusions.some(value=>value!==void 0&&FAILED.has(value)))return {id:row.id,disposition:"failed",turnId:turn.id};return {id:row.id,disposition:"coalesced",turnId:turn.id}}function inboundDispositions(state){return Object.values(state.channel?.inbounds??{}).filter(row=>row.filtered!==void 0||row.root!==void 0).sort((a,b)=>(a.sequence??0)-(b.sequence??0)||(a.id<b.id?-1:a.id>b.id?1:0)).map(row=>inboundDisposition(state,row))}var DEFAULT_DREAM_MAX_DURATION_MS=9e5;var DREAM_WAIT_MS=36e5;var DREAM_HOUR=3;var MIN_PACK_BYTES=1024;var scheduleIn=tz=>({minute:0,hour:DREAM_HOUR,tz});var localZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone;function dreamPolicy(options){if(options===false)return void 0;const check=checkRoutineSchedule(scheduleIn(options?.timeZone??localZone()));if(!check.ok)throw new Error(`dreaming: ${check.code}: ${check.message}`);const maxDurationMs=time(options?.maxDurationMs??DEFAULT_DREAM_MAX_DURATION_MS);if(maxDurationMs<1)throw new Error("dreaming: maxDurationMs must be positive");return {...options?.timeZone===void 0?{}:{timeZone:options.timeZone},models:[...options?.models??[]],maxDurationMs,nativeSessions:options?.nativeSessions??true}}var ownerOf=routine=>{const spec=routine.definition.hostOccurrence;return spec?.type===BOT_DREAM?spec.input.owner:void 0};function dreamOf(state,intentKey){const key=occurrenceOfIntentKey(intentKey);return key!==void 0&&state.dreams&&Object.hasOwn(state.dreams.open,key)?state.dreams.open[key]:void 0}function dreamIntentIds(state){return Object.keys(state.dreams?.open??{}).map(key=>hash(occurrenceIntentKey(key)))}function recordDream(state,run,now){dreamTable(state).open[run.occurrenceKey]={botId:run.input.owner,windowEnd:now};}function reconcileDreamRoutines(s,policy,models,now){const state=stateOf(s.application),rows=Object.values(s.routines).flatMap(row=>{const owner=ownerOf(row);return owner===void 0?[]:[{row,owner}]});const open=new Map;for(const{row,owner}of rows){if(row.lifecycle==="completed")continue;const bot=state.team.bots[owner];if(policy&&bot&&!bot.archived&&!open.has(owner))open.set(owner,row);else setLifecycle(s,row.definition.id,"completed",now,routineCalendar);}if(!policy)return;const commands=routineCommands(s,{now:()=>now,nextTime:routineCalendar,hostJobs:new Map,occurrenceHooks:new Map([[BOT_DREAM,recordDream]]),executionRoutines:"refuse"});const definition2=(id,version,owner,tz)=>({id,version,timeZone:tz,rule:json(scheduleIn(tz)),waitMs:DREAM_WAIT_MS,lateAfterMs:ROUTINE_LATE_AFTER_MS,hostOccurrence:{type:BOT_DREAM,input:{owner}}});for(const bot of Object.values(state.team.bots)){if(bot.archived)continue;const routine=open.get(bot.id),latest=routine?.pending??routine?.definition;if(latest){if(policy.timeZone!==void 0&&latest.timeZone!==policy.timeZone)commands.update(definition2(latest.id,latest.version+1,bot.id,policy.timeZone));}else if(models[bot.model]){commands.create(definition2(`dream:${bot.id}:${rows.filter(row=>row.owner===bot.id).length+1}`,1,bot.id,policy.timeZone??localZone()));dreamTable(state).bots[bot.id]??={since:now};}}}var completed=row=>row.status==="succeeded"||row.status==="delivered";function settledAfter(rows,mark){const after=rows.slice(rows.findIndex(row=>row.id===mark)+1);const open=after.findIndex(row=>row.status==="queued"||row.status==="processing");return open<0?after:after.slice(0,open)}function chooseModel(policy,models,botModel,deviceId){const name=policy.models.find(model=>Object.hasOwn(models,model)&&models[model].deviceId===deviceId);if(name!==void 0)return {template:name,fallback:false,base:models[name]};return models[botModel]?{template:botModel,fallback:true,base:void 0}:void 0}function dreamExecution(base,bot,instruction,maxDurationMs,window,nativeSessions){const{messageEgress:_egress,requiredToolsets:_toolsets,agentMemoryCommit:_commit,homeAccess:_home,preparation:_preparation,nativeSessions:_nativeSessions,...payload}=base.payload;return {deviceId:bot.deviceId,payload:{...payload,instruction,session:{mode:"fresh"},agentRef:bot.payload.agentRef,agentMemory:"none",limits:{...payload.limits,maxDurationMs},terminalProjection:{mode:"none"},...nativeSessions&&payload.harnessId===void 0?{nativeSessions:{...window,ifAdvertised:true}}:{}}}}function dreamInstruction(rows,window,maxDurationMs,instructionMaxBytes){const budget={maxDurationMs},frame={omittedTurns:0,earlier:[],recent:[]};const fixed=Buffer.byteLength(buildDreamInstruction({history:frame,window,budget}),"utf8")-Buffer.byteLength(JSON.stringify(frame),"utf8");const totalBytes=Math.max(instructionMaxBytes-fixed,handoffFrameBytes(rows.length));const history=buildHandoffPack(rows.map(handoffTurn),{recentBytes:Math.floor(totalBytes/4*3),earlyBytes:totalBytes,totalBytes});return buildDreamInstruction({history,window,budget})}function checkDreamInstruction(instructionMaxBytes){const room=instructionMaxBytes-Buffer.byteLength(dreamInstruction([],{fromMs:0,toMs:0},1,0),"utf8");if(room<MIN_PACK_BYTES)throw new Error(`instructionMaxBytes leaves a dream ${room} bytes of history, under ${MIN_PACK_BYTES}`)}function syncDreams(s,sync){const state=stateOf(s.application),dreams=state.dreams;if(!dreams)return false;let changed=false;const close=(key,run,outcome,reason)=>{const bot=dreams.bots[run.botId]??={since:run.windowEnd};bot.last={occurrenceKey:key,at:run.windowEnd,outcome,...reason===void 0?{}:{reason},...run.template===void 0?{}:{template:run.template,fallback:run.fallback}};if(outcome==="succeeded"){bot.since=run.windowEnd;if(run.throughTurn!==void 0)bot.throughTurn=run.throughTurn;}delete dreams.open[key];};const skip=(key,run,reason)=>{const occurrence=s.occurrences[key];if(occurrence&&!occurrence.conclusion){concludeOccurrence(s,key,reason==="superseded"?"superseded":"cancelled");changed=true;}close(key,run,reason==="superseded"?"superseded":"skipped",reason);};for(const[key,run]of Object.entries(dreams.open)){const bot=state.team.bots[run.botId],stopped=!bot?"archived":inactive(bot);if(run.template!==void 0){const intent=s.intents[hash(occurrenceIntentKey(key))];if(!intent)close(key,run,"failed","intent_compacted");else if(intent.conclusion)close(key,run,intent.conclusion);else if(stopped&&intent.phase!=="inflight"&&!intent.cancelReason)intent.cancelReason="cancelled";continue}if(s.occurrences[key]?.hook?.executionSuperseded){skip(key,run,"superseded");continue}if(!sync.policy){skip(key,run,"dreaming_off");continue}if(!bot||stopped){skip(key,run,stopped==="suspended"?"bot_suspended":"bot_archived");continue}if(sync.refused(bot.id)){skip(key,run,"device_unavailable");continue}if(bot.readyRevision!==bot.revision){skip(key,run,"bot_not_ready");continue}const record=dreams.bots[bot.id]??={since:run.windowEnd};const settled=settledAfter(Object.values(state.turns).filter(turn=>turn.botId===bot.id),record.throughTurn),fresh=settled.filter(completed);if(!fresh.length){skip(key,run,"no_new_turns");continue}const model=chooseModel(sync.policy,sync.models,bot.model,bot.execution.deviceId);if(!model){skip(key,run,"model_unavailable");continue}let rows=fresh;let throughTurn=settled.at(-1).id;if(sync.historyMode){const read=sync.history?.get(key);if(read===void 0)continue;if(read===null){skip(key,run,"history_unavailable");continue}const readSettled=settledAfter(read,record.throughTurn);rows=readSettled.filter(completed);if(!rows.length){skip(key,run,"no_new_turns");continue}throughTurn=readSettled.at(-1).id;}const window={fromMs:Math.min(record.since,run.windowEnd),toMs:run.windowEnd};const instruction=dreamInstruction(rows,window,sync.policy.maxDurationMs,sync.instructionMaxBytes);Object.assign(run,{template:model.template,fallback:model.fallback,throughTurn});promoteOccurrence(s,sync.tenant,key,dreamExecution(model.base??bot.execution,bot.execution,instruction,sync.policy.maxDurationMs,window,sync.policy.nativeSessions));changed=true;}return changed}function dreamReads(state){return Object.entries(state.dreams?.open??{}).filter(([,run])=>run.template===void 0).map(([key,run])=>({key,botId:run.botId,turnId:occurrenceIntentKey(key)}))}function roundTurn(state,round){const turns=round.seats.map(id=>state.turns[id]).filter(turn=>turn!==void 0);const conclusions=turns.map(turn=>turn.conclusion).filter(value=>value!==void 0);if(conclusions.includes("cancelled"))return {id:round.id,root:round.root,status:"failed",conclusion:"cancelled"};if(turns.some(turn=>turn.status==="succeeded"||turn.conclusion==="succeeded"||turn.conclusion==="delivered")){return {id:round.id,root:round.root,status:"succeeded",conclusion:"succeeded"}}const failed=new Set(["failed","expired","declined","superseded","abandoned"]);if(conclusions.some(conclusion=>failed.has(conclusion))||turns.some(turn=>turn.status==="failed")){return {id:round.id,root:round.root,status:"failed",conclusion:"failed"}}return {id:round.id,root:round.root,status:"queued"}}function inboundState(state){const turns={...state.turns};for(const round of Object.values(state.team.rounds))if(round.root===round.id)turns[round.id]??=roundTurn(state,round);return {channel:state.channel,turns,inputBatches:state.inputBatches}}function inboundDispositionsOf(state){if(Object.keys(state.channel?.inbounds??{}).length===0)return [];return inboundDispositions(inboundState(state))}function inboundProjection(disposition){const id=disposition.disposition==="filtered"?`inbound:${disposition.id}:filtered:${disposition.code}`:`inbound:${disposition.id}:${disposition.disposition}:${disposition.turnId}`;return {id,value:json(disposition)}}function projectInboundDispositions(state,emit){for(const disposition of inboundDispositionsOf(state)){const projection=inboundProjection(disposition);emit(projection.id,projection.value);}}var IntentOutcomeError=class extends Error{constructor(key,code,message){super(message);this.key=key;this.code=code;this.name="IntentOutcomeError";}key;code};function routeTerminal(state,key,handler){if(handler!==void 0)return {kind:"host_intent",handler};if(dreamOf(state,key))return {kind:"dream"};if(!Object.hasOwn(state.turns,key))throw new IntentOutcomeError(key,"unknown_intent","No Bot Turn or Host intent has this key");return {kind:"bot_turn"}}function runHostIntentHandler(key,name,run){if(run===void 0)throw new IntentOutcomeError(key,"handler_failed",`Unknown Host intent handler: ${name}`);let result;try{result=run();}catch(cause){throw new IntentOutcomeError(key,"handler_failed",cause instanceof Error?cause.message:String(cause))}if(result&&typeof result.then==="function"){void Promise.resolve(result).catch(()=>{});throw new IntentOutcomeError(key,"handler_failed","Host intent handler must be synchronous")}}function outcomeFailure(key,cause){return new IntentOutcomeError(key,"outcome_failed",cause instanceof Error?cause.message:String(cause))}function botOutcomePorts({taskId:taskId3,routines,manage,roomPosts}){return {manage,createRoutine:(turn,action,index)=>routines.create(createDefinition(routines.list(),turn.botId,taskId3,index,action,turn.authority??"bot")),updateRoutine:(turn,action)=>routines.update(updateDefinition(routines.list(),turn.botId,action)),cancelRoutine:(turn,action)=>routines.lifecycle(owned(routines.list(),turn.botId,action.routineId).definition.id,"completed"),roomPosts}}function syncHead(state,coalesce,now){sealDueBatches2(state,coalesce,now);expireCards(state,now);}function syncTail(state,conclusions,now,emit){if(conclusions!==void 0){withholdStaged(conclusions,state);cleanReplyTokens(conclusions,state,now);}projectInputBatches(state,emit);projectInboundDispositions(state,emit);}function intentFacts(s){const intent=key=>s.intents[hash(key)];return {intent:key=>{const row=intent(key);return row&&{taskId:row.taskId,...row.conclusion?{conclusion:row.conclusion}:{},...row.cancelReason?{cancelReason:row.cancelReason}:{}}},started:key=>{const row=intent(key);return !!row&&Array.from({length:row.generation+1},(_,g)=>s.executions[taskId(key,g)]).some(execution=>execution?.started||execution?.terminal!==void 0&&execution.terminal.envelope.type!=="task.decline")},declineCode:key=>{const row=intent(key),envelope=row&&s.executions[row.taskId]?.terminal?.envelope;return envelope?.type==="task.decline"?envelope.payload.code:void 0},offeredTo:key=>{const row=intent(key),execution=row&&s.executions[row.taskId];return row?.phase==="inflight"&&execution?.submission==="delivered"&&!execution.started&&execution.attempt?.status==="offered"?row.execution.deviceId:void 0}}}function intentRows(s){return {intent:key=>intentFacts({intents:s.intents,executions:{}}).intent(key)}}function observeDevices2(s,state,devices,emit){observeDevices(state,intentFacts(s),devices,emit);}function settleDelegations2(s,state,now,emit,timers){settleDelegations(state,intentFacts(s),now,emit,timers);}function turnIntentRetired(ledger,s,turn,now){return ledger.hasTombstone("intent",turn.id,now)||turn.source==="routine"&&!s.occurrences[routineOccurrence(turn)]}var botCompactVeto=(ledger,key)=>{const state=ledger.application.collaboration;if(state===void 0)return void 0;if(state.version!==3)return "Unsupported Bot collaboration state version";if(state.switchExport)return "switch_exported";return compactVeto(state,key,{hasIntent:turnId=>!!ledger.intents[hash(turnId)],receipt:taskId3=>ledger.executions[taskId3]?.messageReceipt})};var SWITCH_EXPORT_VERSION=1;var SWITCH_SECTIONS=["collaboration","archived","intents","routines","occurrences","outbox","tombstones"];function switchAttempts(intent){return intent===void 0||intent.submission==="reserved"?0:intent.generation+1}var SwitchExportError=class extends Error{constructor(reason,message){super(message);this.reason=reason;this.name="SwitchExportError";}reason;code="switch_export_refused"};var IDENTITY={archived:row=>[row.namespace,row.id],intents:row=>row.key,routines:row=>row.id,occurrences:row=>row.key,outbox:row=>[row.kind,row.occurrenceKey],tombstones:row=>[row.kind,row.digest]};var LISTS=SWITCH_SECTIONS.filter(section=>section!=="collaboration");var HEADER=["version","source","domain","devices","exportedAt"];var compare=(a,b)=>a<b?-1:a>b?1:0;function sealSwitchExport(content){checkContent(content,[...HEADER,...SWITCH_SECTIONS]);const sealed=structuredClone(content);sealed.devices.sort((a,b)=>compare(a.deviceId,b.deviceId));for(const section of LISTS){const key=IDENTITY[section];sealed[section].sort((a,b)=>compare(canonical(key(a)),canonical(key(b))));}checkOrder(sealed);return {...sealed,manifest:manifestOf(sealed)}}function verifySwitchExport(document){checkContent(document,[...HEADER,...SWITCH_SECTIONS,"manifest"]);ensure(keys(document.manifest,["counts","digests","digest"])&&keys(document.manifest.counts,SWITCH_SECTIONS)&&keys(document.manifest.digests,SWITCH_SECTIONS),"manifest keys");checkOrder(document);const manifest=manifestOf(document);if(canonical(manifest)!==canonical(document.manifest)){throw new SwitchExportError("manifest",`Switch export manifest does not match its content: ${document.manifest.digest} != ${manifest.digest}`)}return manifest}function manifestOf(content){const counts={},digests={};counts.collaboration=1;digests.collaboration=hash$1(JSON.stringify(content.collaboration));for(const section of LISTS){counts[section]=content[section].length;digests[section]=hash$1(content[section]);}const header={version:content.version,source:content.source,domain:content.domain,devices:content.devices,exportedAt:content.exportedAt};return {counts,digests,digest:hash$1({header,counts,digests})}}function checkOrder(content){for(let i=1;i<content.devices.length;i++){if(compare(content.devices[i-1].deviceId,content.devices[i].deviceId)>0){throw new SwitchExportError("unsorted",`Switch export devices are not in id order at ${content.devices[i].deviceId}`)}}for(const section of LISTS){const key=IDENTITY[section];const ids=content[section].map(row=>canonical(key(row)));for(let i=1;i<ids.length;i++){const order=compare(ids[i-1],ids[i]);if(order===0)throw new SwitchExportError("duplicate",`Switch export ${section} repeats ${ids[i]}`);if(order>0)throw new SwitchExportError("unsorted",`Switch export ${section} is not in identity order at ${ids[i]}`)}}}var object=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);var text=value=>typeof value==="string"&&value.length>0;var time2=value=>Number.isSafeInteger(value)&&value>=0;var digestText=value=>typeof value==="string"&&/^[0-9a-f]{64}$/.test(value);var CONCLUSIONS={succeeded:true,failed:true,declined:true,cancelled:true,expired:true,superseded:true};var conclusionText=value=>typeof value==="string"&&Object.hasOwn(CONCLUSIONS,value);var optional=(value,check)=>value===void 0||check(value);var oneOf=values=>value=>typeof value==="string"&&values.includes(value);function keys(value,required,allowed=[]){return object(value)&&required.every(key=>Object.hasOwn(value,key))&&Object.keys(value).every(key=>required.includes(key)||allowed.includes(key))}var receiptShape=value=>keys(value,["messageId","contentHash"])&&text(value.messageId)&&text(value.contentHash);function json2(value){try{validateJson(value);return true}catch{return false}}function invalid(message){throw new SwitchExportError("invalid",`Invalid switch export: ${message}`)}function ensure(ok,message){if(!ok)invalid(message);}function reference(ok,message){if(!ok)throw new SwitchExportError("reference",`Switch export ${message}`)}function definition(value,id){const runs=["execution","hostJob","hostOccurrence"];if(!keys(value,["id","version","timeZone","rule","waitMs","lateAfterMs"],["retry","endAt",...runs]))return false;const present=runs.filter(run2=>value[run2]!==void 0);if(present.length!==1)return false;const run=value[present[0]];return value.id===id&&time2(value.version)&&value.version>=1&&text(value.timeZone)&&time2(value.waitMs)&&time2(value.lateAfterMs)&&optional(value.endAt,time2)&&optional(value.retry,retryPolicy)&&(present[0]==="execution"?object(run):keys(run,["type","input"])&&text(run.type))}function routineRecord(row){return keys(row,["id","ordinal","definition","lifecycle","status","nextAt"],["pending","calendarErrors","scheduleRetryAt","scheduleRetryCount","lastError"])&&text(row.id)&&time2(row.ordinal)&&definition(row.definition,row.id)&&optional(row.pending,pending=>definition(pending,row.id))&&oneOf(["active","paused","completed"])(row.lifecycle)&&oneOf(["ok","schedule_retrying","no_occurrence_within_horizon","calendar_error"])(row.status)&&(row.nextAt===null||time2(row.nextAt))&&optional(row.calendarErrors,errors=>Array.isArray(errors)&&errors.length>0&&errors.every(error=>keys(error,["at","message"],["wakeKey"])&&time2(error.at)&&typeof error.message==="string"&&optional(error.wakeKey,text)))&&optional(row.scheduleRetryAt,time2)&&optional(row.scheduleRetryCount,count=>time2(count)&&count>=1)&&optional(row.lastError,error=>keys(error,["code","message"])&&text(error.code)&&typeof error.message==="string")}function occurrenceRecord(row){return keys(row,["key","ordinal","routineId","definitionVersion","trigger","recordedAt","nextAt","job","executionSuperseded"],["conclusion","slotReplayCount"])&&text(row.key)&&time2(row.ordinal)&&text(row.routineId)&&time2(row.definitionVersion)&&row.definitionVersion>=1&&keys(row.trigger,["kind","plannedAt"])&&oneOf(["scheduled","catch_up"])(row.trigger.kind)&&time2(row.trigger.plannedAt)&&time2(row.recordedAt)&&(row.nextAt===null||time2(row.nextAt))&&(row.job===null||keys(row.job,["attempts"],["summary"])&&time2(row.job.attempts))&&typeof row.executionSuperseded==="boolean"&&optional(row.conclusion,conclusionText)&&optional(row.slotReplayCount,count=>time2(count)&&count>=1)}function retryPolicy(retry){if(!keys(retry,["maxAttempts","delaysMs","retryFailures"])||!Array.isArray(retry.delaysMs))return false;try{validateRetry(retry);return true}catch{return false}}var executionShape=row=>typeof row.started==="boolean"&&optional(row.attempt,object)&&optional(row.terminal,object)&&optional(row.messageReceipt,receiptShape);function intentRecord(row){return keys(row,["key","source","ordinal","taskId","generation","input","waitUntil","retry","submission","started","earlierExecutions","conclusion"],["handler","attempt","terminal","messageReceipt","preparationError","memoryBlocked","cancelReason","retryUntil"])&&text(row.key)&&oneOf(["user","bot","routine"])(row.source)&&optional(row.handler,text)&&time2(row.ordinal)&&digestText(row.taskId)&&time2(row.generation)&&time2(row.waitUntil)&&keys(row.input,["taskId","deviceId","payload"],["agentMessageContext"])&&text(row.input.deviceId)&&object(row.input.payload)&&object(row.input.payload.agentRef)&&text(row.input.payload.agentRef.agentId)&&retryPolicy(row.retry)&&row.generation<row.retry.maxAttempts&&oneOf(["reserved","uncertain","delivered"])(row.submission)&&executionShape(row)&&(row.submission!=="reserved"||row.generation===0&&!row.started&&row.attempt===void 0&&row.terminal===void 0&&row.messageReceipt===void 0)&&Array.isArray(row.earlierExecutions)&&row.earlierExecutions.length===row.generation&&row.earlierExecutions.every(entry=>keys(entry,["submission","started","attempt","terminal"],["messageReceipt"])&&oneOf(["uncertain","delivered"])(entry.submission)&&executionShape(entry))&&optional(row.preparationError,text)&&optional(row.memoryBlocked,blocked=>keys(blocked,["resume","reason"])&&oneOf(["queued","backoff"])(blocked.resume)&&typeof blocked.reason==="string")&&optional(row.cancelReason,oneOf(["expired","cancelled"]))&&optional(row.retryUntil,time2)&&optional(row.conclusion,conclusionText)}function checkContent(content,top){ensure(keys(content,top),"document keys");ensure(json2(content),"not JSON");ensure(content.version===SWITCH_EXPORT_VERSION,`version ${String(content.version)}`);ensure(content.source==="L"||content.source==="H","source");ensure(text(content.domain),"domain");ensure(time2(content.exportedAt),"exportedAt");ensure(Array.isArray(content.devices)&&content.devices.length>0,"devices");for(const device of content.devices){ensure(keys(device,["deviceId","frozenRevision"])&&text(device.deviceId)&&time2(device.frozenRevision)&&device.frozenRevision>=1,"device");}if(new Set(content.devices.map(device=>device.deviceId)).size!==content.devices.length){throw new SwitchExportError("duplicate","Switch export lists a device twice")}for(const section of LISTS)ensure(Array.isArray(content[section]),section);checkCollaboration(content);for(const row of content.archived){ensure(keys(row,["namespace","id","body"],["expiresAt"])&&text(row.namespace)&&text(row.id)&&optional(row.expiresAt,time2),"archived row");}for(const row of content.intents){if(object(row)&&row.conclusion===void 0)throw new SwitchExportError("open_work",`Switch export has an open intent: ${String(row.key)}`);ensure(intentRecord(row),"intent");}for(const row of content.routines){ensure(routineRecord(row),"routine");if(row.definition.execution!==void 0||row.pending?.execution!==void 0){throw new SwitchExportError("execution_routine",`Switch export has an execution routine, which K8 domains do not run: ${row.id}`)}}for(const row of content.occurrences)ensure(occurrenceRecord(row),"occurrence");for(const row of content.outbox){if(object(row)&&row.kind==="projection"){throw new SwitchExportError("projection_pending",`Switch export has a pending projection; flush it first: ${String(row.id)}`)}ensure(keys(row,["kind","occurrenceKey"])&&row.kind==="host-job"&&text(row.occurrenceKey),"outbox row");}for(const row of content.tombstones){ensure(keys(row,["kind","digest"],["expiresAt"])&&oneOf(["intent","row","slot","application"])(row.kind)&&digestText(row.digest)&&optional(row.expiresAt,time2),"tombstone");}checkReferences(content);}function checkReferences(content){for(const section of ["intents","routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal);if(new Set(ordinals).size!==ordinals.length)throw new SwitchExportError("duplicate",`Switch export ${section} repeats an ordinal`)}for(const section of ["routines","occurrences"]){const ordinals=content[section].map(row=>row.ordinal).sort((a,b)=>a-b);ensure(ordinals.every((ordinal,position)=>ordinal===position),`${section} ordinals are not their positions 0 to ${ordinals.length-1}`);}const occurrences=new Map(content.occurrences.map(row=>[row.key,row]));const occurrenceOfIntent=new Map(content.occurrences.map(row=>[occurrenceIntentKey(row.key),row.key]));const promoted=new Set;for(const row of content.intents){reference(row.taskId===taskId(row.key,row.generation),`intent ${row.key} has task id ${row.taskId}, not that of generation ${row.generation}`);ensure(row.input.taskId===row.taskId,`intent ${row.key} input is not frozen for its task id`);if(isOccurrenceIntentKey(row.key)){const key=occurrenceOfIntent.get(row.key);reference(key!==void 0,`intent ${row.key} names no occurrence of the export`);promoted.add(key);}}const routineById=new Map(content.routines.map(row=>[row.id,row]));const pendingJobs=new Set(content.outbox.map(row=>row.occurrenceKey));const slots=new Set;for(const row of content.occurrences){const routine=routineById.get(row.routineId);reference(routine!==void 0,`occurrence ${row.key} names no routine of the export: ${row.routineId}`);reference(row.key===hash$1([row.routineId,row.definitionVersion,row.trigger]),`occurrence ${row.key} is not the key of its routine slot and trigger`);const slot=routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt);if(slots.has(slot))throw new SwitchExportError("duplicate",`Switch export has two occurrences of the slot of ${row.key}`);slots.add(slot);ensure(!(promoted.has(row.key)&&row.conclusion!==void 0),`occurrence ${row.key} has an intent and its own conclusion`);if(routine.definition.hostJob){ensure(row.job!==null&&!promoted.has(row.key)&&pendingJobs.has(row.key)===(row.conclusion===void 0),`Host job occurrence ${row.key} is not promoted, and has a pending job exactly when it is open`);}else ensure(row.job===null,`occurrence ${row.key} has a Host job, but its routine runs a hook`);}const archivedReplies=new Map(content.archived.filter(row=>row.namespace==="replies").map(row=>[row.id,row.body]));const replyOf=taskId3=>content.collaboration.replies[taskId3]??archivedReplies.get(taskId3);for(const row of content.intents){const receipts=[...row.earlierExecutions.map(entry=>entry.messageReceipt),row.messageReceipt];for(let generation=0;generation<=row.generation;generation++){const reply=replyOf(taskId(row.key,generation)),receipt=receipts[generation];const same2=receipt===void 0?reply===void 0:object(reply)&&reply.messageId===receipt.messageId&&reply.contentHash===receipt.contentHash;if(!same2){throw new SwitchExportError("receipt_mismatch",`Switch export intent ${row.key} generation ${generation} has a message receipt that differs from its K8 reply`)}}}for(const row of content.outbox){reference(occurrences.get(row.occurrenceKey)?.job!=null,`Host job ${row.occurrenceKey} names no Host job occurrence`);}}var COLLABORATION_KEYS=["version","team","turns","budgets","delegations","batches","units","replies","schemas","questions","cards","rejected","audit","sequence"];var COLLABORATION_OPTIONAL=["inputs","inputBatches","channel","revision","commands","cardCalls","wouldDo","dreams"];function checkCollaboration(content){const state=content.collaboration;ensure(object(state),"collaboration state");if(state.topology!==void 0)throw new SwitchExportError("owner_record","Switch export carries the source owner records (topology)");if(state.hostIntents!==void 0)throw new SwitchExportError("owner_record","Switch export carries L hostIntents; each intent carries its handler");if(state.switchExport!==void 0||state.switchImport!==void 0){throw new SwitchExportError("owner_record","Switch export carries an L switch record (switchExport or switchImport)")}ensure(keys(state,COLLABORATION_KEYS,COLLABORATION_OPTIONAL)&&state.version===3&&object(state.team)&&object(state.team.bots)&&Array.isArray(state.team.homeOperations)&&object(state.turns)&&optional(state.inputBatches,object)&&optional(state.cardCalls,object)&&optional(state.wouldDo,object),"collaboration state");for(const bot of Object.values(state.team.bots))ensure(object(bot)&&object(bot.execution)&&text(bot.execution.deviceId),"bot");for(const turn of Object.values(state.turns)){ensure(object(turn),"turn");if(turn.source==="routine")ensure(typeof turn.id==="string"&&isOccurrenceIntentKey(turn.id),`routine Turn ${String(turn.id)} names no occurrence`);}for(const batch of Object.values(state.inputBatches??{}))ensure(object(batch),"input batch");for(const row of Object.values(state.wouldDo??{}))ensure(object(row)&&text(row.turnId),"would-do row without turnId");for(const op of state.team.homeOperations)ensure(object(op),"home operation");const devices=new Set(content.devices.map(device=>device.deviceId));for(const bot of Object.values(state.team.bots)){if(!bot.archived&&!devices.has(bot.execution.deviceId)){throw new SwitchExportError("device_missing",`Bot ${bot.id} runs on device ${bot.execution.deviceId}, which the export does not move`)}}for(const turn of Object.values(state.turns)){if(!turn.conclusion)throw new SwitchExportError("open_work",`Switch export has an open Turn: ${turn.id}`)}for(const batch of Object.values(state.inputBatches??{})){if(batch.state==="open")throw new SwitchExportError("open_work",`Switch export has an open input batch: ${batch.id}`)}for(const op of state.team.homeOperations){if(op.status==="pending"&&op.sent===true){throw new SwitchExportError("home_sent",`Switch export has a pending Agent home write that may have been sent: ${op.sequence}`)}}if(Object.keys(state.cardCalls??{}).length)throw new SwitchExportError("card_call","Switch export has a card call in flight")}var SwitchExportedError=class extends Error{constructor(digest){super(`The domain was exported for a switch (${digest}); it writes nothing until the switch is aborted`);this.digest=digest;this.name="SwitchExportedError";}digest;code="switch_exported"};var SwitchImportedError=class extends Error{constructor(digest){super(`The domain holds the switch import ${digest}; commit it or discard it first`);this.digest=digest;this.name="SwitchImportedError";}digest;code="switch_imported"};var DeviceSwitchingError=class extends Error{constructor(deviceId,target,revision){super(`Device ${deviceId} is switching to ${target}`);this.deviceId=deviceId;this.target=target;this.revision=revision;this.name="DeviceSwitchingError";}deviceId;target;revision;code=DEVICE_SWITCHING};function exportMarkOf(value){const mark=value;const valid=typeof value==="object"&&value!==null&&Object.keys(value).sort().join(",")==="devices,digest,exportedAt"&&typeof mark.digest==="string"&&Number.isSafeInteger(mark.exportedAt)&&Array.isArray(mark.devices)&&mark.devices.length>0&&mark.devices.every(device=>!!device&&Object.keys(device).sort().join(",")==="deviceId,frozenRevision"&&typeof device.deviceId==="string"&&Number.isSafeInteger(device.frozenRevision)&&device.frozenRevision>0);if(!valid)throw new Error("Invalid switch export record");return mark}var DeviceModeError=class extends Error{constructor(deviceId,mode,revision){super(`Device ${deviceId} is owned by ${mode}`);this.deviceId=deviceId;this.mode=mode;this.revision=revision;this.name="DeviceModeError";}deviceId;mode;revision;code=DEVICE_NOT_BOUND;reason="mode"};function recordOf(state,deviceId){return state.topology&&Object.hasOwn(state.topology,deviceId)?state.topology[deviceId]:void 0}function deviceTopology(state,deviceId){const row=recordOf(state,deviceId);return row?{...row}:{mode:"L",revision:0}}function deviceRefusal(state,deviceId){const row=recordOf(state,deviceId);return row?.mode==="H"?"mode":row?.switching?"switching":void 0}function botDeviceRefusal(state,botId){const bot=state.team.bots[botId];return bot&&deviceRefusal(state,bot.execution.deviceId)}function admitDevice(state,deviceId){const row=recordOf(state,deviceId);if(row?.mode==="H")throw new DeviceModeError(deviceId,row.mode,row.revision);if(row?.switching)throw new DeviceSwitchingError(deviceId,row.switching,row.revision)}function admitBot(state,botId){const bot=state.team.bots[botId];if(bot)admitDevice(state,bot.execution.deviceId);}function switchWork(s,deviceId){const state=stateOf(s.application),onDevice=botId=>state.team.bots[botId]?.execution.deviceId===deviceId;return {intents:Object.values(s.intents).filter(intent=>!intent.conclusion&&intent.execution.deviceId===deviceId).map(intent=>intent.key),turns:Object.values(state.turns).filter(turn=>!turn.conclusion&&!s.intents[hash(turn.id)]&&onDevice(turn.botId)).map(turn=>turn.id),batches:Object.values(state.inputBatches??{}).filter(batch=>batch.state==="open"&&onDevice(batch.botId)).map(batch=>batch.id),homeOperations:state.team.homeOperations.filter(op=>op.status==="pending"&&homeSent(op)&&op.request.deviceId===deviceId).map(op=>op.sequence)}}function homeSent(op){return op.sent===true}function switchDrained(work){return !work.intents.length&&!work.turns.length&&!work.batches.length&&!work.homeOperations.length}function switchStep(s,deviceId,expectedRevision,step){const state=stateOf(s.application),row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(step==="freeze"?row.switching:!row.switching)throw new Error(`Device ${deviceId} is ${row.switching?"already":"not"} switching`);if(step==="commit"&&!switchDrained(switchWork(s,deviceId)))throw new Error(`Device ${deviceId} still has open work`);const next=step==="freeze"?{mode:"L",revision:row.revision+1,switching:"H"}:{mode:step==="commit"?"H":"L",revision:row.revision+1};Object.defineProperty(state.topology??={},deviceId,{value:next,enumerable:true,writable:true,configurable:true});return {...next}}function checkTopology(state){for(const[deviceId,row]of Object.entries(state.topology??{})){const keys2=Object.keys(row??{}).sort().join(",");const valid=!!row&&(row.mode==="L"||row.mode==="H")&&Number.isSafeInteger(row.revision)&&row.revision>0&&(row.switching===void 0?keys2==="mode,revision":row.switching==="H"&&row.mode==="L"&&keys2==="mode,revision,switching");if(!valid)throw new Error(`Invalid topology record for device ${deviceId}`)}}function refuseExported(state){if(state.switchExport)throw new SwitchExportedError(state.switchExport.digest)}function refuseImported(state){if(state.switchImport)throw new SwitchImportedError(state.switchImport.digest)}function checkSwitchRecords(state){refuseImported(state);if(state.switchExport!==void 0)exportMarkOf(state.switchExport);}var INTENT_KEYS=["id","key","source","execution","waitUntil","retry","agent","sequence","phase","generation","taskId","notBefore","attempts"];var INTENT_OPTIONAL=["memoryBlocked","preparationError","occurrence","retryUntil","cancelReason","conclusion"];var EXECUTION_KEYS=["input","submission","started"];var EXECUTION_OPTIONAL=["messageReceipt","attempt","terminal"];var ROUTINE_KEYS=["definition","lifecycle","status","next"];var ROUTINE_OPTIONAL=["pending","scheduleRetryAt","scheduleRetryCount","lastError","calendarErrors"];var OCCURRENCE_KEYS=["key","routineId","definitionVersion","trigger","wakeKey","recordedAt","nextAt","attempts"];var OCCURRENCE_OPTIONAL=["intentId","job","hook","conclusion","slotReplayCount"];var LEDGER_KEYS=["version","sequence","scanSequence","intents","executions","routines","occurrences","slots","outbox","applied","application","scanWake"];var LEDGER_OPTIONAL=["memory","ignoredWakes"];function refuse(reason,message){throw new SwitchExportError(reason,`Switch export source: ${message}`)}function derived(ok,message){if(!ok)refuse("reference",message);}function exact(value,required,optional2,what){const own=Object.keys(value);if(!required.every(key=>own.includes(key))||!own.every(key=>required.includes(key)||optional2.includes(key))){refuse("invalid",`${what} has keys ${own.join(", ")}`);}}var same=(a,b)=>canonical$1(a)===canonical$1(b);function defined(source){return Object.fromEntries(Object.entries(source).filter(([,value])=>value!==void 0))}function liveState(state){const live=structuredClone(state);delete live.topology;delete live.hostIntents;delete live.switchExport;delete live.switchImport;return live}function switchContent(dump,tenant,header){const s=dump.body;exact(s,LEDGER_KEYS,LEDGER_OPTIONAL,"The K4 ledger");if(s.memory&&Object.values(s.memory).some(rows=>rows&&Object.keys(rows).length)||dump.memoryTombstones.length){refuse("invalid","the domain has Agent memory state, which a switch does not move");}exact(s.application,["collaboration"],[],"The K4 application state");const state=stateOf(s.application);const handlers=state.hostIntents??{};const intents=[],tasks=new Set,succeeded=new Set;for(const[id,intent]of Object.entries(s.intents)){exact(intent,INTENT_KEYS,INTENT_OPTIONAL,`Intent ${intent.key}`);if(!intent.conclusion||intent.phase!=="settled")refuse("open_work",`intent ${intent.key} is open`);derived(id===hash(intent.key),`intent ${intent.key} is stored under ${id}`);derived(intent.agent===agentKey(tenant,intent.execution),`intent ${intent.key} queues under another tenant`);derived(intent.taskId===taskId(intent.key,intent.generation),`intent ${intent.key} task id is not that of its generation`);derived(isOccurrenceIntentKey(intent.key)?intent.occurrence!==void 0&&intent.key===occurrenceIntentKey(intent.occurrence):intent.occurrence===void 0,`intent ${intent.key} names occurrence ${String(intent.occurrence)}`);const current=s.executions[intent.taskId];if(!current)refuse("reference",`intent ${intent.key} has no execution`);exact(current,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${intent.taskId}`);derived(same(current.input,frozenInput(intent.execution,intent.taskId)),`intent ${intent.key} execution differs from its frozen input`);derived(intent.attempts===switchAttempts({submission:current.submission,generation:intent.generation}),`intent ${intent.key} attempts`);tasks.add(intent.taskId);const earlierExecutions=[];for(let generation=0;generation<intent.generation;generation++){const task=taskId(intent.key,generation),earlier=s.executions[task];if(!earlier)refuse("reference",`intent ${intent.key} has no execution of generation ${generation}`);exact(earlier,EXECUTION_KEYS,EXECUTION_OPTIONAL,`Execution ${task}`);derived(same(earlier.input,frozenInput(intent.execution,task)),`intent ${intent.key} generation ${generation} input differs`);if(earlier.submission==="reserved")refuse("invalid",`intent ${intent.key} generation ${generation} was never begun`);earlierExecutions.push(defined({submission:earlier.submission,started:earlier.started,attempt:earlier.attempt,terminal:earlier.terminal,messageReceipt:earlier.messageReceipt}));tasks.add(task);}if(intent.conclusion==="succeeded")succeeded.add(intent.taskId);const handler=Object.hasOwn(handlers,intent.key)?handlers[intent.key].handler:void 0;intents.push(defined({key:intent.key,source:intent.source,handler,ordinal:intent.sequence,taskId:intent.taskId,generation:intent.generation,input:current.input,waitUntil:intent.waitUntil,retry:intent.retry,submission:current.submission,started:current.started,attempt:current.attempt,terminal:current.terminal,messageReceipt:current.messageReceipt,earlierExecutions,preparationError:intent.preparationError,memoryBlocked:intent.memoryBlocked,cancelReason:intent.cancelReason,retryUntil:intent.retryUntil,conclusion:intent.conclusion}));}for(const task of Object.keys(s.executions))derived(tasks.has(task),`execution ${task} belongs to no intent`);for(const key of Object.keys(handlers))derived(!!s.intents[hash(key)],`Host intent ${key} has no K4 intent`);derived(same(Object.keys(s.applied).sort(),[...succeeded].sort()),"K4 applied is not the succeeded current tasks");const routines=Object.entries(s.routines).map(([id,routine],ordinal)=>{exact(routine,ROUTINE_KEYS,ROUTINE_OPTIONAL,`Routine ${routine.definition.id}`);const{definition:definition2}=routine;derived(id===hash(definition2.id),`routine ${definition2.id} is stored under ${id}`);if(routine.next){exact(routine.next,["dedupKey","availableAt"],[],`Routine ${definition2.id} next wake`);const parsed=parseRoutineWakeKey(routine.next.dedupKey);derived(parsed?.id===definition2.id&&parsed.version===definition2.version&&parsed.at===routine.next.availableAt&&routine.next.dedupKey===routineWakeKey(definition2.id,definition2.version,routine.next.availableAt),`routine ${definition2.id} next wake key`);}return defined({id:definition2.id,ordinal,definition:definition2,pending:routine.pending,lifecycle:routine.lifecycle,status:routine.status,nextAt:routine.next?.availableAt??null,calendarErrors:routine.calendarErrors?.length?routine.calendarErrors:void 0,scheduleRetryAt:routine.scheduleRetryAt,scheduleRetryCount:routine.scheduleRetryCount,lastError:routine.lastError})});const slots=new Map,outbox=[];for(const[key,row]of Object.entries(s.outbox)){if(row.kind==="projection")refuse("projection_pending",`projection ${row.id} is not sent; flush it first`);if(row.kind==="intent")refuse("open_work",`intent ${row.intentId} has a pending submit`);if(row.kind!=="host-job")continue;exact(row,["kind","occurrenceKey"],[],`Host job ${row.occurrenceKey}`);derived(key===`host-job:${row.occurrenceKey}`,`Host job row ${key}`);outbox.push({kind:"host-job",occurrenceKey:row.occurrenceKey});}const occurrences=Object.entries(s.occurrences).map(([key,row],ordinal)=>{exact(row,OCCURRENCE_KEYS,OCCURRENCE_OPTIONAL,`Occurrence ${key}`);derived(row.key===key,`occurrence ${row.key} is stored under ${key}`);const parsed=parseRoutineWakeKey(row.wakeKey);derived(parsed?.id===row.routineId&&parsed.version===row.definitionVersion&&parsed.at===row.trigger.plannedAt&&row.wakeKey===routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt),`occurrence ${key} wake key`);slots.set(hash(row.wakeKey),key);const intent=s.intents[hash(occurrenceIntentKey(key))];derived(intent?row.intentId===intent.id:row.intentId===void 0,`occurrence ${key} intent id`);derived(row.attempts===switchAttempts(intent&&{submission:s.executions[intent.taskId].submission,generation:intent.generation}),`occurrence ${key} attempts`);derived(intent?row.conclusion===intent.conclusion:true,`occurrence ${key} conclusion differs from its intent's`);if(row.job===void 0===(row.hook===void 0))refuse("invalid",`occurrence ${key} is not exactly one of a Host job and a hook`);if(row.job)exact(row.job,["attempts"],["summary","executionSuperseded"],`Occurrence ${key} job`);if(row.hook)exact(row.hook,[],["executionSuperseded"],`Occurrence ${key} hook`);return defined({key,ordinal,routineId:row.routineId,definitionVersion:row.definitionVersion,trigger:row.trigger,recordedAt:row.recordedAt,nextAt:row.nextAt,job:row.job?defined({attempts:row.job.attempts,summary:row.job.summary}):null,executionSuperseded:!!(row.job??row.hook).executionSuperseded,conclusion:intent?void 0:row.conclusion,slotReplayCount:row.slotReplayCount})});derived(same(Object.entries(s.slots).sort(),[...slots].sort()),"K4 slots are not one per occurrence");return {version:1,...header,collaboration:liveState(state),archived:dump.rows.map(row=>defined({namespace:row.namespace,id:row.id,body:row.value,expiresAt:row.expiresAt??void 0})),intents,routines,occurrences,outbox,tombstones:dump.tombstones.map(row=>defined({kind:row.kind,digest:row.identity,expiresAt:row.expiresAt??void 0}))}}function switchDump(content,tenant,owner){const byOrdinal=rows=>[...rows].sort((a,b)=>a.ordinal-b.ordinal);const records=new Map(content.intents.map(row=>[row.key,row]));const s={version:1,sequence:Math.max(0,...content.intents.map(row=>row.ordinal)),scanSequence:0,intents:{},executions:{},routines:{},occurrences:{},slots:{},outbox:{},applied:{},application:{},scanWake:null};const hostIntents={};for(const row of byOrdinal(content.intents)){const{taskId:_task,...execution}=row.input;const intent=defined({key:row.key,source:row.source,execution,waitUntil:row.waitUntil,retry:row.retry,id:hash(row.key),agent:agentKey(tenant,execution),sequence:row.ordinal,phase:"settled",generation:row.generation,taskId:row.taskId,notBefore:0,attempts:switchAttempts(row),memoryBlocked:row.memoryBlocked,preparationError:row.preparationError,retryUntil:row.retryUntil,cancelReason:row.cancelReason,conclusion:row.conclusion});s.intents[intent.id]=intent;s.executions[row.taskId]=defined({input:row.input,submission:row.submission,started:row.started,attempt:row.attempt,terminal:row.terminal,messageReceipt:row.messageReceipt});row.earlierExecutions.forEach((earlier,generation)=>{const task=taskId(row.key,generation);s.executions[task]=defined({input:frozenInput(execution,task),...earlier});});if(row.conclusion==="succeeded")s.applied[row.taskId]=true;if(row.handler!==void 0)Object.defineProperty(hostIntents,row.key,{value:{handler:row.handler},enumerable:true,writable:true,configurable:true});}for(const row of byOrdinal(content.routines)){s.routines[hash(row.id)]=defined({definition:row.definition,pending:row.pending,lifecycle:row.lifecycle,status:row.status,next:row.nextAt===null?null:{dedupKey:routineWakeKey(row.id,row.definition.version,row.nextAt),availableAt:row.nextAt},calendarErrors:row.calendarErrors,scheduleRetryAt:row.scheduleRetryAt,scheduleRetryCount:row.scheduleRetryCount,lastError:row.lastError});}for(const row of byOrdinal(content.occurrences)){const wakeKey=routineWakeKey(row.routineId,row.definitionVersion,row.trigger.plannedAt);const intent=s.intents[hash(occurrenceIntentKey(row.key))];if(intent)intent.occurrence=row.key;const superseded=row.executionSuperseded?{executionSuperseded:true}:{};s.occurrences[row.key]=defined({key:row.key,routineId:row.routineId,definitionVersion:row.definitionVersion,trigger:row.trigger,wakeKey,recordedAt:row.recordedAt,nextAt:row.nextAt,intentId:intent?.id,job:row.job?{...row.job,...superseded}:void 0,hook:row.job?void 0:superseded,attempts:switchAttempts(records.get(occurrenceIntentKey(row.key))),conclusion:intent?intent.conclusion:row.conclusion,slotReplayCount:row.slotReplayCount});s.slots[hash(wakeKey)]=row.key;}for(const row of content.outbox)s.outbox[`host-job:${row.occurrenceKey}`]={kind:"host-job",occurrenceKey:row.occurrenceKey};s.application.collaboration={...structuredClone(content.collaboration),...Object.keys(hostIntents).length?{hostIntents}:{},...defined(owner)};return {version:1,body:s,memoryTombstones:[],tombstones:content.tombstones.map(row=>({kind:row.kind,identity:row.digest,expiresAt:row.expiresAt??null})),rows:content.archived.map(row=>({namespace:row.namespace,id:row.id,value:row.body,expiresAt:row.expiresAt??null}))}}var headerOf=document=>({source:document.source,domain:document.domain,devices:document.devices,exportedAt:document.exportedAt});function sealLedger(ledger,header){return sealSwitchExport(switchContent(ledger.dumpForSwitch(),ledger.tenant,header))}var importOf=state=>{if(!state.switchImport)throw new Error("This ledger holds no switch import record");return state.switchImport};function importForSwitch(ledger,document){const manifest=verifySwitchExport(document);if(document.source!=="H")throw new SwitchExportError("invalid",`An L owner imports only an H export, not one from ${document.source}`);const devices=document.devices.map(device=>device.deviceId);const topology={};for(const id of devices)Object.defineProperty(topology,id,{value:{mode:"H",revision:1},enumerable:true,writable:true,configurable:true});ledger.loadForSwitch(switchDump(document,ledger.tenant,{topology,switchImport:{digest:manifest.digest,devices}}),readBack=>{const back=sealSwitchExport(switchContent(readBack,ledger.tenant,headerOf(document))).manifest.digest;if(back!==manifest.digest)throw new SwitchExportError("manifest",`The imported ledger reads back as ${back}, not ${manifest.digest}`)});return {digest:manifest.digest,devices}}function commitImport(ledger,digest){ledger.transaction(s=>{const state=stateOf(s.application),record=importOf(state);if(record.discarding)throw new Error("The switch import is being discarded");if(record.digest!==digest)throw new Error(`The switch import is ${record.digest}, not ${digest}`);for(const id of record.devices){const row=state.topology&&Object.hasOwn(state.topology,id)?state.topology[id]:void 0;if(row?.mode!=="H"||row.revision!==1||row.switching)throw new Error(`Device ${id} is not an imported device`);state.topology[id]={mode:"L",revision:2};}delete state.switchImport;});}function discardImport(ledger){ledger.transaction(s=>{importOf(stateOf(s.application)).discarding=true;});ledger.discard();}function writeLedger(ledger,apply){return ledger.transaction((s,rows)=>{refuseImported(stateOf(s.application));const result=apply(s,rows);refuseExported(stateOf(s.application));return result})}function commitInLedger(ledger,request,ports){return writeLedger(ledger,(s,rows)=>commitInRows(stateOf(s.application),ledger.tenant,request,rows,ports(s)))}function commitInRows(state,scope,request,rows,ports){let admitted;const result=commitCommand(state,request,{scope,recordCallbacks:false,archived:id=>rows.get("commands",id),admitted:ids=>{admitted=ids;}},ports);refuseRetired(admitted,(namespace,id)=>rows.isRetired(namespace,id));return result}function retainInLedger(ledger,input,limits){return writeLedger(ledger,(s,rows)=>retainRoots(stateOf(s.application),input,limits,{hasIntent:turnId=>!!s.intents[hash(turnId)],occurrenceOpen:turnId=>{const occurrence=s.occurrences[routineOccurrence({id:turnId})];return !!occurrence&&!occurrence.conclusion}},rows))}function migrateWouldDo(ledger){return writeLedger(ledger,(s,rows)=>{const state=stateOf(s.application),owners=new Map,result={backfilled:0,archived:0};for(const intent of Object.values(s.intents)){if(!Object.hasOwn(state.turns,intent.key))continue;for(let generation=0;generation<=intent.generation;generation++)owners.set(taskId(intent.key,generation),intent.key);}for(const row of Object.values(state.wouldDo??{})){if(row.turnId!==void 0)continue;const turnId=owners.get(row.taskId);if(turnId!==void 0){row.turnId=turnId;result.backfilled++;continue}rows.put("wouldDo",row.id,row);delete state.wouldDo[row.id];result.archived++;}return result})}function prioritiseUser(s,state,user){const autonomous=autonomousIntentIds(Object.values(state.turns),dreamIntentIds(state));const plan=userFirst(Object.values(s.intents),user.id,autonomous,s.sequence);if(!plan)return;for(const{id,sequence}of plan.assignments)s.intents[id].sequence=sequence;s.sequence=plan.sequence;}function syncTurnInLedger(ledger,s,rows,turn,options){const facts={intent:intentFacts(s).intent,executionStarted:id=>{const row=s.intents[hash(id)];return !!row&&!!s.executions[row.taskId]?.started},retired:id=>turnIntentRetired(ledger,s,turn,options.now)?"result_retired":retiredIdentity("turn",id,(namespace,row)=>rows.isRetired(namespace,row))?"turn_retired":void 0,deviceRefusal:botId=>botDeviceRefusal(stateOf(s.application),botId)};refuseImported(stateOf(s.application));const step=syncTurn(stateOf(s.application),turn,facts,options,(key,value)=>project(s,key,value));const more=applyStep();refuseExported(stateOf(s.application));return more;function applyStep(){switch(step?.kind){case "freeze":{const intent=enqueue(s,ledger.tenant,step.input);if(step.input.source==="user")prioritiseUser(s,stateOf(s.application),intent);return true}case "routine":promoteOccurrence(s,ledger.tenant,routineOccurrence(turn),step.execution);return true;case "cancel":s.intents[hash(turn.id)].cancelReason="cancelled";return false;case "ended":return turn.source==="routine"&&concludeRoutineTurn(s,turn);default:return false}}}async function callCardsInLedger(ledger,call){for(const old of Object.values(stateOf(ledger.snapshot().application).cards)){if(!cardCallDue(old))continue;const claimed=writeLedger(ledger,s=>{const state=stateOf(s.application),card=state.cards[old.id];if(!card||!cardCallDue(card))return false;const calls=state.cardCalls??={};if(!calls[card.id])return calls[card.id]=true;delete calls[card.id];settleCardCall(card,{error:new Error(CONNECTOR_OUTCOME_UNKNOWN)});return false});if(!claimed)continue;let outcome;try{outcome={result:await call(old)};}catch(error){outcome={error};}writeLedger(ledger,s=>{const state=stateOf(s.application);delete state.cardCalls[old.id];settleCardCall(state.cards[old.id],outcome);});}}function advanceRooms(s,state,now,add,publish){const facts={};for(const id of Object.keys(state.team.seats)){const intent=s.intents[hash(id)],execution=intent&&s.executions[intent.taskId];facts[id]={admitted:!!intent,started:!!execution?.started,conclusion:intent?.conclusion};}for(const seatId of advanceRoomSeats(state,facts,now,add,publish))s.intents[hash(seatId)].cancelReason="cancelled";}function advanceRoomsAndTurns(s,state,now,step,publish){const released=()=>Object.values(state.team.seats).filter(seat=>seat.released).length;let changed=false,before;do{advanceRooms(s,state,now,(id,botId,request)=>addTurn(state,seatTurn(id,botId,request)),publish);before=released();for(const turn of Object.values(state.turns))changed=step(turn)||changed;}while(released()>before);return changed}
|
|
9
|
+
|
|
10
|
+
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitBot, admitDevice, admitUserInput2 as admitUserInput, advanceRoomsAndTurns, botCompactVeto, botDeviceRefusal, botOutcomePorts, callCardsInLedger, checkDreamInstruction, checkSwitchRecords, checkTopology, cleanReplyTokens, commitImport, commitInLedger, commitInRows, deliveryRoute, deviceRefusal, deviceTopology, discardImport, dreamIntentIds, dreamPolicy, dreamReads, echoCandidates, enablePush, exportMarkOf, homeSent, importForSwitch, inboundDisposition, inboundDispositions, inboundDispositionsOf, intentRows, migrateWouldDo, observeDevices2 as observeDevices, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseExported, refuseRoute, rememberFilteredInbound, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelegations2 as settleDelegations, settleDelivery, startDelivery, switchAttempts, switchContent, switchDrained, switchStep, switchWork, syncDreams, syncHead, syncTail, syncTurnInLedger, unknownDelivery, verifySwitchExport, writeLedger };
|
|
11
|
+
//# sourceMappingURL=chunk-5J5SOWWI.js.map
|
|
12
|
+
//# sourceMappingURL=chunk-5J5SOWWI.js.map
|