@genesislcap/ai-assistant 15.40.0 → 15.41.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 +567 -134
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +560 -134
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +1258 -687
  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,
@@ -1579,6 +1586,98 @@ function abortableDelay(ms, signal) {
1579
1586
  });
1580
1587
  }
1581
1588
 
1589
+ // ../../foundation-ai/dist/esm/transports/ai-service-error.js
1590
+ var AI_SERVICE_ERROR_CODES = Object.freeze({
1591
+ /** No API key is configured for the vendor. */
1592
+ NO_API_KEY: "NO_API_KEY",
1593
+ /** The configured key has characters an API key cannot have. */
1594
+ BAD_API_KEY: "BAD_API_KEY",
1595
+ /** An encrypted key could not be decrypted. */
1596
+ KEY_UNREADABLE: "KEY_UNREADABLE",
1597
+ /** The request asked for a model the service does not allow. */
1598
+ MODEL_NOT_ALLOWED: "MODEL_NOT_ALLOWED",
1599
+ /** The service refused the shape of the request. */
1600
+ BAD_REQUEST: "BAD_REQUEST",
1601
+ /** The request named fallback models, which the service does not accept. */
1602
+ FALLBACKS_NOT_SUPPORTED: "FALLBACKS_NOT_SUPPORTED",
1603
+ /** The request body is larger, or nested deeper, than the service accepts. */
1604
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
1605
+ /** The service could not reach the vendor. The only code that is worth retrying. */
1606
+ VENDOR_UNREACHABLE: "VENDOR_UNREACHABLE"
1607
+ });
1608
+ var KNOWN_CODES = new Set(Object.values(AI_SERVICE_ERROR_CODES));
1609
+ function aiServiceErrorCodeOf(code) {
1610
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : void 0;
1611
+ }
1612
+ var AI_SERVICE_ACCESS_REFUSALS = Object.freeze({
1613
+ /** 401: the request had no session. */
1614
+ SIGNED_OUT: "SIGNED_OUT",
1615
+ /** 403: the user lacks the right the endpoint demands. */
1616
+ ACCESS_DENIED: "ACCESS_DENIED"
1617
+ });
1618
+ var UNAUTHORIZED_STATUS = 401;
1619
+ var FORBIDDEN_STATUS = 403;
1620
+ var PAYLOAD_TOO_LARGE_STATUS = 413;
1621
+ var isRouterNack = (payload) => {
1622
+ if (!payload || typeof payload !== "object")
1623
+ return false;
1624
+ const { MESSAGE_TYPE, ERROR } = payload;
1625
+ return MESSAGE_TYPE === "MSG_NACK" || Array.isArray(ERROR);
1626
+ };
1627
+ var hasCode = (payload) => (payload === null || payload === void 0 ? void 0 : payload.code) !== void 0;
1628
+ function aiServiceAccessRefusalOf(status, payload, bodyText) {
1629
+ if (status !== UNAUTHORIZED_STATUS && status !== FORBIDDEN_STATUS)
1630
+ return void 0;
1631
+ if (hasCode(payload))
1632
+ return void 0;
1633
+ const emptyBody = typeof bodyText === "string" && bodyText.trim() === "";
1634
+ if (!isRouterNack(payload) && !emptyBody)
1635
+ return void 0;
1636
+ return status === UNAUTHORIZED_STATUS ? AI_SERVICE_ACCESS_REFUSALS.SIGNED_OUT : AI_SERVICE_ACCESS_REFUSALS.ACCESS_DENIED;
1637
+ }
1638
+ function isUncodedTooLarge(status, payload) {
1639
+ return status === PAYLOAD_TOO_LARGE_STATUS && payload === void 0;
1640
+ }
1641
+ function routerRefusalDetailOf(payload) {
1642
+ var _a;
1643
+ const errors = payload === null || payload === void 0 ? void 0 : payload.ERROR;
1644
+ const text = Array.isArray(errors) ? (_a = errors[0]) === null || _a === void 0 ? void 0 : _a.TEXT : void 0;
1645
+ return typeof text === "string" && text ? text : void 0;
1646
+ }
1647
+ var REFUSED_REQUEST = "The AI service refused the assistant's request. An administrator can find the details in the browser console.";
1648
+ var DEFAULT_AI_SERVICE_ERROR_MESSAGES = Object.freeze({
1649
+ NO_API_KEY: "The assistant isn't set up yet. An administrator needs to add an API key for its AI service.",
1650
+ BAD_API_KEY: "The assistant can't use its AI service key. An administrator needs to check the key.",
1651
+ KEY_UNREADABLE: "The assistant can't read its AI service key. An administrator needs to check how the key is stored.",
1652
+ 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.",
1653
+ BAD_REQUEST: REFUSED_REQUEST,
1654
+ // The assistant never sends fallbacks, so only a mismatched client can meet this one.
1655
+ FALLBACKS_NOT_SUPPORTED: REFUSED_REQUEST,
1656
+ 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.",
1657
+ 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.",
1658
+ SIGNED_OUT: "Your session has ended. Sign in again to use the assistant.",
1659
+ ACCESS_DENIED: "You don't have access to the assistant. An administrator can give you access."
1660
+ });
1661
+ var isTerminalAIServiceRefusal = (code) => code !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE;
1662
+ var AIServiceError = class extends Error {
1663
+ constructor(vendorLabel, code, status, detail) {
1664
+ super(`${vendorLabel} AI service refused the request (${status} ${code})`);
1665
+ this.vendorLabel = vendorLabel;
1666
+ this.code = code;
1667
+ this.status = status;
1668
+ this.detail = detail;
1669
+ this.name = "AIServiceError";
1670
+ }
1671
+ /** Whether sending the request again cannot help. */
1672
+ get terminal() {
1673
+ return isTerminalAIServiceRefusal(this.code);
1674
+ }
1675
+ };
1676
+ function aiServiceDetailOf(payload) {
1677
+ const error = payload === null || payload === void 0 ? void 0 : payload.error;
1678
+ return typeof error === "string" && error ? error : void 0;
1679
+ }
1680
+
1582
1681
  // ../../foundation-ai/dist/esm/transports/context-overflow-error.js
1583
1682
  var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
1584
1683
  /prompt is too long/i,
@@ -1762,9 +1861,13 @@ function serverBackoffSpentMs(resolvedMs, ladderMs) {
1762
1861
  var MAX_RETRIES = 5;
1763
1862
  function postWithRetry(options) {
1764
1863
  return __awaiter(this, void 0, void 0, function* () {
1765
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1864
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1766
1865
  const { url, headers, body, credentials, vendorLabel, retryableStatuses, timeout, stallTimeout, backoffBaseMs, signal } = options;
1767
1866
  const vendor = vendorOfTransportLabel(vendorLabel);
1867
+ const serviceRefusal = (code, status, detail) => {
1868
+ logger.error(`${vendorLabel}Transport: the AI service refused the request (${status} ${code})${detail ? `: ${detail}` : ""}`);
1869
+ return new AIServiceError(vendorLabel, code, status, detail);
1870
+ };
1768
1871
  let serverBackoffSpent = 0;
1769
1872
  const backoff = (attempt, serverMs) => {
1770
1873
  const ladderMs = backoffBaseMs * Math.pow(2, attempt);
@@ -1822,6 +1925,17 @@ function postWithRetry(options) {
1822
1925
  if (isBudgetRejection(response.status, codeOf(parsed))) {
1823
1926
  throw budgetExhaustedFrom(vendorLabel, parsed, errText || void 0);
1824
1927
  }
1928
+ const serviceCode = aiServiceErrorCodeOf(codeOf(parsed));
1929
+ if (serviceCode && serviceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1930
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1931
+ }
1932
+ const accessRefusal = aiServiceAccessRefusalOf(response.status, parsed, errText);
1933
+ if (accessRefusal) {
1934
+ throw serviceRefusal(accessRefusal, response.status, (_e = routerRefusalDetailOf(parsed)) !== null && _e !== void 0 ? _e : errText || void 0);
1935
+ }
1936
+ if (isUncodedTooLarge(response.status, parsed)) {
1937
+ throw serviceRefusal(AI_SERVICE_ERROR_CODES.REQUEST_TOO_LARGE, response.status, errText || void 0);
1938
+ }
1825
1939
  const refusedRetry = shouldNotRetry(response.headers);
1826
1940
  if (retryableStatuses.includes(response.status) && !refusedRetry && attempt < MAX_RETRIES) {
1827
1941
  logger.warn(`${vendorLabel}Transport: retryable status ${response.status}, retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
@@ -1829,15 +1943,18 @@ function postWithRetry(options) {
1829
1943
  yield backoff(attempt, retryAfterMs(response.headers) || retryInfoMs(parsed));
1830
1944
  continue;
1831
1945
  }
1946
+ if (serviceCode) {
1947
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1948
+ }
1832
1949
  throw new Error(`${vendorLabel} request error ${response.status}: ${errText}`);
1833
1950
  }
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) {
1951
+ 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
1952
  rearmStallTimer();
1836
1953
  const frame = yield readFramedBody(response.body, rearmStallTimer, vendorLabel, stallTimeout);
1837
1954
  if (frame.t === "ok")
1838
1955
  return frame.body;
1839
1956
  if (frame.code === "UPSTREAM_STALLED") {
1840
- throw new DOMException(`${vendorLabel} request stalled: ${(_g = frame.error) !== null && _g !== void 0 ? _g : "no upstream data"}`, "TimeoutError");
1957
+ throw new DOMException(`${vendorLabel} request stalled: ${(_h = frame.error) !== null && _h !== void 0 ? _h : "no upstream data"}`, "TimeoutError");
1841
1958
  }
1842
1959
  const framedRefusal = providerRefusalOf(vendor, frame.code, frame);
1843
1960
  if (framedRefusal) {
@@ -1845,18 +1962,25 @@ function postWithRetry(options) {
1845
1962
  }
1846
1963
  const framedOverflow = contextOverflowOf(vendor, frame.status, frame);
1847
1964
  if (framedOverflow) {
1848
- throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_h = framedOverflow.message) !== null && _h !== void 0 ? _h : frame.error);
1965
+ throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_j = framedOverflow.message) !== null && _j !== void 0 ? _j : frame.error);
1849
1966
  }
1850
1967
  if (isBudgetRejection(frame.status, frame.code)) {
1851
1968
  throw budgetExhaustedFrom(vendorLabel, frame);
1852
1969
  }
1970
+ const framedServiceCode = aiServiceErrorCodeOf(frame.code);
1971
+ if (framedServiceCode && framedServiceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1972
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
1973
+ }
1853
1974
  if (retryableStatuses.includes(frame.status) && attempt < MAX_RETRIES) {
1854
1975
  logger.warn(`${vendorLabel}Transport: retryable status ${frame.status} (err frame), retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
1855
1976
  clearTimeout(timeoutId);
1856
1977
  yield backoff(attempt, retryInfoMs(frame));
1857
1978
  continue;
1858
1979
  }
1859
- throw new Error(`${vendorLabel} request error ${frame.status}: ${(_j = frame.error) !== null && _j !== void 0 ? _j : JSON.stringify(frame.details)}`);
1980
+ if (framedServiceCode) {
1981
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
1982
+ }
1983
+ throw new Error(`${vendorLabel} request error ${frame.status}: ${(_k = frame.error) !== null && _k !== void 0 ? _k : JSON.stringify(frame.details)}`);
1860
1984
  }
1861
1985
  return yield response.json();
1862
1986
  } catch (e) {
@@ -3873,80 +3997,6 @@ function clearSession(key) {
3873
3997
  registry.delete(key);
3874
3998
  }
3875
3999
 
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
4000
  // src/utils/context-tokens.ts
3951
4001
  var APPROX_CHARS_PER_TOKEN = 4;
3952
4002
  var IMAGE_TOKEN_ESTIMATE = 1600;
@@ -4080,6 +4130,80 @@ function projectCompaction(history, cut, summaryTokens = COMPACTION_SUMMARY_TOKE
4080
4130
  };
4081
4131
  }
4082
4132
 
4133
+ // src/utils/logger.ts
4134
+ var logger2 = createLogger("ai-assistant");
4135
+
4136
+ // src/suggestions/generate-suggestions.ts
4137
+ var HISTORY_WINDOW = 8;
4138
+ function capabilities(ctx, allAgentInfo) {
4139
+ let agentContext = "";
4140
+ let toolContext = "";
4141
+ if (allAgentInfo?.length) {
4142
+ const agentDescriptions = allAgentInfo.map((agent) => {
4143
+ const tools = agent.tools.map((t) => t.name).join(", ");
4144
+ return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
4145
+ }).join("\n");
4146
+ agentContext = `The assistant has the following capabilities:
4147
+ ${agentDescriptions}`;
4148
+ const allToolNames = [
4149
+ ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
4150
+ ].join(", ");
4151
+ toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
4152
+ } else if (ctx.activeAgentName) {
4153
+ const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
4154
+ agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
4155
+ toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
4156
+ }
4157
+ return agentContext || toolContext ? `
4158
+
4159
+ <capabilities>
4160
+ ${[agentContext, toolContext].filter(Boolean).join(
4161
+ "\n"
4162
+ )}
4163
+ </capabilities>
4164
+ Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
4165
+ }
4166
+ var OUTPUT_FORMAT = (count) => `
4167
+
4168
+ Output format (strict):
4169
+ - Exactly ${count} lines.
4170
+ - One suggestion per line.
4171
+ - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
4172
+ - No preamble, headings, summary, or commentary before or after the list.`;
4173
+ 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.";
4174
+ function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
4175
+ const capabilitiesBlock = capabilities(ctx, allAgentInfo);
4176
+ const guidanceBlock = prompt2 ? `
4177
+
4178
+ Additional guidance: "${prompt2}"` : "";
4179
+ if (history.length === 0) {
4180
+ 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);
4181
+ }
4182
+ const conversationContext = history.filter(
4183
+ (m) => reachesProvider(m) && (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
4184
+ ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
4185
+ return `<conversation_history>
4186
+ ${conversationContext}
4187
+ </conversation_history>
4188
+
4189
+ 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);
4190
+ }
4191
+ function parseSuggestions(text, count) {
4192
+ 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);
4193
+ }
4194
+ async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
4195
+ const defaultProvider = ctx.registry.default();
4196
+ if (!defaultProvider.prompt) {
4197
+ logger2.warn("ChatDriver: default AI provider does not implement prompt()");
4198
+ return [];
4199
+ }
4200
+ const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
4201
+ const text = await defaultProvider.prompt(userMessage, {
4202
+ systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
4203
+ });
4204
+ return parseSuggestions(text, count);
4205
+ }
4206
+
4083
4207
  // src/utils/condense-history.ts
4084
4208
  var CONDENSE_MIN_CHARS = 1e3;
4085
4209
  var CONDENSED_ARGS_KEY = "condensed";
@@ -4468,7 +4592,7 @@ function renderMessageForSummary(m) {
4468
4592
  }
4469
4593
  }
4470
4594
  function buildCompactionSummaryPrompt(toCompact) {
4471
- const transcript = toCompact.map(renderMessageForSummary).filter(Boolean).join("\n");
4595
+ const transcript = toCompact.filter((m) => !m.excludeFromProvider).map(renderMessageForSummary).filter(Boolean).join("\n");
4472
4596
  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
4597
  const userMessage = `<conversation_history>
4474
4598
  ${transcript}
@@ -4986,6 +5110,10 @@ function createInteractionContext(interactionId) {
4986
5110
  }
4987
5111
 
4988
5112
  // src/components/chat-driver/interaction-controller.ts
5113
+ var STOPPED = {
5114
+ status: "timeout",
5115
+ message: "The turn was stopped before this was answered."
5116
+ };
4989
5117
  var InteractionController = class {
4990
5118
  constructor(deps) {
4991
5119
  this.deps = deps;
@@ -5058,6 +5186,19 @@ var InteractionController = class {
5058
5186
  ...presentation ? { presentation } : {}
5059
5187
  }
5060
5188
  });
5189
+ const signal = options?.signal;
5190
+ if (signal) {
5191
+ const onAbort = () => this.resolve(interactionId, STOPPED);
5192
+ if (signal.aborted) {
5193
+ onAbort();
5194
+ } else {
5195
+ signal.addEventListener("abort", onAbort, { once: true });
5196
+ const pending = this.pending.get(interactionId);
5197
+ if (pending) {
5198
+ pending.unlinkSignal = () => signal.removeEventListener("abort", onAbort);
5199
+ }
5200
+ }
5201
+ }
5061
5202
  });
5062
5203
  }
5063
5204
  /**
@@ -5071,6 +5212,7 @@ var InteractionController = class {
5071
5212
  return;
5072
5213
  }
5073
5214
  if (interaction.timeoutHandle) clearTimeout(interaction.timeoutHandle);
5215
+ interaction.unlinkSignal?.();
5074
5216
  this.deps.foldDiagnostics(
5075
5217
  interactionId,
5076
5218
  result?.diagnostics
@@ -5231,6 +5373,13 @@ var TURN_FAILURE_EXITS = {
5231
5373
  // Overridden per wall by `ChatDriver.budgetExhaustedBubble`, which upgrades this with
5232
5374
  // "switch to another AI" when a second vendor is reachable.
5233
5375
  copy: DEFAULT_BUDGET_EXHAUSTED_MESSAGE
5376
+ },
5377
+ aiServiceError: {
5378
+ subReason: "ai_service_error",
5379
+ resultReason: "ai-service-error",
5380
+ // Replaced per code by `ChatDriver.aiServiceErrorBubble`; this is only what a parent says when
5381
+ // a child's failure arrives without its code.
5382
+ copy: DEFAULT_AI_SERVICE_ERROR_MESSAGES.BAD_REQUEST
5234
5383
  }
5235
5384
  // `satisfies`, not an annotation: an annotation would widen `resultReason` to
5236
5385
  // `TurnFailureReason` and cost the literal types that let `turn-failures.test.ts` pin the
@@ -5401,6 +5550,19 @@ var TurnRecorder = class {
5401
5550
  };
5402
5551
 
5403
5552
  // src/components/chat-driver/chat-driver.ts
5553
+ var REQUEST_SCOPED_REFUSALS = /* @__PURE__ */ new Set([
5554
+ "REQUEST_TOO_LARGE",
5555
+ "BAD_REQUEST",
5556
+ "FALLBACKS_NOT_SUPPORTED"
5557
+ ]);
5558
+ var SERVICE_WIDE_REFUSALS = /* @__PURE__ */ new Set([
5559
+ "NO_API_KEY",
5560
+ "BAD_API_KEY",
5561
+ "KEY_UNREADABLE",
5562
+ "SIGNED_OUT",
5563
+ "ACCESS_DENIED",
5564
+ "VENDOR_UNREACHABLE"
5565
+ ]);
5404
5566
  var toolResultImages = (result) => {
5405
5567
  if (!result || typeof result !== "object") return void 0;
5406
5568
  const candidate = result.attachments;
@@ -5429,6 +5591,15 @@ var budgetDetailOf = (e) => {
5429
5591
  ...e.otherVendorAvailable != null ? { otherVendorAvailable: e.otherVendorAvailable } : {}
5430
5592
  };
5431
5593
  };
5594
+ function inFlightToolCallsAt(history) {
5595
+ for (let i = history.length - 1; i >= 0; i -= 1) {
5596
+ const message = history[i];
5597
+ if (message.role !== "assistant" || !message.toolCalls?.length) continue;
5598
+ const answered = new Set(history.slice(i + 1).map((later) => later.toolResult?.toolCallId));
5599
+ return message.toolCalls.some((call) => !answered.has(call.id)) ? i : history.length;
5600
+ }
5601
+ return history.length;
5602
+ }
5432
5603
  var ChatDriver = class _ChatDriver extends EventTarget {
5433
5604
  constructor(providerRegistry, config = {}) {
5434
5605
  super();
@@ -5574,6 +5745,17 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5574
5745
  this.turnController = new AbortController();
5575
5746
  /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
5576
5747
  this.turnCancelled = false;
5748
+ /**
5749
+ * The scope tool handlers see as `turnSignal`: one USER MESSAGE. Minted by `sendMessage`, so a
5750
+ * handoff's `continueFromHistory` — a new `turnController`, but the same message — keeps it,
5751
+ * and a sub-agent inherits it (`inheritedTurnSignal`). Aborted by `cancel()` and by a dispose.
5752
+ * `continueFromHistory` mints one only when the message it would continue was stopped.
5753
+ *
5754
+ * Kept apart from `turnController`, which is per REQUEST and restarts on every continuation: a
5755
+ * handler that remembers something "for the rest of the turn" (the write tools' deny lock) keyed
5756
+ * on that one was reset by every handoff inside a single message.
5757
+ */
5758
+ this.messageController = new AbortController();
5577
5759
  /**
5578
5760
  * Caches validated provider lookups per name within the current agent. Cleared
5579
5761
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -5610,6 +5792,20 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5610
5792
  * children costing N doomed calls plus a doomed parent one.
5611
5793
  */
5612
5794
  this.providerRefusedThisTurn = false;
5795
+ /**
5796
+ * A sub-agent was refused by the AI service this turn in a way that stops this driver too
5797
+ * (GENC-1611): a service-wide code, from the vendor this driver calls. Sub-agent path only, like
5798
+ * `providerRefusedThisTurn`; this driver's own refusal returns straight out of the catch.
5799
+ */
5800
+ this.aiServiceErrorThisTurn = false;
5801
+ /** Codes a child's refusal was already shown for during this user message. */
5802
+ this.aiServiceNoticesShown = /* @__PURE__ */ new Set();
5803
+ /**
5804
+ * Notices waiting for the tool batch to end. Written mid-batch they would sit between the
5805
+ * assistant's tool calls and their results, where a later sub-agent's primer would pick up the
5806
+ * unanswered calls.
5807
+ */
5808
+ this.aiServiceNoticesQueued = [];
5613
5809
  /**
5614
5810
  * Set the moment a budget wall is observed anywhere in this turn — this
5615
5811
  * driver's own 402, or a sub-agent's (which surfaces here only as a
@@ -5639,7 +5835,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5639
5835
  deferAgentRelease = false,
5640
5836
  activityBus = NOOP_ACTIVITY_BUS,
5641
5837
  budgetExhaustedMessage,
5642
- providerRefusedMessage
5838
+ providerRefusedMessage,
5839
+ aiServiceErrorMessages
5643
5840
  } = config;
5644
5841
  this.maxToolIterations = maxToolIterations;
5645
5842
  this.condenseBatchCalls = condenseBatchCalls;
@@ -5648,6 +5845,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5648
5845
  this.activityBus = activityBus;
5649
5846
  this.budgetExhaustedMessageOverride = budgetExhaustedMessage;
5650
5847
  this.providerRefusedMessageOverride = providerRefusedMessage;
5848
+ this.aiServiceErrorMessagesOverride = aiServiceErrorMessages;
5651
5849
  if (typeof toolHandlers === "function") {
5652
5850
  this.toolHandlersFactory = toolHandlers;
5653
5851
  this.toolHandlers = {};
@@ -5712,14 +5910,43 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5712
5910
  /**
5713
5911
  * Stop the current turn (user "stop" button). Aborts the in-flight provider
5714
5912
  * 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.
5913
+ * the loop bails at the next boundary (tools are atomic). When idle it only ends
5914
+ * the message (see below) and appends nothing. The driver stays usable for the
5915
+ * next message.
5717
5916
  */
5718
5917
  cancel() {
5918
+ this.messageController.abort(new DOMException("Cancelled by user", "AbortError"));
5719
5919
  if (!this.busy) return;
5720
5920
  this.turnCancelled = true;
5721
5921
  this.turnController.abort(new DOMException("Cancelled by user", "AbortError"));
5722
5922
  }
5923
+ /**
5924
+ * Start a fresh per-MESSAGE scope for tool handlers (see `messageController`). Chained to
5925
+ * `lifecycleController` so a dispose aborts it; the link lives until the next message, because
5926
+ * a handoff continues this one.
5927
+ */
5928
+ beginMessage() {
5929
+ this.unlinkLifecycleFromMessage?.();
5930
+ this.messageController = new AbortController();
5931
+ const lifecycle = this.lifecycleController.signal;
5932
+ if (lifecycle.aborted) {
5933
+ this.messageController.abort(lifecycle.reason);
5934
+ this.unlinkLifecycleFromMessage = void 0;
5935
+ return;
5936
+ }
5937
+ const onDispose = () => this.messageController.abort(lifecycle.reason);
5938
+ lifecycle.addEventListener("abort", onDispose, { once: true });
5939
+ this.unlinkLifecycleFromMessage = () => lifecycle.removeEventListener("abort", onDispose);
5940
+ }
5941
+ /**
5942
+ * Makes this (sub-agent) driver's handlers see the parent message's `turnSignal` instead of one
5943
+ * of their own: a delegation is part of the message that made it.
5944
+ *
5945
+ * @internal
5946
+ */
5947
+ inheritTurnSignal(signal) {
5948
+ this.inheritedTurnSignal = signal;
5949
+ }
5723
5950
  /**
5724
5951
  * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
5725
5952
  * new `turnController` so a dispose mid-turn also aborts the request.
@@ -5777,8 +6004,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5777
6004
  */
5778
6005
  endTurnWithFailure(exit, overrides) {
5779
6006
  if (this.isSubAgent) {
5780
- this.failSubAgent(exit.subReason, overrides?.budget, overrides?.providerRefused);
5781
- } else {
6007
+ this.failSubAgent(
6008
+ exit.subReason,
6009
+ overrides?.budget,
6010
+ overrides?.providerRefused,
6011
+ overrides?.aiServiceError
6012
+ );
6013
+ } else if (!overrides?.silent) {
5782
6014
  this.appendDriverNotice(overrides?.copy ?? exit.copy);
5783
6015
  }
5784
6016
  return turnDone(exit.resultReason, overrides?.budget, overrides?.providerRefused);
@@ -5815,6 +6047,19 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5815
6047
  const subject = wall?.vendorLabel ? `${wall.vendorLabel}'s AI usage limit` : "your AI usage limit";
5816
6048
  return `You've reached ${subject}. Switch to another AI provider in Settings to keep going, or contact your administrator to raise it.`;
5817
6049
  }
6050
+ /**
6051
+ * Record a message the user sent and then stopped before any turn took it: during an
6052
+ * orchestrator's first classify, or its first agent's install. Only an optimistic
6053
+ * `history-updated` had shown it, so it vanished on the next update, and from a reload. Appended
6054
+ * here with the "Stopped." marker a stopped turn leaves, as `reportBudgetExhausted` appends a
6055
+ * message the budget wall kept from its turn.
6056
+ *
6057
+ * @internal
6058
+ */
6059
+ reportStoppedBeforeTurn(userMessage) {
6060
+ this.appendToHistory(userMessage);
6061
+ this.appendToHistory({ role: "system-event", content: "Stopped." });
6062
+ }
5818
6063
  reportBudgetExhausted(e, pendingUserMessage) {
5819
6064
  if (pendingUserMessage) this.appendToHistory(pendingUserMessage);
5820
6065
  this.budgetExhaustedThisTurn = true;
@@ -5847,6 +6092,158 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5847
6092
  providerRefusedBubble() {
5848
6093
  return this.providerRefusedMessageOverride ?? TURN_FAILURE_EXITS.providerRefused.copy;
5849
6094
  }
6095
+ /**
6096
+ * A terminal AI service error hit **outside** the tool loop — `OrchestratingDriver`'s classification
6097
+ * phase (GENC-1611). The same log line, debug-log entry, sentence and result as the in-loop branch.
6098
+ *
6099
+ * @param pendingUserMessage - the user's message when it has NOT been appended yet, for the reason
6100
+ * `reportBudgetExhausted` gives.
6101
+ */
6102
+ reportAIServiceError(e, pendingUserMessage) {
6103
+ if (pendingUserMessage) {
6104
+ this.aiServiceNoticesShown.clear();
6105
+ this.aiServiceNoticesQueued = [];
6106
+ this.appendToHistory(pendingUserMessage);
6107
+ }
6108
+ return this.endTurnWithAIServiceError(e);
6109
+ }
6110
+ /**
6111
+ * The sentence for an AI service error code (GENC-1611): the host's override, else the default.
6112
+ * Never the service's own text, which goes to the console only.
6113
+ */
6114
+ aiServiceErrorBubble(code) {
6115
+ if (!code) return TURN_FAILURE_EXITS.aiServiceError.copy;
6116
+ const override = this.aiServiceErrorMessagesOverride?.[code];
6117
+ return override?.trim() ? override : DEFAULT_AI_SERVICE_ERROR_MESSAGES[code];
6118
+ }
6119
+ /**
6120
+ * Shows a sub-agent's AI-service refusal that the turn went on without, once per code in a user
6121
+ * message: the user's sentence with the host's overrides, never the service's text. A sub-agent
6122
+ * passes it up to the driver the user sees.
6123
+ */
6124
+ noticeAIServiceRefusal(code) {
6125
+ if (REQUEST_SCOPED_REFUSALS.has(code)) return;
6126
+ if (this.hostAIServiceNotice) {
6127
+ this.hostAIServiceNotice(code);
6128
+ return;
6129
+ }
6130
+ if (!this.busy) return;
6131
+ if (this.aiServiceNoticesShown.has(code) || this.aiServiceNoticesQueued.includes(code)) return;
6132
+ this.aiServiceNoticesQueued.push(code);
6133
+ }
6134
+ /**
6135
+ * Writes the notices queued during a tool batch, once its results are in the history, or before
6136
+ * the failure when the batch threw. A code counts as shown only once written.
6137
+ */
6138
+ flushAIServiceNotices() {
6139
+ const codes = this.aiServiceNoticesQueued;
6140
+ this.aiServiceNoticesQueued = [];
6141
+ for (const code of codes) {
6142
+ this.aiServiceNoticesShown.add(code);
6143
+ this.appendDriverNotice(this.aiServiceErrorBubble(code));
6144
+ }
6145
+ }
6146
+ /** Ends the turn on an AI service error: logged with the service's text, shown without it. */
6147
+ endTurnWithAIServiceError(e) {
6148
+ logger2.error("ChatDriver: the AI service refused the request", e, e.detail ?? "");
6149
+ recordTurnError(this.sessionKey, "ai-service-error", {
6150
+ agent: this.activeAgentName,
6151
+ provider: this.lastResolvedProviderName,
6152
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider,
6153
+ code: e.code,
6154
+ status: e.status,
6155
+ isSubAgent: this.isSubAgent
6156
+ });
6157
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6158
+ copy: this.aiServiceErrorBubble(e.code),
6159
+ aiServiceError: {
6160
+ code: e.code,
6161
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider
6162
+ },
6163
+ silent: this.aiServiceSentenceShown(e.code)
6164
+ });
6165
+ }
6166
+ /**
6167
+ * Whether this user message already showed the sentence for `code`, so a turn-ending failure
6168
+ * does not show it twice. Marks it shown otherwise. Only the driver the user sees keeps count.
6169
+ */
6170
+ aiServiceSentenceShown(code) {
6171
+ if (this.isSubAgent || !code) return false;
6172
+ if (this.aiServiceNoticesShown.has(code)) return true;
6173
+ this.aiServiceNoticesShown.add(code);
6174
+ return false;
6175
+ }
6176
+ /**
6177
+ * Whether a sub-agent hit a wall this turn that stops this driver too. A handoff goes on past an
6178
+ * AI-service wall: the next agent may use another vendor, and if it uses this one its own call
6179
+ * meets the wall and says so.
6180
+ */
6181
+ subAgentWallThisTurn(handingOff = false) {
6182
+ return this.providerRefusedThisTurn || this.budgetExhaustedThisTurn || this.aiServiceErrorThisTurn && !handingOff;
6183
+ }
6184
+ /**
6185
+ * Ends the turn when a sub-agent hit a wall this turn that stops this driver too: the provider
6186
+ * refusing the account, the AI service (GENC-1611), or the budget. Checked before each model call,
6187
+ * and again right after a tool batch, before a handoff or the iteration cap can report the turn as
6188
+ * something else.
6189
+ */
6190
+ endTurnOnSubAgentWall() {
6191
+ if (!this.subAgentWallThisTurn()) return void 0;
6192
+ this.subAgentCompletion = void 0;
6193
+ if (this.providerRefusedThisTurn) {
6194
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6195
+ recordTurnError(this.sessionKey, "provider-refused", {
6196
+ agent: this.activeAgentName,
6197
+ provider: this.lastResolvedProviderName,
6198
+ kind: this.providerRefusedDetail?.kind,
6199
+ via: "sub-agent",
6200
+ isSubAgent: this.isSubAgent
6201
+ });
6202
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6203
+ copy: this.providerRefusedBubble(),
6204
+ providerRefused: this.providerRefusedDetail
6205
+ });
6206
+ }
6207
+ if (this.aiServiceErrorThisTurn) {
6208
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent was refused by the AI service");
6209
+ recordTurnError(this.sessionKey, "ai-service-error", {
6210
+ agent: this.activeAgentName,
6211
+ provider: this.lastResolvedProviderName,
6212
+ code: this.aiServiceWall?.code,
6213
+ via: "sub-agent",
6214
+ isSubAgent: this.isSubAgent
6215
+ });
6216
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6217
+ copy: this.aiServiceErrorBubble(this.aiServiceWall?.code),
6218
+ aiServiceError: this.aiServiceWall,
6219
+ silent: this.aiServiceSentenceShown(this.aiServiceWall?.code)
6220
+ });
6221
+ }
6222
+ if (this.budgetExhaustedThisTurn) {
6223
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6224
+ recordTurnError(this.sessionKey, "budget-exhausted", {
6225
+ agent: this.activeAgentName,
6226
+ provider: this.lastResolvedProviderName,
6227
+ // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6228
+ // path the wall is definitionally the child's, and on a mixed registry
6229
+ // `lastResolvedProvider` is this driver's own vendor — the one known
6230
+ // NOT to have refused. An unattributable child wall must degrade to
6231
+ // the vendor-agnostic block (which `latchBlockedFrom` handles
6232
+ // fail-safe), never to a vendor that is known to be wrong: naming the
6233
+ // parent's vendor here walled BOTH — the child's via its own
6234
+ // tool-loop-end, the parent's via this event — and derived `blocked`
6235
+ // over headroom that still existed.
6236
+ vendor: this.budgetWallDetail?.vendor,
6237
+ via: "sub-agent",
6238
+ isSubAgent: this.isSubAgent
6239
+ });
6240
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6241
+ copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6242
+ budget: this.budgetWallDetail
6243
+ });
6244
+ }
6245
+ return void 0;
6246
+ }
5850
6247
  /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
5851
6248
  static failureReasonOf(result) {
5852
6249
  return result.reason === "done" ? result.failureReason : void 0;
@@ -6127,12 +6524,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6127
6524
  * under a separate session key, so recording here would orphan the event off
6128
6525
  * the user-visible debug-log timeline.)
6129
6526
  */
6130
- failSubAgent(reason, budget, providerRefused) {
6527
+ failSubAgent(reason, budget, providerRefused, aiServiceError) {
6131
6528
  if (!this.isSubAgent || this.subAgentFailure) return;
6132
6529
  this.subAgentFailure = {
6133
6530
  reason,
6134
6531
  ...budget ? { budget } : {},
6135
- ...providerRefused ? { providerRefused } : {}
6532
+ ...providerRefused ? { providerRefused } : {},
6533
+ ...aiServiceError ? { aiServiceError } : {}
6136
6534
  };
6137
6535
  }
6138
6536
  /**
@@ -6563,6 +6961,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6563
6961
  if (this.busy || !userInput.trim() && !attachments?.length) return { reason: "done" };
6564
6962
  this.busy = true;
6565
6963
  this.beginTurn();
6964
+ this.beginMessage();
6566
6965
  this.turnSeq += 1;
6567
6966
  this.subAgentCompletion = void 0;
6568
6967
  this.subAgentFailure = void 0;
@@ -6572,6 +6971,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6572
6971
  this.budgetWallViaSubAgent = false;
6573
6972
  this.providerRefusedThisTurn = false;
6574
6973
  this.providerRefusedDetail = void 0;
6974
+ this.aiServiceErrorThisTurn = false;
6975
+ this.aiServiceWall = void 0;
6976
+ this.aiServiceNoticesShown.clear();
6977
+ this.aiServiceNoticesQueued = [];
6575
6978
  this.appendToHistory({ role: "user", content: userInput, attachments });
6576
6979
  this.turnStartedAt = Date.now();
6577
6980
  recordMetaEvent(this.sessionKey, "turn.start", {
@@ -6592,6 +6995,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6592
6995
  name: e instanceof Error ? e.name : void 0,
6593
6996
  message: e instanceof Error ? e.message : String(e)
6594
6997
  });
6998
+ this.flushAIServiceNotices();
6595
6999
  this.appendDriverNotice(
6596
7000
  "Sorry, something went wrong on my end. Please try again in a moment."
6597
7001
  );
@@ -6636,6 +7040,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6636
7040
  buildHandlerContext(activeToolCallId, traceCapture) {
6637
7041
  return {
6638
7042
  requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options),
7043
+ // The MESSAGE's scope: one object per `sendMessage`, kept across a handoff's continuation
7044
+ // and handed to a sub-agent, and aborted by `cancel()` as well as a dispose. Not the
7045
+ // per-request `turnController`, which every continuation replaces.
7046
+ turnSignal: this.inheritedTurnSignal ?? this.messageController.signal,
6639
7047
  ...this.subAgentsMap.size > 0 && {
6640
7048
  requestSubAgent: (name, options) => this.invokeSubAgent(name, options).then(({ outcome, trace }) => {
6641
7049
  if (traceCapture && trace) traceCapture.traces.push(trace);
@@ -6712,8 +7120,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6712
7120
  );
6713
7121
  }
6714
7122
  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;
7123
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
6717
7124
  const snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
6718
7125
  const contextMessages = context ? [{ role: "user", content: `[Sub-agent context]: ${JSON.stringify(context)}` }] : [];
6719
7126
  const effectivePrimer = [
@@ -6730,6 +7137,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6730
7137
  activityBus: this.activityBus
6731
7138
  });
6732
7139
  child.markAsSubAgent();
7140
+ child.inheritTurnSignal(this.inheritedTurnSignal ?? this.messageController.signal);
6733
7141
  child.setContextGuard(this.contextGuard);
6734
7142
  const disposeChild = () => child.dispose();
6735
7143
  if (this.lifecycleController.signal.aborted) {
@@ -6741,6 +7149,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6741
7149
  child.setHostInteractionRequester(
6742
7150
  (componentName, data, opts) => this.requestInteraction(componentName, data, opts)
6743
7151
  );
7152
+ child.hostAIServiceNotice = (code) => this.noticeAIServiceRefusal(code);
6744
7153
  const forwardTrace = (e) => {
6745
7154
  this.dispatchEvent(
6746
7155
  new CustomEvent("sub-agent-history-updated", {
@@ -6821,6 +7230,28 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6821
7230
  this.providerRefusedThisTurn = true;
6822
7231
  this.providerRefusedDetail ??= failure?.providerRefused;
6823
7232
  }
7233
+ const wall = failure?.aiServiceError;
7234
+ if (reason === "ai_service_error" && wall && SERVICE_WIDE_REFUSALS.has(wall.code) && wall.vendor !== void 0 && wall.vendor === this.lastResolvedProvider) {
7235
+ this.aiServiceErrorThisTurn = true;
7236
+ this.aiServiceWall ??= wall;
7237
+ } else if (reason === "ai_service_error" && wall) {
7238
+ this.noticeAIServiceRefusal(wall.code);
7239
+ }
7240
+ if (reason === "ai_service_error") {
7241
+ if (wall) {
7242
+ return {
7243
+ outcome: {
7244
+ ok: false,
7245
+ reason,
7246
+ code: wall.code,
7247
+ terminal: isTerminalAIServiceRefusal(wall.code)
7248
+ },
7249
+ trace
7250
+ };
7251
+ }
7252
+ logger2.error(`ChatDriver: sub-agent "${name}" was refused by the AI service with no code`);
7253
+ return { outcome: { ok: false, reason: "max_iterations" }, trace };
7254
+ }
6824
7255
  return { outcome: { ok: false, reason }, trace };
6825
7256
  }
6826
7257
  /**
@@ -6830,6 +7261,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6830
7261
  async continueFromHistory(transientPrimer) {
6831
7262
  if (this.busy) return { reason: "done" };
6832
7263
  this.busy = true;
7264
+ if (this.messageController.signal.aborted) this.beginMessage();
6833
7265
  this.beginTurn();
6834
7266
  this.subAgentCompletion = void 0;
6835
7267
  this.subAgentFailure = void 0;
@@ -6838,6 +7270,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6838
7270
  this.budgetWallViaSubAgent = false;
6839
7271
  this.providerRefusedThisTurn = false;
6840
7272
  this.providerRefusedDetail = void 0;
7273
+ this.aiServiceErrorThisTurn = false;
7274
+ this.aiServiceWall = void 0;
6841
7275
  this.turnStartedAt = Date.now();
6842
7276
  recordMetaEvent(this.sessionKey, "turn.start", {
6843
7277
  phase: "continueFromHistory",
@@ -6857,6 +7291,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6857
7291
  name: e instanceof Error ? e.name : void 0,
6858
7292
  message: e instanceof Error ? e.message : String(e)
6859
7293
  });
7294
+ this.flushAIServiceNotices();
6860
7295
  this.appendDriverNotice(
6861
7296
  "Sorry, something went wrong on my end. Please try again in a moment."
6862
7297
  );
@@ -6903,43 +7338,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6903
7338
  if (this.turnController.signal.aborted) {
6904
7339
  return this.completeAbortedTurn();
6905
7340
  }
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
- }
7341
+ const wall = this.endTurnOnSubAgentWall();
7342
+ if (wall) return wall;
6943
7343
  const promptCtx = {
6944
7344
  agentName: this.activeAgentName ?? "",
6945
7345
  history: this.history,
@@ -7185,6 +7585,9 @@ ${tailBody}
7185
7585
  providerRefused: detail
7186
7586
  });
7187
7587
  }
7588
+ if (e instanceof AIServiceError && e.terminal) {
7589
+ return this.endTurnWithAIServiceError(e);
7590
+ }
7188
7591
  if (e instanceof BudgetExhaustedError) {
7189
7592
  this.budgetExhaustedThisTurn = true;
7190
7593
  this.budgetWallDetail = budgetDetailOf(e);
@@ -7226,6 +7629,7 @@ ${tailBody}
7226
7629
  iterations -= 1;
7227
7630
  continue;
7228
7631
  }
7632
+ if (e instanceof AIServiceError) return this.endTurnWithAIServiceError(e);
7229
7633
  throw e;
7230
7634
  }
7231
7635
  if (response.model === void 0 && this.lastResolvedModel !== void 0) {
@@ -7549,6 +7953,7 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7549
7953
  this.history[tcMsgIdx] = { ...tcMsg, toolCalls: annotatedCalls };
7550
7954
  this.notifyHistoryUpdated();
7551
7955
  }
7956
+ this.flushAIServiceNotices();
7552
7957
  if (hitUnknownToolLimit) {
7553
7958
  logger2.error(
7554
7959
  `ChatDriver: unknown-tool limit (${DEFAULT_MAX_UNKNOWN_TOOL_CALLS}) reached \u2014 stopping`
@@ -7578,6 +7983,15 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7578
7983
  return this.endTurnWithFailure(TURN_FAILURE_EXITS.unknownToolLimit);
7579
7984
  }
7580
7985
  const firstContinuation = systemCalls[0];
7986
+ if (!this.subAgentCompletion && this.subAgentWallThisTurn(!!firstContinuation)) {
7987
+ if (this.turnController.signal.aborted) return this.completeAbortedTurn();
7988
+ const wallAfterBatch = this.endTurnOnSubAgentWall();
7989
+ if (wallAfterBatch) return wallAfterBatch;
7990
+ }
7991
+ if (this.aiServiceErrorThisTurn && this.aiServiceWall) {
7992
+ this.noticeAIServiceRefusal(this.aiServiceWall.code);
7993
+ this.flushAIServiceNotices();
7994
+ }
7581
7995
  if (firstContinuation) {
7582
7996
  const { summary, remaining_task: remainingTask } = firstContinuation.args;
7583
7997
  return { reason: "agent-handoff", summary, remainingTask };
@@ -7747,6 +8161,7 @@ var OrchestratingDriver = class extends EventTarget {
7747
8161
  sessionKey: this.sessionKey,
7748
8162
  activityBus: options.activityBus,
7749
8163
  budgetExhaustedMessage: options.budgetExhaustedMessage,
8164
+ aiServiceErrorMessages: options.aiServiceErrorMessages,
7750
8165
  // This driver releases after the turn so it can fire the host-facing events; see the option.
7751
8166
  deferAgentRelease: true
7752
8167
  });
@@ -7927,15 +8342,16 @@ var OrchestratingDriver = class extends EventTarget {
7927
8342
  try {
7928
8343
  return await this.runOrchestratedTurn(input, attachments);
7929
8344
  } catch (e) {
8345
+ const pendingUserMessage = this.userMessageAppended ? void 0 : {
8346
+ role: "user",
8347
+ content: input,
8348
+ ...attachments ? { attachments } : {}
8349
+ };
7930
8350
  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
- );
8351
+ return this.chatDriver.reportBudgetExhausted(e, pendingUserMessage);
8352
+ }
8353
+ if (e instanceof AIServiceError) {
8354
+ return this.chatDriver.reportAIServiceError(e, pendingUserMessage);
7939
8355
  }
7940
8356
  throw e;
7941
8357
  }
@@ -7968,6 +8384,7 @@ var OrchestratingDriver = class extends EventTarget {
7968
8384
  while (true) {
7969
8385
  if (this.cancelled) break;
7970
8386
  await this.installAgent(currentAgent);
8387
+ if (this.cancelled) break;
7971
8388
  let result;
7972
8389
  if (isHandoff) {
7973
8390
  const contextPrimer = handoffSummary ? [{ role: "user", content: `[Context from previous agent]: ${handoffSummary}` }] : [];
@@ -7992,6 +8409,7 @@ var OrchestratingDriver = class extends EventTarget {
7992
8409
  if (result.reason !== "agent-handoff" || isFallback(currentAgent) || pinned) {
7993
8410
  break;
7994
8411
  }
8412
+ if (this.cancelled) break;
7995
8413
  handoffs += 1;
7996
8414
  if (handoffs > this.maxHandoffs) {
7997
8415
  this.appendInlineMessage(
@@ -8010,6 +8428,13 @@ var OrchestratingDriver = class extends EventTarget {
8010
8428
  routed = await this.classify(remainingTask, updatedHistory, void 0, attempted);
8011
8429
  currentAgent = routed.agent;
8012
8430
  }
8431
+ if (this.cancelled && !this.userMessageAppended) {
8432
+ this.chatDriver.reportStoppedBeforeTurn({
8433
+ role: "user",
8434
+ content: input,
8435
+ ...attachments ? { attachments } : {}
8436
+ });
8437
+ }
8013
8438
  return lastResult?.reason === "done" ? lastResult : { reason: "done" };
8014
8439
  }
8015
8440
  async continueFromHistory(transientPrimer) {
@@ -8267,6 +8692,7 @@ ${recentMessages}` : ""}`;
8267
8692
  break;
8268
8693
  } catch (e) {
8269
8694
  if (e instanceof BudgetExhaustedError) throw e;
8695
+ if (e instanceof AIServiceError && e.terminal) throw e;
8270
8696
  lastError = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
8271
8697
  logger2.warn(`OrchestratingDriver: classifier attempt ${attempt + 1} failed:`, e);
8272
8698
  if (attempt === this.classifierRetries) {
@@ -8709,6 +9135,9 @@ function withFreshMetaSnapshot(stored, fresh) {
8709
9135
  }
8710
9136
  // Annotate the CommonJS export names for ESM import in node:
8711
9137
  0 && (module.exports = {
9138
+ AIServiceError,
9139
+ AI_SERVICE_ACCESS_REFUSALS,
9140
+ AI_SERVICE_ERROR_CODES,
8712
9141
  AI_TIER_IDS,
8713
9142
  AI_TIER_VENDORS,
8714
9143
  ANTHROPIC_CACHE_READ_MULTIPLIER,
@@ -8718,6 +9147,7 @@ function withFreshMetaSnapshot(stored, fresh) {
8718
9147
  AnthropicProvider,
8719
9148
  AnthropicTransport,
8720
9149
  ChatDriver,
9150
+ DEFAULT_AI_SERVICE_ERROR_MESSAGES,
8721
9151
  DEFAULT_AI_TIERS,
8722
9152
  DEFAULT_PROVIDER_REFUSED_MESSAGE,
8723
9153
  EMPTY_RESPONSE_NUDGE,
@@ -8738,6 +9168,8 @@ function withFreshMetaSnapshot(stored, fresh) {
8738
9168
  UNROUTABLE_PLACEHOLDER,
8739
9169
  addUsage,
8740
9170
  agenticActivityBus,
9171
+ aiServiceAccessRefusalOf,
9172
+ aiServiceErrorCodeOf,
8741
9173
  anthropicRatesFor,
8742
9174
  anthropicTokenCost,
8743
9175
  assembleDebugLog,
@@ -8751,6 +9183,7 @@ function withFreshMetaSnapshot(stored, fresh) {
8751
9183
  geminiTokenCost,
8752
9184
  getMetaEvents,
8753
9185
  isObservableAIProviderRegistry,
9186
+ isTerminalAIServiceRefusal,
8754
9187
  messageUsage,
8755
9188
  resolveAITiers,
8756
9189
  restoreMachine,