@tangle-network/agent-runtime 0.84.0 → 0.85.0

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.
@@ -24,8 +24,12 @@ import {
24
24
  stringifySafe,
25
25
  zeroTokenUsage
26
26
  } from "./chunk-BZF3KQ6G.js";
27
+ import {
28
+ mapSandboxEvent
29
+ } from "./chunk-4J6RBI3K.js";
27
30
  import {
28
31
  AnalystError,
32
+ BackendTransportError,
29
33
  PlannerError,
30
34
  ValidationError
31
35
  } from "./chunk-YEJR7IXO.js";
@@ -678,8 +682,14 @@ function inlineSandboxClient(factory) {
678
682
  const createOptions = options;
679
683
  return {
680
684
  id,
681
- async *streamPrompt(message) {
685
+ async *streamPrompt(message, opts) {
682
686
  const controller = new AbortController();
687
+ const callerSignal = opts?.signal;
688
+ const onAbort = () => controller.abort(callerSignal?.reason ?? new Error("prompt aborted"));
689
+ if (callerSignal) {
690
+ if (callerSignal.aborted) onAbort();
691
+ else callerSignal.addEventListener("abort", onAbort, { once: true });
692
+ }
683
693
  const spec = { profile: { name: id }, harness: null };
684
694
  const exec = factory(spec, { signal: controller.signal, seams: { createOptions } });
685
695
  try {
@@ -706,6 +716,7 @@ function inlineSandboxClient(factory) {
706
716
  }
707
717
  };
708
718
  } finally {
719
+ callerSignal?.removeEventListener("abort", onAbort);
709
720
  await exec.teardown("brutalKill").catch(() => {
710
721
  });
711
722
  }
@@ -4138,6 +4149,800 @@ ${summary}`,
4138
4149
  };
4139
4150
  }
4140
4151
 
4152
+ // src/runtime/stream-agent-turn.ts
4153
+ import { scoreKnowledgeReadiness } from "@tangle-network/agent-eval";
4154
+
4155
+ // src/sessions.ts
4156
+ function newRuntimeSession(backend, requestedId, metadata) {
4157
+ const now = nowIso();
4158
+ return {
4159
+ id: requestedId || crypto.randomUUID(),
4160
+ backend,
4161
+ status: "active",
4162
+ createdAt: now,
4163
+ updatedAt: now,
4164
+ metadata
4165
+ };
4166
+ }
4167
+ function touchSession(session) {
4168
+ return { ...session, updatedAt: nowIso() };
4169
+ }
4170
+ function nowIso() {
4171
+ return (/* @__PURE__ */ new Date()).toISOString();
4172
+ }
4173
+ var InMemoryRuntimeSessionStore = class {
4174
+ sessions = /* @__PURE__ */ new Map();
4175
+ events = /* @__PURE__ */ new Map();
4176
+ get(sessionId) {
4177
+ return this.sessions.get(sessionId);
4178
+ }
4179
+ put(session) {
4180
+ this.sessions.set(session.id, session);
4181
+ }
4182
+ appendEvent(sessionId, event) {
4183
+ const existing = this.events.get(sessionId) ?? [];
4184
+ existing.push(event);
4185
+ this.events.set(sessionId, existing);
4186
+ }
4187
+ listEvents(sessionId) {
4188
+ return [...this.events.get(sessionId) ?? []];
4189
+ }
4190
+ };
4191
+
4192
+ // src/backends.ts
4193
+ function createIterableBackend(options) {
4194
+ return options;
4195
+ }
4196
+ function createSandboxPromptBackend(options) {
4197
+ const kind = options.kind ?? "sandbox";
4198
+ return {
4199
+ kind,
4200
+ async start(input, context) {
4201
+ const box = await options.getBox(input, context);
4202
+ return newRuntimeSession(
4203
+ kind,
4204
+ options.getSessionId?.(box, input) ?? context.requestedSessionId,
4205
+ { resumable: true }
4206
+ );
4207
+ },
4208
+ resume(session) {
4209
+ return touchSession({ ...session, status: "active" });
4210
+ },
4211
+ async *stream(input, context) {
4212
+ const box = await options.getBox(input, context);
4213
+ const message = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent;
4214
+ for await (const event of options.streamPrompt(box, message, context)) {
4215
+ const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context);
4216
+ if (mapped) yield mapped;
4217
+ }
4218
+ }
4219
+ };
4220
+ }
4221
+ var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504];
4222
+ function pickRetryDelayMs(attempt, policy) {
4223
+ const exp = policy.initialBackoffMs * 2 ** (attempt - 1);
4224
+ const capped = Math.min(exp, policy.maxBackoffMs);
4225
+ const jitter = capped * policy.jitter * (Math.random() * 2 - 1);
4226
+ return Math.max(0, Math.round(capped + jitter));
4227
+ }
4228
+ function withTimeout(callerSignal, timeoutMs) {
4229
+ if (timeoutMs <= 0) {
4230
+ return { signal: callerSignal ?? new AbortController().signal, dispose: () => void 0 };
4231
+ }
4232
+ const controller = new AbortController();
4233
+ const timer = setTimeout(
4234
+ () => controller.abort(new Error(`request timed out after ${timeoutMs}ms`)),
4235
+ timeoutMs
4236
+ );
4237
+ if (typeof timer.unref === "function") {
4238
+ ;
4239
+ timer.unref();
4240
+ }
4241
+ const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error("aborted"));
4242
+ if (callerSignal) {
4243
+ if (callerSignal.aborted) onCallerAbort();
4244
+ else callerSignal.addEventListener("abort", onCallerAbort, { once: true });
4245
+ }
4246
+ return {
4247
+ signal: controller.signal,
4248
+ dispose: () => {
4249
+ clearTimeout(timer);
4250
+ callerSignal?.removeEventListener("abort", onCallerAbort);
4251
+ }
4252
+ };
4253
+ }
4254
+ function sleep2(ms, signal) {
4255
+ return new Promise((resolve, reject) => {
4256
+ if (signal?.aborted) {
4257
+ reject(signal.reason ?? new Error("aborted"));
4258
+ return;
4259
+ }
4260
+ const t = setTimeout(() => {
4261
+ signal?.removeEventListener("abort", onAbort);
4262
+ resolve();
4263
+ }, ms);
4264
+ const onAbort = () => {
4265
+ clearTimeout(t);
4266
+ reject(signal?.reason ?? new Error("aborted"));
4267
+ };
4268
+ signal?.addEventListener("abort", onAbort, { once: true });
4269
+ });
4270
+ }
4271
+ function createOpenAICompatibleBackend(options) {
4272
+ const fetcher = options.fetchImpl ?? fetch;
4273
+ const kind = options.kind ?? "tcloud";
4274
+ const retryPolicy = {
4275
+ maxAttempts: options.retry?.maxAttempts ?? 5,
4276
+ initialBackoffMs: options.retry?.initialBackoffMs ?? 1e3,
4277
+ maxBackoffMs: options.retry?.maxBackoffMs ?? 3e4,
4278
+ jitter: options.retry?.jitter ?? 0.25,
4279
+ retryStatuses: options.retry?.retryStatuses ?? DEFAULT_RETRY_STATUSES,
4280
+ requestTimeoutMs: options.retry?.requestTimeoutMs ?? 12e4
4281
+ };
4282
+ return {
4283
+ kind,
4284
+ start(_input, context) {
4285
+ return newRuntimeSession(kind, context.requestedSessionId);
4286
+ },
4287
+ async *stream(input, context) {
4288
+ const url = `${options.baseUrl.replace(/\/$/, "")}/chat/completions`;
4289
+ const bodyPayload = {
4290
+ model: options.model,
4291
+ stream: true,
4292
+ stream_options: { include_usage: true },
4293
+ messages: input.messages ?? [
4294
+ { role: "user", content: input.message ?? context.task.intent }
4295
+ ]
4296
+ };
4297
+ if (options.tools && options.tools.length > 0) {
4298
+ bodyPayload.tools = options.tools;
4299
+ if (options.toolChoice !== void 0) bodyPayload.tool_choice = options.toolChoice;
4300
+ }
4301
+ if (options.responseFormat !== void 0) {
4302
+ bodyPayload.response_format = options.responseFormat;
4303
+ }
4304
+ const requestBody = JSON.stringify(bodyPayload);
4305
+ let response;
4306
+ let lastStatus = 0;
4307
+ let lastThrown;
4308
+ for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {
4309
+ lastThrown = void 0;
4310
+ const attemptSignal = withTimeout(context.signal, retryPolicy.requestTimeoutMs);
4311
+ try {
4312
+ response = await fetcher(url, {
4313
+ method: "POST",
4314
+ headers: {
4315
+ Authorization: `Bearer ${options.apiKey}`,
4316
+ "Content-Type": "application/json",
4317
+ // Cross-gateway forwarding: when this call is part of a
4318
+ // multi-agent conversation, the runner stamps run/turn/
4319
+ // depth/forwarded-auth headers onto the context. They flow
4320
+ // through to the downstream gateway verbatim so the original
4321
+ // user gets billed, the recursion depth stays bounded, and
4322
+ // the trace correlates across hops.
4323
+ ...context.propagatedHeaders ?? {}
4324
+ },
4325
+ body: requestBody,
4326
+ signal: attemptSignal.signal
4327
+ });
4328
+ } catch (err) {
4329
+ attemptSignal.dispose();
4330
+ if (context.signal?.aborted) throw err;
4331
+ lastThrown = err;
4332
+ response = void 0;
4333
+ if (attempt === retryPolicy.maxAttempts) break;
4334
+ await sleep2(pickRetryDelayMs(attempt, retryPolicy), context.signal);
4335
+ continue;
4336
+ }
4337
+ attemptSignal.dispose();
4338
+ if (response.ok) break;
4339
+ lastStatus = response.status;
4340
+ if (!retryPolicy.retryStatuses.includes(response.status)) break;
4341
+ if (attempt === retryPolicy.maxAttempts) break;
4342
+ try {
4343
+ await response.body?.cancel();
4344
+ } catch {
4345
+ }
4346
+ const delayMs = pickRetryDelayMs(attempt, retryPolicy);
4347
+ await sleep2(delayMs, context.signal);
4348
+ }
4349
+ if (!response) {
4350
+ const reason = lastThrown instanceof Error ? lastThrown.message : String(lastThrown);
4351
+ throw new BackendTransportError(
4352
+ kind,
4353
+ `chat backend unreachable after ${retryPolicy.maxAttempts} attempts: ${reason}`,
4354
+ { status: 0 }
4355
+ );
4356
+ }
4357
+ if (!response.ok) {
4358
+ let body;
4359
+ try {
4360
+ const raw = await response.text();
4361
+ body = raw.length > MAX_ERROR_BODY_BYTES ? `${raw.slice(0, MAX_ERROR_BODY_BYTES)}\u2026` : raw;
4362
+ } catch {
4363
+ body = void 0;
4364
+ }
4365
+ throw new BackendTransportError(kind, `chat backend returned ${lastStatus || "unknown"}`, {
4366
+ status: lastStatus || 0,
4367
+ body
4368
+ });
4369
+ }
4370
+ yield* streamResponseEvents(response, context, options.model);
4371
+ }
4372
+ };
4373
+ }
4374
+ var MAX_ERROR_BODY_BYTES = 2048;
4375
+ function normalizeBackendStreamEvent(event, task, session) {
4376
+ if ("task" in event && event.task && "session" in event && event.session && "timestamp" in event && event.timestamp) {
4377
+ return event;
4378
+ }
4379
+ return {
4380
+ ...event,
4381
+ task: "task" in event && event.task ? event.task : task,
4382
+ session: "session" in event && event.session ? event.session : session,
4383
+ timestamp: "timestamp" in event && event.timestamp ? event.timestamp : nowIso()
4384
+ };
4385
+ }
4386
+ function mapCommonBackendEvent(event, context) {
4387
+ if (!event || typeof event !== "object") return void 0;
4388
+ const record = event;
4389
+ const type = String(record.type ?? "");
4390
+ const data = record.data && typeof record.data === "object" ? record.data : record;
4391
+ if (type === "message.part.updated" || type === "text_delta" || type === "delta") {
4392
+ const part = data.part;
4393
+ const partText = part !== void 0 && typeof part === "object" && (part.type === "text" || part.type === void 0) ? stringValue(part.text) : void 0;
4394
+ const text = stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText;
4395
+ return text ? {
4396
+ type: "text_delta",
4397
+ task: context.task,
4398
+ session: context.session,
4399
+ text,
4400
+ timestamp: nowIso()
4401
+ } : void 0;
4402
+ }
4403
+ if (type === "reasoning_delta") {
4404
+ const text = stringValue(data.text) ?? stringValue(record.text);
4405
+ return text ? {
4406
+ type: "reasoning_delta",
4407
+ task: context.task,
4408
+ session: context.session,
4409
+ text,
4410
+ timestamp: nowIso()
4411
+ } : void 0;
4412
+ }
4413
+ if (type === "tool_call") {
4414
+ return {
4415
+ type: "tool_call",
4416
+ task: context.task,
4417
+ session: context.session,
4418
+ toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? "tool",
4419
+ toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),
4420
+ args: data.args ?? data.input ?? record.args,
4421
+ timestamp: nowIso()
4422
+ };
4423
+ }
4424
+ if (type === "tool_result") {
4425
+ return {
4426
+ type: "tool_result",
4427
+ task: context.task,
4428
+ session: context.session,
4429
+ toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? "tool",
4430
+ toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),
4431
+ result: data.result ?? data.output ?? record.result,
4432
+ timestamp: nowIso()
4433
+ };
4434
+ }
4435
+ if (type === "artifact") {
4436
+ const artifactId = stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId);
4437
+ if (!artifactId) return void 0;
4438
+ return {
4439
+ type: "artifact",
4440
+ task: context.task,
4441
+ session: context.session,
4442
+ artifactId,
4443
+ name: stringValue(data.name) ?? stringValue(record.name),
4444
+ mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),
4445
+ uri: stringValue(data.uri) ?? stringValue(record.uri),
4446
+ content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),
4447
+ metadata: data.metadata && typeof data.metadata === "object" ? data.metadata : void 0,
4448
+ timestamp: nowIso()
4449
+ };
4450
+ }
4451
+ if (type === "proposal_created" || type === "proposal" || type === "filing") {
4452
+ const proposalId = stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId);
4453
+ if (!proposalId) return void 0;
4454
+ const status = stringValue(data.status) ?? stringValue(record.status);
4455
+ return {
4456
+ type: "proposal_created",
4457
+ task: context.task,
4458
+ session: context.session,
4459
+ proposalId,
4460
+ title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,
4461
+ status: status === "pending" || status === "approved" || status === "rejected" ? status : void 0,
4462
+ content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),
4463
+ timestamp: nowIso()
4464
+ };
4465
+ }
4466
+ if (type === "result" || type === "final") {
4467
+ const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text);
4468
+ return text ? {
4469
+ type: "text_delta",
4470
+ task: context.task,
4471
+ session: context.session,
4472
+ text,
4473
+ timestamp: nowIso()
4474
+ } : void 0;
4475
+ }
4476
+ return void 0;
4477
+ }
4478
+ async function* streamResponseEvents(response, context, requestedModel) {
4479
+ const body = response.body;
4480
+ if (!body) return;
4481
+ const reader = body.getReader();
4482
+ const decoder = new TextDecoder();
4483
+ let buffer = "";
4484
+ const usage = { saw: false };
4485
+ const toolCalls = /* @__PURE__ */ new Map();
4486
+ const startedAt = Date.now();
4487
+ for (; ; ) {
4488
+ const { done, value } = await reader.read();
4489
+ if (done) break;
4490
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
4491
+ for (const event of drainStreamBuffer(false)) yield event;
4492
+ }
4493
+ buffer += decoder.decode().replace(/\r\n/g, "\n");
4494
+ for (const event of drainStreamBuffer(true)) yield event;
4495
+ if (buffer.trim()) {
4496
+ for (const event of parseStreamChunk(buffer, context, usage, toolCalls)) yield event;
4497
+ }
4498
+ for (const event of flushPendingToolCalls(toolCalls, context)) yield event;
4499
+ if (usage.saw) {
4500
+ yield {
4501
+ type: "llm_call",
4502
+ task: context.task,
4503
+ session: context.session,
4504
+ model: usage.model ?? requestedModel,
4505
+ tokensIn: usage.tokensIn,
4506
+ tokensOut: usage.tokensOut,
4507
+ // `costUsd` is intentionally absent — pricing tables live in consumers
4508
+ // (agent-eval's `estimateCost`, MetricsCollector). Emitting a wrong
4509
+ // number here is worse than emitting none.
4510
+ latencyMs: Date.now() - startedAt,
4511
+ finishReason: usage.finishReason,
4512
+ timestamp: nowIso()
4513
+ };
4514
+ }
4515
+ function* drainStreamBuffer(flush) {
4516
+ for (; ; ) {
4517
+ const sseBoundary = buffer.indexOf("\n\n");
4518
+ if (sseBoundary >= 0) {
4519
+ const chunk = buffer.slice(0, sseBoundary);
4520
+ buffer = buffer.slice(sseBoundary + 2);
4521
+ for (const event of parseStreamChunk(chunk, context, usage, toolCalls)) yield event;
4522
+ continue;
4523
+ }
4524
+ const newline = buffer.indexOf("\n");
4525
+ if (newline >= 0 && !buffer.slice(0, newline).startsWith("data:")) {
4526
+ const line = buffer.slice(0, newline);
4527
+ buffer = buffer.slice(newline + 1);
4528
+ for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event;
4529
+ continue;
4530
+ }
4531
+ if (flush && buffer.trim() && !buffer.trimStart().startsWith("data:")) {
4532
+ const line = buffer;
4533
+ buffer = "";
4534
+ for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event;
4535
+ continue;
4536
+ }
4537
+ break;
4538
+ }
4539
+ }
4540
+ }
4541
+ function* parseStreamChunk(chunk, context, usage, toolCalls) {
4542
+ const lines = chunk.split(/\r?\n/);
4543
+ const dataLines = lines.filter((line) => line.startsWith("data:"));
4544
+ if (dataLines.length === 0 && lines.every((line) => {
4545
+ const trimmed = line.trim();
4546
+ return trimmed.length === 0 || trimmed.startsWith(":");
4547
+ })) {
4548
+ return;
4549
+ }
4550
+ const data = dataLines.length > 0 ? dataLines.map((line) => line.slice(5).trimStart()).join("\n") : chunk.trim();
4551
+ if (!data || data === "[DONE]") return;
4552
+ let parsed;
4553
+ try {
4554
+ parsed = JSON.parse(data);
4555
+ } catch {
4556
+ yield {
4557
+ type: "text_delta",
4558
+ task: context.task,
4559
+ session: context.session,
4560
+ text: data,
4561
+ timestamp: nowIso()
4562
+ };
4563
+ return;
4564
+ }
4565
+ captureStreamUsage(parsed, usage);
4566
+ const choices = parsed.choices;
4567
+ const choice = Array.isArray(choices) ? choices[0] : void 0;
4568
+ const delta = choice?.delta;
4569
+ const message = choice?.message;
4570
+ const deltaToolCalls = delta?.tool_calls;
4571
+ if (Array.isArray(deltaToolCalls)) {
4572
+ for (const tc of deltaToolCalls) {
4573
+ if (!tc || typeof tc !== "object") continue;
4574
+ const rec = tc;
4575
+ const idx = numberValue(rec.index) ?? 0;
4576
+ const key = `openai:${idx}`;
4577
+ const acc = toolCalls.get(key) ?? { argsRaw: "", source: "openai", finalized: false };
4578
+ const id = stringValue(rec.id);
4579
+ if (id) acc.id = id;
4580
+ const fn = rec.function;
4581
+ const name = stringValue(fn?.name);
4582
+ if (name) acc.name = name;
4583
+ const args = stringValue(fn?.arguments);
4584
+ if (args) acc.argsRaw += args;
4585
+ toolCalls.set(key, acc);
4586
+ }
4587
+ }
4588
+ const messageToolCalls = message?.tool_calls;
4589
+ if (Array.isArray(messageToolCalls)) {
4590
+ for (const tc of messageToolCalls) {
4591
+ if (!tc || typeof tc !== "object") continue;
4592
+ const rec = tc;
4593
+ const fn = rec.function;
4594
+ const idx = numberValue(rec.index) ?? messageToolCalls.indexOf(tc);
4595
+ const key = `openai:${idx}`;
4596
+ const acc = toolCalls.get(key) ?? { argsRaw: "", source: "openai", finalized: false };
4597
+ const id = stringValue(rec.id);
4598
+ if (id) acc.id = id;
4599
+ const name = stringValue(fn?.name);
4600
+ if (name) acc.name = name;
4601
+ const args = stringValue(fn?.arguments);
4602
+ if (args) acc.argsRaw += args;
4603
+ acc.finalized = true;
4604
+ toolCalls.set(key, acc);
4605
+ }
4606
+ }
4607
+ const finishReason = stringValue(choice?.finish_reason);
4608
+ if (finishReason === "tool_calls") {
4609
+ for (const [key, acc] of toolCalls) {
4610
+ if (acc.source === "openai" && !acc.finalized) acc.finalized = true;
4611
+ toolCalls.set(key, acc);
4612
+ }
4613
+ }
4614
+ const eventType = stringValue(parsed.type);
4615
+ if (eventType === "content_block_start") {
4616
+ const block = parsed.content_block;
4617
+ if (block && stringValue(block.type) === "tool_use") {
4618
+ const idx = numberValue(parsed.index) ?? 0;
4619
+ const key = `anthropic:${idx}`;
4620
+ toolCalls.set(key, {
4621
+ id: stringValue(block.id),
4622
+ name: stringValue(block.name),
4623
+ argsRaw: "",
4624
+ source: "anthropic",
4625
+ finalized: false
4626
+ });
4627
+ }
4628
+ }
4629
+ if (eventType === "content_block_delta") {
4630
+ const d = parsed.delta;
4631
+ const dType = stringValue(d?.type);
4632
+ if (dType === "input_json_delta") {
4633
+ const idx = numberValue(parsed.index) ?? 0;
4634
+ const key = `anthropic:${idx}`;
4635
+ const acc = toolCalls.get(key);
4636
+ if (acc) {
4637
+ const partial = stringValue(d?.partial_json) ?? "";
4638
+ acc.argsRaw += partial;
4639
+ toolCalls.set(key, acc);
4640
+ }
4641
+ } else {
4642
+ const text2 = stringValue(d?.text);
4643
+ if (text2) {
4644
+ yield {
4645
+ type: "text_delta",
4646
+ task: context.task,
4647
+ session: context.session,
4648
+ text: text2,
4649
+ timestamp: nowIso()
4650
+ };
4651
+ }
4652
+ }
4653
+ }
4654
+ if (eventType === "content_block_stop") {
4655
+ const idx = numberValue(parsed.index) ?? 0;
4656
+ const key = `anthropic:${idx}`;
4657
+ const acc = toolCalls.get(key);
4658
+ if (acc) {
4659
+ acc.finalized = true;
4660
+ toolCalls.set(key, acc);
4661
+ }
4662
+ }
4663
+ for (const event of drainFinalizedToolCalls(toolCalls, context)) yield event;
4664
+ const text = stringValue(delta?.content) ?? stringValue(message?.content) ?? stringValue(parsed.text);
4665
+ if (text) {
4666
+ yield {
4667
+ type: "text_delta",
4668
+ task: context.task,
4669
+ session: context.session,
4670
+ text,
4671
+ timestamp: nowIso()
4672
+ };
4673
+ return;
4674
+ }
4675
+ const mapped = mapCommonBackendEvent(parsed, context);
4676
+ if (mapped) yield mapped;
4677
+ }
4678
+ function* drainFinalizedToolCalls(toolCalls, context) {
4679
+ for (const [key, acc] of toolCalls) {
4680
+ if (!acc.finalized) continue;
4681
+ toolCalls.delete(key);
4682
+ yield buildToolCallEvent(acc, context);
4683
+ }
4684
+ }
4685
+ function* flushPendingToolCalls(toolCalls, context) {
4686
+ for (const [key, acc] of toolCalls) {
4687
+ toolCalls.delete(key);
4688
+ yield buildToolCallEvent(acc, context);
4689
+ }
4690
+ }
4691
+ function buildToolCallEvent(acc, context) {
4692
+ let args = acc.argsRaw;
4693
+ if (acc.argsRaw.length > 0) {
4694
+ try {
4695
+ args = JSON.parse(acc.argsRaw);
4696
+ } catch {
4697
+ args = acc.argsRaw;
4698
+ }
4699
+ } else {
4700
+ args = {};
4701
+ }
4702
+ return {
4703
+ type: "tool_call",
4704
+ task: context.task,
4705
+ session: context.session,
4706
+ toolName: acc.name ?? "tool",
4707
+ toolCallId: acc.id,
4708
+ args,
4709
+ timestamp: nowIso()
4710
+ };
4711
+ }
4712
+ function captureStreamUsage(parsed, usage) {
4713
+ const model = stringValue(parsed.model);
4714
+ if (model && !usage.model) usage.model = model;
4715
+ const openAiUsage = parsed.usage;
4716
+ if (openAiUsage && typeof openAiUsage === "object") {
4717
+ const promptTokens = numberValue(openAiUsage.prompt_tokens);
4718
+ const completionTokens = numberValue(openAiUsage.completion_tokens);
4719
+ const inputTokens = numberValue(openAiUsage.input_tokens);
4720
+ const outputTokens = numberValue(openAiUsage.output_tokens);
4721
+ if (promptTokens !== void 0) {
4722
+ usage.tokensIn = promptTokens;
4723
+ usage.saw = true;
4724
+ } else if (inputTokens !== void 0) {
4725
+ usage.tokensIn = (usage.tokensIn ?? 0) + inputTokens;
4726
+ usage.saw = true;
4727
+ }
4728
+ if (completionTokens !== void 0) {
4729
+ usage.tokensOut = completionTokens;
4730
+ usage.saw = true;
4731
+ } else if (outputTokens !== void 0) {
4732
+ usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens;
4733
+ usage.saw = true;
4734
+ }
4735
+ }
4736
+ const type = stringValue(parsed.type);
4737
+ if (type === "message_start") {
4738
+ const message = parsed.message;
4739
+ const messageModel = stringValue(message?.model);
4740
+ if (messageModel && !usage.model) usage.model = messageModel;
4741
+ const messageUsage = message?.usage;
4742
+ const inputTokens = numberValue(messageUsage?.input_tokens);
4743
+ if (inputTokens !== void 0) {
4744
+ usage.tokensIn = inputTokens;
4745
+ usage.saw = true;
4746
+ }
4747
+ const outputTokens = numberValue(messageUsage?.output_tokens);
4748
+ if (outputTokens !== void 0) {
4749
+ usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens;
4750
+ usage.saw = true;
4751
+ }
4752
+ }
4753
+ if (type === "message_delta") {
4754
+ const delta = parsed.delta;
4755
+ const stopReason = stringValue(delta?.stop_reason);
4756
+ if (stopReason) usage.finishReason = stopReason;
4757
+ }
4758
+ const choices = parsed.choices;
4759
+ if (Array.isArray(choices)) {
4760
+ const finishReason = stringValue(
4761
+ choices[0]?.finish_reason
4762
+ );
4763
+ if (finishReason) usage.finishReason = finishReason;
4764
+ }
4765
+ }
4766
+ function numberValue(value) {
4767
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4768
+ }
4769
+ function stringValue(value) {
4770
+ return typeof value === "string" && value.length > 0 ? value : void 0;
4771
+ }
4772
+
4773
+ // src/runtime/stream-agent-turn.ts
4774
+ async function* streamAgentTurn(backend, prompt, opts = {}) {
4775
+ const label = backend.kind === "chat" ? backend.backend.kind : backend.kind;
4776
+ const task = { id: `turn-${crypto.randomUUID()}`, intent: prompt };
4777
+ const acc = { deltaText: "", input: 0, output: 0, costUsd: 0 };
4778
+ const deadline = deriveTurnSignal(opts.signal, opts.timeoutMs ?? 0);
4779
+ let session;
4780
+ try {
4781
+ session = await startTurnSession(backend, task, prompt, deadline.signal, label);
4782
+ yield { type: "backend_start", task, session, backend: label, timestamp: nowIso() };
4783
+ const inner = backend.kind === "chat" ? driveChatTurn(backend.backend, task, session, prompt, deadline.signal, acc) : driveBoxTurn(
4784
+ backend.kind === "box" ? backend.box : await inlineSandboxClient(backend.factory).create(),
4785
+ prompt,
4786
+ deadline.signal,
4787
+ backend.agentRunName ?? "agent",
4788
+ acc
4789
+ );
4790
+ for await (const event of inner) {
4791
+ yield event;
4792
+ throwIfAborted(deadline.signal);
4793
+ }
4794
+ yield buildFinalEvent(task, session, acc, { status: "completed", reason: "turn completed" });
4795
+ } catch (err) {
4796
+ const callerAborted = opts.signal?.aborted === true;
4797
+ const status = callerAborted ? "aborted" : "failed";
4798
+ const message = err instanceof Error ? err.message : String(err);
4799
+ const error = err instanceof BackendTransportError ? { kind: "transport", message, status: err.status, body: err.body } : { kind: "backend", message };
4800
+ yield {
4801
+ type: "backend_error",
4802
+ task,
4803
+ ...session ? { session } : {},
4804
+ backend: label,
4805
+ message,
4806
+ recoverable: !callerAborted,
4807
+ error,
4808
+ timestamp: nowIso()
4809
+ };
4810
+ yield buildFinalEvent(task, session, acc, { status, reason: message, error });
4811
+ } finally {
4812
+ deadline.dispose();
4813
+ }
4814
+ }
4815
+ async function collectAgentTurn(stream) {
4816
+ const events = [];
4817
+ for await (const event of stream) events.push(event);
4818
+ const final = events.at(-1);
4819
+ if (!final || final.type !== "final") {
4820
+ throw new Error(
4821
+ `collectAgentTurn: stream ended without a terminal 'final' event (last: ${final ? final.type : "none"})`
4822
+ );
4823
+ }
4824
+ const metadata = final.metadata ?? {};
4825
+ const tokenUsage = metadata.tokenUsage && typeof metadata.tokenUsage === "object" ? metadata.tokenUsage : {};
4826
+ const usage = {
4827
+ input: finiteNumber(tokenUsage.input) ?? 0,
4828
+ output: finiteNumber(tokenUsage.output) ?? 0
4829
+ };
4830
+ const costUsd = finiteNumber(metadata.costUsd);
4831
+ if (costUsd !== void 0) usage.costUsd = costUsd;
4832
+ if (typeof metadata.model === "string" && metadata.model.length > 0) {
4833
+ usage.model = metadata.model;
4834
+ }
4835
+ return {
4836
+ finalText: final.text ?? "",
4837
+ usage,
4838
+ events,
4839
+ status: final.status,
4840
+ ...final.error ? { error: final.error } : {}
4841
+ };
4842
+ }
4843
+ async function startTurnSession(backend, task, prompt, signal, label) {
4844
+ if (backend.kind === "chat" && backend.backend.start) {
4845
+ return backend.backend.start(
4846
+ { task, message: prompt },
4847
+ { task, knowledge: emptyReadiness(task), signal }
4848
+ );
4849
+ }
4850
+ return newRuntimeSession(label);
4851
+ }
4852
+ async function* driveBoxTurn(box, prompt, signal, agentRunName, acc) {
4853
+ for await (const event of box.streamPrompt(prompt, { signal })) {
4854
+ const terminalText = terminalTextFromSandboxEvent(event);
4855
+ if (terminalText !== void 0) acc.terminalText = terminalText;
4856
+ const mapped = mapSandboxEvent(event, { agentRunName });
4857
+ if (!mapped) continue;
4858
+ foldEvent(mapped, acc, agentRunName);
4859
+ yield mapped;
4860
+ }
4861
+ }
4862
+ async function* driveChatTurn(backend, task, session, prompt, signal, acc) {
4863
+ const input = { task, message: prompt };
4864
+ const context = { task, knowledge: emptyReadiness(task), session, signal };
4865
+ for await (const raw of backend.stream(input, context)) {
4866
+ const event = normalizeBackendStreamEvent(raw, task, session);
4867
+ foldEvent(event, acc);
4868
+ yield event;
4869
+ }
4870
+ }
4871
+ function foldEvent(event, acc, fallbackModelLabel) {
4872
+ if (event.type === "text_delta") {
4873
+ acc.deltaText += event.text;
4874
+ return;
4875
+ }
4876
+ if (event.type === "llm_call") {
4877
+ acc.input += event.tokensIn ?? 0;
4878
+ acc.output += event.tokensOut ?? 0;
4879
+ acc.costUsd += event.costUsd ?? 0;
4880
+ if (event.model && event.model !== fallbackModelLabel) acc.model = event.model;
4881
+ }
4882
+ }
4883
+ function terminalTextFromSandboxEvent(event) {
4884
+ if (!event || typeof event !== "object") return void 0;
4885
+ const type = String(event.type ?? "");
4886
+ if (type !== "result" && type !== "done" && type !== "final") return void 0;
4887
+ const data = event.data && typeof event.data === "object" ? event.data : {};
4888
+ for (const key of ["finalText", "text", "response", "content"]) {
4889
+ const value = data[key];
4890
+ if (typeof value === "string") return value;
4891
+ }
4892
+ return void 0;
4893
+ }
4894
+ function buildFinalEvent(task, session, acc, outcome) {
4895
+ const finalText = acc.terminalText ?? acc.deltaText;
4896
+ return {
4897
+ type: "final",
4898
+ task,
4899
+ ...session ? { session } : {},
4900
+ status: outcome.status,
4901
+ reason: outcome.reason,
4902
+ ...finalText ? { text: finalText } : {},
4903
+ metadata: {
4904
+ tokenUsage: { input: acc.input, output: acc.output },
4905
+ ...acc.costUsd > 0 ? { costUsd: acc.costUsd } : {},
4906
+ ...acc.model ? { model: acc.model } : {}
4907
+ },
4908
+ ...outcome.error ? { error: outcome.error } : {},
4909
+ timestamp: nowIso()
4910
+ };
4911
+ }
4912
+ function emptyReadiness(task) {
4913
+ return scoreKnowledgeReadiness({ taskId: task.id, requirements: [] });
4914
+ }
4915
+ function finiteNumber(value) {
4916
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4917
+ }
4918
+ function throwIfAborted(signal) {
4919
+ if (!signal.aborted) return;
4920
+ throw signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason));
4921
+ }
4922
+ function deriveTurnSignal(callerSignal, timeoutMs) {
4923
+ const controller = new AbortController();
4924
+ const timer = timeoutMs > 0 ? setTimeout(
4925
+ () => controller.abort(new Error(`agent turn timed out after ${timeoutMs}ms`)),
4926
+ timeoutMs
4927
+ ) : void 0;
4928
+ if (timer && typeof timer.unref === "function") {
4929
+ ;
4930
+ timer.unref();
4931
+ }
4932
+ const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error("agent turn aborted"));
4933
+ if (callerSignal) {
4934
+ if (callerSignal.aborted) onCallerAbort();
4935
+ else callerSignal.addEventListener("abort", onCallerAbort, { once: true });
4936
+ }
4937
+ return {
4938
+ signal: controller.signal,
4939
+ dispose: () => {
4940
+ if (timer) clearTimeout(timer);
4941
+ callerSignal?.removeEventListener("abort", onCallerAbort);
4942
+ }
4943
+ };
4944
+ }
4945
+
4141
4946
  // src/runtime/supervise/detector-monitor.ts
4142
4947
  import {
4143
4948
  argHash,
@@ -4946,6 +5751,14 @@ function tail(s) {
4946
5751
  }
4947
5752
 
4948
5753
  export {
5754
+ newRuntimeSession,
5755
+ touchSession,
5756
+ nowIso,
5757
+ InMemoryRuntimeSessionStore,
5758
+ createIterableBackend,
5759
+ createSandboxPromptBackend,
5760
+ createOpenAICompatibleBackend,
5761
+ normalizeBackendStreamEvent,
4949
5762
  anytimeReport,
4950
5763
  renderAnytimeTable,
4951
5764
  defaultAuditorInstruction,
@@ -5016,6 +5829,8 @@ export {
5016
5829
  pickChampion,
5017
5830
  selectChampion,
5018
5831
  runStrategyEvolution,
5832
+ streamAgentTurn,
5833
+ collectAgentTurn,
5019
5834
  defaultToolDetectors,
5020
5835
  watchTrace,
5021
5836
  runCoderChecks,
@@ -5036,4 +5851,4 @@ export {
5036
5851
  computeFindingId,
5037
5852
  makeFinding2 as makeFinding
5038
5853
  };
5039
- //# sourceMappingURL=chunk-UJW6EVNY.js.map
5854
+ //# sourceMappingURL=chunk-DLAEEF26.js.map