@tangle-network/agent-app 0.60.247 → 0.60.249

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 (53) hide show
  1. package/dist/assistant/index.js +6 -6
  2. package/dist/chat-react/index.js +4 -4
  3. package/dist/chat-routes/index.js +19 -12
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/wire.d.ts +2 -0
  6. package/dist/chat-store/index.js +2 -2
  7. package/dist/{chunk-PYG2N2JX.js → chunk-23JUSUUB.js} +2 -2
  8. package/dist/{chunk-OXUBZ5SE.js → chunk-2HQP2CTA.js} +33 -12
  9. package/dist/chunk-2HQP2CTA.js.map +1 -0
  10. package/dist/{chunk-YHRWZZJN.js → chunk-5TSRFF5W.js} +1 -1
  11. package/dist/chunk-5TSRFF5W.js.map +1 -0
  12. package/dist/{chunk-PALGMOU3.js → chunk-5Y7Z5G3Y.js} +149 -16
  13. package/dist/chunk-5Y7Z5G3Y.js.map +1 -0
  14. package/dist/{chunk-HJ63OGYD.js → chunk-63QAQP7I.js} +3 -3
  15. package/dist/{chunk-LSXJJL4I.js → chunk-BDCC6UVW.js} +4 -4
  16. package/dist/{chunk-2UIRJPC6.js → chunk-BYP54FMI.js} +3 -3
  17. package/dist/{chunk-2ZRXJ3NO.js → chunk-NHVSO47Q.js} +2 -2
  18. package/dist/{chunk-DUGIVKNA.js → chunk-ORQD4AUO.js} +30 -4
  19. package/dist/chunk-ORQD4AUO.js.map +1 -0
  20. package/dist/{chunk-GMC5DO2O.js → chunk-QTWTZYXC.js} +41 -18
  21. package/dist/chunk-QTWTZYXC.js.map +1 -0
  22. package/dist/{chunk-F5FFOIS5.js → chunk-UFQM46NV.js} +2 -2
  23. package/dist/{chunk-BBYUWYEL.js → chunk-ZLUQYQ4P.js} +2 -2
  24. package/dist/operator/index.js +2 -2
  25. package/dist/public-consultation/index.js +4 -4
  26. package/dist/runtime/index.js +6 -4
  27. package/dist/runtime/index.js.map +1 -1
  28. package/dist/runtime/loop.d.ts +1 -0
  29. package/dist/runtime/openai-stream.d.ts +4 -0
  30. package/dist/runtime/router-turn.d.ts +44 -13
  31. package/dist/runtime/router-turn.js +5 -3
  32. package/dist/sandbox/index.d.ts +1 -0
  33. package/dist/sandbox/index.js +15 -3
  34. package/dist/sandbox/prewarm-route.d.ts +41 -35
  35. package/dist/sandbox/warm-receipts.d.ts +67 -0
  36. package/dist/turn-trace/index.js +2 -2
  37. package/dist/turn-trace/recorder.d.ts +7 -0
  38. package/dist/web-react/index.js +6 -6
  39. package/dist/web-react/workspace-prewarm.d.ts +12 -4
  40. package/dist/workspace-react/index.js +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-DUGIVKNA.js.map +0 -1
  43. package/dist/chunk-GMC5DO2O.js.map +0 -1
  44. package/dist/chunk-OXUBZ5SE.js.map +0 -1
  45. package/dist/chunk-PALGMOU3.js.map +0 -1
  46. package/dist/chunk-YHRWZZJN.js.map +0 -1
  47. /package/dist/{chunk-PYG2N2JX.js.map → chunk-23JUSUUB.js.map} +0 -0
  48. /package/dist/{chunk-HJ63OGYD.js.map → chunk-63QAQP7I.js.map} +0 -0
  49. /package/dist/{chunk-LSXJJL4I.js.map → chunk-BDCC6UVW.js.map} +0 -0
  50. /package/dist/{chunk-2UIRJPC6.js.map → chunk-BYP54FMI.js.map} +0 -0
  51. /package/dist/{chunk-2ZRXJ3NO.js.map → chunk-NHVSO47Q.js.map} +0 -0
  52. /package/dist/{chunk-F5FFOIS5.js.map → chunk-UFQM46NV.js.map} +0 -0
  53. /package/dist/{chunk-BBYUWYEL.js.map → chunk-ZLUQYQ4P.js.map} +0 -0
@@ -3,6 +3,7 @@ import {
3
3
  asksForLanguage,
4
4
  budgetTurnKnowledge,
5
5
  composeRouterTurnPrompt,
6
+ composeRouterTurnPromptSections,
6
7
  placeRouterTurn,
7
8
  replyLanguageInstruction,
8
9
  routerFunctionName,
@@ -11,16 +12,17 @@ import {
11
12
  turnKnowledgeInstructions,
12
13
  workspaceKnowledgeForTurn,
13
14
  workspaceTurnCheckpoints
14
- } from "../chunk-GMC5DO2O.js";
15
- import "../chunk-F5FFOIS5.js";
15
+ } from "../chunk-QTWTZYXC.js";
16
+ import "../chunk-UFQM46NV.js";
16
17
  import "../chunk-D6UJEOZQ.js";
17
18
  import "../chunk-AMUXRAUO.js";
18
- import "../chunk-DUGIVKNA.js";
19
+ import "../chunk-ORQD4AUO.js";
19
20
  export {
20
21
  DURABLE_HOP_BUDGET_MS,
21
22
  asksForLanguage,
22
23
  budgetTurnKnowledge,
23
24
  composeRouterTurnPrompt,
25
+ composeRouterTurnPromptSections,
24
26
  placeRouterTurn,
25
27
  replyLanguageInstruction,
26
28
  routerFunctionName,
@@ -15,6 +15,7 @@ export * from './sandbox-run-tool';
15
15
  export * from './sandbox-exec-tool';
16
16
  export * from './prewarm-claim-d1';
17
17
  export * from './prewarm-route';
18
+ export * from './warm-receipts';
18
19
  export * from './foreground-single-flight';
19
20
  export * from './warm-lease';
20
21
  export * from './warm-lease-d1';
@@ -6,6 +6,7 @@ import {
6
6
  DEFAULT_PROVISION_TIMEOUT_MS,
7
7
  DEFAULT_SANDBOX_RESOURCES,
8
8
  DEFAULT_WARM_LEASE_TABLE,
9
+ DEFAULT_WARM_RECEIPT_TABLE,
9
10
  ENV_TOTAL_MAX_BYTES,
10
11
  ENV_VALUE_MAX_BYTES,
11
12
  PREWARM_CLAIM_TABLE_DDL,
@@ -25,6 +26,7 @@ import {
25
26
  WARM_LEASE_DECLINED_UNTIL_DDL,
26
27
  WARM_LEASE_PENDING_DDL,
27
28
  WARM_LEASE_TABLE_DDL,
29
+ WARM_RECEIPT_TABLE_DDL,
28
30
  WARM_SLOTS,
29
31
  adaptSandboxStream,
30
32
  addColdArrival,
@@ -44,7 +46,9 @@ import {
44
46
  createCacheReuseStore,
45
47
  createD1PrewarmClaimStore,
46
48
  createD1WarmLeaseStore,
49
+ createD1WarmReceiptStore,
47
50
  createEscalationSpeculator,
51
+ createMemoryWarmReceiptStore,
48
52
  createSandboxExecTool,
49
53
  createSandboxPrewarmer,
50
54
  createSandboxRunTool,
@@ -98,9 +102,11 @@ import {
98
102
  traceSandboxPromptEvents,
99
103
  utcDay,
100
104
  warmBinOf,
105
+ warmKey,
106
+ warmReceiptId,
101
107
  warmWeekdayOf,
102
108
  writeProfileFilesToBox
103
- } from "../chunk-PALGMOU3.js";
109
+ } from "../chunk-5Y7Z5G3Y.js";
104
110
  import {
105
111
  EGRESS_PROXY_RECOVERY_PHASE,
106
112
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -149,9 +155,9 @@ import "../chunk-S5SRJJQG.js";
149
155
  import "../chunk-7TZA2TAM.js";
150
156
  import "../chunk-UGWQLQDS.js";
151
157
  import "../chunk-WSQFNMIA.js";
152
- import "../chunk-F5FFOIS5.js";
158
+ import "../chunk-UFQM46NV.js";
153
159
  import "../chunk-D6UJEOZQ.js";
154
- import "../chunk-DUGIVKNA.js";
160
+ import "../chunk-ORQD4AUO.js";
155
161
  export {
156
162
  DEFAULT_ESCALATION_TOOLS,
157
163
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
@@ -160,6 +166,7 @@ export {
160
166
  DEFAULT_PROVISION_TIMEOUT_MS,
161
167
  DEFAULT_SANDBOX_RESOURCES,
162
168
  DEFAULT_WARM_LEASE_TABLE,
169
+ DEFAULT_WARM_RECEIPT_TABLE,
163
170
  EGRESS_PROXY_RECOVERY_PHASE,
164
171
  EGRESS_PROXY_RECOVERY_REQUIRED,
165
172
  ENV_TOTAL_MAX_BYTES,
@@ -184,6 +191,7 @@ export {
184
191
  WARM_LEASE_DECLINED_UNTIL_DDL,
185
192
  WARM_LEASE_PENDING_DDL,
186
193
  WARM_LEASE_TABLE_DDL,
194
+ WARM_RECEIPT_TABLE_DDL,
187
195
  WARM_SLOTS,
188
196
  WORKSPACE_SANDBOX_HOST_EXHAUSTED,
189
197
  WORKSPACE_SANDBOX_MISSING,
@@ -212,7 +220,9 @@ export {
212
220
  createCacheReuseStore,
213
221
  createD1PrewarmClaimStore,
214
222
  createD1WarmLeaseStore,
223
+ createD1WarmReceiptStore,
215
224
  createEscalationSpeculator,
225
+ createMemoryWarmReceiptStore,
216
226
  createSandboxExecTool,
217
227
  createSandboxPrewarmer,
218
228
  createSandboxRunTool,
@@ -284,6 +294,8 @@ export {
284
294
  traceSandboxPromptEvents,
285
295
  utcDay,
286
296
  warmBinOf,
297
+ warmKey,
298
+ warmReceiptId,
287
299
  warmWeekdayOf,
288
300
  workspaceSandboxRecoveryDiagnostic,
289
301
  workspaceSandboxRecoveryFromError,
@@ -1,36 +1,4 @@
1
- /**
2
- * `createWorkspacePrewarmRoute`: the HTTP face of prewarm-on-open, so every
3
- * agent-app product warms the same way. The browser half is
4
- * `useWorkspacePrewarm` in `/web-react`: it POSTs here when a member opens a
5
- * workspace page in a visible tab, and again when they focus the composer.
6
- *
7
- * WHAT THE PRODUCT SUPPLIES. Only `authorize`. It authenticates the member
8
- * from the request exactly as the product's other routes do and returns the
9
- * warm to run: a box resume, a profile preparation, or `createSandboxPrewarmer`
10
- * from this subpath. The route owns everything shared: bot and prefetch
11
- * refusal, per-key single-flight, a short success memory, timing, and the rule
12
- * that a warm never reaches the member as an error.
13
- *
14
- * WHY THE WARM RUNS INSIDE THE REQUEST. A suspended box takes ~31 s to resume
15
- * (Hospitality production, 2026-10-10), past the 30 s that Cloudflare's
16
- * `waitUntil` grants after a response. Awaiting the warm keeps the request
17
- * open for as long as the member's tab is, which is exactly as long as a warm
18
- * is useful. The browser never awaits it for UI.
19
- *
20
- * IDEMPOTENCE. The in-process record only collapses concurrent calls within
21
- * one isolate, and a second call answers `joined` at once instead of awaiting
22
- * the first: on Workers a warm's I/O belongs to the request that started it, so
23
- * when that request is cancelled (the member navigates) its promise never
24
- * settles, and requests awaiting it hung 43-45 s (Hospitality production,
25
- * 2026-10-11). A record older than `staleMs` no longer counts. Two isolates can
26
- * both run the warm, so the product's warm must be safe to repeat: a resume of
27
- * a running box is a no-op, and a creation needs a claim store (see
28
- * `createSandboxPrewarmer`).
29
- *
30
- * FAILURE. A thrown warm answers 200 `{ outcome: 'failed' }` without the error
31
- * text, which can name internal hosts. `onEvent` receives the error so the
32
- * product can log it. The next real turn takes its normal placement path.
33
- */
1
+ import { type WarmReceiptStore } from './warm-receipts';
34
2
  /** What the product decided for this request. */
35
3
  export type WorkspacePrewarmAuthorization =
36
4
  /** Not signed in, not a member, or a foreign origin: return this response. */
@@ -53,9 +21,32 @@ export type WorkspacePrewarmAuthorization =
53
21
  status: 'allowed';
54
22
  key: string;
55
23
  warm: () => Promise<WorkspacePrewarmReport | void>;
24
+ }
25
+ /** Run each step whose key has no unexpired receipt. */
26
+ | {
27
+ status: 'allowed';
28
+ steps: readonly WorkspaceWarmStep[];
56
29
  };
57
- /** Why the browser asked: `useWorkspacePrewarm` sends `page-open` or `composer-focus`. */
58
- export type WorkspacePrewarmReason = 'page-open' | 'composer-focus';
30
+ /** One warm step, keyed by exactly what it depends on. */
31
+ export interface WorkspaceWarmStep {
32
+ /** A short name, unique within the response: `session`, `vault_heads`, `tool_catalog`, `box`. */
33
+ name: string;
34
+ /** What the step depends on (`warmKey({ userId, workspaceId, vaultHead })`). Members who share the result share the key. */
35
+ key: string;
36
+ /** How long a successful run counts. Keep it shorter than the warmed thing's own idle expiry (a box that suspends
37
+ * after 5 idle minutes gets a TTL well under that), because a receipt cannot see the thing go cold. */
38
+ ttlMs: number;
39
+ /** Do the work. The report, small JSON and never a credential, is stored on the receipt for the turn to read. */
40
+ run: () => Promise<WorkspacePrewarmReport | void>;
41
+ }
42
+ /** Why the browser asked: `useWorkspacePrewarm` sends `page-open`, `composer-focus`, or `heartbeat` while the tab stays open. */
43
+ export type WorkspacePrewarmReason = 'page-open' | 'composer-focus' | 'heartbeat';
44
+ export type WorkspaceWarmStepOutcome = 'hit' | 'miss' | 'joined' | 'failed';
45
+ export interface WorkspaceWarmStepResult {
46
+ name: string;
47
+ outcome: WorkspaceWarmStepOutcome;
48
+ ms: number;
49
+ }
59
50
  export type WorkspacePrewarmReport = Record<string, string | number | boolean | null>;
60
51
  export type WorkspacePrewarmOutcome =
61
52
  /** This request ran the warm to completion. */
@@ -72,6 +63,8 @@ export interface WorkspacePrewarmResponse {
72
63
  ms: number;
73
64
  reason?: string;
74
65
  report?: WorkspacePrewarmReport;
66
+ /** Each step's outcome, for an authorization that returned `steps`. */
67
+ steps?: WorkspaceWarmStepResult[];
75
68
  }
76
69
  export type WorkspacePrewarmEvent = {
77
70
  type: 'warmed';
@@ -83,15 +76,28 @@ export type WorkspacePrewarmEvent = {
83
76
  key: string;
84
77
  ms: number;
85
78
  error: string;
79
+ }
80
+ /** One step of a stepped warm; `failed` carries the error. */
81
+ | {
82
+ type: 'step';
83
+ name: string;
84
+ key: string;
85
+ outcome: WorkspaceWarmStepOutcome;
86
+ ms: number;
87
+ error?: string;
86
88
  };
87
89
  export interface CreateWorkspacePrewarmRouteOptions<Context = void> {
88
90
  /** `context` is whatever the caller passed beside the request, such as a
89
91
  * Hono context carrying the Worker's bindings. */
92
+ /** `threadId` is the thread the composer belongs to, when the browser sent one (composer focus). Check the member's access to it before warming anything for it. */
90
93
  authorize(input: {
91
94
  request: Request;
92
95
  context: Context;
93
96
  reason: WorkspacePrewarmReason;
97
+ threadId?: string;
94
98
  }): Promise<WorkspacePrewarmAuthorization>;
99
+ /** Where step receipts live across isolates (`createD1WarmReceiptStore`). Without it, receipts last for this isolate only. */
100
+ receipts?: WarmReceiptStore;
95
101
  /** After a successful warm, answer `recent` for this long. Default 30 000 ms. */
96
102
  recentMs?: number;
97
103
  /** A warm started longer ago than this no longer blocks the key: its request
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Warm receipts: the record that a warm step already ran for exactly the
3
+ * inputs it depends on, so a second warm with the same inputs does no work.
4
+ *
5
+ * A warm step (verify the session, resolve a child key, read the vault heads,
6
+ * build the connected-tool catalog, resume the box) is keyed by what it
7
+ * depends on: identity, workspace, thread, content hash, credential expiry.
8
+ * `createWorkspacePrewarmRoute` looks the key up before it runs the step; an
9
+ * unexpired receipt answers `hit` after one read and the step does not run.
10
+ * The turn reads the same receipt at send to reuse what the warm produced.
11
+ *
12
+ * The receipt store is shared across isolates (D1), because Workers spread one
13
+ * member's requests over many isolates: an in-isolate cache missed on 2 of 3
14
+ * warm turns in Creative staging (2026-10-21, connected-tool catalog 928-2,742
15
+ * ms). The route still keeps an in-isolate copy, so a repeat in the same
16
+ * isolate costs no read at all.
17
+ *
18
+ * A receipt's `report` is small JSON the product chooses (a vault head, a
19
+ * catalog digest, a box id). It must never hold a credential: receipts are
20
+ * rows any reader of the table can see.
21
+ */
22
+ export type WarmReceiptReport = Record<string, string | number | boolean | null>;
23
+ export interface WarmReceipt {
24
+ /** Epoch ms the step finished. */
25
+ at: number;
26
+ /** Epoch ms after which the receipt no longer counts. */
27
+ expiresAt: number;
28
+ report?: WarmReceiptReport;
29
+ }
30
+ export interface WarmReceiptStore {
31
+ get(id: string): Promise<WarmReceipt | null>;
32
+ put(id: string, receipt: WarmReceipt): Promise<void>;
33
+ }
34
+ /** The receipt id for one step and its key. */
35
+ export declare function warmReceiptId(step: string, key: string): string;
36
+ /**
37
+ * A warm key from exactly the values a step depends on: the same values give
38
+ * the same key whatever their order, and any change gives a new one. Values
39
+ * are hashed (SHA-256, hex), so a key names no member, path or expiry in the
40
+ * clear. Pass a credential's expiry or revision, never the credential.
41
+ */
42
+ export declare function warmKey(parts: Record<string, string | number | boolean | null>): Promise<string>;
43
+ /** Receipts in one isolate's memory: for tests and single-process hosts. */
44
+ export declare function createMemoryWarmReceiptStore(options?: {
45
+ limit?: number;
46
+ }): WarmReceiptStore;
47
+ /** The D1 surface the store uses. A real `D1Database` satisfies it. */
48
+ export interface WarmReceiptD1Like {
49
+ prepare(query: string): {
50
+ bind(...values: unknown[]): {
51
+ first<T = Record<string, unknown>>(): Promise<T | null>;
52
+ run(): Promise<unknown>;
53
+ };
54
+ };
55
+ }
56
+ export declare const DEFAULT_WARM_RECEIPT_TABLE = "warm_receipts";
57
+ /** Paste into a product migration; the store never runs DDL. Times are epoch ms. */
58
+ export declare const WARM_RECEIPT_TABLE_DDL = "CREATE TABLE IF NOT EXISTS warm_receipts (\n id TEXT PRIMARY KEY,\n at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n report TEXT\n);\nCREATE INDEX IF NOT EXISTS warm_receipts_by_expiry ON warm_receipts (expires_at)";
59
+ /**
60
+ * Receipts in one D1 table, shared by every isolate. A missing table throws on
61
+ * the first read, which the route treats as a miss: the step runs, and the
62
+ * failure reaches `onEvent`.
63
+ */
64
+ export declare function createD1WarmReceiptStore(db: WarmReceiptD1Like, options?: {
65
+ table?: string;
66
+ now?: () => number;
67
+ }): WarmReceiptStore;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  nextCallIndex,
3
3
  tracedModelFetch
4
- } from "../chunk-F5FFOIS5.js";
4
+ } from "../chunk-UFQM46NV.js";
5
5
  import {
6
6
  TURN_SPAN_KINDS,
7
7
  buildTurnTraceOtelSpans,
@@ -15,7 +15,7 @@ import {
15
15
  serverTimingAttrs,
16
16
  summarizeTurnSpans,
17
17
  turnTraceId
18
- } from "../chunk-DUGIVKNA.js";
18
+ } from "../chunk-ORQD4AUO.js";
19
19
  export {
20
20
  TURN_SPAN_KINDS,
21
21
  buildTurnTraceOtelSpans,
@@ -67,6 +67,13 @@ export interface TurnTraceSummary {
67
67
  firstVisibleMs?: number;
68
68
  /** D1 round trips in the turn scope, when its binding is instrumented. */
69
69
  d1Queries?: number;
70
+ /** From the request to the first model request: the wait the app owns before the model can start. */
71
+ dispatchMs?: number;
72
+ /** Each `admission.*` span's duration by its name after `admission.`, the split of the wait before the turn opens. */
73
+ admission?: Record<string, number>;
74
+ /** Prompt tokens over every model call, and how many of them the provider served from its prompt cache. */
75
+ inputTokens?: number;
76
+ cachedInputTokens?: number;
70
77
  }
71
78
  export interface TurnTraceSnapshot {
72
79
  traceId: string;
@@ -145,7 +145,7 @@ import {
145
145
  withoutRecordGridCreated,
146
146
  withoutRecordGridRemoved,
147
147
  withoutRecordGridUpdate
148
- } from "../chunk-2UIRJPC6.js";
148
+ } from "../chunk-BYP54FMI.js";
149
149
  import {
150
150
  MENTION_PILL_CLASS
151
151
  } from "../chunk-3HUFJ5LO.js";
@@ -181,7 +181,7 @@ import {
181
181
  preloadWhenIdle,
182
182
  useComposerAttachments,
183
183
  useDictation
184
- } from "../chunk-HJ63OGYD.js";
184
+ } from "../chunk-63QAQP7I.js";
185
185
  import "../chunk-L7MB2LLM.js";
186
186
  import {
187
187
  WorkspaceInitial,
@@ -192,7 +192,7 @@ import {
192
192
  requestWorkspacePrewarm,
193
193
  useWorkspacePrewarm,
194
194
  useWorkspacePrewarmHandle
195
- } from "../chunk-OXUBZ5SE.js";
195
+ } from "../chunk-2HQP2CTA.js";
196
196
  import {
197
197
  tabTerminalConnectionId,
198
198
  useSandboxTerminalConnection
@@ -245,7 +245,7 @@ import {
245
245
  ALLOWED_ATTACHMENT_SNIFFED_MIMES,
246
246
  ATTACHMENT_ACCEPT,
247
247
  OOXML_SNIFFED_MIMES
248
- } from "../chunk-2ZRXJ3NO.js";
248
+ } from "../chunk-NHVSO47Q.js";
249
249
  import "../chunk-FPNZMIAW.js";
250
250
  import "../chunk-B7CL7ENS.js";
251
251
  import "../chunk-PV33JZKV.js";
@@ -257,7 +257,7 @@ import {
257
257
  isChatAttachmentPart,
258
258
  mentionInputToPart,
259
259
  mentionPartsFromMessageParts
260
- } from "../chunk-PYG2N2JX.js";
260
+ } from "../chunk-23JUSUUB.js";
261
261
  import "../chunk-ZVEEWGDK.js";
262
262
  import {
263
263
  DISPATCH_MAX_MEDIA_PARTS,
@@ -281,7 +281,7 @@ import {
281
281
  mediaTypeForMentionPath,
282
282
  mentionKindForPath,
283
283
  settleTurnResponse
284
- } from "../chunk-YHRWZZJN.js";
284
+ } from "../chunk-5TSRFF5W.js";
285
285
  import "../chunk-TXD5HXLE.js";
286
286
  import {
287
287
  attachmentPartKey
@@ -6,9 +6,12 @@
6
6
  *
7
7
  * Fires only from a visible, non-prerendered document. A tab opened in the
8
8
  * background fires when it first becomes visible. Requests for the same URL
9
- * are spaced by `minIntervalMs` across every mount in the tab, so navigating
10
- * between pages of one workspace sends one request, not one per page. Call
11
- * `reassert()` on composer focus: a box can suspend while a tab sits open.
9
+ * and reason are spaced by `minIntervalMs` across every mount in the tab, so
10
+ * navigating between pages of one workspace sends one request, not one per
11
+ * page. Call `reassert()` on composer focus: a box can suspend while a tab sits
12
+ * open, and focus warms the thread itself. While the tab stays visible it sends
13
+ * a `heartbeat` every `heartbeatMs`, so what is warm stays warm; the route's
14
+ * receipts make a heartbeat over warm state cost one read.
12
15
  *
13
16
  * Failures are silent by design. A warm is an optimization; the turn itself
14
17
  * still places the box, so nothing here may surface to the member.
@@ -17,13 +20,18 @@ export interface WorkspacePrewarmRequestOptions {
17
20
  /** Minimum gap between requests for the same URL in this tab. Default 60 000 ms. */
18
21
  minIntervalMs?: number;
19
22
  /** Sent to the route so a product can budget page opens apart from composer focus. Default `page-open`. */
20
- reason?: 'page-open' | 'composer-focus';
23
+ reason?: 'page-open' | 'composer-focus' | 'heartbeat';
24
+ /** The thread the composer belongs to, so composer focus can warm that thread. */
25
+ threadId?: string;
21
26
  }
22
27
  export interface UseWorkspacePrewarmOptions extends WorkspacePrewarmRequestOptions {
23
28
  /** The product's prewarm route for this workspace. Empty disables. */
24
29
  url: string | null | undefined;
25
30
  /** False until the member is known to be signed in and allowed to chat. Default true. */
26
31
  enabled?: boolean;
32
+ /** Re-warm this often while the tab is visible and the member has used the page since the last beat (a key,
33
+ * pointer or scroll), so an idle tab lets the box park. Default 240 000 ms; 0 disables. */
34
+ heartbeatMs?: number;
27
35
  }
28
36
  export interface WorkspacePrewarmHandle {
29
37
  /** Ask again, subject to the same visibility and spacing rules. */
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  WorkspacePrewarmContext,
9
9
  useWorkspacePrewarm
10
- } from "../chunk-OXUBZ5SE.js";
10
+ } from "../chunk-2HQP2CTA.js";
11
11
  import {
12
12
  buildSessionNavItem,
13
13
  composeSidebarSessions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.247",
3
+ "version": "0.60.249",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/turn-trace/recorder.ts","../src/turn-trace/otel.ts","../src/turn-trace/server-timing.ts"],"sourcesContent":["/**\n * One trace per agent turn: a root span for the turn's wall time and named\n * child spans for where that time went (admission, each model call, each tool\n * call, the box claim and prompt, persistence).\n *\n * This module only records. It has no imports, so the Router engine, the\n * sandbox helpers and the chat route share it from any runtime, a Worker\n * included. `./otel` turns a finished trace into OTLP spans for Tangle\n * Intelligence.\n *\n * The turn's trace id is its execution id in the charset every hop accepts\n * ({@link turnTraceId}), sent as `x-tangle-trace-id` on every Router and\n * Sandbox call, so a Router dispatch row and a sandbox record join the turn's\n * spans by one id.\n */\n\n/** What a span's time is spent on. Each instant of the turn is credited to the deepest open span's kind. */\nexport type TurnSpanKind =\n | 'admission'\n | 'router'\n | 'model'\n | 'network'\n | 'tool'\n | 'sandbox'\n | 'persist'\n | 'other'\n\nexport const TURN_SPAN_KINDS: readonly TurnSpanKind[] = ['admission', 'router', 'model', 'network', 'tool', 'sandbox', 'persist', 'other']\n\n/** Bounded primitive metadata. Never prompts, answers, tool arguments or credentials. */\nexport type TurnSpanAttrs = Record<string, string | number | boolean>\n\nexport interface TurnSpanRecord {\n spanId: string\n /** The root span's id for a top-level child. */\n parentSpanId: string\n name: string\n kind: TurnSpanKind\n startMs: number\n endMs: number\n attrs: TurnSpanAttrs\n /** Set when the span ended in failure; a short code or message, never content. */\n error?: string\n /** True when the turn finished while the span was still open. */\n unfinished?: boolean\n}\n\nexport interface TurnSpan {\n readonly id: string\n /** Merge attributes. A later value replaces an earlier one. */\n set(attrs: TurnSpanAttrs): TurnSpan\n /** End now. A second call changes nothing. `error` marks the span failed. */\n end(attrs?: TurnSpanAttrs, error?: unknown): void\n /** A child that starts now. */\n child(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs): TurnSpan\n /** A child whose times are already known. */\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs): TurnSpan\n}\n\n/** How much of the turn's wall time is inside named spans, and what the time was spent on. */\nexport interface TurnTraceSummary {\n traceId: string\n wallMs: number\n /** Wall time inside at least one child span. */\n coveredMs: number\n /** `coveredMs / wallMs` as a percentage, one decimal. */\n coveragePct: number\n uncoveredMs: number\n /** The longest stretch with no span open: where an unnamed wait hides. */\n largestGapMs: number\n /** Wall time credited to the deepest open span's kind. Sums to `coveredMs`. */\n byKind: Record<TurnSpanKind, number>\n spans: number\n modelCalls: number\n toolCalls: number\n /** Spans refused after the per-turn cap. */\n dropped: number\n /** From the request to the first visible text the member could read (see {@link TurnTrace.markFirstText}); absent when none streamed. */\n firstTextMs?: number\n /** Headline latency: request to first reasoning, tool activity or answer output. */\n firstVisibleMs?: number\n /** D1 round trips in the turn scope, when its binding is instrumented. */\n d1Queries?: number\n}\n\nexport interface TurnTraceSnapshot {\n traceId: string\n /** The id the root span is exported under. */\n rootSpanId: string\n executionId: string\n startedAt: number\n endedAt: number\n spans: TurnSpanRecord[]\n summary: TurnTraceSummary\n /** `ok`, or the failure the turn ended with. */\n status: 'ok' | 'error'\n error?: string\n}\n\n/** Where a finished turn's trace goes. `labels` are the host's metadata for the root span (session, user, workspace). */\nexport type TurnTraceSink = (snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs) => void | Promise<void>\n\nexport interface TurnTrace {\n /** The turn's execution id in the charset the Router and Sandbox accept. Send it as `x-tangle-trace-id`. */\n readonly traceId: string\n readonly executionId: string\n readonly startedAt: number\n /** The span a top-level child hangs from. */\n readonly root: TurnSpan\n /** Name the turn's execution id once it is known. Spans recorded earlier keep their times. */\n bind(executionId: string): void\n start(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n /** Run `work` inside a span; the span ends when it settles, failed if it throws. */\n measure<T>(name: string, kind: TurnSpanKind, work: (span: TurnSpan) => Promise<T> | T, attrs?: TurnSpanAttrs, parent?: TurnSpan): Promise<T>\n /**\n * Note that the turn's first visible text reached the member. The chat route calls it on the first text event of\n * either lane; a product that owns its turn calls it itself. Only the first call counts. The summary's\n * `firstTextMs` then reads from the request, so it holds admission, the box or the Router, and the model.\n */\n markFirstText(at?: number): void\n /** Mark the first reasoning, tool activity or answer output. Only the first call counts. */\n markFirstVisible(at?: number): void\n /** Read the current numbers without ending the trace. */\n summary(now?: number): TurnTraceSummary\n /** Read the spans recorded so far without ending the trace; an open span reads as ending at `now`. */\n spans(now?: number): TurnSpanRecord[]\n /** End the trace: open spans close at `endedAt`, and later spans are refused. A second call returns the first result. */\n finish(outcome?: { error?: unknown; endedAt?: number }): TurnTraceSnapshot\n}\n\nexport interface CreateTurnTraceOptions {\n /** Epoch ms the turn began (default now). A route passes its request time so admission is inside the trace. */\n startedAt?: number\n executionId?: string\n now?: () => number\n /** Most spans one turn keeps (default 1000); the rest are counted as dropped. */\n maxSpans?: number\n /** Live counter captured by the server turn owner; no Node dependency in the recorder. */\n d1QueryCounter?: { readonly queries: number }\n}\n\nconst TRACE_ID_PATTERN = /^[\\w-]{8,200}$/\nconst MAX_ATTRS = 48\nconst MAX_ATTR_STRING = 200\n\n/** True when the Router and the Sandbox API keep this id as a `x-tangle-trace-id`. */\nexport function isTraceId(value: string): boolean {\n return TRACE_ID_PATTERN.test(value)\n}\n\n/**\n * The turn's execution id as a trace id. Execution ids carry `:` (`app:session:turn`),\n * which the Router drops from `x-tangle-trace-id`, so every character outside\n * `[A-Za-z0-9_-]` becomes `_`. An id already in the charset is returned as it is.\n */\nexport function turnTraceId(executionId: string): string {\n // An id in the charset is the caller's own, whatever its length (the Router drops one under 8 characters; it is not rewritten here).\n if (/^[\\w-]{1,200}$/.test(executionId)) return executionId\n const id = executionId.replace(/[^\\w-]/g, '_').slice(0, 200)\n return id.length >= 8 ? id : id.padEnd(8, '_')\n}\n\nfunction randomHex(bytes: number): string {\n const out = new Uint8Array(bytes)\n if (typeof globalThis.crypto?.getRandomValues === 'function') globalThis.crypto.getRandomValues(out)\n else for (let i = 0; i < bytes; i++) out[i] = Math.floor(Math.random() * 256)\n return Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction boundedAttrs(attrs: TurnSpanAttrs): TurnSpanAttrs {\n const out: TurnSpanAttrs = {}\n let count = 0\n for (const [key, value] of Object.entries(attrs)) {\n if (count >= MAX_ATTRS) break\n if (typeof value === 'number' && !Number.isFinite(value)) continue\n out[key.slice(0, 80)] = typeof value === 'string' ? value.slice(0, MAX_ATTR_STRING) : value\n count++\n }\n return out\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`).slice(0, MAX_ATTR_STRING)\n return String(error).slice(0, MAX_ATTR_STRING)\n}\n\nconst zeroKinds = (): Record<TurnSpanKind, number> => ({\n admission: 0, router: 0, model: 0, network: 0, tool: 0, sandbox: 0, persist: 0, other: 0,\n})\n\nconst round1 = (value: number) => Math.round(value * 10) / 10\n\n/**\n * Coverage and the per-kind split for a set of spans over `[startMs, endMs]`.\n * Exported for a reader that holds the spans of a finished trace.\n */\nexport function summarizeTurnSpans(\n spans: readonly Pick<TurnSpanRecord, 'spanId' | 'parentSpanId' | 'kind' | 'name' | 'startMs' | 'endMs'>[],\n rootSpanId: string,\n startMs: number,\n endMs: number,\n traceId: string,\n dropped = 0,\n): TurnTraceSummary {\n const wallMs = Math.max(0, endMs - startMs)\n const parent = new Map(spans.map((span) => [span.spanId, span.parentSpanId]))\n const depthOf = (id: string): number => {\n let depth = 0\n for (let at = parent.get(id); at !== undefined && at !== rootSpanId; at = parent.get(at)) {\n depth++\n if (depth > 64) break\n }\n return depth\n }\n const clipped = spans\n .map((span) => ({ span, start: Math.max(startMs, span.startMs), end: Math.min(endMs, span.endMs), depth: depthOf(span.spanId) }))\n .filter((entry) => entry.end > entry.start)\n const points = [...new Set([startMs, endMs, ...clipped.flatMap((entry) => [entry.start, entry.end])])].sort((a, b) => a - b)\n const byKind = zeroKinds()\n let coveredMs = 0\n let largestGapMs = 0\n let gap = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n let deepest: (typeof clipped)[number] | undefined\n for (const entry of clipped) {\n if (entry.start <= from && entry.end >= to && (!deepest || entry.depth > deepest.depth || (entry.depth === deepest.depth && entry.start > deepest.start))) deepest = entry\n }\n if (deepest) {\n byKind[deepest.span.kind] += to - from\n coveredMs += to - from\n gap = 0\n } else {\n gap += to - from\n largestGapMs = Math.max(largestGapMs, gap)\n }\n }\n for (const kind of TURN_SPAN_KINDS) byKind[kind] = round1(byKind[kind])\n return {\n traceId,\n wallMs: round1(wallMs),\n coveredMs: round1(coveredMs),\n coveragePct: wallMs > 0 ? round1((coveredMs / wallMs) * 100) : 0,\n uncoveredMs: round1(wallMs - coveredMs),\n largestGapMs: round1(largestGapMs),\n byKind,\n spans: spans.length,\n modelCalls: spans.filter((span) => span.name === 'model.call').length,\n toolCalls: spans.filter((span) => span.name === 'tool.call').length,\n dropped,\n }\n}\n\nexport function createTurnTrace(options: CreateTurnTraceOptions = {}): TurnTrace {\n const now = options.now ?? Date.now\n const startedAt = options.startedAt ?? now()\n const maxSpans = options.maxSpans ?? 1000\n const rootId = randomHex(8)\n let executionId = options.executionId ?? `pending_${randomHex(6)}`\n let traceId = turnTraceId(executionId)\n const records = new Map<string, TurnSpanRecord>()\n const open = new Set<string>()\n let dropped = 0\n let finished: TurnTraceSnapshot | undefined\n let firstVisibleAt: number | undefined\n let firstTextAt: number | undefined\n\n // A refused or late span still returns a handle, so instrumentation never branches on the trace's state.\n const inert = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set: () => handle,\n end: () => {},\n child: () => inert(rootId),\n record: () => inert(rootId),\n }\n return handle\n }\n\n const handleFor = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set(attrs) {\n const record = records.get(id)\n if (record && !finished) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n return handle\n },\n end(attrs, error) {\n const record = records.get(id)\n if (!record || !open.has(id) || finished) return\n open.delete(id)\n record.endMs = Math.max(record.startMs, now())\n if (attrs) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n if (error !== undefined) record.error = errorText(error)\n },\n child: (name, kind, attrs) => trace.start(name, kind, attrs, handle),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs, handle),\n }\n return handle\n }\n\n const add = (name: string, kind: TurnSpanKind, startMs: number, endMs: number | undefined, attrs: TurnSpanAttrs | undefined, parent: TurnSpan | undefined): TurnSpan => {\n if (finished) return inert(rootId)\n if (records.size >= maxSpans) {\n dropped++\n return inert(rootId)\n }\n const spanId = randomHex(8)\n records.set(spanId, {\n spanId,\n parentSpanId: parent && parent.id !== spanId ? parent.id : rootId,\n name: name.slice(0, 80),\n kind,\n startMs,\n endMs: endMs ?? startMs,\n attrs: attrs ? boundedAttrs(attrs) : {},\n })\n if (endMs === undefined) open.add(spanId)\n return handleFor(spanId)\n }\n\n const rootHandle: TurnSpan = {\n id: rootId,\n set: () => rootHandle,\n end: () => {},\n child: (name, kind, attrs) => trace.start(name, kind, attrs),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs),\n }\n\n const withMeasurements = (summary: TurnTraceSummary): TurnTraceSummary => ({\n ...summary,\n ...(firstVisibleAt === undefined ? {} : { firstVisibleMs: round1(firstVisibleAt - startedAt) }),\n ...(firstTextAt === undefined ? {} : { firstTextMs: round1(firstTextAt - startedAt) }),\n ...(options.d1QueryCounter === undefined ? {} : { d1Queries: options.d1QueryCounter.queries }),\n })\n\n const trace: TurnTrace = {\n get traceId() { return traceId },\n get executionId() { return executionId },\n startedAt,\n root: rootHandle,\n bind(id) {\n executionId = id\n traceId = turnTraceId(id)\n },\n start: (name, kind, attrs, parent) => add(name, kind, now(), undefined, attrs, parent),\n record: (name, kind, startMs, endMs, attrs, parent) => add(name, kind, startMs, Math.max(startMs, endMs), attrs, parent),\n async measure(name, kind, work, attrs, parent) {\n const span = trace.start(name, kind, attrs, parent)\n try {\n const result = await work(span)\n span.end()\n return result\n } catch (error) {\n span.end(undefined, error)\n throw error\n }\n },\n markFirstVisible(at) {\n if (finished || firstVisibleAt !== undefined) return\n firstVisibleAt = Math.max(startedAt, at ?? now())\n },\n markFirstText(at) {\n if (finished || firstTextAt !== undefined) return\n firstTextAt = Math.max(startedAt, at ?? now())\n firstVisibleAt ??= firstTextAt\n },\n summary(at) {\n if (finished) return finished.summary\n const end = at ?? now()\n return withMeasurements(summarizeTurnSpans(trace.spans(end), rootId, startedAt, end, traceId, dropped))\n },\n spans(at) {\n const end = at ?? finished?.endedAt ?? now()\n return [...records.values()].map((record) => open.has(record.spanId) ? { ...record, endMs: end } : { ...record })\n },\n finish(outcome) {\n if (finished) return finished\n const endedAt = Math.max(startedAt, outcome?.endedAt ?? now())\n for (const id of open) {\n const record = records.get(id)!\n record.endMs = Math.max(record.startMs, endedAt)\n record.unfinished = true\n }\n open.clear()\n const spans = [...records.values()].sort((a, b) => a.startMs - b.startMs)\n finished = {\n traceId,\n rootSpanId: rootId,\n executionId,\n startedAt,\n endedAt,\n spans,\n summary: withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, endedAt, traceId, dropped)),\n status: outcome?.error === undefined ? 'ok' : 'error',\n ...(outcome?.error === undefined ? {} : { error: errorText(outcome.error) }),\n }\n return finished\n },\n }\n return trace\n}\n","/**\n * A finished turn trace as OTLP spans, sent to Tangle Intelligence.\n *\n * The attribute vocabulary is the one agent-runtime's span builders write\n * (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.*`,\n * `gen_ai.tool.name`, OpenInference's span kind, `agent.parent.confidence`), and\n * the wire shape is the one its `createOtelExporter` posts to\n * `<base>/v1/otlp/v1/traces`.\n *\n * It does not import agent-runtime. The runtime root pulls the whole sandbox\n * SDK into a Worker bundle, and the SDK's chain client imports `viem`, which a\n * Worker build cannot resolve (Hospitality's release failed on exactly that);\n * and its exporter keeps a timer a Worker refuses at module scope. One OTLP\n * POST per finished turn needs neither.\n */\nimport { TURN_SPAN_KINDS, type TurnSpanAttrs, type TurnSpanKind, type TurnTraceSink, type TurnTraceSnapshot } from './recorder'\n\n/** One OTLP/JSON span, as Intelligence's ingest reads it. */\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{ key: string; value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean } }>\n status: { code: number; message?: string }\n}\n\n/** `doubles` names measurements that stay `doubleValue` when they land on a whole number, so a reader sees one type per key. */\nfunction attributes(record: Record<string, string | number | boolean>, doubles: ReadonlySet<string> = new Set()): OtlpSpan['attributes'] {\n return Object.entries(record).flatMap(([key, value]) => {\n if (typeof value === 'number' && !Number.isFinite(value)) return []\n return [{\n key,\n value: typeof value === 'number' ? (Number.isInteger(value) && !doubles.has(key) ? { intValue: value.toString() } : { doubleValue: value })\n : typeof value === 'boolean' ? { boolValue: value } : { stringValue: value },\n }]\n })\n}\n\n/** The root span's measured numbers: one decimal, so each is always a `doubleValue`. */\nconst ROOT_MEASUREMENTS: ReadonlySet<string> = new Set([\n 'tangle.duration_ms',\n 'tangle.turn.wall_ms',\n 'tangle.turn.covered_ms',\n 'tangle.turn.coverage_pct',\n 'tangle.turn.uncovered_ms',\n 'tangle.turn.largest_gap_ms',\n 'tangle.turn.first_visible_ms',\n 'tangle.turn.first_text_ms',\n ...TURN_SPAN_KINDS.map((kind) => `tangle.turn.${kind}_ms`),\n])\n\n/**\n * A Tangle trace id as the 32-hex OTLP trace id. The mapping is the Sandbox SDK's `otelTraceIdForTangleTrace`, so a\n * Sandbox trace export of the same turn lands in the same OTLP trace. An id that is already 32 hex, or a UUID, is used as it is.\n */\nexport function otlpTraceId(traceId: string): string {\n if (/^[0-9a-f]{32}$/.test(traceId)) return traceId\n const dashless = traceId.replace(/-/g, '')\n if (/^[0-9a-f]{32}$/.test(dashless)) return dashless\n return hexId(traceId, 32)\n}\n\nfunction hexId(input: string, length: number): string {\n const hashes = [2166136261, 2654435769, 2246822507, 3266489909]\n for (const byte of new TextEncoder().encode(input)) {\n for (let lane = 0; lane < hashes.length; lane += 1) hashes[lane] = Math.imul((hashes[lane] as number) ^ (byte + lane), 16777619)\n }\n let out = hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, '0')).join('')\n while (out.length < length) out += hexId(`${input}:${out.length}`, 32)\n return out.slice(0, length)\n}\n\nconst msToNs = (ms: number) => (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n\n/** OpenInference span kind per turn span: model calls read as LLM, tool calls as TOOL. */\nconst SPAN_KIND: Partial<Record<string, 'LLM' | 'TOOL'>> = { 'model.call': 'LLM', 'tool.call': 'TOOL' }\n\n/**\n * The root span (`agent_app.turn`) carries the host's labels and the turn's\n * numbers: wall time, the share inside child spans, and the time credited to\n * each kind of span. Children follow under it.\n */\nexport function buildTurnTraceOtelSpans(snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs = {}): OtlpSpan[] {\n const traceId = otlpTraceId(snapshot.traceId)\n const root = snapshot.rootSpanId\n const { summary } = snapshot\n const rootAttrs: Record<string, string | number | boolean> = {\n ...labels,\n 'openinference.span.kind': 'CHAIN',\n 'tangle.execution_id': snapshot.executionId,\n 'tangle.trace_id': snapshot.traceId,\n 'tangle.started_at_ms': snapshot.startedAt,\n 'tangle.completed_at_ms': snapshot.endedAt,\n 'tangle.duration_ms': summary.wallMs,\n 'tangle.turn.wall_ms': summary.wallMs,\n 'tangle.turn.covered_ms': summary.coveredMs,\n 'tangle.turn.coverage_pct': summary.coveragePct,\n 'tangle.turn.uncovered_ms': summary.uncoveredMs,\n 'tangle.turn.largest_gap_ms': summary.largestGapMs,\n 'tangle.turn.spans': summary.spans,\n 'tangle.turn.model_calls': summary.modelCalls,\n 'tangle.turn.tool_calls': summary.toolCalls,\n ...(summary.firstVisibleMs === undefined ? {} : { 'tangle.turn.first_visible_ms': summary.firstVisibleMs }),\n ...(summary.firstTextMs === undefined ? {} : { 'tangle.turn.first_text_ms': summary.firstTextMs }),\n ...(summary.d1Queries === undefined ? {} : { 'tangle.turn.d1_queries': summary.d1Queries }),\n ...(summary.dropped ? { 'tangle.turn.spans_dropped': summary.dropped } : {}),\n ...Object.fromEntries(TURN_SPAN_KINDS.map((kind: TurnSpanKind) => [`tangle.turn.${kind}_ms`, summary.byKind[kind]])),\n }\n const spans: OtlpSpan[] = [{\n traceId,\n spanId: root,\n name: 'agent_app.turn',\n kind: 1,\n startTimeUnixNano: msToNs(snapshot.startedAt),\n endTimeUnixNano: msToNs(snapshot.endedAt),\n attributes: attributes(rootAttrs, ROOT_MEASUREMENTS),\n status: snapshot.status === 'ok' ? { code: 1 } : { code: 2, ...(snapshot.error ? { message: snapshot.error } : {}) },\n }]\n for (const span of snapshot.spans) {\n const attrs: Record<string, string | number | boolean> = {\n ...span.attrs,\n 'openinference.span.kind': SPAN_KIND[span.name] ?? 'CHAIN',\n 'tangle.turn.span_kind': span.kind,\n 'agent.parent.confidence': 'explicit',\n ...(span.name === 'tool.call' ? { 'gen_ai.operation.name': 'execute_tool' } : {}),\n ...(span.unfinished ? { 'tangle.turn.unfinished': true } : {}),\n ...(span.error ? { 'error.message': span.error } : {}),\n }\n spans.push({\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: msToNs(span.startMs),\n endTimeUnixNano: msToNs(span.endMs),\n attributes: attributes(attrs),\n status: span.error ? { code: 2, message: span.error } : { code: 1 },\n })\n }\n return spans\n}\n\nexport interface IntelligenceTurnTraceSinkOptions {\n /** The Intelligence project the spans belong to, e.g. `legal-agent`. */\n project: string\n /**\n * The tenant key the ingest requires. Omit it: the sink reads the Sandbox product key from the first of\n * `SANDBOX_PRODUCTION_API_KEY`, `TCLOUD_SANDBOX_API_KEY` and `SANDBOX_API_KEY` that is set, the platform key the\n * ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468, 2026-10-19), so a key is never assumed: a refusal is a console warning.\n */\n apiKey?: string\n /** Default `https://intelligence.tangle.tools`; spans go to `<base>/v1/otlp/v1/traces`. */\n baseUrl?: string\n /** Called with a short reason when a delivery fails. Never receives span content. Default: a console warning. */\n onError?: (reason: string) => void\n /** Milliseconds one POST may take (default 5000). */\n timeoutMs?: number\n}\n\nconst DEFAULT_INTELLIGENCE_BASE_URL = 'https://intelligence.tangle.tools'\n/** The Sandbox product key names, in the order the apps' sandbox lanes prefer them. Read per delivery: a Worker's env is not populated at module scope. */\nconst INGEST_KEY_ENV = ['SANDBOX_PRODUCTION_API_KEY', 'TCLOUD_SANDBOX_API_KEY', 'SANDBOX_API_KEY'] as const\n\n/** The key the ingest verifies, from the host's environment: what the sink uses when it is given none, and what an app's other Intelligence client should use too. */\nexport function resolveIngestKey(): string | undefined {\n if (typeof process === 'undefined') return undefined\n for (const name of INGEST_KEY_ENV) {\n const value = process.env?.[name]?.trim()\n if (value) return value\n }\n return undefined\n}\nconst SCOPE = { name: '@tangle-network/agent-app', version: 'turn-trace' }\n\n/**\n * The sink a chat route or a Worker turn hands each finished trace to: one OTLP POST per turn, awaited, so a host that\n * runs it under `waitUntil` keeps the isolate alive until delivery. It never throws; every failure, including a missing\n * key and a non-2xx answer, goes to `onError` (a console warning by default), because a silent sink hid Legal's 401s.\n */\nexport function createIntelligenceTurnTraceSink(options: IntelligenceTurnTraceSinkOptions): TurnTraceSink {\n const url = `${(options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\\/+$/, '')}/v1/otlp/v1/traces`\n const report = options.onError ?? ((reason: string) => console.warn(`[turn-trace] export failed: ${reason}`))\n const fail = (reason: string) => { try { report(reason.slice(0, 200)) } catch { /* telemetry only */ } }\n let missingKeyReported = false\n return async (snapshot, labels) => {\n const apiKey = options.apiKey?.trim() || resolveIngestKey()\n if (!apiKey) {\n if (!missingKeyReported) fail(`no ingest key: set ${INGEST_KEY_ENV.join(', ')} or pass apiKey`)\n missingKeyReported = true\n return\n }\n try {\n const body = {\n resourceSpans: [{\n resource: { attributes: attributes({ 'service.name': options.project, 'tangle.project': options.project }) },\n scopeSpans: [{ scope: SCOPE, spans: buildTurnTraceOtelSpans(snapshot, { project: options.project, ...labels }) }],\n }],\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? 5_000),\n })\n const text = await response.text()\n if (!response.ok) return fail(`HTTP ${response.status} from the OTLP ingest`)\n // A 2xx can still refuse part of a batch (`partialSuccess.rejectedSpans`).\n const rejected = Number((JSON.parse(text || '{}') as { partialSuccess?: { rejectedSpans?: unknown } }).partialSuccess?.rejectedSpans ?? 0)\n if (rejected > 0) fail(`the OTLP ingest rejected ${rejected} spans`)\n } catch (error) {\n fail(error instanceof Error ? error.message : 'turn trace export failed')\n }\n }\n}\n","/** One entry of a `Server-Timing` response header. */\nexport interface ServerTimingEntry {\n name: string\n /** Milliseconds, when the entry carries `dur`. */\n durMs?: number\n /** `desc`, unquoted: a count or a label, never a duration. */\n desc?: string\n}\n\n/** Split on commas that sit outside a quoted `desc`. */\nfunction splitEntries(header: string): string[] {\n const out: string[] = []\n let current = ''\n let quoted = false\n for (const char of header) {\n if (char === '\"') quoted = !quoted\n if (char === ',' && !quoted) {\n out.push(current)\n current = ''\n } else {\n current += char\n }\n }\n out.push(current)\n return out\n}\n\n/**\n * Parse a `Server-Timing` header, as the Router and the Sandbox orchestrator\n * send it. A malformed entry is skipped; the result never throws.\n */\nexport function parseServerTiming(header: string | null | undefined): ServerTimingEntry[] {\n if (!header) return []\n const entries: ServerTimingEntry[] = []\n for (const raw of splitEntries(header.slice(0, 4096))) {\n const [name, ...params] = raw.split(';').map((part) => part.trim())\n if (!name || !/^[\\w.!#$%&'*+^`|~-]+$/.test(name)) continue\n const entry: ServerTimingEntry = { name }\n for (const param of params) {\n const eq = param.indexOf('=')\n if (eq < 0) continue\n const key = param.slice(0, eq).trim().toLowerCase()\n const value = param.slice(eq + 1).trim()\n if (key === 'dur') {\n const dur = Number(value)\n if (Number.isFinite(dur) && dur >= 0) entry.durMs = dur\n } else if (key === 'desc') {\n entry.desc = value.replace(/^\"|\"$/g, '').slice(0, 120)\n }\n }\n entries.push(entry)\n }\n return entries\n}\n\n/** Flat span attributes for the entries: `server_timing.<name>_ms` for a duration, `server_timing.<name>` for a `desc`. */\nexport function serverTimingAttrs(entries: readonly ServerTimingEntry[]): Record<string, string | number> {\n const out: Record<string, string | number> = {}\n for (const entry of entries.slice(0, 32)) {\n const key = entry.name.replace(/[^\\w]/g, '_')\n if (entry.durMs !== undefined) out[`server_timing.${key}_ms`] = Math.round(entry.durMs * 10) / 10\n else if (entry.desc !== undefined) out[`server_timing.${key}`] = entry.desc\n }\n return out\n}\n\n/** Format entries as a `Server-Timing` header value, the inverse of {@link parseServerTiming}. Invalid names are skipped. */\nexport function formatServerTiming(entries: readonly ServerTimingEntry[]): string {\n return entries\n .filter((entry) => /^[\\w.!#$%&'*+^`|~-]+$/.test(entry.name))\n .slice(0, 32)\n .map((entry) => [\n entry.name,\n ...(entry.durMs === undefined ? [] : [`dur=${Math.round(entry.durMs * 10) / 10}`]),\n ...(entry.desc === undefined ? [] : [`desc=\"${entry.desc.replace(/[\"\\\\]/g, '').slice(0, 120)}\"`]),\n ].join(';'))\n .join(', ')\n}\n"],"mappings":";AA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