@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
@@ -151,6 +151,12 @@ function combineSignals(signals) {
151
151
  return { signal: controller.signal, dispose };
152
152
  }
153
153
 
154
+ // ../../foundation-logger/dist/esm/log-timestamps.js
155
+ var LOG_TIMESTAMPS_FLAG = Symbol.for("@genesislcap/foundation-logger:timestamps");
156
+ function areLogTimestampsEnabled() {
157
+ return Reflect.get(globalThis, LOG_TIMESTAMPS_FLAG) === true;
158
+ }
159
+
154
160
  // ../../../../node_modules/consola/dist/core.mjs
155
161
  var LogLevels = {
156
162
  silent: Number.NEGATIVE_INFINITY,
@@ -731,15 +737,118 @@ function createConsola2(options = {}) {
731
737
  }
732
738
  var consola = createConsola2();
733
739
 
740
+ // ../../foundation-logger/dist/esm/timestamp-browser-reporter.js
741
+ var TIME_UNIT_DIGITS = 2;
742
+ var MILLISECOND_DIGITS = 3;
743
+ function formatLogTimestamp(date) {
744
+ const hours = String(date.getHours()).padStart(TIME_UNIT_DIGITS, "0");
745
+ const minutes = String(date.getMinutes()).padStart(TIME_UNIT_DIGITS, "0");
746
+ const seconds = String(date.getSeconds()).padStart(TIME_UNIT_DIGITS, "0");
747
+ const milliseconds = String(date.getMilliseconds()).padStart(MILLISECOND_DIGITS, "0");
748
+ return `${hours}:${minutes}:${seconds}.${milliseconds}`;
749
+ }
750
+ function getConsoleLogFn(level) {
751
+ const consolaConsole = console;
752
+ if (level < 1) {
753
+ return consolaConsole.__error || consolaConsole.error;
754
+ }
755
+ if (level === 1) {
756
+ return consolaConsole.__warn || consolaConsole.warn;
757
+ }
758
+ return consolaConsole.__log || consolaConsole.log;
759
+ }
760
+ function shouldIncludeTimestamp(ctx) {
761
+ var _a, _b, _c;
762
+ const timestamps = (_a = ctx === null || ctx === void 0 ? void 0 : ctx.options) === null || _a === void 0 ? void 0 : _a.timestamps;
763
+ if (typeof timestamps === "boolean") {
764
+ return timestamps;
765
+ }
766
+ 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) {
767
+ return true;
768
+ }
769
+ return areLogTimestampsEnabled();
770
+ }
771
+ var TimestampBrowserReporter = class {
772
+ constructor() {
773
+ this.defaultColor = "#7f8c8d";
774
+ this.levelColorMap = {
775
+ 0: "#c0392b",
776
+ 1: "#f39c12",
777
+ 3: "#00BCD4"
778
+ };
779
+ this.typeColorMap = {
780
+ success: "#2ecc71"
781
+ };
782
+ }
783
+ /**
784
+ * Writes a log object to the console, prefixed with `logObj.date` when enabled.
785
+ *
786
+ * @param logObj - The Consola log object. See Consola's `LogObject`.
787
+ * @param ctx - Reporter context, including Consola options.
788
+ */
789
+ log(logObj, ctx) {
790
+ const consoleLogFn = getConsoleLogFn(logObj.level);
791
+ const type = logObj.type === "log" ? "" : logObj.type;
792
+ const tag = logObj.tag || "";
793
+ const timestamp = shouldIncludeTimestamp(ctx) ? formatLogTimestamp(logObj.date) : "";
794
+ const useBrowserStyles = typeof window !== "undefined" && !!(tag || type);
795
+ if (useBrowserStyles) {
796
+ this.logWithBrowserStyles(consoleLogFn, logObj, tag, type, timestamp);
797
+ return;
798
+ }
799
+ this.logPlain(consoleLogFn, logObj, tag, type, timestamp);
800
+ }
801
+ logWithBrowserStyles(consoleLogFn, logObj, tag, type, timestamp) {
802
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
803
+ const style = `
804
+ background: ${color};
805
+ border-radius: 0.5em;
806
+ color: white;
807
+ font-weight: bold;
808
+ padding: 2px 0.5em;
809
+ `;
810
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
811
+ const prefix = timestamp ? `${timestamp} ${badge}` : badge;
812
+ if (typeof logObj.args[0] === "string") {
813
+ consoleLogFn(`${prefix}%c ${logObj.args[0]}`, style, "", ...logObj.args.slice(1));
814
+ return;
815
+ }
816
+ consoleLogFn(prefix, style, ...logObj.args);
817
+ }
818
+ logPlain(consoleLogFn, logObj, tag, type, timestamp) {
819
+ const label = [tag, type].filter(Boolean).join(":");
820
+ const prefix = [timestamp, label ? `[${label}]` : ""].filter(Boolean).join(" ");
821
+ if (typeof logObj.args[0] === "string") {
822
+ consoleLogFn(prefix ? `${prefix} ${logObj.args[0]}` : logObj.args[0], ...logObj.args.slice(1));
823
+ return;
824
+ }
825
+ if (prefix) {
826
+ consoleLogFn(prefix, ...logObj.args);
827
+ return;
828
+ }
829
+ consoleLogFn(...logObj.args);
830
+ }
831
+ };
832
+
734
833
  // ../../foundation-logger/dist/esm/logger.js
735
834
  var defaultLoggerOptions = {
736
- level: LogLevels.debug
835
+ level: LogLevels.debug,
836
+ formatOptions: {
837
+ date: false
838
+ }
737
839
  };
738
- function createLogger(name, options = defaultLoggerOptions) {
739
- const createConsola3 = typeof window !== "undefined" ? createConsola2 : createConsola;
740
- const logger3 = createConsola3().withTag(name);
741
- if ((options === null || options === void 0 ? void 0 : options.level) !== void 0)
742
- logger3.level = options.level;
840
+ var browserReporter = new TimestampBrowserReporter();
841
+ function resolveLoggerOptions(options, isBrowser) {
842
+ const resolved = Object.assign(Object.assign(Object.assign({}, defaultLoggerOptions), options), { formatOptions: Object.assign(Object.assign({}, defaultLoggerOptions.formatOptions), options.formatOptions) });
843
+ if (isBrowser && !resolved.reporters) {
844
+ resolved.reporters = [browserReporter];
845
+ }
846
+ return resolved;
847
+ }
848
+ function createLogger(name, options = {}) {
849
+ const isBrowser = typeof window !== "undefined";
850
+ const createConsola3 = isBrowser ? createConsola2 : createConsola;
851
+ const logger3 = createConsola3(resolveLoggerOptions(options, isBrowser)).withTag(name);
743
852
  const typedLogger = logger3;
744
853
  typedLogger.deprecated = (symbol, instruction = "Consult docs for better alternative.", removalVersionTarget) => {
745
854
  typedLogger.warn(`Deprecated symbol used '${symbol}'. ${instruction}`, `${removalVersionTarget ? `Will be removed in version ${removalVersionTarget}.` : ""}`);
@@ -1504,6 +1613,98 @@ function abortableDelay(ms, signal) {
1504
1613
  });
1505
1614
  }
1506
1615
 
1616
+ // ../../foundation-ai/dist/esm/transports/ai-service-error.js
1617
+ var AI_SERVICE_ERROR_CODES = Object.freeze({
1618
+ /** No API key is configured for the vendor. */
1619
+ NO_API_KEY: "NO_API_KEY",
1620
+ /** The configured key has characters an API key cannot have. */
1621
+ BAD_API_KEY: "BAD_API_KEY",
1622
+ /** An encrypted key could not be decrypted. */
1623
+ KEY_UNREADABLE: "KEY_UNREADABLE",
1624
+ /** The request asked for a model the service does not allow. */
1625
+ MODEL_NOT_ALLOWED: "MODEL_NOT_ALLOWED",
1626
+ /** The service refused the shape of the request. */
1627
+ BAD_REQUEST: "BAD_REQUEST",
1628
+ /** The request named fallback models, which the service does not accept. */
1629
+ FALLBACKS_NOT_SUPPORTED: "FALLBACKS_NOT_SUPPORTED",
1630
+ /** The request body is larger, or nested deeper, than the service accepts. */
1631
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
1632
+ /** The service could not reach the vendor. The only code that is worth retrying. */
1633
+ VENDOR_UNREACHABLE: "VENDOR_UNREACHABLE"
1634
+ });
1635
+ var KNOWN_CODES = new Set(Object.values(AI_SERVICE_ERROR_CODES));
1636
+ function aiServiceErrorCodeOf(code) {
1637
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : void 0;
1638
+ }
1639
+ var AI_SERVICE_ACCESS_REFUSALS = Object.freeze({
1640
+ /** 401: the request had no session. */
1641
+ SIGNED_OUT: "SIGNED_OUT",
1642
+ /** 403: the user lacks the right the endpoint demands. */
1643
+ ACCESS_DENIED: "ACCESS_DENIED"
1644
+ });
1645
+ var UNAUTHORIZED_STATUS = 401;
1646
+ var FORBIDDEN_STATUS = 403;
1647
+ var PAYLOAD_TOO_LARGE_STATUS = 413;
1648
+ var isRouterNack = (payload) => {
1649
+ if (!payload || typeof payload !== "object")
1650
+ return false;
1651
+ const { MESSAGE_TYPE, ERROR } = payload;
1652
+ return MESSAGE_TYPE === "MSG_NACK" || Array.isArray(ERROR);
1653
+ };
1654
+ var hasCode = (payload) => (payload === null || payload === void 0 ? void 0 : payload.code) !== void 0;
1655
+ function aiServiceAccessRefusalOf(status, payload, bodyText) {
1656
+ if (status !== UNAUTHORIZED_STATUS && status !== FORBIDDEN_STATUS)
1657
+ return void 0;
1658
+ if (hasCode(payload))
1659
+ return void 0;
1660
+ const emptyBody = typeof bodyText === "string" && bodyText.trim() === "";
1661
+ if (!isRouterNack(payload) && !emptyBody)
1662
+ return void 0;
1663
+ return status === UNAUTHORIZED_STATUS ? AI_SERVICE_ACCESS_REFUSALS.SIGNED_OUT : AI_SERVICE_ACCESS_REFUSALS.ACCESS_DENIED;
1664
+ }
1665
+ function isUncodedTooLarge(status, payload) {
1666
+ return status === PAYLOAD_TOO_LARGE_STATUS && payload === void 0;
1667
+ }
1668
+ function routerRefusalDetailOf(payload) {
1669
+ var _a;
1670
+ const errors = payload === null || payload === void 0 ? void 0 : payload.ERROR;
1671
+ const text = Array.isArray(errors) ? (_a = errors[0]) === null || _a === void 0 ? void 0 : _a.TEXT : void 0;
1672
+ return typeof text === "string" && text ? text : void 0;
1673
+ }
1674
+ var REFUSED_REQUEST = "The AI service refused the assistant's request. An administrator can find the details in the browser console.";
1675
+ var DEFAULT_AI_SERVICE_ERROR_MESSAGES = Object.freeze({
1676
+ NO_API_KEY: "The assistant isn't set up yet. An administrator needs to add an API key for its AI service.",
1677
+ BAD_API_KEY: "The assistant can't use its AI service key. An administrator needs to check the key.",
1678
+ KEY_UNREADABLE: "The assistant can't read its AI service key. An administrator needs to check how the key is stored.",
1679
+ 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.",
1680
+ BAD_REQUEST: REFUSED_REQUEST,
1681
+ // The assistant never sends fallbacks, so only a mismatched client can meet this one.
1682
+ FALLBACKS_NOT_SUPPORTED: REFUSED_REQUEST,
1683
+ 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.",
1684
+ 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.",
1685
+ SIGNED_OUT: "Your session has ended. Sign in again to use the assistant.",
1686
+ ACCESS_DENIED: "You don't have access to the assistant. An administrator can give you access."
1687
+ });
1688
+ var isTerminalAIServiceRefusal = (code) => code !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE;
1689
+ var AIServiceError = class extends Error {
1690
+ constructor(vendorLabel, code, status, detail) {
1691
+ super(`${vendorLabel} AI service refused the request (${status} ${code})`);
1692
+ this.vendorLabel = vendorLabel;
1693
+ this.code = code;
1694
+ this.status = status;
1695
+ this.detail = detail;
1696
+ this.name = "AIServiceError";
1697
+ }
1698
+ /** Whether sending the request again cannot help. */
1699
+ get terminal() {
1700
+ return isTerminalAIServiceRefusal(this.code);
1701
+ }
1702
+ };
1703
+ function aiServiceDetailOf(payload) {
1704
+ const error = payload === null || payload === void 0 ? void 0 : payload.error;
1705
+ return typeof error === "string" && error ? error : void 0;
1706
+ }
1707
+
1507
1708
  // ../../foundation-ai/dist/esm/transports/context-overflow-error.js
1508
1709
  var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
1509
1710
  /prompt is too long/i,
@@ -1687,9 +1888,13 @@ function serverBackoffSpentMs(resolvedMs, ladderMs) {
1687
1888
  var MAX_RETRIES = 5;
1688
1889
  function postWithRetry(options) {
1689
1890
  return __awaiter(this, void 0, void 0, function* () {
1690
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1891
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1691
1892
  const { url, headers, body, credentials, vendorLabel, retryableStatuses, timeout, stallTimeout, backoffBaseMs, signal } = options;
1692
1893
  const vendor = vendorOfTransportLabel(vendorLabel);
1894
+ const serviceRefusal = (code, status, detail) => {
1895
+ logger.error(`${vendorLabel}Transport: the AI service refused the request (${status} ${code})${detail ? `: ${detail}` : ""}`);
1896
+ return new AIServiceError(vendorLabel, code, status, detail);
1897
+ };
1693
1898
  let serverBackoffSpent = 0;
1694
1899
  const backoff = (attempt, serverMs) => {
1695
1900
  const ladderMs = backoffBaseMs * Math.pow(2, attempt);
@@ -1747,6 +1952,17 @@ function postWithRetry(options) {
1747
1952
  if (isBudgetRejection(response.status, codeOf(parsed))) {
1748
1953
  throw budgetExhaustedFrom(vendorLabel, parsed, errText || void 0);
1749
1954
  }
1955
+ const serviceCode = aiServiceErrorCodeOf(codeOf(parsed));
1956
+ if (serviceCode && serviceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1957
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1958
+ }
1959
+ const accessRefusal = aiServiceAccessRefusalOf(response.status, parsed, errText);
1960
+ if (accessRefusal) {
1961
+ throw serviceRefusal(accessRefusal, response.status, (_e = routerRefusalDetailOf(parsed)) !== null && _e !== void 0 ? _e : errText || void 0);
1962
+ }
1963
+ if (isUncodedTooLarge(response.status, parsed)) {
1964
+ throw serviceRefusal(AI_SERVICE_ERROR_CODES.REQUEST_TOO_LARGE, response.status, errText || void 0);
1965
+ }
1750
1966
  const refusedRetry = shouldNotRetry(response.headers);
1751
1967
  if (retryableStatuses.includes(response.status) && !refusedRetry && attempt < MAX_RETRIES) {
1752
1968
  logger.warn(`${vendorLabel}Transport: retryable status ${response.status}, retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
@@ -1754,15 +1970,18 @@ function postWithRetry(options) {
1754
1970
  yield backoff(attempt, retryAfterMs(response.headers) || retryInfoMs(parsed));
1755
1971
  continue;
1756
1972
  }
1973
+ if (serviceCode) {
1974
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1975
+ }
1757
1976
  throw new Error(`${vendorLabel} request error ${response.status}: ${errText}`);
1758
1977
  }
1759
- 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) {
1978
+ 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) {
1760
1979
  rearmStallTimer();
1761
1980
  const frame = yield readFramedBody(response.body, rearmStallTimer, vendorLabel, stallTimeout);
1762
1981
  if (frame.t === "ok")
1763
1982
  return frame.body;
1764
1983
  if (frame.code === "UPSTREAM_STALLED") {
1765
- throw new DOMException(`${vendorLabel} request stalled: ${(_g = frame.error) !== null && _g !== void 0 ? _g : "no upstream data"}`, "TimeoutError");
1984
+ throw new DOMException(`${vendorLabel} request stalled: ${(_h = frame.error) !== null && _h !== void 0 ? _h : "no upstream data"}`, "TimeoutError");
1766
1985
  }
1767
1986
  const framedRefusal = providerRefusalOf(vendor, frame.code, frame);
1768
1987
  if (framedRefusal) {
@@ -1770,18 +1989,25 @@ function postWithRetry(options) {
1770
1989
  }
1771
1990
  const framedOverflow = contextOverflowOf(vendor, frame.status, frame);
1772
1991
  if (framedOverflow) {
1773
- throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_h = framedOverflow.message) !== null && _h !== void 0 ? _h : frame.error);
1992
+ throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_j = framedOverflow.message) !== null && _j !== void 0 ? _j : frame.error);
1774
1993
  }
1775
1994
  if (isBudgetRejection(frame.status, frame.code)) {
1776
1995
  throw budgetExhaustedFrom(vendorLabel, frame);
1777
1996
  }
1997
+ const framedServiceCode = aiServiceErrorCodeOf(frame.code);
1998
+ if (framedServiceCode && framedServiceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1999
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
2000
+ }
1778
2001
  if (retryableStatuses.includes(frame.status) && attempt < MAX_RETRIES) {
1779
2002
  logger.warn(`${vendorLabel}Transport: retryable status ${frame.status} (err frame), retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
1780
2003
  clearTimeout(timeoutId);
1781
2004
  yield backoff(attempt, retryInfoMs(frame));
1782
2005
  continue;
1783
2006
  }
1784
- throw new Error(`${vendorLabel} request error ${frame.status}: ${(_j = frame.error) !== null && _j !== void 0 ? _j : JSON.stringify(frame.details)}`);
2007
+ if (framedServiceCode) {
2008
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
2009
+ }
2010
+ throw new Error(`${vendorLabel} request error ${frame.status}: ${(_k = frame.error) !== null && _k !== void 0 ? _k : JSON.stringify(frame.details)}`);
1785
2011
  }
1786
2012
  return yield response.json();
1787
2013
  } catch (e) {
@@ -3798,80 +4024,6 @@ function clearSession(key) {
3798
4024
  registry.delete(key);
3799
4025
  }
3800
4026
 
3801
- // src/utils/logger.ts
3802
- var logger2 = createLogger("ai-assistant");
3803
-
3804
- // src/suggestions/generate-suggestions.ts
3805
- var HISTORY_WINDOW = 8;
3806
- function capabilities(ctx, allAgentInfo) {
3807
- let agentContext = "";
3808
- let toolContext = "";
3809
- if (allAgentInfo?.length) {
3810
- const agentDescriptions = allAgentInfo.map((agent) => {
3811
- const tools = agent.tools.map((t) => t.name).join(", ");
3812
- return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
3813
- }).join("\n");
3814
- agentContext = `The assistant has the following capabilities:
3815
- ${agentDescriptions}`;
3816
- const allToolNames = [
3817
- ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
3818
- ].join(", ");
3819
- toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
3820
- } else if (ctx.activeAgentName) {
3821
- const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
3822
- agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
3823
- toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
3824
- }
3825
- return agentContext || toolContext ? `
3826
-
3827
- <capabilities>
3828
- ${[agentContext, toolContext].filter(Boolean).join(
3829
- "\n"
3830
- )}
3831
- </capabilities>
3832
- Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
3833
- }
3834
- var OUTPUT_FORMAT = (count) => `
3835
-
3836
- Output format (strict):
3837
- - Exactly ${count} lines.
3838
- - One suggestion per line.
3839
- - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
3840
- - No preamble, headings, summary, or commentary before or after the list.`;
3841
- 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.";
3842
- function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
3843
- const capabilitiesBlock = capabilities(ctx, allAgentInfo);
3844
- const guidanceBlock = prompt2 ? `
3845
-
3846
- Additional guidance: "${prompt2}"` : "";
3847
- if (history.length === 0) {
3848
- 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);
3849
- }
3850
- const conversationContext = history.filter(
3851
- (m) => (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
3852
- ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
3853
- return `<conversation_history>
3854
- ${conversationContext}
3855
- </conversation_history>
3856
-
3857
- 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);
3858
- }
3859
- function parseSuggestions(text, count) {
3860
- 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);
3861
- }
3862
- async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
3863
- const defaultProvider = ctx.registry.default();
3864
- if (!defaultProvider.prompt) {
3865
- logger2.warn("ChatDriver: default AI provider does not implement prompt()");
3866
- return [];
3867
- }
3868
- const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
3869
- const text = await defaultProvider.prompt(userMessage, {
3870
- systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
3871
- });
3872
- return parseSuggestions(text, count);
3873
- }
3874
-
3875
4027
  // src/utils/context-tokens.ts
3876
4028
  var APPROX_CHARS_PER_TOKEN = 4;
3877
4029
  var IMAGE_TOKEN_ESTIMATE = 1600;
@@ -4005,6 +4157,80 @@ function projectCompaction(history, cut, summaryTokens = COMPACTION_SUMMARY_TOKE
4005
4157
  };
4006
4158
  }
4007
4159
 
4160
+ // src/utils/logger.ts
4161
+ var logger2 = createLogger("ai-assistant");
4162
+
4163
+ // src/suggestions/generate-suggestions.ts
4164
+ var HISTORY_WINDOW = 8;
4165
+ function capabilities(ctx, allAgentInfo) {
4166
+ let agentContext = "";
4167
+ let toolContext = "";
4168
+ if (allAgentInfo?.length) {
4169
+ const agentDescriptions = allAgentInfo.map((agent) => {
4170
+ const tools = agent.tools.map((t) => t.name).join(", ");
4171
+ return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
4172
+ }).join("\n");
4173
+ agentContext = `The assistant has the following capabilities:
4174
+ ${agentDescriptions}`;
4175
+ const allToolNames = [
4176
+ ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
4177
+ ].join(", ");
4178
+ toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
4179
+ } else if (ctx.activeAgentName) {
4180
+ const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
4181
+ agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
4182
+ toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
4183
+ }
4184
+ return agentContext || toolContext ? `
4185
+
4186
+ <capabilities>
4187
+ ${[agentContext, toolContext].filter(Boolean).join(
4188
+ "\n"
4189
+ )}
4190
+ </capabilities>
4191
+ Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
4192
+ }
4193
+ var OUTPUT_FORMAT = (count) => `
4194
+
4195
+ Output format (strict):
4196
+ - Exactly ${count} lines.
4197
+ - One suggestion per line.
4198
+ - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
4199
+ - No preamble, headings, summary, or commentary before or after the list.`;
4200
+ 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.";
4201
+ function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
4202
+ const capabilitiesBlock = capabilities(ctx, allAgentInfo);
4203
+ const guidanceBlock = prompt2 ? `
4204
+
4205
+ Additional guidance: "${prompt2}"` : "";
4206
+ if (history.length === 0) {
4207
+ 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);
4208
+ }
4209
+ const conversationContext = history.filter(
4210
+ (m) => reachesProvider(m) && (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
4211
+ ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
4212
+ return `<conversation_history>
4213
+ ${conversationContext}
4214
+ </conversation_history>
4215
+
4216
+ 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);
4217
+ }
4218
+ function parseSuggestions(text, count) {
4219
+ 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);
4220
+ }
4221
+ async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
4222
+ const defaultProvider = ctx.registry.default();
4223
+ if (!defaultProvider.prompt) {
4224
+ logger2.warn("ChatDriver: default AI provider does not implement prompt()");
4225
+ return [];
4226
+ }
4227
+ const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
4228
+ const text = await defaultProvider.prompt(userMessage, {
4229
+ systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
4230
+ });
4231
+ return parseSuggestions(text, count);
4232
+ }
4233
+
4008
4234
  // src/utils/condense-history.ts
4009
4235
  var CONDENSE_MIN_CHARS = 1e3;
4010
4236
  var CONDENSED_ARGS_KEY = "condensed";
@@ -4393,7 +4619,7 @@ function renderMessageForSummary(m) {
4393
4619
  }
4394
4620
  }
4395
4621
  function buildCompactionSummaryPrompt(toCompact) {
4396
- const transcript = toCompact.map(renderMessageForSummary).filter(Boolean).join("\n");
4622
+ const transcript = toCompact.filter((m) => !m.excludeFromProvider).map(renderMessageForSummary).filter(Boolean).join("\n");
4397
4623
  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.";
4398
4624
  const userMessage = `<conversation_history>
4399
4625
  ${transcript}
@@ -4911,6 +5137,10 @@ function createInteractionContext(interactionId) {
4911
5137
  }
4912
5138
 
4913
5139
  // src/components/chat-driver/interaction-controller.ts
5140
+ var STOPPED = {
5141
+ status: "timeout",
5142
+ message: "The turn was stopped before this was answered."
5143
+ };
4914
5144
  var InteractionController = class {
4915
5145
  constructor(deps) {
4916
5146
  this.deps = deps;
@@ -4983,6 +5213,19 @@ var InteractionController = class {
4983
5213
  ...presentation ? { presentation } : {}
4984
5214
  }
4985
5215
  });
5216
+ const signal = options?.signal;
5217
+ if (signal) {
5218
+ const onAbort = () => this.resolve(interactionId, STOPPED);
5219
+ if (signal.aborted) {
5220
+ onAbort();
5221
+ } else {
5222
+ signal.addEventListener("abort", onAbort, { once: true });
5223
+ const pending = this.pending.get(interactionId);
5224
+ if (pending) {
5225
+ pending.unlinkSignal = () => signal.removeEventListener("abort", onAbort);
5226
+ }
5227
+ }
5228
+ }
4986
5229
  });
4987
5230
  }
4988
5231
  /**
@@ -4996,6 +5239,7 @@ var InteractionController = class {
4996
5239
  return;
4997
5240
  }
4998
5241
  if (interaction.timeoutHandle) clearTimeout(interaction.timeoutHandle);
5242
+ interaction.unlinkSignal?.();
4999
5243
  this.deps.foldDiagnostics(
5000
5244
  interactionId,
5001
5245
  result?.diagnostics
@@ -5156,6 +5400,13 @@ var TURN_FAILURE_EXITS = {
5156
5400
  // Overridden per wall by `ChatDriver.budgetExhaustedBubble`, which upgrades this with
5157
5401
  // "switch to another AI" when a second vendor is reachable.
5158
5402
  copy: DEFAULT_BUDGET_EXHAUSTED_MESSAGE
5403
+ },
5404
+ aiServiceError: {
5405
+ subReason: "ai_service_error",
5406
+ resultReason: "ai-service-error",
5407
+ // Replaced per code by `ChatDriver.aiServiceErrorBubble`; this is only what a parent says when
5408
+ // a child's failure arrives without its code.
5409
+ copy: DEFAULT_AI_SERVICE_ERROR_MESSAGES.BAD_REQUEST
5159
5410
  }
5160
5411
  // `satisfies`, not an annotation: an annotation would widen `resultReason` to
5161
5412
  // `TurnFailureReason` and cost the literal types that let `turn-failures.test.ts` pin the
@@ -5326,6 +5577,19 @@ var TurnRecorder = class {
5326
5577
  };
5327
5578
 
5328
5579
  // src/components/chat-driver/chat-driver.ts
5580
+ var REQUEST_SCOPED_REFUSALS = /* @__PURE__ */ new Set([
5581
+ "REQUEST_TOO_LARGE",
5582
+ "BAD_REQUEST",
5583
+ "FALLBACKS_NOT_SUPPORTED"
5584
+ ]);
5585
+ var SERVICE_WIDE_REFUSALS = /* @__PURE__ */ new Set([
5586
+ "NO_API_KEY",
5587
+ "BAD_API_KEY",
5588
+ "KEY_UNREADABLE",
5589
+ "SIGNED_OUT",
5590
+ "ACCESS_DENIED",
5591
+ "VENDOR_UNREACHABLE"
5592
+ ]);
5329
5593
  var toolResultImages = (result) => {
5330
5594
  if (!result || typeof result !== "object") return void 0;
5331
5595
  const candidate = result.attachments;
@@ -5354,6 +5618,15 @@ var budgetDetailOf = (e) => {
5354
5618
  ...e.otherVendorAvailable != null ? { otherVendorAvailable: e.otherVendorAvailable } : {}
5355
5619
  };
5356
5620
  };
5621
+ function inFlightToolCallsAt(history) {
5622
+ for (let i = history.length - 1; i >= 0; i -= 1) {
5623
+ const message = history[i];
5624
+ if (message.role !== "assistant" || !message.toolCalls?.length) continue;
5625
+ const answered = new Set(history.slice(i + 1).map((later) => later.toolResult?.toolCallId));
5626
+ return message.toolCalls.some((call) => !answered.has(call.id)) ? i : history.length;
5627
+ }
5628
+ return history.length;
5629
+ }
5357
5630
  var ChatDriver = class _ChatDriver extends EventTarget {
5358
5631
  constructor(providerRegistry, config = {}) {
5359
5632
  super();
@@ -5499,6 +5772,17 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5499
5772
  this.turnController = new AbortController();
5500
5773
  /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
5501
5774
  this.turnCancelled = false;
5775
+ /**
5776
+ * The scope tool handlers see as `turnSignal`: one USER MESSAGE. Minted by `sendMessage`, so a
5777
+ * handoff's `continueFromHistory` — a new `turnController`, but the same message — keeps it,
5778
+ * and a sub-agent inherits it (`inheritedTurnSignal`). Aborted by `cancel()` and by a dispose.
5779
+ * `continueFromHistory` mints one only when the message it would continue was stopped.
5780
+ *
5781
+ * Kept apart from `turnController`, which is per REQUEST and restarts on every continuation: a
5782
+ * handler that remembers something "for the rest of the turn" (the write tools' deny lock) keyed
5783
+ * on that one was reset by every handoff inside a single message.
5784
+ */
5785
+ this.messageController = new AbortController();
5502
5786
  /**
5503
5787
  * Caches validated provider lookups per name within the current agent. Cleared
5504
5788
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -5535,6 +5819,20 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5535
5819
  * children costing N doomed calls plus a doomed parent one.
5536
5820
  */
5537
5821
  this.providerRefusedThisTurn = false;
5822
+ /**
5823
+ * A sub-agent was refused by the AI service this turn in a way that stops this driver too
5824
+ * (GENC-1611): a service-wide code, from the vendor this driver calls. Sub-agent path only, like
5825
+ * `providerRefusedThisTurn`; this driver's own refusal returns straight out of the catch.
5826
+ */
5827
+ this.aiServiceErrorThisTurn = false;
5828
+ /** Codes a child's refusal was already shown for during this user message. */
5829
+ this.aiServiceNoticesShown = /* @__PURE__ */ new Set();
5830
+ /**
5831
+ * Notices waiting for the tool batch to end. Written mid-batch they would sit between the
5832
+ * assistant's tool calls and their results, where a later sub-agent's primer would pick up the
5833
+ * unanswered calls.
5834
+ */
5835
+ this.aiServiceNoticesQueued = [];
5538
5836
  /**
5539
5837
  * Set the moment a budget wall is observed anywhere in this turn — this
5540
5838
  * driver's own 402, or a sub-agent's (which surfaces here only as a
@@ -5564,7 +5862,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5564
5862
  deferAgentRelease = false,
5565
5863
  activityBus = NOOP_ACTIVITY_BUS,
5566
5864
  budgetExhaustedMessage,
5567
- providerRefusedMessage
5865
+ providerRefusedMessage,
5866
+ aiServiceErrorMessages
5568
5867
  } = config;
5569
5868
  this.maxToolIterations = maxToolIterations;
5570
5869
  this.condenseBatchCalls = condenseBatchCalls;
@@ -5573,6 +5872,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5573
5872
  this.activityBus = activityBus;
5574
5873
  this.budgetExhaustedMessageOverride = budgetExhaustedMessage;
5575
5874
  this.providerRefusedMessageOverride = providerRefusedMessage;
5875
+ this.aiServiceErrorMessagesOverride = aiServiceErrorMessages;
5576
5876
  if (typeof toolHandlers === "function") {
5577
5877
  this.toolHandlersFactory = toolHandlers;
5578
5878
  this.toolHandlers = {};
@@ -5637,14 +5937,43 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5637
5937
  /**
5638
5938
  * Stop the current turn (user "stop" button). Aborts the in-flight provider
5639
5939
  * request immediately; if a tool is mid-execution it runs to completion and
5640
- * the loop bails at the next boundary (tools are atomic). No-op when idle.
5641
- * The driver stays usable for the next message.
5940
+ * the loop bails at the next boundary (tools are atomic). When idle it only ends
5941
+ * the message (see below) and appends nothing. The driver stays usable for the
5942
+ * next message.
5642
5943
  */
5643
5944
  cancel() {
5945
+ this.messageController.abort(new DOMException("Cancelled by user", "AbortError"));
5644
5946
  if (!this.busy) return;
5645
5947
  this.turnCancelled = true;
5646
5948
  this.turnController.abort(new DOMException("Cancelled by user", "AbortError"));
5647
5949
  }
5950
+ /**
5951
+ * Start a fresh per-MESSAGE scope for tool handlers (see `messageController`). Chained to
5952
+ * `lifecycleController` so a dispose aborts it; the link lives until the next message, because
5953
+ * a handoff continues this one.
5954
+ */
5955
+ beginMessage() {
5956
+ this.unlinkLifecycleFromMessage?.();
5957
+ this.messageController = new AbortController();
5958
+ const lifecycle = this.lifecycleController.signal;
5959
+ if (lifecycle.aborted) {
5960
+ this.messageController.abort(lifecycle.reason);
5961
+ this.unlinkLifecycleFromMessage = void 0;
5962
+ return;
5963
+ }
5964
+ const onDispose = () => this.messageController.abort(lifecycle.reason);
5965
+ lifecycle.addEventListener("abort", onDispose, { once: true });
5966
+ this.unlinkLifecycleFromMessage = () => lifecycle.removeEventListener("abort", onDispose);
5967
+ }
5968
+ /**
5969
+ * Makes this (sub-agent) driver's handlers see the parent message's `turnSignal` instead of one
5970
+ * of their own: a delegation is part of the message that made it.
5971
+ *
5972
+ * @internal
5973
+ */
5974
+ inheritTurnSignal(signal) {
5975
+ this.inheritedTurnSignal = signal;
5976
+ }
5648
5977
  /**
5649
5978
  * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
5650
5979
  * new `turnController` so a dispose mid-turn also aborts the request.
@@ -5702,8 +6031,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5702
6031
  */
5703
6032
  endTurnWithFailure(exit, overrides) {
5704
6033
  if (this.isSubAgent) {
5705
- this.failSubAgent(exit.subReason, overrides?.budget, overrides?.providerRefused);
5706
- } else {
6034
+ this.failSubAgent(
6035
+ exit.subReason,
6036
+ overrides?.budget,
6037
+ overrides?.providerRefused,
6038
+ overrides?.aiServiceError
6039
+ );
6040
+ } else if (!overrides?.silent) {
5707
6041
  this.appendDriverNotice(overrides?.copy ?? exit.copy);
5708
6042
  }
5709
6043
  return turnDone(exit.resultReason, overrides?.budget, overrides?.providerRefused);
@@ -5740,6 +6074,19 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5740
6074
  const subject = wall?.vendorLabel ? `${wall.vendorLabel}'s AI usage limit` : "your AI usage limit";
5741
6075
  return `You've reached ${subject}. Switch to another AI provider in Settings to keep going, or contact your administrator to raise it.`;
5742
6076
  }
6077
+ /**
6078
+ * Record a message the user sent and then stopped before any turn took it: during an
6079
+ * orchestrator's first classify, or its first agent's install. Only an optimistic
6080
+ * `history-updated` had shown it, so it vanished on the next update, and from a reload. Appended
6081
+ * here with the "Stopped." marker a stopped turn leaves, as `reportBudgetExhausted` appends a
6082
+ * message the budget wall kept from its turn.
6083
+ *
6084
+ * @internal
6085
+ */
6086
+ reportStoppedBeforeTurn(userMessage) {
6087
+ this.appendToHistory(userMessage);
6088
+ this.appendToHistory({ role: "system-event", content: "Stopped." });
6089
+ }
5743
6090
  reportBudgetExhausted(e, pendingUserMessage) {
5744
6091
  if (pendingUserMessage) this.appendToHistory(pendingUserMessage);
5745
6092
  this.budgetExhaustedThisTurn = true;
@@ -5772,6 +6119,158 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5772
6119
  providerRefusedBubble() {
5773
6120
  return this.providerRefusedMessageOverride ?? TURN_FAILURE_EXITS.providerRefused.copy;
5774
6121
  }
6122
+ /**
6123
+ * A terminal AI service error hit **outside** the tool loop — `OrchestratingDriver`'s classification
6124
+ * phase (GENC-1611). The same log line, debug-log entry, sentence and result as the in-loop branch.
6125
+ *
6126
+ * @param pendingUserMessage - the user's message when it has NOT been appended yet, for the reason
6127
+ * `reportBudgetExhausted` gives.
6128
+ */
6129
+ reportAIServiceError(e, pendingUserMessage) {
6130
+ if (pendingUserMessage) {
6131
+ this.aiServiceNoticesShown.clear();
6132
+ this.aiServiceNoticesQueued = [];
6133
+ this.appendToHistory(pendingUserMessage);
6134
+ }
6135
+ return this.endTurnWithAIServiceError(e);
6136
+ }
6137
+ /**
6138
+ * The sentence for an AI service error code (GENC-1611): the host's override, else the default.
6139
+ * Never the service's own text, which goes to the console only.
6140
+ */
6141
+ aiServiceErrorBubble(code) {
6142
+ if (!code) return TURN_FAILURE_EXITS.aiServiceError.copy;
6143
+ const override = this.aiServiceErrorMessagesOverride?.[code];
6144
+ return override?.trim() ? override : DEFAULT_AI_SERVICE_ERROR_MESSAGES[code];
6145
+ }
6146
+ /**
6147
+ * Shows a sub-agent's AI-service refusal that the turn went on without, once per code in a user
6148
+ * message: the user's sentence with the host's overrides, never the service's text. A sub-agent
6149
+ * passes it up to the driver the user sees.
6150
+ */
6151
+ noticeAIServiceRefusal(code) {
6152
+ if (REQUEST_SCOPED_REFUSALS.has(code)) return;
6153
+ if (this.hostAIServiceNotice) {
6154
+ this.hostAIServiceNotice(code);
6155
+ return;
6156
+ }
6157
+ if (!this.busy) return;
6158
+ if (this.aiServiceNoticesShown.has(code) || this.aiServiceNoticesQueued.includes(code)) return;
6159
+ this.aiServiceNoticesQueued.push(code);
6160
+ }
6161
+ /**
6162
+ * Writes the notices queued during a tool batch, once its results are in the history, or before
6163
+ * the failure when the batch threw. A code counts as shown only once written.
6164
+ */
6165
+ flushAIServiceNotices() {
6166
+ const codes = this.aiServiceNoticesQueued;
6167
+ this.aiServiceNoticesQueued = [];
6168
+ for (const code of codes) {
6169
+ this.aiServiceNoticesShown.add(code);
6170
+ this.appendDriverNotice(this.aiServiceErrorBubble(code));
6171
+ }
6172
+ }
6173
+ /** Ends the turn on an AI service error: logged with the service's text, shown without it. */
6174
+ endTurnWithAIServiceError(e) {
6175
+ logger2.error("ChatDriver: the AI service refused the request", e, e.detail ?? "");
6176
+ recordTurnError(this.sessionKey, "ai-service-error", {
6177
+ agent: this.activeAgentName,
6178
+ provider: this.lastResolvedProviderName,
6179
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider,
6180
+ code: e.code,
6181
+ status: e.status,
6182
+ isSubAgent: this.isSubAgent
6183
+ });
6184
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6185
+ copy: this.aiServiceErrorBubble(e.code),
6186
+ aiServiceError: {
6187
+ code: e.code,
6188
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider
6189
+ },
6190
+ silent: this.aiServiceSentenceShown(e.code)
6191
+ });
6192
+ }
6193
+ /**
6194
+ * Whether this user message already showed the sentence for `code`, so a turn-ending failure
6195
+ * does not show it twice. Marks it shown otherwise. Only the driver the user sees keeps count.
6196
+ */
6197
+ aiServiceSentenceShown(code) {
6198
+ if (this.isSubAgent || !code) return false;
6199
+ if (this.aiServiceNoticesShown.has(code)) return true;
6200
+ this.aiServiceNoticesShown.add(code);
6201
+ return false;
6202
+ }
6203
+ /**
6204
+ * Whether a sub-agent hit a wall this turn that stops this driver too. A handoff goes on past an
6205
+ * AI-service wall: the next agent may use another vendor, and if it uses this one its own call
6206
+ * meets the wall and says so.
6207
+ */
6208
+ subAgentWallThisTurn(handingOff = false) {
6209
+ return this.providerRefusedThisTurn || this.budgetExhaustedThisTurn || this.aiServiceErrorThisTurn && !handingOff;
6210
+ }
6211
+ /**
6212
+ * Ends the turn when a sub-agent hit a wall this turn that stops this driver too: the provider
6213
+ * refusing the account, the AI service (GENC-1611), or the budget. Checked before each model call,
6214
+ * and again right after a tool batch, before a handoff or the iteration cap can report the turn as
6215
+ * something else.
6216
+ */
6217
+ endTurnOnSubAgentWall() {
6218
+ if (!this.subAgentWallThisTurn()) return void 0;
6219
+ this.subAgentCompletion = void 0;
6220
+ if (this.providerRefusedThisTurn) {
6221
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6222
+ recordTurnError(this.sessionKey, "provider-refused", {
6223
+ agent: this.activeAgentName,
6224
+ provider: this.lastResolvedProviderName,
6225
+ kind: this.providerRefusedDetail?.kind,
6226
+ via: "sub-agent",
6227
+ isSubAgent: this.isSubAgent
6228
+ });
6229
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6230
+ copy: this.providerRefusedBubble(),
6231
+ providerRefused: this.providerRefusedDetail
6232
+ });
6233
+ }
6234
+ if (this.aiServiceErrorThisTurn) {
6235
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent was refused by the AI service");
6236
+ recordTurnError(this.sessionKey, "ai-service-error", {
6237
+ agent: this.activeAgentName,
6238
+ provider: this.lastResolvedProviderName,
6239
+ code: this.aiServiceWall?.code,
6240
+ via: "sub-agent",
6241
+ isSubAgent: this.isSubAgent
6242
+ });
6243
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6244
+ copy: this.aiServiceErrorBubble(this.aiServiceWall?.code),
6245
+ aiServiceError: this.aiServiceWall,
6246
+ silent: this.aiServiceSentenceShown(this.aiServiceWall?.code)
6247
+ });
6248
+ }
6249
+ if (this.budgetExhaustedThisTurn) {
6250
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6251
+ recordTurnError(this.sessionKey, "budget-exhausted", {
6252
+ agent: this.activeAgentName,
6253
+ provider: this.lastResolvedProviderName,
6254
+ // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6255
+ // path the wall is definitionally the child's, and on a mixed registry
6256
+ // `lastResolvedProvider` is this driver's own vendor — the one known
6257
+ // NOT to have refused. An unattributable child wall must degrade to
6258
+ // the vendor-agnostic block (which `latchBlockedFrom` handles
6259
+ // fail-safe), never to a vendor that is known to be wrong: naming the
6260
+ // parent's vendor here walled BOTH — the child's via its own
6261
+ // tool-loop-end, the parent's via this event — and derived `blocked`
6262
+ // over headroom that still existed.
6263
+ vendor: this.budgetWallDetail?.vendor,
6264
+ via: "sub-agent",
6265
+ isSubAgent: this.isSubAgent
6266
+ });
6267
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6268
+ copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6269
+ budget: this.budgetWallDetail
6270
+ });
6271
+ }
6272
+ return void 0;
6273
+ }
5775
6274
  /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
5776
6275
  static failureReasonOf(result) {
5777
6276
  return result.reason === "done" ? result.failureReason : void 0;
@@ -6052,12 +6551,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6052
6551
  * under a separate session key, so recording here would orphan the event off
6053
6552
  * the user-visible debug-log timeline.)
6054
6553
  */
6055
- failSubAgent(reason, budget, providerRefused) {
6554
+ failSubAgent(reason, budget, providerRefused, aiServiceError) {
6056
6555
  if (!this.isSubAgent || this.subAgentFailure) return;
6057
6556
  this.subAgentFailure = {
6058
6557
  reason,
6059
6558
  ...budget ? { budget } : {},
6060
- ...providerRefused ? { providerRefused } : {}
6559
+ ...providerRefused ? { providerRefused } : {},
6560
+ ...aiServiceError ? { aiServiceError } : {}
6061
6561
  };
6062
6562
  }
6063
6563
  /**
@@ -6488,6 +6988,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6488
6988
  if (this.busy || !userInput.trim() && !attachments?.length) return { reason: "done" };
6489
6989
  this.busy = true;
6490
6990
  this.beginTurn();
6991
+ this.beginMessage();
6491
6992
  this.turnSeq += 1;
6492
6993
  this.subAgentCompletion = void 0;
6493
6994
  this.subAgentFailure = void 0;
@@ -6497,6 +6998,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6497
6998
  this.budgetWallViaSubAgent = false;
6498
6999
  this.providerRefusedThisTurn = false;
6499
7000
  this.providerRefusedDetail = void 0;
7001
+ this.aiServiceErrorThisTurn = false;
7002
+ this.aiServiceWall = void 0;
7003
+ this.aiServiceNoticesShown.clear();
7004
+ this.aiServiceNoticesQueued = [];
6500
7005
  this.appendToHistory({ role: "user", content: userInput, attachments });
6501
7006
  this.turnStartedAt = Date.now();
6502
7007
  recordMetaEvent(this.sessionKey, "turn.start", {
@@ -6517,6 +7022,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6517
7022
  name: e instanceof Error ? e.name : void 0,
6518
7023
  message: e instanceof Error ? e.message : String(e)
6519
7024
  });
7025
+ this.flushAIServiceNotices();
6520
7026
  this.appendDriverNotice(
6521
7027
  "Sorry, something went wrong on my end. Please try again in a moment."
6522
7028
  );
@@ -6561,6 +7067,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6561
7067
  buildHandlerContext(activeToolCallId, traceCapture) {
6562
7068
  return {
6563
7069
  requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options),
7070
+ // The MESSAGE's scope: one object per `sendMessage`, kept across a handoff's continuation
7071
+ // and handed to a sub-agent, and aborted by `cancel()` as well as a dispose. Not the
7072
+ // per-request `turnController`, which every continuation replaces.
7073
+ turnSignal: this.inheritedTurnSignal ?? this.messageController.signal,
6564
7074
  ...this.subAgentsMap.size > 0 && {
6565
7075
  requestSubAgent: (name, options) => this.invokeSubAgent(name, options).then(({ outcome, trace }) => {
6566
7076
  if (traceCapture && trace) traceCapture.traces.push(trace);
@@ -6637,8 +7147,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6637
7147
  );
6638
7148
  }
6639
7149
  const { task, historyCap, context, timeoutMs } = options ?? {};
6640
- const lastMsg = this.history[this.history.length - 1];
6641
- const baseHistory = lastMsg?.role === "assistant" && lastMsg.toolCalls?.length ? this.history.slice(0, -1) : this.history;
7150
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
6642
7151
  const snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
6643
7152
  const contextMessages = context ? [{ role: "user", content: `[Sub-agent context]: ${JSON.stringify(context)}` }] : [];
6644
7153
  const effectivePrimer = [
@@ -6655,6 +7164,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6655
7164
  activityBus: this.activityBus
6656
7165
  });
6657
7166
  child.markAsSubAgent();
7167
+ child.inheritTurnSignal(this.inheritedTurnSignal ?? this.messageController.signal);
6658
7168
  child.setContextGuard(this.contextGuard);
6659
7169
  const disposeChild = () => child.dispose();
6660
7170
  if (this.lifecycleController.signal.aborted) {
@@ -6666,6 +7176,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6666
7176
  child.setHostInteractionRequester(
6667
7177
  (componentName, data, opts) => this.requestInteraction(componentName, data, opts)
6668
7178
  );
7179
+ child.hostAIServiceNotice = (code) => this.noticeAIServiceRefusal(code);
6669
7180
  const forwardTrace = (e) => {
6670
7181
  this.dispatchEvent(
6671
7182
  new CustomEvent("sub-agent-history-updated", {
@@ -6746,6 +7257,28 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6746
7257
  this.providerRefusedThisTurn = true;
6747
7258
  this.providerRefusedDetail ??= failure?.providerRefused;
6748
7259
  }
7260
+ const wall = failure?.aiServiceError;
7261
+ if (reason === "ai_service_error" && wall && SERVICE_WIDE_REFUSALS.has(wall.code) && wall.vendor !== void 0 && wall.vendor === this.lastResolvedProvider) {
7262
+ this.aiServiceErrorThisTurn = true;
7263
+ this.aiServiceWall ??= wall;
7264
+ } else if (reason === "ai_service_error" && wall) {
7265
+ this.noticeAIServiceRefusal(wall.code);
7266
+ }
7267
+ if (reason === "ai_service_error") {
7268
+ if (wall) {
7269
+ return {
7270
+ outcome: {
7271
+ ok: false,
7272
+ reason,
7273
+ code: wall.code,
7274
+ terminal: isTerminalAIServiceRefusal(wall.code)
7275
+ },
7276
+ trace
7277
+ };
7278
+ }
7279
+ logger2.error(`ChatDriver: sub-agent "${name}" was refused by the AI service with no code`);
7280
+ return { outcome: { ok: false, reason: "max_iterations" }, trace };
7281
+ }
6749
7282
  return { outcome: { ok: false, reason }, trace };
6750
7283
  }
6751
7284
  /**
@@ -6755,6 +7288,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6755
7288
  async continueFromHistory(transientPrimer) {
6756
7289
  if (this.busy) return { reason: "done" };
6757
7290
  this.busy = true;
7291
+ if (this.messageController.signal.aborted) this.beginMessage();
6758
7292
  this.beginTurn();
6759
7293
  this.subAgentCompletion = void 0;
6760
7294
  this.subAgentFailure = void 0;
@@ -6763,6 +7297,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6763
7297
  this.budgetWallViaSubAgent = false;
6764
7298
  this.providerRefusedThisTurn = false;
6765
7299
  this.providerRefusedDetail = void 0;
7300
+ this.aiServiceErrorThisTurn = false;
7301
+ this.aiServiceWall = void 0;
6766
7302
  this.turnStartedAt = Date.now();
6767
7303
  recordMetaEvent(this.sessionKey, "turn.start", {
6768
7304
  phase: "continueFromHistory",
@@ -6782,6 +7318,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6782
7318
  name: e instanceof Error ? e.name : void 0,
6783
7319
  message: e instanceof Error ? e.message : String(e)
6784
7320
  });
7321
+ this.flushAIServiceNotices();
6785
7322
  this.appendDriverNotice(
6786
7323
  "Sorry, something went wrong on my end. Please try again in a moment."
6787
7324
  );
@@ -6828,43 +7365,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6828
7365
  if (this.turnController.signal.aborted) {
6829
7366
  return this.completeAbortedTurn();
6830
7367
  }
6831
- if (this.providerRefusedThisTurn) {
6832
- logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6833
- recordTurnError(this.sessionKey, "provider-refused", {
6834
- agent: this.activeAgentName,
6835
- provider: this.lastResolvedProviderName,
6836
- kind: this.providerRefusedDetail?.kind,
6837
- via: "sub-agent",
6838
- isSubAgent: this.isSubAgent
6839
- });
6840
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6841
- copy: this.providerRefusedBubble(),
6842
- providerRefused: this.providerRefusedDetail
6843
- });
6844
- }
6845
- if (this.budgetExhaustedThisTurn) {
6846
- logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6847
- recordTurnError(this.sessionKey, "budget-exhausted", {
6848
- agent: this.activeAgentName,
6849
- provider: this.lastResolvedProviderName,
6850
- // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6851
- // path the wall is definitionally the child's, and on a mixed registry
6852
- // `lastResolvedProvider` is this driver's own vendor — the one known
6853
- // NOT to have refused. An unattributable child wall must degrade to
6854
- // the vendor-agnostic block (which `latchBlockedFrom` handles
6855
- // fail-safe), never to a vendor that is known to be wrong: naming the
6856
- // parent's vendor here walled BOTH — the child's via its own
6857
- // tool-loop-end, the parent's via this event — and derived `blocked`
6858
- // over headroom that still existed.
6859
- vendor: this.budgetWallDetail?.vendor,
6860
- via: "sub-agent",
6861
- isSubAgent: this.isSubAgent
6862
- });
6863
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6864
- copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6865
- budget: this.budgetWallDetail
6866
- });
6867
- }
7368
+ const wall = this.endTurnOnSubAgentWall();
7369
+ if (wall) return wall;
6868
7370
  const promptCtx = {
6869
7371
  agentName: this.activeAgentName ?? "",
6870
7372
  history: this.history,
@@ -7110,6 +7612,9 @@ ${tailBody}
7110
7612
  providerRefused: detail
7111
7613
  });
7112
7614
  }
7615
+ if (e instanceof AIServiceError && e.terminal) {
7616
+ return this.endTurnWithAIServiceError(e);
7617
+ }
7113
7618
  if (e instanceof BudgetExhaustedError) {
7114
7619
  this.budgetExhaustedThisTurn = true;
7115
7620
  this.budgetWallDetail = budgetDetailOf(e);
@@ -7151,6 +7656,7 @@ ${tailBody}
7151
7656
  iterations -= 1;
7152
7657
  continue;
7153
7658
  }
7659
+ if (e instanceof AIServiceError) return this.endTurnWithAIServiceError(e);
7154
7660
  throw e;
7155
7661
  }
7156
7662
  if (response.model === void 0 && this.lastResolvedModel !== void 0) {
@@ -7474,6 +7980,7 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7474
7980
  this.history[tcMsgIdx] = { ...tcMsg, toolCalls: annotatedCalls };
7475
7981
  this.notifyHistoryUpdated();
7476
7982
  }
7983
+ this.flushAIServiceNotices();
7477
7984
  if (hitUnknownToolLimit) {
7478
7985
  logger2.error(
7479
7986
  `ChatDriver: unknown-tool limit (${DEFAULT_MAX_UNKNOWN_TOOL_CALLS}) reached \u2014 stopping`
@@ -7503,6 +8010,15 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7503
8010
  return this.endTurnWithFailure(TURN_FAILURE_EXITS.unknownToolLimit);
7504
8011
  }
7505
8012
  const firstContinuation = systemCalls[0];
8013
+ if (!this.subAgentCompletion && this.subAgentWallThisTurn(!!firstContinuation)) {
8014
+ if (this.turnController.signal.aborted) return this.completeAbortedTurn();
8015
+ const wallAfterBatch = this.endTurnOnSubAgentWall();
8016
+ if (wallAfterBatch) return wallAfterBatch;
8017
+ }
8018
+ if (this.aiServiceErrorThisTurn && this.aiServiceWall) {
8019
+ this.noticeAIServiceRefusal(this.aiServiceWall.code);
8020
+ this.flushAIServiceNotices();
8021
+ }
7506
8022
  if (firstContinuation) {
7507
8023
  const { summary, remaining_task: remainingTask } = firstContinuation.args;
7508
8024
  return { reason: "agent-handoff", summary, remainingTask };
@@ -7672,6 +8188,7 @@ var OrchestratingDriver = class extends EventTarget {
7672
8188
  sessionKey: this.sessionKey,
7673
8189
  activityBus: options.activityBus,
7674
8190
  budgetExhaustedMessage: options.budgetExhaustedMessage,
8191
+ aiServiceErrorMessages: options.aiServiceErrorMessages,
7675
8192
  // This driver releases after the turn so it can fire the host-facing events; see the option.
7676
8193
  deferAgentRelease: true
7677
8194
  });
@@ -7852,15 +8369,16 @@ var OrchestratingDriver = class extends EventTarget {
7852
8369
  try {
7853
8370
  return await this.runOrchestratedTurn(input, attachments);
7854
8371
  } catch (e) {
8372
+ const pendingUserMessage = this.userMessageAppended ? void 0 : {
8373
+ role: "user",
8374
+ content: input,
8375
+ ...attachments ? { attachments } : {}
8376
+ };
7855
8377
  if (e instanceof BudgetExhaustedError) {
7856
- return this.chatDriver.reportBudgetExhausted(
7857
- e,
7858
- this.userMessageAppended ? void 0 : {
7859
- role: "user",
7860
- content: input,
7861
- ...attachments ? { attachments } : {}
7862
- }
7863
- );
8378
+ return this.chatDriver.reportBudgetExhausted(e, pendingUserMessage);
8379
+ }
8380
+ if (e instanceof AIServiceError) {
8381
+ return this.chatDriver.reportAIServiceError(e, pendingUserMessage);
7864
8382
  }
7865
8383
  throw e;
7866
8384
  }
@@ -7893,6 +8411,7 @@ var OrchestratingDriver = class extends EventTarget {
7893
8411
  while (true) {
7894
8412
  if (this.cancelled) break;
7895
8413
  await this.installAgent(currentAgent);
8414
+ if (this.cancelled) break;
7896
8415
  let result;
7897
8416
  if (isHandoff) {
7898
8417
  const contextPrimer = handoffSummary ? [{ role: "user", content: `[Context from previous agent]: ${handoffSummary}` }] : [];
@@ -7917,6 +8436,7 @@ var OrchestratingDriver = class extends EventTarget {
7917
8436
  if (result.reason !== "agent-handoff" || isFallback(currentAgent) || pinned) {
7918
8437
  break;
7919
8438
  }
8439
+ if (this.cancelled) break;
7920
8440
  handoffs += 1;
7921
8441
  if (handoffs > this.maxHandoffs) {
7922
8442
  this.appendInlineMessage(
@@ -7935,6 +8455,13 @@ var OrchestratingDriver = class extends EventTarget {
7935
8455
  routed = await this.classify(remainingTask, updatedHistory, void 0, attempted);
7936
8456
  currentAgent = routed.agent;
7937
8457
  }
8458
+ if (this.cancelled && !this.userMessageAppended) {
8459
+ this.chatDriver.reportStoppedBeforeTurn({
8460
+ role: "user",
8461
+ content: input,
8462
+ ...attachments ? { attachments } : {}
8463
+ });
8464
+ }
7938
8465
  return lastResult?.reason === "done" ? lastResult : { reason: "done" };
7939
8466
  }
7940
8467
  async continueFromHistory(transientPrimer) {
@@ -8192,6 +8719,7 @@ ${recentMessages}` : ""}`;
8192
8719
  break;
8193
8720
  } catch (e) {
8194
8721
  if (e instanceof BudgetExhaustedError) throw e;
8722
+ if (e instanceof AIServiceError && e.terminal) throw e;
8195
8723
  lastError = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
8196
8724
  logger2.warn(`OrchestratingDriver: classifier attempt ${attempt + 1} failed:`, e);
8197
8725
  if (attempt === this.classifierRetries) {
@@ -8633,6 +9161,9 @@ function withFreshMetaSnapshot(stored, fresh) {
8633
9161
  return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
8634
9162
  }
8635
9163
  export {
9164
+ AIServiceError,
9165
+ AI_SERVICE_ACCESS_REFUSALS,
9166
+ AI_SERVICE_ERROR_CODES,
8636
9167
  AI_TIER_IDS,
8637
9168
  AI_TIER_VENDORS,
8638
9169
  ANTHROPIC_CACHE_READ_MULTIPLIER,
@@ -8642,6 +9173,7 @@ export {
8642
9173
  AnthropicProvider,
8643
9174
  AnthropicTransport,
8644
9175
  ChatDriver,
9176
+ DEFAULT_AI_SERVICE_ERROR_MESSAGES,
8645
9177
  DEFAULT_AI_TIERS,
8646
9178
  DEFAULT_PROVIDER_REFUSED_MESSAGE,
8647
9179
  EMPTY_RESPONSE_NUDGE,
@@ -8662,6 +9194,8 @@ export {
8662
9194
  UNROUTABLE_PLACEHOLDER,
8663
9195
  addUsage,
8664
9196
  agenticActivityBus,
9197
+ aiServiceAccessRefusalOf,
9198
+ aiServiceErrorCodeOf,
8665
9199
  anthropicRatesFor,
8666
9200
  anthropicTokenCost,
8667
9201
  assembleDebugLog,
@@ -8675,6 +9209,7 @@ export {
8675
9209
  geminiTokenCost,
8676
9210
  getMetaEvents,
8677
9211
  isObservableAIProviderRegistry,
9212
+ isTerminalAIServiceRefusal,
8678
9213
  messageUsage,
8679
9214
  resolveAITiers,
8680
9215
  restoreMachine,