@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
@@ -1504,6 +1504,98 @@ function abortableDelay(ms, signal) {
1504
1504
  });
1505
1505
  }
1506
1506
 
1507
+ // ../../foundation-ai/dist/esm/transports/ai-service-error.js
1508
+ var AI_SERVICE_ERROR_CODES = Object.freeze({
1509
+ /** No API key is configured for the vendor. */
1510
+ NO_API_KEY: "NO_API_KEY",
1511
+ /** The configured key has characters an API key cannot have. */
1512
+ BAD_API_KEY: "BAD_API_KEY",
1513
+ /** An encrypted key could not be decrypted. */
1514
+ KEY_UNREADABLE: "KEY_UNREADABLE",
1515
+ /** The request asked for a model the service does not allow. */
1516
+ MODEL_NOT_ALLOWED: "MODEL_NOT_ALLOWED",
1517
+ /** The service refused the shape of the request. */
1518
+ BAD_REQUEST: "BAD_REQUEST",
1519
+ /** The request named fallback models, which the service does not accept. */
1520
+ FALLBACKS_NOT_SUPPORTED: "FALLBACKS_NOT_SUPPORTED",
1521
+ /** The request body is larger, or nested deeper, than the service accepts. */
1522
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
1523
+ /** The service could not reach the vendor. The only code that is worth retrying. */
1524
+ VENDOR_UNREACHABLE: "VENDOR_UNREACHABLE"
1525
+ });
1526
+ var KNOWN_CODES = new Set(Object.values(AI_SERVICE_ERROR_CODES));
1527
+ function aiServiceErrorCodeOf(code) {
1528
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : void 0;
1529
+ }
1530
+ var AI_SERVICE_ACCESS_REFUSALS = Object.freeze({
1531
+ /** 401: the request had no session. */
1532
+ SIGNED_OUT: "SIGNED_OUT",
1533
+ /** 403: the user lacks the right the endpoint demands. */
1534
+ ACCESS_DENIED: "ACCESS_DENIED"
1535
+ });
1536
+ var UNAUTHORIZED_STATUS = 401;
1537
+ var FORBIDDEN_STATUS = 403;
1538
+ var PAYLOAD_TOO_LARGE_STATUS = 413;
1539
+ var isRouterNack = (payload) => {
1540
+ if (!payload || typeof payload !== "object")
1541
+ return false;
1542
+ const { MESSAGE_TYPE, ERROR } = payload;
1543
+ return MESSAGE_TYPE === "MSG_NACK" || Array.isArray(ERROR);
1544
+ };
1545
+ var hasCode = (payload) => (payload === null || payload === void 0 ? void 0 : payload.code) !== void 0;
1546
+ function aiServiceAccessRefusalOf(status, payload, bodyText) {
1547
+ if (status !== UNAUTHORIZED_STATUS && status !== FORBIDDEN_STATUS)
1548
+ return void 0;
1549
+ if (hasCode(payload))
1550
+ return void 0;
1551
+ const emptyBody = typeof bodyText === "string" && bodyText.trim() === "";
1552
+ if (!isRouterNack(payload) && !emptyBody)
1553
+ return void 0;
1554
+ return status === UNAUTHORIZED_STATUS ? AI_SERVICE_ACCESS_REFUSALS.SIGNED_OUT : AI_SERVICE_ACCESS_REFUSALS.ACCESS_DENIED;
1555
+ }
1556
+ function isUncodedTooLarge(status, payload) {
1557
+ return status === PAYLOAD_TOO_LARGE_STATUS && payload === void 0;
1558
+ }
1559
+ function routerRefusalDetailOf(payload) {
1560
+ var _a;
1561
+ const errors = payload === null || payload === void 0 ? void 0 : payload.ERROR;
1562
+ const text = Array.isArray(errors) ? (_a = errors[0]) === null || _a === void 0 ? void 0 : _a.TEXT : void 0;
1563
+ return typeof text === "string" && text ? text : void 0;
1564
+ }
1565
+ var REFUSED_REQUEST = "The AI service refused the assistant's request. An administrator can find the details in the browser console.";
1566
+ var DEFAULT_AI_SERVICE_ERROR_MESSAGES = Object.freeze({
1567
+ NO_API_KEY: "The assistant isn't set up yet. An administrator needs to add an API key for its AI service.",
1568
+ BAD_API_KEY: "The assistant can't use its AI service key. An administrator needs to check the key.",
1569
+ KEY_UNREADABLE: "The assistant can't read its AI service key. An administrator needs to check how the key is stored.",
1570
+ 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.",
1571
+ BAD_REQUEST: REFUSED_REQUEST,
1572
+ // The assistant never sends fallbacks, so only a mismatched client can meet this one.
1573
+ FALLBACKS_NOT_SUPPORTED: REFUSED_REQUEST,
1574
+ 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.",
1575
+ 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.",
1576
+ SIGNED_OUT: "Your session has ended. Sign in again to use the assistant.",
1577
+ ACCESS_DENIED: "You don't have access to the assistant. An administrator can give you access."
1578
+ });
1579
+ var isTerminalAIServiceRefusal = (code) => code !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE;
1580
+ var AIServiceError = class extends Error {
1581
+ constructor(vendorLabel, code, status, detail) {
1582
+ super(`${vendorLabel} AI service refused the request (${status} ${code})`);
1583
+ this.vendorLabel = vendorLabel;
1584
+ this.code = code;
1585
+ this.status = status;
1586
+ this.detail = detail;
1587
+ this.name = "AIServiceError";
1588
+ }
1589
+ /** Whether sending the request again cannot help. */
1590
+ get terminal() {
1591
+ return isTerminalAIServiceRefusal(this.code);
1592
+ }
1593
+ };
1594
+ function aiServiceDetailOf(payload) {
1595
+ const error = payload === null || payload === void 0 ? void 0 : payload.error;
1596
+ return typeof error === "string" && error ? error : void 0;
1597
+ }
1598
+
1507
1599
  // ../../foundation-ai/dist/esm/transports/context-overflow-error.js
1508
1600
  var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
1509
1601
  /prompt is too long/i,
@@ -1687,9 +1779,13 @@ function serverBackoffSpentMs(resolvedMs, ladderMs) {
1687
1779
  var MAX_RETRIES = 5;
1688
1780
  function postWithRetry(options) {
1689
1781
  return __awaiter(this, void 0, void 0, function* () {
1690
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1782
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1691
1783
  const { url, headers, body, credentials, vendorLabel, retryableStatuses, timeout, stallTimeout, backoffBaseMs, signal } = options;
1692
1784
  const vendor = vendorOfTransportLabel(vendorLabel);
1785
+ const serviceRefusal = (code, status, detail) => {
1786
+ logger.error(`${vendorLabel}Transport: the AI service refused the request (${status} ${code})${detail ? `: ${detail}` : ""}`);
1787
+ return new AIServiceError(vendorLabel, code, status, detail);
1788
+ };
1693
1789
  let serverBackoffSpent = 0;
1694
1790
  const backoff = (attempt, serverMs) => {
1695
1791
  const ladderMs = backoffBaseMs * Math.pow(2, attempt);
@@ -1747,6 +1843,17 @@ function postWithRetry(options) {
1747
1843
  if (isBudgetRejection(response.status, codeOf(parsed))) {
1748
1844
  throw budgetExhaustedFrom(vendorLabel, parsed, errText || void 0);
1749
1845
  }
1846
+ const serviceCode = aiServiceErrorCodeOf(codeOf(parsed));
1847
+ if (serviceCode && serviceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1848
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1849
+ }
1850
+ const accessRefusal = aiServiceAccessRefusalOf(response.status, parsed, errText);
1851
+ if (accessRefusal) {
1852
+ throw serviceRefusal(accessRefusal, response.status, (_e = routerRefusalDetailOf(parsed)) !== null && _e !== void 0 ? _e : errText || void 0);
1853
+ }
1854
+ if (isUncodedTooLarge(response.status, parsed)) {
1855
+ throw serviceRefusal(AI_SERVICE_ERROR_CODES.REQUEST_TOO_LARGE, response.status, errText || void 0);
1856
+ }
1750
1857
  const refusedRetry = shouldNotRetry(response.headers);
1751
1858
  if (retryableStatuses.includes(response.status) && !refusedRetry && attempt < MAX_RETRIES) {
1752
1859
  logger.warn(`${vendorLabel}Transport: retryable status ${response.status}, retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
@@ -1754,15 +1861,18 @@ function postWithRetry(options) {
1754
1861
  yield backoff(attempt, retryAfterMs(response.headers) || retryInfoMs(parsed));
1755
1862
  continue;
1756
1863
  }
1864
+ if (serviceCode) {
1865
+ throw serviceRefusal(serviceCode, response.status, aiServiceDetailOf(parsed));
1866
+ }
1757
1867
  throw new Error(`${vendorLabel} request error ${response.status}: ${errText}`);
1758
1868
  }
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) {
1869
+ 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
1870
  rearmStallTimer();
1761
1871
  const frame = yield readFramedBody(response.body, rearmStallTimer, vendorLabel, stallTimeout);
1762
1872
  if (frame.t === "ok")
1763
1873
  return frame.body;
1764
1874
  if (frame.code === "UPSTREAM_STALLED") {
1765
- throw new DOMException(`${vendorLabel} request stalled: ${(_g = frame.error) !== null && _g !== void 0 ? _g : "no upstream data"}`, "TimeoutError");
1875
+ throw new DOMException(`${vendorLabel} request stalled: ${(_h = frame.error) !== null && _h !== void 0 ? _h : "no upstream data"}`, "TimeoutError");
1766
1876
  }
1767
1877
  const framedRefusal = providerRefusalOf(vendor, frame.code, frame);
1768
1878
  if (framedRefusal) {
@@ -1770,18 +1880,25 @@ function postWithRetry(options) {
1770
1880
  }
1771
1881
  const framedOverflow = contextOverflowOf(vendor, frame.status, frame);
1772
1882
  if (framedOverflow) {
1773
- throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_h = framedOverflow.message) !== null && _h !== void 0 ? _h : frame.error);
1883
+ throw new ContextOverflowError(vendorLabel, framedOverflow.promptTokens, framedOverflow.limitTokens, (_j = framedOverflow.message) !== null && _j !== void 0 ? _j : frame.error);
1774
1884
  }
1775
1885
  if (isBudgetRejection(frame.status, frame.code)) {
1776
1886
  throw budgetExhaustedFrom(vendorLabel, frame);
1777
1887
  }
1888
+ const framedServiceCode = aiServiceErrorCodeOf(frame.code);
1889
+ if (framedServiceCode && framedServiceCode !== AI_SERVICE_ERROR_CODES.VENDOR_UNREACHABLE) {
1890
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
1891
+ }
1778
1892
  if (retryableStatuses.includes(frame.status) && attempt < MAX_RETRIES) {
1779
1893
  logger.warn(`${vendorLabel}Transport: retryable status ${frame.status} (err frame), retrying (attempt ${attempt + 1}/${MAX_RETRIES})`);
1780
1894
  clearTimeout(timeoutId);
1781
1895
  yield backoff(attempt, retryInfoMs(frame));
1782
1896
  continue;
1783
1897
  }
1784
- throw new Error(`${vendorLabel} request error ${frame.status}: ${(_j = frame.error) !== null && _j !== void 0 ? _j : JSON.stringify(frame.details)}`);
1898
+ if (framedServiceCode) {
1899
+ throw serviceRefusal(framedServiceCode, frame.status, aiServiceDetailOf(frame));
1900
+ }
1901
+ throw new Error(`${vendorLabel} request error ${frame.status}: ${(_k = frame.error) !== null && _k !== void 0 ? _k : JSON.stringify(frame.details)}`);
1785
1902
  }
1786
1903
  return yield response.json();
1787
1904
  } catch (e) {
@@ -3798,80 +3915,6 @@ function clearSession(key) {
3798
3915
  registry.delete(key);
3799
3916
  }
3800
3917
 
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
3918
  // src/utils/context-tokens.ts
3876
3919
  var APPROX_CHARS_PER_TOKEN = 4;
3877
3920
  var IMAGE_TOKEN_ESTIMATE = 1600;
@@ -4005,6 +4048,80 @@ function projectCompaction(history, cut, summaryTokens = COMPACTION_SUMMARY_TOKE
4005
4048
  };
4006
4049
  }
4007
4050
 
4051
+ // src/utils/logger.ts
4052
+ var logger2 = createLogger("ai-assistant");
4053
+
4054
+ // src/suggestions/generate-suggestions.ts
4055
+ var HISTORY_WINDOW = 8;
4056
+ function capabilities(ctx, allAgentInfo) {
4057
+ let agentContext = "";
4058
+ let toolContext = "";
4059
+ if (allAgentInfo?.length) {
4060
+ const agentDescriptions = allAgentInfo.map((agent) => {
4061
+ const tools = agent.tools.map((t) => t.name).join(", ");
4062
+ return `- ${agent.name} (${agent.description}): ${tools ? `(Tools: ${tools})` : "No tools"}`;
4063
+ }).join("\n");
4064
+ agentContext = `The assistant has the following capabilities:
4065
+ ${agentDescriptions}`;
4066
+ const allToolNames = [
4067
+ ...new Set(allAgentInfo.flatMap((agent) => agent.tools.map((t) => t.name)))
4068
+ ].join(", ");
4069
+ toolContext = allToolNames ? `You have access to the following tools across all agents: ${allToolNames}.` : "";
4070
+ } else if (ctx.activeAgentName) {
4071
+ const toolNames = ctx.toolDefinitions.map((tool) => tool.name).join(", ");
4072
+ agentContext = `You are currently acting as the "${ctx.activeAgentName}" agent.`;
4073
+ toolContext = toolNames ? `You have access to the following tools: ${toolNames}.` : "";
4074
+ }
4075
+ return agentContext || toolContext ? `
4076
+
4077
+ <capabilities>
4078
+ ${[agentContext, toolContext].filter(Boolean).join(
4079
+ "\n"
4080
+ )}
4081
+ </capabilities>
4082
+ Suggestions must only cover what the agent is capable of. Do not suggest anything outside these capabilities.` : "";
4083
+ }
4084
+ var OUTPUT_FORMAT = (count) => `
4085
+
4086
+ Output format (strict):
4087
+ - Exactly ${count} lines.
4088
+ - One suggestion per line.
4089
+ - No numbering, bullets, markdown, emojis, code blocks, or quotes around the suggestion.
4090
+ - No preamble, headings, summary, or commentary before or after the list.`;
4091
+ 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.";
4092
+ function buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo) {
4093
+ const capabilitiesBlock = capabilities(ctx, allAgentInfo);
4094
+ const guidanceBlock = prompt2 ? `
4095
+
4096
+ Additional guidance: "${prompt2}"` : "";
4097
+ if (history.length === 0) {
4098
+ 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);
4099
+ }
4100
+ const conversationContext = history.filter(
4101
+ (m) => reachesProvider(m) && (m.role === "user" || m.role === "assistant") && !m.toolCalls?.length && !m.thinking && !!m.content?.trim()
4102
+ ).slice(-HISTORY_WINDOW).map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
4103
+ return `<conversation_history>
4104
+ ${conversationContext}
4105
+ </conversation_history>
4106
+
4107
+ 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);
4108
+ }
4109
+ function parseSuggestions(text, count) {
4110
+ 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);
4111
+ }
4112
+ async function generateSuggestions(ctx, history, prompt2, count, allAgentInfo) {
4113
+ const defaultProvider = ctx.registry.default();
4114
+ if (!defaultProvider.prompt) {
4115
+ logger2.warn("ChatDriver: default AI provider does not implement prompt()");
4116
+ return [];
4117
+ }
4118
+ const userMessage = buildSuggestionsPrompt(ctx, history, prompt2, count, allAgentInfo);
4119
+ const text = await defaultProvider.prompt(userMessage, {
4120
+ systemPrompt: SUGGESTIONS_SYSTEM_PROMPT
4121
+ });
4122
+ return parseSuggestions(text, count);
4123
+ }
4124
+
4008
4125
  // src/utils/condense-history.ts
4009
4126
  var CONDENSE_MIN_CHARS = 1e3;
4010
4127
  var CONDENSED_ARGS_KEY = "condensed";
@@ -4393,7 +4510,7 @@ function renderMessageForSummary(m) {
4393
4510
  }
4394
4511
  }
4395
4512
  function buildCompactionSummaryPrompt(toCompact) {
4396
- const transcript = toCompact.map(renderMessageForSummary).filter(Boolean).join("\n");
4513
+ const transcript = toCompact.filter((m) => !m.excludeFromProvider).map(renderMessageForSummary).filter(Boolean).join("\n");
4397
4514
  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
4515
  const userMessage = `<conversation_history>
4399
4516
  ${transcript}
@@ -4911,6 +5028,10 @@ function createInteractionContext(interactionId) {
4911
5028
  }
4912
5029
 
4913
5030
  // src/components/chat-driver/interaction-controller.ts
5031
+ var STOPPED = {
5032
+ status: "timeout",
5033
+ message: "The turn was stopped before this was answered."
5034
+ };
4914
5035
  var InteractionController = class {
4915
5036
  constructor(deps) {
4916
5037
  this.deps = deps;
@@ -4983,6 +5104,19 @@ var InteractionController = class {
4983
5104
  ...presentation ? { presentation } : {}
4984
5105
  }
4985
5106
  });
5107
+ const signal = options?.signal;
5108
+ if (signal) {
5109
+ const onAbort = () => this.resolve(interactionId, STOPPED);
5110
+ if (signal.aborted) {
5111
+ onAbort();
5112
+ } else {
5113
+ signal.addEventListener("abort", onAbort, { once: true });
5114
+ const pending = this.pending.get(interactionId);
5115
+ if (pending) {
5116
+ pending.unlinkSignal = () => signal.removeEventListener("abort", onAbort);
5117
+ }
5118
+ }
5119
+ }
4986
5120
  });
4987
5121
  }
4988
5122
  /**
@@ -4996,6 +5130,7 @@ var InteractionController = class {
4996
5130
  return;
4997
5131
  }
4998
5132
  if (interaction.timeoutHandle) clearTimeout(interaction.timeoutHandle);
5133
+ interaction.unlinkSignal?.();
4999
5134
  this.deps.foldDiagnostics(
5000
5135
  interactionId,
5001
5136
  result?.diagnostics
@@ -5156,6 +5291,13 @@ var TURN_FAILURE_EXITS = {
5156
5291
  // Overridden per wall by `ChatDriver.budgetExhaustedBubble`, which upgrades this with
5157
5292
  // "switch to another AI" when a second vendor is reachable.
5158
5293
  copy: DEFAULT_BUDGET_EXHAUSTED_MESSAGE
5294
+ },
5295
+ aiServiceError: {
5296
+ subReason: "ai_service_error",
5297
+ resultReason: "ai-service-error",
5298
+ // Replaced per code by `ChatDriver.aiServiceErrorBubble`; this is only what a parent says when
5299
+ // a child's failure arrives without its code.
5300
+ copy: DEFAULT_AI_SERVICE_ERROR_MESSAGES.BAD_REQUEST
5159
5301
  }
5160
5302
  // `satisfies`, not an annotation: an annotation would widen `resultReason` to
5161
5303
  // `TurnFailureReason` and cost the literal types that let `turn-failures.test.ts` pin the
@@ -5326,6 +5468,19 @@ var TurnRecorder = class {
5326
5468
  };
5327
5469
 
5328
5470
  // src/components/chat-driver/chat-driver.ts
5471
+ var REQUEST_SCOPED_REFUSALS = /* @__PURE__ */ new Set([
5472
+ "REQUEST_TOO_LARGE",
5473
+ "BAD_REQUEST",
5474
+ "FALLBACKS_NOT_SUPPORTED"
5475
+ ]);
5476
+ var SERVICE_WIDE_REFUSALS = /* @__PURE__ */ new Set([
5477
+ "NO_API_KEY",
5478
+ "BAD_API_KEY",
5479
+ "KEY_UNREADABLE",
5480
+ "SIGNED_OUT",
5481
+ "ACCESS_DENIED",
5482
+ "VENDOR_UNREACHABLE"
5483
+ ]);
5329
5484
  var toolResultImages = (result) => {
5330
5485
  if (!result || typeof result !== "object") return void 0;
5331
5486
  const candidate = result.attachments;
@@ -5354,6 +5509,15 @@ var budgetDetailOf = (e) => {
5354
5509
  ...e.otherVendorAvailable != null ? { otherVendorAvailable: e.otherVendorAvailable } : {}
5355
5510
  };
5356
5511
  };
5512
+ function inFlightToolCallsAt(history) {
5513
+ for (let i = history.length - 1; i >= 0; i -= 1) {
5514
+ const message = history[i];
5515
+ if (message.role !== "assistant" || !message.toolCalls?.length) continue;
5516
+ const answered = new Set(history.slice(i + 1).map((later) => later.toolResult?.toolCallId));
5517
+ return message.toolCalls.some((call) => !answered.has(call.id)) ? i : history.length;
5518
+ }
5519
+ return history.length;
5520
+ }
5357
5521
  var ChatDriver = class _ChatDriver extends EventTarget {
5358
5522
  constructor(providerRegistry, config = {}) {
5359
5523
  super();
@@ -5499,6 +5663,17 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5499
5663
  this.turnController = new AbortController();
5500
5664
  /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
5501
5665
  this.turnCancelled = false;
5666
+ /**
5667
+ * The scope tool handlers see as `turnSignal`: one USER MESSAGE. Minted by `sendMessage`, so a
5668
+ * handoff's `continueFromHistory` — a new `turnController`, but the same message — keeps it,
5669
+ * and a sub-agent inherits it (`inheritedTurnSignal`). Aborted by `cancel()` and by a dispose.
5670
+ * `continueFromHistory` mints one only when the message it would continue was stopped.
5671
+ *
5672
+ * Kept apart from `turnController`, which is per REQUEST and restarts on every continuation: a
5673
+ * handler that remembers something "for the rest of the turn" (the write tools' deny lock) keyed
5674
+ * on that one was reset by every handoff inside a single message.
5675
+ */
5676
+ this.messageController = new AbortController();
5502
5677
  /**
5503
5678
  * Caches validated provider lookups per name within the current agent. Cleared
5504
5679
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -5535,6 +5710,20 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5535
5710
  * children costing N doomed calls plus a doomed parent one.
5536
5711
  */
5537
5712
  this.providerRefusedThisTurn = false;
5713
+ /**
5714
+ * A sub-agent was refused by the AI service this turn in a way that stops this driver too
5715
+ * (GENC-1611): a service-wide code, from the vendor this driver calls. Sub-agent path only, like
5716
+ * `providerRefusedThisTurn`; this driver's own refusal returns straight out of the catch.
5717
+ */
5718
+ this.aiServiceErrorThisTurn = false;
5719
+ /** Codes a child's refusal was already shown for during this user message. */
5720
+ this.aiServiceNoticesShown = /* @__PURE__ */ new Set();
5721
+ /**
5722
+ * Notices waiting for the tool batch to end. Written mid-batch they would sit between the
5723
+ * assistant's tool calls and their results, where a later sub-agent's primer would pick up the
5724
+ * unanswered calls.
5725
+ */
5726
+ this.aiServiceNoticesQueued = [];
5538
5727
  /**
5539
5728
  * Set the moment a budget wall is observed anywhere in this turn — this
5540
5729
  * driver's own 402, or a sub-agent's (which surfaces here only as a
@@ -5564,7 +5753,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5564
5753
  deferAgentRelease = false,
5565
5754
  activityBus = NOOP_ACTIVITY_BUS,
5566
5755
  budgetExhaustedMessage,
5567
- providerRefusedMessage
5756
+ providerRefusedMessage,
5757
+ aiServiceErrorMessages
5568
5758
  } = config;
5569
5759
  this.maxToolIterations = maxToolIterations;
5570
5760
  this.condenseBatchCalls = condenseBatchCalls;
@@ -5573,6 +5763,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5573
5763
  this.activityBus = activityBus;
5574
5764
  this.budgetExhaustedMessageOverride = budgetExhaustedMessage;
5575
5765
  this.providerRefusedMessageOverride = providerRefusedMessage;
5766
+ this.aiServiceErrorMessagesOverride = aiServiceErrorMessages;
5576
5767
  if (typeof toolHandlers === "function") {
5577
5768
  this.toolHandlersFactory = toolHandlers;
5578
5769
  this.toolHandlers = {};
@@ -5637,14 +5828,43 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5637
5828
  /**
5638
5829
  * Stop the current turn (user "stop" button). Aborts the in-flight provider
5639
5830
  * 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.
5831
+ * the loop bails at the next boundary (tools are atomic). When idle it only ends
5832
+ * the message (see below) and appends nothing. The driver stays usable for the
5833
+ * next message.
5642
5834
  */
5643
5835
  cancel() {
5836
+ this.messageController.abort(new DOMException("Cancelled by user", "AbortError"));
5644
5837
  if (!this.busy) return;
5645
5838
  this.turnCancelled = true;
5646
5839
  this.turnController.abort(new DOMException("Cancelled by user", "AbortError"));
5647
5840
  }
5841
+ /**
5842
+ * Start a fresh per-MESSAGE scope for tool handlers (see `messageController`). Chained to
5843
+ * `lifecycleController` so a dispose aborts it; the link lives until the next message, because
5844
+ * a handoff continues this one.
5845
+ */
5846
+ beginMessage() {
5847
+ this.unlinkLifecycleFromMessage?.();
5848
+ this.messageController = new AbortController();
5849
+ const lifecycle = this.lifecycleController.signal;
5850
+ if (lifecycle.aborted) {
5851
+ this.messageController.abort(lifecycle.reason);
5852
+ this.unlinkLifecycleFromMessage = void 0;
5853
+ return;
5854
+ }
5855
+ const onDispose = () => this.messageController.abort(lifecycle.reason);
5856
+ lifecycle.addEventListener("abort", onDispose, { once: true });
5857
+ this.unlinkLifecycleFromMessage = () => lifecycle.removeEventListener("abort", onDispose);
5858
+ }
5859
+ /**
5860
+ * Makes this (sub-agent) driver's handlers see the parent message's `turnSignal` instead of one
5861
+ * of their own: a delegation is part of the message that made it.
5862
+ *
5863
+ * @internal
5864
+ */
5865
+ inheritTurnSignal(signal) {
5866
+ this.inheritedTurnSignal = signal;
5867
+ }
5648
5868
  /**
5649
5869
  * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
5650
5870
  * new `turnController` so a dispose mid-turn also aborts the request.
@@ -5702,8 +5922,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5702
5922
  */
5703
5923
  endTurnWithFailure(exit, overrides) {
5704
5924
  if (this.isSubAgent) {
5705
- this.failSubAgent(exit.subReason, overrides?.budget, overrides?.providerRefused);
5706
- } else {
5925
+ this.failSubAgent(
5926
+ exit.subReason,
5927
+ overrides?.budget,
5928
+ overrides?.providerRefused,
5929
+ overrides?.aiServiceError
5930
+ );
5931
+ } else if (!overrides?.silent) {
5707
5932
  this.appendDriverNotice(overrides?.copy ?? exit.copy);
5708
5933
  }
5709
5934
  return turnDone(exit.resultReason, overrides?.budget, overrides?.providerRefused);
@@ -5740,6 +5965,19 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5740
5965
  const subject = wall?.vendorLabel ? `${wall.vendorLabel}'s AI usage limit` : "your AI usage limit";
5741
5966
  return `You've reached ${subject}. Switch to another AI provider in Settings to keep going, or contact your administrator to raise it.`;
5742
5967
  }
5968
+ /**
5969
+ * Record a message the user sent and then stopped before any turn took it: during an
5970
+ * orchestrator's first classify, or its first agent's install. Only an optimistic
5971
+ * `history-updated` had shown it, so it vanished on the next update, and from a reload. Appended
5972
+ * here with the "Stopped." marker a stopped turn leaves, as `reportBudgetExhausted` appends a
5973
+ * message the budget wall kept from its turn.
5974
+ *
5975
+ * @internal
5976
+ */
5977
+ reportStoppedBeforeTurn(userMessage) {
5978
+ this.appendToHistory(userMessage);
5979
+ this.appendToHistory({ role: "system-event", content: "Stopped." });
5980
+ }
5743
5981
  reportBudgetExhausted(e, pendingUserMessage) {
5744
5982
  if (pendingUserMessage) this.appendToHistory(pendingUserMessage);
5745
5983
  this.budgetExhaustedThisTurn = true;
@@ -5772,6 +6010,158 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5772
6010
  providerRefusedBubble() {
5773
6011
  return this.providerRefusedMessageOverride ?? TURN_FAILURE_EXITS.providerRefused.copy;
5774
6012
  }
6013
+ /**
6014
+ * A terminal AI service error hit **outside** the tool loop — `OrchestratingDriver`'s classification
6015
+ * phase (GENC-1611). The same log line, debug-log entry, sentence and result as the in-loop branch.
6016
+ *
6017
+ * @param pendingUserMessage - the user's message when it has NOT been appended yet, for the reason
6018
+ * `reportBudgetExhausted` gives.
6019
+ */
6020
+ reportAIServiceError(e, pendingUserMessage) {
6021
+ if (pendingUserMessage) {
6022
+ this.aiServiceNoticesShown.clear();
6023
+ this.aiServiceNoticesQueued = [];
6024
+ this.appendToHistory(pendingUserMessage);
6025
+ }
6026
+ return this.endTurnWithAIServiceError(e);
6027
+ }
6028
+ /**
6029
+ * The sentence for an AI service error code (GENC-1611): the host's override, else the default.
6030
+ * Never the service's own text, which goes to the console only.
6031
+ */
6032
+ aiServiceErrorBubble(code) {
6033
+ if (!code) return TURN_FAILURE_EXITS.aiServiceError.copy;
6034
+ const override = this.aiServiceErrorMessagesOverride?.[code];
6035
+ return override?.trim() ? override : DEFAULT_AI_SERVICE_ERROR_MESSAGES[code];
6036
+ }
6037
+ /**
6038
+ * Shows a sub-agent's AI-service refusal that the turn went on without, once per code in a user
6039
+ * message: the user's sentence with the host's overrides, never the service's text. A sub-agent
6040
+ * passes it up to the driver the user sees.
6041
+ */
6042
+ noticeAIServiceRefusal(code) {
6043
+ if (REQUEST_SCOPED_REFUSALS.has(code)) return;
6044
+ if (this.hostAIServiceNotice) {
6045
+ this.hostAIServiceNotice(code);
6046
+ return;
6047
+ }
6048
+ if (!this.busy) return;
6049
+ if (this.aiServiceNoticesShown.has(code) || this.aiServiceNoticesQueued.includes(code)) return;
6050
+ this.aiServiceNoticesQueued.push(code);
6051
+ }
6052
+ /**
6053
+ * Writes the notices queued during a tool batch, once its results are in the history, or before
6054
+ * the failure when the batch threw. A code counts as shown only once written.
6055
+ */
6056
+ flushAIServiceNotices() {
6057
+ const codes = this.aiServiceNoticesQueued;
6058
+ this.aiServiceNoticesQueued = [];
6059
+ for (const code of codes) {
6060
+ this.aiServiceNoticesShown.add(code);
6061
+ this.appendDriverNotice(this.aiServiceErrorBubble(code));
6062
+ }
6063
+ }
6064
+ /** Ends the turn on an AI service error: logged with the service's text, shown without it. */
6065
+ endTurnWithAIServiceError(e) {
6066
+ logger2.error("ChatDriver: the AI service refused the request", e, e.detail ?? "");
6067
+ recordTurnError(this.sessionKey, "ai-service-error", {
6068
+ agent: this.activeAgentName,
6069
+ provider: this.lastResolvedProviderName,
6070
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider,
6071
+ code: e.code,
6072
+ status: e.status,
6073
+ isSubAgent: this.isSubAgent
6074
+ });
6075
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6076
+ copy: this.aiServiceErrorBubble(e.code),
6077
+ aiServiceError: {
6078
+ code: e.code,
6079
+ vendor: vendorTypeOfLabel(e.vendorLabel) ?? this.lastResolvedProvider
6080
+ },
6081
+ silent: this.aiServiceSentenceShown(e.code)
6082
+ });
6083
+ }
6084
+ /**
6085
+ * Whether this user message already showed the sentence for `code`, so a turn-ending failure
6086
+ * does not show it twice. Marks it shown otherwise. Only the driver the user sees keeps count.
6087
+ */
6088
+ aiServiceSentenceShown(code) {
6089
+ if (this.isSubAgent || !code) return false;
6090
+ if (this.aiServiceNoticesShown.has(code)) return true;
6091
+ this.aiServiceNoticesShown.add(code);
6092
+ return false;
6093
+ }
6094
+ /**
6095
+ * Whether a sub-agent hit a wall this turn that stops this driver too. A handoff goes on past an
6096
+ * AI-service wall: the next agent may use another vendor, and if it uses this one its own call
6097
+ * meets the wall and says so.
6098
+ */
6099
+ subAgentWallThisTurn(handingOff = false) {
6100
+ return this.providerRefusedThisTurn || this.budgetExhaustedThisTurn || this.aiServiceErrorThisTurn && !handingOff;
6101
+ }
6102
+ /**
6103
+ * Ends the turn when a sub-agent hit a wall this turn that stops this driver too: the provider
6104
+ * refusing the account, the AI service (GENC-1611), or the budget. Checked before each model call,
6105
+ * and again right after a tool batch, before a handoff or the iteration cap can report the turn as
6106
+ * something else.
6107
+ */
6108
+ endTurnOnSubAgentWall() {
6109
+ if (!this.subAgentWallThisTurn()) return void 0;
6110
+ this.subAgentCompletion = void 0;
6111
+ if (this.providerRefusedThisTurn) {
6112
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the provider wall");
6113
+ recordTurnError(this.sessionKey, "provider-refused", {
6114
+ agent: this.activeAgentName,
6115
+ provider: this.lastResolvedProviderName,
6116
+ kind: this.providerRefusedDetail?.kind,
6117
+ via: "sub-agent",
6118
+ isSubAgent: this.isSubAgent
6119
+ });
6120
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
6121
+ copy: this.providerRefusedBubble(),
6122
+ providerRefused: this.providerRefusedDetail
6123
+ });
6124
+ }
6125
+ if (this.aiServiceErrorThisTurn) {
6126
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent was refused by the AI service");
6127
+ recordTurnError(this.sessionKey, "ai-service-error", {
6128
+ agent: this.activeAgentName,
6129
+ provider: this.lastResolvedProviderName,
6130
+ code: this.aiServiceWall?.code,
6131
+ via: "sub-agent",
6132
+ isSubAgent: this.isSubAgent
6133
+ });
6134
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
6135
+ copy: this.aiServiceErrorBubble(this.aiServiceWall?.code),
6136
+ aiServiceError: this.aiServiceWall,
6137
+ silent: this.aiServiceSentenceShown(this.aiServiceWall?.code)
6138
+ });
6139
+ }
6140
+ if (this.budgetExhaustedThisTurn) {
6141
+ logger2.error("ChatDriver: ending the turn \u2014 a sub-agent hit the AI budget wall");
6142
+ recordTurnError(this.sessionKey, "budget-exhausted", {
6143
+ agent: this.activeAgentName,
6144
+ provider: this.lastResolvedProviderName,
6145
+ // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
6146
+ // path the wall is definitionally the child's, and on a mixed registry
6147
+ // `lastResolvedProvider` is this driver's own vendor — the one known
6148
+ // NOT to have refused. An unattributable child wall must degrade to
6149
+ // the vendor-agnostic block (which `latchBlockedFrom` handles
6150
+ // fail-safe), never to a vendor that is known to be wrong: naming the
6151
+ // parent's vendor here walled BOTH — the child's via its own
6152
+ // tool-loop-end, the parent's via this event — and derived `blocked`
6153
+ // over headroom that still existed.
6154
+ vendor: this.budgetWallDetail?.vendor,
6155
+ via: "sub-agent",
6156
+ isSubAgent: this.isSubAgent
6157
+ });
6158
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
6159
+ copy: this.budgetExhaustedBubble(this.budgetWallDetail),
6160
+ budget: this.budgetWallDetail
6161
+ });
6162
+ }
6163
+ return void 0;
6164
+ }
5775
6165
  /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
5776
6166
  static failureReasonOf(result) {
5777
6167
  return result.reason === "done" ? result.failureReason : void 0;
@@ -6052,12 +6442,13 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6052
6442
  * under a separate session key, so recording here would orphan the event off
6053
6443
  * the user-visible debug-log timeline.)
6054
6444
  */
6055
- failSubAgent(reason, budget, providerRefused) {
6445
+ failSubAgent(reason, budget, providerRefused, aiServiceError) {
6056
6446
  if (!this.isSubAgent || this.subAgentFailure) return;
6057
6447
  this.subAgentFailure = {
6058
6448
  reason,
6059
6449
  ...budget ? { budget } : {},
6060
- ...providerRefused ? { providerRefused } : {}
6450
+ ...providerRefused ? { providerRefused } : {},
6451
+ ...aiServiceError ? { aiServiceError } : {}
6061
6452
  };
6062
6453
  }
6063
6454
  /**
@@ -6488,6 +6879,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6488
6879
  if (this.busy || !userInput.trim() && !attachments?.length) return { reason: "done" };
6489
6880
  this.busy = true;
6490
6881
  this.beginTurn();
6882
+ this.beginMessage();
6491
6883
  this.turnSeq += 1;
6492
6884
  this.subAgentCompletion = void 0;
6493
6885
  this.subAgentFailure = void 0;
@@ -6497,6 +6889,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6497
6889
  this.budgetWallViaSubAgent = false;
6498
6890
  this.providerRefusedThisTurn = false;
6499
6891
  this.providerRefusedDetail = void 0;
6892
+ this.aiServiceErrorThisTurn = false;
6893
+ this.aiServiceWall = void 0;
6894
+ this.aiServiceNoticesShown.clear();
6895
+ this.aiServiceNoticesQueued = [];
6500
6896
  this.appendToHistory({ role: "user", content: userInput, attachments });
6501
6897
  this.turnStartedAt = Date.now();
6502
6898
  recordMetaEvent(this.sessionKey, "turn.start", {
@@ -6517,6 +6913,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6517
6913
  name: e instanceof Error ? e.name : void 0,
6518
6914
  message: e instanceof Error ? e.message : String(e)
6519
6915
  });
6916
+ this.flushAIServiceNotices();
6520
6917
  this.appendDriverNotice(
6521
6918
  "Sorry, something went wrong on my end. Please try again in a moment."
6522
6919
  );
@@ -6561,6 +6958,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6561
6958
  buildHandlerContext(activeToolCallId, traceCapture) {
6562
6959
  return {
6563
6960
  requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options),
6961
+ // The MESSAGE's scope: one object per `sendMessage`, kept across a handoff's continuation
6962
+ // and handed to a sub-agent, and aborted by `cancel()` as well as a dispose. Not the
6963
+ // per-request `turnController`, which every continuation replaces.
6964
+ turnSignal: this.inheritedTurnSignal ?? this.messageController.signal,
6564
6965
  ...this.subAgentsMap.size > 0 && {
6565
6966
  requestSubAgent: (name, options) => this.invokeSubAgent(name, options).then(({ outcome, trace }) => {
6566
6967
  if (traceCapture && trace) traceCapture.traces.push(trace);
@@ -6637,8 +7038,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6637
7038
  );
6638
7039
  }
6639
7040
  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;
7041
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
6642
7042
  const snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
6643
7043
  const contextMessages = context ? [{ role: "user", content: `[Sub-agent context]: ${JSON.stringify(context)}` }] : [];
6644
7044
  const effectivePrimer = [
@@ -6655,6 +7055,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6655
7055
  activityBus: this.activityBus
6656
7056
  });
6657
7057
  child.markAsSubAgent();
7058
+ child.inheritTurnSignal(this.inheritedTurnSignal ?? this.messageController.signal);
6658
7059
  child.setContextGuard(this.contextGuard);
6659
7060
  const disposeChild = () => child.dispose();
6660
7061
  if (this.lifecycleController.signal.aborted) {
@@ -6666,6 +7067,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6666
7067
  child.setHostInteractionRequester(
6667
7068
  (componentName, data, opts) => this.requestInteraction(componentName, data, opts)
6668
7069
  );
7070
+ child.hostAIServiceNotice = (code) => this.noticeAIServiceRefusal(code);
6669
7071
  const forwardTrace = (e) => {
6670
7072
  this.dispatchEvent(
6671
7073
  new CustomEvent("sub-agent-history-updated", {
@@ -6746,6 +7148,28 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6746
7148
  this.providerRefusedThisTurn = true;
6747
7149
  this.providerRefusedDetail ??= failure?.providerRefused;
6748
7150
  }
7151
+ const wall = failure?.aiServiceError;
7152
+ if (reason === "ai_service_error" && wall && SERVICE_WIDE_REFUSALS.has(wall.code) && wall.vendor !== void 0 && wall.vendor === this.lastResolvedProvider) {
7153
+ this.aiServiceErrorThisTurn = true;
7154
+ this.aiServiceWall ??= wall;
7155
+ } else if (reason === "ai_service_error" && wall) {
7156
+ this.noticeAIServiceRefusal(wall.code);
7157
+ }
7158
+ if (reason === "ai_service_error") {
7159
+ if (wall) {
7160
+ return {
7161
+ outcome: {
7162
+ ok: false,
7163
+ reason,
7164
+ code: wall.code,
7165
+ terminal: isTerminalAIServiceRefusal(wall.code)
7166
+ },
7167
+ trace
7168
+ };
7169
+ }
7170
+ logger2.error(`ChatDriver: sub-agent "${name}" was refused by the AI service with no code`);
7171
+ return { outcome: { ok: false, reason: "max_iterations" }, trace };
7172
+ }
6749
7173
  return { outcome: { ok: false, reason }, trace };
6750
7174
  }
6751
7175
  /**
@@ -6755,6 +7179,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6755
7179
  async continueFromHistory(transientPrimer) {
6756
7180
  if (this.busy) return { reason: "done" };
6757
7181
  this.busy = true;
7182
+ if (this.messageController.signal.aborted) this.beginMessage();
6758
7183
  this.beginTurn();
6759
7184
  this.subAgentCompletion = void 0;
6760
7185
  this.subAgentFailure = void 0;
@@ -6763,6 +7188,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6763
7188
  this.budgetWallViaSubAgent = false;
6764
7189
  this.providerRefusedThisTurn = false;
6765
7190
  this.providerRefusedDetail = void 0;
7191
+ this.aiServiceErrorThisTurn = false;
7192
+ this.aiServiceWall = void 0;
6766
7193
  this.turnStartedAt = Date.now();
6767
7194
  recordMetaEvent(this.sessionKey, "turn.start", {
6768
7195
  phase: "continueFromHistory",
@@ -6782,6 +7209,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6782
7209
  name: e instanceof Error ? e.name : void 0,
6783
7210
  message: e instanceof Error ? e.message : String(e)
6784
7211
  });
7212
+ this.flushAIServiceNotices();
6785
7213
  this.appendDriverNotice(
6786
7214
  "Sorry, something went wrong on my end. Please try again in a moment."
6787
7215
  );
@@ -6828,43 +7256,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6828
7256
  if (this.turnController.signal.aborted) {
6829
7257
  return this.completeAbortedTurn();
6830
7258
  }
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
- }
7259
+ const wall = this.endTurnOnSubAgentWall();
7260
+ if (wall) return wall;
6868
7261
  const promptCtx = {
6869
7262
  agentName: this.activeAgentName ?? "",
6870
7263
  history: this.history,
@@ -7110,6 +7503,9 @@ ${tailBody}
7110
7503
  providerRefused: detail
7111
7504
  });
7112
7505
  }
7506
+ if (e instanceof AIServiceError && e.terminal) {
7507
+ return this.endTurnWithAIServiceError(e);
7508
+ }
7113
7509
  if (e instanceof BudgetExhaustedError) {
7114
7510
  this.budgetExhaustedThisTurn = true;
7115
7511
  this.budgetWallDetail = budgetDetailOf(e);
@@ -7151,6 +7547,7 @@ ${tailBody}
7151
7547
  iterations -= 1;
7152
7548
  continue;
7153
7549
  }
7550
+ if (e instanceof AIServiceError) return this.endTurnWithAIServiceError(e);
7154
7551
  throw e;
7155
7552
  }
7156
7553
  if (response.model === void 0 && this.lastResolvedModel !== void 0) {
@@ -7474,6 +7871,7 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7474
7871
  this.history[tcMsgIdx] = { ...tcMsg, toolCalls: annotatedCalls };
7475
7872
  this.notifyHistoryUpdated();
7476
7873
  }
7874
+ this.flushAIServiceNotices();
7477
7875
  if (hitUnknownToolLimit) {
7478
7876
  logger2.error(
7479
7877
  `ChatDriver: unknown-tool limit (${DEFAULT_MAX_UNKNOWN_TOOL_CALLS}) reached \u2014 stopping`
@@ -7503,6 +7901,15 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
7503
7901
  return this.endTurnWithFailure(TURN_FAILURE_EXITS.unknownToolLimit);
7504
7902
  }
7505
7903
  const firstContinuation = systemCalls[0];
7904
+ if (!this.subAgentCompletion && this.subAgentWallThisTurn(!!firstContinuation)) {
7905
+ if (this.turnController.signal.aborted) return this.completeAbortedTurn();
7906
+ const wallAfterBatch = this.endTurnOnSubAgentWall();
7907
+ if (wallAfterBatch) return wallAfterBatch;
7908
+ }
7909
+ if (this.aiServiceErrorThisTurn && this.aiServiceWall) {
7910
+ this.noticeAIServiceRefusal(this.aiServiceWall.code);
7911
+ this.flushAIServiceNotices();
7912
+ }
7506
7913
  if (firstContinuation) {
7507
7914
  const { summary, remaining_task: remainingTask } = firstContinuation.args;
7508
7915
  return { reason: "agent-handoff", summary, remainingTask };
@@ -7672,6 +8079,7 @@ var OrchestratingDriver = class extends EventTarget {
7672
8079
  sessionKey: this.sessionKey,
7673
8080
  activityBus: options.activityBus,
7674
8081
  budgetExhaustedMessage: options.budgetExhaustedMessage,
8082
+ aiServiceErrorMessages: options.aiServiceErrorMessages,
7675
8083
  // This driver releases after the turn so it can fire the host-facing events; see the option.
7676
8084
  deferAgentRelease: true
7677
8085
  });
@@ -7852,15 +8260,16 @@ var OrchestratingDriver = class extends EventTarget {
7852
8260
  try {
7853
8261
  return await this.runOrchestratedTurn(input, attachments);
7854
8262
  } catch (e) {
8263
+ const pendingUserMessage = this.userMessageAppended ? void 0 : {
8264
+ role: "user",
8265
+ content: input,
8266
+ ...attachments ? { attachments } : {}
8267
+ };
7855
8268
  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
- );
8269
+ return this.chatDriver.reportBudgetExhausted(e, pendingUserMessage);
8270
+ }
8271
+ if (e instanceof AIServiceError) {
8272
+ return this.chatDriver.reportAIServiceError(e, pendingUserMessage);
7864
8273
  }
7865
8274
  throw e;
7866
8275
  }
@@ -7893,6 +8302,7 @@ var OrchestratingDriver = class extends EventTarget {
7893
8302
  while (true) {
7894
8303
  if (this.cancelled) break;
7895
8304
  await this.installAgent(currentAgent);
8305
+ if (this.cancelled) break;
7896
8306
  let result;
7897
8307
  if (isHandoff) {
7898
8308
  const contextPrimer = handoffSummary ? [{ role: "user", content: `[Context from previous agent]: ${handoffSummary}` }] : [];
@@ -7917,6 +8327,7 @@ var OrchestratingDriver = class extends EventTarget {
7917
8327
  if (result.reason !== "agent-handoff" || isFallback(currentAgent) || pinned) {
7918
8328
  break;
7919
8329
  }
8330
+ if (this.cancelled) break;
7920
8331
  handoffs += 1;
7921
8332
  if (handoffs > this.maxHandoffs) {
7922
8333
  this.appendInlineMessage(
@@ -7935,6 +8346,13 @@ var OrchestratingDriver = class extends EventTarget {
7935
8346
  routed = await this.classify(remainingTask, updatedHistory, void 0, attempted);
7936
8347
  currentAgent = routed.agent;
7937
8348
  }
8349
+ if (this.cancelled && !this.userMessageAppended) {
8350
+ this.chatDriver.reportStoppedBeforeTurn({
8351
+ role: "user",
8352
+ content: input,
8353
+ ...attachments ? { attachments } : {}
8354
+ });
8355
+ }
7938
8356
  return lastResult?.reason === "done" ? lastResult : { reason: "done" };
7939
8357
  }
7940
8358
  async continueFromHistory(transientPrimer) {
@@ -8192,6 +8610,7 @@ ${recentMessages}` : ""}`;
8192
8610
  break;
8193
8611
  } catch (e) {
8194
8612
  if (e instanceof BudgetExhaustedError) throw e;
8613
+ if (e instanceof AIServiceError && e.terminal) throw e;
8195
8614
  lastError = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
8196
8615
  logger2.warn(`OrchestratingDriver: classifier attempt ${attempt + 1} failed:`, e);
8197
8616
  if (attempt === this.classifierRetries) {
@@ -8633,6 +9052,9 @@ function withFreshMetaSnapshot(stored, fresh) {
8633
9052
  return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
8634
9053
  }
8635
9054
  export {
9055
+ AIServiceError,
9056
+ AI_SERVICE_ACCESS_REFUSALS,
9057
+ AI_SERVICE_ERROR_CODES,
8636
9058
  AI_TIER_IDS,
8637
9059
  AI_TIER_VENDORS,
8638
9060
  ANTHROPIC_CACHE_READ_MULTIPLIER,
@@ -8642,6 +9064,7 @@ export {
8642
9064
  AnthropicProvider,
8643
9065
  AnthropicTransport,
8644
9066
  ChatDriver,
9067
+ DEFAULT_AI_SERVICE_ERROR_MESSAGES,
8645
9068
  DEFAULT_AI_TIERS,
8646
9069
  DEFAULT_PROVIDER_REFUSED_MESSAGE,
8647
9070
  EMPTY_RESPONSE_NUDGE,
@@ -8662,6 +9085,8 @@ export {
8662
9085
  UNROUTABLE_PLACEHOLDER,
8663
9086
  addUsage,
8664
9087
  agenticActivityBus,
9088
+ aiServiceAccessRefusalOf,
9089
+ aiServiceErrorCodeOf,
8665
9090
  anthropicRatesFor,
8666
9091
  anthropicTokenCost,
8667
9092
  assembleDebugLog,
@@ -8675,6 +9100,7 @@ export {
8675
9100
  geminiTokenCost,
8676
9101
  getMetaEvents,
8677
9102
  isObservableAIProviderRegistry,
9103
+ isTerminalAIServiceRefusal,
8678
9104
  messageUsage,
8679
9105
  resolveAITiers,
8680
9106
  restoreMachine,