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

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 (37) hide show
  1. package/dist/agent/session.d.ts +3 -0
  2. package/dist/agent/session.js +10 -0
  3. package/dist/agent/workflow/prompt.js +1 -1
  4. package/dist/agent/workflow/tool.js +1 -1
  5. package/dist/capabilities/background/manager.d.ts +10 -1
  6. package/dist/capabilities/background/manager.js +20 -2
  7. package/dist/capabilities/background/tools.js +32 -6
  8. package/dist/events/events.d.ts +12 -2
  9. package/dist/events/events.js +1 -0
  10. package/dist/events/projection.js +3 -0
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +1 -0
  13. package/dist/loop/turn-step.js +13 -0
  14. package/dist/scope/tokens.d.ts +16 -0
  15. package/dist/scope/tokens.js +2 -0
  16. package/dist/telemetry/appender.d.ts +43 -0
  17. package/dist/telemetry/appender.js +46 -0
  18. package/dist/telemetry/events.d.ts +142 -0
  19. package/dist/telemetry/events.js +141 -0
  20. package/dist/telemetry/index.d.ts +10 -0
  21. package/dist/telemetry/index.js +6 -0
  22. package/dist/telemetry/projection.d.ts +23 -0
  23. package/dist/telemetry/projection.js +185 -0
  24. package/dist/telemetry/redact.d.ts +20 -0
  25. package/dist/telemetry/redact.js +40 -0
  26. package/dist/telemetry/service.d.ts +49 -0
  27. package/dist/telemetry/service.js +137 -0
  28. package/dist/tracing/bridge.d.ts +9 -1
  29. package/dist/tracing/bridge.js +281 -77
  30. package/dist/tracing/index.d.ts +2 -2
  31. package/dist/tracing/otel.d.ts +28 -1
  32. package/dist/tracing/otel.js +127 -17
  33. package/dist/tracing/processor.d.ts +22 -0
  34. package/dist/tracing/processor.js +2 -0
  35. package/dist/tracing/spans.d.ts +54 -0
  36. package/dist/tracing/spans.js +5 -0
  37. package/package.json +5 -1
@@ -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;
@@ -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.
@@ -103,6 +105,13 @@ export class Session {
103
105
  this.events = this.eventPublisher;
104
106
  this.tracing = scope.get(T.Tracing);
105
107
  this.unsubscribeTracing = this.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, this.tracing);
108
+ // Product telemetry rides the same stream. One subscription per session; the projection
109
+ // tells sub-agents apart by address. `resumed` is the one fact the stream cannot tell.
110
+ const telemetry = scope.get(T.Telemetry);
111
+ this.unsubscribeTelemetry =
112
+ telemetry === undefined
113
+ ? undefined
114
+ : subscribeTelemetryProjection(this.events, telemetry.withContext({ session_id: id }), { resumed: opts.resumed === true });
106
115
  this.responder = scope.get(T.Responder);
107
116
  this.steer = scope.require(T.Steer);
108
117
  // Every enqueue — user steer/follow-up, cron fire, background settle — surfaces on the
@@ -741,6 +750,7 @@ export class Session {
741
750
  this.isOpen = false;
742
751
  this.systemPromptContexts.clear();
743
752
  this.unsubscribeTracing?.();
753
+ this.unsubscribeTelemetry?.();
744
754
  this.openedCapabilities = [];
745
755
  try {
746
756
  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;
@@ -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"),
@@ -0,0 +1,43 @@
1
+ import type { TelemetryPrimitive } from "./events.ts";
2
+ /** One event on the wire: name + merged (context ⊕ payload) properties + service clock. */
3
+ export interface TelemetryEvent {
4
+ readonly name: string;
5
+ readonly properties: Readonly<Record<string, TelemetryPrimitive>>;
6
+ /** Epoch millis from the service clock. */
7
+ readonly timestamp: number;
8
+ }
9
+ /**
10
+ * Where events go. Plain objects, not scoped services: the service holds a list and fans out.
11
+ *
12
+ * Contract: `track` is synchronous and must not throw (the service isolates a throw, but an
13
+ * appender that relies on that is a bug). Anything async — batching, HTTP — belongs in `flush`
14
+ * and `shutdown`. `shutdown` drains; after it `track` may drop.
15
+ */
16
+ export interface TelemetryAppender {
17
+ track(event: TelemetryEvent): void;
18
+ flush(): Promise<void>;
19
+ shutdown(): Promise<void>;
20
+ }
21
+ /** The default. A service with only this attached costs one array iteration per `track`. */
22
+ export declare const nullTelemetryAppender: TelemetryAppender;
23
+ export interface ConsoleAppenderOptions {
24
+ readonly write?: (line: string) => void;
25
+ }
26
+ /** Dev echo: one line per event. Does not redact — it is for the developer's own terminal. */
27
+ export declare class ConsoleAppender implements TelemetryAppender {
28
+ private readonly write;
29
+ constructor(options?: ConsoleAppenderOptions);
30
+ track(event: TelemetryEvent): void;
31
+ flush(): Promise<void>;
32
+ shutdown(): Promise<void>;
33
+ }
34
+ /** Test seam and buffer: keeps every event it sees. */
35
+ export declare class MemoryAppender implements TelemetryAppender {
36
+ readonly events: TelemetryEvent[];
37
+ flushCount: number;
38
+ shutdownCount: number;
39
+ track(event: TelemetryEvent): void;
40
+ flush(): Promise<void>;
41
+ shutdown(): Promise<void>;
42
+ }
43
+ //# sourceMappingURL=appender.d.ts.map
@@ -0,0 +1,46 @@
1
+ /** The default. A service with only this attached costs one array iteration per `track`. */
2
+ export const nullTelemetryAppender = Object.freeze({
3
+ track() {
4
+ /* no-op */
5
+ },
6
+ flush() {
7
+ return Promise.resolve();
8
+ },
9
+ shutdown() {
10
+ return Promise.resolve();
11
+ },
12
+ });
13
+ /** Dev echo: one line per event. Does not redact — it is for the developer's own terminal. */
14
+ export class ConsoleAppender {
15
+ write;
16
+ constructor(options = {}) {
17
+ this.write = options.write ?? ((line) => console.error(line));
18
+ }
19
+ track(event) {
20
+ this.write(`[telemetry] ${event.name} ${JSON.stringify(event.properties)}`);
21
+ }
22
+ flush() {
23
+ return Promise.resolve();
24
+ }
25
+ shutdown() {
26
+ return Promise.resolve();
27
+ }
28
+ }
29
+ /** Test seam and buffer: keeps every event it sees. */
30
+ export class MemoryAppender {
31
+ events = [];
32
+ flushCount = 0;
33
+ shutdownCount = 0;
34
+ track(event) {
35
+ this.events.push(event);
36
+ }
37
+ flush() {
38
+ this.flushCount += 1;
39
+ return Promise.resolve();
40
+ }
41
+ shutdown() {
42
+ this.shutdownCount += 1;
43
+ return Promise.resolve();
44
+ }
45
+ }
46
+ //# sourceMappingURL=appender.js.map
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Telemetry event registry — the single source of truth for what the framework counts.
3
+ *
4
+ * Every event is declared once, with a payload interface AND a description for every property.
5
+ * Two type-level devices keep the registry from rotting:
6
+ *
7
+ * - `properties: { [K in keyof P]-?: string }` — a payload property without a description does
8
+ * not compile. Documentation is part of the type.
9
+ * - `Exact<Expected, Actual>` on `track()` — an extra property at the call site does not compile.
10
+ * TypeScript's structural subtyping would otherwise let "one more field" through, and that is
11
+ * precisely how user data leaks into analytics.
12
+ *
13
+ * Red lines (see docs/telemetry.md §2): properties are counts, durations, enums and framework-owned
14
+ * ids. Never prompts, tool args/results, paths, urls, model output. `session_id` / `address` /
15
+ * `agent` are CONTEXT — stamped by the service, never passed at a call site.
16
+ */
17
+ export type TelemetryPrimitive = string | number | boolean | null;
18
+ /** A payload: primitives only; `undefined` means "absent" and is dropped before fan-out. */
19
+ export type TelemetryProperties = Record<string, TelemetryPrimitive | undefined>;
20
+ /** Where the event's identity comes from. `session` events get `session_id` from context. */
21
+ export type TelemetryEventScope = "session" | "global";
22
+ /** Property names reserved for context. The registry rejects them as payload keys. */
23
+ export declare const RESERVED_TELEMETRY_KEYS: readonly string[];
24
+ /** Property names that are a content leak by construction. The registry test rejects them. */
25
+ export declare const FORBIDDEN_TELEMETRY_KEYS: readonly string[];
26
+ export interface TelemetryEventDefinition<P extends TelemetryProperties = TelemetryProperties> {
27
+ readonly owner: string;
28
+ readonly comment: string;
29
+ readonly scope: TelemetryEventScope;
30
+ /** One human-readable line per payload property; `-?` makes optional properties mandatory here. */
31
+ readonly properties: {
32
+ readonly [K in keyof P]-?: string;
33
+ };
34
+ /** Phantom carrier for the payload type; never set at runtime. */
35
+ readonly payload?: P;
36
+ }
37
+ export interface TelemetryEventSpec<P extends TelemetryProperties> {
38
+ readonly owner: string;
39
+ readonly comment: string;
40
+ readonly properties: {
41
+ readonly [K in keyof P]-?: string;
42
+ };
43
+ }
44
+ /** A context-free event (a product-level "app opened", say). */
45
+ export declare function defineEvent<P extends TelemetryProperties>(spec: TelemetryEventSpec<P>): TelemetryEventDefinition<P>;
46
+ /** An event that belongs to a session: `session_id` arrives from context, never from the payload. */
47
+ export declare function defineSessionEvent<P extends TelemetryProperties>(spec: TelemetryEventSpec<P>): TelemetryEventDefinition<P>;
48
+ export type TelemetryRegistry = Readonly<Record<string, TelemetryEventDefinition>>;
49
+ export type PayloadOf<D> = D extends TelemetryEventDefinition<infer P> ? P : never;
50
+ /**
51
+ * Exact-match check: `Actual` must be assignable to `Expected` AND carry no key `Expected` lacks.
52
+ * Resolves to `never` on violation, which makes the `track()` argument uninhabitable — a compile
53
+ * error at the call site rather than a silently wider payload.
54
+ */
55
+ export type Exact<Expected, Actual> = Actual extends Expected ? (Exclude<keyof Actual, keyof Expected> extends never ? Actual : never) : never;
56
+ export type SessionStartedEvent = {
57
+ /** `true` when the session was reopened from a store rather than created. */
58
+ resumed: boolean;
59
+ };
60
+ export type TurnStartedEvent = {
61
+ turn_id: string;
62
+ /** `PromptOrigin.kind` (`user`, `user_follow_up`, `cron_job`, …) or `unknown`. */
63
+ origin: string;
64
+ };
65
+ export type TurnFinishedEvent = {
66
+ turn_id: string;
67
+ reason: "completed" | "cancelled" | "failed";
68
+ duration_ms: number;
69
+ step_count: number;
70
+ tool_call_count: number;
71
+ input_tokens: number;
72
+ output_tokens: number;
73
+ cache_read_tokens: number;
74
+ cache_write_tokens: number;
75
+ /** Model id of the last assistant message in the turn; `null` when no model answered. */
76
+ model: string | null;
77
+ };
78
+ export type ToolCallEvent = {
79
+ turn_id: string | null;
80
+ tool_name: string;
81
+ outcome: "success" | "error";
82
+ duration_ms: number;
83
+ };
84
+ export type ToolSuspendedEvent = {
85
+ turn_id: string | null;
86
+ tool_name: string;
87
+ /** Whether the suspension carried an input request (approval / question) for the host. */
88
+ has_request: boolean;
89
+ };
90
+ export type StepRetryEvent = {
91
+ turn_id: string;
92
+ attempt: number;
93
+ max_attempts: number;
94
+ delay_ms: number;
95
+ /** Short, enum-ish retry reason (first 64 chars), or `null`. */
96
+ reason: string | null;
97
+ };
98
+ export type SubagentSpawnedEvent = {
99
+ /** Sub-agent profile name (`coder`, `explore`, …). */
100
+ agent_name: string;
101
+ /** Nesting depth: number of address segments below the root agent. */
102
+ depth: number;
103
+ };
104
+ export type CompactionEvent = {
105
+ before_tokens: number;
106
+ after_tokens: number;
107
+ compacted_count: number;
108
+ };
109
+ export type GuardrailBlockedEvent = {
110
+ stage: "input" | "output" | "tool_input" | "tool_output";
111
+ guardrail: string;
112
+ };
113
+ export type SkillActivatedEvent = {
114
+ skill_name: string;
115
+ trigger: "user-slash" | "model-tool" | "nested-skill";
116
+ };
117
+ export type SteerQueuedEvent = {
118
+ channel: "steering" | "follow_up";
119
+ /** `PromptOrigin.kind` of the queued message. */
120
+ origin: string;
121
+ };
122
+ export type TurnErrorEvent = {
123
+ turn_id: string | null;
124
+ /** Error text after redaction, capped at 200 chars. */
125
+ message: string;
126
+ };
127
+ export declare const FRAMEWORK_TELEMETRY_EVENTS: {
128
+ readonly session_started: TelemetryEventDefinition<SessionStartedEvent>;
129
+ readonly turn_started: TelemetryEventDefinition<TurnStartedEvent>;
130
+ readonly turn_finished: TelemetryEventDefinition<TurnFinishedEvent>;
131
+ readonly tool_call: TelemetryEventDefinition<ToolCallEvent>;
132
+ readonly tool_suspended: TelemetryEventDefinition<ToolSuspendedEvent>;
133
+ readonly step_retry: TelemetryEventDefinition<StepRetryEvent>;
134
+ readonly subagent_spawned: TelemetryEventDefinition<SubagentSpawnedEvent>;
135
+ readonly compaction: TelemetryEventDefinition<CompactionEvent>;
136
+ readonly guardrail_blocked: TelemetryEventDefinition<GuardrailBlockedEvent>;
137
+ readonly skill_activated: TelemetryEventDefinition<SkillActivatedEvent>;
138
+ readonly steer_queued: TelemetryEventDefinition<SteerQueuedEvent>;
139
+ readonly turn_error: TelemetryEventDefinition<TurnErrorEvent>;
140
+ };
141
+ export type FrameworkTelemetryEvents = typeof FRAMEWORK_TELEMETRY_EVENTS;
142
+ //# sourceMappingURL=events.d.ts.map