@tangle-network/agent-app 4.0.23 → 4.0.25

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.
@@ -43,7 +43,7 @@ import {
43
43
  } from "../chunk-75DKKZQ3.js";
44
44
  import {
45
45
  runProtectedRouterTurn
46
- } from "../chunk-77YMF6MD.js";
46
+ } from "../chunk-HCNEVBPJ.js";
47
47
  import {
48
48
  HYBRID_TURN_GUIDANCE,
49
49
  INTENT_LINE_HISTORY_MESSAGES,
@@ -74,14 +74,14 @@ import {
74
74
  turnPromptText,
75
75
  valueRedactor,
76
76
  withProducerStream
77
- } from "../chunk-QSMFN5GJ.js";
77
+ } from "../chunk-GPCQRTWF.js";
78
78
  import "../chunk-SBHFMDR7.js";
79
79
  import "../chunk-H6BRJU5M.js";
80
80
  import "../chunk-4DBHC63F.js";
81
81
  import "../chunk-RN4WPTBH.js";
82
82
  import "../chunk-MM6RLOXF.js";
83
83
  import "../chunk-M4QITAQV.js";
84
- import "../chunk-QMQB725F.js";
84
+ import "../chunk-Z5M2Z2QK.js";
85
85
  import "../chunk-F4TUZYMX.js";
86
86
  import {
87
87
  redactErrorMessage
@@ -185,9 +185,9 @@ import "../chunk-S5SRJJQG.js";
185
185
  import "../chunk-GD4ONMKJ.js";
186
186
  import "../chunk-UGWQLQDS.js";
187
187
  import "../chunk-R32MULDK.js";
188
- import "../chunk-2TEZZXUT.js";
188
+ import "../chunk-V3YVG7DJ.js";
189
189
  import "../chunk-D6UJEOZQ.js";
190
- import "../chunk-YYA2CVOY.js";
190
+ import "../chunk-ZZZLYVZX.js";
191
191
  import "../chunk-KSLTD4FI.js";
192
192
  import {
193
193
  sniffMimeFromName
@@ -12,6 +12,7 @@ interface TurnExecutionOptions<TContext, TResource> {
12
12
  progressMessages: Record<TurnRoutePhase, string>;
13
13
  traceOptions: ChatTurnTraceOptions<TContext> | undefined;
14
14
  traceSink: TurnTraceSink | undefined;
15
+ traceReceipt(request: Request, executionId: string): Record<string, string>;
15
16
  startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined;
16
17
  log(message: string, meta?: Record<string, unknown>): void;
17
18
  }
@@ -11,6 +11,7 @@ import type { ModelFailoverAttempt } from '../model-resolution/failover.js';
11
11
  import type { ModelPolicy } from '../policy-filters/index.js';
12
12
  import type { PersistedChatMessageForTurn, TurnEventStore } from '../stream/index.js';
13
13
  import type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder.js';
14
+ import type { TurnTraceReader } from '../turn-trace/otel.js';
14
15
  import type { TurnRoutePhase } from './turn-progress.js';
15
16
  import type { AgentProfile } from '@tangle-network/agent-interface';
16
17
  import type { AgentMention, ChatTurnPartInput, ChatTurnRequestPayload } from './wire.js';
@@ -570,6 +571,10 @@ export interface ChatTurnTraceOptions<TContext> {
570
571
  executionId: string;
571
572
  context: TContext;
572
573
  }): TurnSpanAttrs;
574
+ /** Reads a turn's trace back for {@link ChatTurnRoutes.trace}. Default with no `sink`: `createIntelligenceTurnTraceReader({
575
+ * project: projectId })`. A product with its own sink passes the reader for the same store; without one, the turn
576
+ * receipt names no `traceUrl` and the route answers 404. */
577
+ read?: TurnTraceReader;
573
578
  }
574
579
  /** Define options to configure chat turn routes including authorization, storage, and event buffering */
575
580
  export interface CreateChatTurnRoutesOptions<TContext = void, TResource = unknown> {
@@ -839,8 +844,9 @@ export declare const INTENT_LINE_MAX_CHARS = 240;
839
844
  export interface ChatTurnRoutes {
840
845
  /** POST — warm the server-authorized workspace lock (and with `prewarm: 'box'` its box, under `ctx.waitUntil`); verify a named thread first. */
841
846
  prewarm(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>;
842
- /** POST — run one turn, streaming NDJSON. First line is
843
- * `{type:'turn', turnId}` (the replay handle); the rest is the engine's
847
+ /** POST — run one turn, streaming NDJSON. First line is the receipt
848
+ * `{type:'turn', turnId, traceId?, traceUrl?}`: the replay handle, the turn's
849
+ * OTLP trace id and where {@link trace} serves it; the rest is the engine's
844
850
  * event protocol. Pass the platform's `waitUntil` so the turn keeps
845
851
  * running (and buffering) after a client disconnect. A request with
846
852
  * `TURN_PROGRESS_HEADER` gets a progress-first stream once it is
@@ -853,6 +859,13 @@ export interface ChatTurnRoutes {
853
859
  replay(request: Request, params: {
854
860
  turnId: string;
855
861
  }): Promise<Response>;
862
+ /** GET — the turn's own trace as OTLP JSON, for its owner: the waterfall a product shows and a member downloads. Mount
863
+ * it at `<turn path>/turns/:turnId/trace`, the `traceUrl` the turn receipt names; `turnId` is the turn's execution
864
+ * id. The caller is authorized as `running` on the turn's thread, so only a caller who may read that thread gets it;
865
+ * everyone else, and a turn whose trace is not stored yet, gets 404. Metadata only: the turn exporter's spans. */
866
+ trace(request: Request, params: {
867
+ turnId: string;
868
+ }): Promise<Response>;
856
869
  /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still
857
870
  * running on a thread, so a client that reloaded mid-turn can re-attach to
858
871
  * the live stream via {@link replay} instead of losing it. Returns `[]` when
@@ -0,0 +1,19 @@
1
+ import { type TurnTraceReader } from '../turn-trace/otel.js';
2
+ import { type TurnTraceSink } from '../turn-trace/recorder.js';
3
+ import type { ChatTurnAuthorization, ChatTurnAuthorizeArgs, ChatTurnTraceOptions } from './turn-route-contracts.js';
4
+ /** The route's trace store: every turn goes to Intelligence unless the product turns it off (`turnTrace: false`). */
5
+ export declare function turnTraceWiring<TContext>(projectId: string, turnTrace: ChatTurnTraceOptions<TContext> | false | undefined): {
6
+ traceOptions: ChatTurnTraceOptions<TContext> | undefined;
7
+ traceSink: TurnTraceSink | undefined;
8
+ traceReader: TurnTraceReader | undefined;
9
+ traceReceipt: (request: Request, executionId: string) => Record<string, string>;
10
+ };
11
+ /** `routes.trace`: the turn's trace for a caller who may read its thread; 404 for anyone else and for a trace not stored yet. */
12
+ export declare function createTurnTraceRoute<TContext>({ projectId, authorize, reader, log }: {
13
+ projectId: string;
14
+ authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>;
15
+ reader: TurnTraceReader | undefined;
16
+ log(message: string, meta?: Record<string, unknown>): void;
17
+ }): (request: Request, params: {
18
+ turnId: string;
19
+ }) => Promise<Response>;
@@ -30,7 +30,7 @@ import {
30
30
  sandboxRunFailureDetail,
31
31
  streamSandboxPrompt,
32
32
  turnStorageBindings
33
- } from "./chunk-QMQB725F.js";
33
+ } from "./chunk-Z5M2Z2QK.js";
34
34
  import {
35
35
  redactErrorMessage
36
36
  } from "./chunk-MH74DY2I.js";
@@ -143,13 +143,15 @@ import {
143
143
  composeRouterTurnPromptSections,
144
144
  narratesBefore,
145
145
  runRouterTurn
146
- } from "./chunk-2TEZZXUT.js";
146
+ } from "./chunk-V3YVG7DJ.js";
147
147
  import {
148
+ createIntelligenceTurnTraceReader,
148
149
  createIntelligenceTurnTraceSink,
149
150
  createTurnTrace,
150
151
  formatServerTiming,
151
- otlpTraceId
152
- } from "./chunk-YYA2CVOY.js";
152
+ otlpTraceId,
153
+ turnTraceId
154
+ } from "./chunk-ZZZLYVZX.js";
153
155
  import {
154
156
  readSandboxBinaryBytes,
155
157
  statSandboxFileSize
@@ -2009,6 +2011,57 @@ var INTENT_LINE_TIMEOUT_MS = 1500;
2009
2011
  var INTENT_LINE_HISTORY_MESSAGES = 6;
2010
2012
  var INTENT_LINE_MAX_CHARS = 240;
2011
2013
 
2014
+ // src/chat-routes/turn-trace-route.ts
2015
+ import { deriveExecutionId } from "@tangle-network/agent-runtime/durable";
2016
+ function turnTraceWiring(projectId, turnTrace) {
2017
+ const traceOptions = turnTrace === false ? void 0 : turnTrace;
2018
+ const traceSink = turnTrace === false ? void 0 : traceOptions?.sink ?? createIntelligenceTurnTraceSink({ project: projectId });
2019
+ const traceReader = turnTrace === false ? void 0 : traceOptions?.read ?? (traceOptions?.sink ? void 0 : createIntelligenceTurnTraceReader({ project: projectId }));
2020
+ const traceReceipt = (request, executionId) => ({
2021
+ ...traceSink ? { traceId: otlpTraceId(turnTraceId(executionId)) } : {},
2022
+ ...traceReader ? { traceUrl: `${new URL(request.url).pathname.replace(/\/+$/, "")}/turns/${encodeURIComponent(executionId)}/trace` } : {}
2023
+ });
2024
+ return { traceOptions, traceSink, traceReader, traceReceipt };
2025
+ }
2026
+ function createTurnTraceRoute({ projectId, authorize, reader, log }) {
2027
+ const notFound = (code) => Response.json({ error: "No trace for this turn.", code }, { status: 404, headers: { "Cache-Control": "private, no-store" } });
2028
+ return async (request, params) => {
2029
+ const raw = params.turnId?.trim() ?? "";
2030
+ let executionId;
2031
+ try {
2032
+ executionId = raw.includes(":") ? raw : decodeURIComponent(raw);
2033
+ } catch {
2034
+ return notFound("turn_trace_not_found");
2035
+ }
2036
+ const threadId = executionThreadId(executionId, projectId);
2037
+ if (!threadId) return notFound("turn_trace_not_found");
2038
+ const auth = await authorize({ request, intent: "running", threadId });
2039
+ if (!auth.ok) return auth.response.status === 401 ? auth.response : notFound("turn_trace_not_found");
2040
+ if (auth.intent !== void 0 && auth.intent !== "running") return notFound("turn_trace_not_found");
2041
+ if (!reader) return notFound("turn_trace_unreadable");
2042
+ let exported;
2043
+ try {
2044
+ exported = await reader(executionId, { signal: request.signal });
2045
+ } catch (err) {
2046
+ log("[chat-routes] turn trace read failed", { error: err instanceof Error ? err.message : String(err) });
2047
+ return Response.json({ error: "The trace store did not answer. Try again.", code: "turn_trace_unavailable" }, { status: 502 });
2048
+ }
2049
+ if (!exported) return notFound("turn_trace_not_found");
2050
+ return Response.json(exported, { headers: { "Cache-Control": "private, no-store" } });
2051
+ };
2052
+ }
2053
+ function executionThreadId(executionId, projectId) {
2054
+ const [, session, index] = executionId.split(":");
2055
+ if (!session || !/^\d+$/.test(index ?? "")) return null;
2056
+ try {
2057
+ const threadId = decodeURIComponent(session);
2058
+ const turnExecutionId = deriveExecutionId({ projectId, sessionId: threadId, turnIndex: Number(index) });
2059
+ return executionId === turnExecutionId || executionId.startsWith(`${turnExecutionId}:retry:`) ? threadId : null;
2060
+ } catch {
2061
+ return null;
2062
+ }
2063
+ }
2064
+
2012
2065
  // src/chat-routes/turn-prefetch.ts
2013
2066
  function startTurnPrefetch(prefetch, input) {
2014
2067
  let started;
@@ -2044,7 +2097,7 @@ function startTurnPrefetch(prefetch, input) {
2044
2097
  }
2045
2098
 
2046
2099
  // src/chat-routes/turn-execution.ts
2047
- import { deriveExecutionId, handleChatTurn } from "@tangle-network/agent-runtime/durable";
2100
+ import { deriveExecutionId as deriveExecutionId2, handleChatTurn } from "@tangle-network/agent-runtime/durable";
2048
2101
 
2049
2102
  // src/chat-routes/native-turn-timing.ts
2050
2103
  function createNativeTimingTransfer(read, onError) {
@@ -2351,6 +2404,7 @@ async function runAdmittedTurn({
2351
2404
  progressMessages,
2352
2405
  traceOptions,
2353
2406
  traceSink,
2407
+ traceReceipt,
2354
2408
  startIntentLine,
2355
2409
  log
2356
2410
  }, request, ctx, admitted, early, progress, startedIntent) {
@@ -2505,7 +2559,7 @@ async function runAdmittedTurn({
2505
2559
  scopeId: payload.threadId,
2506
2560
  coalesce: coalesceDeltas
2507
2561
  });
2508
- const turnMarker = { type: "turn", turnId: turnStreamId };
2562
+ const turnMarker = { type: "turn", turnId: turnStreamId, ...traceReceipt(request, executionId) };
2509
2563
  await state.tap.onEvent(turnMarker);
2510
2564
  await stopRenewal();
2511
2565
  if (state.completionHandoff) await state.tap.detach();
@@ -2647,7 +2701,7 @@ async function prepareAdmittedTurn(options, trace, log, tenantId, userId, payloa
2647
2701
  userId,
2648
2702
  turnIndex: chatTurn.turnIndex
2649
2703
  };
2650
- const turnExecutionId = deriveExecutionId({
2704
+ const turnExecutionId = deriveExecutionId2({
2651
2705
  projectId: options.projectId,
2652
2706
  sessionId: payload.threadId,
2653
2707
  turnIndex: chatTurn.turnIndex
@@ -3212,8 +3266,7 @@ function createChatTurnRoutes(input) {
3212
3266
  const draftStore = options.store;
3213
3267
  const draftTuning = storeSupportsDraftPersistence(draftStore) ? {} : null;
3214
3268
  const progressMessages = { ...TURN_ROUTE_PHASE_MESSAGES, ...options.progressMessages };
3215
- const traceOptions = options.turnTrace === false ? void 0 : options.turnTrace;
3216
- const traceSink = options.turnTrace === false ? void 0 : traceOptions?.sink ?? createIntelligenceTurnTraceSink({ project: options.projectId });
3269
+ const { traceOptions, traceSink, traceReader, traceReceipt } = turnTraceWiring(options.projectId, options.turnTrace);
3217
3270
  function startIntentLine(admitted) {
3218
3271
  const intentLine = options.intentLine;
3219
3272
  if (!intentLine) return void 0;
@@ -3255,6 +3308,7 @@ function createChatTurnRoutes(input) {
3255
3308
  progressMessages,
3256
3309
  traceOptions,
3257
3310
  traceSink,
3311
+ traceReceipt,
3258
3312
  startIntentLine,
3259
3313
  log
3260
3314
  });
@@ -3447,6 +3501,7 @@ function createChatTurnRoutes(input) {
3447
3501
  turn: (request, ctx) => turnHost && !ctx?.hosted && ctx?.executionLimits === void 0 && ctx?.cancelOnDisconnect !== true && (request.headers.has("cookie") || request.headers.has("authorization")) ? hostTurn(turnHost, request, ctx) : withD1QueryCount(() => turn(request, ctx)),
3448
3502
  cancel: (request) => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),
3449
3503
  replay,
3504
+ trace: createTurnTraceRoute({ projectId: options.projectId, authorize: options.authorize, reader: traceReader, log }),
3450
3505
  running,
3451
3506
  interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null
3452
3507
  };
@@ -3665,4 +3720,4 @@ export {
3665
3720
  createChatTurnRoutes,
3666
3721
  streamChatRouteAsSandboxEvents
3667
3722
  };
3668
- //# sourceMappingURL=chunk-QSMFN5GJ.js.map
3723
+ //# sourceMappingURL=chunk-GPCQRTWF.js.map