@tangle-network/agent-app 0.43.28 → 0.43.30
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.
- package/dist/chat-routes/index.d.ts +111 -1
- package/dist/chat-routes/index.js +245 -97
- package/dist/chat-routes/index.js.map +1 -1
- package/package.json +2 -1
|
@@ -28,6 +28,16 @@ import '../contract-DYbTzEDf.js';
|
|
|
28
28
|
* Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —
|
|
29
29
|
* no router import. Auth/access is one injected `authorize` seam, composable
|
|
30
30
|
* with `/app-auth` guards but not coupled to them.
|
|
31
|
+
*
|
|
32
|
+
* Five optional product seams let a complex turn-orchestrator compose the
|
|
33
|
+
* vertical instead of hand-rolling a generator — each omittable to the exact
|
|
34
|
+
* behavior above: `turnLock` (single-flight acquire/release around the turn),
|
|
35
|
+
* `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`
|
|
36
|
+
* (observe + augment the producer input), `lifecycle` (deterministic
|
|
37
|
+
* start/complete/error telemetry), `heartbeat` (keepalive during silent
|
|
38
|
+
* producer waits), plus `onRawEvent` (the raw producer events, for telemetry).
|
|
39
|
+
* `handleChatTurn` stays the engine — the seams only wrap its input, its
|
|
40
|
+
* producer stream, and its settle.
|
|
31
41
|
*/
|
|
32
42
|
|
|
33
43
|
/** Usage receipt persisted onto the assistant message (the flattened
|
|
@@ -103,6 +113,86 @@ interface ChatTurnProduceArgs<TContext> {
|
|
|
103
113
|
turnStreamId: string;
|
|
104
114
|
priorMessages: PersistedChatMessageForTurn[];
|
|
105
115
|
}
|
|
116
|
+
/** One event as it crosses the route: the producer's own vocabulary, or an
|
|
117
|
+
* injected keepalive. Same shape the engine forwards verbatim. */
|
|
118
|
+
type ChatRouteEvent = {
|
|
119
|
+
type: string;
|
|
120
|
+
data?: Record<string, unknown>;
|
|
121
|
+
};
|
|
122
|
+
/** Keepalive emitted while the producer is quiet (long tool calls, first-token
|
|
123
|
+
* wait) so client watchdogs stay re-armed. One is emitted each time
|
|
124
|
+
* `intervalMs` elapses with no producer event; the window resets on every real
|
|
125
|
+
* event, so a chatty producer never triggers one. The product owns the event
|
|
126
|
+
* shape (`type` + `data`). Omit → no keepalives (today's behavior). */
|
|
127
|
+
interface ChatTurnHeartbeat {
|
|
128
|
+
intervalMs: number;
|
|
129
|
+
event(info: {
|
|
130
|
+
elapsedMs: number;
|
|
131
|
+
tick: number;
|
|
132
|
+
}): ChatRouteEvent;
|
|
133
|
+
}
|
|
134
|
+
/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted
|
|
135
|
+
* fields keep the route-assembled value; the product's `produce` still owns
|
|
136
|
+
* the system prompt. */
|
|
137
|
+
interface ChatTurnInputPatch {
|
|
138
|
+
prompt?: string | ChatTurnPartInput[];
|
|
139
|
+
priorMessages?: PersistedChatMessageForTurn[];
|
|
140
|
+
}
|
|
141
|
+
/** Pre-turn readiness verdict — proceed, or short-circuit with the product's
|
|
142
|
+
* own `Response` (e.g. a canned assistant reply asking for missing context).
|
|
143
|
+
* Distinct from `authorize`: this gates domain readiness, not access. */
|
|
144
|
+
type ChatTurnGateResult = {
|
|
145
|
+
proceed: true;
|
|
146
|
+
} | {
|
|
147
|
+
proceed: false;
|
|
148
|
+
response: Response;
|
|
149
|
+
};
|
|
150
|
+
/** Single-flight lock verdict — acquired (with an opaque handle passed back to
|
|
151
|
+
* `release`), or already held (short-circuit with the product's 409-style
|
|
152
|
+
* `Response`). */
|
|
153
|
+
type ChatTurnLockResult = {
|
|
154
|
+
acquired: true;
|
|
155
|
+
handle?: unknown;
|
|
156
|
+
} | {
|
|
157
|
+
acquired: false;
|
|
158
|
+
response: Response;
|
|
159
|
+
};
|
|
160
|
+
/** Async acquire/release wrapped around the turn. `acquire` runs before any
|
|
161
|
+
* side effect; `release` runs once when the turn settles — including on a
|
|
162
|
+
* short-circuit or a throw. */
|
|
163
|
+
interface ChatTurnLock<TContext> {
|
|
164
|
+
acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>;
|
|
165
|
+
release(handle: unknown): void | Promise<void>;
|
|
166
|
+
}
|
|
167
|
+
interface ChatTurnLifecycleBase<TContext> {
|
|
168
|
+
identity: ChatTurnIdentity;
|
|
169
|
+
executionId: string;
|
|
170
|
+
turnStreamId: string;
|
|
171
|
+
context: TContext;
|
|
172
|
+
}
|
|
173
|
+
interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {
|
|
174
|
+
startedAt: number;
|
|
175
|
+
}
|
|
176
|
+
interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {
|
|
177
|
+
finalText: string;
|
|
178
|
+
usage: ChatTurnUsage;
|
|
179
|
+
durationMs: number;
|
|
180
|
+
}
|
|
181
|
+
interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {
|
|
182
|
+
error: unknown;
|
|
183
|
+
durationMs: number;
|
|
184
|
+
}
|
|
185
|
+
/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;
|
|
186
|
+
* exactly one of `onTurnComplete` / `onTurnError` fires after the turn
|
|
187
|
+
* settles, always after `onTurnStart`. Failure is derived from the turn's own
|
|
188
|
+
* `error` / `session.run.failed` events (or a drain throw), not the engine's
|
|
189
|
+
* lifecycle envelope. Hook errors are swallowed — telemetry never fails a
|
|
190
|
+
* turn. */
|
|
191
|
+
interface ChatTurnLifecycle<TContext> {
|
|
192
|
+
onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>;
|
|
193
|
+
onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>;
|
|
194
|
+
onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>;
|
|
195
|
+
}
|
|
106
196
|
interface CreateChatTurnRoutesOptions<TContext = void> {
|
|
107
197
|
/** Names the product in `deriveExecutionId` so retries land on the same
|
|
108
198
|
* substrate execution. */
|
|
@@ -121,6 +211,26 @@ interface CreateChatTurnRoutesOptions<TContext = void> {
|
|
|
121
211
|
* wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the
|
|
122
212
|
* product's own producer. May be async (box resolution). */
|
|
123
213
|
produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>;
|
|
214
|
+
/** Single-flight lock acquired before any side effect and released once when
|
|
215
|
+
* the turn settles (including short-circuit/throw). Omit → no lock. */
|
|
216
|
+
turnLock?: ChatTurnLock<TContext>;
|
|
217
|
+
/** Pre-turn readiness gate that can short-circuit with a product `Response`
|
|
218
|
+
* before the producer runs (the user row is already persisted). Runs after
|
|
219
|
+
* `turnLock.acquire`, before `beforeTurn`. Omit → always proceed. */
|
|
220
|
+
contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>;
|
|
221
|
+
/** Observe the assembled producer input and optionally augment it (rewrite
|
|
222
|
+
* the prompt / prior messages) before the producer runs. Omit → no change. */
|
|
223
|
+
beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>;
|
|
224
|
+
/** Deterministic run telemetry (start / complete / error) with identity and
|
|
225
|
+
* timing. Omit → no telemetry. */
|
|
226
|
+
lifecycle?: ChatTurnLifecycle<TContext>;
|
|
227
|
+
/** Keepalive injected while the producer is quiet. Omit → no keepalives. */
|
|
228
|
+
heartbeat?: ChatTurnHeartbeat;
|
|
229
|
+
/** Observe each event the producer emits, before the engine frames it and
|
|
230
|
+
* before any heartbeat injection (the raw sidecar-producer events, for
|
|
231
|
+
* telemetry). Never alters the stream; errors are swallowed. Distinct from
|
|
232
|
+
* `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes. */
|
|
233
|
+
onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>;
|
|
124
234
|
/** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).
|
|
125
235
|
* Live stream is never altered. */
|
|
126
236
|
transformFinalText?(text: string): string | Promise<string>;
|
|
@@ -273,4 +383,4 @@ declare function sanitizeUploadFilename(name: string): string;
|
|
|
273
383
|
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
274
384
|
declare function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response>;
|
|
275
385
|
|
|
276
|
-
export { type ChatTurnAuthorization, type ChatTurnAuthorizeArgs, ChatTurnFilePartInput, type ChatTurnMessageStore, ChatTurnPartInput, type ChatTurnProduceArgs, ChatTurnRequestPayload, type ChatTurnRouteProducer, type ChatTurnRoutes, type ChatTurnUsage, type CreateChatTurnRoutesOptions, type CreateUploadRouteOptions, type SandboxChatProducerOptions, type SandboxUploadSink, UPLOAD_INLINE_MAX_BYTES, UPLOAD_MAX_FILE_BYTES, type UploadAuthorization, type UploadedChatFile, bytesToBase64, createChatTurnRoutes, createSandboxChatProducer, createUploadRoute, sanitizeUploadFilename };
|
|
386
|
+
export { type ChatTurnAuthorization, type ChatTurnAuthorizeArgs, ChatTurnFilePartInput, type ChatTurnGateResult, type ChatTurnHeartbeat, type ChatTurnInputPatch, type ChatTurnLifecycle, type ChatTurnLifecycleComplete, type ChatTurnLifecycleError, type ChatTurnLifecycleStart, type ChatTurnLock, type ChatTurnLockResult, type ChatTurnMessageStore, ChatTurnPartInput, type ChatTurnProduceArgs, ChatTurnRequestPayload, type ChatTurnRouteProducer, type ChatTurnRoutes, type ChatTurnUsage, type CreateChatTurnRoutesOptions, type CreateUploadRouteOptions, type SandboxChatProducerOptions, type SandboxUploadSink, UPLOAD_INLINE_MAX_BYTES, UPLOAD_MAX_FILE_BYTES, type UploadAuthorization, type UploadedChatFile, bytesToBase64, createChatTurnRoutes, createSandboxChatProducer, createUploadRoute, sanitizeUploadFilename };
|
|
@@ -66,6 +66,45 @@ function validateTurnBody(body, maxInlinePartBytes) {
|
|
|
66
66
|
function userPartsWithFiles(userParts, fileParts) {
|
|
67
67
|
return toChatMessageParts([...userParts, ...fileParts.map((part) => ({ ...part }))]);
|
|
68
68
|
}
|
|
69
|
+
async function* tapRawEvents(source, onRawEvent, log) {
|
|
70
|
+
for await (const event of source) {
|
|
71
|
+
try {
|
|
72
|
+
await onRawEvent(event);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
log("[chat-routes] onRawEvent failed", { error: err instanceof Error ? err.message : String(err) });
|
|
75
|
+
}
|
|
76
|
+
yield event;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function* withStreamHeartbeat(source, intervalMs, makeEvent) {
|
|
80
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
81
|
+
try {
|
|
82
|
+
let pending = iterator.next();
|
|
83
|
+
let windowStart = Date.now();
|
|
84
|
+
let tick = 0;
|
|
85
|
+
for (; ; ) {
|
|
86
|
+
let timer;
|
|
87
|
+
const heartbeat = new Promise((resolve) => {
|
|
88
|
+
timer = setTimeout(() => resolve("heartbeat"), intervalMs);
|
|
89
|
+
});
|
|
90
|
+
const winner = await Promise.race([pending.then(() => "event"), heartbeat]);
|
|
91
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
92
|
+
if (winner === "heartbeat") {
|
|
93
|
+
tick += 1;
|
|
94
|
+
yield makeEvent({ elapsedMs: Date.now() - windowStart, tick });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const result = await pending;
|
|
98
|
+
if (result.done) return;
|
|
99
|
+
yield result.value;
|
|
100
|
+
pending = iterator.next();
|
|
101
|
+
windowStart = Date.now();
|
|
102
|
+
tick = 0;
|
|
103
|
+
}
|
|
104
|
+
} finally {
|
|
105
|
+
await iterator.return?.();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
69
108
|
function createChatTurnRoutes(options) {
|
|
70
109
|
const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
|
|
71
110
|
async function turn(request, ctx) {
|
|
@@ -89,14 +128,6 @@ function createChatTurnRoutes(options) {
|
|
|
89
128
|
parts: m.parts ?? null
|
|
90
129
|
}));
|
|
91
130
|
const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId });
|
|
92
|
-
if (chatTurn.shouldInsertUserMessage) {
|
|
93
|
-
await options.store.appendMessage({
|
|
94
|
-
threadId: payload.threadId,
|
|
95
|
-
role: "user",
|
|
96
|
-
content,
|
|
97
|
-
parts: userPartsWithFiles(chatTurn.userParts, fileParts)
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
131
|
const identity = {
|
|
101
132
|
tenantId,
|
|
102
133
|
sessionId: payload.threadId,
|
|
@@ -110,104 +141,221 @@ function createChatTurnRoutes(options) {
|
|
|
110
141
|
});
|
|
111
142
|
const turnStreamId = crypto.randomUUID();
|
|
112
143
|
const prompt = fileParts.length === 0 ? content : content ? [{ type: "text", text: content }, ...fileParts] : [...fileParts];
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
scopeId: payload.threadId,
|
|
117
|
-
coalesce: options.coalesceTurnEvents ?? coalesceDeltas
|
|
118
|
-
});
|
|
119
|
-
const turnMarker = { type: "turn", turnId: turnStreamId };
|
|
120
|
-
await tap.onEvent(turnMarker);
|
|
121
|
-
let producer;
|
|
122
|
-
let runFailed = false;
|
|
123
|
-
const result = handleChatTurn({
|
|
144
|
+
let produceArgs = {
|
|
145
|
+
request,
|
|
146
|
+
body: payload,
|
|
124
147
|
identity,
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
prompt,
|
|
138
|
-
executionId,
|
|
139
|
-
turnStreamId,
|
|
140
|
-
priorMessages: chatTurn.priorMessages
|
|
141
|
-
});
|
|
142
|
-
for await (const event of producer.stream) yield event;
|
|
143
|
-
})(),
|
|
144
|
-
finalText: () => producer?.finalText() ?? ""
|
|
145
|
-
}),
|
|
146
|
-
onEvent: async (event) => {
|
|
147
|
-
if (event.type === "session.run.failed" || event.type === "error") runFailed = true;
|
|
148
|
-
await tap.onEvent(event);
|
|
149
|
-
if (options.onEvent) await options.onEvent(event, context);
|
|
150
|
-
},
|
|
151
|
-
...options.transformFinalText ? { transformFinalText: options.transformFinalText } : {},
|
|
152
|
-
persistAssistantMessage: async ({ finalText }) => {
|
|
153
|
-
const parts = producer?.assistantParts ? toChatMessageParts(producer.assistantParts()) : void 0;
|
|
154
|
-
if (!finalText.trim() && (!parts || parts.length === 0)) return;
|
|
155
|
-
const usage = producer?.usage?.() ?? {};
|
|
156
|
-
await options.store.appendMessage({
|
|
157
|
-
threadId: payload.threadId,
|
|
158
|
-
role: "assistant",
|
|
159
|
-
content: finalText,
|
|
160
|
-
...parts && parts.length > 0 ? { parts } : {},
|
|
161
|
-
...producer?.model ? { model: producer.model } : {},
|
|
162
|
-
...usage.inputTokens !== void 0 ? { inputTokens: usage.inputTokens } : {},
|
|
163
|
-
...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {},
|
|
164
|
-
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
165
|
-
...usage.cacheReadTokens !== void 0 ? { cacheReadTokens: usage.cacheReadTokens } : {},
|
|
166
|
-
...usage.cacheWriteTokens !== void 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {},
|
|
167
|
-
...usage.costUsd !== void 0 ? { costUsd: usage.costUsd } : {}
|
|
168
|
-
});
|
|
169
|
-
},
|
|
170
|
-
...options.onTurnComplete ? {
|
|
171
|
-
onTurnComplete: ({ identity: turnIdentity, finalText }) => options.onTurnComplete({ identity: turnIdentity, finalText, context })
|
|
172
|
-
} : {},
|
|
173
|
-
...options.traceFlush ? { traceFlush: () => options.traceFlush(context) } : {}
|
|
174
|
-
}
|
|
175
|
-
});
|
|
176
|
-
const [clientBody, drainBody] = result.body.tee();
|
|
177
|
-
const drained = (async () => {
|
|
178
|
-
const reader = drainBody.getReader();
|
|
148
|
+
context,
|
|
149
|
+
prompt,
|
|
150
|
+
executionId,
|
|
151
|
+
turnStreamId,
|
|
152
|
+
priorMessages: chatTurn.priorMessages
|
|
153
|
+
};
|
|
154
|
+
let lockAcquired = false;
|
|
155
|
+
let lockHandle;
|
|
156
|
+
let lockReleased = false;
|
|
157
|
+
const releaseLock = async () => {
|
|
158
|
+
if (!lockAcquired || lockReleased) return;
|
|
159
|
+
lockReleased = true;
|
|
179
160
|
try {
|
|
180
|
-
|
|
181
|
-
const { done } = await reader.read();
|
|
182
|
-
if (done) break;
|
|
183
|
-
}
|
|
184
|
-
await tap.done(runFailed ? "error" : "complete");
|
|
161
|
+
await options.turnLock.release(lockHandle);
|
|
185
162
|
} catch (err) {
|
|
186
|
-
|
|
187
|
-
log("[chat-routes] turn drain failed", {
|
|
163
|
+
log("[chat-routes] turnLock.release failed", {
|
|
188
164
|
turnId: turnStreamId,
|
|
189
165
|
error: err instanceof Error ? err.message : String(err)
|
|
190
166
|
});
|
|
191
167
|
}
|
|
192
|
-
}
|
|
193
|
-
if (
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
168
|
+
};
|
|
169
|
+
if (options.turnLock) {
|
|
170
|
+
const acquired = await options.turnLock.acquire(produceArgs);
|
|
171
|
+
if (!acquired.acquired) return acquired.response;
|
|
172
|
+
lockAcquired = true;
|
|
173
|
+
lockHandle = acquired.handle;
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
if (chatTurn.shouldInsertUserMessage) {
|
|
177
|
+
await options.store.appendMessage({
|
|
178
|
+
threadId: payload.threadId,
|
|
179
|
+
role: "user",
|
|
180
|
+
content,
|
|
181
|
+
parts: userPartsWithFiles(chatTurn.userParts, fileParts)
|
|
182
|
+
});
|
|
202
183
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
184
|
+
if (options.contextGate) {
|
|
185
|
+
const gate = await options.contextGate(produceArgs);
|
|
186
|
+
if (!gate.proceed) {
|
|
187
|
+
await releaseLock();
|
|
188
|
+
return gate.response;
|
|
189
|
+
}
|
|
209
190
|
}
|
|
210
|
-
|
|
191
|
+
if (options.beforeTurn) {
|
|
192
|
+
const patch = await options.beforeTurn(produceArgs);
|
|
193
|
+
if (patch) produceArgs = { ...produceArgs, ...patch };
|
|
194
|
+
}
|
|
195
|
+
const tap = createBufferedTurnTap({
|
|
196
|
+
store: options.turnStore,
|
|
197
|
+
turnId: turnStreamId,
|
|
198
|
+
scopeId: payload.threadId,
|
|
199
|
+
coalesce: options.coalesceTurnEvents ?? coalesceDeltas
|
|
200
|
+
});
|
|
201
|
+
const turnMarker = { type: "turn", turnId: turnStreamId };
|
|
202
|
+
await tap.onEvent(turnMarker);
|
|
203
|
+
let producer;
|
|
204
|
+
let runFailed = false;
|
|
205
|
+
let lastFailureData;
|
|
206
|
+
const turnStartedAtMs = Date.now();
|
|
207
|
+
if (options.lifecycle?.onTurnStart) {
|
|
208
|
+
try {
|
|
209
|
+
await options.lifecycle.onTurnStart({
|
|
210
|
+
identity,
|
|
211
|
+
executionId,
|
|
212
|
+
turnStreamId,
|
|
213
|
+
context,
|
|
214
|
+
startedAt: turnStartedAtMs
|
|
215
|
+
});
|
|
216
|
+
} catch (err) {
|
|
217
|
+
log("[chat-routes] lifecycle.onTurnStart failed", {
|
|
218
|
+
turnId: turnStreamId,
|
|
219
|
+
error: err instanceof Error ? err.message : String(err)
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const result = handleChatTurn({
|
|
224
|
+
identity,
|
|
225
|
+
waitUntil: ctx?.waitUntil,
|
|
226
|
+
log,
|
|
227
|
+
hooks: {
|
|
228
|
+
// The engine wants a synchronous producer; box resolution is async —
|
|
229
|
+
// defer it into the generator's first pull.
|
|
230
|
+
produce: () => ({
|
|
231
|
+
stream: (async function* () {
|
|
232
|
+
producer = await options.produce(produceArgs);
|
|
233
|
+
let source = producer.stream;
|
|
234
|
+
if (options.onRawEvent) {
|
|
235
|
+
source = tapRawEvents(source, (event) => options.onRawEvent(event, context), log);
|
|
236
|
+
}
|
|
237
|
+
if (options.heartbeat) {
|
|
238
|
+
source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event);
|
|
239
|
+
}
|
|
240
|
+
for await (const event of source) yield event;
|
|
241
|
+
})(),
|
|
242
|
+
finalText: () => producer?.finalText() ?? ""
|
|
243
|
+
}),
|
|
244
|
+
onEvent: async (event) => {
|
|
245
|
+
if (event.type === "session.run.failed" || event.type === "error") {
|
|
246
|
+
runFailed = true;
|
|
247
|
+
lastFailureData = event.data;
|
|
248
|
+
}
|
|
249
|
+
await tap.onEvent(event);
|
|
250
|
+
if (options.onEvent) await options.onEvent(event, context);
|
|
251
|
+
},
|
|
252
|
+
...options.transformFinalText ? { transformFinalText: options.transformFinalText } : {},
|
|
253
|
+
persistAssistantMessage: async ({ finalText }) => {
|
|
254
|
+
const parts = producer?.assistantParts ? toChatMessageParts(producer.assistantParts()) : void 0;
|
|
255
|
+
if (!finalText.trim() && (!parts || parts.length === 0)) return;
|
|
256
|
+
const usage = producer?.usage?.() ?? {};
|
|
257
|
+
await options.store.appendMessage({
|
|
258
|
+
threadId: payload.threadId,
|
|
259
|
+
role: "assistant",
|
|
260
|
+
content: finalText,
|
|
261
|
+
...parts && parts.length > 0 ? { parts } : {},
|
|
262
|
+
...producer?.model ? { model: producer.model } : {},
|
|
263
|
+
...usage.inputTokens !== void 0 ? { inputTokens: usage.inputTokens } : {},
|
|
264
|
+
...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {},
|
|
265
|
+
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
266
|
+
...usage.cacheReadTokens !== void 0 ? { cacheReadTokens: usage.cacheReadTokens } : {},
|
|
267
|
+
...usage.cacheWriteTokens !== void 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {},
|
|
268
|
+
...usage.costUsd !== void 0 ? { costUsd: usage.costUsd } : {}
|
|
269
|
+
});
|
|
270
|
+
},
|
|
271
|
+
...options.onTurnComplete ? {
|
|
272
|
+
onTurnComplete: ({ identity: turnIdentity, finalText }) => options.onTurnComplete({ identity: turnIdentity, finalText, context })
|
|
273
|
+
} : {},
|
|
274
|
+
...options.traceFlush ? { traceFlush: () => options.traceFlush(context) } : {}
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
const fireTerminalLifecycle = async (failed, drainError) => {
|
|
278
|
+
const lifecycle = options.lifecycle;
|
|
279
|
+
if (!lifecycle) return;
|
|
280
|
+
const durationMs = Date.now() - turnStartedAtMs;
|
|
281
|
+
try {
|
|
282
|
+
if (failed) {
|
|
283
|
+
await lifecycle.onTurnError?.({
|
|
284
|
+
identity,
|
|
285
|
+
executionId,
|
|
286
|
+
turnStreamId,
|
|
287
|
+
context,
|
|
288
|
+
durationMs,
|
|
289
|
+
error: drainError ?? lastFailureData ?? new Error("chat turn failed")
|
|
290
|
+
});
|
|
291
|
+
} else {
|
|
292
|
+
await lifecycle.onTurnComplete?.({
|
|
293
|
+
identity,
|
|
294
|
+
executionId,
|
|
295
|
+
turnStreamId,
|
|
296
|
+
context,
|
|
297
|
+
durationMs,
|
|
298
|
+
finalText: producer?.finalText() ?? "",
|
|
299
|
+
usage: producer?.usage?.() ?? {}
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
} catch (err) {
|
|
303
|
+
log("[chat-routes] lifecycle terminal hook failed", {
|
|
304
|
+
turnId: turnStreamId,
|
|
305
|
+
error: err instanceof Error ? err.message : String(err)
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const [clientBody, drainBody] = result.body.tee();
|
|
310
|
+
const drained = (async () => {
|
|
311
|
+
const reader = drainBody.getReader();
|
|
312
|
+
let drainError;
|
|
313
|
+
try {
|
|
314
|
+
for (; ; ) {
|
|
315
|
+
const { done } = await reader.read();
|
|
316
|
+
if (done) break;
|
|
317
|
+
}
|
|
318
|
+
} catch (err) {
|
|
319
|
+
drainError = err;
|
|
320
|
+
log("[chat-routes] turn drain failed", {
|
|
321
|
+
turnId: turnStreamId,
|
|
322
|
+
error: err instanceof Error ? err.message : String(err)
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
const failed = runFailed || drainError !== void 0;
|
|
326
|
+
try {
|
|
327
|
+
await tap.done(failed ? "error" : "complete");
|
|
328
|
+
} catch (err) {
|
|
329
|
+
log("[chat-routes] turn buffer finalize failed", {
|
|
330
|
+
turnId: turnStreamId,
|
|
331
|
+
error: err instanceof Error ? err.message : String(err)
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
await fireTerminalLifecycle(failed, drainError);
|
|
335
|
+
await releaseLock();
|
|
336
|
+
})();
|
|
337
|
+
if (ctx?.waitUntil) ctx.waitUntil(drained);
|
|
338
|
+
else void drained.catch(() => {
|
|
339
|
+
});
|
|
340
|
+
const encoder = new TextEncoder();
|
|
341
|
+
const marker = new ReadableStream({
|
|
342
|
+
start(controller) {
|
|
343
|
+
controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}
|
|
344
|
+
`));
|
|
345
|
+
controller.close();
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
const body = concatStreams([marker, clientBody]);
|
|
349
|
+
return new Response(body, {
|
|
350
|
+
headers: {
|
|
351
|
+
"Content-Type": result.contentType,
|
|
352
|
+
"Cache-Control": "no-cache"
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
} catch (err) {
|
|
356
|
+
await releaseLock();
|
|
357
|
+
throw err;
|
|
358
|
+
}
|
|
211
359
|
}
|
|
212
360
|
async function replay(request, params) {
|
|
213
361
|
const turnId = params.turnId?.trim();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/chat-routes/turn-routes.ts","../../src/chat-routes/sandbox-producer.ts","../../src/chat-routes/upload.ts"],"sourcesContent":["/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n */\n\nimport { deriveExecutionId, handleChatTurn } from '@tangle-network/agent-runtime'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n model?: string\n}\n\nexport type ChatTurnAuthorization<TContext> =\n | { ok: true; tenantId: string; userId: string; context: TContext }\n | { ok: false; response: Response }\n\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n}\n\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n}\n\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Post-processing after a successful turn (billing, titles, audit). Errors\n * are swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string; context: TContext }): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n if (!content && fileParts.length === 0) {\n throw new ChatTurnInputError('Missing content (send text, parts, or both)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n payload: { ...body, threadId, content } as ChatTurnRequestPayload,\n content,\n fileParts,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. The typed\n * projection is `/chat-store`'s (same boundary as the assistant hop). */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n): ChatMessagePart[] {\n return toChatMessageParts([...userParts, ...fileParts.map((part) => ({ ...part }))])\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n async function turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId })\n\n if (chatTurn.shouldInsertUserMessage) {\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts),\n })\n }\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n let producer: ChatTurnRouteProducer | undefined\n let runFailed = false\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce({\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n })\n for await (const event of producer.stream) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') runFailed = true\n await tap.onEvent(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here).\n const parts = producer?.assistantParts ? toChatMessageParts(producer.assistantParts()) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) return\n const usage = producer?.usage?.() ?? {}\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n })\n },\n ...(options.onTurnComplete\n ? {\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) =>\n options.onTurnComplete!({ identity: turnIdentity, finalText, context }),\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n await tap.done(runFailed ? 'error' : 'complete')\n } catch (err) {\n await tap.done('error')\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n controller.enqueue(encoder.encode(`${value.event}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n return {\n turn,\n replay,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `interaction`). Legal and tax each hand-rolled this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport {\n isRenderableInteractionKind,\n parseInteractionRequest,\n} from '../interactions/contract'\nimport {\n asRecord,\n asString,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`). */\n events: AsyncIterable<unknown>\n /** Recorded on the persisted assistant message. */\n model?: string\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan. */\n isRenderableInteraction?: (kind: string) => boolean\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, non-renderable asks are only\n * logged — the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction usageFromStepFinish(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost\n}\n\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n let fullText = ''\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n const usage: ChatTurnUsage = {}\n /** Tool ids already announced as `tool_call` / settled as `tool_result`. */\n const announcedTools = new Set<string>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n let stepCounter = 0\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const raw of options.events) {\n const record = asRecord(raw)\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event = normalized.type === 'message.part.updated' ? normalized : (record as unknown as StreamEvent)\n\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) continue\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'text') fullText += delta\n yield { type: partType, text: delta } as StreamEvent & { text: string }\n }\n continue\n }\n\n if (partType === 'tool') {\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n if (toolId && !announcedTools.has(toolId)) {\n announcedTools.add(toolId)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args: asRecord(state?.input) ?? {} },\n } as StreamEvent\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-finish') {\n usageFromStepFinish(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield { type: 'usage', usage: { promptTokens, completionTokens } } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${stepCounter}`)\n continue\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind)) {\n yield event\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n continue\n }\n\n if (event.type === 'result') {\n const finalText = asString(event.data?.finalText)\n if (finalText) fullText = finalText\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n continue\n }\n\n // Everything else (interaction.cancel, error, lifecycle) forwards\n // verbatim — the client parser ignores unknown types.\n yield event\n }\n }\n\n return {\n stream: stream(),\n finalText: () => fullText,\n assistantParts: () => finalizeAssistantParts(partOrder, partMap, fullText),\n usage: () => usage,\n ...(options.model ? { model: options.model } : {}),\n }\n}\n","/**\n * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Workspace directory for path-ref files. Default `'uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const uploadDir = (auth.uploadDir ?? options.uploadDir ?? 'uploads').replace(/\\/+$/, '')\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,mBAAmB,sBAAsB;AAgKlD,SAAS,cAAc,KAAmC;AACxD,SAAO,SAAS,KAAK,EAAE,MAAM,IAAI,MAAM,OAAO,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,OAAO,CAAC;AACrF;AASA,SAAS,iBAAiB,MAA+B,oBAAwD;AAC/G,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;AAC5E,MAAI,CAAC,SAAU,OAAM,IAAI,mBAAmB,kBAAkB;AAC9D,QAAM,aAAa,KAAK,WAAW,KAAK,WAAW;AACnD,MAAI,OAAO,eAAe,SAAU,OAAM,IAAI,mBAAmB,0BAA0B;AAC3F,QAAM,UAAU,WAAW,KAAK;AAChC,QAAM,YAAY,mBAAmB,KAAK,KAAK;AAC/C,MAAI,CAAC,WAAW,UAAU,WAAW,GAAG;AACtC,UAAM,IAAI,mBAAmB,6CAA6C;AAAA,EAC5E;AACA,6BAA2B,WAAW,kBAAkB;AACxD,MAAI;AACJ,MAAI;AACF,aAAS,sBAAsB,KAAK,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,IAAI,mBAAmB,eAAe,QAAQ,IAAI,UAAU,gBAAgB;AAAA,EACpF;AACA,SAAO;AAAA,IACL,SAAS,EAAE,GAAG,MAAM,UAAU,QAAQ;AAAA,IACtC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAKA,SAAS,mBACP,WACA,WACmB;AACnB,SAAO,mBAAmB,CAAC,GAAG,WAAW,GAAG,UAAU,IAAI,CAAC,UAAU,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;AACrF;AAIO,SAAS,qBACd,SACgB;AAChB,QAAM,MAAM,QAAQ,QAAQ,CA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AO;AAAA,UACL;AAAA,UACA;AAAA,UACA,GAAG,IAAI,OAAO,KAAK,IAAI,eAAe,cAAc;AAAA,QACtD;AAAA,MACF;AACA,YAAM,OAAO,GAAG,SAAS,IAAI,EAAE,IAAI,IAAI;AACvC,YAAM,SAAS,cAAc,IAAI,WAAW,MAAM,KAAK,YAAY,CAAC,CAAC;AACrE,YAAM,KAAK,MAAM,MAAM,QAAQ,EAAE,UAAU,SAAS,CAAC;AACrD,eAAS,KAAK;AAAA,QACZ;AAAA,QACA;AAAA,QACA,MAAM,KAAK;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,QACR,MAAM,EAAE,MAAM,UAAU,UAAU,MAAM,WAAW,KAAK;AAAA,MAC1D,CAAC;AAAA,IACH;AAEA,WAAO,SAAS,KAAK,EAAE,OAAO,SAAS,CAAC;AAAA,EAC1C;AACF;","names":["base64"]}
|
|
1
|
+
{"version":3,"sources":["../../src/chat-routes/turn-routes.ts","../../src/chat-routes/sandbox-producer.ts","../../src/chat-routes/upload.ts"],"sourcesContent":["/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n *\n * Five optional product seams let a complex turn-orchestrator compose the\n * vertical instead of hand-rolling a generator — each omittable to the exact\n * behavior above: `turnLock` (single-flight acquire/release around the turn),\n * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`\n * (observe + augment the producer input), `lifecycle` (deterministic\n * start/complete/error telemetry), `heartbeat` (keepalive during silent\n * producer waits), plus `onRawEvent` (the raw producer events, for telemetry).\n * `handleChatTurn` stays the engine — the seams only wrap its input, its\n * producer stream, and its settle.\n */\n\nimport { deriveExecutionId, handleChatTurn } from '@tangle-network/agent-runtime'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n model?: string\n}\n\nexport type ChatTurnAuthorization<TContext> =\n | { ok: true; tenantId: string; userId: string; context: TContext }\n | { ok: false; response: Response }\n\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n}\n\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n}\n\n/** One event as it crosses the route: the producer's own vocabulary, or an\n * injected keepalive. Same shape the engine forwards verbatim. */\ntype ChatRouteEvent = { type: string; data?: Record<string, unknown> }\n\n/** Keepalive emitted while the producer is quiet (long tool calls, first-token\n * wait) so client watchdogs stay re-armed. One is emitted each time\n * `intervalMs` elapses with no producer event; the window resets on every real\n * event, so a chatty producer never triggers one. The product owns the event\n * shape (`type` + `data`). Omit → no keepalives (today's behavior). */\nexport interface ChatTurnHeartbeat {\n intervalMs: number\n event(info: { elapsedMs: number; tick: number }): ChatRouteEvent\n}\n\n/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted\n * fields keep the route-assembled value; the product's `produce` still owns\n * the system prompt. */\nexport interface ChatTurnInputPatch {\n prompt?: string | ChatTurnPartInput[]\n priorMessages?: PersistedChatMessageForTurn[]\n}\n\n/** Pre-turn readiness verdict — proceed, or short-circuit with the product's\n * own `Response` (e.g. a canned assistant reply asking for missing context).\n * Distinct from `authorize`: this gates domain readiness, not access. */\nexport type ChatTurnGateResult =\n | { proceed: true }\n | { proceed: false; response: Response }\n\n/** Single-flight lock verdict — acquired (with an opaque handle passed back to\n * `release`), or already held (short-circuit with the product's 409-style\n * `Response`). */\nexport type ChatTurnLockResult =\n | { acquired: true; handle?: unknown }\n | { acquired: false; response: Response }\n\n/** Async acquire/release wrapped around the turn. `acquire` runs before any\n * side effect; `release` runs once when the turn settles — including on a\n * short-circuit or a throw. */\nexport interface ChatTurnLock<TContext> {\n acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n}\nexport interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {\n startedAt: number\n}\nexport interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {\n finalText: string\n usage: ChatTurnUsage\n durationMs: number\n}\nexport interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {\n error: unknown\n durationMs: number\n}\n\n/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;\n * exactly one of `onTurnComplete` / `onTurnError` fires after the turn\n * settles, always after `onTurnStart`. Failure is derived from the turn's own\n * `error` / `session.run.failed` events (or a drain throw), not the engine's\n * lifecycle envelope. Hook errors are swallowed — telemetry never fails a\n * turn. */\nexport interface ChatTurnLifecycle<TContext> {\n onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>\n onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>\n onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>\n}\n\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Single-flight lock acquired before any side effect and released once when\n * the turn settles (including short-circuit/throw). Omit → no lock. */\n turnLock?: ChatTurnLock<TContext>\n /** Pre-turn readiness gate that can short-circuit with a product `Response`\n * before the producer runs (the user row is already persisted). Runs after\n * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed. */\n contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>\n /** Observe the assembled producer input and optionally augment it (rewrite\n * the prompt / prior messages) before the producer runs. Omit → no change. */\n beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>\n /** Deterministic run telemetry (start / complete / error) with identity and\n * timing. Omit → no telemetry. */\n lifecycle?: ChatTurnLifecycle<TContext>\n /** Keepalive injected while the producer is quiet. Omit → no keepalives. */\n heartbeat?: ChatTurnHeartbeat\n /** Observe each event the producer emits, before the engine frames it and\n * before any heartbeat injection (the raw sidecar-producer events, for\n * telemetry). Never alters the stream; errors are swallowed. Distinct from\n * `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes. */\n onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Post-processing after a successful turn (billing, titles, audit). Errors\n * are swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string; context: TContext }): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n if (!content && fileParts.length === 0) {\n throw new ChatTurnInputError('Missing content (send text, parts, or both)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n payload: { ...body, threadId, content } as ChatTurnRequestPayload,\n content,\n fileParts,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. The typed\n * projection is `/chat-store`'s (same boundary as the assistant hop). */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n): ChatMessagePart[] {\n return toChatMessageParts([...userParts, ...fileParts.map((part) => ({ ...part }))])\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nasync function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nasync function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n const winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n if (timer !== undefined) clearTimeout(timer)\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n async function turn(request: Request, ctx?: { waitUntil?(p: Promise<unknown>): void }): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // The producer input every pre-turn seam reads (and `beforeTurn` may\n // rewrite). Mutated in place before the producer's deferred first pull.\n let produceArgs: ChatTurnProduceArgs<TContext> = {\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n }\n\n // Single-flight lock: acquire before any side effect. `release` runs\n // exactly once — in the drain's `finally` on a normal turn, or right here\n // on a short-circuit / throw.\n let lockAcquired = false\n let lockHandle: unknown\n let lockReleased = false\n const releaseLock = async (): Promise<void> => {\n if (!lockAcquired || lockReleased) return\n lockReleased = true\n try {\n await options.turnLock!.release(lockHandle)\n } catch (err) {\n log('[chat-routes] turnLock.release failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n if (options.turnLock) {\n const acquired = await options.turnLock.acquire(produceArgs)\n if (!acquired.acquired) return acquired.response\n lockAcquired = true\n lockHandle = acquired.handle\n }\n\n try {\n if (chatTurn.shouldInsertUserMessage) {\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts),\n })\n }\n\n // Domain-readiness gate: may short-circuit with the product's own\n // response before the producer runs. The user row above is kept (a real\n // user turn); the gate's response is the assistant side of it.\n if (options.contextGate) {\n const gate = await options.contextGate(produceArgs)\n if (!gate.proceed) {\n await releaseLock()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n if (options.beforeTurn) {\n const patch = await options.beforeTurn(produceArgs)\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n let producer: ChatTurnRouteProducer | undefined\n let runFailed = false\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n let lastFailureData: Record<string, unknown> | undefined\n\n const turnStartedAtMs = Date.now()\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce(produceArgs)\n let source: AsyncIterable<ChatRouteEvent> = producer.stream\n if (options.onRawEvent) {\n source = tapRawEvents(source, (event) => options.onRawEvent!(event, context), log)\n }\n if (options.heartbeat) {\n source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event)\n }\n for await (const event of source) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') {\n runFailed = true\n lastFailureData = event.data\n }\n await tap.onEvent(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here).\n const parts = producer?.assistantParts ? toChatMessageParts(producer.assistantParts()) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) return\n const usage = producer?.usage?.() ?? {}\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n })\n },\n ...(options.onTurnComplete\n ? {\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) =>\n options.onTurnComplete!({ identity: turnIdentity, finalText, context }),\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Exactly one terminal lifecycle hook, after the turn settles. Failure is\n // this route's own verdict (`runFailed` from error/failed events, or a\n // drain throw), not the engine's envelope.\n const fireTerminalLifecycle = async (failed: boolean, drainError: unknown): Promise<void> => {\n const lifecycle = options.lifecycle\n if (!lifecycle) return\n const durationMs = Date.now() - turnStartedAtMs\n try {\n if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs,\n error: drainError ?? lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n await lifecycle.onTurnComplete?.({\n identity, executionId, turnStreamId, context, durationMs,\n finalText: producer?.finalText() ?? '',\n usage: producer?.usage?.() ?? {},\n })\n }\n } catch (err) {\n log('[chat-routes] lifecycle terminal hook failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n let drainError: unknown\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n } catch (err) {\n drainError = err\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n const failed = runFailed || drainError !== undefined\n try {\n await tap.done(failed ? 'error' : 'complete')\n } catch (err) {\n log('[chat-routes] turn buffer finalize failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n },\n })\n } catch (err) {\n // A throw before the turn began streaming (user-insert, gate, beforeTurn,\n // lifecycle-start, tap setup): release the lock, then propagate.\n await releaseLock()\n throw err\n }\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n controller.enqueue(encoder.encode(`${value.event}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n return {\n turn,\n replay,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `interaction`). Legal and tax each hand-rolled this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport {\n isRenderableInteractionKind,\n parseInteractionRequest,\n} from '../interactions/contract'\nimport {\n asRecord,\n asString,\n finalizeAssistantParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\n\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`). */\n events: AsyncIterable<unknown>\n /** Recorded on the persisted assistant message. */\n model?: string\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan. */\n isRenderableInteraction?: (kind: string) => boolean\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, non-renderable asks are only\n * logged — the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction usageFromStepFinish(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost\n}\n\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n let fullText = ''\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n const usage: ChatTurnUsage = {}\n /** Tool ids already announced as `tool_call` / settled as `tool_result`. */\n const announcedTools = new Set<string>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n let stepCounter = 0\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n async function* stream(): AsyncGenerator<StreamEvent, void, unknown> {\n for await (const raw of options.events) {\n const record = asRecord(raw)\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event = normalized.type === 'message.part.updated' ? normalized : (record as unknown as StreamEvent)\n\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) continue\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'text') fullText += delta\n yield { type: partType, text: delta } as StreamEvent & { text: string }\n }\n continue\n }\n\n if (partType === 'tool') {\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n if (toolId && !announcedTools.has(toolId)) {\n announcedTools.add(toolId)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args: asRecord(state?.input) ?? {} },\n } as StreamEvent\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-finish') {\n usageFromStepFinish(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield { type: 'usage', usage: { promptTokens, completionTokens } } as StreamEvent\n }\n continue\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${stepCounter}`)\n continue\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind)) {\n yield event\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n continue\n }\n\n if (event.type === 'result') {\n const finalText = asString(event.data?.finalText)\n if (finalText) fullText = finalText\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n continue\n }\n\n // Everything else (interaction.cancel, error, lifecycle) forwards\n // verbatim — the client parser ignores unknown types.\n yield event\n }\n }\n\n return {\n stream: stream(),\n finalText: () => fullText,\n assistantParts: () => finalizeAssistantParts(partOrder, partMap, fullText),\n usage: () => usage,\n ...(options.model ? { model: options.model } : {}),\n }\n}\n","/**\n * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Workspace directory for path-ref files. Default `'uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const uploadDir = (auth.uploadDir ?? options.uploadDir ?? 'uploads').replace(/\\/+$/, '')\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,mBAAmB,sBAAsB;AA+PlD,SAAS,cAAc,KAAmC;AACxD,SAAO,SAAS,KAAK,EAAE,MAAM,IAAI,MAAM,OAAO,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,OAAO,CAAC;AACrF;AASA,SAAS,iBAAiB,MAA+B,oBAAwD;AAC/G,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;AAC5E,MAAI,CAAC,SAAU,OAAM,IAAI,mBAAmB,kBAAkB;AAC9D,QAAM,aAAa,KAAK,WAAW,KAAK,WAAW;AACnD,MAAI,OAAO,eAAe,SAAU,OAAM,IAAI,mBAAmB,0BAA0B;AAC3F,QAAM,UAAU,WAAW,KAAK;AAChC,QAAM,YAAY,mBAAmB,KAAK,KAAK;AAC/C,MAAI,CAAC,WAAW,UAAU,WAAW,GAAG;AACtC,UAAM,IAAI,mBAAmB,6CAA6C;AAAA,EAC5E;AACA,6BAA2B,WAAW,kBAAkB;AACxD,MAAI;AACJ,MAAI;AACF,aAAS,sBAAsB,KAAK,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,IAAI,mBAAmB,eAAe,QAAQ,IAAI,UAAU,gBAAgB;AAAA,EACpF;AACA,SAAO;AAA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ACD;AAAA,MACF;AAEA,UAAI,CAAC,MAAM;AACT,eAAO;AAAA,UACL;AAAA,UACA;AAAA,UACA,GAAG,IAAI,OAAO,KAAK,IAAI,eAAe,cAAc;AAAA,QACtD;AAAA,MACF;AACA,YAAM,OAAO,GAAG,SAAS,IAAI,EAAE,IAAI,IAAI;AACvC,YAAM,SAAS,cAAc,IAAI,WAAW,MAAM,KAAK,YAAY,CAAC,CAAC;AACrE,YAAM,KAAK,MAAM,MAAM,QAAQ,EAAE,UAAU,SAAS,CAAC;AACrD,eAAS,KAAK;AAAA,QACZ;AAAA,QACA;AAAA,QACA,MAAM,KAAK;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,QACR,MAAM,EAAE,MAAM,UAAU,UAAU,MAAM,WAAW,KAAK;AAAA,MAC1D,CAAC;AAAA,IACH;AAEA,WAAO,SAAS,KAAK,EAAE,OAAO,SAAS,CAAC;AAAA,EAC1C;AACF;","names":["base64"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.43.
|
|
3
|
+
"version": "0.43.30",
|
|
4
4
|
"packageManager": "pnpm@10.33.4",
|
|
5
5
|
"description": "Application-shell framework for Tangle agent products: a bounded tool loop, the structured agent→app tool side channel, integration-hub client, per-workspace billing, and crypto — composed over the Tangle agent substrate through typed seams.",
|
|
6
6
|
"keywords": [
|
|
@@ -385,6 +385,7 @@
|
|
|
385
385
|
"knip": "knip"
|
|
386
386
|
},
|
|
387
387
|
"devDependencies": {
|
|
388
|
+
"@cloudflare/workers-types": "^4.20250620.0",
|
|
388
389
|
"@radix-ui/react-dialog": "^1.1.15",
|
|
389
390
|
"@tangle-network/agent-eval": "^0.100.0",
|
|
390
391
|
"@tangle-network/agent-integrations": "^0.44.0",
|