@vionwilliams/agent-os 1.0.0-alpha.22 → 1.0.0-alpha.23

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 (3) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +696 -680
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -8463,49 +8463,57 @@ function getFsImplementation() {
8463
8463
  return activeFs;
8464
8464
  }
8465
8465
  async function readFileRange(path2, offset, maxBytes) {
8466
- await using fh = await open(path2, "r");
8467
- const size = (await fh.stat()).size;
8468
- if (size <= offset) {
8469
- return null;
8470
- }
8471
- const bytesToRead = Math.min(size - offset, maxBytes);
8472
- const buffer = Buffer.allocUnsafe(bytesToRead);
8473
- let totalRead = 0;
8474
- while (totalRead < bytesToRead) {
8475
- const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
8476
- if (bytesRead === 0) {
8477
- break;
8466
+ const fh = await open(path2, "r");
8467
+ try {
8468
+ const size = (await fh.stat()).size;
8469
+ if (size <= offset) {
8470
+ return null;
8478
8471
  }
8479
- totalRead += bytesRead;
8472
+ const bytesToRead = Math.min(size - offset, maxBytes);
8473
+ const buffer = Buffer.allocUnsafe(bytesToRead);
8474
+ let totalRead = 0;
8475
+ while (totalRead < bytesToRead) {
8476
+ const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
8477
+ if (bytesRead === 0) {
8478
+ break;
8479
+ }
8480
+ totalRead += bytesRead;
8481
+ }
8482
+ return {
8483
+ content: buffer.toString("utf8", 0, totalRead),
8484
+ bytesRead: totalRead,
8485
+ bytesTotal: size
8486
+ };
8487
+ } finally {
8488
+ await fh.close();
8480
8489
  }
8481
- return {
8482
- content: buffer.toString("utf8", 0, totalRead),
8483
- bytesRead: totalRead,
8484
- bytesTotal: size
8485
- };
8486
8490
  }
8487
8491
  async function tailFile(path2, maxBytes) {
8488
- await using fh = await open(path2, "r");
8489
- const size = (await fh.stat()).size;
8490
- if (size === 0) {
8491
- return { content: "", bytesRead: 0, bytesTotal: 0 };
8492
- }
8493
- const offset = Math.max(0, size - maxBytes);
8494
- const bytesToRead = size - offset;
8495
- const buffer = Buffer.allocUnsafe(bytesToRead);
8496
- let totalRead = 0;
8497
- while (totalRead < bytesToRead) {
8498
- const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
8499
- if (bytesRead === 0) {
8500
- break;
8492
+ const fh = await open(path2, "r");
8493
+ try {
8494
+ const size = (await fh.stat()).size;
8495
+ if (size === 0) {
8496
+ return { content: "", bytesRead: 0, bytesTotal: 0 };
8497
+ }
8498
+ const offset = Math.max(0, size - maxBytes);
8499
+ const bytesToRead = size - offset;
8500
+ const buffer = Buffer.allocUnsafe(bytesToRead);
8501
+ let totalRead = 0;
8502
+ while (totalRead < bytesToRead) {
8503
+ const { bytesRead } = await fh.read(buffer, totalRead, bytesToRead - totalRead, offset + totalRead);
8504
+ if (bytesRead === 0) {
8505
+ break;
8506
+ }
8507
+ totalRead += bytesRead;
8501
8508
  }
8502
- totalRead += bytesRead;
8509
+ return {
8510
+ content: buffer.toString("utf8", 0, totalRead),
8511
+ bytesRead: totalRead,
8512
+ bytesTotal: size
8513
+ };
8514
+ } finally {
8515
+ await fh.close();
8503
8516
  }
8504
- return {
8505
- content: buffer.toString("utf8", 0, totalRead),
8506
- bytesRead: totalRead,
8507
- bytesTotal: size
8508
- };
8509
8517
  }
8510
8518
  async function* readLinesReverse(path2) {
8511
8519
  const CHUNK_SIZE = 1024 * 4;
@@ -35288,21 +35296,25 @@ async function readJSONLFile(filePath) {
35288
35296
  if (size <= MAX_JSONL_READ_BYTES) {
35289
35297
  return parseJSONL(await readFile6(filePath));
35290
35298
  }
35291
- await using fd = await open3(filePath, "r");
35292
- const buf = Buffer.allocUnsafe(MAX_JSONL_READ_BYTES);
35293
- let totalRead = 0;
35294
- const fileOffset = size - MAX_JSONL_READ_BYTES;
35295
- while (totalRead < MAX_JSONL_READ_BYTES) {
35296
- const { bytesRead } = await fd.read(buf, totalRead, MAX_JSONL_READ_BYTES - totalRead, fileOffset + totalRead);
35297
- if (bytesRead === 0)
35298
- break;
35299
- totalRead += bytesRead;
35300
- }
35301
- const newlineIndex = buf.indexOf(10);
35302
- if (newlineIndex !== -1 && newlineIndex < totalRead - 1) {
35303
- return parseJSONL(buf.subarray(newlineIndex + 1, totalRead));
35299
+ const fd = await open3(filePath, "r");
35300
+ try {
35301
+ const buf = Buffer.allocUnsafe(MAX_JSONL_READ_BYTES);
35302
+ let totalRead = 0;
35303
+ const fileOffset = size - MAX_JSONL_READ_BYTES;
35304
+ while (totalRead < MAX_JSONL_READ_BYTES) {
35305
+ const { bytesRead } = await fd.read(buf, totalRead, MAX_JSONL_READ_BYTES - totalRead, fileOffset + totalRead);
35306
+ if (bytesRead === 0)
35307
+ break;
35308
+ totalRead += bytesRead;
35309
+ }
35310
+ const newlineIndex = buf.indexOf(10);
35311
+ if (newlineIndex !== -1 && newlineIndex < totalRead - 1) {
35312
+ return parseJSONL(buf.subarray(newlineIndex + 1, totalRead));
35313
+ }
35314
+ return parseJSONL(buf.subarray(0, totalRead));
35315
+ } finally {
35316
+ await fd.close();
35304
35317
  }
35305
- return parseJSONL(buf.subarray(0, totalRead));
35306
35318
  }
35307
35319
  function addItemToJSONCArray(content, newItem) {
35308
35320
  try {
@@ -93302,7 +93314,7 @@ var init_system = __esm(() => {
93302
93314
  AGENT_SDK_CLAUDE_CODE_PRESET_PREFIX,
93303
93315
  AGENT_SDK_PREFIX
93304
93316
  ];
93305
- AGENT_OS_VERSION = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "dev";
93317
+ AGENT_OS_VERSION = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "dev";
93306
93318
  CLI_SYSPROMPT_PREFIXES = new Set(CLI_SYSPROMPT_PREFIX_VALUES);
93307
93319
  });
93308
93320
 
@@ -93746,7 +93758,7 @@ function getClaudeCodeUserAgent() {
93746
93758
  }
93747
93759
  var AGENT_OS_VERSION2;
93748
93760
  var init_userAgent = __esm(() => {
93749
- AGENT_OS_VERSION2 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "dev";
93761
+ AGENT_OS_VERSION2 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "dev";
93750
93762
  });
93751
93763
 
93752
93764
  // src/utils/http.ts
@@ -93827,7 +93839,7 @@ var init_http2 = __esm(() => {
93827
93839
  init_auth();
93828
93840
  init_userAgent();
93829
93841
  init_workloadContext();
93830
- AGENT_OS_VERSION3 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "dev";
93842
+ AGENT_OS_VERSION3 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "dev";
93831
93843
  });
93832
93844
 
93833
93845
  // src/services/api/router/userProviders.ts
@@ -207163,7 +207175,7 @@ var init_sessionStorage = __esm(() => {
207163
207175
  init_settings2();
207164
207176
  init_slowOperations();
207165
207177
  init_uuid();
207166
- VERSION4 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "unknown";
207178
+ VERSION4 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "unknown";
207167
207179
  MAX_TOMBSTONE_REWRITE_BYTES = 50 * 1024 * 1024;
207168
207180
  SKIP_FIRST_PROMPT_PATTERN = /^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/;
207169
207181
  EPHEMERAL_PROGRESS_TYPES = new Set([
@@ -207293,7 +207305,7 @@ function Feedback({
207293
207305
  platform: env3.platform,
207294
207306
  gitRepo: envInfo.isGit,
207295
207307
  terminal: env3.terminal,
207296
- version: "1.0.0-alpha.22",
207308
+ version: "1.0.0-alpha.23",
207297
207309
  transcript: normalizeMessagesForAPI(messages),
207298
207310
  errors: sanitizedErrors,
207299
207311
  lastApiRequest: getLastAPIRequest(),
@@ -207477,7 +207489,7 @@ function Feedback({
207477
207489
  ", ",
207478
207490
  env3.terminal,
207479
207491
  ", v",
207480
- "1.0.0-alpha.22"
207492
+ "1.0.0-alpha.23"
207481
207493
  ]
207482
207494
  })
207483
207495
  ]
@@ -207583,7 +207595,7 @@ ${sanitizedDescription}
207583
207595
  ` + `**Environment Info**
207584
207596
  ` + `- Platform: ${env3.platform}
207585
207597
  ` + `- Terminal: ${env3.terminal}
207586
- ` + `- Version: ${"1.0.0-alpha.22"}
207598
+ ` + `- Version: ${"1.0.0-alpha.23"}
207587
207599
  ` + `- Feedback ID: ${feedbackId}
207588
207600
  ` + `
207589
207601
  **Errors**
@@ -259968,8 +259980,8 @@ var init_toolAnalytics = __esm(() => {
259968
259980
  init_agentContext();
259969
259981
  init_slowOperations();
259970
259982
  init_teammate();
259971
- AGENT_OS_VERSION4 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "dev";
259972
- AGENT_OS_BUILD_TIME = typeof MACRO !== "undefined" ? "2026-05-21T08:12:13Z" : undefined;
259983
+ AGENT_OS_VERSION4 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "dev";
259984
+ AGENT_OS_BUILD_TIME = typeof MACRO !== "undefined" ? "2026-05-21T08:38:17Z" : undefined;
259973
259985
  BUILTIN_MCP_SERVER_NAMES = new Set([]);
259974
259986
  TOOL_INPUT_MAX_JSON_CHARS = 4 * 1024;
259975
259987
  FILE_COMMANDS = new Set([
@@ -274615,7 +274627,7 @@ function getInstallationEnv() {
274615
274627
  return;
274616
274628
  }
274617
274629
  function getClaudeCodeVersion() {
274618
- return "1.0.0-alpha.22";
274630
+ return "1.0.0-alpha.23";
274619
274631
  }
274620
274632
  async function getInstalledVSCodeExtensionVersion(command) {
274621
274633
  const { stdout } = await execFileNoThrow(command, ["--list-extensions", "--show-versions"], {
@@ -297333,7 +297345,7 @@ async function setupSdkMcpClients(sdkMcpConfigs, sendMcpMessage) {
297333
297345
  const client = new Client({
297334
297346
  name: "claude-code",
297335
297347
  title: "Agent-OS",
297336
- version: "1.0.0-alpha.22",
297348
+ version: "1.0.0-alpha.23",
297337
297349
  description: "Anthropic's agentic coding tool",
297338
297350
  websiteUrl: PRODUCT_URL
297339
297351
  }, {
@@ -297686,7 +297698,7 @@ var init_client4 = __esm(() => {
297686
297698
  const client = new Client({
297687
297699
  name: "claude-code",
297688
297700
  title: "Agent-OS",
297689
- version: "1.0.0-alpha.22",
297701
+ version: "1.0.0-alpha.23",
297690
297702
  description: "Anthropic's agentic coding tool",
297691
297703
  websiteUrl: PRODUCT_URL
297692
297704
  }, {
@@ -416331,7 +416343,7 @@ function getInvokedBinary() {
416331
416343
  async function getDoctorDiagnostic() {
416332
416344
  return {
416333
416345
  installationType: "package-manager",
416334
- version: "1.0.0-alpha.22",
416346
+ version: "1.0.0-alpha.23",
416335
416347
  installationPath: process.argv[1] ?? "",
416336
416348
  invokedBinary: getInvokedBinary(),
416337
416349
  configInstallMethod: "not set",
@@ -416736,7 +416748,7 @@ function buildPrimarySection() {
416736
416748
  });
416737
416749
  return [{
416738
416750
  label: "Version",
416739
- value: "1.0.0-alpha.22"
416751
+ value: "1.0.0-alpha.23"
416740
416752
  }, {
416741
416753
  label: "Session name",
416742
416754
  value: nameValue
@@ -420379,7 +420391,7 @@ function Config({
420379
420391
  }
420380
420392
  })
420381
420393
  }) : showSubmenu === "ChannelDowngrade" ? /* @__PURE__ */ jsx_runtime169.jsx(ChannelDowngradeDialog, {
420382
- currentVersion: "1.0.0-alpha.22",
420394
+ currentVersion: "1.0.0-alpha.23",
420383
420395
  onChoice: (choice) => {
420384
420396
  setShowSubmenu(null);
420385
420397
  setTabsHidden(false);
@@ -420391,7 +420403,7 @@ function Config({
420391
420403
  autoUpdatesChannel: "stable"
420392
420404
  };
420393
420405
  if (choice === "stay") {
420394
- newSettings.minimumVersion = "1.0.0-alpha.22";
420406
+ newSettings.minimumVersion = "1.0.0-alpha.23";
420395
420407
  }
420396
420408
  updateSettingsForSource("userSettings", newSettings);
420397
420409
  setSettingsData((prev_27) => ({
@@ -428382,7 +428394,7 @@ function HelpV2(t0) {
428382
428394
  let t6;
428383
428395
  if ($3[31] !== tabs) {
428384
428396
  t6 = /* @__PURE__ */ jsx_runtime195.jsx(Tabs, {
428385
- title: `Agent-OS v${"1.0.0-alpha.22"}`,
428397
+ title: `Agent-OS v${"1.0.0-alpha.23"}`,
428386
428398
  color: "professionalBlue",
428387
428399
  defaultTab: "general",
428388
428400
  children: tabs
@@ -431510,7 +431522,7 @@ var init_user = __esm(() => {
431510
431522
  deviceId,
431511
431523
  sessionId: getSessionId(),
431512
431524
  email: getEmail(),
431513
- appVersion: "1.0.0-alpha.22",
431525
+ appVersion: "1.0.0-alpha.23",
431514
431526
  platform: getHostPlatformForAnalytics(),
431515
431527
  organizationUuid,
431516
431528
  accountUuid,
@@ -451761,7 +451773,7 @@ function getAllReleaseNotes(changelogContent = getStoredChangelogFromMemory()) {
451761
451773
  return [];
451762
451774
  }
451763
451775
  }
451764
- async function checkForReleaseNotes(lastSeenVersion, currentVersion = "1.0.0-alpha.22") {
451776
+ async function checkForReleaseNotes(lastSeenVersion, currentVersion = "1.0.0-alpha.23") {
451765
451777
  if (process.env.USER_TYPE === "ant") {
451766
451778
  const changelog = "";
451767
451779
  if (changelog) {
@@ -451788,7 +451800,7 @@ async function checkForReleaseNotes(lastSeenVersion, currentVersion = "1.0.0-alp
451788
451800
  releaseNotes
451789
451801
  };
451790
451802
  }
451791
- function checkForReleaseNotesSync(lastSeenVersion, currentVersion = "1.0.0-alpha.22") {
451803
+ function checkForReleaseNotesSync(lastSeenVersion, currentVersion = "1.0.0-alpha.23") {
451792
451804
  if (process.env.USER_TYPE === "ant") {
451793
451805
  const changelog = "";
451794
451806
  if (changelog) {
@@ -452915,7 +452927,7 @@ function getRecentActivitySync() {
452915
452927
  return cachedActivity;
452916
452928
  }
452917
452929
  function getLogoDisplayData() {
452918
- const version2 = process.env.DEMO_VERSION ?? "1.0.0-alpha.22";
452930
+ const version2 = process.env.DEMO_VERSION ?? "1.0.0-alpha.23";
452919
452931
  const serverUrl = getDirectConnectServerUrl();
452920
452932
  const displayPath = process.env.DEMO_VERSION ? "/code/claude" : getDisplayPath(getCwd());
452921
452933
  const cwd2 = serverUrl ? `${displayPath} in ${serverUrl.replace(/^https?:\/\//, "")}` : displayPath;
@@ -454130,7 +454142,7 @@ function LogoV2() {
454130
454142
  if ($3[2] === Symbol.for("react.memo_cache_sentinel")) {
454131
454143
  t2 = () => {
454132
454144
  const currentConfig = getGlobalConfig();
454133
- if (currentConfig.lastReleaseNotesSeen === "1.0.0-alpha.22") {
454145
+ if (currentConfig.lastReleaseNotesSeen === "1.0.0-alpha.23") {
454134
454146
  return;
454135
454147
  }
454136
454148
  saveGlobalConfig(_temp328);
@@ -454796,12 +454808,12 @@ function AgentOsPoster() {
454796
454808
  });
454797
454809
  }
454798
454810
  function _temp328(current) {
454799
- if (current.lastReleaseNotesSeen === "1.0.0-alpha.22") {
454811
+ if (current.lastReleaseNotesSeen === "1.0.0-alpha.23") {
454800
454812
  return current;
454801
454813
  }
454802
454814
  return {
454803
454815
  ...current,
454804
- lastReleaseNotesSeen: "1.0.0-alpha.22"
454816
+ lastReleaseNotesSeen: "1.0.0-alpha.23"
454805
454817
  };
454806
454818
  }
454807
454819
  function _temp245(s_0) {
@@ -481378,7 +481390,7 @@ async function captureMemoryDiagnostics(trigger, dumpNumber = 0) {
481378
481390
  smapsRollup,
481379
481391
  platform: process.platform,
481380
481392
  nodeVersion: process.version,
481381
- ccVersion: "1.0.0-alpha.22"
481393
+ ccVersion: "1.0.0-alpha.23"
481382
481394
  };
481383
481395
  }
481384
481396
  async function performHeapDump(trigger = "manual", dumpNumber = 0) {
@@ -481951,7 +481963,7 @@ var init_bridge_kick = __esm(() => {
481951
481963
  var call58 = async () => {
481952
481964
  return {
481953
481965
  type: "text",
481954
- value: `${"1.0.0-alpha.22"} (built ${"2026-05-21T08:12:13Z"})`
481966
+ value: `${"1.0.0-alpha.23"} (built ${"2026-05-21T08:38:17Z"})`
481955
481967
  };
481956
481968
  }, version2, version_default;
481957
481969
  var init_version = __esm(() => {
@@ -491443,7 +491455,7 @@ function generateHtmlReport(data, insights) {
491443
491455
  </html>`;
491444
491456
  }
491445
491457
  function buildExportData(data, insights, facets, remoteStats) {
491446
- const version3 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "unknown";
491458
+ const version3 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "unknown";
491447
491459
  const remote_hosts_collected = remoteStats?.hosts.filter((h3) => h3.sessionCount > 0).map((h3) => h3.name);
491448
491460
  const facets_summary = {
491449
491461
  total: facets.size,
@@ -497812,653 +497824,657 @@ async function* queryLoop(params, consumedCommandUuids) {
497812
497824
  const budgetTracker = null;
497813
497825
  let taskBudgetRemaining = undefined;
497814
497826
  const config4 = buildQueryConfig();
497815
- using pendingMemoryPrefetch = startRelevantMemoryPrefetch(state.messages, state.toolUseContext);
497816
- while (true) {
497817
- let { toolUseContext } = state;
497818
- const {
497819
- messages,
497820
- autoCompactTracking,
497821
- maxOutputTokensRecoveryCount,
497822
- hasAttemptedReactiveCompact,
497823
- maxOutputTokensOverride,
497824
- pendingToolUseSummary,
497825
- stopHookActive,
497826
- turnCount
497827
- } = state;
497828
- const pendingSkillPrefetch = skillPrefetch?.startSkillDiscoveryPrefetch(null, messages, toolUseContext);
497829
- yield { type: "stream_request_start" };
497830
- queryCheckpoint("query_fn_entry");
497831
- if (!toolUseContext.agentId) {
497832
- headlessProfilerCheckpoint("query_started");
497833
- }
497834
- const queryTracking = toolUseContext.queryTracking ? {
497835
- chainId: toolUseContext.queryTracking.chainId,
497836
- depth: toolUseContext.queryTracking.depth + 1
497837
- } : {
497838
- chainId: deps.uuid(),
497839
- depth: 0
497840
- };
497841
- const queryChainIdForAnalytics = queryTracking.chainId;
497842
- toolUseContext = {
497843
- ...toolUseContext,
497844
- queryTracking
497845
- };
497846
- let messagesForQuery = [...getMessagesAfterCompactBoundary(messages)];
497847
- let tracking = autoCompactTracking;
497848
- const persistReplacements = querySource.startsWith("agent:") || querySource.startsWith("repl_main_thread");
497849
- messagesForQuery = await applyToolResultBudget(messagesForQuery, toolUseContext.contentReplacementState, persistReplacements ? (records) => void recordContentReplacement(records, toolUseContext.agentId).catch(logError2) : undefined, new Set(toolUseContext.options.tools.filter((t2) => !Number.isFinite(t2.maxResultSizeChars)).map((t2) => t2.name)));
497850
- let snipTokensFreed = 0;
497851
- if (false) {}
497852
- queryCheckpoint("query_microcompact_start");
497853
- const microcompactResult = await deps.microcompact(messagesForQuery, toolUseContext, querySource);
497854
- messagesForQuery = microcompactResult.messages;
497855
- const pendingCacheEdits2 = undefined;
497856
- queryCheckpoint("query_microcompact_end");
497857
- if (false) {}
497858
- const fullSystemPrompt = asSystemPrompt(appendSystemContext(systemPrompt, systemContext));
497859
- queryCheckpoint("query_autocompact_start");
497860
- const { compactionResult, consecutiveFailures } = await deps.autocompact(messagesForQuery, toolUseContext, {
497861
- systemPrompt,
497862
- userContext,
497863
- systemContext,
497864
- toolUseContext,
497865
- forkContextMessages: messagesForQuery
497866
- }, querySource, tracking, snipTokensFreed);
497867
- queryCheckpoint("query_autocompact_end");
497868
- if (compactionResult) {
497827
+ const pendingMemoryPrefetch = startRelevantMemoryPrefetch(state.messages, state.toolUseContext);
497828
+ try {
497829
+ while (true) {
497830
+ let { toolUseContext } = state;
497869
497831
  const {
497870
- preCompactTokenCount,
497871
- postCompactTokenCount,
497872
- truePostCompactTokenCount,
497873
- compactionUsage
497874
- } = compactionResult;
497875
- if (params.taskBudget) {
497876
- const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
497877
- taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
497878
- }
497879
- tracking = {
497880
- compacted: true,
497881
- turnId: deps.uuid(),
497882
- turnCounter: 0,
497883
- consecutiveFailures: 0
497884
- };
497885
- const postCompactMessages = buildPostCompactMessages(compactionResult);
497886
- for (const message of postCompactMessages) {
497887
- yield message;
497888
- }
497889
- messagesForQuery = postCompactMessages;
497890
- } else if (consecutiveFailures !== undefined) {
497891
- tracking = {
497892
- ...tracking ?? { compacted: false, turnId: "", turnCounter: 0 },
497893
- consecutiveFailures
497832
+ messages,
497833
+ autoCompactTracking,
497834
+ maxOutputTokensRecoveryCount,
497835
+ hasAttemptedReactiveCompact,
497836
+ maxOutputTokensOverride,
497837
+ pendingToolUseSummary,
497838
+ stopHookActive,
497839
+ turnCount
497840
+ } = state;
497841
+ const pendingSkillPrefetch = skillPrefetch?.startSkillDiscoveryPrefetch(null, messages, toolUseContext);
497842
+ yield { type: "stream_request_start" };
497843
+ queryCheckpoint("query_fn_entry");
497844
+ if (!toolUseContext.agentId) {
497845
+ headlessProfilerCheckpoint("query_started");
497846
+ }
497847
+ const queryTracking = toolUseContext.queryTracking ? {
497848
+ chainId: toolUseContext.queryTracking.chainId,
497849
+ depth: toolUseContext.queryTracking.depth + 1
497850
+ } : {
497851
+ chainId: deps.uuid(),
497852
+ depth: 0
497894
497853
  };
497895
- }
497896
- toolUseContext = {
497897
- ...toolUseContext,
497898
- messages: messagesForQuery
497899
- };
497900
- const assistantMessages = [];
497901
- const toolResults = [];
497902
- const toolUseBlocks = [];
497903
- let needsFollowUp = false;
497904
- queryCheckpoint("query_setup_start");
497905
- const useStreamingToolExecution = config4.gates.streamingToolExecution;
497906
- let streamingToolExecutor = useStreamingToolExecution ? new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext) : null;
497907
- const appState = toolUseContext.getAppState();
497908
- const permissionMode = appState.toolPermissionContext.mode;
497909
- let currentModel = getRuntimeMainLoopModel({
497910
- permissionMode,
497911
- mainLoopModel: toolUseContext.options.mainLoopModel,
497912
- exceeds200kTokens: permissionMode === "plan" && doesMostRecentAssistantMessageExceed200k(messagesForQuery)
497913
- });
497914
- queryCheckpoint("query_setup_end");
497915
- const dumpPromptsFetch = config4.gates.isAnt ? createDumpPromptsFetch(toolUseContext.agentId ?? config4.sessionId) : undefined;
497916
- let collapseOwnsIt = false;
497917
- if (false) {}
497918
- const mediaRecoveryEnabled = reactiveCompact2?.isReactiveCompactEnabled() ?? false;
497919
- if (!compactionResult && querySource !== "compact" && querySource !== "session_memory" && !(reactiveCompact2?.isReactiveCompactEnabled() && isAutoCompactEnabled()) && !collapseOwnsIt) {
497920
- const { isAtBlockingLimit } = calculateTokenWarningState(tokenCountWithEstimation(messagesForQuery) - snipTokensFreed, toolUseContext.options.mainLoopModel);
497921
- if (isAtBlockingLimit) {
497922
- yield createAssistantAPIErrorMessage({
497923
- content: PROMPT_TOO_LONG_ERROR_MESSAGE,
497924
- error: "invalid_request"
497925
- });
497926
- return { reason: "blocking_limit" };
497854
+ const queryChainIdForAnalytics = queryTracking.chainId;
497855
+ toolUseContext = {
497856
+ ...toolUseContext,
497857
+ queryTracking
497858
+ };
497859
+ let messagesForQuery = [...getMessagesAfterCompactBoundary(messages)];
497860
+ let tracking = autoCompactTracking;
497861
+ const persistReplacements = querySource.startsWith("agent:") || querySource.startsWith("repl_main_thread");
497862
+ messagesForQuery = await applyToolResultBudget(messagesForQuery, toolUseContext.contentReplacementState, persistReplacements ? (records) => void recordContentReplacement(records, toolUseContext.agentId).catch(logError2) : undefined, new Set(toolUseContext.options.tools.filter((t2) => !Number.isFinite(t2.maxResultSizeChars)).map((t2) => t2.name)));
497863
+ let snipTokensFreed = 0;
497864
+ if (false) {}
497865
+ queryCheckpoint("query_microcompact_start");
497866
+ const microcompactResult = await deps.microcompact(messagesForQuery, toolUseContext, querySource);
497867
+ messagesForQuery = microcompactResult.messages;
497868
+ const pendingCacheEdits2 = undefined;
497869
+ queryCheckpoint("query_microcompact_end");
497870
+ if (false) {}
497871
+ const fullSystemPrompt = asSystemPrompt(appendSystemContext(systemPrompt, systemContext));
497872
+ queryCheckpoint("query_autocompact_start");
497873
+ const { compactionResult, consecutiveFailures } = await deps.autocompact(messagesForQuery, toolUseContext, {
497874
+ systemPrompt,
497875
+ userContext,
497876
+ systemContext,
497877
+ toolUseContext,
497878
+ forkContextMessages: messagesForQuery
497879
+ }, querySource, tracking, snipTokensFreed);
497880
+ queryCheckpoint("query_autocompact_end");
497881
+ if (compactionResult) {
497882
+ const {
497883
+ preCompactTokenCount,
497884
+ postCompactTokenCount,
497885
+ truePostCompactTokenCount,
497886
+ compactionUsage
497887
+ } = compactionResult;
497888
+ if (params.taskBudget) {
497889
+ const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
497890
+ taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
497891
+ }
497892
+ tracking = {
497893
+ compacted: true,
497894
+ turnId: deps.uuid(),
497895
+ turnCounter: 0,
497896
+ consecutiveFailures: 0
497897
+ };
497898
+ const postCompactMessages = buildPostCompactMessages(compactionResult);
497899
+ for (const message of postCompactMessages) {
497900
+ yield message;
497901
+ }
497902
+ messagesForQuery = postCompactMessages;
497903
+ } else if (consecutiveFailures !== undefined) {
497904
+ tracking = {
497905
+ ...tracking ?? { compacted: false, turnId: "", turnCounter: 0 },
497906
+ consecutiveFailures
497907
+ };
497927
497908
  }
497928
- }
497929
- let attemptWithFallback = true;
497930
- queryCheckpoint("query_api_loop_start");
497931
- try {
497932
- while (attemptWithFallback) {
497933
- attemptWithFallback = false;
497934
- try {
497935
- let streamingFallbackOccured = false;
497936
- queryCheckpoint("query_api_streaming_start");
497937
- for await (const message of deps.callModel({
497938
- messages: prependUserContext(messagesForQuery, userContext),
497939
- systemPrompt: fullSystemPrompt,
497940
- thinkingConfig: toolUseContext.options.thinkingConfig,
497941
- tools: toolUseContext.options.tools,
497942
- signal: toolUseContext.abortController.signal,
497943
- options: {
497944
- async getToolPermissionContext() {
497945
- const appState2 = toolUseContext.getAppState();
497946
- return appState2.toolPermissionContext;
497947
- },
497948
- model: currentModel,
497949
- ...config4.gates.fastModeEnabled && {
497950
- fastMode: appState.fastMode
497951
- },
497952
- toolChoice: undefined,
497953
- isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession,
497954
- fallbackModel,
497955
- onStreamingFallback: () => {
497956
- streamingFallbackOccured = true;
497957
- },
497958
- querySource,
497959
- agents: toolUseContext.options.agentDefinitions.activeAgents,
497960
- allowedAgentTypes: toolUseContext.options.agentDefinitions.allowedAgentTypes,
497961
- hasAppendSystemPrompt: !!toolUseContext.options.appendSystemPrompt,
497962
- maxOutputTokensOverride,
497963
- fetchOverride: dumpPromptsFetch,
497964
- mcpTools: appState.mcp.tools,
497965
- hasPendingMcpServers: appState.mcp.clients.some((c5) => c5.type === "pending"),
497966
- queryTracking,
497967
- effortValue: appState.effortValue,
497968
- advisorModel: appState.advisorModel,
497969
- skipCacheWrite,
497970
- agentId: toolUseContext.agentId,
497971
- addNotification: toolUseContext.addNotification,
497972
- routeContext: buildRouteContext(turnCount, querySource, messagesForQuery, toolUseContext.options.maxBudgetUsd),
497973
- ...params.taskBudget && {
497974
- taskBudget: {
497975
- total: params.taskBudget.total,
497976
- ...taskBudgetRemaining !== undefined && {
497977
- remaining: taskBudgetRemaining
497909
+ toolUseContext = {
497910
+ ...toolUseContext,
497911
+ messages: messagesForQuery
497912
+ };
497913
+ const assistantMessages = [];
497914
+ const toolResults = [];
497915
+ const toolUseBlocks = [];
497916
+ let needsFollowUp = false;
497917
+ queryCheckpoint("query_setup_start");
497918
+ const useStreamingToolExecution = config4.gates.streamingToolExecution;
497919
+ let streamingToolExecutor = useStreamingToolExecution ? new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext) : null;
497920
+ const appState = toolUseContext.getAppState();
497921
+ const permissionMode = appState.toolPermissionContext.mode;
497922
+ let currentModel = getRuntimeMainLoopModel({
497923
+ permissionMode,
497924
+ mainLoopModel: toolUseContext.options.mainLoopModel,
497925
+ exceeds200kTokens: permissionMode === "plan" && doesMostRecentAssistantMessageExceed200k(messagesForQuery)
497926
+ });
497927
+ queryCheckpoint("query_setup_end");
497928
+ const dumpPromptsFetch = config4.gates.isAnt ? createDumpPromptsFetch(toolUseContext.agentId ?? config4.sessionId) : undefined;
497929
+ let collapseOwnsIt = false;
497930
+ if (false) {}
497931
+ const mediaRecoveryEnabled = reactiveCompact2?.isReactiveCompactEnabled() ?? false;
497932
+ if (!compactionResult && querySource !== "compact" && querySource !== "session_memory" && !(reactiveCompact2?.isReactiveCompactEnabled() && isAutoCompactEnabled()) && !collapseOwnsIt) {
497933
+ const { isAtBlockingLimit } = calculateTokenWarningState(tokenCountWithEstimation(messagesForQuery) - snipTokensFreed, toolUseContext.options.mainLoopModel);
497934
+ if (isAtBlockingLimit) {
497935
+ yield createAssistantAPIErrorMessage({
497936
+ content: PROMPT_TOO_LONG_ERROR_MESSAGE,
497937
+ error: "invalid_request"
497938
+ });
497939
+ return { reason: "blocking_limit" };
497940
+ }
497941
+ }
497942
+ let attemptWithFallback = true;
497943
+ queryCheckpoint("query_api_loop_start");
497944
+ try {
497945
+ while (attemptWithFallback) {
497946
+ attemptWithFallback = false;
497947
+ try {
497948
+ let streamingFallbackOccured = false;
497949
+ queryCheckpoint("query_api_streaming_start");
497950
+ for await (const message of deps.callModel({
497951
+ messages: prependUserContext(messagesForQuery, userContext),
497952
+ systemPrompt: fullSystemPrompt,
497953
+ thinkingConfig: toolUseContext.options.thinkingConfig,
497954
+ tools: toolUseContext.options.tools,
497955
+ signal: toolUseContext.abortController.signal,
497956
+ options: {
497957
+ async getToolPermissionContext() {
497958
+ const appState2 = toolUseContext.getAppState();
497959
+ return appState2.toolPermissionContext;
497960
+ },
497961
+ model: currentModel,
497962
+ ...config4.gates.fastModeEnabled && {
497963
+ fastMode: appState.fastMode
497964
+ },
497965
+ toolChoice: undefined,
497966
+ isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession,
497967
+ fallbackModel,
497968
+ onStreamingFallback: () => {
497969
+ streamingFallbackOccured = true;
497970
+ },
497971
+ querySource,
497972
+ agents: toolUseContext.options.agentDefinitions.activeAgents,
497973
+ allowedAgentTypes: toolUseContext.options.agentDefinitions.allowedAgentTypes,
497974
+ hasAppendSystemPrompt: !!toolUseContext.options.appendSystemPrompt,
497975
+ maxOutputTokensOverride,
497976
+ fetchOverride: dumpPromptsFetch,
497977
+ mcpTools: appState.mcp.tools,
497978
+ hasPendingMcpServers: appState.mcp.clients.some((c5) => c5.type === "pending"),
497979
+ queryTracking,
497980
+ effortValue: appState.effortValue,
497981
+ advisorModel: appState.advisorModel,
497982
+ skipCacheWrite,
497983
+ agentId: toolUseContext.agentId,
497984
+ addNotification: toolUseContext.addNotification,
497985
+ routeContext: buildRouteContext(turnCount, querySource, messagesForQuery, toolUseContext.options.maxBudgetUsd),
497986
+ ...params.taskBudget && {
497987
+ taskBudget: {
497988
+ total: params.taskBudget.total,
497989
+ ...taskBudgetRemaining !== undefined && {
497990
+ remaining: taskBudgetRemaining
497991
+ }
497978
497992
  }
497979
497993
  }
497980
497994
  }
497981
- }
497982
- })) {
497983
- if (streamingFallbackOccured) {
497984
- for (const msg of assistantMessages) {
497985
- yield { type: "tombstone", message: msg };
497986
- }
497987
- assistantMessages.length = 0;
497988
- toolResults.length = 0;
497989
- toolUseBlocks.length = 0;
497990
- needsFollowUp = false;
497991
- if (streamingToolExecutor) {
497992
- streamingToolExecutor.discard();
497993
- streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
497995
+ })) {
497996
+ if (streamingFallbackOccured) {
497997
+ for (const msg of assistantMessages) {
497998
+ yield { type: "tombstone", message: msg };
497999
+ }
498000
+ assistantMessages.length = 0;
498001
+ toolResults.length = 0;
498002
+ toolUseBlocks.length = 0;
498003
+ needsFollowUp = false;
498004
+ if (streamingToolExecutor) {
498005
+ streamingToolExecutor.discard();
498006
+ streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
498007
+ }
497994
498008
  }
497995
- }
497996
- let yieldMessage = message;
497997
- if (message.type === "assistant") {
497998
- let clonedContent;
497999
- for (let i4 = 0;i4 < message.message.content.length; i4++) {
498000
- const block2 = message.message.content[i4];
498001
- if (block2.type === "tool_use" && typeof block2.input === "object" && block2.input !== null) {
498002
- const tool = findToolByName(toolUseContext.options.tools, block2.name);
498003
- if (tool?.backfillObservableInput) {
498004
- const originalInput = block2.input;
498005
- const inputCopy = { ...originalInput };
498006
- tool.backfillObservableInput(inputCopy);
498007
- const addedFields = Object.keys(inputCopy).some((k2) => !(k2 in originalInput));
498008
- if (addedFields) {
498009
- clonedContent ??= [...message.message.content];
498010
- clonedContent[i4] = { ...block2, input: inputCopy };
498009
+ let yieldMessage = message;
498010
+ if (message.type === "assistant") {
498011
+ let clonedContent;
498012
+ for (let i4 = 0;i4 < message.message.content.length; i4++) {
498013
+ const block2 = message.message.content[i4];
498014
+ if (block2.type === "tool_use" && typeof block2.input === "object" && block2.input !== null) {
498015
+ const tool = findToolByName(toolUseContext.options.tools, block2.name);
498016
+ if (tool?.backfillObservableInput) {
498017
+ const originalInput = block2.input;
498018
+ const inputCopy = { ...originalInput };
498019
+ tool.backfillObservableInput(inputCopy);
498020
+ const addedFields = Object.keys(inputCopy).some((k2) => !(k2 in originalInput));
498021
+ if (addedFields) {
498022
+ clonedContent ??= [...message.message.content];
498023
+ clonedContent[i4] = { ...block2, input: inputCopy };
498024
+ }
498011
498025
  }
498012
498026
  }
498013
498027
  }
498028
+ if (clonedContent) {
498029
+ yieldMessage = {
498030
+ ...message,
498031
+ message: { ...message.message, content: clonedContent }
498032
+ };
498033
+ }
498014
498034
  }
498015
- if (clonedContent) {
498016
- yieldMessage = {
498017
- ...message,
498018
- message: { ...message.message, content: clonedContent }
498019
- };
498035
+ let withheld = false;
498036
+ if (false) {}
498037
+ if (reactiveCompact2?.isWithheldPromptTooLong(message)) {
498038
+ withheld = true;
498020
498039
  }
498021
- }
498022
- let withheld = false;
498023
- if (false) {}
498024
- if (reactiveCompact2?.isWithheldPromptTooLong(message)) {
498025
- withheld = true;
498026
- }
498027
- if (mediaRecoveryEnabled && reactiveCompact2?.isWithheldMediaSizeError(message)) {
498028
- withheld = true;
498029
- }
498030
- if (isWithheldMaxOutputTokens(message)) {
498031
- withheld = true;
498032
- }
498033
- if (!withheld) {
498034
- yield yieldMessage;
498035
- }
498036
- if (message.type === "assistant") {
498037
- assistantMessages.push(message);
498038
- const msgToolUseBlocks = message.message.content.filter((content) => content.type === "tool_use");
498039
- if (msgToolUseBlocks.length > 0) {
498040
- toolUseBlocks.push(...msgToolUseBlocks);
498041
- needsFollowUp = true;
498040
+ if (mediaRecoveryEnabled && reactiveCompact2?.isWithheldMediaSizeError(message)) {
498041
+ withheld = true;
498042
498042
  }
498043
- if (streamingToolExecutor && !toolUseContext.abortController.signal.aborted) {
498044
- for (const toolBlock of msgToolUseBlocks) {
498045
- streamingToolExecutor.addTool(toolBlock, message);
498043
+ if (isWithheldMaxOutputTokens(message)) {
498044
+ withheld = true;
498045
+ }
498046
+ if (!withheld) {
498047
+ yield yieldMessage;
498048
+ }
498049
+ if (message.type === "assistant") {
498050
+ assistantMessages.push(message);
498051
+ const msgToolUseBlocks = message.message.content.filter((content) => content.type === "tool_use");
498052
+ if (msgToolUseBlocks.length > 0) {
498053
+ toolUseBlocks.push(...msgToolUseBlocks);
498054
+ needsFollowUp = true;
498055
+ }
498056
+ if (streamingToolExecutor && !toolUseContext.abortController.signal.aborted) {
498057
+ for (const toolBlock of msgToolUseBlocks) {
498058
+ streamingToolExecutor.addTool(toolBlock, message);
498059
+ }
498046
498060
  }
498047
498061
  }
498048
- }
498049
- if (streamingToolExecutor && !toolUseContext.abortController.signal.aborted) {
498050
- for (const result of streamingToolExecutor.getCompletedResults()) {
498051
- if (result.message) {
498052
- yield result.message;
498053
- toolResults.push(...normalizeMessagesForAPI([result.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
498062
+ if (streamingToolExecutor && !toolUseContext.abortController.signal.aborted) {
498063
+ for (const result of streamingToolExecutor.getCompletedResults()) {
498064
+ if (result.message) {
498065
+ yield result.message;
498066
+ toolResults.push(...normalizeMessagesForAPI([result.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
498067
+ }
498054
498068
  }
498055
498069
  }
498056
498070
  }
498057
- }
498058
- queryCheckpoint("query_api_streaming_end");
498059
- if (false) {}
498060
- } catch (innerError) {
498061
- if (innerError instanceof FallbackTriggeredError && fallbackModel) {
498062
- currentModel = fallbackModel;
498063
- attemptWithFallback = true;
498064
- yield* yieldMissingToolResultBlocks(assistantMessages, "Model fallback triggered");
498065
- assistantMessages.length = 0;
498066
- toolResults.length = 0;
498067
- toolUseBlocks.length = 0;
498068
- needsFollowUp = false;
498069
- if (streamingToolExecutor) {
498070
- streamingToolExecutor.discard();
498071
- streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
498072
- }
498073
- toolUseContext.options.mainLoopModel = fallbackModel;
498074
- if (process.env.USER_TYPE === "ant") {
498075
- messagesForQuery = stripSignatureBlocks(messagesForQuery);
498071
+ queryCheckpoint("query_api_streaming_end");
498072
+ if (false) {}
498073
+ } catch (innerError) {
498074
+ if (innerError instanceof FallbackTriggeredError && fallbackModel) {
498075
+ currentModel = fallbackModel;
498076
+ attemptWithFallback = true;
498077
+ yield* yieldMissingToolResultBlocks(assistantMessages, "Model fallback triggered");
498078
+ assistantMessages.length = 0;
498079
+ toolResults.length = 0;
498080
+ toolUseBlocks.length = 0;
498081
+ needsFollowUp = false;
498082
+ if (streamingToolExecutor) {
498083
+ streamingToolExecutor.discard();
498084
+ streamingToolExecutor = new StreamingToolExecutor(toolUseContext.options.tools, canUseTool, toolUseContext);
498085
+ }
498086
+ toolUseContext.options.mainLoopModel = fallbackModel;
498087
+ if (process.env.USER_TYPE === "ant") {
498088
+ messagesForQuery = stripSignatureBlocks(messagesForQuery);
498089
+ }
498090
+ yield createSystemMessage(`Switched to ${renderModelName(innerError.fallbackModel)} due to high demand for ${renderModelName(innerError.originalModel)}`, "warning");
498091
+ continue;
498076
498092
  }
498077
- yield createSystemMessage(`Switched to ${renderModelName(innerError.fallbackModel)} due to high demand for ${renderModelName(innerError.originalModel)}`, "warning");
498078
- continue;
498093
+ throw innerError;
498079
498094
  }
498080
- throw innerError;
498081
498095
  }
498082
- }
498083
- } catch (error41) {
498084
- logError2(error41);
498085
- const errorMessage2 = error41 instanceof Error ? error41.message : String(error41);
498086
- if (error41 instanceof ImageSizeError || error41 instanceof ImageResizeError) {
498096
+ } catch (error41) {
498097
+ logError2(error41);
498098
+ const errorMessage2 = error41 instanceof Error ? error41.message : String(error41);
498099
+ if (error41 instanceof ImageSizeError || error41 instanceof ImageResizeError) {
498100
+ yield createAssistantAPIErrorMessage({
498101
+ content: error41.message
498102
+ });
498103
+ return { reason: "image_error" };
498104
+ }
498105
+ yield* yieldMissingToolResultBlocks(assistantMessages, errorMessage2);
498087
498106
  yield createAssistantAPIErrorMessage({
498088
- content: error41.message
498107
+ content: errorMessage2
498089
498108
  });
498090
- return { reason: "image_error" };
498109
+ logAntError("Query error", error41);
498110
+ return { reason: "model_error", error: error41 };
498091
498111
  }
498092
- yield* yieldMissingToolResultBlocks(assistantMessages, errorMessage2);
498093
- yield createAssistantAPIErrorMessage({
498094
- content: errorMessage2
498095
- });
498096
- logAntError("Query error", error41);
498097
- return { reason: "model_error", error: error41 };
498098
- }
498099
- if (assistantMessages.length > 0) {
498100
- executePostSamplingHooks([...messagesForQuery, ...assistantMessages], systemPrompt, userContext, systemContext, toolUseContext, querySource);
498101
- }
498102
- if (toolUseContext.abortController.signal.aborted) {
498103
- if (streamingToolExecutor) {
498104
- for await (const update of streamingToolExecutor.getRemainingResults()) {
498105
- if (update.message) {
498106
- yield update.message;
498112
+ if (assistantMessages.length > 0) {
498113
+ executePostSamplingHooks([...messagesForQuery, ...assistantMessages], systemPrompt, userContext, systemContext, toolUseContext, querySource);
498114
+ }
498115
+ if (toolUseContext.abortController.signal.aborted) {
498116
+ if (streamingToolExecutor) {
498117
+ for await (const update of streamingToolExecutor.getRemainingResults()) {
498118
+ if (update.message) {
498119
+ yield update.message;
498120
+ }
498107
498121
  }
498122
+ } else {
498123
+ yield* yieldMissingToolResultBlocks(assistantMessages, "Interrupted by user");
498108
498124
  }
498109
- } else {
498110
- yield* yieldMissingToolResultBlocks(assistantMessages, "Interrupted by user");
498111
- }
498112
- if (false) {}
498113
- if (toolUseContext.abortController.signal.reason !== "interrupt") {
498114
- yield createUserInterruptionMessage({
498115
- toolUse: false
498116
- });
498117
- }
498118
- return { reason: "aborted_streaming" };
498119
- }
498120
- if (pendingToolUseSummary) {
498121
- const summary = await pendingToolUseSummary;
498122
- if (summary) {
498123
- yield summary;
498124
- }
498125
- }
498126
- if (!needsFollowUp) {
498127
- const lastMessage = assistantMessages.at(-1);
498128
- const isWithheld413 = lastMessage?.type === "assistant" && lastMessage.isApiErrorMessage && isPromptTooLongMessage(lastMessage);
498129
- const isWithheldMedia = mediaRecoveryEnabled && reactiveCompact2?.isWithheldMediaSizeError(lastMessage);
498130
- if (isWithheld413) {
498131
498125
  if (false) {}
498126
+ if (toolUseContext.abortController.signal.reason !== "interrupt") {
498127
+ yield createUserInterruptionMessage({
498128
+ toolUse: false
498129
+ });
498130
+ }
498131
+ return { reason: "aborted_streaming" };
498132
498132
  }
498133
- if ((isWithheld413 || isWithheldMedia) && reactiveCompact2) {
498134
- const compacted = await reactiveCompact2.tryReactiveCompact({
498135
- hasAttempted: hasAttemptedReactiveCompact,
498136
- querySource,
498137
- aborted: toolUseContext.abortController.signal.aborted,
498138
- messages: messagesForQuery,
498139
- cacheSafeParams: {
498140
- systemPrompt,
498141
- userContext,
498142
- systemContext,
498143
- toolUseContext,
498144
- forkContextMessages: messagesForQuery
498133
+ if (pendingToolUseSummary) {
498134
+ const summary = await pendingToolUseSummary;
498135
+ if (summary) {
498136
+ yield summary;
498137
+ }
498138
+ }
498139
+ if (!needsFollowUp) {
498140
+ const lastMessage = assistantMessages.at(-1);
498141
+ const isWithheld413 = lastMessage?.type === "assistant" && lastMessage.isApiErrorMessage && isPromptTooLongMessage(lastMessage);
498142
+ const isWithheldMedia = mediaRecoveryEnabled && reactiveCompact2?.isWithheldMediaSizeError(lastMessage);
498143
+ if (isWithheld413) {
498144
+ if (false) {}
498145
+ }
498146
+ if ((isWithheld413 || isWithheldMedia) && reactiveCompact2) {
498147
+ const compacted = await reactiveCompact2.tryReactiveCompact({
498148
+ hasAttempted: hasAttemptedReactiveCompact,
498149
+ querySource,
498150
+ aborted: toolUseContext.abortController.signal.aborted,
498151
+ messages: messagesForQuery,
498152
+ cacheSafeParams: {
498153
+ systemPrompt,
498154
+ userContext,
498155
+ systemContext,
498156
+ toolUseContext,
498157
+ forkContextMessages: messagesForQuery
498158
+ }
498159
+ });
498160
+ if (compacted) {
498161
+ if (params.taskBudget) {
498162
+ const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
498163
+ taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
498164
+ }
498165
+ const postCompactMessages = buildPostCompactMessages(compacted);
498166
+ for (const msg of postCompactMessages) {
498167
+ yield msg;
498168
+ }
498169
+ const next3 = {
498170
+ messages: postCompactMessages,
498171
+ toolUseContext,
498172
+ autoCompactTracking: undefined,
498173
+ maxOutputTokensRecoveryCount,
498174
+ hasAttemptedReactiveCompact: true,
498175
+ maxOutputTokensOverride: undefined,
498176
+ pendingToolUseSummary: undefined,
498177
+ stopHookActive: undefined,
498178
+ turnCount,
498179
+ transition: { reason: "reactive_compact_retry" }
498180
+ };
498181
+ state = next3;
498182
+ continue;
498145
498183
  }
498146
- });
498147
- if (compacted) {
498148
- if (params.taskBudget) {
498149
- const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
498150
- taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
498184
+ yield lastMessage;
498185
+ executeStopFailureHooks(lastMessage, toolUseContext);
498186
+ return { reason: isWithheldMedia ? "image_error" : "prompt_too_long" };
498187
+ } else if (isWithheld413) {
498188
+ try {
498189
+ const forcedCompactionResult = await compactConversation(messagesForQuery, toolUseContext, {
498190
+ systemPrompt,
498191
+ userContext,
498192
+ systemContext,
498193
+ toolUseContext,
498194
+ forkContextMessages: messagesForQuery
498195
+ }, true, undefined, true, {
498196
+ isRecompactionInChain: tracking?.compacted === true,
498197
+ turnsSincePreviousCompact: tracking?.turnCounter ?? -1,
498198
+ previousCompactTurnId: tracking?.turnId,
498199
+ autoCompactThreshold: getAutoCompactThreshold(currentModel),
498200
+ querySource
498201
+ });
498202
+ if (params.taskBudget) {
498203
+ const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
498204
+ taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
498205
+ }
498206
+ const postCompactMessages = buildPostCompactMessages(forcedCompactionResult);
498207
+ for (const msg of postCompactMessages) {
498208
+ yield msg;
498209
+ }
498210
+ tracking = {
498211
+ compacted: true,
498212
+ turnId: deps.uuid(),
498213
+ turnCounter: 0,
498214
+ consecutiveFailures: 0
498215
+ };
498216
+ const next3 = {
498217
+ messages: postCompactMessages,
498218
+ toolUseContext,
498219
+ autoCompactTracking: tracking,
498220
+ maxOutputTokensRecoveryCount,
498221
+ hasAttemptedReactiveCompact: true,
498222
+ maxOutputTokensOverride: undefined,
498223
+ pendingToolUseSummary: undefined,
498224
+ stopHookActive: undefined,
498225
+ turnCount,
498226
+ transition: { reason: "forced_prompt_too_long_compact_retry" }
498227
+ };
498228
+ state = next3;
498229
+ continue;
498230
+ } catch {
498231
+ yield lastMessage;
498232
+ executeStopFailureHooks(lastMessage, toolUseContext);
498233
+ return { reason: "prompt_too_long" };
498151
498234
  }
498152
- const postCompactMessages = buildPostCompactMessages(compacted);
498153
- for (const msg of postCompactMessages) {
498154
- yield msg;
498235
+ } else if (false) {}
498236
+ if (isWithheldMaxOutputTokens(lastMessage)) {
498237
+ const capEnabled = false;
498238
+ if (capEnabled && maxOutputTokensOverride === undefined && !process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS) {
498239
+ const next3 = {
498240
+ messages: messagesForQuery,
498241
+ toolUseContext,
498242
+ autoCompactTracking: tracking,
498243
+ maxOutputTokensRecoveryCount,
498244
+ hasAttemptedReactiveCompact,
498245
+ maxOutputTokensOverride: ESCALATED_MAX_TOKENS,
498246
+ pendingToolUseSummary: undefined,
498247
+ stopHookActive: undefined,
498248
+ turnCount,
498249
+ transition: { reason: "max_output_tokens_escalate" }
498250
+ };
498251
+ state = next3;
498252
+ continue;
498253
+ }
498254
+ if (maxOutputTokensRecoveryCount < MAX_OUTPUT_TOKENS_RECOVERY_LIMIT) {
498255
+ const recoveryMessage = createUserMessage({
498256
+ content: `Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. ` + `Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,
498257
+ isMeta: true
498258
+ });
498259
+ const next3 = {
498260
+ messages: [
498261
+ ...messagesForQuery,
498262
+ ...assistantMessages,
498263
+ recoveryMessage
498264
+ ],
498265
+ toolUseContext,
498266
+ autoCompactTracking: tracking,
498267
+ maxOutputTokensRecoveryCount: maxOutputTokensRecoveryCount + 1,
498268
+ hasAttemptedReactiveCompact,
498269
+ maxOutputTokensOverride: undefined,
498270
+ pendingToolUseSummary: undefined,
498271
+ stopHookActive: undefined,
498272
+ turnCount,
498273
+ transition: {
498274
+ reason: "max_output_tokens_recovery",
498275
+ attempt: maxOutputTokensRecoveryCount + 1
498276
+ }
498277
+ };
498278
+ state = next3;
498279
+ continue;
498155
498280
  }
498156
- const next3 = {
498157
- messages: postCompactMessages,
498158
- toolUseContext,
498159
- autoCompactTracking: undefined,
498160
- maxOutputTokensRecoveryCount,
498161
- hasAttemptedReactiveCompact: true,
498162
- maxOutputTokensOverride: undefined,
498163
- pendingToolUseSummary: undefined,
498164
- stopHookActive: undefined,
498165
- turnCount,
498166
- transition: { reason: "reactive_compact_retry" }
498167
- };
498168
- state = next3;
498169
- continue;
498170
- }
498171
- yield lastMessage;
498172
- executeStopFailureHooks(lastMessage, toolUseContext);
498173
- return { reason: isWithheldMedia ? "image_error" : "prompt_too_long" };
498174
- } else if (isWithheld413) {
498175
- try {
498176
- const forcedCompactionResult = await compactConversation(messagesForQuery, toolUseContext, {
498177
- systemPrompt,
498178
- userContext,
498179
- systemContext,
498180
- toolUseContext,
498181
- forkContextMessages: messagesForQuery
498182
- }, true, undefined, true, {
498183
- isRecompactionInChain: tracking?.compacted === true,
498184
- turnsSincePreviousCompact: tracking?.turnCounter ?? -1,
498185
- previousCompactTurnId: tracking?.turnId,
498186
- autoCompactThreshold: getAutoCompactThreshold(currentModel),
498187
- querySource
498188
- });
498189
- if (params.taskBudget) {
498190
- const preCompactContext = finalContextTokensFromLastResponse(messagesForQuery);
498191
- taskBudgetRemaining = Math.max(0, (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext);
498192
- }
498193
- const postCompactMessages = buildPostCompactMessages(forcedCompactionResult);
498194
- for (const msg of postCompactMessages) {
498195
- yield msg;
498196
- }
498197
- tracking = {
498198
- compacted: true,
498199
- turnId: deps.uuid(),
498200
- turnCounter: 0,
498201
- consecutiveFailures: 0
498202
- };
498203
- const next3 = {
498204
- messages: postCompactMessages,
498205
- toolUseContext,
498206
- autoCompactTracking: tracking,
498207
- maxOutputTokensRecoveryCount,
498208
- hasAttemptedReactiveCompact: true,
498209
- maxOutputTokensOverride: undefined,
498210
- pendingToolUseSummary: undefined,
498211
- stopHookActive: undefined,
498212
- turnCount,
498213
- transition: { reason: "forced_prompt_too_long_compact_retry" }
498214
- };
498215
- state = next3;
498216
- continue;
498217
- } catch {
498218
498281
  yield lastMessage;
498282
+ }
498283
+ if (lastMessage?.isApiErrorMessage) {
498219
498284
  executeStopFailureHooks(lastMessage, toolUseContext);
498220
- return { reason: "prompt_too_long" };
498285
+ return { reason: "completed" };
498221
498286
  }
498222
- } else if (false) {}
498223
- if (isWithheldMaxOutputTokens(lastMessage)) {
498224
- const capEnabled = false;
498225
- if (capEnabled && maxOutputTokensOverride === undefined && !process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS) {
498226
- const next3 = {
498227
- messages: messagesForQuery,
498228
- toolUseContext,
498229
- autoCompactTracking: tracking,
498230
- maxOutputTokensRecoveryCount,
498231
- hasAttemptedReactiveCompact,
498232
- maxOutputTokensOverride: ESCALATED_MAX_TOKENS,
498233
- pendingToolUseSummary: undefined,
498234
- stopHookActive: undefined,
498235
- turnCount,
498236
- transition: { reason: "max_output_tokens_escalate" }
498237
- };
498238
- state = next3;
498239
- continue;
498287
+ const stopHookResult = yield* handleStopHooks(messagesForQuery, assistantMessages, systemPrompt, userContext, systemContext, toolUseContext, querySource, stopHookActive);
498288
+ if (stopHookResult.preventContinuation) {
498289
+ return { reason: "stop_hook_prevented" };
498240
498290
  }
498241
- if (maxOutputTokensRecoveryCount < MAX_OUTPUT_TOKENS_RECOVERY_LIMIT) {
498242
- const recoveryMessage = createUserMessage({
498243
- content: `Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. ` + `Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,
498244
- isMeta: true
498245
- });
498291
+ if (stopHookResult.blockingErrors.length > 0) {
498246
498292
  const next3 = {
498247
498293
  messages: [
498248
498294
  ...messagesForQuery,
498249
498295
  ...assistantMessages,
498250
- recoveryMessage
498296
+ ...stopHookResult.blockingErrors
498251
498297
  ],
498252
498298
  toolUseContext,
498253
498299
  autoCompactTracking: tracking,
498254
- maxOutputTokensRecoveryCount: maxOutputTokensRecoveryCount + 1,
498300
+ maxOutputTokensRecoveryCount: 0,
498255
498301
  hasAttemptedReactiveCompact,
498256
498302
  maxOutputTokensOverride: undefined,
498257
498303
  pendingToolUseSummary: undefined,
498258
- stopHookActive: undefined,
498304
+ stopHookActive: true,
498259
498305
  turnCount,
498260
- transition: {
498261
- reason: "max_output_tokens_recovery",
498262
- attempt: maxOutputTokensRecoveryCount + 1
498263
- }
498306
+ transition: { reason: "stop_hook_blocking" }
498264
498307
  };
498265
498308
  state = next3;
498266
498309
  continue;
498267
498310
  }
498268
- yield lastMessage;
498269
- }
498270
- if (lastMessage?.isApiErrorMessage) {
498271
- executeStopFailureHooks(lastMessage, toolUseContext);
498311
+ if (false) {}
498272
498312
  return { reason: "completed" };
498273
498313
  }
498274
- const stopHookResult = yield* handleStopHooks(messagesForQuery, assistantMessages, systemPrompt, userContext, systemContext, toolUseContext, querySource, stopHookActive);
498275
- if (stopHookResult.preventContinuation) {
498276
- return { reason: "stop_hook_prevented" };
498277
- }
498278
- if (stopHookResult.blockingErrors.length > 0) {
498279
- const next3 = {
498280
- messages: [
498281
- ...messagesForQuery,
498282
- ...assistantMessages,
498283
- ...stopHookResult.blockingErrors
498284
- ],
498285
- toolUseContext,
498286
- autoCompactTracking: tracking,
498287
- maxOutputTokensRecoveryCount: 0,
498288
- hasAttemptedReactiveCompact,
498289
- maxOutputTokensOverride: undefined,
498290
- pendingToolUseSummary: undefined,
498291
- stopHookActive: true,
498292
- turnCount,
498293
- transition: { reason: "stop_hook_blocking" }
498294
- };
498295
- state = next3;
498296
- continue;
498297
- }
498298
- if (false) {}
498299
- return { reason: "completed" };
498300
- }
498301
- let shouldPreventContinuation = false;
498302
- let updatedToolUseContext = toolUseContext;
498303
- queryCheckpoint("query_tool_execution_start");
498304
- if (streamingToolExecutor) {}
498305
- const toolUpdates = streamingToolExecutor ? streamingToolExecutor.getRemainingResults() : runTools(toolUseBlocks, assistantMessages, canUseTool, toolUseContext);
498306
- for await (const update of toolUpdates) {
498307
- if (update.message) {
498308
- yield update.message;
498309
- if (update.message.type === "attachment" && update.message.attachment.type === "hook_stopped_continuation") {
498310
- shouldPreventContinuation = true;
498311
- }
498312
- toolResults.push(...normalizeMessagesForAPI([update.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
498313
- }
498314
- if (update.newContext) {
498315
- updatedToolUseContext = {
498316
- ...update.newContext,
498317
- queryTracking
498318
- };
498319
- }
498320
- }
498321
- queryCheckpoint("query_tool_execution_end");
498322
- let nextPendingToolUseSummary;
498323
- if (config4.gates.emitToolUseSummaries && toolUseBlocks.length > 0 && !toolUseContext.abortController.signal.aborted && !toolUseContext.agentId) {
498324
- const lastAssistantMessage = assistantMessages.at(-1);
498325
- let lastAssistantText;
498326
- if (lastAssistantMessage) {
498327
- const textBlocks = lastAssistantMessage.message.content.filter((block2) => block2.type === "text");
498328
- if (textBlocks.length > 0) {
498329
- const lastTextBlock = textBlocks.at(-1);
498330
- if (lastTextBlock && "text" in lastTextBlock) {
498331
- lastAssistantText = lastTextBlock.text;
498314
+ let shouldPreventContinuation = false;
498315
+ let updatedToolUseContext = toolUseContext;
498316
+ queryCheckpoint("query_tool_execution_start");
498317
+ if (streamingToolExecutor) {}
498318
+ const toolUpdates = streamingToolExecutor ? streamingToolExecutor.getRemainingResults() : runTools(toolUseBlocks, assistantMessages, canUseTool, toolUseContext);
498319
+ for await (const update of toolUpdates) {
498320
+ if (update.message) {
498321
+ yield update.message;
498322
+ if (update.message.type === "attachment" && update.message.attachment.type === "hook_stopped_continuation") {
498323
+ shouldPreventContinuation = true;
498332
498324
  }
498325
+ toolResults.push(...normalizeMessagesForAPI([update.message], toolUseContext.options.tools).filter((_) => _.type === "user"));
498326
+ }
498327
+ if (update.newContext) {
498328
+ updatedToolUseContext = {
498329
+ ...update.newContext,
498330
+ queryTracking
498331
+ };
498333
498332
  }
498334
498333
  }
498335
- const toolUseIds = toolUseBlocks.map((block2) => block2.id);
498336
- const toolInfoForSummary = toolUseBlocks.map((block2) => {
498337
- const toolResult = toolResults.find((result) => result.type === "user" && Array.isArray(result.message.content) && result.message.content.some((content) => content.type === "tool_result" && content.tool_use_id === block2.id));
498338
- const resultContent = toolResult?.type === "user" && Array.isArray(toolResult.message.content) ? toolResult.message.content.find((c5) => c5.type === "tool_result" && c5.tool_use_id === block2.id) : undefined;
498339
- return {
498340
- name: block2.name,
498341
- input: block2.input,
498342
- output: resultContent && "content" in resultContent ? resultContent.content : null
498343
- };
498344
- });
498345
- nextPendingToolUseSummary = generateToolUseSummary({
498346
- tools: toolInfoForSummary,
498347
- signal: toolUseContext.abortController.signal,
498348
- isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession,
498349
- lastAssistantText
498350
- }).then((summary) => {
498351
- if (summary) {
498352
- return createToolUseSummaryMessage(summary, toolUseIds);
498334
+ queryCheckpoint("query_tool_execution_end");
498335
+ let nextPendingToolUseSummary;
498336
+ if (config4.gates.emitToolUseSummaries && toolUseBlocks.length > 0 && !toolUseContext.abortController.signal.aborted && !toolUseContext.agentId) {
498337
+ const lastAssistantMessage = assistantMessages.at(-1);
498338
+ let lastAssistantText;
498339
+ if (lastAssistantMessage) {
498340
+ const textBlocks = lastAssistantMessage.message.content.filter((block2) => block2.type === "text");
498341
+ if (textBlocks.length > 0) {
498342
+ const lastTextBlock = textBlocks.at(-1);
498343
+ if (lastTextBlock && "text" in lastTextBlock) {
498344
+ lastAssistantText = lastTextBlock.text;
498345
+ }
498346
+ }
498353
498347
  }
498354
- return null;
498355
- }).catch(() => null);
498356
- }
498357
- if (toolUseContext.abortController.signal.aborted) {
498358
- if (false) {}
498359
- if (toolUseContext.abortController.signal.reason !== "interrupt") {
498360
- yield createUserInterruptionMessage({
498361
- toolUse: true
498348
+ const toolUseIds = toolUseBlocks.map((block2) => block2.id);
498349
+ const toolInfoForSummary = toolUseBlocks.map((block2) => {
498350
+ const toolResult = toolResults.find((result) => result.type === "user" && Array.isArray(result.message.content) && result.message.content.some((content) => content.type === "tool_result" && content.tool_use_id === block2.id));
498351
+ const resultContent = toolResult?.type === "user" && Array.isArray(toolResult.message.content) ? toolResult.message.content.find((c5) => c5.type === "tool_result" && c5.tool_use_id === block2.id) : undefined;
498352
+ return {
498353
+ name: block2.name,
498354
+ input: block2.input,
498355
+ output: resultContent && "content" in resultContent ? resultContent.content : null
498356
+ };
498362
498357
  });
498358
+ nextPendingToolUseSummary = generateToolUseSummary({
498359
+ tools: toolInfoForSummary,
498360
+ signal: toolUseContext.abortController.signal,
498361
+ isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession,
498362
+ lastAssistantText
498363
+ }).then((summary) => {
498364
+ if (summary) {
498365
+ return createToolUseSummaryMessage(summary, toolUseIds);
498366
+ }
498367
+ return null;
498368
+ }).catch(() => null);
498369
+ }
498370
+ if (toolUseContext.abortController.signal.aborted) {
498371
+ if (false) {}
498372
+ if (toolUseContext.abortController.signal.reason !== "interrupt") {
498373
+ yield createUserInterruptionMessage({
498374
+ toolUse: true
498375
+ });
498376
+ }
498377
+ const nextTurnCountOnAbort = turnCount + 1;
498378
+ if (maxTurns && nextTurnCountOnAbort > maxTurns) {
498379
+ yield createAttachmentMessage({
498380
+ type: "max_turns_reached",
498381
+ maxTurns,
498382
+ turnCount: nextTurnCountOnAbort
498383
+ });
498384
+ }
498385
+ return { reason: "aborted_tools" };
498386
+ }
498387
+ if (shouldPreventContinuation) {
498388
+ return { reason: "hook_stopped" };
498389
+ }
498390
+ if (tracking?.compacted) {
498391
+ tracking.turnCounter++;
498363
498392
  }
498364
- const nextTurnCountOnAbort = turnCount + 1;
498365
- if (maxTurns && nextTurnCountOnAbort > maxTurns) {
498393
+ const sleepRan = toolUseBlocks.some((b3) => b3.name === SLEEP_TOOL_NAME);
498394
+ const isMainThread = querySource.startsWith("repl_main_thread") || querySource === "sdk";
498395
+ const currentAgentId = toolUseContext.agentId;
498396
+ const queuedCommandsSnapshot = getCommandsByMaxPriority(sleepRan ? "later" : "next").filter((cmd) => {
498397
+ if (isSlashCommand(cmd))
498398
+ return false;
498399
+ if (isMainThread)
498400
+ return cmd.agentId === undefined;
498401
+ return cmd.mode === "task-notification" && cmd.agentId === currentAgentId;
498402
+ });
498403
+ for await (const attachment of getAttachmentMessages(null, updatedToolUseContext, null, queuedCommandsSnapshot, [...messagesForQuery, ...assistantMessages, ...toolResults], querySource)) {
498404
+ yield attachment;
498405
+ toolResults.push(attachment);
498406
+ }
498407
+ if (pendingMemoryPrefetch && pendingMemoryPrefetch.settledAt !== null && pendingMemoryPrefetch.consumedOnIteration === -1) {
498408
+ const memoryAttachments = filterDuplicateMemoryAttachments(await pendingMemoryPrefetch.promise, toolUseContext.readFileState);
498409
+ for (const memAttachment of memoryAttachments) {
498410
+ const msg = createAttachmentMessage(memAttachment);
498411
+ yield msg;
498412
+ toolResults.push(msg);
498413
+ }
498414
+ pendingMemoryPrefetch.consumedOnIteration = turnCount - 1;
498415
+ }
498416
+ if (skillPrefetch && pendingSkillPrefetch) {
498417
+ const skillAttachments = await skillPrefetch.collectSkillDiscoveryPrefetch(pendingSkillPrefetch);
498418
+ for (const att of skillAttachments) {
498419
+ const msg = createAttachmentMessage(att);
498420
+ yield msg;
498421
+ toolResults.push(msg);
498422
+ }
498423
+ }
498424
+ const consumedCommands = queuedCommandsSnapshot.filter((cmd) => cmd.mode === "prompt" || cmd.mode === "task-notification");
498425
+ if (consumedCommands.length > 0) {
498426
+ for (const cmd of consumedCommands) {
498427
+ if (cmd.uuid) {
498428
+ consumedCommandUuids.push(cmd.uuid);
498429
+ notifyCommandLifecycle(cmd.uuid, "started");
498430
+ }
498431
+ }
498432
+ remove(consumedCommands);
498433
+ }
498434
+ const fileChangeAttachmentCount = count2(toolResults, (tr) => tr.type === "attachment" && tr.attachment.type === "edited_text_file");
498435
+ if (updatedToolUseContext.options.refreshTools) {
498436
+ const refreshedTools = updatedToolUseContext.options.refreshTools();
498437
+ if (refreshedTools !== updatedToolUseContext.options.tools) {
498438
+ updatedToolUseContext = {
498439
+ ...updatedToolUseContext,
498440
+ options: {
498441
+ ...updatedToolUseContext.options,
498442
+ tools: refreshedTools
498443
+ }
498444
+ };
498445
+ }
498446
+ }
498447
+ const toolUseContextWithQueryTracking = {
498448
+ ...updatedToolUseContext,
498449
+ queryTracking
498450
+ };
498451
+ const nextTurnCount = turnCount + 1;
498452
+ if (false) {}
498453
+ if (maxTurns && nextTurnCount > maxTurns) {
498366
498454
  yield createAttachmentMessage({
498367
498455
  type: "max_turns_reached",
498368
498456
  maxTurns,
498369
- turnCount: nextTurnCountOnAbort
498457
+ turnCount: nextTurnCount
498370
498458
  });
498459
+ return { reason: "max_turns", turnCount: nextTurnCount };
498371
498460
  }
498372
- return { reason: "aborted_tools" };
498373
- }
498374
- if (shouldPreventContinuation) {
498375
- return { reason: "hook_stopped" };
498376
- }
498377
- if (tracking?.compacted) {
498378
- tracking.turnCounter++;
498379
- }
498380
- const sleepRan = toolUseBlocks.some((b3) => b3.name === SLEEP_TOOL_NAME);
498381
- const isMainThread = querySource.startsWith("repl_main_thread") || querySource === "sdk";
498382
- const currentAgentId = toolUseContext.agentId;
498383
- const queuedCommandsSnapshot = getCommandsByMaxPriority(sleepRan ? "later" : "next").filter((cmd) => {
498384
- if (isSlashCommand(cmd))
498385
- return false;
498386
- if (isMainThread)
498387
- return cmd.agentId === undefined;
498388
- return cmd.mode === "task-notification" && cmd.agentId === currentAgentId;
498389
- });
498390
- for await (const attachment of getAttachmentMessages(null, updatedToolUseContext, null, queuedCommandsSnapshot, [...messagesForQuery, ...assistantMessages, ...toolResults], querySource)) {
498391
- yield attachment;
498392
- toolResults.push(attachment);
498393
- }
498394
- if (pendingMemoryPrefetch && pendingMemoryPrefetch.settledAt !== null && pendingMemoryPrefetch.consumedOnIteration === -1) {
498395
- const memoryAttachments = filterDuplicateMemoryAttachments(await pendingMemoryPrefetch.promise, toolUseContext.readFileState);
498396
- for (const memAttachment of memoryAttachments) {
498397
- const msg = createAttachmentMessage(memAttachment);
498398
- yield msg;
498399
- toolResults.push(msg);
498400
- }
498401
- pendingMemoryPrefetch.consumedOnIteration = turnCount - 1;
498402
- }
498403
- if (skillPrefetch && pendingSkillPrefetch) {
498404
- const skillAttachments = await skillPrefetch.collectSkillDiscoveryPrefetch(pendingSkillPrefetch);
498405
- for (const att of skillAttachments) {
498406
- const msg = createAttachmentMessage(att);
498407
- yield msg;
498408
- toolResults.push(msg);
498409
- }
498410
- }
498411
- const consumedCommands = queuedCommandsSnapshot.filter((cmd) => cmd.mode === "prompt" || cmd.mode === "task-notification");
498412
- if (consumedCommands.length > 0) {
498413
- for (const cmd of consumedCommands) {
498414
- if (cmd.uuid) {
498415
- consumedCommandUuids.push(cmd.uuid);
498416
- notifyCommandLifecycle(cmd.uuid, "started");
498417
- }
498418
- }
498419
- remove(consumedCommands);
498420
- }
498421
- const fileChangeAttachmentCount = count2(toolResults, (tr) => tr.type === "attachment" && tr.attachment.type === "edited_text_file");
498422
- if (updatedToolUseContext.options.refreshTools) {
498423
- const refreshedTools = updatedToolUseContext.options.refreshTools();
498424
- if (refreshedTools !== updatedToolUseContext.options.tools) {
498425
- updatedToolUseContext = {
498426
- ...updatedToolUseContext,
498427
- options: {
498428
- ...updatedToolUseContext.options,
498429
- tools: refreshedTools
498430
- }
498431
- };
498432
- }
498461
+ queryCheckpoint("query_recursive_call");
498462
+ const next2 = {
498463
+ messages: [...messagesForQuery, ...assistantMessages, ...toolResults],
498464
+ toolUseContext: toolUseContextWithQueryTracking,
498465
+ autoCompactTracking: tracking,
498466
+ turnCount: nextTurnCount,
498467
+ maxOutputTokensRecoveryCount: 0,
498468
+ hasAttemptedReactiveCompact: false,
498469
+ pendingToolUseSummary: nextPendingToolUseSummary,
498470
+ maxOutputTokensOverride: undefined,
498471
+ stopHookActive,
498472
+ transition: { reason: "next_turn" }
498473
+ };
498474
+ state = next2;
498433
498475
  }
498434
- const toolUseContextWithQueryTracking = {
498435
- ...updatedToolUseContext,
498436
- queryTracking
498437
- };
498438
- const nextTurnCount = turnCount + 1;
498439
- if (false) {}
498440
- if (maxTurns && nextTurnCount > maxTurns) {
498441
- yield createAttachmentMessage({
498442
- type: "max_turns_reached",
498443
- maxTurns,
498444
- turnCount: nextTurnCount
498445
- });
498446
- return { reason: "max_turns", turnCount: nextTurnCount };
498447
- }
498448
- queryCheckpoint("query_recursive_call");
498449
- const next2 = {
498450
- messages: [...messagesForQuery, ...assistantMessages, ...toolResults],
498451
- toolUseContext: toolUseContextWithQueryTracking,
498452
- autoCompactTracking: tracking,
498453
- turnCount: nextTurnCount,
498454
- maxOutputTokensRecoveryCount: 0,
498455
- hasAttemptedReactiveCompact: false,
498456
- pendingToolUseSummary: nextPendingToolUseSummary,
498457
- maxOutputTokensOverride: undefined,
498458
- stopHookActive,
498459
- transition: { reason: "next_turn" }
498460
- };
498461
- state = next2;
498476
+ } finally {
498477
+ pendingMemoryPrefetch?.[Symbol.dispose]();
498462
498478
  }
498463
498479
  }
498464
498480
  function buildRouteContext(turnCount, querySource, messages, maxBudgetUsd) {
@@ -515661,7 +515677,7 @@ var init_filesystem = __esm(() => {
515661
515677
  });
515662
515678
  getBundledSkillsRoot = memoize_default(function getBundledSkillsRoot2() {
515663
515679
  const nonce = randomBytes18(16).toString("hex");
515664
- return join146(getClaudeTempDir(), "bundled-skills", "1.0.0-alpha.22", nonce);
515680
+ return join146(getClaudeTempDir(), "bundled-skills", "1.0.0-alpha.23", nonce);
515665
515681
  });
515666
515682
  getResolvedWorkingDirPaths = memoize_default(getPathsForPermissionCheck);
515667
515683
  });
@@ -521591,7 +521607,7 @@ function computeFingerprintFromMessages(messages) {
521591
521607
  }
521592
521608
  var AGENT_OS_VERSION5, FINGERPRINT_SALT = "59cf53e54c78";
521593
521609
  var init_fingerprint = __esm(() => {
521594
- AGENT_OS_VERSION5 = typeof MACRO !== "undefined" ? "1.0.0-alpha.22" : "dev";
521610
+ AGENT_OS_VERSION5 = typeof MACRO !== "undefined" ? "1.0.0-alpha.23" : "dev";
521595
521611
  });
521596
521612
 
521597
521613
  // src/services/compact/apiMicrocompact.ts
@@ -523345,7 +523361,7 @@ async function sideQuery(opts) {
523345
523361
  betas.push(STRUCTURED_OUTPUTS_BETA_HEADER);
523346
523362
  }
523347
523363
  const messageText = extractFirstUserMessageText(messages);
523348
- const fingerprint = computeFingerprint(messageText, "1.0.0-alpha.22");
523364
+ const fingerprint = computeFingerprint(messageText, "1.0.0-alpha.23");
523349
523365
  const attributionHeader = getAttributionHeader(fingerprint);
523350
523366
  const systemBlocks = [
523351
523367
  attributionHeader ? { type: "text", text: attributionHeader } : null,
@@ -525264,7 +525280,7 @@ function appendToLog(path24, message) {
525264
525280
  cwd: getFsImplementation().cwd(),
525265
525281
  userType: process.env.USER_TYPE,
525266
525282
  sessionId: getSessionId(),
525267
- version: "1.0.0-alpha.22"
525283
+ version: "1.0.0-alpha.23"
525268
525284
  };
525269
525285
  getLogWriter(path24).write(messageWithTimestamp);
525270
525286
  }
@@ -528242,7 +528258,7 @@ function getTelemetryAttributes() {
528242
528258
  attributes["session.id"] = sessionId;
528243
528259
  }
528244
528260
  if (shouldIncludeAttribute("OTEL_METRICS_INCLUDE_VERSION")) {
528245
- attributes["app.version"] = "1.0.0-alpha.22";
528261
+ attributes["app.version"] = "1.0.0-alpha.23";
528246
528262
  }
528247
528263
  if (envDynamic.terminal) {
528248
528264
  attributes["terminal.type"] = envDynamic.terminal;
@@ -538386,7 +538402,7 @@ function buildSystemInitMessage(inputs) {
538386
538402
  slash_commands: inputs.commands.filter((c5) => c5.userInvocable !== false).map((c5) => c5.name),
538387
538403
  apiKeySource: getAnthropicApiKeyWithSource().source,
538388
538404
  betas: getSdkBetas(),
538389
- claude_code_version: "1.0.0-alpha.22",
538405
+ claude_code_version: "1.0.0-alpha.23",
538390
538406
  output_style: outputStyle2,
538391
538407
  agents: inputs.agents.map((agent) => agent.agentType),
538392
538408
  skills: inputs.skills.filter((s2) => s2.userInvocable !== false).map((skill) => skill.name),
@@ -560855,7 +560871,7 @@ function buildStatusLineCommandInput(permissionMode, exceeds200kTokens, settings
560855
560871
  project_dir: getOriginalCwd(),
560856
560872
  added_dirs: addedDirs
560857
560873
  },
560858
- version: "1.0.0-alpha.22",
560874
+ version: "1.0.0-alpha.23",
560859
560875
  output_style: {
560860
560876
  name: outputStyleName
560861
560877
  },
@@ -584211,7 +584227,7 @@ function WelcomeV2() {
584211
584227
  dimColor: true,
584212
584228
  children: [
584213
584229
  "v",
584214
- "1.0.0-alpha.22",
584230
+ "1.0.0-alpha.23",
584215
584231
  " "
584216
584232
  ]
584217
584233
  })
@@ -584411,7 +584427,7 @@ function WelcomeV2() {
584411
584427
  dimColor: true,
584412
584428
  children: [
584413
584429
  "v",
584414
- "1.0.0-alpha.22",
584430
+ "1.0.0-alpha.23",
584415
584431
  " "
584416
584432
  ]
584417
584433
  })
@@ -584637,7 +584653,7 @@ function AppleTerminalWelcomeV2(t0) {
584637
584653
  dimColor: true,
584638
584654
  children: [
584639
584655
  "v",
584640
- "1.0.0-alpha.22",
584656
+ "1.0.0-alpha.23",
584641
584657
  " "
584642
584658
  ]
584643
584659
  });
@@ -584891,7 +584907,7 @@ function AppleTerminalWelcomeV2(t0) {
584891
584907
  dimColor: true,
584892
584908
  children: [
584893
584909
  "v",
584894
- "1.0.0-alpha.22",
584910
+ "1.0.0-alpha.23",
584895
584911
  " "
584896
584912
  ]
584897
584913
  });
@@ -586357,7 +586373,7 @@ function completeOnboarding() {
586357
586373
  saveGlobalConfig((current) => ({
586358
586374
  ...current,
586359
586375
  hasCompletedOnboarding: true,
586360
- lastOnboardingVersion: "1.0.0-alpha.22"
586376
+ lastOnboardingVersion: "1.0.0-alpha.23"
586361
586377
  }));
586362
586378
  }
586363
586379
  function showDialog(root3, renderer) {
@@ -594820,8 +594836,8 @@ async function getEnvLessBridgeConfig() {
594820
594836
  }
594821
594837
  async function checkEnvLessBridgeMinVersion() {
594822
594838
  const cfg = await getEnvLessBridgeConfig();
594823
- if (cfg.min_version && lt("1.0.0-alpha.22", cfg.min_version)) {
594824
- return `Your version of Agent-OS (${"1.0.0-alpha.22"}) is too old for Remote Control.
594839
+ if (cfg.min_version && lt("1.0.0-alpha.23", cfg.min_version)) {
594840
+ return `Your version of Agent-OS (${"1.0.0-alpha.23"}) is too old for Remote Control.
594825
594841
  Version ${cfg.min_version} or higher is required. Run \`agent-os update\` to update.`;
594826
594842
  }
594827
594843
  return null;
@@ -595294,7 +595310,7 @@ async function initBridgeCore(params) {
595294
595310
  const rawApi = createBridgeApiClient({
595295
595311
  baseUrl,
595296
595312
  getAccessToken,
595297
- runnerVersion: "1.0.0-alpha.22",
595313
+ runnerVersion: "1.0.0-alpha.23",
595298
595314
  onDebug: logForDebugging,
595299
595315
  onAuth401,
595300
595316
  getTrustedDeviceToken
@@ -600973,7 +600989,7 @@ async function startMCPServer(cwd3, debug2, verbose) {
600973
600989
  setCwd(cwd3);
600974
600990
  const server = new Server({
600975
600991
  name: "claude/tengu",
600976
- version: "1.0.0-alpha.22"
600992
+ version: "1.0.0-alpha.23"
600977
600993
  }, {
600978
600994
  capabilities: {
600979
600995
  tools: {}
@@ -606484,7 +606500,7 @@ ${customInstructions}` : customInstructions;
606484
606500
  }
606485
606501
  }
606486
606502
  logForDiagnosticsNoPII("info", "started", {
606487
- version: "1.0.0-alpha.22",
606503
+ version: "1.0.0-alpha.23",
606488
606504
  is_native_binary: isInBundledMode()
606489
606505
  });
606490
606506
  registerCleanup(async () => {
@@ -607276,7 +607292,7 @@ Usage: agent-os --remote "your task description"`, () => gracefulShutdown(1));
607276
607292
  pendingHookMessages
607277
607293
  }, renderAndRun);
607278
607294
  }
607279
- }).version("1.0.0-alpha.22 (Agent-OS)", "-v, --version", "Output the version number");
607295
+ }).version("1.0.0-alpha.23 (Agent-OS)", "-v, --version", "Output the version number");
607280
607296
  program2.option("-w, --worktree [name]", "Create a new git worktree for this session (optionally specify a name)");
607281
607297
  program2.option("--tmux", "Create a tmux session for the worktree (requires --worktree). Uses iTerm2 native panes when available; use --tmux=classic for traditional tmux.");
607282
607298
  if (canUserConfigureAdvisor()) {
@@ -609114,7 +609130,7 @@ if (false) {}
609114
609130
  async function main2() {
609115
609131
  const args = process.argv.slice(2);
609116
609132
  if (args.length === 1 && (args[0] === "--version" || args[0] === "-v" || args[0] === "-V")) {
609117
- console.log(`${"1.0.0-alpha.22"} (Agent-OS)`);
609133
+ console.log(`${"1.0.0-alpha.23"} (Agent-OS)`);
609118
609134
  return;
609119
609135
  }
609120
609136
  const {