@orbit-build/cli 0.8.3 → 0.8.6

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 (45) hide show
  1. package/README.md +4 -1
  2. package/commands/cumcm-draft.md +3 -1
  3. package/dist/index.js +1158 -310
  4. package/package.json +1 -1
  5. package/skills/cumcm-draft/SKILL.md +102 -48
  6. package/skills/cumcm-draft/agents/openai.yaml +1 -1
  7. package/skills/cumcm-draft/assets/project-template/{code → .cumcm}/finalize.py +33 -4
  8. package/skills/cumcm-draft/assets/project-template/{paper/contest-profile.json → .cumcm/profile.json} +9 -6
  9. package/skills/cumcm-draft/assets/project-template/code/requirements.txt +1 -11
  10. package/skills/cumcm-draft/assets/project-template/paper/AI/345/267/245/345/205/267/344/275/277/347/224/250/350/257/246/346/203/205.tex +1 -11
  11. package/skills/cumcm-draft/assets/project-template/paper/main.tex +70 -11
  12. package/skills/cumcm-draft/references/code-and-output-style.md +9 -14
  13. package/skills/cumcm-draft/references/cumcm-compliance.md +28 -25
  14. package/skills/cumcm-draft/references/latex-figures-tables.md +1 -1
  15. package/skills/cumcm-draft/references/modeling-quality.md +1 -1
  16. package/skills/cumcm-draft/references/paper-architecture.md +3 -3
  17. package/skills/cumcm-draft/references/project-architecture.md +70 -89
  18. package/skills/cumcm-draft/scripts/audit_paper.py +37 -9
  19. package/skills/cumcm-draft/scripts/bootstrap_project.py +198 -56
  20. package/skills/cumcm-draft/scripts/build_paper.py +38 -23
  21. package/skills/cumcm-draft/scripts/capture_environment.py +3 -1
  22. package/skills/cumcm-draft/scripts/clean_project.py +7 -2
  23. package/skills/cumcm-draft/scripts/evidence_freeze.py +8 -4
  24. package/skills/cumcm-draft/scripts/finalize_project.py +16 -0
  25. package/skills/cumcm-draft/scripts/inspect_inputs.py +6 -4
  26. package/skills/cumcm-draft/scripts/package_support.py +41 -15
  27. package/skills/cumcm-draft/scripts/project_utils.py +40 -8
  28. package/skills/cumcm-draft/scripts/validate_project.py +394 -57
  29. package/skills/cumcm-draft/assets/project-template/code/always/__init__.py +0 -1
  30. package/skills/cumcm-draft/assets/project-template/code/always/config.py +0 -18
  31. package/skills/cumcm-draft/assets/project-template/code/always/data.py +0 -24
  32. package/skills/cumcm-draft/assets/project-template/code/always/plotting.py +0 -25
  33. package/skills/cumcm-draft/assets/project-template/code/always/validation.py +0 -21
  34. package/skills/cumcm-draft/assets/project-template/paper/sections/abstract.tex +0 -6
  35. package/skills/cumcm-draft/assets/project-template/paper/sections/ai-disclosure.tex +0 -3
  36. package/skills/cumcm-draft/assets/project-template/paper/sections/appendix.tex +0 -3
  37. package/skills/cumcm-draft/assets/project-template/paper/sections/assumptions.tex +0 -5
  38. package/skills/cumcm-draft/assets/project-template/paper/sections/data.tex +0 -19
  39. package/skills/cumcm-draft/assets/project-template/paper/sections/evaluation.tex +0 -9
  40. package/skills/cumcm-draft/assets/project-template/paper/sections/problem-analysis.tex +0 -3
  41. package/skills/cumcm-draft/assets/project-template/paper/sections/problem-restatement.tex +0 -3
  42. package/skills/cumcm-draft/assets/project-template/paper/sections/references.tex +0 -12
  43. package/skills/cumcm-draft/assets/project-template/paper/sections/source-code.tex +0 -1
  44. package/skills/cumcm-draft/assets/project-template/paper/sections/support-files.tex +0 -3
  45. /package/skills/cumcm-draft/assets/project-template/{paper → .cumcm}/ai-use-log.md +0 -0
package/dist/index.js CHANGED
@@ -239238,8 +239238,8 @@ function localizeOrbit(language, english, simplifiedChinese, traditionalChinese)
239238
239238
  return language === "zh" ? simplifiedChinese : english;
239239
239239
  }
239240
239240
  var ORBIT_CONFIG_SCHEMA_VERSION = 1;
239241
- var DEFAULT_AGENT_MAX_ITERATIONS = 64;
239242
- var MAX_AGENT_MAX_ITERATIONS = 200;
239241
+ var DEFAULT_AGENT_MAX_ITERATIONS = 200;
239242
+ var MAX_AGENT_MAX_ITERATIONS = 1e3;
239243
239243
  var EnvironmentVariableNameSchema = z22.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/);
239244
239244
  var HttpHeaderNameSchema = z22.string().max(256).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/);
239245
239245
  var HttpHeaderValueSchema = z22.string().max(16384).refine((value) => !/[\r\n]/.test(value));
@@ -239595,7 +239595,8 @@ var ConfigSchema = z22.object({
239595
239595
  requireWriteApproval: z22.boolean().default(false),
239596
239596
  requireBashApproval: z22.boolean().default(false),
239597
239597
  disableWebSearch: z22.boolean().default(false),
239598
- disableMcp: z22.boolean().default(false)
239598
+ disableMcp: z22.boolean().default(false),
239599
+ maxIterations: z22.number().int().positive().max(MAX_AGENT_MAX_ITERATIONS).optional()
239599
239600
  }).optional(),
239600
239601
  hooks: z22.object({
239601
239602
  preEdit: z22.string().max(2e4).optional(),
@@ -239732,8 +239733,10 @@ var DEFAULT_CONFIG = {
239732
239733
  testCommands: []
239733
239734
  },
239734
239735
  agent: {
239735
- // Long enough for document, migration, and verification workflows; the
239736
- // progress guard, periodic checkpoints, and budget still bound bad runs.
239736
+ // Long enough for complete document, migration, and verification
239737
+ // workflows. Normal modes retain periodic consent; Full Access continues
239738
+ // checkpoints without interruption. Progress and budget guards still
239739
+ // bound unhealthy runs.
239737
239740
  maxIterations: DEFAULT_AGENT_MAX_ITERATIONS,
239738
239741
  fastMaxOutputTokens: 32768,
239739
239742
  maxOutputTokens: 16384,
@@ -240603,7 +240606,8 @@ function applyManagedPolicy(source, policy) {
240603
240606
  requireWriteApproval: policy.requireWriteApproval,
240604
240607
  requireBashApproval: policy.requireBashApproval,
240605
240608
  disableWebSearch: policy.disableWebSearch,
240606
- disableMcp: policy.disableMcp
240609
+ disableMcp: policy.disableMcp,
240610
+ maxIterations: policy.maxIterations
240607
240611
  };
240608
240612
  return config;
240609
240613
  }
@@ -240628,6 +240632,9 @@ function validateManagedRuntimeChange(config, change) {
240628
240632
  if (change.webSearchEnabled && policy.disableWebSearch) {
240629
240633
  return "Managed policy disables web search.";
240630
240634
  }
240635
+ if (change.agentMaxIterations !== void 0 && policy.maxIterations !== void 0 && change.agentMaxIterations > policy.maxIterations) {
240636
+ return `Managed policy limits agent runs to ${policy.maxIterations} iterations.`;
240637
+ }
240631
240638
  return void 0;
240632
240639
  }
240633
240640
  function permissionRank(mode) {
@@ -242956,7 +242963,6 @@ async function fetchWithRetry(url, init, maxRetries = 3) {
242956
242963
  const timeoutId = setTimeout(() => {
242957
242964
  controller.abort();
242958
242965
  }, timeoutMs);
242959
- timeoutId.unref?.();
242960
242966
  try {
242961
242967
  const response = await fetch(url, {
242962
242968
  ...init,
@@ -243029,6 +243035,33 @@ function sanitizeProviderError(value, secrets = [], fallbackMessage = "Unknown p
243029
243035
  error.name = source.name;
243030
243036
  return error;
243031
243037
  }
243038
+ function normalizeProviderStreamError(value, secrets = [], partialOutput = false) {
243039
+ const source = sanitizeProviderError(value, secrets);
243040
+ if (source.name === "AbortError") return source;
243041
+ if (source instanceof ProviderError) {
243042
+ return new ProviderError(source.code, source.message, {
243043
+ status: source.status,
243044
+ retryAfterMs: source.retryAfterMs,
243045
+ requestId: source.requestId,
243046
+ retryable: source.retryable,
243047
+ partialOutput,
243048
+ cause: source.cause
243049
+ });
243050
+ }
243051
+ const timeout = source.name === "TimeoutError" || /(?:timed?\s*out|timeout)/i.test(source.message);
243052
+ const closed = /(?:\bterminated\b|premature(?:ly)?\s+closed|other side closed|socket(?:\s+hang\s+up|\s+closed)?|stream (?:ended|closed) before|fetch failed|network connection (?:was )?lost|ECONNRESET|EPIPE|UND_ERR_(?:SOCKET|ABORTED))/i.test(
243053
+ source.message
243054
+ );
243055
+ return new ProviderError(
243056
+ timeout ? "TIMEOUT" : closed ? "STREAM_CLOSED" : "MALFORMED_RESPONSE",
243057
+ source.message,
243058
+ {
243059
+ retryable: timeout || closed,
243060
+ partialOutput,
243061
+ cause: source
243062
+ }
243063
+ );
243064
+ }
243032
243065
  function providerHttpError(provider, status, responseBody, secrets = [], metadata = {}) {
243033
243066
  const detail = sanitizeProviderErrorText(responseBody, secrets);
243034
243067
  const normalized = detail.toLowerCase();
@@ -243077,7 +243110,6 @@ function abortableDelay(delayMs, signal) {
243077
243110
  cleanup();
243078
243111
  resolve26();
243079
243112
  }, delayMs);
243080
- timeoutId.unref?.();
243081
243113
  function onAbort() {
243082
243114
  clearTimeout(timeoutId);
243083
243115
  cleanup();
@@ -243729,9 +243761,14 @@ var AnthropicCompatibleProvider = class {
243729
243761
  this.options.maxRetries ?? (this.isOfficialDeepSeekEndpoint() ? 0 : 2)
243730
243762
  );
243731
243763
  } catch (error) {
243764
+ const sanitized = sanitizeProviderError(error, [key]);
243732
243765
  yield {
243733
243766
  type: "error",
243734
- error: sanitizeProviderError(error, [key])
243767
+ error: isProviderError(sanitized) ? sanitized : new ProviderError(
243768
+ sanitized.name === "TimeoutError" ? "TIMEOUT" : "TRANSPORT",
243769
+ sanitized.message,
243770
+ { retryable: true, cause: sanitized }
243771
+ )
243735
243772
  };
243736
243773
  return;
243737
243774
  }
@@ -244066,9 +244103,14 @@ var AnthropicCompatibleProvider = class {
244066
244103
  yield { type: "done" };
244067
244104
  }
244068
244105
  } catch (error) {
244106
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244069
244107
  yield {
244070
244108
  type: "error",
244071
- error: sanitizeProviderError(error, [key])
244109
+ error: normalizeProviderStreamError(
244110
+ abortReason ?? error,
244111
+ [key],
244112
+ emittedToolCalls > 0
244113
+ )
244072
244114
  };
244073
244115
  } finally {
244074
244116
  if (streamTimeoutId) clearTimeout(streamTimeoutId);
@@ -244493,7 +244535,6 @@ async function* parseStreamingResponse(input, options, response, controller) {
244493
244535
  )
244494
244536
  );
244495
244537
  }, streamTimeoutMs);
244496
- timeoutId.unref?.();
244497
244538
  };
244498
244539
  const outputKey = (outputIndex, itemId) => {
244499
244540
  const aliased = itemId ? outputAliases.get(itemId) : void 0;
@@ -244729,25 +244770,11 @@ async function* parseStreamingResponse(input, options, response, controller) {
244729
244770
  );
244730
244771
  }
244731
244772
  } catch (error) {
244732
- const source = toError(error);
244733
- if (source instanceof ProviderError) {
244734
- throw new ProviderError(source.code, source.message, {
244735
- status: source.status,
244736
- retryAfterMs: source.retryAfterMs,
244737
- requestId: source.requestId,
244738
- retryable: source.retryable,
244739
- partialOutput: emittedOutput || tools.size > 0,
244740
- cause: source.cause
244741
- });
244742
- }
244743
- throw new ProviderError(
244744
- source.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
244745
- source.message,
244746
- {
244747
- retryable: source.name === "TimeoutError",
244748
- partialOutput: emittedOutput || tools.size > 0,
244749
- cause: source
244750
- }
244773
+ const abortReason = controller.signal.aborted ? controller.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244774
+ throw normalizeProviderStreamError(
244775
+ abortReason ?? error,
244776
+ [options.apiKey],
244777
+ emittedOutput || tools.size > 0
244751
244778
  );
244752
244779
  } finally {
244753
244780
  if (timeoutId) clearTimeout(timeoutId);
@@ -245869,22 +245896,11 @@ ${jsonInstruction}`;
245869
245896
  yield { type: "done" };
245870
245897
  }
245871
245898
  } catch (error) {
245872
- const sanitized = sanitizeProviderError(error, [key]);
245873
- const streamError = isProviderError(sanitized) ? new ProviderError(sanitized.code, sanitized.message, {
245874
- status: sanitized.status,
245875
- retryAfterMs: sanitized.retryAfterMs,
245876
- requestId: sanitized.requestId,
245877
- retryable: sanitized.retryable,
245878
- partialOutput: emittedOutput || streamingTools.size > 0,
245879
- cause: sanitized.cause
245880
- }) : new ProviderError(
245881
- sanitized.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
245882
- sanitized.message,
245883
- {
245884
- retryable: sanitized.name === "TimeoutError",
245885
- partialOutput: emittedOutput || streamingTools.size > 0,
245886
- cause: sanitized
245887
- }
245899
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
245900
+ const streamError = normalizeProviderStreamError(
245901
+ abortReason ?? error,
245902
+ [key],
245903
+ emittedOutput || streamingTools.size > 0
245888
245904
  );
245889
245905
  yield {
245890
245906
  type: "error",
@@ -247801,10 +247817,10 @@ import glob2 from "fast-glob";
247801
247817
  import { z as z16 } from "zod";
247802
247818
  import { z as z17 } from "zod";
247803
247819
  import { existsSync as existsSync7 } from "fs";
247804
- import { join as join32 } from "path";
247820
+ import { win32 as win322 } from "path";
247805
247821
  import { z as z18 } from "zod";
247806
247822
  import { existsSync as existsSync8 } from "fs";
247807
- import { join as join42 } from "path";
247823
+ import { join as join32, resolve as resolve32 } from "path";
247808
247824
  import { z as z20 } from "zod";
247809
247825
  var import_ipaddr = __toESM(require_ipaddr(), 1);
247810
247826
  import { lookup } from "dns/promises";
@@ -249563,45 +249579,73 @@ function firstExistingPath(candidates, pathExists = existsSync7) {
249563
249579
  }
249564
249580
  return null;
249565
249581
  }
249582
+ function normalizePowerShellCommand(command) {
249583
+ const leadingWhitespace = command.match(/^\s*/)?.[0] ?? "";
249584
+ const trimmed = command.slice(leadingWhitespace.length);
249585
+ if (/^&(?:\s|$)/.test(trimmed)) return command;
249586
+ const quotedExecutable = trimmed.match(/^(["'])([^"']+)\1(?=\s|$)/);
249587
+ const executablePath = quotedExecutable?.[2];
249588
+ if (!executablePath || !/[\\/]/.test(executablePath) && !/\.(?:exe|cmd|bat|com|ps1)$/i.test(executablePath)) {
249589
+ return command;
249590
+ }
249591
+ return `${leadingWhitespace}& ${trimmed}`;
249592
+ }
249566
249593
  function resolveCommandShellInvocation(command, options = {}) {
249567
249594
  const platform = options.platform ?? process.platform;
249568
249595
  const environment = options.environment ?? process.env;
249569
249596
  const pathExists = options.pathExists ?? existsSync7;
249570
249597
  if (platform !== "win32") {
249571
- const bash2 = firstExistingPath(
249598
+ const bash = firstExistingPath(
249572
249599
  [environment.ORBIT_BASH_PATH, "/bin/bash", "/usr/bin/bash"],
249573
249600
  pathExists
249574
249601
  );
249575
- if (bash2) {
249602
+ if (bash) {
249576
249603
  return {
249577
- file: bash2,
249578
- args: ["--noprofile", "--norc", "-c", command]
249604
+ file: bash,
249605
+ args: ["--noprofile", "--norc", "-c", command],
249606
+ dialect: "bash"
249579
249607
  };
249580
249608
  }
249581
249609
  return {
249582
249610
  file: "/bin/sh",
249583
- args: ["-c", command]
249611
+ args: ["-c", command],
249612
+ dialect: "sh"
249584
249613
  };
249585
249614
  }
249586
- const bash = firstExistingPath(
249615
+ const systemRoot = environment.SystemRoot || environment.WINDIR;
249616
+ const powershell = firstExistingPath(
249587
249617
  [
249588
- environment.ORBIT_BASH_PATH,
249589
- environment.ProgramFiles ? join32(environment.ProgramFiles, "Git", "bin", "bash.exe") : void 0,
249590
- environment["ProgramFiles(x86)"] ? join32(environment["ProgramFiles(x86)"], "Git", "bin", "bash.exe") : void 0,
249591
- environment.LOCALAPPDATA ? join32(environment.LOCALAPPDATA, "Programs", "Git", "bin", "bash.exe") : void 0,
249592
- environment.LOCALAPPDATA ? join32(environment.LOCALAPPDATA, "hermes", "git", "bin", "bash.exe") : void 0
249618
+ environment.ORBIT_POWERSHELL_PATH,
249619
+ environment.ProgramFiles ? win322.join(environment.ProgramFiles, "PowerShell", "7", "pwsh.exe") : void 0,
249620
+ environment.ProgramW6432 ? win322.join(environment.ProgramW6432, "PowerShell", "7", "pwsh.exe") : void 0,
249621
+ systemRoot ? win322.join(
249622
+ systemRoot,
249623
+ "System32",
249624
+ "WindowsPowerShell",
249625
+ "v1.0",
249626
+ "powershell.exe"
249627
+ ) : void 0
249593
249628
  ],
249594
249629
  pathExists
249595
249630
  );
249596
- if (bash) {
249631
+ if (powershell) {
249632
+ const normalizedCommand = normalizePowerShellCommand(command);
249633
+ const script = [
249634
+ "$ErrorActionPreference = 'Stop'",
249635
+ "$global:LASTEXITCODE = 0",
249636
+ `& { ${normalizedCommand} }`,
249637
+ "if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }"
249638
+ ].join("; ");
249597
249639
  return {
249598
- file: bash,
249599
- args: ["--noprofile", "--norc", "-lc", command]
249640
+ file: powershell,
249641
+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
249642
+ dialect: "powershell"
249600
249643
  };
249601
249644
  }
249602
249645
  return {
249603
249646
  file: environment.ComSpec?.trim() || "cmd.exe",
249604
- args: ["/d", "/s", "/c", command]
249647
+ args: ["/d", "/s", "/c", command],
249648
+ dialect: "cmd"
249605
249649
  };
249606
249650
  }
249607
249651
  var BashInputSchema = z17.object({
@@ -249611,7 +249655,7 @@ var BashInputSchema = z17.object({
249611
249655
  });
249612
249656
  var BashTool = class {
249613
249657
  name = "bash";
249614
- description = "Run a command in the local shell environment. Set background=true for dev servers, watchers, or long builds; this returns a task id immediately for use with the background task tools.";
249658
+ description = process.platform === "win32" ? "Run a command in native Windows PowerShell. The working directory is already the project root: use PowerShell cmdlets and do not prepend cd or use POSIX grep/sed/head/tail/heredoc syntax. A failed result already includes captured stdout/stderr, so diagnose that output instead of rerunning the same command through redirection. Set background=true only for dev servers, watchers, or long builds." : "Run a command in non-interactive Bash/POSIX sh. The working directory is already the project root; do not prepend cd. A failed result already includes captured stdout/stderr, so diagnose that output instead of rerunning the same command through redirection. Set background=true only for dev servers, watchers, or long builds.";
249615
249659
  inputSchema = BashInputSchema;
249616
249660
  risk = "execute";
249617
249661
  async execute(input, ctx) {
@@ -249706,7 +249750,8 @@ ${displayStderr}` : "",
249706
249750
  truncated,
249707
249751
  stdoutChars: stdout2.length,
249708
249752
  stderrChars: stderr.length,
249709
- outputLimitExceeded
249753
+ outputLimitExceeded,
249754
+ shellDialect: invocation.dialect
249710
249755
  }
249711
249756
  };
249712
249757
  } catch (error) {
@@ -249726,6 +249771,7 @@ ${displayStderr}` : "",
249726
249771
  var RunTestsInputSchema = z18.object({
249727
249772
  command: z18.string().trim().min(1).max(1e5).optional()
249728
249773
  });
249774
+ var ORBIT_TERMINAL_SUCCESS_MARKER = "[ORBIT_TERMINAL_SUCCESS]";
249729
249775
  function classifyVerificationCommand(command) {
249730
249776
  if (/[\r\n&]/.test(command) || /(?:--if-present|--passwithnotests|--allow-no-tests)(?:\s|=|$)/i.test(
249731
249777
  command
@@ -249764,19 +249810,46 @@ function classifyVerificationCommand(command) {
249764
249810
  )) {
249765
249811
  return "test";
249766
249812
  }
249767
- if (/^(?:python(?:\.exe)? -m compileall|(?:"[^"]*[\\/])?node(?:\.exe)?"? --check)(?:\s|$)/i.test(
249813
+ if (/^(?:python(?:\.exe)? -m (?:compileall|py_compile)|(?:"[^"]*[\\/])?node(?:\.exe)?"? --check)(?:\s|$)/i.test(
249768
249814
  normalized
249769
249815
  )) {
249770
249816
  return "syntax";
249771
249817
  }
249818
+ if (/^python(?:\.exe)? (?:"[^"]*(?:[\\/](?:code|\.cumcm)[\\/]finalize\.py)"|'[^']*(?:[\\/](?:code|\.cumcm)[\\/]finalize\.py)'|(?:\S*[\\/])?(?:code|\.cumcm)[\\/]finalize\.py)(?:\s|$)/i.test(
249819
+ normalized
249820
+ )) {
249821
+ return "build";
249822
+ }
249772
249823
  if (/^(?:cmake --build|dotnet build)(?:\s|$)/i.test(normalized)) {
249773
249824
  return "build";
249774
249825
  }
249775
249826
  return void 0;
249776
249827
  }
249828
+ function detectTrustedTerminalSuccess(command, cwd, output, exitCode) {
249829
+ if (exitCode !== 0 || classifyVerificationCommand(command) !== "build" || !output.includes(ORBIT_TERMINAL_SUCCESS_MARKER)) {
249830
+ return void 0;
249831
+ }
249832
+ const normalized = command.trim().replace(/\s+/g, " ");
249833
+ const match = /^python(?:\.exe)?\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?=\s|$)/i.exec(
249834
+ normalized
249835
+ );
249836
+ const script = match?.[1] || match?.[2] || match?.[3];
249837
+ if (!script) return void 0;
249838
+ const actual = comparablePath(resolve32(cwd, script));
249839
+ const expected = [
249840
+ resolve32(cwd, ".cumcm", "finalize.py"),
249841
+ // Read compatibility for projects scaffolded by Orbit <= 0.8.3.
249842
+ resolve32(cwd, "code", "finalize.py")
249843
+ ].map(comparablePath);
249844
+ return expected.includes(actual) ? "cumcm-finalizer" : void 0;
249845
+ }
249846
+ function comparablePath(value) {
249847
+ const normalized = value.replace(/\\/g, "/");
249848
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
249849
+ }
249777
249850
  var RunTestsTool = class {
249778
249851
  name = "run_tests";
249779
- description = "Run a standalone project verification command. Recognized test, build, lint, typecheck, or syntax commands count toward the completion gate; arbitrary shell commands do not. If omitted, Orbit auto-detects the project test runner.";
249852
+ description = "Run one standalone project verification command in the native OS shell. Recognized test, build, lint, typecheck, or syntax commands (including python -m py_compile) count toward the completion gate; arbitrary or piped shell commands do not. If omitted, Orbit auto-detects the project test runner.";
249780
249853
  inputSchema = RunTestsInputSchema;
249781
249854
  risk = "execute";
249782
249855
  async execute(input, ctx) {
@@ -249810,6 +249883,13 @@ var RunTestsTool = class {
249810
249883
  const failureMessage = readProcessFailureMessage(result);
249811
249884
  const outputLimitExceeded = result.failed && /maxBuffer exceeded/i.test(failureMessage);
249812
249885
  const exitCode = result.exitCode ?? (result.failed ? 1 : 0);
249886
+ const terminalSuccess = detectTrustedTerminalSuccess(
249887
+ testCommand,
249888
+ ctx.cwd,
249889
+ `${stdout2}
249890
+ ${stderr}`,
249891
+ exitCode
249892
+ );
249813
249893
  const displayStdout = redactSecrets(
249814
249894
  LogTruncator.truncate(stdout2, 150, 2e4)
249815
249895
  );
@@ -249836,7 +249916,8 @@ Exit code: ${exitCode}`,
249836
249916
  stderrChars: stderr.length,
249837
249917
  outputLimitExceeded,
249838
249918
  verificationEvidence: verificationKind !== void 0,
249839
- ...verificationKind ? { verificationKind } : {}
249919
+ ...verificationKind ? { verificationKind } : {},
249920
+ ...terminalSuccess ? { terminalSuccess } : {}
249840
249921
  }
249841
249922
  };
249842
249923
  } catch (error) {
@@ -249853,36 +249934,36 @@ Exit code: ${exitCode}`,
249853
249934
  }
249854
249935
  }
249855
249936
  inferTestCommand(cwd) {
249856
- if (existsSync8(join42(cwd, "Cargo.toml"))) {
249937
+ if (existsSync8(join32(cwd, "Cargo.toml"))) {
249857
249938
  return "cargo test";
249858
249939
  }
249859
- if (existsSync8(join42(cwd, "go.mod"))) {
249940
+ if (existsSync8(join32(cwd, "go.mod"))) {
249860
249941
  return "go test ./...";
249861
249942
  }
249862
- if (existsSync8(join42(cwd, "pom.xml"))) {
249943
+ if (existsSync8(join32(cwd, "pom.xml"))) {
249863
249944
  return "mvn test";
249864
249945
  }
249865
- if (existsSync8(join42(cwd, "build.gradle"))) {
249946
+ if (existsSync8(join32(cwd, "build.gradle"))) {
249866
249947
  return "./gradlew test";
249867
249948
  }
249868
- if (existsSync8(join42(cwd, "package.json"))) {
249949
+ if (existsSync8(join32(cwd, "package.json"))) {
249869
249950
  try {
249870
249951
  const raw = readBoundedRegularFile(
249871
- join42(cwd, "package.json"),
249952
+ join32(cwd, "package.json"),
249872
249953
  1024 * 1024
249873
249954
  );
249874
249955
  if (raw === void 0) return "npm test";
249875
249956
  const pkg = JSON.parse(raw);
249876
249957
  if (pkg.scripts?.test) {
249877
- if (existsSync8(join42(cwd, "pnpm-lock.yaml"))) return "pnpm test";
249878
- if (existsSync8(join42(cwd, "yarn.lock"))) return "yarn test";
249958
+ if (existsSync8(join32(cwd, "pnpm-lock.yaml"))) return "pnpm test";
249959
+ if (existsSync8(join32(cwd, "yarn.lock"))) return "yarn test";
249879
249960
  return "npm test";
249880
249961
  }
249881
249962
  } catch {
249882
249963
  }
249883
249964
  return "npm test";
249884
249965
  }
249885
- if (existsSync8(join42(cwd, "pytest.ini")) || existsSync8(join42(cwd, "pyproject.toml"))) {
249966
+ if (existsSync8(join32(cwd, "pytest.ini")) || existsSync8(join32(cwd, "pyproject.toml"))) {
249886
249967
  return "pytest";
249887
249968
  }
249888
249969
  return "npm test";
@@ -249904,10 +249985,10 @@ var PUBLIC_DNS_ENDPOINTS = [
249904
249985
  ];
249905
249986
  async function resolveSystemAddresses(hostname, signal, lookupImplementation = lookup) {
249906
249987
  if (signal?.aborted) throw abortError("System DNS lookup was cancelled.");
249907
- return new Promise((resolve34, reject) => {
249988
+ return new Promise((resolve43, reject) => {
249908
249989
  const onAbort = () => reject(abortError("System DNS lookup was cancelled."));
249909
249990
  signal?.addEventListener("abort", onAbort, { once: true });
249910
- lookupImplementation(hostname, { all: true, verbatim: true }).then((entries) => resolve34(entries.map((entry) => entry.address))).catch(reject).finally(() => signal?.removeEventListener("abort", onAbort));
249991
+ lookupImplementation(hostname, { all: true, verbatim: true }).then((entries) => resolve43(entries.map((entry) => entry.address))).catch(reject).finally(() => signal?.removeEventListener("abort", onAbort));
249911
249992
  });
249912
249993
  }
249913
249994
  function createPublicDnsResolver(fetchImplementation = globalThis.fetch) {
@@ -250916,7 +250997,6 @@ var WebSearchTool = class {
250916
250997
  const controller = new AbortController();
250917
250998
  const abort = () => controller.abort();
250918
250999
  const timeoutId = setTimeout(abort, timeoutMs);
250919
- timeoutId.unref?.();
250920
251000
  if (parentSignal) {
250921
251001
  if (parentSignal.aborted) {
250922
251002
  controller.abort();
@@ -251166,7 +251246,7 @@ Diagnostics:
251166
251246
  var TaskIdSchema = z222.string().regex(/^bg_[a-f0-9]{16}$/);
251167
251247
  var GetBackgroundTaskOutputInputSchema = z222.object({
251168
251248
  taskIds: z222.array(TaskIdSchema).min(1).max(20),
251169
- waitMs: z222.number().int().min(0).max(3e4).optional(),
251249
+ waitMs: z222.number().int().min(0).transform((value) => Math.min(value, 3e4)).optional(),
251170
251250
  waitFor: z222.enum(["any", "all"]).optional()
251171
251251
  });
251172
251252
  var KillBackgroundTaskInputSchema = z222.object({
@@ -251175,7 +251255,7 @@ var KillBackgroundTaskInputSchema = z222.object({
251175
251255
  var ListBackgroundTasksInputSchema = z222.object({}).strict();
251176
251256
  var GetBackgroundTaskOutputTool = class {
251177
251257
  name = "get_background_task_output";
251178
- description = "Get bounded output and status for one or more background tasks. Set waitMs to wait briefly for any or all tasks without polling or sleeping.";
251258
+ description = "Get bounded output and status for one or more background tasks. Set waitMs to wait briefly for any or all tasks without polling or sleeping; values above 30000 are safely capped to 30000.";
251179
251259
  inputSchema = GetBackgroundTaskOutputInputSchema;
251180
251260
  risk = "read";
251181
251261
  async execute(input, ctx) {
@@ -251396,8 +251476,8 @@ var BackgroundTaskRuntime = class {
251396
251476
  );
251397
251477
  }
251398
251478
  let resolveCompletion = () => void 0;
251399
- const completion = new Promise((resolve34) => {
251400
- resolveCompletion = resolve34;
251479
+ const completion = new Promise((resolve43) => {
251480
+ resolveCompletion = resolve43;
251401
251481
  });
251402
251482
  const task = {
251403
251483
  id,
@@ -251592,8 +251672,16 @@ Orbit could not confirm timeout termination: ${errorMessage(error)}
251592
251672
  if (task.status !== "running") return;
251593
251673
  task.requestedStop = status;
251594
251674
  const gracefulSignalConfirmed = await signalProcessTree(task.child, false);
251675
+ if (process.platform === "win32" && gracefulSignalConfirmed && task.status === "running") {
251676
+ this.settleTask(task, status, task.child.exitCode);
251677
+ return;
251678
+ }
251595
251679
  if (await waitWithTimeout(task.completion, this.terminateGraceMs)) return;
251596
251680
  const forcedSignalConfirmed = await signalProcessTree(task.child, true);
251681
+ if (process.platform === "win32" && forcedSignalConfirmed && task.status === "running") {
251682
+ this.settleTask(task, status, task.child.exitCode);
251683
+ return;
251684
+ }
251597
251685
  if (await waitWithTimeout(task.completion, this.terminateGraceMs)) return;
251598
251686
  if (task.status === "running" && (task.child.exitCode !== null || task.child.signalCode !== null)) {
251599
251687
  this.settleTask(
@@ -251604,10 +251692,6 @@ Orbit could not confirm timeout termination: ${errorMessage(error)}
251604
251692
  );
251605
251693
  return;
251606
251694
  }
251607
- if (process.platform === "win32" && task.status === "running" && (gracefulSignalConfirmed || forcedSignalConfirmed)) {
251608
- this.settleTask(task, status, task.child.exitCode);
251609
- return;
251610
- }
251611
251695
  throw new Error(
251612
251696
  `Background task ${task.id} did not exit after graceful and forced termination.`
251613
251697
  );
@@ -251642,12 +251726,12 @@ async function signalProcessTree(child, force) {
251642
251726
  const pid = child.pid;
251643
251727
  if (!pid) return false;
251644
251728
  if (process.platform === "win32") {
251645
- return new Promise((resolve34) => {
251729
+ return new Promise((resolve43) => {
251646
251730
  execFile(
251647
251731
  "taskkill.exe",
251648
251732
  ["/pid", String(pid), "/t", ...force ? ["/f"] : []],
251649
251733
  HIDDEN_CHILD_PROCESS_OPTIONS,
251650
- (error) => resolve34(error === null)
251734
+ (error) => resolve43(error === null)
251651
251735
  );
251652
251736
  });
251653
251737
  }
@@ -251668,17 +251752,16 @@ async function waitWithTimeout(promise, timeoutMs, abortSignal) {
251668
251752
  try {
251669
251753
  return await Promise.race([
251670
251754
  promise.then(() => true),
251671
- new Promise((resolve34) => {
251672
- timeout = setTimeout(() => resolve34(false), timeoutMs);
251673
- timeout.unref?.();
251755
+ new Promise((resolve43) => {
251756
+ timeout = setTimeout(() => resolve43(false), timeoutMs);
251674
251757
  }),
251675
- new Promise((resolve34) => {
251758
+ new Promise((resolve43) => {
251676
251759
  if (!abortSignal) return;
251677
251760
  if (abortSignal.aborted) {
251678
- resolve34(false);
251761
+ resolve43(false);
251679
251762
  return;
251680
251763
  }
251681
- abortListener = () => resolve34(false);
251764
+ abortListener = () => resolve43(false);
251682
251765
  abortSignal.addEventListener("abort", abortListener, { once: true });
251683
251766
  })
251684
251767
  ]);
@@ -251711,7 +251794,7 @@ import { z as z25 } from "zod";
251711
251794
  import { basename, join as join7 } from "path";
251712
251795
  import { existsSync as existsSync43, writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, renameSync as renameSync3, rmSync as rmSync2 } from "fs";
251713
251796
  import { promises as fsPromises3 } from "fs";
251714
- import { join as join24, dirname as dirname32, isAbsolute as isAbsolute4, resolve as resolve32 } from "path";
251797
+ import { join as join24, dirname as dirname32, isAbsolute as isAbsolute4, resolve as resolve33 } from "path";
251715
251798
  import { createHash as createHash4, randomUUID as randomUUID32 } from "crypto";
251716
251799
  import { execFile as execFile2 } from "child_process";
251717
251800
  import glob3 from "fast-glob";
@@ -251735,11 +251818,11 @@ import { existsSync as existsSync53, promises as fs2 } from "fs";
251735
251818
  import { fileURLToPath as fileURLToPath2 } from "url";
251736
251819
  import { parse as parseYaml3 } from "yaml";
251737
251820
  import { z as z53 } from "zod";
251738
- import { dirname as dirname42, join as join43 } from "path";
251821
+ import { dirname as dirname42, join as join42 } from "path";
251739
251822
  import { parse as parseYaml22 } from "yaml";
251740
251823
  import { z as z63 } from "zod";
251741
251824
  import { existsSync as existsSync62, lstatSync as lstatSync3, promises as fs22 } from "fs";
251742
- import { dirname as dirname6, isAbsolute as isAbsolute32, join as join52, win32 as win322 } from "path";
251825
+ import { dirname as dirname6, isAbsolute as isAbsolute32, join as join52, win32 as win323 } from "path";
251743
251826
  import { parse as parseYaml32 } from "yaml";
251744
251827
  var ProjectIndexer = class {
251745
251828
  constructor(cwd) {
@@ -252967,7 +253050,7 @@ function embeddingBatches(texts) {
252967
253050
  return batches;
252968
253051
  }
252969
253052
  function workspaceIndexKey(cwd) {
252970
- const absolute = resolve32(cwd).replace(/\\/g, "/");
253053
+ const absolute = resolve33(cwd).replace(/\\/g, "/");
252971
253054
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
252972
253055
  }
252973
253056
  function resolveConfiguredApiKey(provider) {
@@ -253172,7 +253255,7 @@ function getEmbeddingProvider(config) {
253172
253255
  var SymbolIndexer = class {
253173
253256
  constructor(cwd) {
253174
253257
  this.cwd = cwd;
253175
- this.indexPath = resolve32(cwd, ".orbit", "symbols.json");
253258
+ this.indexPath = resolve33(cwd, ".orbit", "symbols.json");
253176
253259
  }
253177
253260
  cwd;
253178
253261
  indexPath;
@@ -253194,9 +253277,9 @@ var SymbolIndexer = class {
253194
253277
  async performIndex() {
253195
253278
  try {
253196
253279
  this.initializeIndexPath();
253197
- const normCwd = resolve32(this.cwd).toLowerCase().replace(/\\/g, "/");
253280
+ const normCwd = resolve33(this.cwd).toLowerCase().replace(/\\/g, "/");
253198
253281
  const { homedir: homedir22 } = await import("os");
253199
- const normHome = resolve32(homedir22()).toLowerCase().replace(/\\/g, "/");
253282
+ const normHome = resolve33(homedir22()).toLowerCase().replace(/\\/g, "/");
253200
253283
  if (normCwd === normHome || normCwd === "/" || /^[a-zA-Z]:\/$/.test(normCwd) || dirname32(normCwd) === normCwd) {
253201
253284
  return;
253202
253285
  }
@@ -253858,6 +253941,28 @@ var CODEBASE_FORCE_MARKER_ALL = /@codebase\b/gi;
253858
253941
  var CODEBASE_DISABLE_MARKER_ALL = /@no-codebase\b/gi;
253859
253942
  var CODE_INTENT = /\b(?:implement|fix|debug|refactor|review|inspect|trace|codebase|repository|repo|function|class|module|dependency|build|test|error|stack\s*trace)\b|(?:实现|修改|修复|调试|重构|审查|检查|代码|项目|仓库|函数|类|模块|依赖|构建|测试|报错|异常|架构)/i;
253860
253943
  var SOURCE_REFERENCE = /(?:^|[\s`'"(])[^\s`'"()]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyw)(?=$|[\s`'"),:])/i;
253944
+ var CODEBASE_CONTEXT_BUDGETS = {
253945
+ automatic: {
253946
+ queryTokens: 256,
253947
+ searchTokens: 3072,
253948
+ referenceTokens: 1024,
253949
+ repoMapTokens: 512,
253950
+ totalTokens: 6144,
253951
+ resultLimit: 4,
253952
+ referencesPerSymbol: 2,
253953
+ totalReferences: 6
253954
+ },
253955
+ explicit: {
253956
+ queryTokens: 512,
253957
+ searchTokens: 8192,
253958
+ referenceTokens: 4096,
253959
+ repoMapTokens: 2048,
253960
+ totalTokens: 16384,
253961
+ resultLimit: 8,
253962
+ referencesPerSymbol: 3,
253963
+ totalReferences: 12
253964
+ }
253965
+ };
253861
253966
  function selectCodebaseRetrievalMode(userQuery, autoEnabled) {
253862
253967
  if (!userQuery || CODEBASE_DISABLE_MARKER.test(userQuery)) return "off";
253863
253968
  if (CODEBASE_FORCE_MARKER.test(userQuery)) {
@@ -253879,9 +253984,13 @@ var CodebaseContextRetriever = class {
253879
253984
  cwd;
253880
253985
  retrieval;
253881
253986
  async retrieve(userQuery, config, mode) {
253987
+ const budget = CODEBASE_CONTEXT_BUDGETS[mode];
253882
253988
  const cleanQuery = cleanCodebaseQuery(userQuery);
253883
- const searchQuery = cleanQuery || "repository architecture and entrypoints";
253884
- const prepared = await this.retrieval.prepare(2048);
253989
+ const searchQuery = truncateTextToTokenBudget(
253990
+ cleanQuery || "repository architecture and entrypoints",
253991
+ budget.queryTokens
253992
+ );
253993
+ const prepared = await this.retrieval.prepare(budget.repoMapTokens);
253885
253994
  let chunksText = "";
253886
253995
  let referencesText = "";
253887
253996
  try {
@@ -253897,14 +254006,17 @@ var CodebaseContextRetriever = class {
253897
254006
  return provider.embed(texts, { model: modelName });
253898
254007
  };
253899
254008
  const results = await prepared.search.search(searchQuery, embedFn, {
253900
- limit: 5
254009
+ limit: budget.resultLimit
253901
254010
  });
253902
254011
  if (results.length > 0) {
253903
- chunksText = results.map(
253904
- (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
254012
+ chunksText = truncateTextToTokenBudget(
254013
+ results.map(
254014
+ (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
253905
254015
  ${result.text}
253906
254016
  `
253907
- ).join("\n");
254017
+ ).join("\n"),
254018
+ budget.searchTokens
254019
+ );
253908
254020
  const referencedSymbols = Array.from(
253909
254021
  new Set(
253910
254022
  results.map((result) => result.metadata.symbolName).filter((name) => Boolean(name))
@@ -253913,7 +254025,15 @@ ${result.text}
253913
254025
  if (referencedSymbols.length > 0) {
253914
254026
  referencesText = await new ReferencesRetriever(
253915
254027
  this.cwd
253916
- ).getReferencesContext(referencedSymbols);
254028
+ ).getReferencesContext(
254029
+ referencedSymbols,
254030
+ budget.referencesPerSymbol,
254031
+ budget.totalReferences
254032
+ );
254033
+ referencesText = truncateTextToTokenBudget(
254034
+ referencesText,
254035
+ budget.referenceTokens
254036
+ );
253917
254037
  }
253918
254038
  } else {
253919
254039
  chunksText = "(No relevant code matches found in search index.)\n";
@@ -253925,13 +254045,18 @@ ${result.text}
253925
254045
  chunksText = `(RAG retrieval failed: ${message2})
253926
254046
  `;
253927
254047
  }
253928
- return `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
254048
+ const repoMap = truncateTextToTokenBudget(
254049
+ prepared.repoMap || "(No landmarks mapped.)",
254050
+ budget.repoMapTokens
254051
+ );
254052
+ const context = `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
253929
254053
  Use the following repository evidence when it is relevant; verify files before editing.
253930
254054
 
253931
254055
  ${chunksText}
253932
254056
  ${referencesText}=== Codebase Landmark Repo Map ===
253933
- ${prepared.repoMap || "(No landmarks mapped.)"}
254057
+ ${repoMap}
253934
254058
  ================================================================`;
254059
+ return truncateTextToTokenBudget(context, budget.totalTokens);
253935
254060
  }
253936
254061
  };
253937
254062
  var IGNORED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
@@ -253977,6 +254102,7 @@ var WEAK_TERM_SCORE = 1;
253977
254102
  var NAME_MENTION_SCORE = 8;
253978
254103
  var STRONG_TERM_MIN_LENGTH = 5;
253979
254104
  var MIN_AUTO_SCORE = 3;
254105
+ var MIN_AUTO_MATCHED_TERMS = 2;
253980
254106
  function normalizePath3(path9) {
253981
254107
  return path9.replace(/\\/g, "/");
253982
254108
  }
@@ -254179,7 +254305,7 @@ var SkillPresentationSchema = z63.object({
254179
254305
  }).passthrough().optional()
254180
254306
  }).passthrough();
254181
254307
  async function loadSkillPresentation(skillFilePath) {
254182
- const metadataPath = join43(
254308
+ const metadataPath = join42(
254183
254309
  dirname42(skillFilePath),
254184
254310
  ...PRESENTATION_SIDECAR_SEGMENTS
254185
254311
  );
@@ -254321,13 +254447,18 @@ function selectSkills(skills, userQuery, config) {
254321
254447
  if (!explicit2 && config.activation === "auto" && skill.allowImplicitInvocation) {
254322
254448
  const metadata = normalize2(`${skill.name} ${skill.description}`);
254323
254449
  const metadataTerms = new Set(terms(metadata));
254450
+ let matchedTerms = 0;
254324
254451
  for (const term of queryTerms) {
254325
254452
  if (metadataTerms.has(term)) {
254453
+ matchedTerms += 1;
254326
254454
  score += term.length >= STRONG_TERM_MIN_LENGTH ? STRONG_TERM_SCORE : WEAK_TERM_SCORE;
254327
254455
  }
254328
254456
  }
254329
- if (mentionsName(query, name)) score += NAME_MENTION_SCORE;
254330
- if (score < MIN_AUTO_SCORE) score = 0;
254457
+ const nameMentioned = mentionsName(query, name);
254458
+ if (nameMentioned) score += NAME_MENTION_SCORE;
254459
+ if (score < MIN_AUTO_SCORE || !nameMentioned && matchedTerms < MIN_AUTO_MATCHED_TERMS) {
254460
+ score = 0;
254461
+ }
254331
254462
  }
254332
254463
  return { skill, explicit: explicit2, score };
254333
254464
  }).filter(({ score }) => score > 0).sort(
@@ -254537,7 +254668,7 @@ function validateReference(skill, reference, diagnostics) {
254537
254668
  return;
254538
254669
  }
254539
254670
  if (!relativePath) return;
254540
- if (isAbsolute32(relativePath) || win322.isAbsolute(relativePath)) {
254671
+ if (isAbsolute32(relativePath) || win323.isAbsolute(relativePath)) {
254541
254672
  diagnostics.push(
254542
254673
  diagnostic(
254543
254674
  skill.path,
@@ -257913,8 +258044,13 @@ var WorktreeManager = class {
257913
258044
  );
257914
258045
  }
257915
258046
  }
258047
+ const baseCommit = this.git(["rev-parse", "HEAD"]).trim();
257916
258048
  this.git(["worktree", "add", "-b", branchName, worktreePath, "HEAD"]);
257917
- const session = { path: worktreePath, branchName };
258049
+ const session = {
258050
+ path: worktreePath,
258051
+ branchName,
258052
+ baseCommit
258053
+ };
257918
258054
  if (options.snapshotWorkingTree) {
257919
258055
  try {
257920
258056
  session.baselineCommit = this.snapshotWorkingTree(worktreePath);
@@ -257944,19 +258080,7 @@ var WorktreeManager = class {
257944
258080
  };
257945
258081
  }
257946
258082
  try {
257947
- this.git(["add", "-A"], session.path);
257948
- if (this.git(["status", "--porcelain"], session.path).trim()) {
257949
- this.git(
257950
- [
257951
- "commit",
257952
- "--no-verify",
257953
- "--no-gpg-sign",
257954
- "-m",
257955
- "subagent automatic worktree commit"
257956
- ],
257957
- session.path
257958
- );
257959
- }
258083
+ this.commitWorktreeChanges(session);
257960
258084
  } catch (error) {
257961
258085
  return {
257962
258086
  success: false,
@@ -257999,6 +258123,97 @@ var WorktreeManager = class {
257999
258123
  }
258000
258124
  return { success: true };
258001
258125
  }
258126
+ /**
258127
+ * Combine independent writer deltas inside another managed worktree. The
258128
+ * main workspace remains untouched until the integration worktree passes
258129
+ * review and is merged with `mergeAndCleanup`.
258130
+ */
258131
+ integrateWorktrees(sources, target) {
258132
+ try {
258133
+ this.assertManagedSession(target);
258134
+ for (const source of sources) {
258135
+ this.assertManagedSession(source);
258136
+ if (path4.resolve(source.path) === path4.resolve(target.path) || source.branchName === target.branchName) {
258137
+ throw new Error("A writer worktree cannot integrate into itself.");
258138
+ }
258139
+ }
258140
+ } catch (error) {
258141
+ return { success: false, error: toErrorMessage2(error), preserved: true };
258142
+ }
258143
+ let integratedCount = 0;
258144
+ try {
258145
+ for (const source of sources) {
258146
+ this.commitWorktreeChanges(source);
258147
+ const baseline = source.baselineCommit || source.baseCommit;
258148
+ if (!baseline) {
258149
+ throw new Error(
258150
+ `Writer worktree has no trusted baseline: ${source.branchName}`
258151
+ );
258152
+ }
258153
+ const delta = this.gitBuffer(
258154
+ ["diff", "--binary", baseline, source.branchName],
258155
+ source.path
258156
+ );
258157
+ if (delta.length > 0) {
258158
+ execFileSync4("git", ["apply", "--whitespace=nowarn", "-"], {
258159
+ ...HIDDEN_CHILD_PROCESS_OPTIONS,
258160
+ cwd: target.path,
258161
+ input: delta,
258162
+ stdio: ["pipe", "pipe", "pipe"],
258163
+ maxBuffer: 64 * 1024 * 1024
258164
+ });
258165
+ }
258166
+ integratedCount += 1;
258167
+ }
258168
+ } catch (error) {
258169
+ try {
258170
+ this.git(["reset", "--hard", "HEAD"], target.path);
258171
+ this.git(["clean", "-fd"], target.path);
258172
+ } catch {
258173
+ }
258174
+ return {
258175
+ success: false,
258176
+ integratedCount,
258177
+ error: `Failed to integrate writer changes: ${toErrorMessage2(error)}`,
258178
+ preserved: true
258179
+ };
258180
+ }
258181
+ const cleanupErrors = [];
258182
+ for (const source of sources) {
258183
+ try {
258184
+ this.discardWorktree(source);
258185
+ } catch (error) {
258186
+ cleanupErrors.push(`${source.branchName}: ${toErrorMessage2(error)}`);
258187
+ }
258188
+ }
258189
+ return {
258190
+ success: true,
258191
+ integratedCount,
258192
+ ...cleanupErrors.length ? {
258193
+ preserved: true,
258194
+ error: `Writer changes were integrated, but cleanup is incomplete: ${cleanupErrors.join(" | ")}`
258195
+ } : {}
258196
+ };
258197
+ }
258198
+ /** List the complete writer delta before integration or review. */
258199
+ listChangedFiles(session) {
258200
+ this.assertManagedSession(session);
258201
+ const baseline = session.baselineCommit || session.baseCommit;
258202
+ if (!baseline) {
258203
+ throw new Error(
258204
+ `Managed worktree has no trusted baseline: ${session.branchName}`
258205
+ );
258206
+ }
258207
+ const tracked = this.git(
258208
+ ["diff", "--name-only", "-z", baseline],
258209
+ session.path
258210
+ ).split("\0").filter(Boolean);
258211
+ const untracked = this.git(
258212
+ ["ls-files", "--others", "--exclude-standard", "-z"],
258213
+ session.path
258214
+ ).split("\0").filter(Boolean);
258215
+ return Array.from(/* @__PURE__ */ new Set([...tracked, ...untracked])).map((file) => file.replace(/\\/g, "/")).filter((file) => file !== ".orbit" && !file.startsWith(".orbit/")).sort();
258216
+ }
258002
258217
  discardWorktree(session) {
258003
258218
  this.assertManagedSession(session);
258004
258219
  if (fs4.existsSync(session.path)) {
@@ -258029,6 +258244,20 @@ var WorktreeManager = class {
258029
258244
  return [];
258030
258245
  }
258031
258246
  }
258247
+ commitWorktreeChanges(session) {
258248
+ this.git(["add", "-A"], session.path);
258249
+ if (!this.git(["status", "--porcelain"], session.path).trim()) return;
258250
+ this.git(
258251
+ [
258252
+ "commit",
258253
+ "--no-verify",
258254
+ "--no-gpg-sign",
258255
+ "-m",
258256
+ "subagent automatic worktree commit"
258257
+ ],
258258
+ session.path
258259
+ );
258260
+ }
258032
258261
  /** Copy the user's tracked and safe untracked state into the isolated branch. */
258033
258262
  snapshotWorkingTree(worktreePath) {
258034
258263
  const patch = this.gitBuffer(["diff", "HEAD", "--binary", "--no-ext-diff"]);
@@ -258158,7 +258387,7 @@ import {
258158
258387
  readdirSync as readdirSync22,
258159
258388
  unlinkSync as unlinkSync22
258160
258389
  } from "fs";
258161
- import { basename as basename22, join as join34, resolve as resolve33 } from "path";
258390
+ import { basename as basename22, join as join34, resolve as resolve34 } from "path";
258162
258391
  import { z as z45 } from "zod";
258163
258392
  var SafeObjectKeySchema = z30.string().refine(
258164
258393
  (key) => !["__proto__", "constructor", "prototype"].includes(key),
@@ -259849,7 +260078,7 @@ var AgentRunSchema = z45.object({
259849
260078
  var AgentRunStore = class {
259850
260079
  constructor(cwd, options = {}) {
259851
260080
  this.cwd = cwd;
259852
- this.directory = resolve33(cwd, ".orbit", "agent-runs");
260081
+ this.directory = resolve34(cwd, ".orbit", "agent-runs");
259853
260082
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
259854
260083
  this.ownerPid = options.ownerPid ?? process.pid;
259855
260084
  this.ownerInstanceId = options.ownerInstanceId ?? generateId("orbit");
@@ -260180,7 +260409,7 @@ var AgentRunStore = class {
260180
260409
  this.cwd,
260181
260410
  join34(".orbit", "agent-runs")
260182
260411
  );
260183
- if (resolve33(safeDirectory) !== this.directory) {
260412
+ if (resolve34(safeDirectory) !== this.directory) {
260184
260413
  throw new Error("Orbit agent-run directory escaped the workspace.");
260185
260414
  }
260186
260415
  }
@@ -260276,10 +260505,11 @@ import path52 from "path";
260276
260505
  import { z as z73 } from "zod";
260277
260506
  import { z as z103 } from "zod";
260278
260507
  import { z as z93 } from "zod";
260508
+ import { z as z112 } from "zod";
260279
260509
  import path8 from "path";
260280
260510
  import { existsSync as existsSync34, statSync as statSync3 } from "fs";
260281
- import { z as z112 } from "zod";
260282
260511
  import { z as z122 } from "zod";
260512
+ import { z as z132 } from "zod";
260283
260513
  function createInitialState(sessionId, task, maxAttempts = 8) {
260284
260514
  return {
260285
260515
  sessionId,
@@ -261211,7 +261441,7 @@ function getErrorMessage(error) {
261211
261441
  return error instanceof Error ? error.message : String(error);
261212
261442
  }
261213
261443
  var Planner = class {
261214
- static makeSystemPrompt(modelName = "DeepSeek", language = "en", providerId, sessionGoal, projectMemory, taskPlan, supportsThinking = false) {
261444
+ static makeSystemPrompt(modelName = "DeepSeek", language = "en", providerId, sessionGoal, projectMemory, taskPlan, supportsThinking = false, platform = process.platform) {
261215
261445
  const cleanModel = cleanRuntimeLabel(modelName, "unknown-model");
261216
261446
  const cleanProviderId = cleanRuntimeLabel(providerId || "", "");
261217
261447
  const normalizedProvider = cleanProviderId.toLowerCase();
@@ -261256,6 +261486,7 @@ Active Task Plan:
261256
261486
  ${planItems.map((item) => `- ${item}`).join("\n")}
261257
261487
  - Continue from the current in-progress item and keep plan status accurate.
261258
261488
  ` : "";
261489
+ const shellSection = runtimeShellGuidance(platform);
261259
261490
  const prompt = `You are Orbit, a local AI coding agent running inside the user's terminal, powered by ${providerName} (model: ${cleanModel}).
261260
261491
  Your job is to help the user modify, debug, test, document, and understand software projects.
261261
261492
  You have tools for reading files, searching code, editing files, running commands, inspecting git status, and managing diffs.
@@ -261270,6 +261501,14 @@ Self-Identity Rules:
261270
261501
  Language Rules:
261271
261502
  ${language !== "en" ? "- Reply in Simplified Chinese by default unless the user explicitly asks for another language. Keep commands, file paths, code identifiers, API names, and quoted source text in their original language." : "- Reply in the user's language when it is clear from their message. If the language is ambiguous, use concise English. Keep commands, file paths, code identifiers, API names, and quoted source text in their original language."}
261272
261503
 
261504
+ Runtime and tool rules:
261505
+ ${shellSection}
261506
+ - Shell commands already start in the workspace root. Do not prepend cd/chdir or repeat the absolute workspace path.
261507
+ - Prefer read_file, grep, glob, and edit_file over shell commands that merely read, search, or rewrite text. Use the shell for actual project executables, builds, tests, and operating-system tasks.
261508
+ - Keep each command single-purpose and directly executable in the declared shell. Avoid nested command strings, inline script heredocs, output-suppression pipelines, and byte-level probes when a structured file tool can answer the question.
261509
+ - For background work, poll with get_background_task_output using waitMs at most 30000. Read and obey tool validation ranges instead of retrying invalid inputs.
261510
+ - After a command failure, use its first actionable diagnostic to change the command or repair the cause. Do not repeat near-identical probes that return the same evidence.
261511
+
261273
261512
  Core rules:
261274
261513
  1. Understand the project before editing.
261275
261514
  2. Prefer minimal, precise changes.
@@ -261292,6 +261531,21 @@ Core rules:
261292
261531
  return prompt;
261293
261532
  }
261294
261533
  };
261534
+ function runtimeShellGuidance(platform) {
261535
+ if (platform === "win32") {
261536
+ return [
261537
+ "- Runtime OS: Windows. The tool named bash executes native non-interactive PowerShell for compatibility with the existing tool protocol.",
261538
+ "- Write PowerShell commands: Get-Content, Get-ChildItem, Select-String, Where-Object, Set-Location only when truly needed, and $LASTEXITCODE for native-process exit status.",
261539
+ "- Do not use POSIX-only grep/sed/head/tail, heredoc (<<), /dev/null, export, or Bash $? syntax. Do not join steps with &&; use one command per tool call or explicit PowerShell control flow.",
261540
+ "- Quote Windows paths with single quotes and use -LiteralPath for paths containing spaces, brackets, or non-ASCII characters."
261541
+ ].join("\n");
261542
+ }
261543
+ const os3 = platform === "darwin" ? "macOS" : "Linux/Unix";
261544
+ return [
261545
+ `- Runtime OS: ${os3}. The bash tool executes non-interactive Bash, falling back to POSIX sh when Bash is unavailable.`,
261546
+ "- Write portable POSIX commands and quote paths. Do not use PowerShell cmdlets, -LiteralPath, or $LASTEXITCODE."
261547
+ ].join("\n");
261548
+ }
261295
261549
  function cleanRuntimeGoal(value) {
261296
261550
  return (value || "").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 4e3);
261297
261551
  }
@@ -261780,13 +262034,38 @@ var AgentInputQueueController = class {
261780
262034
  var IDENTICAL_CALL_THRESHOLD = 3;
261781
262035
  var REPEATED_FAILURE_THRESHOLD = 2;
261782
262036
  var RENUDGE_INCREMENT = 2;
261783
- function canonicalizeArguments(rawArguments) {
262037
+ function canonicalizeArguments(toolName, rawArguments) {
261784
262038
  try {
261785
- return JSON.stringify(sortValue(JSON.parse(rawArguments)));
262039
+ const parsed = JSON.parse(rawArguments);
262040
+ if (toolName === "bash") {
262041
+ const probe = canonicalizeShellProbe(parsed);
262042
+ if (probe) return probe;
262043
+ }
262044
+ return JSON.stringify(sortValue(parsed));
261786
262045
  } catch {
261787
262046
  return rawArguments.trim();
261788
262047
  }
261789
262048
  }
262049
+ function canonicalizeShellProbe(value) {
262050
+ if (value === null || typeof value !== "object") return void 0;
262051
+ const command = value.command;
262052
+ if (typeof command !== "string") return void 0;
262053
+ const looksLikeProbe = /(?:\b(?:Get-Content|Select-String|grep|sed|head|tail|cat)\b|\bpython(?:\.exe)?\b[\s\S]*\b(?:open|read_text|read_bytes)\s*\()/i.test(
262054
+ command
262055
+ );
262056
+ const looksMutatingOrExecutable = /(?:\b(?:Set-Content|Add-Content|Remove-Item|Move-Item|Copy-Item|xelatex|pdflatex|npm|pnpm|yarn|pytest|vitest)\b|(?:^|\s)(?:>|>>)(?:\s|$)|\.write\s*\()/i.test(
262057
+ command
262058
+ );
262059
+ if (!looksLikeProbe || looksMutatingOrExecutable) return void 0;
262060
+ const files = command.match(
262061
+ /[\p{L}\p{N}_./\\:@+~-]+\.(?:[cm]?[jt]sx?|py|json|ya?ml|toml|md|tex|log|txt|csv|xml|html|css|scss|sql|rs|go|java|kt|swift)/giu
262062
+ );
262063
+ if (!files?.length) return void 0;
262064
+ const normalized = [
262065
+ ...new Set(files.map((file) => file.replace(/\\/g, "/")))
262066
+ ].sort();
262067
+ return `shell-probe:${normalized.join("|")}`;
262068
+ }
261790
262069
  function sortValue(value) {
261791
262070
  if (Array.isArray(value)) return value.map(sortValue);
261792
262071
  if (value !== null && typeof value === "object") {
@@ -261814,7 +262093,11 @@ var LoopProgressGuard = class {
261814
262093
  * no-progress streak past a threshold, or null when the loop looks healthy.
261815
262094
  */
261816
262095
  record(observation) {
261817
- const signature = `${observation.name}\0${canonicalizeArguments(observation.arguments)}`;
262096
+ const canonicalArguments = canonicalizeArguments(
262097
+ observation.name,
262098
+ observation.arguments
262099
+ );
262100
+ const signature = JSON.stringify([observation.name, canonicalArguments]);
261818
262101
  if (signature !== this.lastSignature) {
261819
262102
  this.lastSignature = signature;
261820
262103
  this.streakLength = 1;
@@ -261835,10 +262118,11 @@ var LoopProgressGuard = class {
261835
262118
  }
261836
262119
  if (this.streakLength >= IDENTICAL_CALL_THRESHOLD) {
261837
262120
  this.nextNudgeAt = this.streakLength + RENUDGE_INCREMENT;
262121
+ const repeatedProbe = canonicalArguments.startsWith("shell-probe:");
261838
262122
  return {
261839
- reason: "repeated_identical_call",
262123
+ reason: repeatedProbe ? "repeated_probe" : "repeated_identical_call",
261840
262124
  repeatCount: this.streakLength,
261841
- message: `[Loop guard] You have now made the exact same "${observation.name}" call ${this.streakLength} times in a row. The result will not change. Use the information you already have, take a different action, or report what is blocking you.`
262125
+ message: repeatedProbe ? `[Loop guard] You have made ${this.streakLength} consecutive read-only shell probes against the same file(s). Stop varying grep/sed/Python snippets. Use the evidence already collected, use read_file once with a focused range, or repair the reported line directly.` : `[Loop guard] You have now made the exact same "${observation.name}" call ${this.streakLength} times in a row. The result will not change. Use the information you already have, take a different action, or report what is blocking you.`
261842
262126
  };
261843
262127
  }
261844
262128
  return null;
@@ -263148,17 +263432,27 @@ var NETWORK_SUMMARY_CHARS = 280;
263148
263432
  var NETWORK_RESULT_CHARS = 6e3;
263149
263433
  var TOOL_RESULT_MAX_CHARS = 24e3;
263150
263434
  var TOOL_STATUS_MAX_CHARS = 2e3;
263435
+ var TOOL_ERROR_MAX_CHARS = 8e3;
263151
263436
  function buildToolResultContent(toolName, result) {
263152
- const content = result.ok ? serializeToolResultData(result.data, result.display) : result.error || "Unknown error";
263437
+ const content = result.ok ? serializeToolResultData(result.data, result.display) : serializeToolFailure(result.error, result.display);
263153
263438
  const redacted = redactSecrets(content);
263154
263439
  if (!result.ok || toolName !== "web_search") {
263155
263440
  return truncateToolText(
263156
263441
  redacted,
263157
- result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_STATUS_MAX_CHARS
263442
+ result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_ERROR_MAX_CHARS
263158
263443
  );
263159
263444
  }
263160
263445
  return compactSearchResult(redacted, redactSecrets(result.display || ""));
263161
263446
  }
263447
+ function serializeToolFailure(error, display) {
263448
+ const message2 = error?.trim() || "Unknown error";
263449
+ const output = display?.trim();
263450
+ if (!output || output === message2) return message2;
263451
+ return `${message2}
263452
+
263453
+ Captured command output:
263454
+ ${output}`;
263455
+ }
263162
263456
  function truncateToolText(text2, maxChars) {
263163
263457
  if (text2.length <= maxChars) return text2;
263164
263458
  const suffix = "\n... [truncated for context budget]";
@@ -263238,6 +263532,14 @@ function safeAgentLoopErrorMessage(error) {
263238
263532
  if (message2.length <= AGENT_LOOP_ERROR_MESSAGE_MAX_CHARS) return message2;
263239
263533
  return `${message2.slice(0, AGENT_LOOP_ERROR_MESSAGE_MAX_CHARS - 1)}\u2026`;
263240
263534
  }
263535
+ function formatToolInputValidationError(error) {
263536
+ const issues = error.issues.slice(0, 3).map((issue) => {
263537
+ const field = issue.path.length > 0 ? issue.path.join(".") : "input";
263538
+ return `${field}: ${issue.message}`;
263539
+ });
263540
+ const remaining = Math.max(0, error.issues.length - issues.length);
263541
+ return `Invalid tool input \u2014 ${issues.join("; ")}${remaining ? `; +${remaining} more` : ""}.`;
263542
+ }
263241
263543
  function waitForAgentRetry(delayMs, signal) {
263242
263544
  return new Promise((resolve26, reject) => {
263243
263545
  const cleanup = () => signal?.removeEventListener("abort", onAbort);
@@ -263245,7 +263547,6 @@ function waitForAgentRetry(delayMs, signal) {
263245
263547
  cleanup();
263246
263548
  resolve26();
263247
263549
  }, delayMs);
263248
- timeout.unref?.();
263249
263550
  const onAbort = () => {
263250
263551
  clearTimeout(timeout);
263251
263552
  cleanup();
@@ -263462,6 +263763,7 @@ var AgentLoop = class _AgentLoop {
263462
263763
  outputLimitRetriesForRun = 0;
263463
263764
  providerRetriesForRun = 0;
263464
263765
  completionVerificationNudgedForRun = false;
263766
+ finalResponseOnlyReason = null;
263465
263767
  approvedToolScopes = /* @__PURE__ */ new Set();
263466
263768
  terminalFailure = null;
263467
263769
  verificationStatus = "not_run";
@@ -263696,6 +263998,7 @@ var AgentLoop = class _AgentLoop {
263696
263998
  this.completionVerificationNudgedForRun = false;
263697
263999
  this.approvedToolScopes.clear();
263698
264000
  this.terminalFailure = null;
264001
+ this.finalResponseOnlyReason = this.pendingTerminalCompletionReason();
263699
264002
  this.verificationStatus = "not_run";
263700
264003
  this.workspaceMutationRevision = 0;
263701
264004
  this.verifiedMutationRevision = -1;
@@ -263784,10 +264087,19 @@ var AgentLoop = class _AgentLoop {
263784
264087
  });
263785
264088
  if (this.state.attemptCount > 1 && Number.isFinite(this.getRunawayPromptInterval()) && (this.state.attemptCount - 1) % this.getRunawayPromptInterval() === 0) {
263786
264089
  const completedIterations = this.state.attemptCount - 1;
263787
- const continueExec = this.options.autoContinueRunaway ? true : await this.interaction.askApproval(
264090
+ const fullAccess = isFullAccessEnabled(this.config);
264091
+ const autoContinue = fullAccess || this.options.autoContinueRunaway === true;
264092
+ const continueExec = autoContinue ? true : await this.interaction.askApproval(
263788
264093
  `Agent loop has run for ${completedIterations} iterations. Continue executing to prevent runaway costs?`
263789
264094
  );
263790
- if (this.options.autoContinueRunaway) {
264095
+ if (autoContinue) {
264096
+ this.sessionManager.logEvent("runaway_checkpoint", {
264097
+ completedIterations,
264098
+ continuedAutomatically: true,
264099
+ reason: fullAccess ? "full_access" : "bounded_automation"
264100
+ });
264101
+ }
264102
+ if (this.options.autoContinueRunaway && !fullAccess) {
263791
264103
  this.interaction.showText(
263792
264104
  picocolors3.gray(
263793
264105
  `\u25CF Automated evaluation checkpoint: continuing after ${completedIterations} iterations within configured limits.`
@@ -263936,6 +264248,9 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
263936
264248
  (t2) => this.options.allowedTools.includes(t2.name)
263937
264249
  );
263938
264250
  }
264251
+ if (this.finalResponseOnlyReason) {
264252
+ toolDefs = [];
264253
+ }
263939
264254
  toolDefs.sort((a2, b) => a2.name.localeCompare(b.name));
263940
264255
  const capabilities = resolveModelCapabilities(
263941
264256
  this.provider,
@@ -264214,9 +264529,14 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
264214
264529
  continue;
264215
264530
  }
264216
264531
  }
264217
- const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? ["RATE_LIMIT", "SERVER", "OVERLOADED", "TIMEOUT"].includes(
264218
- providerFailure.code
264219
- ) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
264532
+ const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? [
264533
+ "RATE_LIMIT",
264534
+ "SERVER",
264535
+ "OVERLOADED",
264536
+ "TIMEOUT",
264537
+ "TRANSPORT",
264538
+ "STREAM_CLOSED"
264539
+ ].includes(providerFailure.code) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
264220
264540
  chatErrorMessage
264221
264541
  ));
264222
264542
  if (canFallbackToFlash) {
@@ -264242,7 +264562,7 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
264242
264562
  this.contextOverflowRetriesForRun = 0;
264243
264563
  this.outputLimitRetriesForRun = 0;
264244
264564
  this.providerRetriesForRun = 0;
264245
- if (toolCallsToExecute.length === 0 && responseText && !capabilities.toolCalls) {
264565
+ if (toolCallsToExecute.length === 0 && responseText && !capabilities.toolCalls && !this.finalResponseOnlyReason) {
264246
264566
  const xmlToolCalls = parseXMLToolCalls(responseText);
264247
264567
  const textToolCalls = xmlToolCalls.length > 0 ? [] : parseTextToolCalls(
264248
264568
  responseText,
@@ -264672,8 +264992,18 @@ Please analyze this failure log, locate the files causing assertion or compile e
264672
264992
  { startedAt }
264673
264993
  );
264674
264994
  };
264995
+ let terminalSuccessReachedThisBatch;
264675
264996
  for (const tc of toolCallsToExecute) {
264676
264997
  const toolStartedAt = (/* @__PURE__ */ new Date()).toISOString();
264998
+ if (this.finalResponseOnlyReason) {
264999
+ rejectInvalidToolCall(
265000
+ tc,
265001
+ "A trusted finalizer already completed the delivery. Tool execution is locked; return the final delivery report now.",
265002
+ "read",
265003
+ toolStartedAt
265004
+ );
265005
+ continue;
265006
+ }
264677
265007
  let argSummary = "";
264678
265008
  try {
264679
265009
  const parsed = JSON.parse(tc.arguments);
@@ -264743,7 +265073,7 @@ Please analyze this failure log, locate the files causing assertion or compile e
264743
265073
  if (!validation.success) {
264744
265074
  rejectInvalidToolCall(
264745
265075
  tc,
264746
- `Tool input validation failed: ${validation.error.message}`,
265076
+ formatToolInputValidationError(validation.error),
264747
265077
  declaredRisk,
264748
265078
  toolStartedAt
264749
265079
  );
@@ -265801,6 +266131,19 @@ ${stdout2.substring(0, 2e4)}`
265801
266131
  );
265802
266132
  }
265803
266133
  }
266134
+ const terminalSuccess = finalResult.ok && tc.name === "run_tests" && finalResult.metadata?.terminalSuccess === "cumcm-finalizer" ? "cumcm-finalizer" : void 0;
266135
+ if (terminalSuccess) {
266136
+ terminalSuccessReachedThisBatch = terminalSuccess;
266137
+ this.finalResponseOnlyReason = terminalSuccess;
266138
+ this.sessionManager.logEvent("terminal_completion_latched", {
266139
+ toolName: tc.name,
266140
+ kind: terminalSuccess
266141
+ });
266142
+ }
266143
+ const modelVisibleToolResult = buildToolResultContent(
266144
+ tc.name,
266145
+ finalResult
266146
+ );
265804
266147
  if (finalResult.ok) {
265805
266148
  const statusText = truncateToolText(
265806
266149
  redactSecrets(finalResult.display || "Done"),
@@ -265818,7 +266161,7 @@ ${stdout2.substring(0, 2e4)}`
265818
266161
  }
265819
266162
  } else {
265820
266163
  const statusError = truncateToolText(
265821
- redactSecrets(finalResult.error || "Unknown error"),
266164
+ modelVisibleToolResult,
265822
266165
  TOOL_STATUS_MAX_CHARS
265823
266166
  );
265824
266167
  this.interaction.showText(
@@ -265830,7 +266173,7 @@ ${stdout2.substring(0, 2e4)}`
265830
266173
  toolName: tc.name,
265831
266174
  result: finalResult.ok ? redactSensitiveValue(finalResult.data) : void 0,
265832
266175
  display: finalResult.ok ? redactSecrets(finalResult.display || "") : void 0,
265833
- error: finalResult.ok ? void 0 : redactSecrets(finalResult.error || "Unknown error")
266176
+ error: finalResult.ok ? void 0 : modelVisibleToolResult
265834
266177
  });
265835
266178
  const guardNudge = this.progressGuard.record({
265836
266179
  name: tc.name,
@@ -265854,7 +266197,7 @@ ${stdout2.substring(0, 2e4)}`
265854
266197
  toolResult: {
265855
266198
  toolCallId: tc.id,
265856
266199
  name: tc.name,
265857
- content: buildToolResultContent(tc.name, finalResult) + (guardNudge ? `
266200
+ content: modelVisibleToolResult + (guardNudge ? `
265858
266201
 
265859
266202
  ${guardNudge.message}` : ""),
265860
266203
  isError: !finalResult.ok
@@ -265868,6 +266211,27 @@ ${guardNudge.message}` : ""),
265868
266211
  content: toolResultBlocks
265869
266212
  };
265870
266213
  this.state.history.push(toolMsg);
266214
+ if (terminalSuccessReachedThisBatch) {
266215
+ this.state.history.push({
266216
+ id: `msg_terminal_completion_${Date.now()}`,
266217
+ role: "user",
266218
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
266219
+ content: [
266220
+ {
266221
+ type: "text",
266222
+ text: [
266223
+ "Orbit terminal completion contract: the trusted project finalizer succeeded.",
266224
+ "Do not call or describe any further tools, edits, probes, builds, or verification.",
266225
+ "Return only the concise final delivery report required by the active Skill, using the verified artifacts already present."
266226
+ ].join(" ")
266227
+ }
266228
+ ],
266229
+ metadata: {
266230
+ kind: "terminal_completion",
266231
+ terminalSuccess: terminalSuccessReachedThisBatch
266232
+ }
266233
+ });
266234
+ }
265871
266235
  this.abortController = null;
265872
266236
  this.sessionManager.saveHistory(this.state.history);
265873
266237
  }
@@ -266336,6 +266700,8 @@ ${diff.substring(0, 2e4)}`
266336
266700
  this.state.task = task;
266337
266701
  this.state.done = false;
266338
266702
  this.state.attemptCount = 0;
266703
+ this.state.maxAttempts = resolveAgentMaxLoopAttempts(this.config);
266704
+ this.finalResponseOnlyReason = null;
266339
266705
  this.progressGuard.reset();
266340
266706
  this.state.history.push({
266341
266707
  id: `msg_user_${Date.now()}`,
@@ -266345,10 +266711,15 @@ ${diff.substring(0, 2e4)}`
266345
266711
  });
266346
266712
  this.sessionManager.saveHistory(this.state.history);
266347
266713
  }
266714
+ pendingTerminalCompletionReason() {
266715
+ const lastMessage = this.state.history.at(-1);
266716
+ return lastMessage?.role === "user" && lastMessage.metadata?.kind === "terminal_completion" && lastMessage.metadata?.terminalSuccess === "cumcm-finalizer" ? "cumcm-finalizer" : null;
266717
+ }
266348
266718
  /** Apply all pending steering inputs at a provider-safe conversation boundary. */
266349
266719
  applyPendingSteeringInputs() {
266350
266720
  const inputs = this.inputQueue.drainSteering();
266351
266721
  if (inputs.length === 0) return false;
266722
+ this.finalResponseOnlyReason = null;
266352
266723
  for (const input of inputs) {
266353
266724
  this.state.history.push({
266354
266725
  id: `msg_user_steer_${randomUUID52().replace(/-/g, "")}`,
@@ -266984,6 +267355,15 @@ function agentOwnershipScopesOverlap(left, right) {
266984
267355
  const comparableRight = comparableScope(normalizedRight);
266985
267356
  return comparableLeft === comparableRight || comparableLeft.startsWith(`${comparableRight}/`) || comparableRight.startsWith(`${comparableLeft}/`);
266986
267357
  }
267358
+ function agentOwnershipScopeContains(scope, filePath) {
267359
+ const normalizedScope = normalizeAgentOwnershipScope(scope);
267360
+ const normalizedFile = normalizeUnchecked(filePath);
267361
+ if (!normalizedFile || normalizedFile === "*") return false;
267362
+ if (normalizedScope === "*") return true;
267363
+ const comparableOwner = comparableScope(normalizedScope);
267364
+ const comparableFile = comparableScope(normalizedFile);
267365
+ return comparableFile === comparableOwner || comparableFile.startsWith(`${comparableOwner}/`);
267366
+ }
266987
267367
  function normalizeUnchecked(scope) {
266988
267368
  const portable = scope.trim().replace(/\\/g, "/");
266989
267369
  if (portable === "*" || portable.toLowerCase() === "workspace") return "*";
@@ -267207,7 +267587,6 @@ var AgentTaskScheduler = class {
267207
267587
  runResult.then(() => void 0),
267208
267588
  new Promise((resolve26) => {
267209
267589
  graceTimer = setTimeout(resolve26, this.abortGraceMs);
267210
- graceTimer.unref?.();
267211
267590
  })
267212
267591
  ]);
267213
267592
  } finally {
@@ -267241,6 +267620,61 @@ function abortError2(signal) {
267241
267620
  function toError2(error) {
267242
267621
  return error instanceof Error ? error : new Error(String(error));
267243
267622
  }
267623
+ var ParallelWriterTaskSchema = z112.object({
267624
+ id: z112.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
267625
+ task: z112.string().trim().min(1).max(2e4),
267626
+ scopes: z112.array(AgentOwnershipScopeSchema).min(1).max(50)
267627
+ });
267628
+ var ParallelWorkPlanSchema = z112.object({
267629
+ summary: z112.string().trim().min(1).max(2e4),
267630
+ tasks: z112.array(ParallelWriterTaskSchema).min(1).max(4)
267631
+ }).superRefine((plan, context) => {
267632
+ const ids = /* @__PURE__ */ new Set();
267633
+ for (const [index, task] of plan.tasks.entries()) {
267634
+ if (ids.has(task.id)) {
267635
+ context.addIssue({
267636
+ code: z112.ZodIssueCode.custom,
267637
+ path: ["tasks", index, "id"],
267638
+ message: `Duplicate writer task id: ${task.id}`
267639
+ });
267640
+ }
267641
+ ids.add(task.id);
267642
+ }
267643
+ if (plan.tasks.length < 2) return;
267644
+ for (let left = 0; left < plan.tasks.length; left++) {
267645
+ for (let right = left + 1; right < plan.tasks.length; right++) {
267646
+ const overlap = plan.tasks[left].scopes.some(
267647
+ (leftScope) => plan.tasks[right].scopes.some(
267648
+ (rightScope) => agentOwnershipScopesOverlap(leftScope, rightScope)
267649
+ )
267650
+ );
267651
+ if (!overlap) continue;
267652
+ context.addIssue({
267653
+ code: z112.ZodIssueCode.custom,
267654
+ path: ["tasks", right, "scopes"],
267655
+ message: `Writer scopes overlap with task ${plan.tasks[left].id}.`
267656
+ });
267657
+ }
267658
+ }
267659
+ });
267660
+ function parseParallelWorkPlan(text2) {
267661
+ const candidate = extractJsonObject(text2);
267662
+ if (!candidate) return void 0;
267663
+ try {
267664
+ const result = ParallelWorkPlanSchema.safeParse(JSON.parse(candidate));
267665
+ return result.success ? result.data : void 0;
267666
+ } catch {
267667
+ return void 0;
267668
+ }
267669
+ }
267670
+ function extractJsonObject(text2) {
267671
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text2)?.[1]?.trim();
267672
+ const source = fenced || text2.trim();
267673
+ const start = source.indexOf("{");
267674
+ const end = source.lastIndexOf("}");
267675
+ if (start < 0 || end <= start) return void 0;
267676
+ return source.slice(start, end + 1);
267677
+ }
267244
267678
  var AgentRunTracker = class {
267245
267679
  constructor(cwd, task, budgetUsd, warn) {
267246
267680
  this.cwd = cwd;
@@ -267389,9 +267823,9 @@ function resolveAgentTeam(config) {
267389
267823
  reviewers
267390
267824
  };
267391
267825
  }
267392
- var ReviewVerdictSchema = z112.object({
267393
- verdict: z112.enum(["approved", "rejected"]),
267394
- feedback: z112.string().default("")
267826
+ var ReviewVerdictSchema = z122.object({
267827
+ verdict: z122.enum(["approved", "rejected"]),
267828
+ feedback: z122.string().default("")
267395
267829
  });
267396
267830
  var Orchestrator = class {
267397
267831
  constructor(cwd, config, provider, task, interaction) {
@@ -267465,8 +267899,10 @@ var Orchestrator = class {
267465
267899
  this.abortedOutcome(0, "Orchestration was interrupted.")
267466
267900
  );
267467
267901
  }
267468
- const planText = planner.plan;
267469
- this.persistPlan(planText);
267902
+ const planText = planner.workPlan?.summary || planner.plan;
267903
+ this.persistPlan(
267904
+ planner.workPlan ? JSON.stringify(planner.workPlan, null, 2) : planner.plan
267905
+ );
267470
267906
  const worktrees = new WorktreeManager(this.cwd);
267471
267907
  let worktree;
267472
267908
  let agentCwd = this.cwd;
@@ -267474,12 +267910,25 @@ var Orchestrator = class {
267474
267910
  let mergeFailureMessage = "";
267475
267911
  let completed = false;
267476
267912
  let completedAttempts = 0;
267913
+ let parallelPrepared = false;
267477
267914
  if (worktrees.isGitRepo()) {
267478
267915
  try {
267479
- const worktreeId = generateId("wt").slice(0, 12);
267480
- worktree = worktrees.createWorktree(worktreeId, {
267481
- snapshotWorkingTree: true
267482
- });
267916
+ if (planner.workPlan && planner.workPlan.tasks.length > 1) {
267917
+ const prepared = await this.prepareParallelWorkspace(
267918
+ worktrees,
267919
+ planner.workPlan
267920
+ );
267921
+ if (!prepared.success) {
267922
+ return this.finalizeOutcome(prepared.outcome);
267923
+ }
267924
+ worktree = prepared.integration;
267925
+ parallelPrepared = true;
267926
+ } else {
267927
+ const worktreeId = generateId("wt").slice(0, 12);
267928
+ worktree = worktrees.createWorktree(worktreeId, {
267929
+ snapshotWorkingTree: true
267930
+ });
267931
+ }
267483
267932
  if (!existsSync34(worktree.path) || !statSync3(worktree.path).isDirectory()) {
267484
267933
  throw new Error(
267485
267934
  `Worktree manager returned a missing directory: ${worktree.path}`
@@ -267487,7 +267936,7 @@ var Orchestrator = class {
267487
267936
  }
267488
267937
  agentCwd = worktree.path;
267489
267938
  this.interaction.showText(
267490
- ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
267939
+ parallelPrepared ? ` \u25CF Reviewing the combined parallel implementation in: ${agentCwd}` : ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
267491
267940
  );
267492
267941
  } catch (error) {
267493
267942
  if (worktree) {
@@ -267512,15 +267961,17 @@ var Orchestrator = class {
267512
267961
  try {
267513
267962
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
267514
267963
  if (this.aborted) break;
267515
- const coderOutcome = await this.runCoder(
267516
- agentCwd,
267517
- planText,
267518
- feedback,
267519
- attempt,
267520
- maxAttempts
267521
- );
267522
- if (coderOutcome.status !== "completed") {
267523
- return this.finalizeOutcome(coderOutcome);
267964
+ if (!(parallelPrepared && attempt === 1)) {
267965
+ const coderOutcome = await this.runCoder(
267966
+ agentCwd,
267967
+ planText,
267968
+ feedback,
267969
+ attempt,
267970
+ maxAttempts
267971
+ );
267972
+ if (coderOutcome.status !== "completed") {
267973
+ return this.finalizeOutcome(coderOutcome);
267974
+ }
267524
267975
  }
267525
267976
  if (this.aborted) break;
267526
267977
  const review = await this.runReviewer(agentCwd, attempt, maxAttempts);
@@ -267619,8 +268070,10 @@ var Orchestrator = class {
267619
268070
  {
267620
268071
  modelOverride: this.config.models.planner,
267621
268072
  systemPromptOverride: `You are the Orbit Planner Agent.
267622
- Analyze the codebase and produce a detailed implementation plan.
267623
- Do not modify files. Return the plan as plain text.`,
268073
+ Analyze the codebase and produce a bounded implementation plan. Do not modify files.
268074
+ Return ONLY one JSON object with this shape:
268075
+ {"summary":"shared architecture and acceptance criteria","tasks":[{"id":"short-id","task":"self-contained writer assignment","scopes":["workspace-relative/path"]}]}
268076
+ Use 2-4 tasks only when their write scopes are provably disjoint and they can be implemented independently from the same baseline. Use one task with scope "workspace" for coupled work. Never invent absolute paths or parent traversal.`,
267624
268077
  allowedTools: [
267625
268078
  "read_file",
267626
268079
  "list_files",
@@ -267642,8 +268095,10 @@ Do not modify files. Return the plan as plain text.`,
267642
268095
  let outcome;
267643
268096
  try {
267644
268097
  outcome = await loop.run();
268098
+ const plan = lastAssistantText(loop) || "No plan generated.";
267645
268099
  return {
267646
- plan: lastAssistantText(loop) || "No plan generated.",
268100
+ plan,
268101
+ workPlan: parseParallelWorkPlan(plan),
267647
268102
  outcome
267648
268103
  };
267649
268104
  } catch (error) {
@@ -267666,15 +268121,48 @@ ${feedback}
267666
268121
  Original plan:
267667
268122
  ${plan}` : `Implement the following plan:
267668
268123
  ${plan}`;
267669
- const tracked = this.addTrackedAgent(
268124
+ return this.runWriter(
268125
+ cwd,
268126
+ prompt,
267670
268127
  `coder:${attempt}`,
268128
+ ["workspace"],
268129
+ 0.45 / maxAttempts,
268130
+ `You are the Orbit Coder Agent.
268131
+ Make precise changes in the current isolated workspace. Run focused verification when useful. Do not commit or merge.`
268132
+ );
268133
+ }
268134
+ async runParallelCoder(cwd, plan, task, signal) {
268135
+ this.interaction.showText(
268136
+ `
268137
+ [Phase 2: Parallel writer ${task.id}] Owning ${task.scopes.join(", ")}...`
268138
+ );
268139
+ const prompt = [
268140
+ `Shared plan: ${plan.summary}`,
268141
+ `Your assignment: ${task.task}`,
268142
+ `You exclusively own these write scopes: ${task.scopes.join(", ")}.`,
268143
+ "Do not modify files outside those scopes. Run focused verification for your changes."
268144
+ ].join("\n\n");
268145
+ return this.runWriter(
268146
+ cwd,
268147
+ prompt,
268148
+ `writer:${task.id}`,
268149
+ task.scopes,
268150
+ 0.45 / plan.tasks.length,
268151
+ `You are an Orbit parallel Writer Agent.
268152
+ Work only in your assigned isolated worktree and only inside the declared write scopes. Read broader context when necessary, but never edit outside your ownership. Do not commit or merge.`,
268153
+ signal
268154
+ );
268155
+ }
268156
+ async runWriter(cwd, prompt, role, scopes, budgetFraction, systemPrompt, signal) {
268157
+ const tracked = this.addTrackedAgent(
268158
+ role,
267671
268159
  prompt,
267672
268160
  this.config.models.coder,
267673
- 0.45 / maxAttempts,
268161
+ budgetFraction,
267674
268162
  "write",
267675
- ["workspace"]
268163
+ scopes
267676
268164
  );
267677
- const activeId = tracked?.id || `coder-${attempt}`;
268165
+ const activeId = tracked?.id || role.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64);
267678
268166
  const loop = AgentLoop.initialize(
267679
268167
  cwd,
267680
268168
  this.config,
@@ -267683,8 +268171,7 @@ ${plan}`;
267683
268171
  this.interaction,
267684
268172
  {
267685
268173
  modelOverride: this.config.models.coder,
267686
- systemPromptOverride: `You are the Orbit Coder Agent.
267687
- Make precise changes in the current isolated workspace. Do not commit or merge.`,
268174
+ systemPromptOverride: systemPrompt,
267688
268175
  allowedTools: [
267689
268176
  "read_file",
267690
268177
  "write_file",
@@ -267693,13 +268180,21 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267693
268180
  "glob",
267694
268181
  "grep",
267695
268182
  "git_status",
267696
- "git_diff"
268183
+ "git_diff",
268184
+ "run_tests",
268185
+ "bash",
268186
+ "get_background_task_output",
268187
+ "kill_background_task",
268188
+ "list_background_tasks"
267697
268189
  ],
267698
268190
  disableMcp: true,
267699
- agent: { id: activeId, role: `coder:${attempt}` },
268191
+ agent: { id: activeId, role },
267700
268192
  sessionStorage: this.agentSessionStorage()
267701
268193
  }
267702
268194
  );
268195
+ const abortLoop = () => loop.abort("immediate");
268196
+ if (signal?.aborted) abortLoop();
268197
+ signal?.addEventListener("abort", abortLoop, { once: true });
267703
268198
  this.agentRunTracker.attachSession(tracked, loop.getSessionId());
267704
268199
  this.activeLoops.set(activeId, loop);
267705
268200
  this.markAgentRunning(tracked);
@@ -267712,10 +268207,131 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267712
268207
  throw error;
267713
268208
  } finally {
267714
268209
  if (outcome) this.markAgentFinished(tracked, loop, outcome);
268210
+ signal?.removeEventListener("abort", abortLoop);
267715
268211
  this.activeLoops.delete(activeId);
267716
268212
  await loop.dispose();
267717
268213
  }
267718
268214
  }
268215
+ async prepareParallelWorkspace(worktrees, plan) {
268216
+ const integration = worktrees.createWorktree(
268217
+ generateId("integration").slice(0, 24),
268218
+ { snapshotWorkingTree: true }
268219
+ );
268220
+ const writers = [];
268221
+ let cleanup = true;
268222
+ try {
268223
+ for (const task of plan.tasks) {
268224
+ writers.push({
268225
+ task,
268226
+ session: worktrees.createWorktree(
268227
+ `${task.id}-${generateId("writer").slice(0, 12)}`.slice(0, 63),
268228
+ { snapshotWorkingTree: true }
268229
+ )
268230
+ });
268231
+ }
268232
+ this.interaction.showText(
268233
+ ` \u25CF Running ${writers.length} isolated writers with disjoint ownership scopes...`
268234
+ );
268235
+ const scheduler = new AgentTaskScheduler({
268236
+ maxConcurrency: Math.min(
268237
+ writers.length,
268238
+ this.config.agent.maxReviewConcurrency
268239
+ )
268240
+ });
268241
+ this.activeTaskScheduler = scheduler;
268242
+ const results = await (async () => {
268243
+ try {
268244
+ return await scheduler.run(
268245
+ writers.map(({ task, session }) => ({
268246
+ id: task.id,
268247
+ timeoutMs: this.reviewerTimeoutMs(),
268248
+ access: { mode: "write", scopes: task.scopes },
268249
+ run: (signal) => this.runParallelCoder(session.path, plan, task, signal)
268250
+ }))
268251
+ );
268252
+ } finally {
268253
+ if (this.activeTaskScheduler === scheduler) {
268254
+ this.activeTaskScheduler = void 0;
268255
+ }
268256
+ }
268257
+ })();
268258
+ for (const [index, result] of results.entries()) {
268259
+ if (result.status !== "completed") {
268260
+ return {
268261
+ success: false,
268262
+ preserved: false,
268263
+ outcome: result.status === "aborted" ? this.abortedOutcome(0, result.error.message) : this.failedOutcome(0, result.error.message)
268264
+ };
268265
+ }
268266
+ if (result.value.status !== "completed") {
268267
+ return { success: false, preserved: false, outcome: result.value };
268268
+ }
268269
+ const { task, session } = writers[index];
268270
+ const changedFiles = worktrees.listChangedFiles(session);
268271
+ const outsideScope = changedFiles.filter(
268272
+ (file) => !task.scopes.some(
268273
+ (scope) => agentOwnershipScopeContains(scope, file)
268274
+ )
268275
+ );
268276
+ if (outsideScope.length > 0) {
268277
+ return {
268278
+ success: false,
268279
+ preserved: false,
268280
+ outcome: this.failedOutcome(
268281
+ 0,
268282
+ `Writer ${task.id} modified files outside its ownership: ${outsideScope.join(", ")}`
268283
+ )
268284
+ };
268285
+ }
268286
+ if (changedFiles.length === 0) {
268287
+ return {
268288
+ success: false,
268289
+ preserved: false,
268290
+ outcome: this.failedOutcome(
268291
+ 0,
268292
+ `Writer ${task.id} completed without producing its assigned change.`
268293
+ )
268294
+ };
268295
+ }
268296
+ }
268297
+ const integrated = worktrees.integrateWorktrees(
268298
+ writers.map(({ session }) => session),
268299
+ integration
268300
+ );
268301
+ if (!integrated.success) {
268302
+ cleanup = false;
268303
+ this.interaction.showText(
268304
+ ` \u2716 Parallel integration failed; worktrees were preserved for recovery: ${errorMessage22(integrated.error || "unknown integration error")}`
268305
+ );
268306
+ return {
268307
+ success: false,
268308
+ preserved: true,
268309
+ outcome: this.failedOutcome(
268310
+ 0,
268311
+ integrated.error || "Parallel writer integration failed."
268312
+ )
268313
+ };
268314
+ }
268315
+ cleanup = false;
268316
+ this.interaction.showText(
268317
+ ` \u2714 Integrated ${integrated.integratedCount || writers.length} writer deltas into one review worktree.`
268318
+ );
268319
+ return { success: true, integration };
268320
+ } finally {
268321
+ if (cleanup) {
268322
+ for (const { session } of writers) {
268323
+ try {
268324
+ worktrees.discardWorktree(session);
268325
+ } catch {
268326
+ }
268327
+ }
268328
+ try {
268329
+ worktrees.discardWorktree(integration);
268330
+ } catch {
268331
+ }
268332
+ }
268333
+ }
268334
+ }
267719
268335
  async runReviewer(cwd, attempt, maxAttempts) {
267720
268336
  const team = resolveAgentTeam(this.config);
267721
268337
  const reviewerNames = team.reviewers.map(({ perspective }) => perspective).join(", ");
@@ -267956,62 +268572,62 @@ function errorMessage22(error) {
267956
268572
  const raw = error instanceof Error ? error.message : String(error);
267957
268573
  return redactSecrets(raw).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 2e3);
267958
268574
  }
267959
- var AcceptanceVerificationSchema = z122.object({
267960
- name: z122.string().trim().min(1).max(120),
267961
- command: z122.string().trim().min(1).max(4e3),
267962
- timeoutMs: z122.number().int().min(1e3).max(30 * 6e4).default(12e4)
268575
+ var AcceptanceVerificationSchema = z132.object({
268576
+ name: z132.string().trim().min(1).max(120),
268577
+ command: z132.string().trim().min(1).max(4e3),
268578
+ timeoutMs: z132.number().int().min(1e3).max(30 * 6e4).default(12e4)
267963
268579
  });
267964
- var AcceptanceTaskSchema = z122.object({
267965
- id: z122.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
267966
- prompt: z122.string().trim().min(1).max(2e4),
267967
- mode: z122.enum(["single", "multi"]).default("single"),
267968
- provider: z122.string().trim().min(1).optional(),
267969
- model: z122.string().trim().min(1).optional(),
267970
- verification: z122.array(AcceptanceVerificationSchema).max(20).default([]),
267971
- requiredChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
267972
- forbiddenChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
267973
- maxChangedFiles: z122.number().int().min(0).max(1e4).optional(),
267974
- limits: z122.object({
267975
- maxDurationMs: z122.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
267976
- maxInputTokens: z122.number().int().nonnegative().optional(),
267977
- maxOutputTokens: z122.number().int().nonnegative().optional(),
267978
- maxCostUsd: z122.number().finite().nonnegative().optional(),
267979
- minCacheHitRate: z122.number().finite().min(0).max(1).optional()
268580
+ var AcceptanceTaskSchema = z132.object({
268581
+ id: z132.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
268582
+ prompt: z132.string().trim().min(1).max(2e4),
268583
+ mode: z132.enum(["single", "multi"]).default("single"),
268584
+ provider: z132.string().trim().min(1).optional(),
268585
+ model: z132.string().trim().min(1).optional(),
268586
+ verification: z132.array(AcceptanceVerificationSchema).max(20).default([]),
268587
+ requiredChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
268588
+ forbiddenChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
268589
+ maxChangedFiles: z132.number().int().min(0).max(1e4).optional(),
268590
+ limits: z132.object({
268591
+ maxDurationMs: z132.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
268592
+ maxInputTokens: z132.number().int().nonnegative().optional(),
268593
+ maxOutputTokens: z132.number().int().nonnegative().optional(),
268594
+ maxCostUsd: z132.number().finite().nonnegative().optional(),
268595
+ minCacheHitRate: z132.number().finite().min(0).max(1).optional()
267980
268596
  }).optional()
267981
268597
  });
267982
- var AcceptanceSuiteSchema = z122.object({
267983
- schemaVersion: z122.literal(1),
267984
- name: z122.string().trim().min(1).max(200),
267985
- description: z122.string().trim().max(2e3).optional(),
267986
- tasks: z122.array(AcceptanceTaskSchema).min(1).max(100)
268598
+ var AcceptanceSuiteSchema = z132.object({
268599
+ schemaVersion: z132.literal(1),
268600
+ name: z132.string().trim().min(1).max(200),
268601
+ description: z132.string().trim().max(2e3).optional(),
268602
+ tasks: z132.array(AcceptanceTaskSchema).min(1).max(100)
267987
268603
  });
267988
- var AcceptanceCheckResultSchema = z122.object({
267989
- name: z122.string(),
267990
- passed: z122.boolean(),
267991
- durationMs: z122.number().int().nonnegative(),
267992
- exitCode: z122.number().int().optional(),
267993
- summary: z122.string().max(4e3)
268604
+ var AcceptanceCheckResultSchema = z132.object({
268605
+ name: z132.string(),
268606
+ passed: z132.boolean(),
268607
+ durationMs: z132.number().int().nonnegative(),
268608
+ exitCode: z132.number().int().optional(),
268609
+ summary: z132.string().max(4e3)
267994
268610
  });
267995
- var AcceptanceTaskResultSchema = z122.object({
267996
- taskId: z122.string(),
267997
- sessionId: z122.string().optional(),
267998
- traceFile: z122.string().optional(),
267999
- passed: z122.boolean(),
268000
- agentStatus: z122.enum(["completed", "failed", "aborted"]),
268001
- durationMs: z122.number().int().nonnegative(),
268002
- requestedProvider: z122.string().optional(),
268003
- requestedModel: z122.string().optional(),
268004
- resolvedModels: z122.array(z122.string()).default([]),
268005
- usage: z122.object({
268006
- inputTokens: z122.number().int().nonnegative(),
268007
- outputTokens: z122.number().int().nonnegative(),
268008
- cacheReadTokens: z122.number().int().nonnegative(),
268009
- cacheHitRate: z122.number().finite().min(0).max(1),
268010
- costUsd: z122.number().finite().nonnegative()
268611
+ var AcceptanceTaskResultSchema = z132.object({
268612
+ taskId: z132.string(),
268613
+ sessionId: z132.string().optional(),
268614
+ traceFile: z132.string().optional(),
268615
+ passed: z132.boolean(),
268616
+ agentStatus: z132.enum(["completed", "failed", "aborted"]),
268617
+ durationMs: z132.number().int().nonnegative(),
268618
+ requestedProvider: z132.string().optional(),
268619
+ requestedModel: z132.string().optional(),
268620
+ resolvedModels: z132.array(z132.string()).default([]),
268621
+ usage: z132.object({
268622
+ inputTokens: z132.number().int().nonnegative(),
268623
+ outputTokens: z132.number().int().nonnegative(),
268624
+ cacheReadTokens: z132.number().int().nonnegative(),
268625
+ cacheHitRate: z132.number().finite().min(0).max(1),
268626
+ costUsd: z132.number().finite().nonnegative()
268011
268627
  }).optional(),
268012
- changedFiles: z122.array(z122.string()),
268013
- checks: z122.array(AcceptanceCheckResultSchema),
268014
- failureReasons: z122.array(z122.string())
268628
+ changedFiles: z132.array(z132.string()),
268629
+ checks: z132.array(AcceptanceCheckResultSchema),
268630
+ failureReasons: z132.array(z132.string())
268015
268631
  });
268016
268632
  function scoreAcceptanceTask(input) {
268017
268633
  const task = AcceptanceTaskSchema.parse(input.task);
@@ -268858,7 +269474,6 @@ async function probeProviderCapabilities(cwd, config, provider, options = {}) {
268858
269474
  () => controller.abort(),
268859
269475
  options.timeoutMs ?? DEFAULT_PROVIDER_PROBE_TIMEOUT_MS
268860
269476
  );
268861
- timeout.unref?.();
268862
269477
  const result = {
268863
269478
  providerId: provider.id,
268864
269479
  model,
@@ -277382,6 +277997,10 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
277382
277997
  button.addEventListener('click', () => requestPermissionMode(button.dataset.mode).catch(() => {}));
277383
277998
  });
277384
277999
 
278000
+ elements.agentMaxIterations.addEventListener('change', () => {
278001
+ applySettings({ agentMaxIterations: Number(elements.agentMaxIterations.value) }, true).catch(() => {});
278002
+ });
278003
+
277385
278004
  elements.searchToggle.addEventListener('click', () => {
277386
278005
  const enabled = elements.searchToggle.getAttribute('aria-pressed') !== 'true';
277387
278006
  applySettings({ webSearchEnabled: enabled }, true).catch(() => {});
@@ -278409,6 +279028,7 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
278409
279028
  table: '数据表格',
278410
279029
  reasoning: '思考过程',
278411
279030
  tool: '工具',
279031
+ toolBatch: '工具步骤',
278412
279032
  running: '运行中',
278413
279033
  done: '完成',
278414
279034
  error: '失败',
@@ -278534,9 +279154,9 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
278534
279154
  permissionStrict: chinese('严格模式会在重要操作前请求确认。', '嚴格模式會在重要操作前請求確認。'),
278535
279155
  permissionNormal: chinese('标准模式会在写入和执行命令前请求确认。', '標準模式會在寫入和執行命令前請求確認。'),
278536
279156
  permissionPlan: chinese('规划模式只分析和读取,不修改文件。', '規劃模式只分析和讀取,不修改檔案。'),
278537
- permissionGuards: chinese('危险操作会被阻止,显式文件路径会受保护;本机命令、成本与失控检查仍然有效。', '危險操作會被阻止,顯式檔案路徑會受保護;本機命令、成本與失控檢查仍然有效。'),
279157
+ permissionGuards: chinese('危险操作会被阻止,显式文件路径会受保护;本机命令、预算与长任务上限仍然有效。', '危險操作會被阻止,顯式檔案路徑會受保護;本機命令、預算與長任務上限仍然有效。'),
278538
279158
  permissionGuardsReduced: chinese('警告:部分硬安全保护已在配置中关闭。', '警告:部分硬安全保護已在設定中關閉。'),
278539
- permissionNoGuards: chinese('权限策略不再拦截或复核危险、密钥、不透明、本地网络及工作区外操作。命令拥有当前系统账户权限并继承 Orbit 进程环境;已运行的子进程会保留这些权限直至停止。输出脱敏、项目钩子、验证契约、工具限制及成本与失控检查仍有效;工作区外改动无法由 Orbit 回滚。', '權限策略不再攔截或複核危險、密鑰、不透明、本機網路及工作區外操作。命令擁有目前系統帳戶權限並繼承 Orbit 程序環境;已執行的子程序會保留這些權限直至停止。輸出脫敏、專案掛鉤、驗證契約、工具限制及成本與失控檢查仍有效;工作區外變更無法由 Orbit 回滾。'),
279159
+ permissionNoGuards: chinese('权限策略不再拦截或复核危险、密钥、不透明、本地网络及工作区外操作。命令拥有当前系统账户权限并继承 Orbit 进程环境;已运行的子进程会保留这些权限直至停止。中间迭代检查点会自动继续且不再询问。输出脱敏、项目钩子、验证契约、预算、停滞循环检测和配置的最终迭代上限仍有效;工作区外改动无法由 Orbit 回滚。', '權限策略不再攔截或複核危險、密鑰、不透明、本機網路及工作區外操作。命令擁有目前系統帳戶權限並繼承 Orbit 程序環境;已執行的子程序會保留這些權限直至停止。中間迭代檢查點會自動繼續且不再詢問。輸出脫敏、專案掛鉤、驗證契約、預算、停滯迴圈偵測和設定的最終迭代上限仍有效;工作區外變更無法由 Orbit 回滾。'),
278540
279160
  }
278541
279161
  : {
278542
279162
  connected: 'Connected',
@@ -278562,6 +279182,7 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
278562
279182
  table: 'Data table',
278563
279183
  reasoning: 'Reasoning',
278564
279184
  tool: 'Tool',
279185
+ toolBatch: 'Tool steps',
278565
279186
  running: 'Running',
278566
279187
  done: 'Done',
278567
279188
  error: 'Failed',
@@ -278687,9 +279308,9 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
278687
279308
  permissionStrict: 'Strict mode asks before consequential operations.',
278688
279309
  permissionNormal: 'Normal mode asks before writes and command execution.',
278689
279310
  permissionPlan: 'Plan mode analyzes and reads without changing files.',
278690
- permissionGuards: 'Dangerous patterns are blocked and explicit file paths are guarded; commands remain host processes and periodic cost/runaway checks stay active.',
279311
+ permissionGuards: 'Dangerous patterns are blocked and explicit file paths are guarded; commands remain host processes and budget/long-task limits stay active.',
278691
279312
  permissionGuardsReduced: 'Warning: some hard safety guards are disabled in configuration.',
278692
- permissionNoGuards: "The permission policy no longer blocks or reviews dangerous, protected, opaque, local-network, or outside-workspace actions. Commands use host-account permissions and inherit Orbit's process environment; running children retain that authority until stopped. Output redaction, project hooks, verification contracts, tool limits, and cost/runaway checks remain; outside-workspace changes have no Orbit rollback.",
279313
+ permissionNoGuards: "The permission policy no longer blocks or reviews dangerous, protected, opaque, local-network, or outside-workspace actions. Commands use host-account permissions and inherit Orbit's process environment; running children retain that authority until stopped. Intermediate iteration checkpoints continue automatically without asking. Output redaction, project hooks, verification contracts, budget, stalled-loop detection, and the configured final iteration ceiling remain; outside-workspace changes have no Orbit rollback.",
278693
279314
  };
278694
279315
 
278695
279316
  if (language === 'zh-TW') {
@@ -278934,6 +279555,7 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
278934
279555
  permissionSelect: byId('permissionSelect'),
278935
279556
  permissionSegments: byId('permissionSegments'),
278936
279557
  permissionSummary: byId('permissionSummary'),
279558
+ agentMaxIterations: byId('agentMaxIterations'),
278937
279559
  searchToggle: byId('searchToggle'),
278938
279560
  searchEnabled: byId('searchEnabled'),
278939
279561
  searchDependencies: byId('searchDependencies'),
@@ -280082,6 +280704,54 @@ var WEB_UI_CLIENT_MESSAGES_SCRIPT = String.raw` function appendInline(parent, t
280082
280704
  return { root: details, body };
280083
280705
  }
280084
280706
 
280707
+ function displayToolName(name) {
280708
+ const normalized = String(name || copy.tool).trim();
280709
+ if (normalized === 'bash') return 'Shell';
280710
+ if (normalized === 'run_tests') return language === 'en' ? 'Verification' : '验证';
280711
+ return normalized.replace(/_/g, ' ');
280712
+ }
280713
+
280714
+ function isBatchableTool(block) {
280715
+ return block
280716
+ && block.type === 'tool'
280717
+ && block.status === 'success'
280718
+ && !block.isError
280719
+ && ['read_file', 'grep', 'glob', 'bash', 'get_background_task_output'].includes(block.name);
280720
+ }
280721
+
280722
+ function createToolBatch(blocks) {
280723
+ const root = document.createElement('details');
280724
+ root.className = 'tool-batch is-success';
280725
+ const summary = document.createElement('summary');
280726
+ summary.className = 'tool-batch-summary';
280727
+ const status = document.createElement('span');
280728
+ status.className = 'tool-status';
280729
+ const label = document.createElement('strong');
280730
+ label.textContent = copy.toolBatch;
280731
+ const names = [...new Set(blocks.map((block) => displayToolName(block.name)))];
280732
+ const context = document.createElement('span');
280733
+ context.className = 'tool-context';
280734
+ context.textContent = names.slice(0, 3).join(' · ');
280735
+ const count = document.createElement('span');
280736
+ count.className = 'tool-batch-count';
280737
+ count.textContent = '×' + blocks.length;
280738
+ const chevron = document.createElement('span');
280739
+ chevron.className = 'tool-chevron';
280740
+ chevron.setAttribute('aria-hidden', 'true');
280741
+ chevron.textContent = '›';
280742
+ summary.append(status, label, context, count, chevron);
280743
+ const body = document.createElement('div');
280744
+ body.className = 'tool-batch-body';
280745
+ blocks.forEach((block) => body.append(createToolCard(block)));
280746
+ root.append(summary, body);
280747
+ summary.setAttribute('aria-label', copy.toolBatch + ' · ' + blocks.length);
280748
+ summary.setAttribute('aria-expanded', 'false');
280749
+ root.addEventListener('toggle', () => {
280750
+ summary.setAttribute('aria-expanded', String(root.open));
280751
+ });
280752
+ return root;
280753
+ }
280754
+
280085
280755
  function createToolCard(block) {
280086
280756
  const root = document.createElement('details');
280087
280757
  const summary = document.createElement('summary');
@@ -280122,7 +280792,7 @@ var WEB_UI_CLIENT_MESSAGES_SCRIPT = String.raw` function appendInline(parent, t
280122
280792
  const context = root.querySelector('.tool-context');
280123
280793
  const outcome = root.querySelector('.tool-outcome');
280124
280794
  const detail = root.querySelector('.tool-detail');
280125
- label.textContent = block.name || copy.tool;
280795
+ label.textContent = displayToolName(block.name);
280126
280796
  const summaryText = String(block.summary || '').trim();
280127
280797
  const detailText = String(block.detail || '').trim();
280128
280798
  context.textContent = summaryText || detailText.split('\n', 1)[0] || '';
@@ -280240,7 +280910,21 @@ var WEB_UI_CLIENT_MESSAGES_SCRIPT = String.raw` function appendInline(parent, t
280240
280910
  const blocks = Array.isArray(message.blocks) && message.blocks.length
280241
280911
  ? message.blocks
280242
280912
  : [{ type: 'text', text: message.text || '' }];
280243
- for (const block of blocks) {
280913
+ for (let blockIndex = 0; blockIndex < blocks.length; blockIndex += 1) {
280914
+ const block = blocks[blockIndex];
280915
+ if (!streaming && isBatchableTool(block)) {
280916
+ const sequence = [block];
280917
+ while (blockIndex + 1 < blocks.length && isBatchableTool(blocks[blockIndex + 1])) {
280918
+ sequence.push(blocks[blockIndex + 1]);
280919
+ blockIndex += 1;
280920
+ }
280921
+ if (sequence.length >= 3) {
280922
+ content.append(createToolBatch(sequence));
280923
+ continue;
280924
+ }
280925
+ sequence.forEach((item) => content.append(createToolCard(item)));
280926
+ continue;
280927
+ }
280244
280928
  if (block.type === 'text' && block.text) {
280245
280929
  const body = document.createElement('div');
280246
280930
  body.className = 'rich-text' + (streaming ? ' stream-caret' : '');
@@ -281711,6 +282395,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
281711
282395
  }
281712
282396
  elements.permissionSummary.classList.toggle('is-full-access', Boolean(permissions.fullAccess));
281713
282397
  elements.permissionSummary.classList.toggle('is-warning', !hardGuardsEnabled || (mode === 'auto' && !permissions.fullAccess));
282398
+ elements.agentMaxIterations.value = String(data.agent && data.agent.maxIterations || 200);
281714
282399
  const webSearch = data.tools && data.tools.webSearch || {};
281715
282400
  elements.searchProvider.value = webSearch.provider || 'auto';
281716
282401
  syncSelectControl(elements.searchProvider);
@@ -282971,7 +283656,8 @@ function summarizeWebToolValue(value, options = {}) {
282971
283656
  "symbol",
282972
283657
  "url",
282973
283658
  "language",
282974
- "description"
283659
+ "description",
283660
+ "command"
282975
283661
  ];
282976
283662
  const entries = [];
282977
283663
  for (const field of safeFields) {
@@ -283077,6 +283763,9 @@ function safeWebText(value, maxLength) {
283077
283763
  }
283078
283764
  function safeWebToolText(value, maxLength) {
283079
283765
  return safeWebText(value, maxLength).replace(
283766
+ /(--(?:api-?key|token|password|secret)(?:=|\s+))(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
283767
+ "$1***REDACTED***"
283768
+ ).replace(
283080
283769
  /((?:api[_-]?key|token|password|secret)\s*[=:]\s*)[^\s,;]+/gi,
283081
283770
  "$1***REDACTED***"
283082
283771
  ).trim();
@@ -283268,6 +283957,9 @@ function collectWebUiStatus(options, activeTurn) {
283268
283957
  maxReviewAttempts: config.agent.maxReviewAttempts,
283269
283958
  maxReviewConcurrency: config.agent.maxReviewConcurrency
283270
283959
  },
283960
+ agent: {
283961
+ maxIterations: config.agent.maxIterations
283962
+ },
283271
283963
  backgroundTasks,
283272
283964
  inputQueue,
283273
283965
  provider: {
@@ -283582,6 +284274,7 @@ function collectWebUiSettings(options) {
283582
284274
  model: activeModel2,
283583
284275
  modelOptions: buildModelOptions(options, activeModel2),
283584
284276
  permissionMode: config.permissions.mode,
284277
+ agentMaxIterations: config.agent.maxIterations,
283585
284278
  webSearchEnabled: config.tools.webSearch.enabled,
283586
284279
  webSearchProvider: config.tools.webSearch.provider,
283587
284280
  webSearchMaxResults: config.tools.webSearch.maxResults,
@@ -284194,11 +284887,13 @@ var BASE_COPY = {
284194
284887
  permission: "Permission mode",
284195
284888
  permissionDescription: "Choose how much Orbit may do without interrupting you.",
284196
284889
  permissionGuardLabel: "The active permission scope and remaining safeguards appear here.",
284890
+ agentMaxIterations: "Long-task iteration limit",
284891
+ agentMaxIterationsDescription: "Maximum model/tool rounds in one task. Full Access continues intermediate checkpoints without asking; this final ceiling, cancellation, budget, and stalled-loop detection remain active.",
284197
284892
  fullAccessConfirmTitle: "Grant unrestricted Full Access?",
284198
284893
  fullAccessConfirmBody: "Orbit's permission policy will approve every enabled tool action without asking or requesting post-write review.",
284199
284894
  fullAccessConfirmScope: "Reads, writes, local/private network calls, dangerous operations, protected paths, and outside-workspace commands run automatically.",
284200
284895
  fullAccessConfirmGuards: "No permission guard remains. Opaque interpreters and commands that can delete or overwrite host data are also approved.",
284201
- fullAccessConfirmHost: "Actions receive your operating-system account's permissions, and child commands inherit the Orbit process environment, including credential variables; already-running children keep that authority until stopped. Credential values remain redacted from logs and model-visible output. Outside-workspace changes are not covered by Orbit rollback. Project hooks, verification contracts, tool limits, cancellation, and cost/runaway checks remain active.",
284896
+ fullAccessConfirmHost: "Actions receive your operating-system account's permissions, and child commands inherit the Orbit process environment, including credential variables; already-running children keep that authority until stopped. Credential values remain redacted from logs and model-visible output. Outside-workspace changes are not covered by Orbit rollback. Intermediate iteration checkpoints continue automatically without asking; the configured final iteration ceiling, cancellation, budget, stalled-loop detection, project hooks, and verification contracts remain active.",
284202
284897
  fullAccessConfirmAction: "Grant Full Access",
284203
284898
  modeStrict: "Strict",
284204
284899
  modeNormal: "Normal",
@@ -284380,11 +285075,13 @@ var BASE_COPY = {
284380
285075
  permission: "\u6743\u9650\u6A21\u5F0F",
284381
285076
  permissionDescription: "\u9009\u62E9 Orbit \u53EF\u4EE5\u5728\u4E0D\u6253\u65AD\u4F60\u7684\u60C5\u51B5\u4E0B\u6267\u884C\u54EA\u4E9B\u64CD\u4F5C\u3002",
284382
285077
  permissionGuardLabel: "\u8FD9\u91CC\u4F1A\u663E\u793A\u5F53\u524D\u6743\u9650\u8303\u56F4\u4EE5\u53CA\u4ECD\u7136\u751F\u6548\u7684\u4FDD\u62A4\u673A\u5236\u3002",
285078
+ agentMaxIterations: "\u957F\u4EFB\u52A1\u8FED\u4EE3\u4E0A\u9650",
285079
+ agentMaxIterationsDescription: "\u5355\u6B21\u4EFB\u52A1\u5141\u8BB8\u7684\u6700\u5927\u6A21\u578B/\u5DE5\u5177\u8F6E\u6570\u3002Full Access \u4F1A\u65E0\u8BE2\u95EE\u8D8A\u8FC7\u4E2D\u95F4\u68C0\u67E5\u70B9\uFF1B\u6700\u7EC8\u4E0A\u9650\u3001\u53D6\u6D88\u3001\u9884\u7B97\u548C\u505C\u6EDE\u5FAA\u73AF\u68C0\u6D4B\u4ECD\u7136\u6709\u6548\u3002",
284383
285080
  fullAccessConfirmTitle: "\u6388\u4E88\u5B8C\u6574 Full Access\uFF1F",
284384
285081
  fullAccessConfirmBody: "Orbit \u7684\u6743\u9650\u7B56\u7565\u5C06\u81EA\u52A8\u6279\u51C6\u6240\u6709\u5DF2\u542F\u7528\u5DE5\u5177\u64CD\u4F5C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u6216\u8981\u6C42\u5199\u5165\u540E\u590D\u6838\u3002",
284385
285082
  fullAccessConfirmScope: "\u8BFB\u53D6\u3001\u5199\u5165\u3001\u672C\u5730\u6216\u79C1\u6709\u7F51\u7EDC\u8BBF\u95EE\u3001\u5371\u9669\u64CD\u4F5C\u3001\u5BC6\u94A5\u8DEF\u5F84\u53CA\u5DE5\u4F5C\u533A\u5916\u547D\u4EE4\u5747\u4F1A\u81EA\u52A8\u6267\u884C\u3002",
284386
285083
  fullAccessConfirmGuards: "\u6743\u9650\u4FDD\u62A4\u5C06\u5168\u90E8\u5173\u95ED\uFF1B\u4E0D\u900F\u660E\u89E3\u91CA\u5668\u4EE5\u53CA\u53EF\u80FD\u5220\u9664\u6216\u8986\u76D6\u4E3B\u673A\u6570\u636E\u7684\u547D\u4EE4\u4E5F\u4F1A\u83B7\u51C6\u6267\u884C\u3002",
284387
- fullAccessConfirmHost: "\u64CD\u4F5C\u62E5\u6709\u5F53\u524D\u7CFB\u7EDF\u8D26\u6237\u7684\u6743\u9650\uFF0C\u5B50\u547D\u4EE4\u4F1A\u7EE7\u627F Orbit \u8FDB\u7A0B\u73AF\u5883\uFF0C\u5305\u62EC\u51ED\u636E\u53D8\u91CF\uFF1B\u5DF2\u8FD0\u884C\u7684\u5B50\u8FDB\u7A0B\u4F1A\u4FDD\u7559\u8FD9\u4E9B\u6743\u9650\u76F4\u81F3\u505C\u6B62\u3002\u51ED\u636E\u503C\u4ECD\u4F1A\u4ECE\u65E5\u5FD7\u548C\u6A21\u578B\u53EF\u89C1\u8F93\u51FA\u4E2D\u8131\u654F\uFF0C\u5DE5\u4F5C\u533A\u5916\u6539\u52A8\u4E0D\u53D7 Orbit \u56DE\u6EDA\u4FDD\u62A4\u3002\u9879\u76EE\u94A9\u5B50\u3001\u9A8C\u8BC1\u5951\u7EA6\u3001\u5DE5\u5177\u9650\u5236\u3001\u53D6\u6D88\u80FD\u529B\u4EE5\u53CA\u6210\u672C\u4E0E\u5931\u63A7\u68C0\u67E5\u4ECD\u7136\u6709\u6548\u3002",
285084
+ fullAccessConfirmHost: "\u64CD\u4F5C\u62E5\u6709\u5F53\u524D\u7CFB\u7EDF\u8D26\u6237\u7684\u6743\u9650\uFF0C\u5B50\u547D\u4EE4\u4F1A\u7EE7\u627F Orbit \u8FDB\u7A0B\u73AF\u5883\uFF0C\u5305\u62EC\u51ED\u636E\u53D8\u91CF\uFF1B\u5DF2\u8FD0\u884C\u7684\u5B50\u8FDB\u7A0B\u4F1A\u4FDD\u7559\u8FD9\u4E9B\u6743\u9650\u76F4\u81F3\u505C\u6B62\u3002\u51ED\u636E\u503C\u4ECD\u4F1A\u4ECE\u65E5\u5FD7\u548C\u6A21\u578B\u53EF\u89C1\u8F93\u51FA\u4E2D\u8131\u654F\uFF0C\u5DE5\u4F5C\u533A\u5916\u6539\u52A8\u4E0D\u53D7 Orbit \u56DE\u6EDA\u4FDD\u62A4\u3002\u4E2D\u95F4\u8FED\u4EE3\u68C0\u67E5\u70B9\u4F1A\u65E0\u8BE2\u95EE\u81EA\u52A8\u7EE7\u7EED\uFF1B\u914D\u7F6E\u7684\u6700\u7EC8\u8FED\u4EE3\u4E0A\u9650\u3001\u53D6\u6D88\u80FD\u529B\u3001\u9884\u7B97\u3001\u505C\u6EDE\u5FAA\u73AF\u68C0\u6D4B\u3001\u9879\u76EE\u94A9\u5B50\u53CA\u9A8C\u8BC1\u5951\u7EA6\u4ECD\u7136\u6709\u6548\u3002",
284388
285085
  fullAccessConfirmAction: "\u6388\u4E88\u5B8C\u6574\u6743\u9650",
284389
285086
  modeStrict: "\u4E25\u683C",
284390
285087
  modeNormal: "\u6807\u51C6",
@@ -284538,11 +285235,13 @@ var COPY = {
284538
285235
  permission: "\u6B0A\u9650\u6A21\u5F0F",
284539
285236
  permissionDescription: "\u9078\u64C7 Orbit \u53EF\u4EE5\u5728\u4E0D\u4E2D\u65B7\u4F60\u7684\u60C5\u6CC1\u4E0B\u57F7\u884C\u54EA\u4E9B\u64CD\u4F5C\u3002",
284540
285237
  permissionGuardLabel: "\u9019\u88E1\u6703\u986F\u793A\u76EE\u524D\u6B0A\u9650\u7BC4\u570D\u4EE5\u53CA\u4ECD\u7136\u751F\u6548\u7684\u4FDD\u8B77\u6A5F\u5236\u3002",
285238
+ agentMaxIterations: "\u9577\u4EFB\u52D9\u8FED\u4EE3\u4E0A\u9650",
285239
+ agentMaxIterationsDescription: "\u55AE\u6B21\u4EFB\u52D9\u5141\u8A31\u7684\u6700\u5927\u6A21\u578B/\u5DE5\u5177\u8F2A\u6578\u3002Full Access \u6703\u4E0D\u7D93\u8A62\u554F\u8D8A\u904E\u4E2D\u9593\u6AA2\u67E5\u9EDE\uFF1B\u6700\u7D42\u4E0A\u9650\u3001\u53D6\u6D88\u3001\u9810\u7B97\u548C\u505C\u6EEF\u8FF4\u5708\u5075\u6E2C\u4ECD\u7136\u6709\u6548\u3002",
284541
285240
  fullAccessConfirmTitle: "\u6388\u4E88\u5B8C\u6574 Full Access\uFF1F",
284542
285241
  fullAccessConfirmBody: "Orbit \u7684\u6B0A\u9650\u7B56\u7565\u5C07\u81EA\u52D5\u6279\u51C6\u6240\u6709\u5DF2\u555F\u7528\u5DE5\u5177\u64CD\u4F5C\uFF0C\u4E0D\u518D\u8A62\u554F\u6216\u8981\u6C42\u5BEB\u5165\u5F8C\u8907\u6838\u3002",
284543
285242
  fullAccessConfirmScope: "\u8B80\u53D6\u3001\u5BEB\u5165\u3001\u672C\u6A5F\u6216\u79C1\u6709\u7DB2\u8DEF\u5B58\u53D6\u3001\u5371\u96AA\u64CD\u4F5C\u3001\u5BC6\u9470\u8DEF\u5F91\u53CA\u5DE5\u4F5C\u5340\u5916\u547D\u4EE4\u5747\u6703\u81EA\u52D5\u57F7\u884C\u3002",
284544
285243
  fullAccessConfirmGuards: "\u6B0A\u9650\u4FDD\u8B77\u5C07\u5168\u90E8\u95DC\u9589\uFF1B\u4E0D\u900F\u660E\u89E3\u8B6F\u5668\u4EE5\u53CA\u53EF\u80FD\u522A\u9664\u6216\u8986\u5BEB\u4E3B\u6A5F\u8CC7\u6599\u7684\u547D\u4EE4\u4E5F\u6703\u7372\u51C6\u57F7\u884C\u3002",
284545
- fullAccessConfirmHost: "\u64CD\u4F5C\u64C1\u6709\u76EE\u524D\u7CFB\u7D71\u5E33\u6236\u7684\u6B0A\u9650\uFF0C\u5B50\u547D\u4EE4\u6703\u7E7C\u627F Orbit \u7A0B\u5E8F\u74B0\u5883\uFF0C\u5305\u62EC\u6191\u64DA\u8B8A\u6578\uFF1B\u5DF2\u57F7\u884C\u7684\u5B50\u7A0B\u5E8F\u6703\u4FDD\u7559\u9019\u4E9B\u6B0A\u9650\u76F4\u81F3\u505C\u6B62\u3002\u6191\u64DA\u503C\u4ECD\u6703\u5F9E\u65E5\u8A8C\u548C\u6A21\u578B\u53EF\u898B\u8F38\u51FA\u4E2D\u812B\u654F\uFF0C\u5DE5\u4F5C\u5340\u5916\u8B8A\u66F4\u4E0D\u53D7 Orbit \u56DE\u6EFE\u4FDD\u8B77\u3002\u5C08\u6848\u639B\u9264\u3001\u9A57\u8B49\u5951\u7D04\u3001\u5DE5\u5177\u9650\u5236\u3001\u53D6\u6D88\u80FD\u529B\u4EE5\u53CA\u6210\u672C\u8207\u5931\u63A7\u6AA2\u67E5\u4ECD\u7136\u6709\u6548\u3002",
285244
+ fullAccessConfirmHost: "\u64CD\u4F5C\u64C1\u6709\u76EE\u524D\u7CFB\u7D71\u5E33\u6236\u7684\u6B0A\u9650\uFF0C\u5B50\u547D\u4EE4\u6703\u7E7C\u627F Orbit \u7A0B\u5E8F\u74B0\u5883\uFF0C\u5305\u62EC\u6191\u64DA\u8B8A\u6578\uFF1B\u5DF2\u57F7\u884C\u7684\u5B50\u7A0B\u5E8F\u6703\u4FDD\u7559\u9019\u4E9B\u6B0A\u9650\u76F4\u81F3\u505C\u6B62\u3002\u6191\u64DA\u503C\u4ECD\u6703\u5F9E\u65E5\u8A8C\u548C\u6A21\u578B\u53EF\u898B\u8F38\u51FA\u4E2D\u812B\u654F\uFF0C\u5DE5\u4F5C\u5340\u5916\u8B8A\u66F4\u4E0D\u53D7 Orbit \u56DE\u6EFE\u4FDD\u8B77\u3002\u4E2D\u9593\u8FED\u4EE3\u6AA2\u67E5\u9EDE\u6703\u4E0D\u7D93\u8A62\u554F\u81EA\u52D5\u7E7C\u7E8C\uFF1B\u8A2D\u5B9A\u7684\u6700\u7D42\u8FED\u4EE3\u4E0A\u9650\u3001\u53D6\u6D88\u80FD\u529B\u3001\u9810\u7B97\u3001\u505C\u6EEF\u8FF4\u5708\u5075\u6E2C\u3001\u5C08\u6848\u639B\u9264\u53CA\u9A57\u8B49\u5951\u7D04\u4ECD\u7136\u6709\u6548\u3002",
284546
285245
  fullAccessConfirmAction: "\u6388\u4E88\u5B8C\u6574\u6B0A\u9650",
284547
285246
  modeStrict: "\u56B4\u683C",
284548
285247
  modeNormal: "\u6A19\u6E96",
@@ -285034,6 +285733,10 @@ function renderWebUiPage(language) {
285034
285733
  <button type="button" data-mode="plan" aria-pressed="false">${copy.modePlan}</button>
285035
285734
  </div>
285036
285735
  <p class="permission-summary" id="permissionSummary" role="status" aria-live="polite">${copy.permissionGuardLabel}</p>
285736
+ <div class="setting-row setting-row-stacked long-task-setting">
285737
+ <div><label for="agentMaxIterations"><h3>${copy.agentMaxIterations}</h3></label><p id="agentMaxIterationsDescription">${copy.agentMaxIterationsDescription}</p></div>
285738
+ <input class="field-control" id="agentMaxIterations" type="number" min="1" max="1000" step="20" value="200" inputmode="numeric" aria-describedby="agentMaxIterationsDescription" />
285739
+ </div>
285037
285740
  </section>
285038
285741
  <section class="settings-group">
285039
285742
  <div class="setting-row">
@@ -287159,6 +287862,64 @@ var WEB_UI_CONVERSATION_STYLES = String.raw`
287159
287862
  color: var(--danger);
287160
287863
  }
287161
287864
 
287865
+ .tool-batch {
287866
+ margin: 11px 0;
287867
+ overflow: hidden;
287868
+ color: var(--muted);
287869
+ background: color-mix(in srgb, var(--surface-subtle) 72%, transparent);
287870
+ border: 1px solid var(--border);
287871
+ border-radius: 11px;
287872
+ }
287873
+
287874
+ .tool-batch-summary {
287875
+ min-height: 40px;
287876
+ display: grid;
287877
+ grid-template-columns: auto auto minmax(0, 1fr) auto auto;
287878
+ align-items: center;
287879
+ gap: 9px;
287880
+ padding: 8px 11px;
287881
+ cursor: pointer;
287882
+ list-style: none;
287883
+ }
287884
+
287885
+ .tool-batch-summary::-webkit-details-marker {
287886
+ display: none;
287887
+ }
287888
+
287889
+ .tool-batch-summary strong {
287890
+ color: var(--ink-strong);
287891
+ font-size: 11.5px;
287892
+ }
287893
+
287894
+ .tool-batch-count {
287895
+ min-width: 30px;
287896
+ padding: 2px 7px;
287897
+ color: var(--accent-strong);
287898
+ background: var(--accent-soft);
287899
+ border-radius: 999px;
287900
+ font: 600 10.5px/1.4 var(--font-mono);
287901
+ text-align: center;
287902
+ }
287903
+
287904
+ .tool-batch-body {
287905
+ padding: 1px 9px 9px;
287906
+ border-top: 1px solid var(--border);
287907
+ }
287908
+
287909
+ .tool-batch-body .tool-card {
287910
+ margin: 8px 0 0;
287911
+ background: var(--surface-raised);
287912
+ }
287913
+
287914
+ .tool-batch.is-success > .tool-batch-summary .tool-status {
287915
+ background: var(--success);
287916
+ box-shadow: 0 0 0 3px var(--success-soft);
287917
+ }
287918
+
287919
+ .tool-batch[open] > .tool-batch-summary .tool-chevron {
287920
+ transform: rotate(90deg);
287921
+ }
287922
+
287162
287923
  .stream-caret > p:last-child::after,
287163
287924
  .stream-caret > h1:last-child::after,
287164
287925
  .stream-caret > h2:last-child::after,
@@ -290349,6 +291110,7 @@ var WEB_UI_RESPONSIVE_STYLES = String.raw`
290349
291110
  textarea,
290350
291111
  .message.user .message-content,
290351
291112
  .tool-card,
291113
+ .tool-batch,
290352
291114
  .code-block,
290353
291115
  .composer-shell,
290354
291116
  .inspector,
@@ -291984,6 +292746,7 @@ var SettingsPatchSchema = z58.object({
291984
292746
  model: z58.string().trim().min(1).max(200).optional(),
291985
292747
  permissionMode: z58.enum(["strict", "normal", "auto", "plan"]).optional(),
291986
292748
  fullAccessConfirmed: z58.literal(true).optional(),
292749
+ agentMaxIterations: z58.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
291987
292750
  webSearchEnabled: z58.boolean().optional(),
291988
292751
  webSearchProvider: z58.enum(["auto", "searxng", "tavily", "bing", "duckduckgo"]).optional(),
291989
292752
  webSearchMaxResults: z58.number().int().min(1).max(20).optional(),
@@ -297483,6 +298246,9 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
297483
298246
  const preset = applyPermissionModePreset(draft, patch.permissionMode);
297484
298247
  if (!preset.ok) return preset;
297485
298248
  }
298249
+ if (typeof patch.agentMaxIterations === "number") {
298250
+ draft.agent.maxIterations = patch.agentMaxIterations;
298251
+ }
297486
298252
  if (typeof patch.webSearchEnabled === "boolean") {
297487
298253
  draft.tools.webSearch.enabled = patch.webSearchEnabled;
297488
298254
  }
@@ -297541,6 +298307,10 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
297541
298307
  this.tui.setPermissionsMode(patch.permissionMode);
297542
298308
  this.saveLocalState({ permissionMode: patch.permissionMode });
297543
298309
  }
298310
+ if (typeof patch.agentMaxIterations === "number") {
298311
+ this.config.agent.maxIterations = patch.agentMaxIterations;
298312
+ this.saveLocalState({ agentMaxIterations: patch.agentMaxIterations });
298313
+ }
297544
298314
  if (typeof patch.webSearchEnabled === "boolean") {
297545
298315
  this.config.tools.webSearch.enabled = patch.webSearchEnabled;
297546
298316
  }
@@ -297812,6 +298582,7 @@ var LocalRuntimeStateSchema = z68.object({
297812
298582
  lastModel: z68.string().max(512).optional(),
297813
298583
  language: OrbitLanguageSchema.optional(),
297814
298584
  permissionMode: z68.enum(["strict", "normal", "auto", "plan"]).optional(),
298585
+ agentMaxIterations: z68.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
297815
298586
  skills: LocalSkillsStateSchema.optional()
297816
298587
  });
297817
298588
  function readLocalRuntimeState(cwd) {
@@ -298102,8 +298873,9 @@ Risk Warning: ${reason}`);
298102
298873
  {
298103
298874
  disableStatusBar: useFullscreenTui,
298104
298875
  sessionId: resumeSessionId,
298105
- // Permission elevation never opts the user out of periodic cost guards.
298106
- autoContinueRunaway: false
298876
+ // Full Access is an explicit request for uninterrupted autonomous work.
298877
+ // Budget, cancellation, progress, and the configured hard ceiling remain.
298878
+ autoContinueRunaway: isFullAccessEnabled(this.config)
298107
298879
  }
298108
298880
  );
298109
298881
  tui.setActiveInputHandler((submitted) => {
@@ -298587,6 +299359,13 @@ function shouldUseStoredPermissionMode(cliOverrides) {
298587
299359
  const permissions = cliOverrides.permissions;
298588
299360
  return !(typeof permissions === "object" && permissions !== null && !Array.isArray(permissions) && typeof permissions.mode === "string");
298589
299361
  }
299362
+ function shouldUseStoredAgentMaxIterations(cliOverrides) {
299363
+ if (typeof cliOverrides !== "object" || cliOverrides === null || Array.isArray(cliOverrides)) {
299364
+ return true;
299365
+ }
299366
+ const agent = cliOverrides.agent;
299367
+ return !(typeof agent === "object" && agent !== null && !Array.isArray(agent) && typeof agent.maxIterations === "number");
299368
+ }
298590
299369
  function getExplicitModelOverride(cliOverrides) {
298591
299370
  if (typeof cliOverrides !== "object" || cliOverrides === null || Array.isArray(cliOverrides)) {
298592
299371
  return void 0;
@@ -298624,9 +299403,15 @@ function applyStoredRuntimeSelection(config, localState, cliOverrides) {
298624
299403
  if (shouldUseStoredPermissionMode(cliOverrides) && localState.permissionMode) {
298625
299404
  applyPermissionModePreset(config, localState.permissionMode);
298626
299405
  }
299406
+ if (shouldUseStoredAgentMaxIterations(cliOverrides) && localState.agentMaxIterations) {
299407
+ config.agent.maxIterations = Math.min(
299408
+ localState.agentMaxIterations,
299409
+ config.managedPolicy?.maxIterations ?? MAX_AGENT_MAX_ITERATIONS
299410
+ );
299411
+ }
298627
299412
  }
298628
- function shouldAutoContinueRunaway(options) {
298629
- return options?.autoContinueRunaway === true;
299413
+ function shouldAutoContinueRunaway(config, options) {
299414
+ return isFullAccessEnabled(config) || options?.autoContinueRunaway === true;
298630
299415
  }
298631
299416
  async function runAgent(cwd, task, cliOverrides, multi, options) {
298632
299417
  const cleanupJsonl = options?.jsonl ? configureJsonlOutput() : () => {
@@ -298762,7 +299547,7 @@ Risk Warning: ${reason}`);
298762
299547
  requireSession: Boolean(options?.resumeSessionId),
298763
299548
  disableStatusBar: !!options?.nonInteractive || !!options?.jsonl,
298764
299549
  nonInteractive: !!options?.nonInteractive,
298765
- autoContinueRunaway: shouldAutoContinueRunaway(options)
299550
+ autoContinueRunaway: shouldAutoContinueRunaway(config, options)
298766
299551
  }
298767
299552
  );
298768
299553
  return await loop.run();
@@ -299574,10 +300359,36 @@ async function runMcpLogin(serverName, options = {}) {
299574
300359
 
299575
300360
  // src/commands/skills.ts
299576
300361
  import picocolors24 from "picocolors";
300362
+ import { z as z71 } from "zod";
300363
+ var SkillDirectoryOverrideSchema = z71.array(z71.string().trim().min(1).max(4096)).min(1).max(50);
299577
300364
  async function runSkillsCommand(action, options = {}) {
299578
300365
  const cwd = options.cwd ?? process.cwd();
299579
300366
  const config = ConfigLoader.loadSync(cwd);
299580
- if (config.skills.enabled === false) {
300367
+ const directoryOverride = options.directories ? SkillDirectoryOverrideSchema.safeParse(options.directories) : void 0;
300368
+ if (directoryOverride && !directoryOverride.success) {
300369
+ const message2 = directoryOverride.error.issues.map((issue) => issue.message).join("; ");
300370
+ if (options.json) {
300371
+ console.log(
300372
+ JSON.stringify({
300373
+ enabled: true,
300374
+ skills: [],
300375
+ diagnostics: [
300376
+ {
300377
+ path: cwd,
300378
+ severity: "error",
300379
+ code: "invalid-directory-override",
300380
+ message: message2
300381
+ }
300382
+ ]
300383
+ })
300384
+ );
300385
+ } else {
300386
+ console.error(picocolors24.red(`\u2716 Invalid Skill directory: ${message2}`));
300387
+ }
300388
+ return 1;
300389
+ }
300390
+ const targeted = Boolean(directoryOverride?.success);
300391
+ if (config.skills.enabled === false && !targeted) {
299581
300392
  if (options.json) {
299582
300393
  console.log(
299583
300394
  JSON.stringify({ enabled: false, skills: [], diagnostics: [] })
@@ -299587,7 +300398,12 @@ async function runSkillsCommand(action, options = {}) {
299587
300398
  }
299588
300399
  return 0;
299589
300400
  }
299590
- const catalog = await discoverSkills(cwd, config.skills);
300401
+ const skillConfig = targeted ? {
300402
+ ...config.skills,
300403
+ enabled: true,
300404
+ directories: directoryOverride.data
300405
+ } : config.skills;
300406
+ const catalog = await discoverSkills(cwd, skillConfig);
299591
300407
  if (options.deep) {
299592
300408
  catalog.diagnostics.push(
299593
300409
  ...await validateSkillCatalogBundles(catalog.skills)
@@ -299602,6 +300418,7 @@ async function runSkillsCommand(action, options = {}) {
299602
300418
  {
299603
300419
  enabled: true,
299604
300420
  deep: options.deep === true,
300421
+ targeted,
299605
300422
  directories: catalog.directories,
299606
300423
  skills: catalog.skills.map((skill) => ({
299607
300424
  name: skill.name,
@@ -299670,10 +300487,10 @@ import {
299670
300487
  } from "fs";
299671
300488
  import { dirname as dirname15, resolve as resolve15 } from "path";
299672
300489
  import { randomUUID as randomUUID14 } from "crypto";
299673
- import { z as z71 } from "zod";
299674
- var TraceOptionsSchema = z71.object({
299675
- full: z71.boolean().default(false),
299676
- out: z71.string().trim().min(1).max(4096).optional()
300490
+ import { z as z74 } from "zod";
300491
+ var TraceOptionsSchema = z74.object({
300492
+ full: z74.boolean().default(false),
300493
+ out: z74.string().trim().min(1).max(4096).optional()
299677
300494
  });
299678
300495
  function runTraceExport(cwd, sessionId, options = {}) {
299679
300496
  const value = TraceOptionsSchema.parse(options);
@@ -299728,16 +300545,16 @@ import { randomUUID as randomUUID15 } from "crypto";
299728
300545
  import { promisify as promisify5 } from "util";
299729
300546
  import picocolors25 from "picocolors";
299730
300547
  import { parse as parseYaml4 } from "yaml";
299731
- import { z as z74 } from "zod";
300548
+ import { z as z75 } from "zod";
299732
300549
  var exec5 = promisify5(execCallback);
299733
300550
  var MAX_SUITE_BYTES = 1024 * 1024;
299734
300551
  var MAX_VERIFICATION_OUTPUT = 4e3;
299735
- var EvalOptionsSchema = z74.object({
299736
- provider: z74.string().trim().min(1).optional(),
299737
- model: z74.string().trim().min(1).optional(),
299738
- task: z74.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
299739
- allowCommands: z74.boolean().default(false),
299740
- json: z74.boolean().default(false)
300552
+ var EvalOptionsSchema = z75.object({
300553
+ provider: z75.string().trim().min(1).optional(),
300554
+ model: z75.string().trim().min(1).optional(),
300555
+ task: z75.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
300556
+ allowCommands: z75.boolean().default(false),
300557
+ json: z75.boolean().default(false)
299741
300558
  });
299742
300559
  async function runEval(cwd, suiteFile, options = {}) {
299743
300560
  const value = EvalOptionsSchema.parse(options);
@@ -299769,6 +300586,9 @@ async function runEval(cwd, suiteFile, options = {}) {
299769
300586
  `eval-${task.id}`.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 60)
299770
300587
  );
299771
300588
  snapshotWorkspaceIntoWorktree(cwd, worktree.path);
300589
+ if (value.allowCommands) {
300590
+ writeAcceptanceVerificationContract(worktree.path, task);
300591
+ }
299772
300592
  const outcome = await runAgent(
299773
300593
  worktree.path,
299774
300594
  task.prompt,
@@ -299781,6 +300601,12 @@ async function runEval(cwd, suiteFile, options = {}) {
299781
300601
  requireApprovalForWrite: false,
299782
300602
  requireApprovalForBash: !value.allowCommands
299783
300603
  },
300604
+ security: {
300605
+ ...DEFAULT_CONFIG.security,
300606
+ // The suite commands were explicitly reviewed and authorized by
300607
+ // --allow-commands, and execute only in this disposable worktree.
300608
+ trustProjectExecutables: value.allowCommands
300609
+ },
299784
300610
  agent: {
299785
300611
  ...DEFAULT_CONFIG.agent,
299786
300612
  // Acceptance tasks commonly include implementation plus their
@@ -299908,6 +300734,22 @@ function loadAcceptanceSuite(cwd, suiteFile) {
299908
300734
  const raw = filePath.endsWith(".json") ? JSON.parse(text2) : parseYaml4(text2);
299909
300735
  return AcceptanceSuiteSchema.parse(raw);
299910
300736
  }
300737
+ function writeAcceptanceVerificationContract(cwd, task) {
300738
+ if (task.verification.length === 0) return void 0;
300739
+ const suites = Object.fromEntries(
300740
+ task.verification.map((check, index) => [
300741
+ `${String(index + 1).padStart(2, "0")}-${check.name}`,
300742
+ check.command
300743
+ ])
300744
+ );
300745
+ const contract = VerificationContractSchema.parse({
300746
+ suites,
300747
+ maxRepairAttempts: 3
300748
+ });
300749
+ const filePath = resolveSafePath(cwd, join19(".orbit", "verification.json"));
300750
+ writeJsonAtomically2(filePath, contract);
300751
+ return filePath;
300752
+ }
299911
300753
  async function runVerificationChecks(cwd, checks) {
299912
300754
  const results = [];
299913
300755
  for (const check of checks) {
@@ -300085,7 +300927,7 @@ function safeSummary(value) {
300085
300927
  import readline6 from "readline";
300086
300928
  import picocolors26 from "picocolors";
300087
300929
  import { resolve as resolve17 } from "path";
300088
- import { z as z76 } from "zod";
300930
+ import { z as z77 } from "zod";
300089
300931
 
300090
300932
  // src/runtime/CleanupManager.ts
300091
300933
  import {
@@ -300097,10 +300939,10 @@ import {
300097
300939
  } from "fs";
300098
300940
  import { homedir as homedir11 } from "os";
300099
300941
  import { basename as basename6, join as join20, parse as parse5, resolve as resolve16 } from "path";
300100
- import { z as z75 } from "zod";
300101
- var CleanupScopeSchema = z75.enum(["user", "project"]);
300942
+ import { z as z76 } from "zod";
300943
+ var CleanupScopeSchema = z76.enum(["user", "project"]);
300102
300944
  function buildCleanupPlan(options) {
300103
- const scopes = z75.array(CleanupScopeSchema).min(1).parse(options.scopes);
300945
+ const scopes = z76.array(CleanupScopeSchema).min(1).parse(options.scopes);
300104
300946
  const homeDirectory = resolve16(options.homeDirectory ?? homedir11());
300105
300947
  const projectDirectory = resolve16(options.projectDirectory ?? options.cwd);
300106
300948
  const candidates = scopes.map((scope) => ({
@@ -300258,12 +301100,12 @@ function safeInventoryWarning(targetPath, error) {
300258
301100
  }
300259
301101
 
300260
301102
  // src/commands/clean.ts
300261
- var CleanCommandOptionsSchema = z76.object({
300262
- user: z76.boolean().default(false),
300263
- project: z76.union([z76.boolean(), z76.string().min(1).max(4096)]).optional(),
300264
- all: z76.boolean().default(false),
300265
- yes: z76.boolean().default(false),
300266
- json: z76.boolean().default(false)
301103
+ var CleanCommandOptionsSchema = z77.object({
301104
+ user: z77.boolean().default(false),
301105
+ project: z77.union([z77.boolean(), z77.string().min(1).max(4096)]).optional(),
301106
+ all: z77.boolean().default(false),
301107
+ yes: z77.boolean().default(false),
301108
+ json: z77.boolean().default(false)
300267
301109
  }).strict();
300268
301110
  async function runClean(cwd, rawOptions, dependencies = {}) {
300269
301111
  const options = CleanCommandOptionsSchema.parse(rawOptions);
@@ -300378,7 +301220,7 @@ async function confirmDeletion(prompt) {
300378
301220
  // src/commands/backup.ts
300379
301221
  import { basename as basename7, resolve as resolve19 } from "path";
300380
301222
  import picocolors27 from "picocolors";
300381
- import { z as z78 } from "zod";
301223
+ import { z as z79 } from "zod";
300382
301224
 
300383
301225
  // src/runtime/ProjectBackup.ts
300384
301226
  import {
@@ -300392,25 +301234,25 @@ import {
300392
301234
  } from "fs";
300393
301235
  import { createHash as createHash10, randomUUID as randomUUID16 } from "crypto";
300394
301236
  import { dirname as dirname17, isAbsolute as isAbsolute9, join as join21, relative as relative10, resolve as resolve18, sep as sep2 } from "path";
300395
- import { z as z77 } from "zod";
301237
+ import { z as z78 } from "zod";
300396
301238
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
300397
301239
  var MAX_SERIALIZED_BACKUP_BYTES = 96 * 1024 * 1024;
300398
301240
  var MAX_BACKUP_FILES = 1e4;
300399
301241
  var MAX_BACKUP_TREE_ENTRIES = 5e4;
300400
301242
  var MAX_BACKUP_TREE_DEPTH = 64;
300401
301243
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
300402
- var BackupFileSchema = z77.object({
300403
- path: z77.string().min(1).max(4096),
300404
- size: z77.number().int().min(0).max(MAX_BACKUP_BYTES),
300405
- sha256: z77.string().regex(SHA256_PATTERN),
300406
- content: z77.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
301244
+ var BackupFileSchema = z78.object({
301245
+ path: z78.string().min(1).max(4096),
301246
+ size: z78.number().int().min(0).max(MAX_BACKUP_BYTES),
301247
+ sha256: z78.string().regex(SHA256_PATTERN),
301248
+ content: z78.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
300407
301249
  });
300408
- var ProjectBackupBundleSchema = z77.object({
300409
- schemaVersion: z77.literal(1),
300410
- kind: z77.literal("orbit-project-backup"),
300411
- createdAt: z77.string().datetime(),
300412
- sourceName: z77.string().min(1).max(512),
300413
- files: z77.array(BackupFileSchema).max(MAX_BACKUP_FILES)
301250
+ var ProjectBackupBundleSchema = z78.object({
301251
+ schemaVersion: z78.literal(1),
301252
+ kind: z78.literal("orbit-project-backup"),
301253
+ createdAt: z78.string().datetime(),
301254
+ sourceName: z78.string().min(1).max(512),
301255
+ files: z78.array(BackupFileSchema).max(MAX_BACKUP_FILES)
300414
301256
  }).superRefine((bundle, context) => {
300415
301257
  let totalBytes = 0;
300416
301258
  const seen = /* @__PURE__ */ new Set();
@@ -300418,7 +301260,7 @@ var ProjectBackupBundleSchema = z77.object({
300418
301260
  totalBytes += file.size;
300419
301261
  if (totalBytes > MAX_BACKUP_BYTES) {
300420
301262
  context.addIssue({
300421
- code: z77.ZodIssueCode.custom,
301263
+ code: z78.ZodIssueCode.custom,
300422
301264
  message: `Backup exceeds ${MAX_BACKUP_BYTES} bytes.`
300423
301265
  });
300424
301266
  break;
@@ -300426,14 +301268,14 @@ var ProjectBackupBundleSchema = z77.object({
300426
301268
  const normalized = normalizeBundlePath(file.path);
300427
301269
  if (!normalized || normalized !== file.path) {
300428
301270
  context.addIssue({
300429
- code: z77.ZodIssueCode.custom,
301271
+ code: z78.ZodIssueCode.custom,
300430
301272
  message: `Unsafe backup path: ${file.path}`
300431
301273
  });
300432
301274
  continue;
300433
301275
  }
300434
301276
  if (seen.has(normalized.toLowerCase())) {
300435
301277
  context.addIssue({
300436
- code: z77.ZodIssueCode.custom,
301278
+ code: z78.ZodIssueCode.custom,
300437
301279
  message: `Duplicate backup path: ${file.path}`
300438
301280
  });
300439
301281
  }
@@ -300666,9 +301508,9 @@ function formatBytes2(bytes) {
300666
301508
  }
300667
301509
 
300668
301510
  // src/commands/backup.ts
300669
- var BackupOptionsSchema = z78.object({
300670
- output: z78.string().min(1).max(4096).optional(),
300671
- json: z78.boolean().default(false)
301511
+ var BackupOptionsSchema = z79.object({
301512
+ output: z79.string().min(1).max(4096).optional(),
301513
+ json: z79.boolean().default(false)
300672
301514
  }).strict();
300673
301515
  function runBackupCreate(cwd, rawOptions = {}) {
300674
301516
  const options = BackupOptionsSchema.parse(rawOptions);
@@ -300768,21 +301610,21 @@ import {
300768
301610
  import { randomUUID as randomUUID17 } from "crypto";
300769
301611
  import { dirname as dirname18, isAbsolute as isAbsolute10, join as join26, relative as relative11, resolve as resolve20, sep as sep3 } from "path";
300770
301612
  import { homedir as homedir12 } from "os";
300771
- import { z as z79 } from "zod";
300772
- var InstalledExtensionSchema2 = z79.object({
301613
+ import { z as z80 } from "zod";
301614
+ var InstalledExtensionSchema2 = z80.object({
300773
301615
  id: InstalledExtensionIdSchema,
300774
- displayName: z79.string().min(1).max(256),
300775
- version: z79.string().min(1).max(128),
300776
- digest: z79.string().regex(/^[a-f0-9]{64}$/),
301616
+ displayName: z80.string().min(1).max(256),
301617
+ version: z80.string().min(1).max(128),
301618
+ digest: z80.string().regex(/^[a-f0-9]{64}$/),
300777
301619
  digestAlgorithm: ExtensionDigestAlgorithmSchema.default("sha256-v1"),
300778
- installedAt: z79.string().datetime(),
300779
- trusted: z79.boolean(),
300780
- path: z79.string().min(1).max(4096),
300781
- manifestFile: z79.string().min(1).max(4096).default("extension.yaml")
301620
+ installedAt: z80.string().datetime(),
301621
+ trusted: z80.boolean(),
301622
+ path: z80.string().min(1).max(4096),
301623
+ manifestFile: z80.string().min(1).max(4096).default("extension.yaml")
300782
301624
  });
300783
- var ExtensionRegistrySchema2 = z79.object({
300784
- schemaVersion: z79.literal(1),
300785
- extensions: z79.array(InstalledExtensionSchema2).max(500).default([])
301625
+ var ExtensionRegistrySchema2 = z80.object({
301626
+ schemaVersion: z80.literal(1),
301627
+ extensions: z80.array(InstalledExtensionSchema2).max(500).default([])
300786
301628
  });
300787
301629
  var ExtensionManager = class {
300788
301630
  orbitDir;
@@ -301340,14 +302182,20 @@ skillsCommand.command("list").description("list discovered skills with their dia
301340
302182
  process.exitCode = await runSkillsCommand("list", { json: !!options.json });
301341
302183
  });
301342
302184
  skillsCommand.command("validate").description("validate SKILL.md files; non-zero exit on errors (CI-friendly)").option("--json", "print a machine-readable report").option(
302185
+ "-d, --directory <paths...>",
302186
+ "validate only the specified Skill source directories"
302187
+ ).option(
301343
302188
  "--deep",
301344
302189
  "validate bundled references, assets, and filesystem safety"
301345
- ).action(async (options) => {
301346
- process.exitCode = await runSkillsCommand("validate", {
301347
- json: !!options.json,
301348
- deep: !!options.deep
301349
- });
301350
- });
302190
+ ).action(
302191
+ async (options) => {
302192
+ process.exitCode = await runSkillsCommand("validate", {
302193
+ json: !!options.json,
302194
+ deep: !!options.deep,
302195
+ directories: options.directory
302196
+ });
302197
+ }
302198
+ );
301351
302199
  var mcpCommand = program.command("mcp").description("manage Model Context Protocol servers");
301352
302200
  mcpCommand.command("login <server>").description("authorize an MCP server via OAuth (PKCE) and save the login").option("--port <port>", "fixed loopback port for the OAuth redirect").action(async (server2, options) => {
301353
302201
  const port = options.port ? Number.parseInt(options.port, 10) : void 0;