@tangle-network/agent-app 0.60.119 → 0.60.121

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.
@@ -54,11 +54,11 @@ import "../chunk-BMZTYGKE.js";
54
54
  import "../chunk-UGWQLQDS.js";
55
55
  import "../chunk-TMOYOMSW.js";
56
56
  import {
57
- ProtectedModelSettlementError
58
- } from "../chunk-RN2N75EI.js";
57
+ runProtectedRouterTurn
58
+ } from "../chunk-2HGAMEOY.js";
59
59
  import {
60
60
  runRouterTurn
61
- } from "../chunk-2YEQGNIU.js";
61
+ } from "../chunk-4U2CA7N2.js";
62
62
  import "../chunk-D6UJEOZQ.js";
63
63
  import "../chunk-RFLC7BPY.js";
64
64
  import {
@@ -1258,11 +1258,58 @@ function createRouterTurnProducer(options) {
1258
1258
  }
1259
1259
 
1260
1260
  // src/chat-routes/protected-runtime-producer.ts
1261
- import { createExecutor, streamAgentTurn } from "@tangle-network/agent-runtime/kernel";
1262
- import {
1263
- runProtectedAgentCandidateModelGrant
1264
- } from "@tangle-network/agent-runtime/candidate-execution";
1265
- var PROTECTED_CHAT_PROVIDERS = /* @__PURE__ */ new Set(["anthropic", "openai"]);
1261
+ import { profileMaterializationAxes } from "@tangle-network/agent-interface";
1262
+ var PROTECTED_TURN_AXES = /* @__PURE__ */ new Set([
1263
+ "name",
1264
+ "description",
1265
+ "version",
1266
+ "tags",
1267
+ "metadata",
1268
+ "harness",
1269
+ "tools",
1270
+ "systemPrompt",
1271
+ "instructions",
1272
+ "modelDefault",
1273
+ "modelProvider",
1274
+ "modelReasoningEffort",
1275
+ "modelMaxVisibleOutputTokens",
1276
+ "modelMaxTotalOutputTokens",
1277
+ "modelMetadata"
1278
+ ]);
1279
+ function protectedTurnSettings(profile, toolNames) {
1280
+ if (profile.harness && profile.harness !== "cli-base") throw new Error(`Protected chat runs only the cli-base harness, not ${profile.harness}`);
1281
+ if (profile.resources) throw new Error("Protected chat applies prompt text only; run profile resources in the Sandbox lane");
1282
+ if (profile.model?.metadata && Object.keys(profile.model.metadata).length > 0) {
1283
+ throw new Error("Protected chat does not apply AgentProfile.model.metadata");
1284
+ }
1285
+ if (profile.model?.maxReasoningTokens !== void 0) throw new Error("Protected chat cannot enforce maxReasoningTokens");
1286
+ const unsupported = profileMaterializationAxes(profile).filter((axis) => !PROTECTED_TURN_AXES.has(axis));
1287
+ if (unsupported.length > 0) {
1288
+ throw new Error(`Protected chat does not apply AgentProfile ${unsupported.join(", ")}; run this profile in the Sandbox lane`);
1289
+ }
1290
+ const declared = profile.model?.default?.trim();
1291
+ const provider = profile.model?.provider?.trim();
1292
+ const model = declared && provider && declared.startsWith(`${provider}/`) ? declared.slice(provider.length + 1) : declared;
1293
+ if (!model) throw new Error("Protected chat requires AgentProfile.model.default");
1294
+ for (const [name, enabled] of Object.entries(profile.tools ?? {})) {
1295
+ if (enabled !== toolNames.has(name)) throw new Error(`Protected tool ${name} does not match AgentProfile.tools`);
1296
+ }
1297
+ for (const name of toolNames) {
1298
+ if (profile.tools?.[name] !== true) throw new Error(`Protected tool ${name} is not enabled by AgentProfile.tools`);
1299
+ }
1300
+ const { visible, total } = { visible: profile.model?.maxVisibleOutputTokens, total: profile.model?.maxTotalOutputTokens };
1301
+ return {
1302
+ model,
1303
+ systemPrompt: [profile.prompt?.systemPrompt, ...profile.prompt?.instructions ?? []].filter((part) => typeof part === "string" && part.trim().length > 0).join("\n"),
1304
+ ...profile.model?.reasoningEffort ? { reasoningEffort: profile.model.reasoningEffort } : {},
1305
+ ...visible !== void 0 ? { maxTokens: visible } : {},
1306
+ ...total !== void 0 ? { maxCompletionTokens: total } : {}
1307
+ };
1308
+ }
1309
+ function protectedToolResultText(outcome) {
1310
+ if (!outcome.ok) return `error: ${outcome.message}`;
1311
+ return JSON.stringify(outcome.result) ?? "null";
1312
+ }
1266
1313
  function createProtectedRuntimeChatProducer(options) {
1267
1314
  if (!Number.isSafeInteger(options.maxToolCalls) || options.maxToolCalls < 0) {
1268
1315
  throw new Error("maxToolCalls must be a non-negative integer");
@@ -1287,9 +1334,10 @@ function createProtectedRuntimeChatProducer(options) {
1287
1334
  async function* events() {
1288
1335
  if (started) throw new Error("A protected chat producer can only execute once");
1289
1336
  started = true;
1290
- const controller = new AbortController();
1291
1337
  options.signal?.throwIfAborted();
1292
1338
  if (Date.now() >= options.grant.deadlineAtMs) throw new Error("Protected execution deadline expired");
1339
+ const settings = protectedTurnSettings(profile, new Set(tools.keys()));
1340
+ const controller = new AbortController();
1293
1341
  const signal = AbortSignal.any([
1294
1342
  controller.signal,
1295
1343
  AbortSignal.timeout(Math.max(1, options.grant.deadlineAtMs - Date.now())),
@@ -1299,114 +1347,56 @@ function createProtectedRuntimeChatProducer(options) {
1299
1347
  const writer = channel.writable.getWriter();
1300
1348
  const reader = channel.readable.getReader();
1301
1349
  const emit = (event) => writer.write(event);
1302
- const execution = runProtectedAgentCandidateModelGrant({
1303
- ...options.grant,
1304
- port: {
1305
- resolve: (input) => options.grant.port.resolve(input),
1306
- reserveGrant: (input) => options.grant.port.reserveGrant(input),
1307
- activateGrant: (input) => options.grant.port.activateGrant(input),
1308
- // Runtime settles failed executions before rethrowing. Retain that receipt too.
1309
- settleGrant: async (input) => {
1310
- let auditError;
1311
- const settlement = await options.grant.port.settleGrant(input).catch((error) => {
1312
- if (!(error instanceof ProtectedModelSettlementError)) throw error;
1313
- auditError = error;
1314
- return error.settlement;
1315
- });
1316
- usage = {
1317
- inputTokens: settlement.calls.reduce((sum2, call) => sum2 + call.accountedInputTokens, 0),
1318
- outputTokens: settlement.calls.reduce((sum2, call) => sum2 + call.outputTokens, 0),
1319
- reasoningTokens: settlement.calls.reduce((sum2, call) => sum2 + call.reasoningTokens, 0),
1320
- costUsd: settlement.calls.reduce((sum2, call) => sum2 + call.costUsdNanos, 0) / 1e9
1321
- };
1322
- const unauthorizedReasoning = usage.reasoningTokens > 0 && options.grant.resolve.reasoningEffort === "none";
1323
- budgetEnforced = settlement.usageWithinLimits && !unauthorizedReasoning;
1324
- if (unauthorizedReasoning) throw new Error("Provider reported reasoning tokens although reasoning was disabled");
1325
- if (!budgetEnforced) throw new Error("Provider settlement exceeded execution limits");
1326
- if (auditError) throw auditError;
1327
- return settlement;
1328
- }
1329
- },
1330
- execute: async ({ activation, resolved }) => {
1331
- signal.throwIfAborted();
1332
- if (Date.now() >= options.grant.deadlineAtMs) throw new Error("Protected execution deadline expired");
1333
- model = resolved.model;
1334
- if (!PROTECTED_CHAT_PROVIDERS.has(resolved.provider) || resolved.reasoningEffort !== "none") {
1335
- throw new Error("Protected chat currently requires an Anthropic or OpenAI model without reasoning");
1336
- }
1337
- toolTokens = 0;
1338
- const apiKey = activation.env.OPENAI_API_KEY;
1339
- const baseUrl = activation.env.OPENAI_BASE_URL;
1340
- if (!apiKey || !baseUrl) throw new Error("Protected Router activation is missing");
1341
- const factory = createExecutor({
1342
- backend: "router-tools",
1343
- routerBaseUrl: baseUrl,
1344
- routerKey: apiKey,
1345
- tools: options.tools.map((tool) => ({
1346
- type: "function",
1347
- function: { name: tool.name, description: tool.description, parameters: tool.inputSchema }
1348
- })),
1349
- ...options.priorMessages?.length ? { initialMessages: options.priorMessages } : {},
1350
- executeToolCall: async (name, args) => {
1351
- signal.throwIfAborted();
1352
- const tool = tools.get(name);
1353
- if (!tool) throw new Error("Tool is not authorized for this execution");
1354
- if (toolCalls >= options.maxToolCalls) {
1355
- controller.abort(new Error("Execution tool-call limit reached"));
1356
- signal.throwIfAborted();
1357
- }
1358
- toolCalls += 1;
1359
- const id = `tool-${toolCalls}`;
1360
- await emit({ type: "tool_call", data: { id, name, arguments: args } });
1361
- try {
1362
- const result = await tool.run(args, { signal });
1363
- await emit({ type: "tool_result", data: { id, name, output: result } });
1364
- return JSON.stringify(result);
1365
- } catch (error) {
1366
- const message = error instanceof Error ? error.message : "Tool failed";
1367
- await emit({ type: "tool_result", data: { id, name, error: message } });
1368
- throw error;
1369
- }
1370
- }
1371
- });
1372
- let completed = false;
1373
- let streamedText = "";
1374
- for await (const event of streamAgentTurn(
1375
- { kind: "executor", factory, profile },
1376
- { prompt: options.prompt },
1377
- {
1378
- signal,
1379
- callId: options.grant.reserve.executionId,
1380
- timeoutMs: Math.max(1, options.grant.deadlineAtMs - Date.now())
1381
- }
1382
- )) {
1383
- if (event.type === "text_delta") streamedText += event.text;
1384
- if (event.type === "text_delta" || event.type === "reasoning_delta") {
1385
- await emit({ type: "message.part.updated", data: {
1386
- part: { id: event.type, type: event.type === "text_delta" ? "text" : "reasoning" },
1387
- delta: event.text
1388
- } });
1389
- }
1390
- if (event.type === "final") {
1391
- if (event.status !== "completed") throw new Error(`Protected execution ${event.status}`);
1392
- if (event.text !== void 0) {
1393
- if (!event.text.startsWith(streamedText)) {
1394
- throw new Error("Protected execution revised already streamed text");
1395
- }
1396
- const suffix = event.text.slice(streamedText.length);
1397
- if (suffix) await emit({ type: "message.part.updated", data: {
1398
- part: { id: "text_delta", type: "text" },
1399
- delta: suffix
1400
- } });
1401
- streamedText = event.text;
1402
- }
1403
- completed = true;
1404
- await emit({ type: "result", data: { finalText: event.text } });
1350
+ const segments = [];
1351
+ const execution = runProtectedRouterTurn({
1352
+ ...settings,
1353
+ grant: options.grant,
1354
+ userMessage: options.prompt,
1355
+ history: [...options.priorMessages ?? []],
1356
+ signal,
1357
+ // The grant's ledger expects one buffered completion per model call.
1358
+ stream: false,
1359
+ maxToolCalls: options.maxToolCalls,
1360
+ // The grant bounds model calls; the loop must not stop the turn earlier.
1361
+ maxToolTurns: options.grant.reserve.limits.maxModelCalls,
1362
+ tools: options.tools.map((tool) => ({
1363
+ name: tool.name,
1364
+ description: tool.description,
1365
+ inputSchema: tool.inputSchema,
1366
+ run: async (args) => {
1367
+ signal.throwIfAborted();
1368
+ toolCalls += 1;
1369
+ const id = `tool-${toolCalls}`;
1370
+ await emit({ type: "tool_call", data: { id, name: tool.name, arguments: args } });
1371
+ try {
1372
+ const result = await tool.run(args, { signal });
1373
+ await emit({ type: "tool_result", data: { id, name: tool.name, output: result } });
1374
+ return result;
1375
+ } catch (error) {
1376
+ const message = error instanceof Error ? error.message : "Tool failed";
1377
+ await emit({ type: "tool_result", data: { id, name: tool.name, error: message } });
1378
+ throw error;
1405
1379
  }
1406
1380
  }
1407
- if (!completed) throw new Error("Protected execution ended without a terminal result");
1381
+ })),
1382
+ toolError: (error) => ({ code: "tool_failed", message: error instanceof Error ? error.message : "Tool failed" }),
1383
+ renderToolResult: (_toolName, outcome) => protectedToolResultText(outcome),
1384
+ onEvent: (event) => {
1385
+ if (event.type === "text") segments[event.segment - 1] = (segments[event.segment - 1] ?? "") + event.delta;
1386
+ }
1387
+ }).then(async (outcome) => {
1388
+ if (outcome.settlement) {
1389
+ usage = { ...outcome.settlement.usage };
1390
+ budgetEnforced = outcome.settlement.budgetEnforced;
1391
+ model = outcome.settlement.model;
1392
+ toolTokens = 0;
1393
+ }
1394
+ if (!outcome.failure || outcome.failure.code.startsWith("settlement_")) {
1395
+ const finalText = segments.filter(Boolean).at(-1) ?? "";
1396
+ if (finalText) await emit({ type: "message.part.updated", data: { part: { id: "text_delta", type: "text" }, delta: finalText } });
1397
+ await emit({ type: "result", data: { finalText } });
1408
1398
  }
1409
- }).then(async () => {
1399
+ if (outcome.failure) throw new Error(outcome.failure.message);
1410
1400
  await writer.close();
1411
1401
  }).catch((error) => writer.abort(error));
1412
1402
  try {