@tangle-network/agent-provider-tangle 3.4.0 → 3.4.1

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/README.md CHANGED
@@ -682,3 +682,13 @@ Authentication failures and malformed metadata do not become typed quota refusal
682
682
  The command transport accepts the same public capacity body only with exit code 75.
683
683
  Its typed error has no HTTP status.
684
684
  The caller's execution owner decides whether and when to retry.
685
+
686
+ ### Completion and native evidence
687
+
688
+ The provider projects terminal results and terminal stream events into bounded completion summaries.
689
+ Cumulative `toolInvocations` stay in native session evidence; they are not copied into the summary or truncated.
690
+ A projected terminal event omits `providerEvent`, which would otherwise claim to contain the full native event.
691
+ The session, execution, and event identities still bind the summary to its source.
692
+ Use `captureTangleEnvironmentEvidence` or the exact Sandbox session's `rawEvidence()` to retain original arguments, outputs, and process records.
693
+ Capture completeness and missing-source reasons remain authoritative; a successful completion does not imply complete archival capture.
694
+ Individual event, terminal text, identity, and usage validation remain unchanged.
@@ -1,6 +1,7 @@
1
1
  import { CanonicalStreamEventSchema, boundedEventContentRecordSchema, } from "@tangle-network/agent-interface";
2
2
  import { optionalNonEmptyString } from "./tangle-environment-values.js";
3
3
  import { tokenUsageFromData } from "./tangle-result-values.js";
4
+ import { sandboxTerminalProjection } from "./tangle-prompt.js";
4
5
  /** The sidecar sends this envelope when an SSE connection is ready. */
5
6
  export function isSandboxConnectionMarker(event) {
6
7
  if (!event || typeof event !== "object")
@@ -133,8 +134,11 @@ export function environmentEventFromSandboxEvent(event, expected = {}) {
133
134
  record.id.trim() !== record.id)) {
134
135
  throw new Error("Tangle Sandbox event contained an invalid event id");
135
136
  }
136
- const data = record.data;
137
- assertBoundedRecord(record);
137
+ const terminal = record.type === "result" || record.type === "done";
138
+ const sourceData = record.data;
139
+ const projected = terminal && Object.hasOwn(sourceData, "toolInvocations");
140
+ const data = projected ? sandboxTerminalProjection(sourceData) : sourceData;
141
+ assertBoundedRecord(projected ? { ...record, data } : record);
138
142
  if (Object.prototype.hasOwnProperty.call(data, "contextTransferReceipt")) {
139
143
  throw new Error("Tangle Sandbox emitted an unsolicited context transfer receipt");
140
144
  }
@@ -189,7 +193,9 @@ export function environmentEventFromSandboxEvent(event, expected = {}) {
189
193
  // contribute a total to whatever sums these events.
190
194
  ...(usage ? { usage } : {}),
191
195
  ...(usageMode === undefined ? {} : { usageMode }),
192
- providerEvent: event,
196
+ // A terminal projection is not the complete native event. The source is
197
+ // available through exact session/execution evidence, including tool history.
198
+ ...(!projected ? { providerEvent: event } : {}),
193
199
  };
194
200
  }
195
201
  function normalizeSandboxEvent(type, data, identity) {
@@ -83,12 +83,11 @@ type ValidatedSandboxPromptResult = Record<string, unknown> & {
83
83
  executionId?: string;
84
84
  };
85
85
  /**
86
- * The marker left in place of a tool result's discarded tail.
87
- *
88
- * It names the byte counts so a reader can tell a truncated result from a tool that genuinely
89
- * returned little, and so a caller can decide to re-fetch rather than reason from a partial page.
86
+ * Completion is a bounded summary; cumulative tool history is retained separately.
87
+ * The native session evidence owns the original arguments and outputs. Never
88
+ * truncate that history or require the whole conversation to fit one event.
90
89
  */
91
- export declare function toolOutputTruncationMarker(keptBytes: number, originalBytes: number): string;
90
+ export declare function sandboxTerminalProjection(record: Record<string, unknown>): Record<string, unknown>;
92
91
  export declare function validatedSandboxPromptResult(result: PromptResult): ValidatedSandboxPromptResult;
93
92
  export declare function agentTurnResultFromPromptRecord(record: ValidatedSandboxPromptResult, options?: {
94
93
  contextTransferRequested?: boolean;
@@ -1,5 +1,5 @@
1
1
  import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
2
- import { agentProfileSchema, canonicalAgentProfileDigest, CONTRACT_MAX_JSON_BYTES, boundedEventContentRecordSchema, isBoundedEventContentJson, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
2
+ import { agentProfileSchema, canonicalAgentProfileDigest, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
3
3
  import { tokenUsageFromData } from "./tangle-result-values.js";
4
4
  import { assertBoundedJson, boundedString, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
5
5
  import { profileCredentialSource } from "./model-credential-source.js";
@@ -412,72 +412,13 @@ const SANDBOX_OPTIONAL_RESULT_FIELDS = new Set([
412
412
  "costUsd",
413
413
  ]);
414
414
  /**
415
- * The marker left in place of a tool result's discarded tail.
416
- *
417
- * It names the byte counts so a reader can tell a truncated result from a tool that genuinely
418
- * returned little, and so a caller can decide to re-fetch rather than reason from a partial page.
419
- */
420
- export function toolOutputTruncationMarker(keptBytes, originalBytes) {
421
- return `\n\n[truncated by the Tangle provider: kept ${keptBytes} of ${originalBytes} bytes to stay inside the ${CONTRACT_MAX_JSON_BYTES}-byte record content bound]`;
422
- }
423
- /**
424
- * Shrink oversized tool output until the whole record fits the content bound.
425
- *
426
- * Only `toolInvocations[].result` is touched, because it is the one field that carries arbitrary
427
- * fetched material rather than identity, accounting, or control state. The largest result is cut
428
- * first and the loop repeats, so a record with several big results converges instead of destroying
429
- * the first one it meets.
430
- *
431
- * Returns the record unchanged when it already fits, so the common path allocates nothing.
415
+ * Completion is a bounded summary; cumulative tool history is retained separately.
416
+ * The native session evidence owns the original arguments and outputs. Never
417
+ * truncate that history or require the whole conversation to fit one event.
432
418
  */
433
- function withTruncatedToolOutput(record) {
434
- if (isBoundedEventContentJson(record))
435
- return { record, truncated: 0 };
436
- const invocations = record.toolInvocations;
437
- if (!Array.isArray(invocations))
438
- return { record, truncated: 0 };
439
- const next = invocations.map((entry) => entry && typeof entry === "object" && !Array.isArray(entry)
440
- ? { ...entry }
441
- : entry);
442
- const originalLengths = new Map();
443
- let truncated = 0;
444
- // Each pass cuts the current widest result by the record's measured overflow, so a single huge
445
- // value converges immediately and several large ones shrink in turn rather than the first being
446
- // destroyed. The cap is a backstop: `isBoundedEventContentJson` also enforces node, depth, and
447
- // array limits that trimming a string cannot satisfy, and those must fall through to the refusal
448
- // rather than spin here.
449
- for (let pass = 0; pass < next.length * 4 + 8; pass += 1) {
450
- const candidate = { ...record, toolInvocations: next };
451
- if (isBoundedEventContentJson(candidate))
452
- return { record: candidate, truncated };
453
- let widest = -1;
454
- let widestLength = 0;
455
- for (const [index, entry] of next.entries()) {
456
- const value = entry?.result;
457
- if (typeof value === "string" && value.length > widestLength) {
458
- widest = index;
459
- widestLength = value.length;
460
- }
461
- }
462
- // Nothing left to shrink: the overflow is elsewhere, and the caller refuses rather than
463
- // silently altering a field that is not tool output.
464
- if (widest < 0 || widestLength === 0)
465
- return { record, truncated };
466
- const entry = next[widest];
467
- const current = entry.result;
468
- const original = originalLengths.get(widest) ?? current.length;
469
- originalLengths.set(widest, original);
470
- // Cut by what the record is actually over, plus room for the marker and for JSON escaping,
471
- // which can widen a byte count well past the character count.
472
- const serialized = Buffer.byteLength(JSON.stringify(candidate) ?? "", "utf8");
473
- const overflow = Math.max(0, serialized - CONTRACT_MAX_JSON_BYTES);
474
- const marker = toolOutputTruncationMarker(0, original).length;
475
- const cut = Math.max(1, overflow + marker + 1024);
476
- const kept = Math.max(0, current.length - cut);
477
- entry.result = current.slice(0, kept) + toolOutputTruncationMarker(kept, original);
478
- truncated += 1;
479
- }
480
- return { record, truncated };
419
+ export function sandboxTerminalProjection(record) {
420
+ const { toolInvocations: _toolInvocations, ...terminal } = record;
421
+ return terminal;
481
422
  }
482
423
  export function validatedSandboxPromptResult(result) {
483
424
  if (!result || typeof result !== "object" || Array.isArray(result)) {
@@ -491,54 +432,16 @@ export function validatedSandboxPromptResult(result) {
491
432
  // The Sandbox SDK materializes absent optional response fields as
492
433
  // `undefined`. They were absent on the JSON wire and must stay absent in the
493
434
  // provider-neutral result before the strict JSON check runs.
494
- let record = Object.fromEntries(Object.entries(source).filter(([field, value]) => value !== undefined || !SANDBOX_OPTIONAL_RESULT_FIELDS.has(field)));
495
- // Oversized tool output is TRUNCATED, never thrown.
496
- //
497
- // This validator runs inside the terminal result read — after the live stream has drained and
498
- // after the usage receipt has been credited — so a throw here cannot prevent the work or the
499
- // charge. It can only discard a finished, fully paid turn, which a supervisor then reports as a
500
- // child that did nothing at all. That failure mode cost one Discovery Lab 143 of 199 children
501
- // across 16 pursuits, and its six-stage sourcing graph blocked in 24 of 24 invocations.
502
- //
503
- // Widening the bound alone does not remove it. The Sandbox SDK serializes each tool value up to
504
- // MAX_SERIALIZED_TOOL_VALUE_BYTES (4 MiB) while this bound is CONTRACT_MAX_JSON_BYTES (1 MiB)
505
- // across the WHOLE record, so a single 2 MiB fetch still dies, and so do two 0.6 MiB fetches
506
- // together. Any bound that throws on this path is one large page away from discarding a paid
507
- // turn again.
508
- //
509
- // So the bound is enforced by replacing what does not fit, and saying so in the record. The
510
- // caller still receives the turn, its response text, its usage, and every tool call it made;
511
- // what it loses is the tail of an oversized tool result, marked where it was cut. Only tool
512
- // output is truncatable: every other field is identity, accounting, or control material where a
513
- // silently shortened value would be worse than a refusal, so those still refuse below.
514
- const bounded = withTruncatedToolOutput(record);
515
- const content = boundedEventContentRecordSchema.safeParse(bounded.record);
435
+ const record = sandboxTerminalProjection(Object.fromEntries(Object.entries(source).filter(([field, value]) => value !== undefined || !SANDBOX_OPTIONAL_RESULT_FIELDS.has(field))));
436
+ const content = boundedEventContentRecordSchema.safeParse(record);
516
437
  if (!content.success) {
517
438
  throw new Error("Tangle prompt result exceeded its JSON bound", { cause: content.error });
518
439
  }
519
- record = bounded.record;
520
- // What the agent produced is content and is bounded as content by the check above; the fields
521
- // that describe the turn keep their metadata limits.
522
- //
523
- // `toolInvocations` belongs with the response text, not with the metadata. It carries whatever a
524
- // tool returned, and one `webfetch` of a paper or an API page is routinely tens or hundreds of
525
- // kilobytes, while the metadata bound is CONTRACT_MAX_STRING_LENGTH — 16,384 characters per
526
- // string. `isBoundedEventContentJson` was written for exactly this material ("content may contain
527
- // a single large transcript or tool result") and the whole record has already passed it at
528
- // CONTRACT_MAX_JSON_BYTES.
529
- //
530
- // Holding tool output to the metadata bound rejected a turn the Sandbox SDK had already accepted:
531
- // it serializes each tool value up to MAX_SERIALIZED_TOOL_VALUE_BYTES (4 MiB), a 256x mismatch.
532
- // Because this validator runs inside the terminal result read, AFTER the live stream has drained
533
- // and the usage receipt has been credited, the rejection did not fail the tool call — it
534
- // converted a finished, fully paid turn into an unreconcilable retained execution that a
535
- // supervisor reports as a child that did no work at all. Measured 2026-09-11 in one Discovery Lab
536
- // worktree: 143 of 199 children across 16 pursuits, every one at `iterations: 0`, and the
537
- // enumerate and extract stages that fetch papers were the ones that died.
440
+ // Text is content. Identity, accounting and interaction state retain their
441
+ // stricter metadata bounds. The projection does not mutate the native source.
538
442
  assertBoundedJson(Object.fromEntries(Object.entries(record).filter(([field]) => field !== "response" &&
539
443
  field !== "text" &&
540
- field !== "finalText" &&
541
- field !== "toolInvocations")), "Tangle prompt result");
444
+ field !== "finalText")), "Tangle prompt result");
542
445
  if (typeof record.success !== "boolean") {
543
446
  throw new Error("Tangle prompt result omitted its success status");
544
447
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "3.4.0",
3
+ "version": "3.4.1",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",