@kingsoftcloud/agentkit-harness-node 0.0.13 → 0.0.15

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/index.mjs CHANGED
@@ -373,6 +373,18 @@ function nativeContextStatus(record, { driving = false } = {}) {
373
373
 
374
374
  // packages/agentkit-harness-node/src/native/activity-status.mjs
375
375
  import { createHash as createHash2 } from "node:crypto";
376
+ import { canonical as canonical4 } from "@kingsoftcloud/agentkit-harness-core";
377
+ var settledCommandStates = /* @__PURE__ */ new Set(["completed", "failed", "canceled", "timed_out", "output_limit"]);
378
+ function foregroundReceiptState(record, ref, intent) {
379
+ if (ref.sourceRunId !== record.snapshot.runId || intent?.kind !== "tool" || intent.payload.calls?.length !== 1) return null;
380
+ const definition = record.configuration?.tools.find((tool) => tool.name === intent.payload.calls[0].name);
381
+ if (definition?.backgroundCommandPolicy !== "owned-command-launch/v1") return null;
382
+ const receipt = record.receipts?.find((row) => row.operationKey === ref.operationKey);
383
+ const results = receipt?.result?.results;
384
+ const result = results?.length === 1 ? results[0] : null;
385
+ if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
386
+ return result.content.status;
387
+ }
376
388
  function nativeActivityStatus(record, { driving = false } = {}) {
377
389
  if (!record) return null;
378
390
  const { snapshot } = record;
@@ -395,7 +407,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
395
407
  id: ref.taskId,
396
408
  runId: snapshot.runId,
397
409
  title: call?.arguments.command?.slice(0, 512) || ref.taskId,
398
- state: observed?.status ?? "unknown",
410
+ state: observed?.status ?? foregroundReceiptState(record, ref, intent) ?? "unknown",
399
411
  canCancel: false
400
412
  };
401
413
  });
@@ -416,14 +428,14 @@ function nativeActivityStatus(record, { driving = false } = {}) {
416
428
  }
417
429
 
418
430
  // packages/agentkit-harness-node/src/native/a2a-receipt-source.mjs
419
- import { canonical as canonical4 } from "@kingsoftcloud/agentkit-harness-core";
431
+ import { canonical as canonical5 } from "@kingsoftcloud/agentkit-harness-core";
420
432
  function nativeA2aReceiptWaitSource(record) {
421
433
  const snapshot = record?.snapshot, marker = snapshot?.toolReconciliation;
422
434
  if (snapshot?.phase !== "awaiting_reconciliation" || snapshot.pendingIntent !== null || marker?.contract !== "agentkit.tool-receipt-observation/v1") return null;
423
435
  const intent = record.intents.find((item) => item.operationKey === marker.operationKey);
424
436
  const call = intent?.payload.calls?.[0], definition = record.configuration.tools.find((item) => item.name === call?.name);
425
437
  const receipt = record.receipts.find((item) => item.operationKey === marker.operationKey);
426
- if (call?.name !== "call_a2a_agent" || definition?.recoveryPolicy !== "receipt-observation/v1" || intent.kind !== "tool" || intent.status !== "running" || intent.payload.calls.length !== 1 || !Number.isSafeInteger(intent.claimedFence) || intent.claimedFence <= 0 || call.callId !== marker.callId || canonical4(snapshot.pendingTools.slice(0, 1)) !== canonical4([call]) || !receipt || !(receipt.status === "uncertain" || receipt.result.results?.[0]?.status === "uncertain")) return null;
438
+ if (call?.name !== "call_a2a_agent" || definition?.recoveryPolicy !== "receipt-observation/v1" || intent.kind !== "tool" || intent.status !== "running" || intent.payload.calls.length !== 1 || !Number.isSafeInteger(intent.claimedFence) || intent.claimedFence <= 0 || call.callId !== marker.callId || canonical5(snapshot.pendingTools.slice(0, 1)) !== canonical5([call]) || !receipt || !(receipt.status === "uncertain" || receipt.result.results?.[0]?.status === "uncertain")) return null;
427
439
  return { intent, call, definition };
428
440
  }
429
441
 
@@ -440,7 +452,7 @@ function canCloseNativeReadInterruption(record) {
440
452
 
441
453
  // packages/agentkit-harness-node/src/native/run-observation.mjs
442
454
  var NATIVE_RUN_OBSERVATION = "agentkit.native-run-observation/v1";
443
- var NATIVE_COMMIT_PROJECTION = "agentkit.native-commit-projection/v2";
455
+ var NATIVE_COMMIT_PROJECTION = "agentkit.native-commit-projection/v3";
444
456
  function contextProjection(previous, record) {
445
457
  let lastPlan = previous?.lastPlan ?? null, lastAdmission = previous?.lastAdmission ?? null;
446
458
  for (const event of record.events ?? []) if (event.kind === "context.planned") {
@@ -471,7 +483,8 @@ function observationHeader(s) {
471
483
  "outcome",
472
484
  "reason",
473
485
  "pendingIntent",
474
- "toolReconciliation"
486
+ "toolReconciliation",
487
+ "retryNotBefore"
475
488
  ].filter((key) => s[key] !== void 0).map((key) => [key, s[key]]));
476
489
  header.diagnostics = Object.fromEntries(["providerUsageIncomplete", "descendantUsageIncomplete", "lastModelFailure"].filter((key) => s.diagnostics[key] !== void 0).map((key) => [key, s.diagnostics[key]]));
477
490
  return header;
@@ -595,7 +608,7 @@ function advanceNativeRunCommitObservation(previous, state, changes) {
595
608
  // packages/agentkit-harness-node/src/native/sqlite-store.mjs
596
609
  import {
597
610
  TransactionalRunStore,
598
- canonical as canonical5,
611
+ canonical as canonical6,
599
612
  invariant as invariant3,
600
613
  scopeKey,
601
614
  runKey,
@@ -668,7 +681,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
668
681
  for (const row of legacy) {
669
682
  const item = parseNativeJson2(row.data);
670
683
  invariant3(typeof item.fingerprint === "string", "invalid_commit_fingerprint");
671
- compact.run(canonical5({ ...item, fingerprint: commitFingerprint(item.fingerprint) }), row.rowid);
684
+ compact.run(canonical6({ ...item, fingerprint: commitFingerprint(item.fingerprint) }), row.rowid);
672
685
  }
673
686
  if (versions.length && versions[0].version === 1) db.prepare("UPDATE native_schema SET version=2").run();
674
687
  db.exec("COMMIT");
@@ -694,7 +707,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
694
707
  scopeKey(scope);
695
708
  const row = db.prepare(`SELECT data FROM native_runs
696
709
  WHERE json_extract(data,'$.snapshot.scope')=? AND json_extract(data,'$.snapshot.sessionId')=?
697
- ORDER BY rowid DESC LIMIT 1`).get(canonical5(scope), sessionId);
710
+ ORDER BY rowid DESC LIMIT 1`).get(canonical6(scope), sessionId);
698
711
  return row ? parseNativeJson2(row.data).snapshot : null;
699
712
  };
700
713
  const read = (key) => {
@@ -763,14 +776,14 @@ var SqliteRunStore = class extends TransactionalRunStore {
763
776
  return row ? parseNativeJson2(row.data) : null;
764
777
  };
765
778
  const writeDeliveryHead = (key, snapshot) => db.prepare(`INSERT INTO native_delivery_heads VALUES (?,?)
766
- ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical5(deliveryJournalHead(snapshot)));
779
+ ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(deliveryJournalHead(snapshot)));
767
780
  const appendDelivery = (key, evidence, snapshot) => {
768
781
  const insert = db.prepare(`INSERT INTO native_delivery_items VALUES (?,?,?,?)
769
782
  ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=CASE
770
783
  WHEN native_delivery_items.collection='tools'
771
784
  OR native_delivery_items.collection='outcomes' AND native_delivery_items.data='"not_dispatched"'
772
785
  THEN native_delivery_items.data ELSE excluded.data END`);
773
- for (const row of sessionDeliveryEntries(evidence)) insert.run(key, row.collection, row.key, canonical5(row.data));
786
+ for (const row of sessionDeliveryEntries(evidence)) insert.run(key, row.collection, row.key, canonical6(row.data));
774
787
  writeDeliveryHead(key, snapshot);
775
788
  };
776
789
  const rebuildDelivery = (key, record) => {
@@ -779,21 +792,21 @@ var SqliteRunStore = class extends TransactionalRunStore {
779
792
  };
780
793
  const persist = (key, previous, record) => {
781
794
  const { events, intents, receipts, commands, commits, ...metadata } = record;
782
- db.prepare("INSERT INTO native_runs(key,data) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(key, canonical5(metadata));
795
+ db.prepare("INSERT INTO native_runs(key,data) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(key, canonical6(metadata));
783
796
  invariant3(events.length >= (previous?.events.length ?? 0), "events_immutable");
784
797
  for (const event of events.slice(previous?.events.length ?? 0))
785
- db.prepare("INSERT INTO native_events VALUES (?,?,?,?)").run(key, event.seq, event.eventId, canonical5(event));
798
+ db.prepare("INSERT INTO native_events VALUES (?,?,?,?)").run(key, event.seq, event.eventId, canonical6(event));
786
799
  for (const [collection, identify] of Object.entries(collections)) {
787
- const old = new Map((previous?.[collection] ?? []).map((item) => [identify(item), canonical5(item)]));
800
+ const old = new Map((previous?.[collection] ?? []).map((item) => [identify(item), canonical6(item)]));
788
801
  invariant3(record[collection].length >= old.size, "ledger_items_immutable");
789
802
  for (const item of record[collection]) {
790
- const id = identify(item), data = canonical5(item);
803
+ const id = identify(item), data = canonical6(item);
791
804
  if (old.get(id) !== data) db.prepare("INSERT INTO native_items VALUES (?,?,?,?) ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=excluded.data").run(key, collection, id, data);
792
805
  }
793
806
  }
794
807
  if (!previous) inbox.consume(record.snapshot);
795
808
  db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
796
- ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical5(projectNativeRunObservation(record)));
809
+ ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(projectNativeRunObservation(record)));
797
810
  rebuildDelivery(key, record);
798
811
  beforeCommit?.({ key, record });
799
812
  };
@@ -850,7 +863,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
850
863
  const row = db.prepare("SELECT data FROM native_run_observations WHERE run_key=?").get(key);
851
864
  const observation = row ? parseNativeJson2(row.data) : null;
852
865
  const exceptional = !current || ["interrupted", "awaiting_reconciliation", "reconciling_tool"].some((phase) => current.snapshot.phase === phase || batch.snapshot.phase === phase);
853
- const compatible = observation?.contract === NATIVE_RUN_OBSERVATION && observation.commitProjection?.contract === NATIVE_COMMIT_PROJECTION && Array.isArray(observation.commitProjection?.tools?.calls) && Array.isArray(observation.facts?.toolOutcomes) && observation.snapshot.revision === current?.snapshot.revision && observation.snapshot.eventSeq === current?.snapshot.eventSeq && observation.snapshot.configDigest === current?.snapshot.configDigest && observation.snapshot.runId === current?.snapshot.runId && observation.snapshot.sessionId === current?.snapshot.sessionId && canonical5(observation.snapshot.scope) === canonical5(current?.snapshot.scope);
866
+ const compatible = observation?.contract === NATIVE_RUN_OBSERVATION && observation.commitProjection?.contract === NATIVE_COMMIT_PROJECTION && Array.isArray(observation.commitProjection?.tools?.calls) && Array.isArray(observation.facts?.toolOutcomes) && observation.snapshot.revision === current?.snapshot.revision && observation.snapshot.eventSeq === current?.snapshot.eventSeq && observation.snapshot.configDigest === current?.snapshot.configDigest && observation.snapshot.runId === current?.snapshot.runId && observation.snapshot.sessionId === current?.snapshot.sessionId && canonical6(observation.snapshot.scope) === canonical6(current?.snapshot.scope);
854
867
  if (exceptional || !compatible || !matchesDeliveryJournal(deliveryHead(key), current.snapshot)) {
855
868
  const previous = read(key), result = change(previous ? projectLedgerCommitState(previous, batch) : null);
856
869
  if (result.changes) persist(key, previous, applyLedgerCommitChanges(previous, result.changes));
@@ -860,16 +873,16 @@ var SqliteRunStore = class extends TransactionalRunStore {
860
873
  const { changes, value } = change(current);
861
874
  if (changes) {
862
875
  const { commands, intents, existingReceiptKeys, existingEventIds, duplicateCommit, ...metadata } = current;
863
- db.prepare("UPDATE native_runs SET data=? WHERE key=?").run(canonical5({ ...metadata, snapshot: changes.snapshot }), key);
876
+ db.prepare("UPDATE native_runs SET data=? WHERE key=?").run(canonical6({ ...metadata, snapshot: changes.snapshot }), key);
864
877
  const eventInsert = db.prepare("INSERT INTO native_events VALUES (?,?,?,?)");
865
- for (const event of changes.events) eventInsert.run(key, event.seq, event.eventId, canonical5(event));
878
+ for (const event of changes.events) eventInsert.run(key, event.seq, event.eventId, canonical6(event));
866
879
  const itemInsert = db.prepare("INSERT INTO native_items VALUES (?,?,?,?)");
867
880
  for (const [collection, items] of [["intents", changes.intents], ["receipts", changes.receipts], ["commits", [changes.commit]]])
868
- for (const item of items) itemInsert.run(key, collection, collections[collection](item), canonical5(item));
881
+ for (const item of items) itemInsert.run(key, collection, collections[collection](item), canonical6(item));
869
882
  const commandUpdate = db.prepare("UPDATE native_items SET data=? WHERE run_key=? AND collection='commands' AND item_key=?");
870
- for (const row2 of changes.commands) commandUpdate.run(canonical5(row2), key, row2.command.commandId);
883
+ for (const row2 of changes.commands) commandUpdate.run(canonical6(row2), key, row2.command.commandId);
871
884
  const advanced = advanceNativeRunCommitObservation(observation, current, changes);
872
- db.prepare("UPDATE native_run_observations SET data=? WHERE run_key=?").run(canonical5(advanced), key);
885
+ db.prepare("UPDATE native_run_observations SET data=? WHERE run_key=?").run(canonical6(advanced), key);
873
886
  appendDelivery(key, {
874
887
  events: changes.events,
875
888
  receipts: changes.receipts,
@@ -908,27 +921,27 @@ var SqliteRunStore = class extends TransactionalRunStore {
908
921
  const presentationCurrent = matchesDeliveryJournal(deliveryHead(key), current.snapshot);
909
922
  const cached = db.prepare("SELECT data FROM native_run_observations WHERE run_key=?").get(key);
910
923
  let observation = cached ? parseNativeJson2(cached.data) : null;
911
- if (!observation || observation.contract !== NATIVE_RUN_OBSERVATION || observation.commitProjection?.contract !== NATIVE_COMMIT_PROJECTION || !Array.isArray(observation.commitProjection?.tools?.calls) || !Array.isArray(observation.facts?.toolOutcomes) || observation.snapshot.revision !== current.snapshot.revision || observation.snapshot.eventSeq !== current.snapshot.eventSeq || observation.snapshot.configDigest !== current.snapshot.configDigest || observation.snapshot.runId !== current.snapshot.runId || observation.snapshot.sessionId !== current.snapshot.sessionId || canonical5(observation.snapshot.scope) !== canonical5(current.snapshot.scope))
924
+ if (!observation || observation.contract !== NATIVE_RUN_OBSERVATION || observation.commitProjection?.contract !== NATIVE_COMMIT_PROJECTION || !Array.isArray(observation.commitProjection?.tools?.calls) || !Array.isArray(observation.facts?.toolOutcomes) || observation.snapshot.revision !== current.snapshot.revision || observation.snapshot.eventSeq !== current.snapshot.eventSeq || observation.snapshot.configDigest !== current.snapshot.configDigest || observation.snapshot.runId !== current.snapshot.runId || observation.snapshot.sessionId !== current.snapshot.sessionId || canonical6(observation.snapshot.scope) !== canonical6(current.snapshot.scope))
912
925
  observation = projectNativeRunObservation(read(key));
913
926
  if (changes.claim) {
914
927
  const { snapshot, intent } = changes.claim;
915
- db.prepare("UPDATE native_runs SET data=json_set(data,'$.snapshot',json(?)) WHERE key=?").run(canonical5(snapshot), key);
928
+ db.prepare("UPDATE native_runs SET data=json_set(data,'$.snapshot',json(?)) WHERE key=?").run(canonical6(snapshot), key);
916
929
  const result = db.prepare(`UPDATE native_items SET data=?
917
- WHERE run_key=? AND collection='intents' AND item_key=?`).run(canonical5(intent), key, intent.operationKey);
930
+ WHERE run_key=? AND collection='intents' AND item_key=?`).run(canonical6(intent), key, intent.operationKey);
918
931
  invariant3(result.changes === 1, "pending_intent_missing");
919
932
  }
920
933
  if (changes.commands) {
921
- const previous = new Map(current.commands.map((row) => [row.command.commandId, canonical5(row)]));
934
+ const previous = new Map(current.commands.map((row) => [row.command.commandId, canonical6(row)]));
922
935
  for (const row of changes.commands) {
923
- const data = canonical5(row), id = row.command.commandId;
936
+ const data = canonical6(row), id = row.command.commandId;
924
937
  if (previous.get(id) !== data) db.prepare(`INSERT INTO native_items VALUES (?,?,?,?)
925
938
  ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=excluded.data`).run(key, "commands", id, data);
926
939
  }
927
940
  }
928
- if (changes.projections) db.prepare("UPDATE native_runs SET data=json_set(data,'$.projections',json(?)) WHERE key=?").run(canonical5(changes.projections), key);
941
+ if (changes.projections) db.prepare("UPDATE native_runs SET data=json_set(data,'$.projections',json(?)) WHERE key=?").run(canonical6(changes.projections), key);
929
942
  const updated = advanceNativeRunControlObservation(observation, current, changes);
930
943
  db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
931
- ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical5(updated));
944
+ ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(updated));
932
945
  if (presentationCurrent) writeDeliveryHead(key, changes.claim?.snapshot ?? current.snapshot);
933
946
  }
934
947
  db.exec("COMMIT");
@@ -946,7 +959,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
946
959
  'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
947
960
  'backgroundCommands',json_extract(data,'$.snapshot.backgroundCommands'), 'lease',json_extract(data,'$.lease')) AS head
948
961
  FROM native_runs WHERE json_extract(data,'$.snapshot.scope')=? AND json_extract(data,'$.snapshot.sessionId')=?
949
- ORDER BY rowid DESC LIMIT 1`).get(canonical5(scope), sessionId);
962
+ ORDER BY rowid DESC LIMIT 1`).get(canonical6(scope), sessionId);
950
963
  return row ? parseNativeJson2(row.head) : null;
951
964
  },
952
965
  projectionCursors: (key) => {
@@ -1022,7 +1035,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1022
1035
  ...row.retirement === null ? {} : { resourceRetirementReview: parseNativeJson2(row.retirement) }
1023
1036
  } : null);
1024
1037
  invariant3(row, "run_not_found");
1025
- db.prepare(`UPDATE native_runs SET data=json_set(data,'$.lease',json(?),'$.fence',?) WHERE key=?`).run(canonical5(record.lease), record.fence, key);
1038
+ db.prepare(`UPDATE native_runs SET data=json_set(data,'$.lease',json(?),'$.fence',?) WHERE key=?`).run(canonical6(record.lease), record.fence, key);
1026
1039
  db.exec("COMMIT");
1027
1040
  return value;
1028
1041
  } catch (error) {
@@ -1073,7 +1086,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1073
1086
  open();
1074
1087
  return db.prepare(`SELECT json_extract(data,'$.snapshot') AS snapshot FROM native_runs
1075
1088
  WHERE json_extract(data,'$.snapshot.scope')=?
1076
- ${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical5(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.snapshot));
1089
+ ${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical6(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.snapshot));
1077
1090
  },
1078
1091
  heads: (scope, sessionId) => {
1079
1092
  open();
@@ -1083,7 +1096,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1083
1096
  'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
1084
1097
  'backgroundCommands',json_extract(data,'$.snapshot.backgroundCommands'), 'lease',json_extract(data,'$.lease')) AS head
1085
1098
  FROM native_runs WHERE json_extract(data,'$.snapshot.scope')=?
1086
- ${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical5(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.head));
1099
+ ${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical6(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.head));
1087
1100
  },
1088
1101
  values: () => {
1089
1102
  open();
@@ -1125,6 +1138,29 @@ var SqliteRunStore = class extends TransactionalRunStore {
1125
1138
  }
1126
1139
  }
1127
1140
  });
1141
+ this.traceView = (scope, runId, after = 0) => {
1142
+ open();
1143
+ invariant3(Number.isSafeInteger(after) && after >= 0, "invalid_trace_cursor");
1144
+ const key = runKey(scope, runId);
1145
+ db.exec("BEGIN");
1146
+ try {
1147
+ const row = db.prepare(`SELECT json_object(
1148
+ 'scope',json_extract(data,'$.snapshot.scope'), 'runId',json_extract(data,'$.snapshot.runId'),
1149
+ 'sessionId',json_extract(data,'$.snapshot.sessionId'), 'phase',json_extract(data,'$.snapshot.phase'),
1150
+ 'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
1151
+ 'usage',json_extract(data,'$.snapshot.usage'), 'outcome',json_extract(data,'$.snapshot.outcome')) AS snapshot
1152
+ FROM native_runs WHERE key=?`).get(key);
1153
+ invariant3(row, "run_not_found");
1154
+ const snapshot = parseNativeJson2(row.snapshot);
1155
+ invariant3(snapshot.runId === runId && canonical6(snapshot.scope) === canonical6(scope), "native_trace_identity_mismatch");
1156
+ const events = db.prepare("SELECT data FROM native_events WHERE run_key=? AND seq>? AND seq<=? ORDER BY seq").all(key, after, snapshot.eventSeq).map((row2) => parseNativeJson2(row2.data));
1157
+ db.exec("COMMIT");
1158
+ return { contract: "agentkit.native-trace-view/v1", snapshot, events };
1159
+ } catch (error) {
1160
+ db.exec("ROLLBACK");
1161
+ throw error;
1162
+ }
1163
+ };
1128
1164
  this.sessionDeliveryState = (scope, runId) => {
1129
1165
  open();
1130
1166
  const key = runKey(scope, runId);
@@ -1136,7 +1172,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1136
1172
  invariant3(row, "run_not_found");
1137
1173
  const snapshot = parseNativeJson2(row.snapshot), presence = parseNativeJson2(row.presence);
1138
1174
  for (const [name, type] of Object.entries(presence)) if (type === null) delete snapshot[name];
1139
- invariant3(snapshot.runId === runId && canonical5(snapshot.scope) === canonical5(scope), "delivery_identity_mismatch");
1175
+ invariant3(snapshot.runId === runId && canonical6(snapshot.scope) === canonical6(scope), "delivery_identity_mismatch");
1140
1176
  return { snapshot, configuration: parseNativeJson2(row.configuration), projections: parseNativeJson2(row.projections) };
1141
1177
  };
1142
1178
  db.exec("BEGIN");
@@ -1160,11 +1196,11 @@ var SqliteRunStore = class extends TransactionalRunStore {
1160
1196
  WHERE run_key=? AND collection='receipts' AND item_key=?`).get(path, path + ".status", path + ".context", path + ".content", key, reference.operationKey);
1161
1197
  }
1162
1198
  if (receipt?.status === "committed" && receipt.observed === "object") return {
1163
- context: receipt.context === null ? { content: canonical5(parseNativeJson2(receipt.content)) } : toolContext2(parseNativeJson2(receipt.context)),
1199
+ context: receipt.context === null ? { content: canonical6(parseNativeJson2(receipt.content)) } : toolContext2(parseNativeJson2(receipt.context)),
1164
1200
  isError: receipt.resultStatus !== "ok"
1165
1201
  };
1166
1202
  const unknown = intent?.status === "running" && (!receipt || receipt.status === "uncertain");
1167
- return { context: { content: canonical5({
1203
+ return { context: { content: canonical6({
1168
1204
  status: unknown ? "uncertain" : "not_dispatched",
1169
1205
  reason: unknown ? "effect_outcome_unknown" : current.snapshot.reason ?? "run_ended"
1170
1206
  }) }, isError: true };
@@ -1198,9 +1234,9 @@ var SqliteRunStore = class extends TransactionalRunStore {
1198
1234
  invariant3(head, "run_not_found");
1199
1235
  view = projectNativeRunObservation(read(key));
1200
1236
  db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
1201
- ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical5(view));
1237
+ ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(view));
1202
1238
  }
1203
- invariant3(canonical5(view.snapshot.scope) === canonical5(scope) && view.snapshot.runId === runId && view.snapshot.sessionId === head.sessionId, "observation_identity_mismatch");
1239
+ invariant3(canonical6(view.snapshot.scope) === canonical6(scope) && view.snapshot.runId === runId && view.snapshot.sessionId === head.sessionId, "observation_identity_mismatch");
1204
1240
  view.lease = head.lease === null ? null : parseNativeJson2(head.lease);
1205
1241
  view.fence = head.fence;
1206
1242
  view.projections = parseNativeJson2(head.projections);
@@ -1227,7 +1263,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1227
1263
  OR json_extract(v.data,'$.snapshot.configDigest')<>json_extract(r.data,'$.snapshot.configDigest')
1228
1264
  OR json_extract(v.data,'$.snapshot.scope')<>json_extract(r.data,'$.snapshot.scope')
1229
1265
  OR json_extract(v.data,'$.snapshot.sessionId')<>json_extract(r.data,'$.snapshot.sessionId')
1230
- OR json_extract(v.data,'$.snapshot.runId')<>json_extract(r.data,'$.snapshot.runId'))`).all(canonical5(scope), sessionId, NATIVE_RUN_OBSERVATION, NATIVE_COMMIT_PROJECTION);
1266
+ OR json_extract(v.data,'$.snapshot.runId')<>json_extract(r.data,'$.snapshot.runId'))`).all(canonical6(scope), sessionId, NATIVE_RUN_OBSERVATION, NATIVE_COMMIT_PROJECTION);
1231
1267
  for (const { runId } of missing) this.observation(scope, runId);
1232
1268
  return db.prepare(`SELECT json_extract(v.data,'$.snapshot.runId') AS runId,
1233
1269
  json_extract(v.data,'$.snapshot.turnId') AS turnId, json_extract(c.value,'$.callId') AS callId,
@@ -1239,7 +1275,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
1239
1275
  AND json_extract(v.data,'$.snapshot.sessionId')=json_extract(r.data,'$.snapshot.sessionId')
1240
1276
  AND json_extract(v.data,'$.snapshot.runId')=json_extract(r.data,'$.snapshot.runId')
1241
1277
  AND json_extract(c.value,'$.status') IN ('uncertain','not_dispatched')
1242
- ORDER BY r.rowid,callId`).all(canonical5(scope), sessionId).map((row) => ({ ...row }));
1278
+ ORDER BY r.rowid,callId`).all(canonical6(scope), sessionId).map((row) => ({ ...row }));
1243
1279
  };
1244
1280
  this.uncertainToolCalls = (scope, sessionId) => this.sessionToolOutcomes(scope, sessionId).filter((row) => row.status === "uncertain").map(({ status, ...row }) => row);
1245
1281
  this.listScopes = (principal) => {
@@ -1602,7 +1638,7 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
1602
1638
 
1603
1639
  // packages/agentkit-harness-node/src/native/model-replay.mjs
1604
1640
  import { createHash as createHash4 } from "node:crypto";
1605
- import { canonical as canonical6, modelWireToolCall } from "@kingsoftcloud/agentkit-harness-core";
1641
+ import { canonical as canonical7, modelWireToolCall } from "@kingsoftcloud/agentkit-harness-core";
1606
1642
  var SEALED_KINDS = /* @__PURE__ */ new Set(["tool_calls", "final_candidate", "output_limit"]);
1607
1643
  function profileFingerprint(profile) {
1608
1644
  return `${String(profile?.profileId ?? "")}\0${String(profile?.profileVersion ?? "")}\0${String(profile?.compatibilityDigest ?? "")}`;
@@ -1660,7 +1696,7 @@ function anthropicReplayContent(message, profile) {
1660
1696
  if (!validateReplayPairing(blocks, message)) return null;
1661
1697
  const view = message.providerReplayProjection;
1662
1698
  if (view) {
1663
- const contentDigest = createHash4("sha256").update(canonical6(replay.anthropicContent)).digest("hex");
1699
+ const contentDigest = createHash4("sha256").update(canonical7(replay.anthropicContent)).digest("hex");
1664
1700
  if (profile.providerReplayProjectionPolicy !== "anthropic-client-compaction/v1" || view.version !== "anthropic-client-compaction/v1" || view.profileDigest !== profile.compatibilityDigest || view.originalContentDigest !== contentDigest || !/^[0-9a-f]{64}$/.test(view.prefixDigest))
1665
1701
  throw new ProtocolError("anthropic_replay_projection_mismatch");
1666
1702
  blocks = blocks.filter((block) => !["thinking", "redacted_thinking"].includes(block?.type));
@@ -2001,21 +2037,28 @@ function applyAnthropicThinking(payload, profile, binding) {
2001
2037
  }
2002
2038
  function resolveProviderCompatibility(policy, binding) {
2003
2039
  if (!policy) return null;
2004
- if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2040
+ if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2005
2041
  const rule = resolveCompatibilityRule(policy.rule, binding);
2006
2042
  const name = String(binding.model ?? "").trim().toLowerCase();
2007
2043
  const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
2008
- const reasoningRequired = policy.contract === "provider-compat/v3" && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2044
+ const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
2045
+ const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2009
2046
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
2010
2047
  return {
2011
2048
  rule,
2012
2049
  supportsUsage: !strict.has(rule),
2013
2050
  supportsThinking: !strict.has(rule) && !kimi,
2014
- supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2051
+ supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2015
2052
  reasoningRequired,
2016
- modern: policy.contract === "provider-compat/v3",
2053
+ modern,
2054
+ // This route already uses the supported non-thinking mode for tool work.
2055
+ // A bounded summary has no tools: omitting the switch can instead select
2056
+ // the provider's default high reasoning and consume its whole output cap.
2057
+ // Freeze this purpose-specific default only on new admissions; mandatory
2058
+ // thinking models and explicit caller choices remain authoritative.
2059
+ compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
2017
2060
  // Only the observed provider/model dialects may seal without [DONE].
2018
- finishOnEof: policy.contract === "provider-compat/v3" && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2061
+ finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2019
2062
  supportsEffort: !kimi,
2020
2063
  toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
2021
2064
  thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
@@ -2070,11 +2113,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
2070
2113
  if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
2071
2114
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
2072
2115
  const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
2116
+ const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
2073
2117
  const budget = result.max_completion_tokens ?? result.max_tokens;
2074
2118
  if (mode === "enabled") {
2075
2119
  if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
2076
2120
  result.thinking = { type: "enabled" };
2077
- } else if (mayDisable && (mode === "disabled" || summaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2121
+ } else if (mayDisable && (mode === "disabled" || summaryOff || boundedSummaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2078
2122
  if (!compat.supportsThinking) delete result.thinking;
2079
2123
  if (!compat.supportsEffort) delete result.reasoning_effort;
2080
2124
  if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
@@ -2111,6 +2155,80 @@ function explicitLiteralTypes(schema) {
2111
2155
  return result;
2112
2156
  }
2113
2157
 
2158
+ // packages/agentkit-harness-node/src/native/model-provider-error.mjs
2159
+ import { createHash as createHash6 } from "node:crypto";
2160
+ import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
2161
+ var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
2162
+ "rate_limit_error",
2163
+ "rate_limit_exceeded",
2164
+ "overloaded_error",
2165
+ "server_error",
2166
+ "api_error",
2167
+ "service_unavailable_error",
2168
+ "server_is_overloaded",
2169
+ "timeout_error",
2170
+ "MODEL_PROVIDER_RATE_LIMIT",
2171
+ "MODEL_PROVIDER_UNAVAILABLE"
2172
+ ]);
2173
+ var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
2174
+ "invalid_request_error",
2175
+ "invalid_api_key",
2176
+ "authentication_error",
2177
+ "permission_error",
2178
+ "not_found_error",
2179
+ "request_too_large",
2180
+ "billing_error",
2181
+ "insufficient_quota",
2182
+ "MODEL_PROVIDER_AUTHENTICATION",
2183
+ "MODEL_PROVIDER_PERMISSION",
2184
+ "MODEL_PROVIDER_INVALID_REQUEST",
2185
+ "MODEL_PROVIDER_NOT_FOUND",
2186
+ "MODEL_PROVIDER_QUOTA_EXHAUSTED"
2187
+ ]);
2188
+ function classifyOpenAIProviderError(error) {
2189
+ const decision = classifyError(error);
2190
+ let fingerprint;
2191
+ try {
2192
+ fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
2193
+ } catch {
2194
+ return decision;
2195
+ }
2196
+ const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
2197
+ return { ...decision, diagnostic: {
2198
+ category: decision.failureKind,
2199
+ fingerprint,
2200
+ ...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
2201
+ ...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
2202
+ ...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
2203
+ } };
2204
+ }
2205
+ function classifyError(error) {
2206
+ const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
2207
+ if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
2208
+ if (error.type != null && typeof error.type !== "string") return invalid;
2209
+ const status = typeof error.code === "number" ? error.code : null;
2210
+ if (status != null && (!Number.isInteger(status) || status < 400 || status > 599)) return invalid;
2211
+ const codes = [status == null ? error.code : null, error.type].filter((value) => value != null);
2212
+ if (codes.some((value) => typeof value !== "string")) return invalid;
2213
+ if (codes.some((value) => TERMINAL_ERROR_CODES.has(value))) {
2214
+ return { kind: "provider_terminal_error", failureKind: "client_error" };
2215
+ }
2216
+ if (status != null) {
2217
+ if (status === 408) return { kind: "provider_retryable_error", failureKind: "request_timeout" };
2218
+ if (status === 429) return { kind: "provider_retryable_error", failureKind: "rate_limit" };
2219
+ return {
2220
+ kind: status >= 500 ? "provider_retryable_error" : "provider_terminal_error",
2221
+ failureKind: status >= 500 ? "server_error" : "client_error"
2222
+ };
2223
+ }
2224
+ const code = codes.find((value) => RETRYABLE_ERROR_CODES.has(value));
2225
+ if (code) return {
2226
+ kind: "provider_retryable_error",
2227
+ failureKind: ["rate_limit_error", "rate_limit_exceeded", "MODEL_PROVIDER_RATE_LIMIT"].includes(code) ? "rate_limit" : code === "timeout_error" ? "request_timeout" : "server_error"
2228
+ };
2229
+ return invalid;
2230
+ }
2231
+
2114
2232
  // packages/agentkit-harness-node/src/native/model-chat-usage.mjs
2115
2233
  var CUMULATIVE_CHAT_USAGE = "cumulative-snapshots/v1";
2116
2234
  var fields = ["inputTokens", "outputTokens", "cachedInputTokens", "reasoningTokens"];
@@ -2302,7 +2420,14 @@ function parseOpenAIBuffered(bodyText, request, { captureReplay = false, binding
2302
2420
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
2303
2421
  throw new ProtocolError("invalid response envelope", "envelope_invalid");
2304
2422
  }
2305
- if ("error" in payload) throw new ProtocolError("invalid response envelope", "provider_error");
2423
+ if ("error" in payload) {
2424
+ if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
2425
+ throw new ProtocolError("conflicting error envelope", "envelope_invalid");
2426
+ }
2427
+ throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
2428
+ streamError: classifyOpenAIProviderError(payload.error)
2429
+ });
2430
+ }
2306
2431
  const choices = payload.choices;
2307
2432
  if (!Array.isArray(choices) || choices.length > 1) {
2308
2433
  throw new ProtocolError("expected one completion choice", "choice_invalid");
@@ -2478,7 +2603,14 @@ function createOpenAIStreamTurn(profile, binding) {
2478
2603
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
2479
2604
  throw new ProtocolError("invalid stream envelope", "envelope_invalid");
2480
2605
  }
2481
- if ("error" in payload) throw new ProtocolError("invalid stream envelope", "provider_error");
2606
+ if ("error" in payload) {
2607
+ if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
2608
+ throw new ProtocolError("conflicting error envelope", "envelope_invalid");
2609
+ }
2610
+ throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
2611
+ streamError: classifyOpenAIProviderError(payload.error)
2612
+ });
2613
+ }
2482
2614
  if (payload.id != null) {
2483
2615
  if (typeof payload.id !== "string" || !payload.id) throw new ProtocolError("invalid completion ID", "identity_conflict");
2484
2616
  if (this.completionId != null && payload.id !== this.completionId) {
@@ -2933,7 +3065,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
2933
3065
  if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
2934
3066
  const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
2935
3067
  for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
2936
- const inverse = new Map([...wireIds].map(([canonical7, original]) => [canonical7, original]));
3068
+ const inverse = new Map([...wireIds].map(([canonical9, original]) => [canonical9, original]));
2937
3069
  blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
2938
3070
  } else blocks = replayContent;
2939
3071
  } else {
@@ -2994,8 +3126,13 @@ function parseAnthropicBuffered(bodyText, request, { captureReplay = false, onTh
2994
3126
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
2995
3127
  throw new ProtocolError("invalid response envelope", "envelope_invalid");
2996
3128
  }
3129
+ if ("error" in payload) {
3130
+ if (payload.type !== "error") throw new ProtocolError("conflicting error envelope", "envelope_invalid");
3131
+ throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
3132
+ streamError: classifyAnthropicStreamError(payload.error)
3133
+ });
3134
+ }
2997
3135
  if ("type" in payload && payload.type !== "message") throw new ProtocolError("invalid response envelope", "envelope_invalid");
2998
- if ("error" in payload) throw new ProtocolError("invalid response envelope", "envelope_invalid");
2999
3136
  if (typeof payload.stop_sequence !== "undefined" && payload.stop_sequence !== null && typeof payload.stop_sequence !== "string") {
3000
3137
  throw new ProtocolError("invalid stop_sequence");
3001
3138
  }
@@ -3489,33 +3626,6 @@ var HOSTED_ITEM_TYPES = /* @__PURE__ */ new Set([
3489
3626
  "mcp_call",
3490
3627
  "local_shell_call"
3491
3628
  ]);
3492
- var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
3493
- "rate_limit_error",
3494
- "rate_limit_exceeded",
3495
- "overloaded_error",
3496
- "server_error",
3497
- "api_error",
3498
- "service_unavailable_error",
3499
- "server_is_overloaded",
3500
- "timeout_error",
3501
- "MODEL_PROVIDER_RATE_LIMIT",
3502
- "MODEL_PROVIDER_UNAVAILABLE"
3503
- ]);
3504
- var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
3505
- "invalid_request_error",
3506
- "invalid_api_key",
3507
- "authentication_error",
3508
- "permission_error",
3509
- "not_found_error",
3510
- "request_too_large",
3511
- "billing_error",
3512
- "insufficient_quota",
3513
- "MODEL_PROVIDER_AUTHENTICATION",
3514
- "MODEL_PROVIDER_PERMISSION",
3515
- "MODEL_PROVIDER_INVALID_REQUEST",
3516
- "MODEL_PROVIDER_NOT_FOUND",
3517
- "MODEL_PROVIDER_QUOTA_EXHAUSTED"
3518
- ]);
3519
3629
  function securityHeaders3() {
3520
3630
  return /* @__PURE__ */ new Set(["authorization", "x-api-key", "anthropic-version", "content-type", "accept"]);
3521
3631
  }
@@ -3776,9 +3886,9 @@ function projectResponsesOutput(payload, { status }) {
3776
3886
  reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
3777
3887
  }
3778
3888
  }
3779
- const canonical7 = messages.join("");
3889
+ const canonical9 = messages.join("");
3780
3890
  const convenience = optionalText(payload.output_text);
3781
- if ("output" in payload && payload.output_text != null && canonical7 !== convenience) {
3891
+ if ("output" in payload && payload.output_text != null && canonical9 !== convenience) {
3782
3892
  throw new ProtocolError("invalid model frame", "envelope_invalid");
3783
3893
  }
3784
3894
  let finish;
@@ -3798,7 +3908,7 @@ function projectResponsesOutput(payload, { status }) {
3798
3908
  finish = "content_filter";
3799
3909
  calls.length = 0;
3800
3910
  }
3801
- return { finish, content: canonical7 || convenience, reasoning: reasoning.join(""), calls, refused };
3911
+ return { finish, content: canonical9 || convenience, reasoning: reasoning.join(""), calls, refused };
3802
3912
  }
3803
3913
  function responseMessageContent(value) {
3804
3914
  if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
@@ -3838,8 +3948,13 @@ function parseResponsesBuffered(bodyText, request, { captureReplay = false, onTh
3838
3948
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
3839
3949
  throw new ProtocolError("invalid response envelope", "envelope_invalid");
3840
3950
  }
3951
+ if (payload.error != null || payload.status === "failed") {
3952
+ if (payload.status != null && payload.status !== "failed") throw new ProtocolError("conflicting response envelope", "envelope_invalid");
3953
+ throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
3954
+ streamError: classifyOpenAIProviderError(payload.error)
3955
+ });
3956
+ }
3841
3957
  const status = identityOf(payload.status);
3842
- if (payload.error != null) throw new ProtocolError("invalid response envelope", "envelope_invalid");
3843
3958
  if (status === "failed") throw new ProtocolError("invalid response envelope", "envelope_invalid");
3844
3959
  validateBufferedIdentity(payload);
3845
3960
  const reportedUsage = parseResponsesUsage(payload.usage);
@@ -4372,21 +4487,7 @@ function createResponsesStreamState(profile) {
4372
4487
  }
4373
4488
  const usage = parseResponsesUsage(failedBody.usage);
4374
4489
  if (usage != null) this.usage = usage;
4375
- const errorObj = failedBody.error != null && typeof failedBody.error === "object" ? failedBody.error : {};
4376
- const code = String(errorObj.code || errorObj.type || "");
4377
- let kind;
4378
- let failureKind;
4379
- if (RETRYABLE_ERROR_CODES.has(code)) {
4380
- kind = "provider_retryable_error";
4381
- failureKind = code === "rate_limit_error" || code === "rate_limit_exceeded" ? "rate_limit" : "server_error";
4382
- } else if (TERMINAL_ERROR_CODES.has(code)) {
4383
- kind = "provider_terminal_error";
4384
- failureKind = "client_error";
4385
- } else {
4386
- kind = "provider_terminal_error";
4387
- failureKind = "invalid_response";
4388
- }
4389
- this.streamError = { kind, failureKind };
4490
+ this.streamError = classifyOpenAIProviderError(failedBody.error);
4390
4491
  },
4391
4492
  handleTerminal(event, { text: drainText, reasoning: drainReasoning }, emit) {
4392
4493
  const responsePayload = objectOf(event.response);
@@ -4483,6 +4584,9 @@ function createResponsesStreamState(profile) {
4483
4584
  const { usage, usageReported } = sealUsage(this.usage);
4484
4585
  const reasoning = this.reasoning;
4485
4586
  if (this.streamError) {
4587
+ if (this.streamError.kind === "provider_retryable_error" && (this.refused || this.finish === "content_filter")) {
4588
+ return { kind: "policy_abort", text: this.text, toolCalls: [], usage, usageReported };
4589
+ }
4486
4590
  return {
4487
4591
  kind: this.streamError.kind,
4488
4592
  text: this.text,
@@ -4741,14 +4845,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4741
4845
  const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
4742
4846
  const abort = (reason) => internal.abort(reason);
4743
4847
  let frameIndex = -1;
4744
- const failed = (result2, code) => withFailure(
4848
+ const failed = (result2, code, fields2 = {}) => withFailure(
4745
4849
  result2,
4746
4850
  binding,
4747
4851
  "stream",
4748
4852
  code,
4749
4853
  {
4750
4854
  ...frameIndex < 0 ? {} : { frameIndex },
4751
- ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
4855
+ ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
4856
+ ...fields2
4752
4857
  }
4753
4858
  );
4754
4859
  try {
@@ -4770,7 +4875,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4770
4875
  }
4771
4876
  if (error instanceof ProtocolError) {
4772
4877
  if (error.streamError) {
4773
- return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), "provider_error");
4878
+ return failed(
4879
+ state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
4880
+ "provider_error",
4881
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4882
+ );
4774
4883
  }
4775
4884
  return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
4776
4885
  }
@@ -4780,7 +4889,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4780
4889
  return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
4781
4890
  }
4782
4891
  const result = state.finalize();
4783
- return failed(result, state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid");
4892
+ return failed(
4893
+ result,
4894
+ state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
4895
+ state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
4896
+ );
4784
4897
  }
4785
4898
  async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
4786
4899
  const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
@@ -4797,6 +4910,16 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
4797
4910
  }
4798
4911
  return withFailure(parseOpenAIBuffered(bodyText, request, { captureReplay, binding, onThinking }), binding, "buffered", "protocol_invalid");
4799
4912
  } catch (error) {
4913
+ if (error instanceof ProtocolError && error.streamError) {
4914
+ const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
4915
+ return withFailure(
4916
+ result,
4917
+ binding,
4918
+ "buffered",
4919
+ "provider_error",
4920
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4921
+ );
4922
+ }
4800
4923
  return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
4801
4924
  }
4802
4925
  }
@@ -4841,7 +4964,7 @@ function protocolCode(error) {
4841
4964
  function withFailure(result, binding, phase, code, fields2 = {}) {
4842
4965
  if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
4843
4966
  const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
4844
- return { ...result, failureDiagnostic: { contract: fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4967
+ return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4845
4968
  }
4846
4969
  function retryableResult(failureKind, retryAfterMs = null) {
4847
4970
  const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };