@alineo-labs/schema 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1057 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import * as z$1 from "zod";
3
+ import { z } from "zod";
4
+ //#region src/vocabulary.ts
5
+ /**
6
+ * The two lists every alineo surface derives its names from.
7
+ *
8
+ * One user meets the CLI, the SDK, the daemon's HTTP API, the MCP tools and the event
9
+ * stream. Each of those is free to pick its own spelling, and historically each did — which
10
+ * is how `spawn` came to mean "create a root agent" in the CLI and "create a child" in the
11
+ * SDK, and how `fork` came to mean three different operations.
12
+ *
13
+ * Making the vocabulary *data* is what lets CI fail a name rather than a reviewer catch it.
14
+ * The checks that consume these lists land with the surfaces they police (CLI and help
15
+ * strings, MCP tools and HTTP routes, event types); this module is only the source of truth.
16
+ */
17
+ /**
18
+ * The things alineo acts on. A name's first segment is one of these.
19
+ *
20
+ * Ordered by layer rather than alphabetically — control plane, then the agent loop, then the
21
+ * substrate, then the operator-facing objects — because that is how the surfaces group.
22
+ *
23
+ * `event`, `result` and `transcript` are the records a run leaves behind. They joined the list
24
+ * when the HTTP and MCP checks landed and found them already on the wire
25
+ * (`GET /agents/:id/transcript`, `GET /runs/:id/events`): they were vocabulary in use, just not
26
+ * written down.
27
+ *
28
+ * `memory` and `fact` joined with alineod's memory routes (`GET /agents/:id/memory`,
29
+ * `POST /agents/:id/facts`): `memory` is an agent's durable working memory, `fact` one item of
30
+ * its semantic memory.
31
+ */
32
+ const SUBJECTS = [
33
+ "run",
34
+ "agent",
35
+ "sandbox",
36
+ "session",
37
+ "turn",
38
+ "message",
39
+ "tool",
40
+ "handle",
41
+ "wait",
42
+ "inbox",
43
+ "notify",
44
+ "budget",
45
+ "exec",
46
+ "egress",
47
+ "credential",
48
+ "permission",
49
+ "workflow",
50
+ "step",
51
+ "compaction",
52
+ "retry",
53
+ "extension",
54
+ "queue",
55
+ "spec",
56
+ "environment",
57
+ "event",
58
+ "result",
59
+ "transcript",
60
+ "memory",
61
+ "fact"
62
+ ];
63
+ /**
64
+ * What alineo does to a subject. A name's second segment is one of these — in the imperative
65
+ * for a command, method, route or tool, and in the past tense for an event (`agent.spawned`).
66
+ *
67
+ * `branchSession` and `duplicateSession` are camelCase because they exist only as SDK
68
+ * methods; no route, tool or event uses them. They carry `Session` in the name on purpose:
69
+ * unqualified `branch`/`duplicate` read like sandbox operations, and they are not — both stay
70
+ * inside one container and only touch the harness conversation.
71
+ */
72
+ const VERBS = [
73
+ "start",
74
+ "spawn",
75
+ "stop",
76
+ "pause",
77
+ "resume",
78
+ "reattach",
79
+ "attach",
80
+ "prompt",
81
+ "steer",
82
+ "await",
83
+ "checkpoint",
84
+ "fork",
85
+ "branchSession",
86
+ "duplicateSession",
87
+ "add",
88
+ "list",
89
+ "remove",
90
+ "get",
91
+ "watch",
92
+ "init",
93
+ "deliver"
94
+ ];
95
+ const SUBJECT_SET = new Set(SUBJECTS);
96
+ const VERB_SET = new Set(VERBS);
97
+ function isSubject(value) {
98
+ return SUBJECT_SET.has(value);
99
+ }
100
+ function isVerb(value) {
101
+ return VERB_SET.has(value);
102
+ }
103
+ /**
104
+ * Split a two-segment name into its subject and verb, or return `null` if either half is not
105
+ * in the lists above.
106
+ *
107
+ * The separator is what distinguishes the surfaces: `_` for an MCP tool (`agent_spawn`), `.`
108
+ * for an event type (`agent.spawned`). Only the first separator splits, so a multi-word verb
109
+ * stays intact.
110
+ *
111
+ * Note for the event check (Track 1): event verbs are past tense and so will not be in
112
+ * `VERBS` literally — `agent.spawned`, not `agent.spawn`. That check needs its own tense
113
+ * rule on top of `isSubject`; this helper is exact-match only.
114
+ */
115
+ function parseName(name, separator) {
116
+ const at = name.indexOf(separator);
117
+ if (at <= 0) return null;
118
+ const subject = name.slice(0, at);
119
+ const verb = name.slice(at + separator.length);
120
+ if (!isSubject(subject) || !isVerb(verb)) return null;
121
+ return {
122
+ subject,
123
+ verb
124
+ };
125
+ }
126
+ //#endregion
127
+ //#region src/define.ts
128
+ /**
129
+ * Every definition, by type. Populated as a side effect of `defineEvent`, which is why the
130
+ * event files must be imported for the registry to be complete — `index.ts` imports all five.
131
+ */
132
+ const registry = /* @__PURE__ */ new Map();
133
+ /** A `type` that is well-formed but whose subject is not in `SUBJECTS`. */
134
+ const TYPE_SHAPE = /^([a-z]+)\.([a-z][a-z_]*)$/;
135
+ function defineEvent(definition) {
136
+ const match = TYPE_SHAPE.exec(definition.type);
137
+ if (!match) throw new Error(`Event type "${definition.type}" is not "<subject>.<past_tense_verb>" in lower snake case.`);
138
+ if (!isSubject(match[1])) throw new Error(`Event type "${definition.type}" has subject "${match[1]}", which is not in SUBJECTS. Add it to @alineo-labs/schema's vocabulary, or name the event after a subject that is already there.`);
139
+ const existing = registry.get(definition.type);
140
+ if (existing && existing !== definition) throw new Error(`Event type "${definition.type}" is defined twice.`);
141
+ registry.set(definition.type, definition);
142
+ return definition;
143
+ }
144
+ /** Every registered definition. Order is definition order, which is file order. */
145
+ function allEvents() {
146
+ return [...registry.values()];
147
+ }
148
+ function getEvent(type) {
149
+ return registry.get(type);
150
+ }
151
+ /** The subset that earns a ledger row. */
152
+ function durableEvents() {
153
+ return allEvents().filter((d) => d.durable);
154
+ }
155
+ //#endregion
156
+ //#region src/events/sandbox.ts
157
+ /**
158
+ * Substrate events — the sandbox itself, and what runs inside it.
159
+ *
160
+ * Owned by `@alineo-labs/core`, which emits every one of them through the single funnel at
161
+ * `sandbox/core.ts`'s `emit()` plus five `SandboxCreated` sites in the SDK client.
162
+ *
163
+ * These were declared in `packages/core/src/ledger.ts`, in one enum alongside the agent and
164
+ * workflow layers' events — the bottom layer defining the vocabulary of two layers above it.
165
+ * That is the coupling this package exists to break.
166
+ */
167
+ var sandbox_exports = /* @__PURE__ */ __exportAll({
168
+ CredentialBound: () => CredentialBound,
169
+ CredentialRevoked: () => CredentialRevoked,
170
+ EgressRuleAdded: () => EgressRuleAdded,
171
+ EgressRuleRemoved: () => EgressRuleRemoved,
172
+ ExecCompleted: () => ExecCompleted,
173
+ ExecOutput: () => ExecOutput,
174
+ ExecStarted: () => ExecStarted,
175
+ SandboxCheckpointCreated: () => SandboxCheckpointCreated,
176
+ SandboxClosed: () => SandboxClosed,
177
+ SandboxCreated: () => SandboxCreated,
178
+ SandboxPaused: () => SandboxPaused,
179
+ SandboxResumed: () => SandboxResumed
180
+ });
181
+ const SandboxCreated = defineEvent({
182
+ type: "sandbox.created",
183
+ durable: true,
184
+ version: 1,
185
+ description: "A sandbox reached Running state.",
186
+ schema: z.object({
187
+ sandboxId: z.string(),
188
+ name: z.string(),
189
+ runId: z.string(),
190
+ resourceId: z.string().optional(),
191
+ teamId: z.string().optional(),
192
+ /** Set when this session came from `sb.fork()`; absent for a top-level `client.sandbox()`. */
193
+ parentSandboxId: z.string().optional()
194
+ })
195
+ });
196
+ const SandboxClosed = defineEvent({
197
+ type: "sandbox.closed",
198
+ durable: true,
199
+ version: 1,
200
+ description: "A sandbox was closed and its container released.",
201
+ schema: z.object({ sandboxId: z.string() })
202
+ });
203
+ const SandboxPaused = defineEvent({
204
+ type: "sandbox.paused",
205
+ durable: true,
206
+ version: 1,
207
+ description: "pause() froze the container.",
208
+ schema: z.object({ sandboxId: z.string() })
209
+ });
210
+ const SandboxResumed = defineEvent({
211
+ type: "sandbox.resumed",
212
+ durable: true,
213
+ version: 1,
214
+ description: "resume() restored a frozen container to Running.",
215
+ schema: z.object({ sandboxId: z.string() })
216
+ });
217
+ const SandboxCheckpointCreated = defineEvent({
218
+ type: "sandbox.checkpoint_created",
219
+ durable: true,
220
+ version: 1,
221
+ description: "checkpoint() captured a snapshot.",
222
+ schema: z.object({
223
+ snapshotId: z.string(),
224
+ tag: z.string().optional()
225
+ })
226
+ });
227
+ const ExecStarted = defineEvent({
228
+ type: "exec.started",
229
+ durable: true,
230
+ version: 1,
231
+ description: "An exec() or execCode() call began.",
232
+ schema: z.object({
233
+ command: z.string().optional(),
234
+ code: z.string().optional()
235
+ })
236
+ });
237
+ const ExecOutput = defineEvent({
238
+ type: "exec.output",
239
+ durable: false,
240
+ version: 1,
241
+ description: "A streaming output chunk from a running exec.",
242
+ schema: z.object({
243
+ stream: z.enum(["stdout", "stderr"]).optional(),
244
+ text: z.string()
245
+ })
246
+ });
247
+ const ExecCompleted = defineEvent({
248
+ type: "exec.completed",
249
+ durable: true,
250
+ version: 1,
251
+ description: "An exec() or execCode() call finished.",
252
+ schema: z.object({
253
+ exitCode: z.number().int().optional(),
254
+ stdout: z.string().optional(),
255
+ stderr: z.string().optional()
256
+ })
257
+ });
258
+ const EgressRuleAdded = defineEvent({
259
+ type: "egress.rule_added",
260
+ durable: true,
261
+ version: 1,
262
+ description: "sb.egress.patch() — the exact rules handed to the sidecar, so a resume can fold a still-wanted allowance back into the new boot policy.",
263
+ schema: z.object({ rules: z.array(z.unknown()) })
264
+ });
265
+ const EgressRuleRemoved = defineEvent({
266
+ type: "egress.rule_removed",
267
+ durable: true,
268
+ version: 1,
269
+ description: "sb.egress.delete().",
270
+ schema: z.object({ targets: z.array(z.string()) })
271
+ });
272
+ const CredentialBound = defineEvent({
273
+ type: "credential.bound",
274
+ durable: true,
275
+ version: 1,
276
+ description: "sb.credentials.set()/.patch(). Binding metadata only — the credential value is never written to the ledger.",
277
+ schema: z.object({
278
+ name: z.string(),
279
+ host: z.string().optional(),
280
+ injection: z.string().optional()
281
+ })
282
+ });
283
+ const CredentialRevoked = defineEvent({
284
+ type: "credential.revoked",
285
+ durable: true,
286
+ version: 1,
287
+ description: "sb.credentials.remove().",
288
+ schema: z.object({ name: z.string() })
289
+ });
290
+ //#endregion
291
+ //#region src/events/agent.ts
292
+ /**
293
+ * The agent SDK's own events — what `alineo` adds on top of a sandbox.
294
+ *
295
+ * Started as two, both from the human-in-the-loop permission gate; `AgentCheckpointed`
296
+ * (durability-roadmap M3, 3.2) is the third. All three live in `packages/core`'s ledger enum
297
+ * too, under a "used by the `alineo` agent SDK" heading, which is exactly the layering
298
+ * inversion this package fixes: `core` knows nothing about agents. Not resolved here —
299
+ * `sb.emit()` is typed to `packages/core`'s `LedgerEvent` enum, so a new agent-SDK event still
300
+ * needs a member there to be emittable at all; this file is the vocabulary-check and
301
+ * documentation registry for the same type string, not a replacement for it yet.
302
+ */
303
+ var agent_exports = /* @__PURE__ */ __exportAll({
304
+ AgentCheckpointed: () => AgentCheckpointed,
305
+ PermissionRequested: () => PermissionRequested,
306
+ PermissionResolved: () => PermissionResolved
307
+ });
308
+ const PermissionRequested = defineEvent({
309
+ type: "permission.requested",
310
+ durable: true,
311
+ version: 1,
312
+ description: "The permission gate paused a tool call for human approval. Metadata only — raw tool arguments can carry secrets in a bash command or a file write, and are never recorded.",
313
+ schema: z.object({
314
+ requestId: z.string(),
315
+ tool: z.string(),
316
+ target: z.string(),
317
+ title: z.string().optional()
318
+ })
319
+ });
320
+ const PermissionResolved = defineEvent({
321
+ type: "permission.resolved",
322
+ durable: true,
323
+ version: 1,
324
+ description: "A permission request was answered — by a caller, a batched always/reject decision, a timeout, or a session resume dropping it.",
325
+ schema: z.object({
326
+ requestId: z.string(),
327
+ decision: z.string()
328
+ })
329
+ });
330
+ const AgentCheckpointed = defineEvent({
331
+ type: "agent.checkpointed",
332
+ durable: true,
333
+ version: 1,
334
+ description: "A turn-level checkpoint (workspace + session-file tarball) was captured and durably stored, after the tarball itself was confirmed written — a snapshot with no event pointing at it is unreachable garbage.",
335
+ schema: z.object({
336
+ turn: z.number(),
337
+ snapshotRef: z.string()
338
+ })
339
+ });
340
+ //#endregion
341
+ //#region src/events/harness.ts
342
+ /**
343
+ * The harness stream — what the agent-loop driver reports while a turn runs.
344
+ *
345
+ * These are the highest-volume events in the system and most of them are stream-only: a
346
+ * `message.updated` delta is superseded by the `message.ended` that follows it, so persisting
347
+ * every one would bloat the ledger to record something the next event already says.
348
+ *
349
+ * Two collisions the subject namespacing settles: `agent_start`/`agent_end` were a *harness
350
+ * session* beginning and ending, not an alineod agent's lifecycle, so they become
351
+ * `session.*`; and `text` was a delta of exactly one message, so it becomes
352
+ * `message.updated` rather than keeping a name that hides what it is about.
353
+ */
354
+ var harness_exports = /* @__PURE__ */ __exportAll({
355
+ CompactionEnded: () => CompactionEnded,
356
+ CompactionStarted: () => CompactionStarted,
357
+ ExtensionError: () => ExtensionError,
358
+ ExtensionUi: () => ExtensionUi,
359
+ MessageEnded: () => MessageEnded,
360
+ MessageStarted: () => MessageStarted,
361
+ MessageUpdated: () => MessageUpdated,
362
+ QueueUpdated: () => QueueUpdated,
363
+ RetryEnded: () => RetryEnded,
364
+ RetryStarted: () => RetryStarted,
365
+ SessionEnded: () => SessionEnded,
366
+ SessionStarted: () => SessionStarted,
367
+ ToolEnded: () => ToolEnded,
368
+ ToolStarted: () => ToolStarted,
369
+ ToolUpdated: () => ToolUpdated,
370
+ TurnEnded: () => TurnEnded,
371
+ TurnStarted: () => TurnStarted
372
+ });
373
+ const SessionStarted = defineEvent({
374
+ type: "session.started",
375
+ durable: true,
376
+ version: 1,
377
+ description: "The harness began a session. Was `agent_start`.",
378
+ schema: z.object({})
379
+ });
380
+ const SessionEnded = defineEvent({
381
+ type: "session.ended",
382
+ durable: true,
383
+ version: 1,
384
+ description: "The harness session finished. Was `agent_end`.",
385
+ schema: z.object({ messages: z.array(z.unknown()).optional() })
386
+ });
387
+ const TurnStarted = defineEvent({
388
+ type: "turn.started",
389
+ durable: true,
390
+ version: 1,
391
+ schema: z.object({
392
+ turnIndex: z.number().int(),
393
+ timestamp: z.number()
394
+ })
395
+ });
396
+ const TurnEnded = defineEvent({
397
+ type: "turn.ended",
398
+ durable: true,
399
+ version: 1,
400
+ schema: z.object({
401
+ turnIndex: z.number().int(),
402
+ message: z.unknown().optional(),
403
+ toolResults: z.array(z.unknown()).optional()
404
+ })
405
+ });
406
+ const ToolStarted = defineEvent({
407
+ type: "tool.started",
408
+ durable: true,
409
+ version: 1,
410
+ schema: z.object({
411
+ toolCallId: z.string(),
412
+ toolName: z.string(),
413
+ args: z.unknown()
414
+ })
415
+ });
416
+ const ToolUpdated = defineEvent({
417
+ type: "tool.updated",
418
+ durable: false,
419
+ version: 1,
420
+ description: "A partial tool result. Superseded by `tool.ended`.",
421
+ schema: z.object({
422
+ toolCallId: z.string(),
423
+ toolName: z.string(),
424
+ partialResult: z.unknown()
425
+ })
426
+ });
427
+ const ToolEnded = defineEvent({
428
+ type: "tool.ended",
429
+ durable: true,
430
+ version: 1,
431
+ schema: z.object({
432
+ toolCallId: z.string(),
433
+ toolName: z.string(),
434
+ result: z.unknown(),
435
+ isError: z.boolean()
436
+ })
437
+ });
438
+ const MessageStarted = defineEvent({
439
+ type: "message.started",
440
+ durable: false,
441
+ version: 1,
442
+ schema: z.object({ message: z.unknown() })
443
+ });
444
+ const MessageUpdated = defineEvent({
445
+ type: "message.updated",
446
+ durable: false,
447
+ version: 1,
448
+ description: "A delta on the message being written — including a plain text chunk, which was its own `text` event before. Superseded by `message.ended`.",
449
+ schema: z.object({
450
+ message: z.unknown().optional(),
451
+ delta: z.unknown().optional(),
452
+ /** Set when the delta is plain text and nothing else. */
453
+ text: z.string().optional()
454
+ })
455
+ });
456
+ const MessageEnded = defineEvent({
457
+ type: "message.ended",
458
+ durable: false,
459
+ version: 1,
460
+ schema: z.object({ message: z.unknown() })
461
+ });
462
+ const CompactionStarted = defineEvent({
463
+ type: "compaction.started",
464
+ durable: true,
465
+ version: 1,
466
+ schema: z.object({ reason: z.enum([
467
+ "manual",
468
+ "threshold",
469
+ "overflow"
470
+ ]) })
471
+ });
472
+ const CompactionEnded = defineEvent({
473
+ type: "compaction.ended",
474
+ durable: true,
475
+ version: 1,
476
+ schema: z.object({
477
+ reason: z.enum([
478
+ "manual",
479
+ "threshold",
480
+ "overflow"
481
+ ]),
482
+ result: z.object({
483
+ summary: z.string(),
484
+ firstKeptEntryId: z.string(),
485
+ tokensBefore: z.number(),
486
+ estimatedTokensAfter: z.number(),
487
+ details: z.unknown()
488
+ }).nullable(),
489
+ aborted: z.boolean(),
490
+ willRetry: z.boolean()
491
+ })
492
+ });
493
+ const RetryStarted = defineEvent({
494
+ type: "retry.started",
495
+ durable: true,
496
+ version: 1,
497
+ description: "The harness is retrying a failed model call. Was `auto_retry_start`.",
498
+ schema: z.object({
499
+ attempt: z.number().int(),
500
+ maxAttempts: z.number().int(),
501
+ delayMs: z.number(),
502
+ errorMessage: z.string()
503
+ })
504
+ });
505
+ const RetryEnded = defineEvent({
506
+ type: "retry.ended",
507
+ durable: true,
508
+ version: 1,
509
+ schema: z.object({
510
+ success: z.boolean(),
511
+ attempt: z.number().int(),
512
+ finalError: z.string().optional()
513
+ })
514
+ });
515
+ const QueueUpdated = defineEvent({
516
+ type: "queue.updated",
517
+ durable: false,
518
+ version: 1,
519
+ description: "The steering and follow-up queues changed. A view of current state, not a fact.",
520
+ schema: z.object({
521
+ steering: z.array(z.string()),
522
+ followUp: z.array(z.string())
523
+ })
524
+ });
525
+ const ExtensionUi = defineEvent({
526
+ type: "extension.ui",
527
+ durable: false,
528
+ version: 1,
529
+ description: "An extension asked the host to show something.",
530
+ schema: z.object({
531
+ method: z.string(),
532
+ params: z.unknown(),
533
+ isDialog: z.boolean(),
534
+ requestId: z.string().optional()
535
+ })
536
+ });
537
+ const ExtensionError = defineEvent({
538
+ type: "extension.error",
539
+ durable: true,
540
+ version: 1,
541
+ schema: z.object({
542
+ extensionPath: z.string(),
543
+ event: z.string(),
544
+ error: z.string()
545
+ })
546
+ });
547
+ //#endregion
548
+ //#region src/events/workflow.ts
549
+ /**
550
+ * Workflow-engine events — `@alineo-labs/workflow`'s steps and saga compensation.
551
+ *
552
+ * Moved out of `packages/core`'s enum now rather than later. Leaving them there is the exact
553
+ * defect this package exists to fix, and moving them costs nothing while everything else moves.
554
+ *
555
+ * Two names change meaning rather than spelling:
556
+ *
557
+ * - `run_started` meant a workflow run here and a *swarm* run in alineod. The two are
558
+ * `workflow.started` and `run.started` now, and nothing has to guess from context.
559
+ * - `snapshot` is **dropped**. It recorded a sandbox checkpoint that the workflow engine
560
+ * happened to take — so it emits `sandbox.checkpoint_created`, the event that already
561
+ * describes it. `checkpoint` (the workflow's own resumption point) is **dropped** too: an early
562
+ * version wrote it, nothing has for a long time, and nothing reads it.
563
+ */
564
+ var workflow_exports = /* @__PURE__ */ __exportAll({
565
+ StepCompleted: () => StepCompleted,
566
+ StepFailed: () => StepFailed,
567
+ StepRolledBack: () => StepRolledBack,
568
+ StepStarted: () => StepStarted,
569
+ WorkflowCompleted: () => WorkflowCompleted,
570
+ WorkflowFailed: () => WorkflowFailed,
571
+ WorkflowStarted: () => WorkflowStarted
572
+ });
573
+ const WorkflowStarted = defineEvent({
574
+ type: "workflow.started",
575
+ durable: true,
576
+ version: 1,
577
+ description: "A workflow run began, before any step executed. Was `run_started`.",
578
+ schema: z.object({ runId: z.string().optional() })
579
+ });
580
+ const WorkflowCompleted = defineEvent({
581
+ type: "workflow.completed",
582
+ durable: true,
583
+ version: 1,
584
+ description: "Every step finished without error.",
585
+ schema: z.object({})
586
+ });
587
+ const WorkflowFailed = defineEvent({
588
+ type: "workflow.failed",
589
+ durable: true,
590
+ version: 1,
591
+ description: "Rollback completed after a step failure.",
592
+ schema: z.object({ error: z.string().optional() })
593
+ });
594
+ const StepStarted = defineEvent({
595
+ type: "step.started",
596
+ durable: true,
597
+ version: 1,
598
+ schema: z.object({ name: z.string().optional() })
599
+ });
600
+ const StepCompleted = defineEvent({
601
+ type: "step.completed",
602
+ durable: true,
603
+ version: 1,
604
+ schema: z.object({ output: z.unknown().optional() })
605
+ });
606
+ const StepFailed = defineEvent({
607
+ type: "step.failed",
608
+ durable: true,
609
+ version: 1,
610
+ schema: z.object({ error: z.string().optional() })
611
+ });
612
+ const StepRolledBack = defineEvent({
613
+ type: "step.rolled_back",
614
+ durable: true,
615
+ version: 1,
616
+ description: "A step's rollback handler completed during saga compensation.",
617
+ schema: z.object({})
618
+ });
619
+ //#endregion
620
+ //#region src/events/alineod.ts
621
+ /**
622
+ * Swarm control-plane events — the run tree, its budgets, and how agents coordinate.
623
+ *
624
+ * Every one of these is durable. alineod's projections are rebuilt by folding them
625
+ * (`state/projection.ts`'s `rebuild()`), so an event that is not written is state that does
626
+ * not survive a restart — which is the whole basis of the daemon's crash-only design.
627
+ *
628
+ * Namespaced by subject rather than by the daemon that emits them: a user reads one mixed
629
+ * stream and needs to know what an event is *about*. `agent.spawned`, not
630
+ * `alineod.agent_spawned`.
631
+ */
632
+ var alineod_exports = /* @__PURE__ */ __exportAll({
633
+ AgentAdmissionGranted: () => AgentAdmissionGranted,
634
+ AgentAdmissionQueued: () => AgentAdmissionQueued,
635
+ AgentAdmissionTimeout: () => AgentAdmissionTimeout,
636
+ AgentEnded: () => AgentEnded,
637
+ AgentProvisioned: () => AgentProvisioned,
638
+ AgentReleased: () => AgentReleased,
639
+ AgentSpawned: () => AgentSpawned,
640
+ AgentStateChanged: () => AgentStateChanged,
641
+ AgentSteered: () => AgentSteered,
642
+ AgentSupervisionNeeded: () => AgentSupervisionNeeded,
643
+ AgentTurnFailed: () => AgentTurnFailed,
644
+ AgentTurnInterrupted: () => AgentTurnInterrupted,
645
+ BudgetDenied: () => BudgetDenied,
646
+ HandleSettled: () => HandleSettled,
647
+ InboxDelivered: () => InboxDelivered,
648
+ InboxDropped: () => InboxDropped,
649
+ InboxQueued: () => InboxQueued,
650
+ NotifyRegistered: () => NotifyRegistered,
651
+ RunClosed: () => RunClosed,
652
+ RunQuiescent: () => RunQuiescent,
653
+ RunStarted: () => RunStarted,
654
+ WaitBlocked: () => WaitBlocked,
655
+ WaitResolved: () => WaitResolved
656
+ });
657
+ const WaitMode = z.enum([
658
+ "all",
659
+ "any",
660
+ "quorum"
661
+ ]);
662
+ const RunStarted = defineEvent({
663
+ type: "run.started",
664
+ durable: true,
665
+ version: 1,
666
+ description: "A swarm run was created. Was `run_started` — the name workflow also used.",
667
+ schema: z.object({
668
+ runId: z.string(),
669
+ closeWhen: z.enum(["explicit", "quiescent"]).default("explicit")
670
+ })
671
+ });
672
+ const RunClosed = defineEvent({
673
+ type: "run.closed",
674
+ durable: true,
675
+ version: 1,
676
+ description: "The run finalized — a client deleted it (`explicit`), or it reached quiescence on its own under closeWhen: \"quiescent\". Resources are released; the ledger is kept.",
677
+ schema: z.object({
678
+ agentId: z.string().nullable(),
679
+ reason: z.enum(["explicit", "quiescent"])
680
+ })
681
+ });
682
+ const RunQuiescent = defineEvent({
683
+ type: "run.quiescent",
684
+ durable: true,
685
+ version: 1,
686
+ description: "The subtree rooted at this agent went quiescent. Only tracked while someone is awaiting it. Was `subtree_quiescent`.",
687
+ schema: z.object({
688
+ agentId: z.string().nullable(),
689
+ memberCount: z.number().int(),
690
+ asOf: z.number()
691
+ })
692
+ });
693
+ const AgentSpawned = defineEvent({
694
+ type: "agent.spawned",
695
+ durable: true,
696
+ version: 1,
697
+ schema: z.object({
698
+ agentId: z.string().nullable(),
699
+ parentAgentId: z.string().nullable(),
700
+ runId: z.string(),
701
+ specName: z.string(),
702
+ depth: z.number().int(),
703
+ spawnIndex: z.number().int(),
704
+ sandboxId: z.string().nullable(),
705
+ waitFor: z.array(z.string()).nullable().optional().describe("Persisted rather than left in the spec, so rehydrate() can retry a still-pending spawn instead of losing it."),
706
+ prompt: z.string().nullable().optional()
707
+ })
708
+ });
709
+ const AgentProvisioned = defineEvent({
710
+ type: "agent.provisioned",
711
+ durable: true,
712
+ version: 1,
713
+ description: "The sandbox exists and the bridge is up — backfills what `agent.spawned` could not know yet.",
714
+ schema: z.object({
715
+ agentId: z.string().nullable(),
716
+ sandboxId: z.string()
717
+ })
718
+ });
719
+ const AgentStateChanged = defineEvent({
720
+ type: "agent.state_changed",
721
+ durable: true,
722
+ version: 1,
723
+ schema: z.object({
724
+ agentId: z.string().nullable(),
725
+ from: z.string(),
726
+ to: z.string(),
727
+ reason: z.string().optional(),
728
+ pausedBy: z.enum(["operator", "cascade"]).optional().describe("On a transition to paused: whether this agent was the target, or was reached by a subtree pause.")
729
+ })
730
+ });
731
+ const AgentSteered = defineEvent({
732
+ type: "agent.steered",
733
+ durable: true,
734
+ version: 1,
735
+ schema: z.object({
736
+ agentId: z.string().nullable(),
737
+ message: z.string(),
738
+ scope: z.enum(["agent", "subtree"]).optional(),
739
+ roster: z.array(z.string()).optional(),
740
+ deliveredAs: z.enum([
741
+ "steer",
742
+ "turn",
743
+ "queued"
744
+ ]).optional()
745
+ })
746
+ });
747
+ const AgentReleased = defineEvent({
748
+ type: "agent.released",
749
+ durable: true,
750
+ version: 1,
751
+ description: "A finished agent's still-open sandbox was closed, or a fork landed after its spawn was stopped. The recorded outcome is unchanged.",
752
+ schema: z.object({
753
+ agentId: z.string().nullable(),
754
+ reason: z.string()
755
+ })
756
+ });
757
+ const AgentEnded = defineEvent({
758
+ type: "agent.ended",
759
+ durable: true,
760
+ version: 1,
761
+ schema: z.object({
762
+ agentId: z.string().nullable(),
763
+ outcome: z.string(),
764
+ endedAt: z.number(),
765
+ error: z.string().optional()
766
+ })
767
+ });
768
+ const HandleSettled = defineEvent({
769
+ type: "handle.settled",
770
+ durable: true,
771
+ version: 1,
772
+ schema: z.object({
773
+ agentId: z.string().nullable(),
774
+ outcome: z.string(),
775
+ resultRef: z.string().nullable()
776
+ })
777
+ });
778
+ const WaitResolved = defineEvent({
779
+ type: "wait.resolved",
780
+ durable: true,
781
+ version: 1,
782
+ description: "A held spawn's waitFor resolved. A depfail or deadline outcome ends the child failed, without ever forking it.",
783
+ schema: z.object({
784
+ agentId: z.string().nullable(),
785
+ mode: WaitMode,
786
+ outcome: z.enum([
787
+ "satisfied",
788
+ "partial",
789
+ "deadline",
790
+ "depfail"
791
+ ]),
792
+ selected: z.array(z.string()),
793
+ settled: z.array(z.object({
794
+ agentId: z.string(),
795
+ outcome: z.string().nullable()
796
+ })),
797
+ pending: z.array(z.string())
798
+ })
799
+ });
800
+ const WaitBlocked = defineEvent({
801
+ type: "wait.blocked",
802
+ durable: true,
803
+ version: 1,
804
+ description: "A held spawn is waiting on a paused dependency — one event per dependency. Was `wait_blocked_on_paused`.",
805
+ schema: z.object({
806
+ agentId: z.string().nullable(),
807
+ blockedOn: z.string()
808
+ })
809
+ });
810
+ const NotifyRegistered = defineEvent({
811
+ type: "notify.registered",
812
+ durable: true,
813
+ version: 1,
814
+ description: "This agent asked to be told when each agent in `on` finishes.",
815
+ schema: z.object({
816
+ agentId: z.string().nullable(),
817
+ on: z.array(z.string()),
818
+ wake: z.boolean()
819
+ })
820
+ });
821
+ const InboxQueued = defineEvent({
822
+ type: "inbox.queued",
823
+ durable: true,
824
+ version: 1,
825
+ description: "Something for this agent to be told — a notification, a steer waiting for it to resume, or a child needing a supervision decision.",
826
+ schema: z.object({
827
+ agentId: z.string().nullable(),
828
+ kind: z.enum([
829
+ "notification",
830
+ "steer",
831
+ "supervision"
832
+ ]),
833
+ aboutAgentId: z.string().nullable().optional(),
834
+ aboutSpec: z.string().nullable().optional(),
835
+ outcome: z.string().nullable().optional(),
836
+ resultRef: z.string().nullable().optional(),
837
+ excerpt: z.string().nullable().optional(),
838
+ again: z.boolean().optional(),
839
+ text: z.string().optional()
840
+ })
841
+ });
842
+ const InboxDelivered = defineEvent({
843
+ type: "inbox.delivered",
844
+ durable: true,
845
+ version: 1,
846
+ schema: z.object({
847
+ agentId: z.string().nullable(),
848
+ seqs: z.array(z.number().int()),
849
+ as: z.enum([
850
+ "steer",
851
+ "turn",
852
+ "prompt"
853
+ ])
854
+ })
855
+ });
856
+ const InboxDropped = defineEvent({
857
+ type: "inbox.dropped",
858
+ durable: true,
859
+ version: 1,
860
+ schema: z.object({
861
+ agentId: z.string().nullable(),
862
+ seqs: z.array(z.number().int()),
863
+ reason: z.string()
864
+ })
865
+ });
866
+ const BudgetDenied = defineEvent({
867
+ type: "budget.denied",
868
+ durable: true,
869
+ version: 1,
870
+ schema: z.object({
871
+ agentId: z.string().nullable(),
872
+ dimension: z.enum(["spawnDepth", "maxAgents"]),
873
+ remaining: z.number().int()
874
+ })
875
+ });
876
+ const AgentAdmissionQueued = defineEvent({
877
+ type: "agent.admission_queued",
878
+ durable: true,
879
+ version: 1,
880
+ description: "No free provisioning slot was available, so the fork is held instead of run immediately. Only emitted when a real wait happens — the common uncontended case emits nothing, to keep this a signal for genuinely stuck spawns, not noise on every spawn.",
881
+ schema: z.object({
882
+ agentId: z.string().nullable(),
883
+ capacity: z.number().int()
884
+ })
885
+ });
886
+ const AgentAdmissionGranted = defineEvent({
887
+ type: "agent.admission_granted",
888
+ durable: true,
889
+ version: 1,
890
+ description: "A held provisioning request got its slot and is proceeding.",
891
+ schema: z.object({ agentId: z.string().nullable() })
892
+ });
893
+ const AgentAdmissionTimeout = defineEvent({
894
+ type: "agent.admission_timeout",
895
+ durable: true,
896
+ version: 1,
897
+ description: "A held provisioning request never got a slot within the bound and failed loudly instead of hanging silently.",
898
+ schema: z.object({
899
+ agentId: z.string().nullable(),
900
+ waitedMs: z.number().int()
901
+ })
902
+ });
903
+ const AgentTurnFailed = defineEvent({
904
+ type: "agent.turn_failed",
905
+ durable: true,
906
+ version: 1,
907
+ description: "A turn concluded in failure -- recorded before the failure-policy decision (settle, auto-retry, or hold) is made, so the circuit breaker's consecutive-failure count is accurate regardless of what's decided next.",
908
+ schema: z.object({
909
+ agentId: z.string().nullable(),
910
+ error: z.string(),
911
+ consecutiveFailures: z.number().int()
912
+ })
913
+ });
914
+ const AgentTurnInterrupted = defineEvent({
915
+ type: "agent.turn_interrupted",
916
+ durable: true,
917
+ version: 1,
918
+ description: "alineod found this agent still `running` on boot — its turn died with the previous process, mid-stream, with no SDK around to report it. Recorded before the catch-up poll that follows (`rehydrate.ts`'s `wasRunning` checks), so a turn a crash interrupted carries an audit trail distinct from one that ran straight through, whatever catch-up later finds. Named under `agent`, not `turn`: `turn.*` is reserved for events the harness itself reports, and the harness has nothing to report here — the same reasoning that renamed `turn.failed` to `agent.turn_failed`.",
919
+ schema: z.object({ agentId: z.string().nullable() })
920
+ });
921
+ const AgentSupervisionNeeded = defineEvent({
922
+ type: "agent.supervision_needed",
923
+ durable: true,
924
+ version: 1,
925
+ description: "The agent is held (state: blocked) awaiting an operator decision: POST .../prompt to retry (optionally with corrective text), POST .../stop to give up.",
926
+ schema: z.object({
927
+ agentId: z.string().nullable(),
928
+ reason: z.enum([
929
+ "ask",
930
+ "retries-exhausted",
931
+ "circuit-tripped"
932
+ ]),
933
+ error: z.string()
934
+ })
935
+ });
936
+ //#endregion
937
+ //#region src/agent-spec.ts
938
+ /**
939
+ * `AgentSpec` — the JSON an agent is defined by.
940
+ *
941
+ * Both the documented `interface` and the `AgentSpecSchema` that validates it are kept by
942
+ * hand, deliberately: the interface carries doc comments that `z.infer<>` would erase, and
943
+ * they are what a reader sees on hover. `agent-spec.test.ts` asserts at the type level that
944
+ * the two cannot drift apart, which buys the safety of a single source without the DX loss.
945
+ *
946
+ * `validateAgentSpec()` and `AgentSpecValidationError` stay in `@alineo-labs/agent` — they
947
+ * are behaviour, and this package has none.
948
+ *
949
+ * Moved here from `@alineo-labs/agent` so that `apps/alineod` can stop modelling it as
950
+ * `z.record(z.unknown())` and emit a real `AgentSpec` into its OpenAPI spec.
951
+ */
952
+ /** Renders an arbitrary invalid field value for an error message without risking "[object Object]". */
953
+ function describeValue(value) {
954
+ if (typeof value === "string") return value;
955
+ try {
956
+ const json = JSON.stringify(value);
957
+ if (json !== void 0) return json;
958
+ } catch {}
959
+ return typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : String(value);
960
+ }
961
+ /**
962
+ * Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
963
+ * generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
964
+ * full field-level JSDoc — TypeScript doesn't propagate comments through generic type inference,
965
+ * and that documentation is load-bearing (it's what IDE hover/autocomplete shows spec authors).
966
+ * If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
967
+ * here too — `packages/agent/test/schema.test.ts` is the drift check.
968
+ */
969
+ const CredentialEnvBindingSchema = z$1.object({
970
+ credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
971
+ host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
972
+ pathPrefix: z$1.string().optional(),
973
+ injection: z$1.union([z$1.object({
974
+ type: z$1.literal("header"),
975
+ name: z$1.string()
976
+ }), z$1.object({
977
+ type: z$1.literal("substitution"),
978
+ placeholder: z$1.string(),
979
+ in: z$1.array(z$1.enum([
980
+ "path",
981
+ "query",
982
+ "header",
983
+ "body"
984
+ ])).min(1)
985
+ })]),
986
+ approval: z$1.literal("hold").optional()
987
+ }).loose();
988
+ const SetupStepSchema = z$1.object({
989
+ name: z$1.string({ error: "Each setup step must have a 'name' string" }),
990
+ run: z$1.string({ error: "Each setup step must have a 'run' string" }),
991
+ cwd: z$1.string().optional()
992
+ }).loose();
993
+ const PermissionActionSchema = z$1.enum([
994
+ "allow",
995
+ "ask",
996
+ "deny",
997
+ "rate_limit",
998
+ "classify"
999
+ ]);
1000
+ const PermissionRuleSchema = z$1.object({
1001
+ tool: z$1.string({ error: "Each permission rule must have a 'tool' string" }),
1002
+ pattern: z$1.string().optional(),
1003
+ action: PermissionActionSchema,
1004
+ limit: z$1.object({
1005
+ count: z$1.number().int().positive(),
1006
+ windowMs: z$1.number().int().positive()
1007
+ }).optional()
1008
+ }).loose();
1009
+ const PermissionPolicySchema = z$1.object({
1010
+ default: PermissionActionSchema.optional(),
1011
+ rules: z$1.array(PermissionRuleSchema).optional(),
1012
+ disabledTools: z$1.array(z$1.string()).optional(),
1013
+ restrictToTools: z$1.array(z$1.string()).optional()
1014
+ }).loose();
1015
+ const PermissionsSchema = z$1.union([z$1.enum([
1016
+ "auto",
1017
+ "ask",
1018
+ "readonly"
1019
+ ]), PermissionPolicySchema]);
1020
+ const nonNegativeIntSpecField = (fieldName) => z$1.number({ error: `Agent spec '${fieldName}' must be a non-negative integer if set` }).int(`Agent spec '${fieldName}' must be a non-negative integer if set`).nonnegative(`Agent spec '${fieldName}' must be a non-negative integer if set`).optional();
1021
+ const AgentSpecSchema = z$1.object({
1022
+ $schema: z$1.string().optional(),
1023
+ name: z$1.string({ error: (issue) => issue.input === void 0 ? "Agent spec must have a 'name' string" : "Agent spec 'name' must be a string" }).min(1, "Agent spec must have a 'name' string"),
1024
+ title: z$1.string().optional(),
1025
+ description: z$1.string().optional(),
1026
+ author: z$1.string().optional(),
1027
+ categories: z$1.array(z$1.string()).optional(),
1028
+ harness: z$1.literal("pi", { error: (issue) => issue.input === void 0 ? "Agent spec must have a 'harness' field. Supported values: pi" : `Unsupported harness: '${describeValue(issue.input)}'. Supported values: pi` }),
1029
+ harnessVersion: z$1.string().optional(),
1030
+ provider: z$1.string().optional(),
1031
+ model: z$1.string({ error: (issue) => issue.input === void 0 ? "Agent spec must have a 'model' string — name the model this agent runs on" : "Agent spec 'model' must be a string" }).min(1, "Agent spec must have a 'model' string — name the model this agent runs on"),
1032
+ packages: z$1.array(z$1.string()).optional(),
1033
+ env: z$1.record(z$1.string(), z$1.union([z$1.string(), CredentialEnvBindingSchema])).optional(),
1034
+ resources: z$1.object({
1035
+ cpu: z$1.string(),
1036
+ memory: z$1.string(),
1037
+ gpu: z$1.string().optional()
1038
+ }).optional(),
1039
+ metadata: z$1.record(z$1.string(), z$1.string()).optional(),
1040
+ registryDependencies: z$1.array(z$1.string()).optional(),
1041
+ setup: z$1.array(SetupStepSchema).optional(),
1042
+ spawnDepth: nonNegativeIntSpecField("spawnDepth"),
1043
+ maxAgents: nonNegativeIntSpecField("maxAgents"),
1044
+ teamId: z$1.string().optional(),
1045
+ resourceId: z$1.string().optional(),
1046
+ permissions: PermissionsSchema.optional(),
1047
+ onFailure: z$1.enum([
1048
+ "ask",
1049
+ "retry",
1050
+ "fail"
1051
+ ]).optional(),
1052
+ maxRetries: nonNegativeIntSpecField("maxRetries"),
1053
+ maxConsecutiveFailures: nonNegativeIntSpecField("maxConsecutiveFailures"),
1054
+ checkpoint: z$1.boolean().optional()
1055
+ }).loose();
1056
+ //#endregion
1057
+ export { agent_exports as a, defineEvent as c, SUBJECTS as d, VERBS as f, parseName as h, harness_exports as i, durableEvents as l, isVerb as m, alineod_exports as n, sandbox_exports as o, isSubject as p, workflow_exports as r, allEvents as s, AgentSpecSchema as t, getEvent as u };