operon-agents-core 0.1.0-alpha.4 → 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/agent/runner.js +29 -6
  2. package/dist/agent/session.d.ts +8 -1
  3. package/dist/agent/session.js +21 -4
  4. package/dist/agent/workflow/prompt.js +1 -1
  5. package/dist/agent/workflow/tool.js +1 -1
  6. package/dist/capabilities/background/manager.d.ts +10 -1
  7. package/dist/capabilities/background/manager.js +20 -2
  8. package/dist/capabilities/background/tools.js +32 -6
  9. package/dist/events/events.d.ts +12 -2
  10. package/dist/events/events.js +1 -0
  11. package/dist/events/projection.js +3 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +1 -0
  14. package/dist/loop/turn-step.js +13 -0
  15. package/dist/scope/index.d.ts +1 -1
  16. package/dist/scope/scope.d.ts +14 -3
  17. package/dist/scope/scope.js +40 -18
  18. package/dist/scope/tokens.d.ts +16 -0
  19. package/dist/scope/tokens.js +2 -0
  20. package/dist/telemetry/appender.d.ts +43 -0
  21. package/dist/telemetry/appender.js +46 -0
  22. package/dist/telemetry/events.d.ts +142 -0
  23. package/dist/telemetry/events.js +141 -0
  24. package/dist/telemetry/index.d.ts +10 -0
  25. package/dist/telemetry/index.js +6 -0
  26. package/dist/telemetry/projection.d.ts +23 -0
  27. package/dist/telemetry/projection.js +185 -0
  28. package/dist/telemetry/redact.d.ts +20 -0
  29. package/dist/telemetry/redact.js +40 -0
  30. package/dist/telemetry/service.d.ts +49 -0
  31. package/dist/telemetry/service.js +137 -0
  32. package/dist/tracing/bridge.d.ts +9 -1
  33. package/dist/tracing/bridge.js +281 -77
  34. package/dist/tracing/index.d.ts +2 -2
  35. package/dist/tracing/otel.d.ts +28 -1
  36. package/dist/tracing/otel.js +127 -17
  37. package/dist/tracing/processor.d.ts +22 -0
  38. package/dist/tracing/processor.js +2 -0
  39. package/dist/tracing/spans.d.ts +54 -0
  40. package/dist/tracing/spans.js +5 -0
  41. package/package.json +5 -1
@@ -37,7 +37,12 @@ export class Runner {
37
37
  return this.withLease(opts, async (lease) => {
38
38
  const { session, owned } = await this.acquireSession(opts, undefined, lease);
39
39
  try {
40
- return await session.withRunLock(() => this.execute(agent, input, opts, session));
40
+ return await session.withRunLock(() => {
41
+ // Cancelled while queued behind another run: leave without touching the session —
42
+ // no reconcile, no context replay, no `agent.started` on the log.
43
+ opts?.signal?.throwIfAborted();
44
+ return this.execute(agent, input, opts, session);
45
+ });
41
46
  }
42
47
  finally {
43
48
  if (owned)
@@ -75,9 +80,18 @@ export class Runner {
75
80
  // One-shot pull sessions emit straight to `pull` (the bus IS the iterable). For a
76
81
  // shared session, subscribe `pull` to its bus so we never replace the channel (Invariant 4).
77
82
  const { session, owned } = await this.acquireSession(opts, pull, lease);
78
- const unsub = owned ? undefined : session.events.subscribe((ev) => void pull.emit(ev));
83
+ let unsub;
79
84
  try {
80
- return await session.withRunLock(() => this.execute(agent, input, opts, session));
85
+ return await session.withRunLock(() => {
86
+ // Cancelled while queued behind another run: leave without touching the session —
87
+ // no reconcile, no context replay, no `agent.started` on the log.
88
+ opts?.signal?.throwIfAborted();
89
+ // Subscribe only now, holding the lock: subscribing while queued would hand this
90
+ // stream the tail of the run ahead of it (its inputs and answers) before its own.
91
+ if (!owned)
92
+ unsub = session.events.subscribe((ev) => void pull.emit(ev));
93
+ return this.execute(agent, input, opts, session);
94
+ });
81
95
  }
82
96
  finally {
83
97
  unsub?.();
@@ -119,6 +133,7 @@ export class Runner {
119
133
  await session.reconcileSubagents();
120
134
  try {
121
135
  return await session.withRunLock(async () => {
136
+ baseOpts?.signal?.throwIfAborted();
122
137
  const store = session.store;
123
138
  if (!store)
124
139
  throw new Error("Cannot resume an interrupted run without a durable session store.");
@@ -192,9 +207,17 @@ export class Runner {
192
207
  // A one-shot pull stream IS the session's event bus (Invariant 4); it wins over the hook's.
193
208
  if (eventsOverride !== undefined)
194
209
  scope.register(T.Events, eventsOverride, { owned: false });
195
- const capabilities = (await this.config.session?.(scope, { sessionId: opts?.sessionId })) ?? [];
196
- const session = await Session.open(scope, { capabilities });
197
- return { session, owned: true };
210
+ try {
211
+ const capabilities = (await this.config.session?.(scope, { sessionId: opts?.sessionId })) ?? [];
212
+ const session = await Session.open(scope, { capabilities });
213
+ return { session, owned: true };
214
+ }
215
+ catch (error) {
216
+ // The scope is ours: a hook or open that fails must not leave it (and whatever it already
217
+ // registered — a provision, an MCP connection) hanging off the runner's scope.
218
+ await scope.close().catch(() => undefined);
219
+ throw error;
220
+ }
198
221
  }
199
222
  /** Resolve the durable conversation owner by following committed handoffs from `main`. */
200
223
  async resolveConversationHead(session, rootAgent) {
@@ -50,6 +50,8 @@ export interface SessionOpenOptions {
50
50
  * Must be the complete log (all addresses, append order) as `readRecords()` returns it.
51
51
  */
52
52
  readonly preloadedLog?: readonly AgentRecord[];
53
+ /** Reopened from a store (vs created fresh). Only telemetry cares; the stream cannot tell. */
54
+ readonly resumed?: boolean;
53
55
  }
54
56
  /** The current owner and root conversation shard for the next user prompt. */
55
57
  export interface ConversationHead {
@@ -146,6 +148,7 @@ export declare class Session implements SessionPort {
146
148
  readonly logger: Logger;
147
149
  private readonly tracing?;
148
150
  private readonly unsubscribeTracing?;
151
+ private readonly unsubscribeTelemetry?;
149
152
  private readonly allCapabilities;
150
153
  private readonly systemPromptContexts;
151
154
  private readonly liveContexts;
@@ -160,6 +163,8 @@ export declare class Session implements SessionPort {
160
163
  private thinkingOverride?;
161
164
  private openedCapabilities;
162
165
  private isOpen;
166
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
167
+ private closing;
163
168
  private runChain;
164
169
  private readonly pendingDiagnostics;
165
170
  private lastContextBreakdown?;
@@ -340,9 +345,11 @@ export declare class Session implements SessionPort {
340
345
  /**
341
346
  * Close the session: flush telemetry and the store, then close the scope — which disposes
342
347
  * every capability provision in reverse order (each under a deadline) and finally the
343
- * session's own infrastructure. Idempotent.
348
+ * session's own infrastructure. Every call returns the SAME promise, so a second caller
349
+ * (or the facade above) waits for the teardown instead of returning while it is still running.
344
350
  */
345
351
  close(): Promise<void>;
352
+ private runClose;
346
353
  /** Public URL for a port inside the machine, or undefined when the backend can't expose one. */
347
354
  resolveExposedPort(port: number): Promise<string | undefined>;
348
355
  }
@@ -7,6 +7,7 @@ import { joinAddress, ListenerSink, SessionEventPublisher } from "../events/inde
7
7
  import { envLogger, noopLogger } from "../logging/index.js";
8
8
  import { DEFAULT_ADDRESS } from "../store/index.js";
9
9
  import { eventSinkTracingBridge } from "../tracing/index.js";
10
+ import { subscribeTelemetryProjection } from "../telemetry/projection.js";
10
11
  import { ConversationContext } from "../loop/context.js";
11
12
  import { readLog } from "../capabilities/capability-state.js";
12
13
  import { SteerBus, steerOriginToPromptOrigin } from "../loop/steer.js";
@@ -62,6 +63,7 @@ export class Session {
62
63
  logger;
63
64
  tracing;
64
65
  unsubscribeTracing;
66
+ unsubscribeTelemetry;
65
67
  allCapabilities;
66
68
  // Runtime prompt data is live-Session state, not Agent state: machine identity + cwd isolate
67
69
  // root/subagent/worktree frames, and the date stays fixed for the Session's lifetime.
@@ -85,6 +87,8 @@ export class Session {
85
87
  thinkingOverride;
86
88
  openedCapabilities = [];
87
89
  isOpen = false;
90
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
91
+ closing;
88
92
  runChain = Promise.resolve();
89
93
  pendingDiagnostics = [];
90
94
  // Most-recent per-turn context-window breakdown, stamped by the Runner at each turn boundary.
@@ -103,6 +107,13 @@ export class Session {
103
107
  this.events = this.eventPublisher;
104
108
  this.tracing = scope.get(T.Tracing);
105
109
  this.unsubscribeTracing = this.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, this.tracing);
110
+ // Product telemetry rides the same stream. One subscription per session; the projection
111
+ // tells sub-agents apart by address. `resumed` is the one fact the stream cannot tell.
112
+ const telemetry = scope.get(T.Telemetry);
113
+ this.unsubscribeTelemetry =
114
+ telemetry === undefined
115
+ ? undefined
116
+ : subscribeTelemetryProjection(this.events, telemetry.withContext({ session_id: id }), { resumed: opts.resumed === true });
106
117
  this.responder = scope.get(T.Responder);
107
118
  this.steer = scope.require(T.Steer);
108
119
  // Every enqueue — user steer/follow-up, cron fire, background settle — surfaces on the
@@ -733,14 +744,20 @@ export class Session {
733
744
  /**
734
745
  * Close the session: flush telemetry and the store, then close the scope — which disposes
735
746
  * every capability provision in reverse order (each under a deadline) and finally the
736
- * session's own infrastructure. Idempotent.
747
+ * session's own infrastructure. Every call returns the SAME promise, so a second caller
748
+ * (or the facade above) waits for the teardown instead of returning while it is still running.
737
749
  */
738
- async close() {
739
- if (!this.isOpen)
740
- return;
750
+ close() {
751
+ if (this.closing !== undefined)
752
+ return this.closing;
753
+ this.closing = this.isOpen ? this.runClose() : Promise.resolve();
754
+ return this.closing;
755
+ }
756
+ async runClose() {
741
757
  this.isOpen = false;
742
758
  this.systemPromptContexts.clear();
743
759
  this.unsubscribeTracing?.();
760
+ this.unsubscribeTelemetry?.();
744
761
  this.openedCapabilities = [];
745
762
  try {
746
763
  await withTimeout(Promise.resolve(this.tracing?.forceFlush()), CLOSE_TIMEOUT_MS);
@@ -6,7 +6,7 @@
6
6
  */
7
7
  export function workflowPrompt(availableAgents) {
8
8
  const agentList = availableAgents.length > 0 ? availableAgents.join(", ") : "(none configured)";
9
- return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately and poll progress/result with BackgroundOutput. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
9
+ return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately; a completion notice arrives on its own, and BackgroundOutput(task_id, block=false) reads progress/result meanwhile. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
10
10
 
11
11
  A workflow structures work across many agents — to be comprehensive (decompose and cover in parallel), to be confident (independent perspectives and adversarial checks before committing), or to take on scale one context can't hold (migrations, audits, broad sweeps). The script is where you encode that structure: what fans out, what verifies, what synthesizes.
12
12
 
@@ -149,7 +149,7 @@ export function buildWorkflowTool(spawner, parent) {
149
149
  args: z.unknown().optional().describe("Value exposed to the script as the global `args` (pass real JSON, not a stringified value)."),
150
150
  resumeFromRunId: z.string().optional().describe("Resume a prior run; unchanged agent() calls return cached results instantly."),
151
151
  tokenBudget: z.number().optional().describe("Output-token target for the run; enables budget.remaining()-guarded loops in the script."),
152
- run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). Poll progress + result with BackgroundOutput. Requires a BackgroundManager."),
152
+ run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). A completion notice arrives on its own; BackgroundOutput(task_id, block=false) reads progress or the result meanwhile. Requires a BackgroundManager."),
153
153
  });
154
154
  return defineTool({
155
155
  name: "Workflow",
@@ -145,7 +145,16 @@ export declare class BackgroundManager implements BackgroundSpawner {
145
145
  suppressTerminalNotification(taskId: string): Promise<void>;
146
146
  stop(taskId: string, reason?: string): Promise<BackgroundTaskInfo | undefined>;
147
147
  stopAll(reason?: string): Promise<readonly BackgroundTaskInfo[]>;
148
- wait(taskId: string, timeoutMs?: number): Promise<BackgroundTaskInfo | undefined>;
148
+ /**
149
+ * Settle when the task reaches a terminal status, the timeout elapses, or `signal` aborts —
150
+ * whichever comes first. Returns the task's status either way; the caller compares it against
151
+ * the terminal set to tell "it finished" from "I stopped waiting".
152
+ *
153
+ * `signal` matters because the timeout can be up to an hour: without it a blocking waiter
154
+ * outlives the turn that started it, and the loop's post-abort grace window has to shoot the
155
+ * tool down with a synthetic error instead of letting it return cleanly.
156
+ */
157
+ wait(taskId: string, timeoutMs?: number, signal?: AbortSignal): Promise<BackgroundTaskInfo | undefined>;
149
158
  private settleTask;
150
159
  private resolveWaiters;
151
160
  private fireTerminalEffects;
@@ -835,15 +835,25 @@ export class BackgroundManager {
835
835
  const results = await Promise.all(ids.map((id) => this.stop(id, reason)));
836
836
  return results.filter((info) => info !== undefined);
837
837
  }
838
- async wait(taskId, timeoutMs = 30_000) {
838
+ /**
839
+ * Settle when the task reaches a terminal status, the timeout elapses, or `signal` aborts —
840
+ * whichever comes first. Returns the task's status either way; the caller compares it against
841
+ * the terminal set to tell "it finished" from "I stopped waiting".
842
+ *
843
+ * `signal` matters because the timeout can be up to an hour: without it a blocking waiter
844
+ * outlives the turn that started it, and the loop's post-abort grace window has to shoot the
845
+ * tool down with a synthetic error instead of letting it return cleanly.
846
+ */
847
+ async wait(taskId, timeoutMs = 30_000, signal) {
839
848
  const entry = this.tasks.get(taskId);
840
849
  if (!entry)
841
850
  return undefined;
842
- if (TERMINAL_STATUSES.has(entry.status)) {
851
+ if (TERMINAL_STATUSES.has(entry.status) || signal?.aborted === true) {
843
852
  return this.toInfo(entry);
844
853
  }
845
854
  let terminalWaiter;
846
855
  let timeout;
856
+ let onAbort;
847
857
  try {
848
858
  await Promise.race([
849
859
  new Promise((resolve) => {
@@ -853,11 +863,19 @@ export class BackgroundManager {
853
863
  new Promise((resolve) => {
854
864
  timeout = setTimeout(resolve, timeoutMs);
855
865
  }),
866
+ new Promise((resolve) => {
867
+ if (signal === undefined)
868
+ return; // never settles — leaves the race to the other two
869
+ onAbort = resolve;
870
+ signal.addEventListener("abort", onAbort, { once: true });
871
+ }),
856
872
  ]);
857
873
  }
858
874
  finally {
859
875
  if (timeout !== undefined)
860
876
  clearTimeout(timeout);
877
+ if (onAbort !== undefined)
878
+ signal?.removeEventListener("abort", onAbort);
861
879
  if (terminalWaiter !== undefined) {
862
880
  const index = entry.waiters.indexOf(terminalWaiter);
863
881
  if (index !== -1)
@@ -79,28 +79,54 @@ export function backgroundOutputTool(manager) {
79
79
  name: "BackgroundOutput",
80
80
  description: [
81
81
  "Read a background AGENT's or WORKFLOW's result, taken from where it already lives — a sub-agent's own conversation, a workflow run's journal. Works while it is still running: you get whatever it has produced so far.",
82
- "- You do NOT need to poll. Every background task sends a completion notification on its own; call this when you want the answer before that arrives, or after a notification tells you the agent is done.",
82
+ "- You do NOT need to poll, and you do NOT need to stay in the turn. Every background task notifies on its own when it settles — including minutes after the turn that started it has ended, which wakes a new turn by itself. So ending your turn is never how you lose a result: it is the normal way to wait for one. Call this when you want the answer before that notification arrives, or after one tells you the task is done.",
83
83
  "- For a background BASH command this returns status only, plus output_path. The command's output is a file on the machine — Read that path instead, which also gives you offset/limit paging over a large log.",
84
84
  "- For a background WORKFLOW this returns the run's story from its journal: each phase, each agent's result, any failure, and the final outcome — for a running one, everything so far.",
85
85
  "- For a background question this returns the user's answer in full — the place to read the rest when the completion notification truncated it.",
86
86
  "- For a terminal task the metadata explains why it ended: status=timed_out when aborted by its deadline, and reason when it was explicitly stopped; terminal_reason is a categorical label (timed_out | stopped | failed). A task that ended on its own emits none of these.",
87
- "- block=true waits for completion (optional timeout in seconds). Rarely needed — the notification already wakes you.",
87
+ "- block=true waits for completion (optional timeout in seconds). It costs you the whole turn — the user cannot say anything to you until the task settles or the timeout expires, so a long block locks them out. Justified only when all three hold: the task settles in seconds, nothing and nobody else has to act first, and you have no other work to do. Otherwise read with block=false, say what you are waiting on, and end the turn.",
88
+ "- NEVER block on a task that is waiting for the user — a login/OAuth flow in a browser, a confirmation, anything whose next step is a human action. Blocking there deadlocks the two of you: the user is waiting to see what you say, and you are waiting for the thing only they can finish. End your turn instead, tell them what to do, and read the task when they say they are done.",
88
89
  ].join("\n"),
89
90
  params: z.object({
90
91
  task_id: z.string().describe("The background task ID to inspect."),
91
- block: z.boolean().default(false).describe("Wait for the task to finish before returning.").optional(),
92
- timeout: z.number().int().min(0).max(3600).default(30).describe("Max seconds to wait when block=true.").optional(),
92
+ block: z
93
+ .boolean()
94
+ .default(false)
95
+ .describe("Hold the turn until the task finishes. Leave false unless you have nothing else to do — never true for a task awaiting user action.")
96
+ .optional(),
97
+ timeout: z
98
+ .number()
99
+ .int()
100
+ .min(0)
101
+ .max(3600)
102
+ .default(30)
103
+ .describe("Max seconds to wait when block=true. The ceiling is high for the rare task worth standing guard over; it is not a suggestion. Past a few seconds the completion notification is the better instrument, so raise this deliberately, not by default.")
104
+ .optional(),
93
105
  }),
94
106
  resolve: (args) => ({
95
107
  ...globApproval("BackgroundOutput", args.task_id),
96
108
  accesses: ToolAccesses.none(),
97
109
  display: { title: `Read output of task ${args.task_id}` },
98
- run: async () => {
110
+ run: async ({ signal }) => {
99
111
  const info = manager.getTask(args.task_id);
100
112
  if (!info)
101
113
  return text(`Task not found: ${args.task_id}`, true);
114
+ // A question is answered by the user, in the conversation this turn is holding open.
115
+ // Blocking on it is a guaranteed deadlock — the answer cannot arrive until the turn
116
+ // ends, and the turn cannot end while this waits. Refuse rather than burn the timeout.
117
+ if (args.block && info.kind === "question" && !isBackgroundTaskTerminal(info.status)) {
118
+ return text([
119
+ formatTaskInfo(info),
120
+ "",
121
+ "block=true is refused for a pending question: it waits for the user, who cannot answer while this turn is held open.",
122
+ "End your turn instead — the answer arrives as a completion notification.",
123
+ ].join("\n"), true);
124
+ }
125
+ // Hand the signal down: a blocking wait can be an hour long, and without it an
126
+ // interrupted turn cannot reclaim this tool — the loop's grace window kills it with a
127
+ // synthetic error instead. With it, an abort returns the task's real status normally.
102
128
  if (args.block && !isBackgroundTaskTerminal(info.status)) {
103
- await manager.wait(args.task_id, (args.timeout ?? 30) * 1000);
129
+ await manager.wait(args.task_id, (args.timeout ?? 30) * 1000, signal);
104
130
  }
105
131
  const current = manager.getTask(args.task_id);
106
132
  if (!current)
@@ -2,6 +2,7 @@ import type { Message, TextContent, ThinkingContent, Usage } from "../protocol/i
2
2
  import type { PromptOrigin } from "../store/origin.ts";
3
3
  import type { ToolInputRequest, ToolResult, ToolUpdate } from "../tool/types.ts";
4
4
  import type { PendingRunInterrupt } from "../loop/interruption.ts";
5
+ import type { ModelSettings } from "../llm/model.ts";
5
6
  import type { SkillActivationTrigger } from "../capabilities/skills/service.ts";
6
7
  import type { SkillSource } from "../capabilities/skills/types.ts";
7
8
  /** One step of a workflow run, as it happens. Defined here because it is a WIRE shape: the
@@ -127,6 +128,15 @@ export type AgentEventBody = {
127
128
  readonly step: number;
128
129
  readonly reason: string;
129
130
  readonly message?: string;
131
+ } | {
132
+ readonly type: "model.request";
133
+ readonly turnId: string;
134
+ readonly step: number;
135
+ readonly stepId: string;
136
+ readonly system?: string;
137
+ readonly messages: readonly Message[];
138
+ readonly toolNames: readonly string[];
139
+ readonly params?: ModelSettings;
130
140
  } | {
131
141
  readonly type: "content.part";
132
142
  readonly turnId: string;
@@ -291,7 +301,7 @@ export type LifecycleEvent = Extract<AgentEventBody, {
291
301
  }>;
292
302
  /** Runtime detail that is intentionally not replayable from `events.list()`. */
293
303
  export type LiveOnlyEvent = Extract<AgentEventBody, {
294
- readonly type: "assistant.delta" | "thinking.delta" | "tool.call.delta" | "tool.progress" | "turn.step.retrying";
304
+ readonly type: "assistant.delta" | "thinking.delta" | "tool.call.delta" | "tool.progress" | "turn.step.retrying" | "model.request";
295
305
  }>;
296
306
  /** Lifecycle bodies persisted separately because they affect Projection state but are not
297
307
  * already encoded in a context/workflow/audit record. */
@@ -313,7 +323,7 @@ export type PersistedLifecycleEvent = Extract<LifecycleEvent, {
313
323
  * low-frequency lifecycle events additionally use compact `event.lifecycle` records because
314
324
  * they affect Projection state but are not encoded in messages.
315
325
  */
316
- export declare const VOLATILE_EVENT_TYPES: readonly ["assistant.delta", "thinking.delta", "tool.call.delta", "tool.progress", "turn.step.retrying"];
326
+ export declare const VOLATILE_EVENT_TYPES: readonly ["assistant.delta", "thinking.delta", "tool.call.delta", "tool.progress", "turn.step.retrying", "model.request"];
317
327
  export declare function isVolatileEventType(type: string): boolean;
318
328
  export type AgentEventListener = (event: AgentEvent) => void | Promise<void>;
319
329
  export interface EventSink {
@@ -23,6 +23,7 @@ export const VOLATILE_EVENT_TYPES = [
23
23
  "tool.call.delta",
24
24
  "tool.progress",
25
25
  "turn.step.retrying",
26
+ "model.request",
26
27
  ];
27
28
  const volatileEventTypeSet = new Set(VOLATILE_EVENT_TYPES);
28
29
  export function isVolatileEventType(type) {
@@ -217,6 +217,9 @@ export class SessionProjection {
217
217
  // step boundary.
218
218
  break;
219
219
  case "turn.step.retrying":
220
+ // Live-only observer signal (tracing): the transcript it describes is already folded
221
+ // from `message.appended`.
222
+ case "model.request":
220
223
  break;
221
224
  case "turn.step.reset": {
222
225
  const turn = state.turn;
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@ export * from "./store/index.ts";
9
9
  export * from "./logging/index.ts";
10
10
  export * from "./net/index.ts";
11
11
  export * from "./tracing/index.ts";
12
+ export * from "./telemetry/index.ts";
12
13
  export * from "./scope/index.ts";
13
14
  export * from "./agent/index.ts";
14
15
  export * from "./capabilities/index.ts";
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ export * from "./store/index.js";
8
8
  export * from "./logging/index.js";
9
9
  export * from "./net/index.js";
10
10
  export * from "./tracing/index.js";
11
+ export * from "./telemetry/index.js";
11
12
  export * from "./scope/index.js";
12
13
  export * from "./agent/index.js";
13
14
  export * from "./capabilities/index.js";
@@ -71,6 +71,19 @@ export async function executeStep(deps) {
71
71
  });
72
72
  const call = { signal: outputGuardrail?.signal ?? signal };
73
73
  deps.dispatchEvent?.({ type: "turn.step.started", turnId, step: currentStep, stepId });
74
+ // The final request, after both hooks — the only place the system prompt reaches the stream.
75
+ // `messages` is snapshotted: `request.messages` may alias the live context array, which this
76
+ // very step appends to below.
77
+ deps.dispatchEvent?.({
78
+ type: "model.request",
79
+ turnId,
80
+ step: currentStep,
81
+ stepId,
82
+ ...(request.system !== undefined ? { system: request.system } : {}),
83
+ messages: [...request.messages],
84
+ toolNames: (request.tools ?? []).map((tool) => tool.name),
85
+ ...(request.params !== undefined ? { params: request.params } : {}),
86
+ });
74
87
  let message;
75
88
  let stopReason;
76
89
  let stopTurnAfterUsage = false;
@@ -1,5 +1,5 @@
1
1
  export { Scope, ServiceUnavailableError, deadHandle, isProbeProperty } from "./scope.ts";
2
- export type { RegisterOptions, CloseOptions, ServiceUnavailableReason, Below } from "./scope.ts";
2
+ export type { RegisterOptions, CloseOptions, ServiceUnavailableReason, Below, ScopeState } from "./scope.ts";
3
3
  export { token, SCOPE_ORDER, resetTokenDeclarationsForTest } from "./token.ts";
4
4
  export type { Token, ScopeKind } from "./token.ts";
5
5
  export { T } from "./tokens.ts";
@@ -50,6 +50,7 @@ export interface CloseOptions {
50
50
  /** Where a dispose failure/timeout goes. Default: the scope's `warn`. */
51
51
  readonly onDisposeError?: (name: string, error: unknown) => void;
52
52
  }
53
+ export type ScopeState = "open" | "closing" | "closed";
53
54
  export declare class Scope<K extends ScopeKind = ScopeKind> {
54
55
  readonly kind: K;
55
56
  readonly parent: Scope | undefined;
@@ -62,11 +63,16 @@ export declare class Scope<K extends ScopeKind = ScopeKind> {
62
63
  private readonly ops;
63
64
  private readonly children;
64
65
  private readonly warn;
65
- private _closed;
66
+ /** open → closing (the one `close()` in flight) → closed. Never goes back. */
67
+ private _state;
68
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
69
+ private closing;
66
70
  constructor(kind: K, parent?: Scope, options?: {
67
71
  readonly warn?: (message: string) => void;
68
72
  });
73
+ /** Not open: closing or closed. `register`/`provide`/`child` throw from here on. */
69
74
  get closed(): boolean;
75
+ get state(): ScopeState;
70
76
  /** Open a nested scope. Tiers only go down: harness → workspace | session, workspace → session. */
71
77
  child<C extends Below<K>>(kind: C): Scope<C>;
72
78
  /** Register a built instance under a token. Duplicate names fail closed — a scope that wants
@@ -116,10 +122,15 @@ export declare class Scope<K extends ScopeKind = ScopeKind> {
116
122
  unregister<T>(tok: Token<T, K>, options?: CloseOptions): Promise<void>;
117
123
  /**
118
124
  * Tear the scope down: children first (newest first), then this scope's entries in reverse
119
- * registration order. Idempotent. Afterwards `register`/`provide`/`child` throw; `get` still
120
- * reads the parent chain. Parents are never touched.
125
+ * registration order. Every call — concurrent or later — returns the SAME promise, so a parent
126
+ * closing while a child's close is still in flight waits for that close instead of skipping it
127
+ * and pulling its own resources out from under the child's disposers. Entering `closing` stops
128
+ * pending defaults from materializing (a disposer asking for one gets "missing"), so nothing
129
+ * new can appear behind the teardown's back. Afterwards `register`/`provide`/`child` throw;
130
+ * `get` still reads the parent chain. Parents are never touched.
121
131
  */
122
132
  close(options?: CloseOptions): Promise<void>;
133
+ private runClose;
123
134
  private lookup;
124
135
  private invoke;
125
136
  private enqueueOp;
@@ -60,15 +60,22 @@ export class Scope {
60
60
  ops = new Map();
61
61
  children = new Set();
62
62
  warn;
63
- _closed = false;
63
+ /** open → closing (the one `close()` in flight) → closed. Never goes back. */
64
+ _state = "open";
65
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
66
+ closing;
64
67
  constructor(kind, parent, options = {}) {
65
68
  this.kind = kind;
66
69
  this.parent = parent;
67
70
  this.warn = options.warn ?? parent?.warn ?? ((message) => console.warn(`[scope] ${message}`));
68
71
  parent?.children.add(this);
69
72
  }
73
+ /** Not open: closing or closed. `register`/`provide`/`child` throw from here on. */
70
74
  get closed() {
71
- return this._closed;
75
+ return this._state !== "open";
76
+ }
77
+ get state() {
78
+ return this._state;
72
79
  }
73
80
  /** Open a nested scope. Tiers only go down: harness → workspace | session, workspace → session. */
74
81
  child(kind) {
@@ -222,27 +229,42 @@ export class Scope {
222
229
  }
223
230
  /**
224
231
  * Tear the scope down: children first (newest first), then this scope's entries in reverse
225
- * registration order. Idempotent. Afterwards `register`/`provide`/`child` throw; `get` still
226
- * reads the parent chain. Parents are never touched.
232
+ * registration order. Every call — concurrent or later — returns the SAME promise, so a parent
233
+ * closing while a child's close is still in flight waits for that close instead of skipping it
234
+ * and pulling its own resources out from under the child's disposers. Entering `closing` stops
235
+ * pending defaults from materializing (a disposer asking for one gets "missing"), so nothing
236
+ * new can appear behind the teardown's back. Afterwards `register`/`provide`/`child` throw;
237
+ * `get` still reads the parent chain. Parents are never touched.
227
238
  */
228
- async close(options = {}) {
229
- if (this._closed)
230
- return;
231
- this._closed = true;
232
- for (const child of [...this.children].reverse())
233
- await child.close(options);
234
- this.children.clear();
235
- for (const name of [...this.order].reverse()) {
236
- await this.unregister({ name, scope: this.kind }, options);
237
- }
239
+ close(options = {}) {
240
+ if (this.closing !== undefined)
241
+ return this.closing;
242
+ this._state = "closing";
238
243
  this.providers.clear();
239
- this.parent?.children.delete(this);
244
+ this.closing = this.runClose(options);
245
+ return this.closing;
246
+ }
247
+ async runClose(options) {
248
+ try {
249
+ for (const child of [...this.children].reverse())
250
+ await child.close(options);
251
+ this.children.clear();
252
+ for (const name of [...this.order].reverse()) {
253
+ await this.unregister({ name, scope: this.kind }, options);
254
+ }
255
+ }
256
+ finally {
257
+ this._state = "closed";
258
+ this.parent?.children.delete(this);
259
+ }
240
260
  }
241
261
  lookup(name) {
242
262
  const local = this.table.get(name);
243
263
  if (local !== undefined)
244
264
  return local;
245
- const provider = this.providers.get(name);
265
+ // Once closing, no default materializes: a disposer that first touches a lazy service
266
+ // during teardown must not create an instance the teardown snapshot will never dispose.
267
+ const provider = this._state === "open" ? this.providers.get(name) : undefined;
246
268
  if (provider !== undefined) {
247
269
  this.providers.delete(name);
248
270
  const entry = entryOf(provider.create(this), provider.options);
@@ -344,8 +366,8 @@ export class Scope {
344
366
  }
345
367
  }
346
368
  assertOpen() {
347
- if (this._closed)
348
- throw new Error(`${this.kind} scope is closed`);
369
+ if (this._state !== "open")
370
+ throw new Error(`${this.kind} scope is ${this._state}`);
349
371
  }
350
372
  assertTier(tok) {
351
373
  if (tok.scope !== this.kind) {
@@ -18,6 +18,7 @@ import type { Machine, MachineFactory } from "../tool/machine.ts";
18
18
  import type { EventPublicationMode, EventSink } from "../events/index.ts";
19
19
  import type { SessionEventPublisher } from "../events/publisher.ts";
20
20
  import type { TracingProcessor } from "../tracing/processor.ts";
21
+ import type { TelemetryService } from "../telemetry/service.ts";
21
22
  import type { McpServersHandle } from "../mcp/manager.ts";
22
23
  import type { SkillRegistry } from "../capabilities/skills/registry.ts";
23
24
  import type { McpOAuthService } from "../mcp/oauth/service.ts";
@@ -47,6 +48,21 @@ export declare const T: Readonly<{
47
48
  MachineFactory: import("./token.ts").Token<Machine | MachineFactory, "harness">;
48
49
  EventPublication: import("./token.ts").Token<EventPublicationMode, "harness">;
49
50
  Tracing: import("./token.ts").Token<TracingProcessor, "harness">;
51
+ /** Product telemetry (docs/telemetry.md). Absent = nothing is counted. */
52
+ Telemetry: import("./token.ts").Token<TelemetryService<{
53
+ readonly session_started: import("../index.ts").TelemetryEventDefinition<import("../index.ts").SessionStartedEvent>;
54
+ readonly turn_started: import("../index.ts").TelemetryEventDefinition<import("../index.ts").TurnStartedEvent>;
55
+ readonly turn_finished: import("../index.ts").TelemetryEventDefinition<import("../index.ts").TurnFinishedEvent>;
56
+ readonly tool_call: import("../index.ts").TelemetryEventDefinition<import("../index.ts").ToolCallEvent>;
57
+ readonly tool_suspended: import("../index.ts").TelemetryEventDefinition<import("../index.ts").ToolSuspendedEvent>;
58
+ readonly step_retry: import("../index.ts").TelemetryEventDefinition<import("../index.ts").StepRetryEvent>;
59
+ readonly subagent_spawned: import("../index.ts").TelemetryEventDefinition<import("../index.ts").SubagentSpawnedEvent>;
60
+ readonly compaction: import("../index.ts").TelemetryEventDefinition<import("../index.ts").CompactionEvent>;
61
+ readonly guardrail_blocked: import("../index.ts").TelemetryEventDefinition<import("../index.ts").GuardrailBlockedEvent>;
62
+ readonly skill_activated: import("../index.ts").TelemetryEventDefinition<import("../index.ts").SkillActivatedEvent>;
63
+ readonly steer_queued: import("../index.ts").TelemetryEventDefinition<import("../index.ts").SteerQueuedEvent>;
64
+ readonly turn_error: import("../index.ts").TelemetryEventDefinition<import("../index.ts").TurnErrorEvent>;
65
+ }>, "harness">;
50
66
  McpServers: import("./token.ts").Token<McpServersHandle, "workspace">;
51
67
  SkillRegistry: import("./token.ts").Token<SkillRegistry, "workspace">;
52
68
  McpOAuth: import("./token.ts").Token<McpOAuthService, "workspace">;
@@ -9,6 +9,8 @@ export const T = Object.freeze({
9
9
  MachineFactory: token("machine-factory", "harness"),
10
10
  EventPublication: token("event-publication", "harness"),
11
11
  Tracing: token("tracing", "harness"),
12
+ /** Product telemetry (docs/telemetry.md). Absent = nothing is counted. */
13
+ Telemetry: token("telemetry", "harness"),
12
14
  // ── workspace tier: one per working directory (or tenant / environment on a server) ─────
13
15
  McpServers: token("mcp", "workspace"),
14
16
  SkillRegistry: token("skill-registry", "workspace"),