@tangle-network/agent-app 4.0.13 → 4.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.
Files changed (32) hide show
  1. package/dist/billing/identity-bound.d.ts +14 -9
  2. package/dist/billing/index.js +1 -1
  3. package/dist/chat-routes/detached-turn.d.ts +1 -1
  4. package/dist/chat-routes/failure-wording.d.ts +3 -4
  5. package/dist/chat-routes/index.js +5 -5
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/{chunk-XCUT2I52.js → chunk-5QQBQS7W.js} +8 -2
  8. package/dist/{chunk-XCUT2I52.js.map → chunk-5QQBQS7W.js.map} +1 -1
  9. package/dist/{chunk-GWATTXFR.js → chunk-FYF564KJ.js} +2 -2
  10. package/dist/{chunk-QPD42X6A.js → chunk-G4NHCLYA.js} +17 -9
  11. package/dist/chunk-G4NHCLYA.js.map +1 -0
  12. package/dist/{chunk-TMWUWKLU.js → chunk-GE242CLI.js} +2 -2
  13. package/dist/{chunk-RNDWCT4O.js → chunk-MZZMOGFN.js} +101 -89
  14. package/dist/{chunk-RNDWCT4O.js.map → chunk-MZZMOGFN.js.map} +1 -1
  15. package/dist/{chunk-CD4SJXYC.js → chunk-RFXROORA.js} +12 -12
  16. package/dist/chunk-RFXROORA.js.map +1 -0
  17. package/dist/platform/delegated-keys.d.ts +5 -1
  18. package/dist/platform/index.js +8 -2
  19. package/dist/platform/index.js.map +1 -1
  20. package/dist/preset-cloudflare/index.js +3 -3
  21. package/dist/public-consultation/index.js +3 -3
  22. package/dist/runtime/index.js +2 -2
  23. package/dist/runtime/router-turn.js +1 -1
  24. package/dist/spend/delegate-budget.d.ts +4 -0
  25. package/dist/spend/index.js.map +1 -1
  26. package/dist/turn-health/index.js +3 -1
  27. package/dist/turn-health/index.js.map +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-CD4SJXYC.js.map +0 -1
  30. package/dist/chunk-QPD42X6A.js.map +0 -1
  31. /package/dist/{chunk-GWATTXFR.js.map → chunk-FYF564KJ.js.map} +0 -0
  32. /package/dist/{chunk-TMWUWKLU.js.map → chunk-GE242CLI.js.map} +0 -0
@@ -863,12 +863,17 @@ async function closeIteratorAfterAbort(iterator) {
863
863
  // src/chat-routes/failure-wording.ts
864
864
  var utcTime = (at) => `${at.toISOString().slice(11, 19)} UTC`;
865
865
  var FAILED_TURN_TEXT = "That answer stopped before it finished. Please send your question again.";
866
- var ANSWER_COMPLETE_TEXT = "The answer above is complete.";
867
- var MODEL_KEY_REFUSED_TEXT = "The assistant's model refused its access key, so this message was not answered. If the assistant has just started, send it again in a minute; if this repeats, tell the team.";
868
- var BUDGET_TEXT = "This assistant's spending budget is used up. Raise its cap or wait for it to reset, then send again.";
869
- var BALANCE_TEXT = "Insufficient credits to cover this request. Add funds, then send again.";
870
- var MODEL_POLICY_TEXT = "That model isn't available here. Choose another model and send again.";
871
- var RETRY_TEXT = "The model provider is busy, so the request is being retried.";
866
+ var SENTENCES = {
867
+ settlement: "The answer above is complete.",
868
+ model_key_refused: "The assistant's model refused its access key, so this message was not answered. If the assistant has just started, send it again in a minute; if this repeats, tell the team.",
869
+ budget_exhausted: "This assistant's spending budget is used up. Raise its cap or wait for it to reset, then send again.",
870
+ balance_low: "Insufficient credits to cover this request. Add funds, then send again.",
871
+ model_policy: "That model isn't available here. Choose another model and send again.",
872
+ grant_model_unsupported: "This assistant's model can't run here. Ask the team to choose a supported model.",
873
+ grant_activation_missing: "This assistant couldn't connect to its model. Tell the team; sending again won't help.",
874
+ profile_unsupported: "This assistant's setup can't run here. Ask the team to update it.",
875
+ provider_retry: "The model provider is busy, so the request is being retried."
876
+ };
872
877
  function providerRetryNotice(event) {
873
878
  const retry = event.type === "raw" ? asRecord(asRecord(event.data)?.event) : void 0;
874
879
  if (retry?.type !== "retry" || !(Number(retry.next) > 0)) return void 0;
@@ -882,28 +887,23 @@ function providerResetSentence(message) {
882
887
  var MODEL_KEY_REFUSED_CODE = "model.key_refused";
883
888
  function modelKeyRefusedSentence(message) {
884
889
  const lower = message.toLowerCase();
885
- const refused = lower.includes("invalid api key") || /\b401\b/.test(message) && (lower.includes("unauthorized") || lower.includes("unauthorised") || lower.includes("api key"));
886
- return refused ? MODEL_KEY_REFUSED_TEXT : void 0;
890
+ const refused = lower.includes("invalid api key") || /\b401\b/.test(message) && /unauthori[sz]ed|api key/.test(lower);
891
+ return refused ? SENTENCES.model_key_refused : void 0;
887
892
  }
888
893
  var ROUTER_BUDGET = [
889
894
  "This key's monthly budget is exhausted",
890
895
  "This key's lifetime budget is exhausted",
891
- "This key's remaining budget, after other in-flight requests, is below",
896
+ "Monthly budget exceeded (",
892
897
  "The key or product budget cannot cover"
893
898
  ];
894
- var ROUTER_BALANCE = ["Your available balance, after other in-flight requests, is below", "Available credits cannot cover"];
895
899
  var REFUSALS = /* @__PURE__ */ new Map([
896
- ["MODEL_REFUSED", { class: "model_policy", shown: MODEL_POLICY_TEXT }],
897
- ["model_policy_denied", { class: "model_policy", shown: MODEL_POLICY_TEXT }],
898
- ["grant_model_unsupported", {
899
- class: "grant_model_unsupported",
900
- shown: "This assistant's model can't run here. Ask the team to choose a supported model."
901
- }],
902
- ["grant_activation_missing", {
903
- class: "grant_activation_missing",
904
- shown: "This assistant couldn't connect to its model. Tell the team; sending again won't help."
905
- }],
906
- ["profile_unsupported", { class: "profile_unsupported", shown: "This assistant's setup can't run here. Ask the team to update it." }]
900
+ ["MODEL_REFUSED", "model_policy"],
901
+ ["model_policy_denied", "model_policy"],
902
+ ["budget_exceeded", "budget_exhausted"],
903
+ ["grant_model_unsupported", "grant_model_unsupported"],
904
+ ["grant_activation_missing", "grant_activation_missing"],
905
+ ["profile_unsupported", "profile_unsupported"],
906
+ [MODEL_KEY_REFUSED_CODE, "model_key_refused"]
907
907
  ]);
908
908
  var LED_CLASSES = /* @__PURE__ */ new Set([
909
909
  "funding",
@@ -916,7 +916,7 @@ var LED_CLASSES = /* @__PURE__ */ new Set([
916
916
  var WARNING_SENTENCES = /* @__PURE__ */ new Map([
917
917
  ["empty_visible_output_retry", "The model returned no visible answer, so it is trying once more."],
918
918
  ["OPENCODE_STEP_TRUNCATED", "A step of this answer was cut short, so the answer may be incomplete."],
919
- ["OPENCODE_PROVIDER_RETRY", RETRY_TEXT],
919
+ ["OPENCODE_PROVIDER_RETRY", SENTENCES.provider_retry],
920
920
  ["CODEX_UNEXPECTED_APPROVAL", "The agent asked for an approval it does not need here, and it was declined."],
921
921
  ["CODEX_UNEXPECTED_QUESTION", "The agent asked a question it cannot ask here, and it was declined."],
922
922
  ["EXECUTION_INTERRUPTED", "This answer was interrupted before it finished."],
@@ -931,15 +931,17 @@ function lastAttempt(reason) {
931
931
  return colon < 0 ? last : last.slice(colon + 2);
932
932
  }
933
933
  function classify(reason, code, status) {
934
- const last = lastAttempt(reason);
935
- const wait = providerResetSentence(last);
936
- if (wait) return { class: "provider_wait", shown: wait };
937
- if (modelKeyRefusedSentence(last)) return { class: "model_key_refused", shown: MODEL_KEY_REFUSED_TEXT };
938
- if (ROUTER_BUDGET.some((phrase) => last.includes(phrase))) return { class: "budget_exhausted", shown: BUDGET_TEXT };
939
- if (ROUTER_BALANCE.some((phrase) => last.includes(phrase))) return { class: "balance_low", shown: BALANCE_TEXT };
940
934
  const refusal = REFUSALS.get(code ?? "");
941
- if (refusal) return refusal;
942
- const recovery = getChatFundingRecovery({ code, message: last }) ?? (Number(status) === 402 || code === "PAYMENT_REQUIRED" ? getChatFundingRecovery({ code: "insufficient_credits" }) : null);
935
+ if (refusal) return { class: refusal, shown: SENTENCES[refusal] };
936
+ const funding = getChatFundingRecovery({ code: code === "PAYMENT_REQUIRED" ? "insufficient_credits" : code });
937
+ const last = lastAttempt(reason);
938
+ if (!funding) {
939
+ const wait = providerResetSentence(last);
940
+ if (wait) return { class: "provider_wait", shown: wait };
941
+ const kind = modelKeyRefusedSentence(last) ? "model_key_refused" : ROUTER_BUDGET.some((phrase) => last.includes(phrase)) ? "budget_exhausted" : last.includes("Available credits cannot cover") ? "balance_low" : void 0;
942
+ if (kind) return { class: kind, shown: SENTENCES[kind] };
943
+ }
944
+ const recovery = funding ?? getChatFundingRecovery({ message: last }) ?? (Number(status) === 402 ? getChatFundingRecovery({ code: "insufficient_credits" }) : null);
943
945
  if (!recovery) return void 0;
944
946
  const paidAccess = recovery.reason === "paid_access_required" ? "Inference requires verified paid access. " : "";
945
947
  return { class: "funding", shown: `${recovery.title}. ${paidAccess}${recovery.message}` };
@@ -955,49 +957,66 @@ function failureText(view, partialAnswer) {
955
957
 
956
958
  Error: ${view.shown}`;
957
959
  }
958
- var CODE_VALUE = /^[a-z0-9_.]+$/;
959
- function failureReason(event) {
960
+ var REASONS = /* @__PURE__ */ new Set(["provider_error", "abort"]);
961
+ var USAGE_KEYS = /* @__PURE__ */ new Set([...TURN_USAGE_KEYS, "cacheReadInputTokens", "cacheCreationInputTokens", "cost", "totalCostUsd"]);
962
+ function failureSources(event) {
960
963
  const record = asRecord(event);
961
964
  const data = asRecord(record?.data);
962
- const error = asRecord(data?.error);
963
- const sessionError = asRecord(asRecord(data?.properties)?.error);
964
965
  const raw = asRecord(data?.event);
965
- const rawError = asRecord(raw?.error);
966
- const prose = typeof data?.reason === "string" && !CODE_VALUE.test(data.reason) ? asString(data.reason) : void 0;
967
- return asString(data?.message) ?? asString(data?.error) ?? asString(data?.detail) ?? prose ?? asString(error?.message) ?? asString(asRecord(error?.data)?.message) ?? asString(sessionError?.message) ?? asString(asRecord(sessionError?.data)?.message) ?? asString(record?.error) ?? asString(asRecord(record?.error)?.message) ?? asString(record?.message) ?? asString(record?.details) ?? asString(raw?.message) ?? asString(raw?.error) ?? asString(rawError?.message) ?? asString(asRecord(rawError?.data)?.message) ?? asString(asRecord(raw?.item)?.message) ?? "";
966
+ return [
967
+ data,
968
+ asRecord(data?.error),
969
+ asRecord(asRecord(data?.properties)?.error),
970
+ record,
971
+ asRecord(record?.error),
972
+ raw,
973
+ asRecord(raw?.error),
974
+ asRecord(raw?.item)
975
+ ];
976
+ }
977
+ function failureReason(event) {
978
+ for (const row of failureSources(event)) {
979
+ const reason = asString(row?.message) ?? asString(row?.error) ?? asString(row?.detail) ?? asString(row?.details) ?? (REASONS.has(String(row?.reason)) ? void 0 : asString(row?.reason)) ?? asString(asRecord(row?.data)?.message);
980
+ if (reason) return reason;
981
+ }
982
+ return "";
968
983
  }
969
984
  var FAILURE_TYPES = /* @__PURE__ */ new Set(["error", "warning", "session.run.failed", "session.error"]);
970
- var DETAIL_KEYS = /* @__PURE__ */ new Set(["code", "statusCode", "retryable", "retryAt", "class"]);
985
+ function failureCode(event) {
986
+ return failureSources(event).map((row) => asString(row?.code)).find(Boolean);
987
+ }
988
+ function visibleValues(data) {
989
+ return Object.fromEntries(Object.entries(data).filter(([key, value]) => {
990
+ if (["turnId", "threadId", "sessionId", "executionId", "code"].includes(key)) return typeof value === "string" && /^[\w.:-]+$/.test(value);
991
+ if (key === "reason") return typeof value === "string" && REASONS.has(value);
992
+ if (key === "retryable") return typeof value === "boolean";
993
+ if (key === "status" && value === "failed") return true;
994
+ return (["status", "statusCode", "retryAt", "resetAt"].includes(key) || USAGE_KEYS.has(key)) && typeof value === "number" && Number.isFinite(value);
995
+ }));
996
+ }
971
997
  function shownFailure(event, shown, reason) {
972
998
  const data = asRecord(event.data) ?? {};
973
- const visible = { ...data };
974
- const shownError = (value) => typeof value === "string" || asRecord(value) ? { ...typeof asRecord(value)?.code === "string" ? { code: asRecord(value).code } : {}, message: shown } : value;
975
- for (const key of ["message", "detail"]) if (key in visible) visible[key] = shown;
976
- if ("error" in visible) visible.error = typeof visible.error === "string" ? shown : shownError(visible.error);
977
- if (typeof visible.reason === "string" && !CODE_VALUE.test(visible.reason)) visible.reason = shown;
978
- const properties = asRecord(data.properties);
979
- if (properties && "error" in properties) visible.properties = { ...properties, error: shownError(properties.error) };
980
- if (event.type === "error" || event.type === "session.run.failed") visible.message = shown;
981
- const details = Object.entries(asRecord(data.details) ?? {}).filter(([key]) => DETAIL_KEYS.has(key));
982
- delete visible.details;
983
- if (details.length > 0) visible.details = Object.fromEntries(details);
999
+ const visible = { ...visibleValues(data), ...visibleValues({ code: failureCode(event) }), message: shown };
1000
+ const details = visibleValues(asRecord(data.details) ?? {});
1001
+ if (Object.keys(details).length) Object.assign(visible, { details });
1002
+ for (const key of ["usage", "tokenUsage"]) {
1003
+ const usage = Object.fromEntries(Object.entries(asRecord(data[key]) ?? {}).filter(([name, value]) => USAGE_KEYS.has(name) && typeof value === "number" && Number.isFinite(value)));
1004
+ if (Object.keys(usage).length) Object.assign(visible, { [key]: usage });
1005
+ }
984
1006
  const original = typeof data.message === "string" ? data : { ...data, message: reason };
985
- const out = { ...event, data: Object.assign(visible, { [WITHHELD_FAILURE]: original }) };
986
- if ("error" in event) out.error = typeof event.error === "string" ? shown : shownError(event.error);
987
- if ("message" in event) out.message = shown;
988
- delete out.details;
989
- return out;
1007
+ return { type: event.type, data: Object.assign(visible, { [WITHHELD_FAILURE]: original }) };
990
1008
  }
991
1009
  function personFacing(options) {
992
1010
  const views = /* @__PURE__ */ new Map();
993
1011
  const droppedWarnings = /* @__PURE__ */ new Set();
994
1012
  const warn = (message, meta) => (options.log ?? console.warn)(message, meta);
995
1013
  const view = (reason, code, status, meta = {}) => {
996
- const key = [reason, code, Number(status) === 402].join("\n");
1014
+ const settled = code?.startsWith("settlement_") ?? false;
1015
+ const answered = settled && options.hasAnswer?.();
1016
+ const key = [reason, code, Number(status) === 402, answered].join("\n");
997
1017
  const known = views.get(key);
998
1018
  if (known) return known;
999
- const settled = code?.startsWith("settlement_") ?? false;
1000
- const seen = classify(reason, code, status) ?? (settled && options.hasAnswer?.() ? { class: "settlement", shown: ANSWER_COMPLETE_TEXT } : void 0) ?? { class: settled ? "settlement" : "runtime_failure", shown: options.failedTurnText };
1019
+ const seen = (answered ? { class: "settlement", shown: SENTENCES.settlement } : void 0) ?? classify(reason, code, status) ?? { class: settled ? "settlement" : "runtime_failure", shown: options.failedTurnText };
1001
1020
  warn("[chat-routes] turn failure withheld from the person", { failureClass: seen.class, code, error: reason, ...meta });
1002
1021
  views.set(key, seen);
1003
1022
  return seen;
@@ -1016,61 +1035,54 @@ ${message}`);
1016
1035
  const raw = event2.type === "raw" ? asRecord(data?.event) : void 0;
1017
1036
  if (raw) {
1018
1037
  const part = asRecord(raw.part);
1019
- if (part?.type === "tool") return { ...event2, data: { ...data, event: { ...raw, part: withoutToolList(part) } } };
1020
1038
  const item = asRecord(raw.item)?.type === "error" ? asRecord(raw.item) : void 0;
1021
- if (raw.type !== "error" && raw.type !== "retry" && raw.type !== "turn.failed" && !("error" in raw) && !item) return event2;
1022
- const shown = raw.type === "retry" ? RETRY_TEXT : view(failureReason(event2), void 0, void 0, failureIds(data)).shown;
1023
- return { ...event2, data: { ...data, event: {
1024
- ...raw,
1025
- ..."message" in raw ? { message: shown } : {},
1026
- ..."error" in raw ? { error: { message: shown } } : {},
1027
- ...item ? { item: { type: "error", message: shown } } : {}
1028
- } } };
1039
+ if (raw.type !== "error" && raw.type !== "retry" && raw.type !== "turn.failed" && !("error" in raw) && !item) {
1040
+ return part?.type === "tool" ? { ...event2, data: { ...data, event: { ...raw, part: withoutToolList(part) } } } : event2;
1041
+ }
1042
+ const reason2 = failureReason(event2);
1043
+ const shown = raw.type === "retry" ? SENTENCES.provider_retry : view(reason2, failureCode(event2), raw.statusCode ?? raw.status, failureIds(data)).shown;
1044
+ return { type: "raw", data: {
1045
+ ...shownFailure(event2, shown, reason2).data,
1046
+ event: { type: raw.type === "retry" ? "retry" : "error", ...visibleValues({ code: failureCode(event2) }), message: shown }
1047
+ } };
1029
1048
  }
1030
1049
  const failed = (event2.type === "done" || event2.type === "status") && data?.status === "failed";
1031
1050
  if (!failed && !FAILURE_TYPES.has(String(event2.type))) return event2;
1032
1051
  const reason = failureReason(event2);
1033
1052
  if (event2.type === "warning") {
1034
- const shown = warning(asString(data?.code), reason, failureIds(data));
1053
+ const shown = warning(failureCode(event2), reason, failureIds(data));
1035
1054
  return shown ? shownFailure(event2, shown, reason) : void 0;
1036
1055
  }
1037
1056
  const status = data?.statusCode ?? (failed ? void 0 : data?.status);
1038
- return shownFailure(event2, view(reason, asString(data?.code), status, failureIds(data)).shown, reason);
1057
+ return shownFailure(event2, view(reason, failureCode(event2), status, failureIds(data)).shown, reason);
1039
1058
  };
1040
1059
  return { view, warning, event };
1041
1060
  }
1042
- function noModelAllowed(error) {
1043
- return error.attempts.length > 0 && error.attempts.every((attempt) => attempt.reason?.includes(" is not admitted by policy: "));
1044
- }
1045
1061
  function sandboxStreamFailureDiagnostic(error) {
1046
1062
  const streamMessage = error?.streamMessage;
1047
1063
  const message = typeof streamMessage === "string" ? streamMessage : error instanceof Error ? error.message : "Sandbox stream failed";
1048
- const diagnostics = asRecord(error?.diagnostics);
1049
- let diagnosticText;
1050
- if (diagnostics) {
1051
- try {
1052
- diagnosticText = JSON.stringify(diagnostics);
1053
- } catch {
1054
- diagnosticText = "[unserializable diagnostics]";
1055
- }
1064
+ let failureNote = `sandbox-stream: ${message}`;
1065
+ try {
1066
+ const diagnostics = asRecord(error?.diagnostics);
1067
+ if (diagnostics) failureNote += `; ${JSON.stringify(diagnostics)}`;
1068
+ } catch {
1069
+ failureNote += "; [unserializable diagnostics]";
1056
1070
  }
1057
- const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
1058
1071
  const ownCode = asString(asRecord(error)?.code);
1072
+ const last = error instanceof ModelFailoverExhaustedError ? error.attempts.at(-1) : void 0;
1073
+ const reason = last?.reason ?? message;
1059
1074
  let code = "sandbox.stream_failed";
1060
1075
  if (error instanceof SandboxRunError) {
1061
1076
  code = error.code;
1062
1077
  } else if (error instanceof ModelFailoverTimeoutError) {
1063
1078
  code = error.code;
1064
1079
  } else if (error instanceof ModelFailoverExhaustedError) {
1065
- code = noModelAllowed(error) ? "model_policy_denied" : error.upstreamCode ?? code;
1066
- } else if (ownCode && (REFUSALS.has(ownCode) || ownCode === "PAYMENT_REQUIRED" || ownCode.startsWith("settlement_"))) {
1080
+ code = last?.errorCode ?? (last && error.attempts.every((attempt) => attempt.reason?.includes(" is not admitted by policy: ")) ? "model_policy_denied" : code);
1081
+ } else if (ownCode && (REFUSALS.has(ownCode) || getChatFundingRecovery({ code: ownCode }) || ownCode === "PAYMENT_REQUIRED" || ownCode.startsWith("settlement_"))) {
1067
1082
  code = ownCode;
1068
1083
  }
1069
- if (modelKeyRefusedSentence(message)) code = MODEL_KEY_REFUSED_CODE;
1070
- return { failureNote, code, reason: message };
1071
- }
1072
- function sandboxStreamErrorCode(data) {
1073
- return asString(asRecord(data)?.code) ?? "sandbox.stream_error";
1084
+ if (modelKeyRefusedSentence(reason) && code === "sandbox.stream_failed") code = MODEL_KEY_REFUSED_CODE;
1085
+ return { failureNote, code, reason };
1074
1086
  }
1075
1087
  var UNAVAILABLE_TOOL_TEXT = "That tool isn't available.";
1076
1088
  function withoutToolListTail(text) {
@@ -1128,9 +1140,9 @@ export {
1128
1140
  failureIds,
1129
1141
  failureText,
1130
1142
  failureReason,
1143
+ failureCode,
1131
1144
  personFacing,
1132
1145
  sandboxStreamFailureDiagnostic,
1133
- sandboxStreamErrorCode,
1134
1146
  withoutToolList
1135
1147
  };
1136
- //# sourceMappingURL=chunk-RNDWCT4O.js.map
1148
+ //# sourceMappingURL=chunk-MZZMOGFN.js.map