@genesislcap/ai-assistant 15.40.0 → 15.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/ai-assistant.api.json +409 -9
  2. package/dist/ai-assistant.d.ts +196 -6
  3. package/dist/chat-driver.cjs +682 -140
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +675 -140
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +1007 -436
  8. package/dist/dts/chat-driver-node.d.ts +2 -2
  9. package/dist/dts/chat-driver-node.d.ts.map +1 -1
  10. package/dist/dts/components/ai-driver/ai-driver.d.ts +4 -0
  11. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.d.ts +121 -4
  13. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  14. package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
  15. package/dist/dts/components/chat-driver/turn-failures.d.ts +7 -1
  16. package/dist/dts/components/chat-driver/turn-failures.d.ts.map +1 -1
  17. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +3 -1
  18. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  19. package/dist/dts/genesis/index.d.ts +2 -1
  20. package/dist/dts/genesis/index.d.ts.map +1 -1
  21. package/dist/dts/genesis/register-genesis-assistant.d.ts +21 -0
  22. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  23. package/dist/dts/genesis/review-model.d.ts +40 -0
  24. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  25. package/dist/dts/genesis/review-payload.d.ts +47 -0
  26. package/dist/dts/genesis/review-payload.d.ts.map +1 -0
  27. package/dist/dts/genesis/write-review/write-review.d.ts +75 -11
  28. package/dist/dts/genesis/write-review/write-review.d.ts.map +1 -1
  29. package/dist/dts/genesis/write-review/write-review.styles.d.ts.map +1 -1
  30. package/dist/dts/genesis/write-review/write-review.template.d.ts.map +1 -1
  31. package/dist/dts/genesis/write-tools.d.ts +49 -0
  32. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  33. package/dist/dts/genesis/write-turn.d.ts +114 -0
  34. package/dist/dts/genesis/write-turn.d.ts.map +1 -0
  35. package/dist/dts/index.d.ts +2 -0
  36. package/dist/dts/index.d.ts.map +1 -1
  37. package/dist/dts/main/budget-controller.d.ts +12 -2
  38. package/dist/dts/main/budget-controller.d.ts.map +1 -1
  39. package/dist/dts/main/main.d.ts +33 -6
  40. package/dist/dts/main/main.d.ts.map +1 -1
  41. package/dist/dts/react.d.ts +2 -1
  42. package/dist/dts/state/ai-assistant-slice.d.ts +15 -0
  43. package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
  44. package/dist/dts/state/session-store.d.ts +1 -0
  45. package/dist/dts/state/session-store.d.ts.map +1 -1
  46. package/dist/dts/suggestions/generate-suggestions.d.ts.map +1 -1
  47. package/dist/dts/utils/history-transform.d.ts.map +1 -1
  48. package/dist/esm/chat-driver-node.js +5 -1
  49. package/dist/esm/components/chat-driver/chat-driver.js +431 -92
  50. package/dist/esm/components/chat-driver/interaction-controller.js +25 -2
  51. package/dist/esm/components/chat-driver/turn-failures.js +9 -2
  52. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +30 -4
  53. package/dist/esm/genesis/register-genesis-assistant.js +38 -2
  54. package/dist/esm/genesis/review-model.js +47 -1
  55. package/dist/esm/genesis/review-payload.js +18 -0
  56. package/dist/esm/genesis/write-review/write-review.js +225 -40
  57. package/dist/esm/genesis/write-review/write-review.styles.js +18 -0
  58. package/dist/esm/genesis/write-review/write-review.template.js +46 -22
  59. package/dist/esm/genesis/write-tools.js +321 -49
  60. package/dist/esm/genesis/write-turn.js +110 -0
  61. package/dist/esm/main/budget-controller.js +39 -5
  62. package/dist/esm/main/main.js +45 -23
  63. package/dist/esm/state/ai-assistant-slice.js +11 -1
  64. package/dist/esm/state/debug-event-log.js +1 -1
  65. package/dist/esm/suggestions/generate-suggestions.js +4 -1
  66. package/dist/esm/utils/history-transform.js +7 -1
  67. package/dist/react.cjs +14 -2
  68. package/dist/react.mjs +14 -2
  69. package/docs/genesis.md +120 -3
  70. package/docs/migration-GENC-1464.md +12 -2
  71. package/docs/sub_agent.md +21 -4
  72. package/package.json +18 -18
  73. package/scripts/smoke-chat-driver-node.mjs +15 -0
@@ -19,6 +19,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/chat-driver-node.ts
20
20
  var chat_driver_node_exports = {};
21
21
  __export(chat_driver_node_exports, {
22
+ AIServiceError: () => AIServiceError,
23
+ AI_SERVICE_ACCESS_REFUSALS: () => AI_SERVICE_ACCESS_REFUSALS,
24
+ AI_SERVICE_ERROR_CODES: () => AI_SERVICE_ERROR_CODES,
22
25
  AI_TIER_IDS: () => AI_TIER_IDS,
23
26
  AI_TIER_VENDORS: () => AI_TIER_VENDORS,
24
27
  ANTHROPIC_CACHE_READ_MULTIPLIER: () => ANTHROPIC_CACHE_READ_MULTIPLIER,
@@ -28,6 +31,7 @@ __export(chat_driver_node_exports, {
28
31
  AnthropicProvider: () => AnthropicProvider,
29
32
  AnthropicTransport: () => AnthropicTransport,
30
33
  ChatDriver: () => ChatDriver,
34
+ DEFAULT_AI_SERVICE_ERROR_MESSAGES: () => DEFAULT_AI_SERVICE_ERROR_MESSAGES,
31
35
  DEFAULT_AI_TIERS: () => DEFAULT_AI_TIERS,
32
36
  DEFAULT_PROVIDER_REFUSED_MESSAGE: () => DEFAULT_PROVIDER_REFUSED_MESSAGE,
33
37
  EMPTY_RESPONSE_NUDGE: () => EMPTY_RESPONSE_NUDGE,
@@ -48,6 +52,8 @@ __export(chat_driver_node_exports, {
48
52
  UNROUTABLE_PLACEHOLDER: () => UNROUTABLE_PLACEHOLDER,
49
53
  addUsage: () => addUsage,
50
54
  agenticActivityBus: () => agenticActivityBus,
55
+ aiServiceAccessRefusalOf: () => aiServiceAccessRefusalOf,
56
+ aiServiceErrorCodeOf: () => aiServiceErrorCodeOf,
51
57
  anthropicRatesFor: () => anthropicRatesFor,
52
58
  anthropicTokenCost: () => anthropicTokenCost,
53
59
  assembleDebugLog: () => assembleDebugLog,
@@ -61,6 +67,7 @@ __export(chat_driver_node_exports, {
61
67
  geminiTokenCost: () => geminiTokenCost,
62
68
  getMetaEvents: () => getMetaEvents,
63
69
  isObservableAIProviderRegistry: () => isObservableAIProviderRegistry,
70
+ isTerminalAIServiceRefusal: () => isTerminalAIServiceRefusal,
64
71
  messageUsage: () => messageUsage,
65
72
  resolveAITiers: () => resolveAITiers,
66
73
  restoreMachine: () => restoreMachine,
@@ -226,6 +233,12 @@ function combineSignals(signals) {
226
233
  return { signal: controller.signal, dispose };
227
234
  }
228
235
 
236
+ // ../../foundation-logger/dist/esm/log-timestamps.js
237
+ var LOG_TIMESTAMPS_FLAG = Symbol.for("@genesislcap/foundation-logger:timestamps");
238
+ function areLogTimestampsEnabled() {
239
+ return Reflect.get(globalThis, LOG_TIMESTAMPS_FLAG) === true;
240
+ }
241
+
229
242
  // ../../../../node_modules/consola/dist/core.mjs
230
243
  var LogLevels = {
231
244
  silent: Number.NEGATIVE_INFINITY,
@@ -806,15 +819,118 @@ function createConsola2(options = {}) {
806
819
  }
807
820
  var consola = createConsola2();
808
821
 
822
+ // ../../foundation-logger/dist/esm/timestamp-browser-reporter.js
823
+ var TIME_UNIT_DIGITS = 2;
824
+ var MILLISECOND_DIGITS = 3;
825
+ function formatLogTimestamp(date) {
826
+ const hours = String(date.getHours()).padStart(TIME_UNIT_DIGITS, "0");
827
+ const minutes = String(date.getMinutes()).padStart(TIME_UNIT_DIGITS, "0");
828
+ const seconds = String(date.getSeconds()).padStart(TIME_UNIT_DIGITS, "0");
829
+ const milliseconds = String(date.getMilliseconds()).padStart(MILLISECOND_DIGITS, "0");
830
+ return `${hours}:${minutes}:${seconds}.${milliseconds}`;
831
+ }
832
+ function getConsoleLogFn(level) {
833
+ const consolaConsole = console;
834
+ if (level < 1) {
835
+ return consolaConsole.__error || consolaConsole.error;
836
+ }
837
+ if (level === 1) {
838
+ return consolaConsole.__warn || consolaConsole.warn;
839
+ }
840
+ return consolaConsole.__log || consolaConsole.log;
841
+ }
842
+ function shouldIncludeTimestamp(ctx) {
843
+ var _a, _b, _c;
844
+ const timestamps = (_a = ctx === null || ctx === void 0 ? void 0 : ctx.options) === null || _a === void 0 ? void 0 : _a.timestamps;
845
+ if (typeof timestamps === "boolean") {
846
+ return timestamps;
847
+ }
848
+ if (((_c = (_b = ctx === null || ctx === void 0 ? void 0 : ctx.options) === null || _b === void 0 ? void 0 : _b.formatOptions) === null || _c === void 0 ? void 0 : _c.date) === true) {
849
+ return true;
850
+ }
851
+ return areLogTimestampsEnabled();
852
+ }
853
+ var TimestampBrowserReporter = class {
854
+ constructor() {
855
+ this.defaultColor = "#7f8c8d";
856
+ this.levelColorMap = {
857
+ 0: "#c0392b",
858
+ 1: "#f39c12",
859
+ 3: "#00BCD4"
860
+ };
861
+ this.typeColorMap = {
862
+ success: "#2ecc71"
863
+ };
864
+ }
865
+ /**
866
+ * Writes a log object to the console, prefixed with `logObj.date` when enabled.
867
+ *
868
+ * @param logObj - The Consola log object. See Consola's `LogObject`.
869
+ * @param ctx - Reporter context, including Consola options.
870
+ */
871
+ log(logObj, ctx) {
872
+ const consoleLogFn = getConsoleLogFn(logObj.level);
873
+ const type = logObj.type === "log" ? "" : logObj.type;
874
+ const tag = logObj.tag || "";
875
+ const timestamp = shouldIncludeTimestamp(ctx) ? formatLogTimestamp(logObj.date) : "";
876
+ const useBrowserStyles = typeof window !== "undefined" && !!(tag || type);
877
+ if (useBrowserStyles) {
878
+ this.logWithBrowserStyles(consoleLogFn, logObj, tag, type, timestamp);
879
+ return;
880
+ }
881
+ this.logPlain(consoleLogFn, logObj, tag, type, timestamp);
882
+ }
883
+ logWithBrowserStyles(consoleLogFn, logObj, tag, type, timestamp) {
884
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
885
+ const style = `
886
+ background: ${color};
887
+ border-radius: 0.5em;
888
+ color: white;
889
+ font-weight: bold;
890
+ padding: 2px 0.5em;
891
+ `;
892
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
893
+ const prefix = timestamp ? `${timestamp} ${badge}` : badge;
894
+ if (typeof logObj.args[0] === "string") {
895
+ consoleLogFn(`${prefix}%c ${logObj.args[0]}`, style, "", ...logObj.args.slice(1));
896
+ return;
897
+ }
898
+ consoleLogFn(prefix, style, ...logObj.args);
899
+ }
900
+ logPlain(consoleLogFn, logObj, tag, type, timestamp) {
901
+ const label = [tag, type].filter(Boolean).join(":");
902
+ const prefix = [timestamp, label ? `[${label}]` : ""].filter(Boolean).join(" ");
903
+ if (typeof logObj.args[0] === "string") {
904
+ consoleLogFn(prefix ? `${prefix} ${logObj.args[0]}` : logObj.args[0], ...logObj.args.slice(1));
905
+ return;
906
+ }
907
+ if (prefix) {
908
+ consoleLogFn(prefix, ...logObj.args);
909
+ return;
910
+ }
911
+ consoleLogFn(...logObj.args);
912
+ }
913
+ };
914
+
809
915
  // ../../foundation-logger/dist/esm/logger.js
810
916
  var defaultLoggerOptions = {
811
- level: LogLevels.debug
917
+ level: LogLevels.debug,
918
+ formatOptions: {
919
+ date: false
920
+ }
812
921
  };
813
- function createLogger(name, options = defaultLoggerOptions) {
814
- const createConsola3 = typeof window !== "undefined" ? createConsola2 : createConsola;
815
- const logger3 = createConsola3().withTag(name);
816
- if ((options === null || options === void 0 ? void 0 : options.level) !== void 0)
817
- logger3.level = options.level;
922
+ var browserReporter = new TimestampBrowserReporter();
923
+ function resolveLoggerOptions(options, isBrowser) {
924
+ const resolved = Object.assign(Object.assign(Object.assign({}, defaultLoggerOptions), options), { formatOptions: Object.assign(Object.assign({}, defaultLoggerOptions.formatOptions), options.formatOptions) });
925
+ if (isBrowser && !resolved.reporters) {
926
+ resolved.reporters = [browserReporter];
927
+ }
928
+ return resolved;
929
+ }
930
+ function createLogger(name, options = {}) {
931
+ const isBrowser = typeof window !== "undefined";
932
+ const createConsola3 = isBrowser ? createConsola2 : createConsola;
933
+ const logger3 = createConsola3(resolveLoggerOptions(options, isBrowser)).withTag(name);
818
934
  const typedLogger = logger3;
819
935
  typedLogger.deprecated = (symbol, instruction = "Consult docs for better alternative.", removalVersionTarget) => {
820
936
  typedLogger.warn(`Deprecated symbol used '${symbol}'. ${instruction}`, `${removalVersionTarget ? `Will be removed in version ${removalVersionTarget}.` : ""}`);
@@ -1579,6 +1695,98 @@ function abortableDelay(ms, signal) {
1579
1695
  });
1580
1696
  }
1581
1697
 
1698
+ // ../../foundation-ai/dist/esm/transports/ai-service-error.js
1699
+ var AI_SERVICE_ERROR_CODES = Object.freeze({
1700
+ /** No API key is configured for the vendor. */
1701
+ NO_API_KEY: "NO_API_KEY",
1702
+ /** The configured key has characters an API key cannot have. */
1703
+ BAD_API_KEY: "BAD_API_KEY",
1704
+ /** An encrypted key could not be decrypted. */
1705
+ KEY_UNREADABLE: "KEY_UNREADABLE",
1706
+ /** The request asked for a model the service does not allow. */
1707
+ MODEL_NOT_ALLOWED: "MODEL_NOT_ALLOWED",
1708
+ /** The service refused the shape of the request. */
1709
+ BAD_REQUEST: "BAD_REQUEST",
1710
+ /** The request named fallback models, which the service does not accept. */
1711
+ FALLBACKS_NOT_SUPPORTED: "FALLBACKS_NOT_SUPPORTED",
1712
+ /** The request body is larger, or nested deeper, than the service accepts. */
1713
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
1714
+ /** The service could not reach the vendor. The only code that is worth retrying. */
1715
+ VENDOR_UNREACHABLE: "VENDOR_UNREACHABLE"
1716
+ });
1717
+ var KNOWN_CODES = new Set(Object.values(AI_SERVICE_ERROR_CODES));
1718
+ function aiServiceErrorCodeOf(code) {
1719
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : void 0;
1720
+ }
1721
+ var AI_SERVICE_ACCESS_REFUSALS = Object.freeze({
1722
+ /** 401: the request had no session. */
1723
+ SIGNED_OUT: "SIGNED_OUT",
1724
+ /** 403: the user lacks the right the endpoint demands. */
1725
+ ACCESS_DENIED: "ACCESS_DENIED"
1726
+ });
1727
+ var UNAUTHORIZED_STATUS = 401;
1728
+ var FORBIDDEN_STATUS = 403;
1729
+ var PAYLOAD_TOO_LARGE_STATUS = 413;
1730
+ var isRouterNack = (payload) => {
1731
+ if (!payload || typeof payload !== "object")
1732
+ return false;
1733
+ const { MESSAGE_TYPE, ERROR } = payload;
1734
+ return MESSAGE_TYPE === "MSG_NACK" || Array.isArray(ERROR);
1735
+ };
1736
+ var hasCode = (payload) => (payload === null || payload === void 0 ? void 0 : payload.code) !== void 0;
1737
+ function aiServiceAccessRefusalOf(status, payload, bodyText) {
1738
+ if (status !== UNAUTHORIZED_STATUS && status !== FORBIDDEN_STATUS)
1739
+ return void 0;
1740
+ if (hasCode(payload))
1741
+ return void 0;
1742
+ const emptyBody = typeof bodyText === "string" && bodyText.trim() === "";
1743
+ if (!isRouterNack(payload) && !emptyBody)
1744
+ return void 0;
1745
+ return status === UNAUTHORIZED_STATUS ? AI_SERVICE_ACCESS_REFUSALS.SIGNED_OUT : AI_SERVICE_ACCESS_REFUSALS.ACCESS_DENIED;
1746
+ }
1747
+ function isUncodedTooLarge(status, payload) {
1748
+ return status === PAYLOAD_TOO_LARGE_STATUS && payload === void 0;
1749
+ }
1750
+ function routerRefusalDetailOf(payload) {
1751
+ var _a;
1752
+ const errors = payload === null || payload === void 0 ? void 0 : payload.ERROR;
1753
+ const text = Array.isArray(errors) ? (_a = errors[0]) === null || _a === void 0 ? void 0 : _a.TEXT : void 0;
1754
+ return typeof text === "string" && text ? text : void 0;
1755
+ }
1756
+ var REFUSED_REQUEST = "The AI service refused the assistant's request. An administrator can find the details in the browser console.";
1757
+ var DEFAULT_AI_SERVICE_ERROR_MESSAGES = Object.freeze({
1758
+ NO_API_KEY: "The assistant isn't set up yet. An administrator needs to add an API key for its AI service.",
1759
+ BAD_API_KEY: "The assistant can't use its AI service key. An administrator needs to check the key.",
1760
+ KEY_UNREADABLE: "The assistant can't read its AI service key. An administrator needs to check how the key is stored.",
1761
+ MODEL_NOT_ALLOWED: "The assistant asked for an AI model this app doesn't allow. An administrator needs to check the app's allowed models.",
1762
+ BAD_REQUEST: REFUSED_REQUEST,
1763
+ // The assistant never sends fallbacks, so only a mismatched client can meet this one.
1764
+ FALLBACKS_NOT_SUPPORTED: REFUSED_REQUEST,
1765
+ REQUEST_TOO_LARGE: "This request is too large to send. Start a new conversation or send a shorter message, and if you attached a file, try a smaller one.",
1766
+ VENDOR_UNREACHABLE: "The AI service can't be reached right now. Please try again in a few minutes. If it keeps happening, tell an administrator.",
1767
+ SIGNED_OUT: "Your session has ended. Sign in again to use the assistant.",
1768
+ ACCESS_DENIED: "You don't have access to the assistant. An administrator can give you access."
1769
+ });
1770
+ var isTerminalAIServiceRefusal = (code) => code !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE;
1771
+ var AIServiceError = class extends Error {
1772
+ constructor(vendorLabel, code, status, detail) {
1773
+ super(`${vendorLabel} AI service refused the request (${status} ${code})`);
1774
+ this.vendorLabel = vendorLabel;
1775
+ this.code = code;
1776
+ this.status = status;
1777
+ this.detail = detail;
1778
+ this.name = "AIServiceError";
1779
+ }
1780
+ /** Whether sending the request again cannot help. */
1781
+ get terminal() {
1782
+ return isTerminalAIServiceRefusal(this.code);
1783
+ }
1784
+ };
1785
+ function aiServiceDetailOf(payload) {
1786
+ const error = payload === null || payload === void 0 ? void 0 : payload.error;
1787
+ return typeof error === "string" && error ? error : void 0;
1788
+ }
1789
+
1582
1790
  // ../../foundation-ai/dist/esm/transports/context-overflow-error.js
1583
1791
  var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
1584
1792
  /prompt is too long/i,
@@ -1762,9 +1970,13 @@ function serverBackoffSpentMs(resolvedMs, ladderMs) {
1762
1970
  var MAX_RETRIES = 5;
1763
1971
  function postWithRetry(options) {
1764
1972
  return __awaiter(this, void 0, void 0, function* () {
1765
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1973
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1766
1974
  const { url, headers, body, credentials, vendorLabel, retryableStatuses, timeout, stallTimeout, backoffBaseMs, signal } = options;
1767
1975
  const vendor = vendorOfTransportLabel(vendorLabel);
1976
+ const serviceRefusal = (code, status, detail) => {
1977
+ logger.error(`${vendorLabel}Transport: the AI service refused the request (${status} ${code})${detail ? `: ${detail}` : ""}`);
1978
+ return new AIServiceError(vendorLabel, code, status, detail);
1979
+ };
1768
1980
  let serverBackoffSpent = 0;
1769
1981
  const backoff = (attempt, serverMs) => {
1770
1982
  const ladderMs = backoffBaseMs * Math.pow(2, attempt);
@@ -1822,6 +2034,17 @@ function postWithRetry(options) {
1822
2034
  if (isBudgetRejection(response.status, codeOf(parsed))) {
1823
2035
  throw budgetExhaustedFrom(vendorLabel, parsed, errText || void 0);
1824
2036
  }
2037
+ const serviceCode = aiServiceErrorCodeOf(codeOf(parsed));
2038
+ if (serviceCode && serviceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
2039
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
2040
+ }
2041
+ const accessRefusal = aiServiceAccessRefusalOf(response.status, parsed, errText);
2042
+ if (accessRefusal) {
2043
+ throw serviceRefusal(accessRefusal, response.status, (_e = routerRefusalDetailOf(parsed)) !== null && _e !== void 0 ? _e : errText || void 0);
2044
+ }
2045
+ if (isUncodedTooLarge(response.status, parsed)) {
2046
+ throw serviceRefusal(AI_SERVICE_ERROR_CODES.REQUEST_TOO_LARGE, response.status, errText || void 0);
2047
+ }
1825
2048
  const refusedRetry = shouldNotRetry(response.headers);
1826
2049
  if (retryableStatuses.includes(response.status) && !refusedRetry && attempt < MAX_RETRIES) {
1827
2050
  logger.warn(`${vendorLabel}Transport: retryable status ${response.status}, retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
@@ -1829,15 +2052,18 @@ function postWithRetry(options) {
1829
2052
  yield backoff(attempt, retryAfterMs(response.headers) || retryInfoMs(parsed));
1830
2053
  continue;
1831
2054
  }
2055
+ if (serviceCode) {
2056
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
2057
+ }
1832
2058
  throw new Error(`${vendorLabel} request error ${response.status}: ${errText}`);
1833
2059
  }
1834
- if (((_f = (_e = response.headers) === null || _e === void 0 ? void 0 : _e.get("content-type")) === null || _f === void 0 ? void 0 : _f.toLowerCase().includes("application/x-ndjson")) && response.body) {
2060
+ if (((_g = (_f = response.headers) === null || _f === void 0 ? void 0 : _f.get("content-type")) === null || _g === void 0 ? void 0 : _g.toLowerCase().includes("application/x-ndjson")) && response.body) {
1835
2061
  rearmStallTimer();
1836
2062
  const frame = yield readFramedBody(response.body, rearmStallTimer, vendorLabel, stallTimeout);
1837
2063
  if (frame.t === "ok")
1838
2064
  return frame.body;
1839
2065
  if (frame.code === "UPSTREAM_STALLED") {
1840
- throw new DOMException(`${vendorLabel} request stalled: ${(_g = frame.error) !== null && _g !== void 0 ? _g : "no upstream data"}`, "TimeoutError");
2066
+ throw new DOMException(`${vendorLabel} request stalled: ${(_h = frame.error) !== null && _h !== void 0 ? _h : "no upstream data"}`, "TimeoutError");
1841
2067
  }
1842
2068
  const framedRefusal = providerRefusalOf(vendor, frame.code, frame);
1843
2069
  if (framedRefusal) {
@@ -1845,18 +2071,25 @@ function postWithRetry(options) {
1845
2071
  }
1846
2072
  const framedOverflow = contextOverflowOf(vendor, frame.status, frame);
1847
2073
  if (framedOverflow) {
1848
- throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_h = framedOverflow.message) !== null && _h !== void 0 ? _h : frame.error);
2074
+ throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_j = framedOverflow.message) !== null && _j !== void 0 ? _j : frame.error);
1849
2075
  }
1850
2076
  if (isBudgetRejection(frame.status, frame.code)) {
1851
2077
  throw budgetExhaustedFrom(vendorLabel, frame);
1852
2078
  }
2079
+ const framedServiceCode = aiServiceErrorCodeOf(frame.code);
2080
+ if (framedServiceCode && framedServiceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
2081
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
2082
+ }
1853
2083
  if (retryableStatuses.includes(frame.status) && attempt < MAX_RETRIES) {
1854
2084
  logger.warn(`${vendorLabel}Transport: retryable status ${frame.status} (err frame), retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
1855
2085
  clearTimeout(timeoutId);
1856
2086
  yield backoff(attempt, retryInfoMs(frame));
1857
2087
  continue;
1858
2088
  }
1859
- throw new Error(`${vendorLabel} request error ${frame.status}: ${(_j = frame.error) !== null && _j !== void 0 ? _j : JSON.stringify(frame.details)}`);
2089
+ if (framedServiceCode) {
2090
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
2091
+ }
2092
+ throw new Error(`${vendorLabel} request error ${frame.status}: ${(_k = frame.error) !== null && _k !== void 0 ? _k : JSON.stringify(frame.details)}`);
1860
2093
  }
1861
2094
  return yield response.json();
1862
2095
  } catch (e) {
@@ -3873,80 +4106,6 @@ function clearSession(key) {
3873
4106
  registry.delete(key);
3874
4107
  }
3875
4108
 
3876
- // src/utils/logger.ts
3877
- var logger2 = createLogger("ai-assistant");
3878
-
3879
- // src/suggestions/generate-suggestions.ts
3880
- var HISTORY_WINDOW = 8;
3881
- function capabilities(ctx, allAgentInfo) {
3882
- let agentContext = "";
3883
- let toolContext = "";
3884
- if (allAgentInfo?.length) {
3885
- const agentDescriptions = allAgentInfo.map((agent) => {
3886
- const tools = agent.tools.map((t) => t.name).join(", ");
3887
- return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
3888
- }).join("\n");
3889
- agentContext = `The assistant has the following capabilities:
3890
- ${agentDescriptions}`;
3891
- const allToolNames = [
3892
- ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
3893
- ].join(", ");
3894
- toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
3895
- } else if (ctx.activeAgentName) {
3896
- const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
3897
- agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
3898
- toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
3899
- }
3900
- return agentContext || toolContext ? `
3901
-
3902
- <capabilities>
3903
- ${[agentContext, toolContext].filter(Boolean).join(
3904
- "\n"
3905
- )}
3906
- </capabilities>
3907
- Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
3908
- }
3909
- var OUTPUT_FORMAT = (count) => `
3910
-
3911
- Output format (strict):
3912
- - Exactly ${count} lines.
3913
- - One suggestion per line.
3914
- - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
3915
- - No preamble, headings, summary, or commentary before or after the list.`;
3916
- var SUGGESTIONS_SYSTEM_PROMPT = "You generate suggested prompts that a user could send to an AI assistant. You never continue the conversation or roleplay as the assistant.";
3917
- function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
3918
- const capabilitiesBlock = capabilities(ctx, allAgentInfo);
3919
- const guidanceBlock = prompt2 ? `
3920
-
3921
- Additional guidance: "${prompt2}"` : "";
3922
- if (history.length === 0) {
3923
- return `Generate exactly ${count} brief starter prompts to show a user what an AI assistant can do. Phrase each one as the user would write it. Keep them short and generic \u2014 do not invent specific names, IDs, or data (e.g. prefer "Search for a trade" over "Find all trades with Client A").` + capabilitiesBlock + guidanceBlock + OUTPUT_FORMAT(count);
3924
- }
3925
- const conversationContext = history.filter(
3926
- (m) => (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
3927
- ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
3928
- return `<conversation_history>
3929
- ${conversationContext}
3930
- </conversation_history>
3931
-
3932
- The conversation above has ended. Do not continue it or respond as the assistant. Generate exactly ${count} follow-up prompts the *user* might send next, phrased in first person as the user would write them. The first ${Math.max(0, count - 1)} should be natural follow-ups to the last turn. Do not invent specific names, IDs, or data values that do not appear in <conversation_history>.` + capabilitiesBlock + guidanceBlock + OUTPUT_FORMAT(count);
3933
- }
3934
- function parseSuggestions(text, count) {
3935
- return text.split("\n").map((s) => s.trim()).map((s) => s.replace(/^([-*•]|\d+[.)])\s+/, "")).map((s) => s.replace(/^[*_]{1,3}|[*_]{1,3}$/g, "").trim()).filter((s) => s.length > 0).filter((s) => !/^[-=]{2,}$/.test(s)).filter((s) => !/^here (are|is) /i.test(s)).filter((s) => !s.endsWith(":")).slice(0, count);
3936
- }
3937
- async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
3938
- const defaultProvider = ctx.registry.default();
3939
- if (!defaultProvider.prompt) {
3940
- logger2.warn("ChatDriver: default AI provider does not implement prompt()");
3941
- return [];
3942
- }
3943
- const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
3944
- const text = await defaultProvider.prompt(userMessage, {
3945
- systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
3946
- });
3947
- return parseSuggestions(text, count);
3948
- }
3949
-
3950
4109
  // src/utils/context-tokens.ts
3951
4110
  var APPROX_CHARS_PER_TOKEN = 4;
3952
4111
  var IMAGE_TOKEN_ESTIMATE = 1600;
@@ -4080,6 +4239,80 @@ function projectCompaction(history, cut, summaryTokens = COMPACTION_SUMMARY_TOKE
4080
4239
  };
4081
4240
  }
4082
4241
 
4242
+ // src/utils/logger.ts
4243
+ var logger2 = createLogger("ai-assistant");
4244
+
4245
+ // src/suggestions/generate-suggestions.ts
4246
+ var HISTORY_WINDOW = 8;
4247
+ function capabilities(ctx, allAgentInfo) {
4248
+ let agentContext = "";
4249
+ let toolContext = "";
4250
+ if (allAgentInfo?.length) {
4251
+ const agentDescriptions = allAgentInfo.map((agent) => {
4252
+ const tools = agent.tools.map((t) => t.name).join(", ");
4253
+ return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
4254
+ }).join("\n");
4255
+ agentContext = `The assistant has the following capabilities:
4256
+ ${agentDescriptions}`;
4257
+ const allToolNames = [
4258
+ ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
4259
+ ].join(", ");
4260
+ toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
4261
+ } else if (ctx.activeAgentName) {
4262
+ const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
4263
+ agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
4264
+ toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
4265
+ }
4266
+ return agentContext || toolContext ? `
4267
+
4268
+ <capabilities>
4269
+ ${[agentContext, toolContext].filter(Boolean).join(
4270
+ "\n"
4271
+ )}
4272
+ </capabilities>
4273
+ Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
4274
+ }
4275
+ var OUTPUT_FORMAT = (count) => `
4276
+
4277
+ Output format (strict):
4278
+ - Exactly ${count} lines.
4279
+ - One suggestion per line.
4280
+ - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
4281
+ - No preamble, headings, summary, or commentary before or after the list.`;
4282
+ var SUGGESTIONS_SYSTEM_PROMPT = "You generate suggested prompts that a user could send to an AI assistant. You never continue the conversation or roleplay as the assistant.";
4283
+ function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
4284
+ const capabilitiesBlock = capabilities(ctx, allAgentInfo);
4285
+ const guidanceBlock = prompt2 ? `
4286
+
4287
+ Additional guidance: "${prompt2}"` : "";
4288
+ if (history.length === 0) {
4289
+ return `Generate exactly ${count} brief starter prompts to show a user what an AI assistant can do. Phrase each one as the user would write it. Keep them short and generic \u2014 do not invent specific names, IDs, or data (e.g. prefer "Search for a trade" over "Find all trades with Client A").` + capabilitiesBlock + guidanceBlock + OUTPUT_FORMAT(count);
4290
+ }
4291
+ const conversationContext = history.filter(
4292
+ (m) => reachesProvider(m) && (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
4293
+ ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
4294
+ return `<conversation_history>
4295
+ ${conversationContext}
4296
+ </conversation_history>
4297
+
4298
+ The conversation above has ended. Do not continue it or respond as the assistant. Generate exactly ${count} follow-up prompts the *user* might send next, phrased in first person as the user would write them. The first ${Math.max(0, count - 1)} should be natural follow-ups to the last turn. Do not invent specific names, IDs, or data values that do not appear in <conversation_history>.` + capabilitiesBlock + guidanceBlock + OUTPUT_FORMAT(count);
4299
+ }
4300
+ function parseSuggestions(text, count) {
4301
+ return text.split("\n").map((s) => s.trim()).map((s) => s.replace(/^([-*•]|\d+[.)])\s+/, "")).map((s) => s.replace(/^[*_]{1,3}|[*_]{1,3}$/g, "").trim()).filter((s) => s.length > 0).filter((s) => !/^[-=]{2,}$/.test(s)).filter((s) => !/^here (are|is) /i.test(s)).filter((s) => !s.endsWith(":")).slice(0, count);
4302
+ }
4303
+ async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
4304
+ const defaultProvider = ctx.registry.default();
4305
+ if (!defaultProvider.prompt) {
4306
+ logger2.warn("ChatDriver: default AI provider does not implement prompt()");
4307
+ return [];
4308
+ }
4309
+ const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
4310
+ const text = await defaultProvider.prompt(userMessage, {
4311
+ systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
4312
+ });
4313
+ return parseSuggestions(text, count);
4314
+ }
4315
+
4083
4316
  // src/utils/condense-history.ts
4084
4317
  var CONDENSE_MIN_CHARS = 1e3;
4085
4318
  var CONDENSED_ARGS_KEY = "condensed";
@@ -4468,7 +4701,7 @@ function renderMessageForSummary(m) {
4468
4701
  }
4469
4702
  }
4470
4703
  function buildCompactionSummaryPrompt(toCompact) {
4471
- const transcript = toCompact.map(renderMessageForSummary).filter(Boolean).join("\n");
4704
+ const transcript = toCompact.filter((m) => !m.excludeFromProvider).map(renderMessageForSummary).filter(Boolean).join("\n");
4472
4705
  const systemPrompt = "You compress a conversation transcript into a concise summary that lets an AI assistant continue the conversation seamlessly. Preserve key facts, decisions, what the user wants, entity names and IDs, and any unresolved threads. Write plain prose. Never roleplay or continue the conversation.";
4473
4706
  const userMessage = `<conversation_history>
4474
4707
  ${transcript}
@@ -4986,6 +5219,10 @@ function createInteractionContext(interactionId) {
4986
5219
  }
4987
5220
 
4988
5221
  // src/components/chat-driver/interaction-controller.ts
5222
+ var STOPPED = {
5223
+ status: "timeout",
5224
+ message: "The turn was stopped before this was answered."
5225
+ };
4989
5226
  var InteractionController = class {
4990
5227
  constructor(deps) {
4991
5228
  this.deps = deps;
@@ -5058,6 +5295,19 @@ var InteractionController = class {
5058
5295
  ...presentation ? { presentation } : {}
5059
5296
  }
5060
5297
  });
5298
+ const signal = options?.signal;
5299
+ if (signal) {
5300
+ const onAbort = () => this.resolve(interactionId, STOPPED);
5301
+ if (signal.aborted) {
5302
+ onAbort();
5303
+ } else {
5304
+ signal.addEventListener("abort", onAbort, { once: true });
5305
+ const pending = this.pending.get(interactionId);
5306
+ if (pending) {
5307
+ pending.unlinkSignal = () => signal.removeEventListener("abort", onAbort);
5308
+ }
5309
+ }
5310
+ }
5061
5311
  });
5062
5312
  }
5063
5313
  /**
@@ -5071,6 +5321,7 @@ var InteractionController = class {
5071
5321
  return;
5072
5322
  }
5073
5323
  if (interaction.timeoutHandle) clearTimeout(interaction.timeoutHandle);
5324
+ interaction.unlinkSignal?.();
5074
5325
  this.deps.foldDiagnostics(
5075
5326
  interactionId,
5076
5327
  result?.diagnostics
@@ -5231,6 +5482,13 @@ var TURN_FAILURE_EXITS = {
5231
5482
  // Overridden per wall by `ChatDriver.budgetExhaustedBubble`, which upgrades this with
5232
5483
  // "switch to another AI" when a second vendor is reachable.
5233
5484
  copy: DEFAULT_BUDGET_EXHAUSTED_MESSAGE
5485
+ },
5486
+ aiServiceError: {
5487
+ subReason: "ai_service_error",
5488
+ resultReason: "ai-service-error",
5489
+ // Replaced per code by `ChatDriver.aiServiceErrorBubble`; this is only what a parent says when
5490
+ // a child's failure arrives without its code.
5491
+ copy: DEFAULT_AI_SERVICE_ERROR_MESSAGES.BAD_REQUEST
5234
5492
  }
5235
5493
  // `satisfies`, not an annotation: an annotation would widen `resultReason` to
5236
5494
  // `TurnFailureReason` and cost the literal types that let `turn-failures.test.ts` pin the
@@ -5401,6 +5659,19 @@ var TurnRecorder = class {
5401
5659
  };
5402
5660
 
5403
5661
  // src/components/chat-driver/chat-driver.ts
5662
+ var REQUEST_SCOPED_REFUSALS = /* @__PURE__ */ new Set([
5663
+ "REQUEST_TOO_LARGE",
5664
+ "BAD_REQUEST",
5665
+ "FALLBACKS_NOT_SUPPORTED"
5666
+ ]);
5667
+ var SERVICE_WIDE_REFUSALS = /* @__PURE__ */ new Set([
5668
+ "NO_API_KEY",
5669
+ "BAD_API_KEY",
5670
+ "KEY_UNREADABLE",
5671
+ "SIGNED_OUT",
5672
+ "ACCESS_DENIED",
5673
+ "VENDOR_UNREACHABLE"
5674
+ ]);
5404
5675
  var toolResultImages = (result) => {
5405
5676
  if (!result || typeof result !== "object") return void 0;
5406
5677
  const candidate = result.attachments;
@@ -5429,6 +5700,15 @@ var budgetDetailOf = (e) => {
5429
5700
  ...e.otherVendorAvailable != null ? { otherVendorAvailable: e.otherVendorAvailable } : {}
5430
5701
  };
5431
5702
  };
5703
+ function inFlightToolCallsAt(history) {
5704
+ for (let i = history.length - 1; i >= 0; i -= 1) {
5705
+ const message = history[i];
5706
+ if (message.role !== "assistant" || !message.toolCalls?.length) continue;
5707
+ const answered = new Set(history.slice(i + 1).map((later) => later.toolResult?.toolCallId));
5708
+ return message.toolCalls.some((call) => !answered.has(call.id)) ? i : history.length;
5709
+ }
5710
+ return history.length;
5711
+ }
5432
5712
  var ChatDriver = class _ChatDriver extends EventTarget {
5433
5713
  constructor(providerRegistry, config = {}) {
5434
5714
  super();
@@ -5574,6 +5854,17 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5574
5854
  this.turnController = new AbortController();
5575
5855
  /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
5576
5856
  this.turnCancelled = false;
5857
+ /**
5858
+ * The scope tool handlers see as `turnSignal`: one USER MESSAGE. Minted by `sendMessage`, so a
5859
+ * handoff's `continueFromHistory` — a new `turnController`, but the same message — keeps it,
5860
+ * and a sub-agent inherits it (`inheritedTurnSignal`). Aborted by `cancel()` and by a dispose.
5861
+ * `continueFromHistory` mints one only when the message it would continue was stopped.
5862
+ *
5863
+ * Kept apart from `turnController`, which is per REQUEST and restarts on every continuation: a
5864
+ * handler that remembers something "for the rest of the turn" (the write tools' deny lock) keyed
5865
+ * on that one was reset by every handoff inside a single message.
5866
+ */
5867
+ this.messageController = new AbortController();
5577
5868
  /**
5578
5869
  * Caches validated provider lookups per name within the current agent. Cleared
5579
5870
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -5610,6 +5901,20 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5610
5901
  * children costing N doomed calls plus a doomed parent one.
5611
5902
  */
5612
5903
  this.providerRefusedThisTurn = false;
5904
+ /**
5905
+ * A sub-agent was refused by the AI service this turn in a way that stops this driver too
5906
+ * (GENC-1611): a service-wide code, from the vendor this driver calls. Sub-agent path only, like
5907
+ * `providerRefusedThisTurn`; this driver's own refusal returns straight out of the catch.
5908
+ */
5909
+ this.aiServiceErrorThisTurn = false;
5910
+ /** Codes a child's refusal was already shown for during this user message. */
5911
+ this.aiServiceNoticesShown = /* @__PURE__ */ new Set();
5912
+ /**
5913
+ * Notices waiting for the tool batch to end. Written mid-batch they would sit between the
5914
+ * assistant's tool calls and their results, where a later sub-agent's primer would pick up the
5915
+ * unanswered calls.
5916
+ */
5917
+ this.aiServiceNoticesQueued = [];
5613
5918
  /**
5614
5919
  * Set the moment a budget wall is observed anywhere in this turn — this
5615
5920
  * driver's own 402, or a sub-agent's (which surfaces here only as a
@@ -5639,7 +5944,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5639
5944
  deferAgentRelease = false,
5640
5945
  activityBus = NOOP_ACTIVITY_BUS,
5641
5946
  budgetExhaustedMessage,
5642
- providerRefusedMessage
5947
+ providerRefusedMessage,
5948
+ aiServiceErrorMessages
5643
5949
  } = config;
5644
5950
  this.maxToolIterations = maxToolIterations;
5645
5951
  this.condenseBatchCalls = condenseBatchCalls;
@@ -5648,6 +5954,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5648
5954
  this.activityBus = activityBus;
5649
5955
  this.budgetExhaustedMessageOverride = budgetExhaustedMessage;
5650
5956
  this.providerRefusedMessageOverride = providerRefusedMessage;
5957
+ this.aiServiceErrorMessagesOverride = aiServiceErrorMessages;
5651
5958
  if (typeof toolHandlers === "function") {
5652
5959
  this.toolHandlersFactory = toolHandlers;
5653
5960
  this.toolHandlers = {};
@@ -5712,14 +6019,43 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5712
6019
  /**
5713
6020
  * Stop the current turn (user "stop" button). Aborts the in-flight provider
5714
6021
  * request immediately; if a tool is mid-execution it runs to completion and
5715
- * the loop bails at the next boundary (tools are atomic). No-op when idle.
5716
- * The driver stays usable for the next message.
6022
+ * the loop bails at the next boundary (tools are atomic). When idle it only ends
6023
+ * the message (see below) and appends nothing. The driver stays usable for the
6024
+ * next message.
5717
6025
  */
5718
6026
  cancel() {
6027
+ this.messageController.abort(new DOMException("Cancelled by user", "AbortError"));
5719
6028
  if (!this.busy) return;
5720
6029
  this.turnCancelled = true;
5721
6030
  this.turnController.abort(new DOMException("Cancelled by user", "AbortError"));
5722
6031
  }
6032
+ /**
6033
+ * Start a fresh per-MESSAGE scope for tool handlers (see `messageController`). Chained to
6034
+ * `lifecycleController` so a dispose aborts it; the link lives until the next message, because
6035
+ * a handoff continues this one.
6036
+ */
6037
+ beginMessage() {
6038
+ this.unlinkLifecycleFromMessage?.();
6039
+ this.messageController = new AbortController();
6040
+ const lifecycle = this.lifecycleController.signal;
6041
+ if (lifecycle.aborted) {
6042
+ this.messageController.abort(lifecycle.reason);
6043
+ this.unlinkLifecycleFromMessage = void 0;
6044
+ return;
6045
+ }
6046
+ const onDispose = () => this.messageController.abort(lifecycle.reason);
6047
+ lifecycle.addEventListener("abort", onDispose, { once: true });
6048
+ this.unlinkLifecycleFromMessage = () => lifecycle.removeEventListener("abort", onDispose);
6049
+ }
6050
+ /**
6051
+ * Makes this (sub-agent) driver's handlers see the parent message's `turnSignal` instead of one
6052
+ * of their own: a delegation is part of the message that made it.
6053
+ *
6054
+ * @internal
6055
+ */
6056
+ inheritTurnSignal(signal) {
6057
+ this.inheritedTurnSignal = signal;
6058
+ }
5723
6059
  /**
5724
6060
  * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
5725
6061
  * new `turnController` so a dispose mid-turn also aborts the request.
@@ -5777,8 +6113,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5777
6113
  */
5778
6114
  endTurnWithFailure(exit, overrides) {
5779
6115
  if (this.isSubAgent) {
5780
- this.failSubAgent(exit.subReason, overrides?.budget, overrides?.providerRefused);
5781
- } else {
6116
+ this.failSubAgent(
6117
+ exit.subReason,
6118
+ overrides?.budget,
6119
+ overrides?.providerRefused,
6120
+ overrides?.aiServiceError
6121
+ );
6122
+ } else if (!overrides?.silent) {
5782
6123
  this.appendDriverNotice(overrides?.copy ?? exit.copy);
5783
6124
  }
5784
6125
  return turnDone(exit.resultReason, overrides?.budget, overrides?.providerRefused);
@@ -5815,6 +6156,19 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5815
6156
  const subject = wall?.vendorLabel ? `${wall.vendorLabel}'s AI usage limit` : "your AI usage limit";
5816
6157
  return `You've reached ${subject}. Switch to another AI provider in Settings to keep going, or contact your administrator to raise it.`;
5817
6158
  }
6159
+ /**
6160
+ * Record a message the user sent and then stopped before any turn took it: during an
6161
+ * orchestrator's first classify, or its first agent's install. Only an optimistic
6162
+ * `history-updated` had shown it, so it vanished on the next update, and from a reload. Appended
6163
+ * here with the "Stopped." marker a stopped turn leaves, as `reportBudgetExhausted` appends a
6164
+ * message the budget wall kept from its turn.
6165
+ *
6166
+ * @internal
6167
+ */
6168
+ reportStoppedBeforeTurn(userMessage) {
6169
+ this.appendToHistory(userMessage);
6170
+ this.appendToHistory({ role: "system-event", content: "Stopped." });
6171
+ }
5818
6172
  reportBudgetExhausted(e, pendingUserMessage) {
5819
6173
  if (pendingUserMessage) this.appendToHistory(pendingUserMessage);
5820
6174
  this.budgetExhaustedThisTurn = true;
@@ -5847,6 +6201,158 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5847
6201
  providerRefusedBubble() {
5848
6202
  return this.providerRefusedMessageOverride ?? TURN_FAILURE_EXITS.providerRefused.copy;
5849
6203
  }
6204
+ /**
6205
+ * A terminal AI service error hit **outside** the tool loop — `OrchestratingDriver`'s classification
6206
+ * phase (GENC-1611). The same log line, debug-log entry, sentence and result as the in-loop branch.
6207
+ *
6208
+ * @param pendingUserMessage - the user's message when it has NOT been appended yet, for the reason
6209
+ * `reportBudgetExhausted` gives.
6210
+ */
6211
+ reportAIServiceError(e, pendingUserMessage) {
6212
+ if (pendingUserMessage) {
6213
+ this.aiServiceNoticesShown.clear();
6214
+ this.aiServiceNoticesQueued = [];
6215
+ this.appendToHistory(pendingUserMessage);
6216
+ }
6217
+ return this.endTurnWithAIServiceError(e);
6218
+ }
6219
+ /**
6220
+ * The sentence for an AI service error code (GENC-1611): the host's override, else the default.
6221
+ * Never the service's own text, which goes to the console only.
6222
+ */
6223
+ aiServiceErrorBubble(code) {
6224
+ if (!code) return TURN_FAILURE_EXITS.aiServiceError.copy;
6225
+ const override = this.aiServiceErrorMessagesOverride?.[code];
6226
+ return override?.trim() ? override : DEFAULT_AI_SERVICE_ERROR_MESSAGES[code];
6227
+ }
6228
+ /**
6229
+ * Shows a sub-agent's AI-service refusal that the turn went on without, once per code in a user
6230
+ * message: the user's sentence with the host's overrides, never the service's text. A sub-agent
6231
+ * passes it up to the driver the user sees.
6232
+ */
6233
+ noticeAIServiceRefusal(code) {
6234
+ if (REQUEST_SCOPED_REFUSALS.has(code)) return;
6235
+ if (this.hostAIServiceNotice) {
6236
+ this.hostAIServiceNotice(code);
6237
+ return;
6238
+ }
6239
+ if (!this.busy) return;
6240
+ if (this.aiServiceNoticesShown.has(code) || this.aiServiceNoticesQueued.includes(code)) return;
6241
+ this.aiServiceNoticesQueued.push(code);
6242
+ }
6243
+ /**
6244
+ * Writes the notices queued during a tool batch, once its results are in the history, or before
6245
+ * the failure when the batch threw. A code counts as shown only once written.
6246
+ */
6247
+ flushAIServiceNotices() {
6248
+ const codes = this.aiServiceNoticesQueued;
6249
+ this.aiServiceNoticesQueued = [];
6250
+ for (const code of codes) {
6251
+ this.aiServiceNoticesShown.add(code);
6252
+ this.appendDriverNotice(this.aiServiceErrorBubble(code));
6253
+ }
6254
+ }
6255
+ /** Ends the turn on an AI service error: logged with the service's text, shown without it. */
6256
+ endTurnWithAIServiceError(e) {
6257
+ logger2.error("ChatDriver: the AI service refused the request", e, e.detail ?? "");
6258
+ recordTurnError(this.sessionKey, "ai-service-error", {
6259
+ agent: this.activeAgentName,
6260
+ provider: this.lastResolvedProviderName,
6261
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider,
6262
+ code: e.code,
6263
+ status: e.status,
6264
+ isSubAgent: this.isSubAgent
6265
+ });
6266
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6267
+ copy: this.aiServiceErrorBubble(e.code),
6268
+ aiServiceError: {
6269
+ code: e.code,
6270
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider
6271
+ },
6272
+ silent: this.aiServiceSentenceShown(e.code)
6273
+ });
6274
+ }
6275
+ /**
6276
+ * Whether this user message already showed the sentence for `code`, so a turn-ending failure
6277
+ * does not show it twice. Marks it shown otherwise. Only the driver the user sees keeps count.
6278
+ */
6279
+ aiServiceSentenceShown(code) {
6280
+ if (this.isSubAgent || !code) return false;
6281
+ if (this.aiServiceNoticesShown.has(code)) return true;
6282
+ this.aiServiceNoticesShown.add(code);
6283
+ return false;
6284
+ }
6285
+ /**
6286
+ * Whether a sub-agent hit a wall this turn that stops this driver too. A handoff goes on past an
6287
+ * AI-service wall: the next agent may use another vendor, and if it uses this one its own call
6288
+ * meets the wall and says so.
6289
+ */
6290
+ subAgentWallThisTurn(handingOff = false) {
6291
+ return this.providerRefusedThisTurn || this.budgetExhaustedThisTurn || this.aiServiceErrorThisTurn && !handingOff;
6292
+ }
6293
+ /**
6294
+ * Ends the turn when a sub-agent hit a wall this turn that stops this driver too: the provider
6295
+ * refusing the account, the AI service (GENC-1611), or the budget. Checked before each model call,
6296
+ * and again right after a tool batch, before a handoff or the iteration cap can report the turn as
6297
+ * something else.
6298
+ */
6299
+ endTurnOnSubAgentWall() {
6300
+ if (!this.subAgentWallThisTurn()) return void 0;
6301
+ this.subAgentCompletion = void 0;
6302
+ if (this.providerRefusedThisTurn) {
6303
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6304
+ recordTurnError(this.sessionKey, "provider-refused", {
6305
+ agent: this.activeAgentName,
6306
+ provider: this.lastResolvedProviderName,
6307
+ kind: this.providerRefusedDetail?.kind,
6308
+ via: "sub-agent",
6309
+ isSubAgent: this.isSubAgent
6310
+ });
6311
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6312
+ copy: this.providerRefusedBubble(),
6313
+ providerRefused: this.providerRefusedDetail
6314
+ });
6315
+ }
6316
+ if (this.aiServiceErrorThisTurn) {
6317
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent was refused by the AI service");
6318
+ recordTurnError(this.sessionKey, "ai-service-error", {
6319
+ agent: this.activeAgentName,
6320
+ provider: this.lastResolvedProviderName,
6321
+ code: this.aiServiceWall?.code,
6322
+ via: "sub-agent",
6323
+ isSubAgent: this.isSubAgent
6324
+ });
6325
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6326
+ copy: this.aiServiceErrorBubble(this.aiServiceWall?.code),
6327
+ aiServiceError: this.aiServiceWall,
6328
+ silent: this.aiServiceSentenceShown(this.aiServiceWall?.code)
6329
+ });
6330
+ }
6331
+ if (this.budgetExhaustedThisTurn) {
6332
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6333
+ recordTurnError(this.sessionKey, "budget-exhausted", {
6334
+ agent: this.activeAgentName,
6335
+ provider: this.lastResolvedProviderName,
6336
+ // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6337
+ // path the wall is definitionally the child's, and on a mixed registry
6338
+ // `lastResolvedProvider` is this driver's own vendor — the one known
6339
+ // NOT to have refused. An unattributable child wall must degrade to
6340
+ // the vendor-agnostic block (which `latchBlockedFrom` handles
6341
+ // fail-safe), never to a vendor that is known to be wrong: naming the
6342
+ // parent's vendor here walled BOTH — the child's via its own
6343
+ // tool-loop-end, the parent's via this event — and derived `blocked`
6344
+ // over headroom that still existed.
6345
+ vendor: this.budgetWallDetail?.vendor,
6346
+ via: "sub-agent",
6347
+ isSubAgent: this.isSubAgent
6348
+ });
6349
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6350
+ copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6351
+ budget: this.budgetWallDetail
6352
+ });
6353
+ }
6354
+ return void 0;
6355
+ }
5850
6356
  /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
5851
6357
  static failureReasonOf(result) {
5852
6358
  return result.reason === "done" ? result.failureReason : void 0;
@@ -6127,12 +6633,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6127
6633
  * under a separate session key, so recording here would orphan the event off
6128
6634
  * the user-visible debug-log timeline.)
6129
6635
  */
6130
- failSubAgent(reason, budget, providerRefused) {
6636
+ failSubAgent(reason, budget, providerRefused, aiServiceError) {
6131
6637
  if (!this.isSubAgent || this.subAgentFailure) return;
6132
6638
  this.subAgentFailure = {
6133
6639
  reason,
6134
6640
  ...budget ? { budget } : {},
6135
- ...providerRefused ? { providerRefused } : {}
6641
+ ...providerRefused ? { providerRefused } : {},
6642
+ ...aiServiceError ? { aiServiceError } : {}
6136
6643
  };
6137
6644
  }
6138
6645
  /**
@@ -6563,6 +7070,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6563
7070
  if (this.busy || !userInput.trim() && !attachments?.length) return { reason: "done" };
6564
7071
  this.busy = true;
6565
7072
  this.beginTurn();
7073
+ this.beginMessage();
6566
7074
  this.turnSeq += 1;
6567
7075
  this.subAgentCompletion = void 0;
6568
7076
  this.subAgentFailure = void 0;
@@ -6572,6 +7080,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6572
7080
  this.budgetWallViaSubAgent = false;
6573
7081
  this.providerRefusedThisTurn = false;
6574
7082
  this.providerRefusedDetail = void 0;
7083
+ this.aiServiceErrorThisTurn = false;
7084
+ this.aiServiceWall = void 0;
7085
+ this.aiServiceNoticesShown.clear();
7086
+ this.aiServiceNoticesQueued = [];
6575
7087
  this.appendToHistory({ role: "user", content: userInput, attachments });
6576
7088
  this.turnStartedAt = Date.now();
6577
7089
  recordMetaEvent(this.sessionKey, "turn.start", {
@@ -6592,6 +7104,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6592
7104
  name: e instanceof Error ? e.name : void 0,
6593
7105
  message: e instanceof Error ? e.message : String(e)
6594
7106
  });
7107
+ this.flushAIServiceNotices();
6595
7108
  this.appendDriverNotice(
6596
7109
  "Sorry, something went wrong on my end. Please try again in a moment."
6597
7110
  );
@@ -6636,6 +7149,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6636
7149
  buildHandlerContext(activeToolCallId, traceCapture) {
6637
7150
  return {
6638
7151
  requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options),
7152
+ // The MESSAGE's scope: one object per `sendMessage`, kept across a handoff's continuation
7153
+ // and handed to a sub-agent, and aborted by `cancel()` as well as a dispose. Not the
7154
+ // per-request `turnController`, which every continuation replaces.
7155
+ turnSignal: this.inheritedTurnSignal ?? this.messageController.signal,
6639
7156
  ...this.subAgentsMap.size > 0 && {
6640
7157
  requestSubAgent: (name, options) => this.invokeSubAgent(name, options).then(({ outcome, trace }) => {
6641
7158
  if (traceCapture && trace) traceCapture.traces.push(trace);
@@ -6712,8 +7229,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6712
7229
  );
6713
7230
  }
6714
7231
  const { task, historyCap, context, timeoutMs } = options ?? {};
6715
- const lastMsg = this.history[this.history.length - 1];
6716
- const baseHistory = lastMsg?.role === "assistant" && lastMsg.toolCalls?.length ? this.history.slice(0, -1) : this.history;
7232
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
6717
7233
  const snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
6718
7234
  const contextMessages = context ? [{ role: "user", content: `[Sub-agent context]: ${JSON.stringify(context)}` }] : [];
6719
7235
  const effectivePrimer = [
@@ -6730,6 +7246,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6730
7246
  activityBus: this.activityBus
6731
7247
  });
6732
7248
  child.markAsSubAgent();
7249
+ child.inheritTurnSignal(this.inheritedTurnSignal ?? this.messageController.signal);
6733
7250
  child.setContextGuard(this.contextGuard);
6734
7251
  const disposeChild = () => child.dispose();
6735
7252
  if (this.lifecycleController.signal.aborted) {
@@ -6741,6 +7258,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6741
7258
  child.setHostInteractionRequester(
6742
7259
  (componentName, data, opts) => this.requestInteraction(componentName, data, opts)
6743
7260
  );
7261
+ child.hostAIServiceNotice = (code) => this.noticeAIServiceRefusal(code);
6744
7262
  const forwardTrace = (e) => {
6745
7263
  this.dispatchEvent(
6746
7264
  new CustomEvent("sub-agent-history-updated", {
@@ -6821,6 +7339,28 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6821
7339
  this.providerRefusedThisTurn = true;
6822
7340
  this.providerRefusedDetail ??= failure?.providerRefused;
6823
7341
  }
7342
+ const wall = failure?.aiServiceError;
7343
+ if (reason === "ai_service_error" && wall && SERVICE_WIDE_REFUSALS.has(wall.code) && wall.vendor !== void 0 && wall.vendor === this.lastResolvedProvider) {
7344
+ this.aiServiceErrorThisTurn = true;
7345
+ this.aiServiceWall ??= wall;
7346
+ } else if (reason === "ai_service_error" && wall) {
7347
+ this.noticeAIServiceRefusal(wall.code);
7348
+ }
7349
+ if (reason === "ai_service_error") {
7350
+ if (wall) {
7351
+ return {
7352
+ outcome: {
7353
+ ok: false,
7354
+ reason,
7355
+ code: wall.code,
7356
+ terminal: isTerminalAIServiceRefusal(wall.code)
7357
+ },
7358
+ trace
7359
+ };
7360
+ }
7361
+ logger2.error(`ChatDriver: sub-agent "${name}" was refused by the AI service with no code`);
7362
+ return { outcome: { ok: false, reason: "max_iterations" }, trace };
7363
+ }
6824
7364
  return { outcome: { ok: false, reason }, trace };
6825
7365
  }
6826
7366
  /**
@@ -6830,6 +7370,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6830
7370
  async continueFromHistory(transientPrimer) {
6831
7371
  if (this.busy) return { reason: "done" };
6832
7372
  this.busy = true;
7373
+ if (this.messageController.signal.aborted) this.beginMessage();
6833
7374
  this.beginTurn();
6834
7375
  this.subAgentCompletion = void 0;
6835
7376
  this.subAgentFailure = void 0;
@@ -6838,6 +7379,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6838
7379
  this.budgetWallViaSubAgent = false;
6839
7380
  this.providerRefusedThisTurn = false;
6840
7381
  this.providerRefusedDetail = void 0;
7382
+ this.aiServiceErrorThisTurn = false;
7383
+ this.aiServiceWall = void 0;
6841
7384
  this.turnStartedAt = Date.now();
6842
7385
  recordMetaEvent(this.sessionKey, "turn.start", {
6843
7386
  phase: "continueFromHistory",
@@ -6857,6 +7400,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6857
7400
  name: e instanceof Error ? e.name : void 0,
6858
7401
  message: e instanceof Error ? e.message : String(e)
6859
7402
  });
7403
+ this.flushAIServiceNotices();
6860
7404
  this.appendDriverNotice(
6861
7405
  "Sorry, something went wrong on my end. Please try again in a moment."
6862
7406
  );
@@ -6903,43 +7447,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6903
7447
  if (this.turnController.signal.aborted) {
6904
7448
  return this.completeAbortedTurn();
6905
7449
  }
6906
- if (this.providerRefusedThisTurn) {
6907
- logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6908
- recordTurnError(this.sessionKey, "provider-refused", {
6909
- agent: this.activeAgentName,
6910
- provider: this.lastResolvedProviderName,
6911
- kind: this.providerRefusedDetail?.kind,
6912
- via: "sub-agent",
6913
- isSubAgent: this.isSubAgent
6914
- });
6915
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6916
- copy: this.providerRefusedBubble(),
6917
- providerRefused: this.providerRefusedDetail
6918
- });
6919
- }
6920
- if (this.budgetExhaustedThisTurn) {
6921
- logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6922
- recordTurnError(this.sessionKey, "budget-exhausted", {
6923
- agent: this.activeAgentName,
6924
- provider: this.lastResolvedProviderName,
6925
- // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6926
- // path the wall is definitionally the child's, and on a mixed registry
6927
- // `lastResolvedProvider` is this driver's own vendor — the one known
6928
- // NOT to have refused. An unattributable child wall must degrade to
6929
- // the vendor-agnostic block (which `latchBlockedFrom` handles
6930
- // fail-safe), never to a vendor that is known to be wrong: naming the
6931
- // parent's vendor here walled BOTH — the child's via its own
6932
- // tool-loop-end, the parent's via this event — and derived `blocked`
6933
- // over headroom that still existed.
6934
- vendor: this.budgetWallDetail?.vendor,
6935
- via: "sub-agent",
6936
- isSubAgent: this.isSubAgent
6937
- });
6938
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6939
- copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6940
- budget: this.budgetWallDetail
6941
- });
6942
- }
7450
+ const wall = this.endTurnOnSubAgentWall();
7451
+ if (wall) return wall;
6943
7452
  const promptCtx = {
6944
7453
  agentName: this.activeAgentName ?? "",
6945
7454
  history: this.history,
@@ -7185,6 +7694,9 @@ ${tailBody}
7185
7694
  providerRefused: detail
7186
7695
  });
7187
7696
  }
7697
+ if (e instanceof AIServiceError && e.terminal) {
7698
+ return this.endTurnWithAIServiceError(e);
7699
+ }
7188
7700
  if (e instanceof BudgetExhaustedError) {
7189
7701
  this.budgetExhaustedThisTurn = true;
7190
7702
  this.budgetWallDetail = budgetDetailOf(e);
@@ -7226,6 +7738,7 @@ ${tailBody}
7226
7738
  iterations -= 1;
7227
7739
  continue;
7228
7740
  }
7741
+ if (e instanceof AIServiceError) return this.endTurnWithAIServiceError(e);
7229
7742
  throw e;
7230
7743
  }
7231
7744
  if (response.model === void 0 && this.lastResolvedModel !== void 0) {
@@ -7549,6 +8062,7 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7549
8062
  this.history[tcMsgIdx] = { ...tcMsg, toolCalls: annotatedCalls };
7550
8063
  this.notifyHistoryUpdated();
7551
8064
  }
8065
+ this.flushAIServiceNotices();
7552
8066
  if (hitUnknownToolLimit) {
7553
8067
  logger2.error(
7554
8068
  `ChatDriver: unknown-tool limit (${DEFAULT_MAX_UNKNOWN_TOOL_CALLS}) reached \u2014 stopping`
@@ -7578,6 +8092,15 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7578
8092
  return this.endTurnWithFailure(TURN_FAILURE_EXITS.unknownToolLimit);
7579
8093
  }
7580
8094
  const firstContinuation = systemCalls[0];
8095
+ if (!this.subAgentCompletion && this.subAgentWallThisTurn(!!firstContinuation)) {
8096
+ if (this.turnController.signal.aborted) return this.completeAbortedTurn();
8097
+ const wallAfterBatch = this.endTurnOnSubAgentWall();
8098
+ if (wallAfterBatch) return wallAfterBatch;
8099
+ }
8100
+ if (this.aiServiceErrorThisTurn && this.aiServiceWall) {
8101
+ this.noticeAIServiceRefusal(this.aiServiceWall.code);
8102
+ this.flushAIServiceNotices();
8103
+ }
7581
8104
  if (firstContinuation) {
7582
8105
  const { summary, remaining_task: remainingTask } = firstContinuation.args;
7583
8106
  return { reason: "agent-handoff", summary, remainingTask };
@@ -7747,6 +8270,7 @@ var OrchestratingDriver = class extends EventTarget {
7747
8270
  sessionKey: this.sessionKey,
7748
8271
  activityBus: options.activityBus,
7749
8272
  budgetExhaustedMessage: options.budgetExhaustedMessage,
8273
+ aiServiceErrorMessages: options.aiServiceErrorMessages,
7750
8274
  // This driver releases after the turn so it can fire the host-facing events; see the option.
7751
8275
  deferAgentRelease: true
7752
8276
  });
@@ -7927,15 +8451,16 @@ var OrchestratingDriver = class extends EventTarget {
7927
8451
  try {
7928
8452
  return await this.runOrchestratedTurn(input, attachments);
7929
8453
  } catch (e) {
8454
+ const pendingUserMessage = this.userMessageAppended ? void 0 : {
8455
+ role: "user",
8456
+ content: input,
8457
+ ...attachments ? { attachments } : {}
8458
+ };
7930
8459
  if (e instanceof BudgetExhaustedError) {
7931
- return this.chatDriver.reportBudgetExhausted(
7932
- e,
7933
- this.userMessageAppended ? void 0 : {
7934
- role: "user",
7935
- content: input,
7936
- ...attachments ? { attachments } : {}
7937
- }
7938
- );
8460
+ return this.chatDriver.reportBudgetExhausted(e, pendingUserMessage);
8461
+ }
8462
+ if (e instanceof AIServiceError) {
8463
+ return this.chatDriver.reportAIServiceError(e, pendingUserMessage);
7939
8464
  }
7940
8465
  throw e;
7941
8466
  }
@@ -7968,6 +8493,7 @@ var OrchestratingDriver = class extends EventTarget {
7968
8493
  while (true) {
7969
8494
  if (this.cancelled) break;
7970
8495
  await this.installAgent(currentAgent);
8496
+ if (this.cancelled) break;
7971
8497
  let result;
7972
8498
  if (isHandoff) {
7973
8499
  const contextPrimer = handoffSummary ? [{ role: "user", content: `[Context from previous agent]: ${handoffSummary}` }] : [];
@@ -7992,6 +8518,7 @@ var OrchestratingDriver = class extends EventTarget {
7992
8518
  if (result.reason !== "agent-handoff" || isFallback(currentAgent) || pinned) {
7993
8519
  break;
7994
8520
  }
8521
+ if (this.cancelled) break;
7995
8522
  handoffs += 1;
7996
8523
  if (handoffs > this.maxHandoffs) {
7997
8524
  this.appendInlineMessage(
@@ -8010,6 +8537,13 @@ var OrchestratingDriver = class extends EventTarget {
8010
8537
  routed = await this.classify(remainingTask, updatedHistory, void 0, attempted);
8011
8538
  currentAgent = routed.agent;
8012
8539
  }
8540
+ if (this.cancelled && !this.userMessageAppended) {
8541
+ this.chatDriver.reportStoppedBeforeTurn({
8542
+ role: "user",
8543
+ content: input,
8544
+ ...attachments ? { attachments } : {}
8545
+ });
8546
+ }
8013
8547
  return lastResult?.reason === "done" ? lastResult : { reason: "done" };
8014
8548
  }
8015
8549
  async continueFromHistory(transientPrimer) {
@@ -8267,6 +8801,7 @@ ${recentMessages}` : ""}`;
8267
8801
  break;
8268
8802
  } catch (e) {
8269
8803
  if (e instanceof BudgetExhaustedError) throw e;
8804
+ if (e instanceof AIServiceError && e.terminal) throw e;
8270
8805
  lastError = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
8271
8806
  logger2.warn(`OrchestratingDriver: classifier attempt ${attempt + 1} failed:`, e);
8272
8807
  if (attempt === this.classifierRetries) {
@@ -8709,6 +9244,9 @@ function withFreshMetaSnapshot(stored, fresh) {
8709
9244
  }
8710
9245
  // Annotate the CommonJS export names for ESM import in node:
8711
9246
  0 && (module.exports = {
9247
+ AIServiceError,
9248
+ AI_SERVICE_ACCESS_REFUSALS,
9249
+ AI_SERVICE_ERROR_CODES,
8712
9250
  AI_TIER_IDS,
8713
9251
  AI_TIER_VENDORS,
8714
9252
  ANTHROPIC_CACHE_READ_MULTIPLIER,
@@ -8718,6 +9256,7 @@ function withFreshMetaSnapshot(stored, fresh) {
8718
9256
  AnthropicProvider,
8719
9257
  AnthropicTransport,
8720
9258
  ChatDriver,
9259
+ DEFAULT_AI_SERVICE_ERROR_MESSAGES,
8721
9260
  DEFAULT_AI_TIERS,
8722
9261
  DEFAULT_PROVIDER_REFUSED_MESSAGE,
8723
9262
  EMPTY_RESPONSE_NUDGE,
@@ -8738,6 +9277,8 @@ function withFreshMetaSnapshot(stored, fresh) {
8738
9277
  UNROUTABLE_PLACEHOLDER,
8739
9278
  addUsage,
8740
9279
  agenticActivityBus,
9280
+ aiServiceAccessRefusalOf,
9281
+ aiServiceErrorCodeOf,
8741
9282
  anthropicRatesFor,
8742
9283
  anthropicTokenCost,
8743
9284
  assembleDebugLog,
@@ -8751,6 +9292,7 @@ function withFreshMetaSnapshot(stored, fresh) {
8751
9292
  geminiTokenCost,
8752
9293
  getMetaEvents,
8753
9294
  isObservableAIProviderRegistry,
9295
+ isTerminalAIServiceRefusal,
8754
9296
  messageUsage,
8755
9297
  resolveAITiers,
8756
9298
  restoreMachine,