@orbit-build/cli 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -239240,6 +239240,37 @@ function localizeOrbit(language, english, simplifiedChinese, traditionalChinese)
239240
239240
  var ORBIT_CONFIG_SCHEMA_VERSION = 1;
239241
239241
  var DEFAULT_AGENT_MAX_ITERATIONS = 200;
239242
239242
  var MAX_AGENT_MAX_ITERATIONS = 1e3;
239243
+ var ORBIT_LIFECYCLE_HOOK_EVENTS = [
239244
+ "sessionStart",
239245
+ "promptSubmit",
239246
+ "permissionRequest",
239247
+ "preToolUse",
239248
+ "postToolUse",
239249
+ "postToolFailure",
239250
+ "preCompact",
239251
+ "postCompact",
239252
+ "verificationStart",
239253
+ "verificationEnd",
239254
+ "subagentStart",
239255
+ "subagentStop",
239256
+ "stop"
239257
+ ];
239258
+ var LifecycleHookEventSchema = z22.enum(ORBIT_LIFECYCLE_HOOK_EVENTS);
239259
+ var LifecycleHookCommandSchema = z22.object({
239260
+ command: z22.string().trim().min(1).max(2e4),
239261
+ /** Safe glob matched against the tool name, agent role, or lifecycle subject. */
239262
+ matcher: z22.string().trim().min(1).max(256).optional(),
239263
+ timeoutMs: z22.number().int().min(100).max(6e5).default(3e4),
239264
+ onFailure: z22.enum(["block", "warn", "ignore"]).default("warn")
239265
+ });
239266
+ var LifecycleHooksSchema = z22.object(
239267
+ Object.fromEntries(
239268
+ ORBIT_LIFECYCLE_HOOK_EVENTS.map((event) => [
239269
+ event,
239270
+ z22.array(LifecycleHookCommandSchema).max(16).optional()
239271
+ ])
239272
+ )
239273
+ ).strict();
239243
239274
  var EnvironmentVariableNameSchema = z22.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/);
239244
239275
  var HttpHeaderNameSchema = z22.string().max(256).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/);
239245
239276
  var HttpHeaderValueSchema = z22.string().max(16384).refine((value) => !/[\r\n]/.test(value));
@@ -239599,9 +239630,12 @@ var ConfigSchema = z22.object({
239599
239630
  maxIterations: z22.number().int().positive().max(MAX_AGENT_MAX_ITERATIONS).optional()
239600
239631
  }).optional(),
239601
239632
  hooks: z22.object({
239633
+ /** @deprecated Use lifecycle.preToolUse with a write-tool matcher. */
239602
239634
  preEdit: z22.string().max(2e4).optional(),
239603
- postEdit: z22.string().max(2e4).optional()
239604
- }).default({}),
239635
+ /** @deprecated Use lifecycle.postToolUse with a write-tool matcher. */
239636
+ postEdit: z22.string().max(2e4).optional(),
239637
+ lifecycle: LifecycleHooksSchema.optional()
239638
+ }).strict().default({}),
239605
239639
  pricing: PricingTableSchema.default({}),
239606
239640
  budgetLimit: z22.number().finite().nonnegative().default(10),
239607
239641
  session: z22.object({
@@ -242963,7 +242997,6 @@ async function fetchWithRetry(url, init, maxRetries = 3) {
242963
242997
  const timeoutId = setTimeout(() => {
242964
242998
  controller.abort();
242965
242999
  }, timeoutMs);
242966
- timeoutId.unref?.();
242967
243000
  try {
242968
243001
  const response = await fetch(url, {
242969
243002
  ...init,
@@ -243036,6 +243069,33 @@ function sanitizeProviderError(value, secrets = [], fallbackMessage = "Unknown p
243036
243069
  error.name = source.name;
243037
243070
  return error;
243038
243071
  }
243072
+ function normalizeProviderStreamError(value, secrets = [], partialOutput = false) {
243073
+ const source = sanitizeProviderError(value, secrets);
243074
+ if (source.name === "AbortError") return source;
243075
+ if (source instanceof ProviderError) {
243076
+ return new ProviderError(source.code, source.message, {
243077
+ status: source.status,
243078
+ retryAfterMs: source.retryAfterMs,
243079
+ requestId: source.requestId,
243080
+ retryable: source.retryable,
243081
+ partialOutput,
243082
+ cause: source.cause
243083
+ });
243084
+ }
243085
+ const timeout = source.name === "TimeoutError" || /(?:timed?\s*out|timeout)/i.test(source.message);
243086
+ 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(
243087
+ source.message
243088
+ );
243089
+ return new ProviderError(
243090
+ timeout ? "TIMEOUT" : closed ? "STREAM_CLOSED" : "MALFORMED_RESPONSE",
243091
+ source.message,
243092
+ {
243093
+ retryable: timeout || closed,
243094
+ partialOutput,
243095
+ cause: source
243096
+ }
243097
+ );
243098
+ }
243039
243099
  function providerHttpError(provider, status, responseBody, secrets = [], metadata = {}) {
243040
243100
  const detail = sanitizeProviderErrorText(responseBody, secrets);
243041
243101
  const normalized = detail.toLowerCase();
@@ -243084,7 +243144,6 @@ function abortableDelay(delayMs, signal) {
243084
243144
  cleanup();
243085
243145
  resolve26();
243086
243146
  }, delayMs);
243087
- timeoutId.unref?.();
243088
243147
  function onAbort() {
243089
243148
  clearTimeout(timeoutId);
243090
243149
  cleanup();
@@ -243736,9 +243795,14 @@ var AnthropicCompatibleProvider = class {
243736
243795
  this.options.maxRetries ?? (this.isOfficialDeepSeekEndpoint() ? 0 : 2)
243737
243796
  );
243738
243797
  } catch (error) {
243798
+ const sanitized = sanitizeProviderError(error, [key]);
243739
243799
  yield {
243740
243800
  type: "error",
243741
- error: sanitizeProviderError(error, [key])
243801
+ error: isProviderError(sanitized) ? sanitized : new ProviderError(
243802
+ sanitized.name === "TimeoutError" ? "TIMEOUT" : "TRANSPORT",
243803
+ sanitized.message,
243804
+ { retryable: true, cause: sanitized }
243805
+ )
243742
243806
  };
243743
243807
  return;
243744
243808
  }
@@ -244073,9 +244137,14 @@ var AnthropicCompatibleProvider = class {
244073
244137
  yield { type: "done" };
244074
244138
  }
244075
244139
  } catch (error) {
244140
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244076
244141
  yield {
244077
244142
  type: "error",
244078
- error: sanitizeProviderError(error, [key])
244143
+ error: normalizeProviderStreamError(
244144
+ abortReason ?? error,
244145
+ [key],
244146
+ emittedToolCalls > 0
244147
+ )
244079
244148
  };
244080
244149
  } finally {
244081
244150
  if (streamTimeoutId) clearTimeout(streamTimeoutId);
@@ -244500,7 +244569,6 @@ async function* parseStreamingResponse(input, options, response, controller) {
244500
244569
  )
244501
244570
  );
244502
244571
  }, streamTimeoutMs);
244503
- timeoutId.unref?.();
244504
244572
  };
244505
244573
  const outputKey = (outputIndex, itemId) => {
244506
244574
  const aliased = itemId ? outputAliases.get(itemId) : void 0;
@@ -244736,25 +244804,11 @@ async function* parseStreamingResponse(input, options, response, controller) {
244736
244804
  );
244737
244805
  }
244738
244806
  } catch (error) {
244739
- const source = toError(error);
244740
- if (source instanceof ProviderError) {
244741
- throw new ProviderError(source.code, source.message, {
244742
- status: source.status,
244743
- retryAfterMs: source.retryAfterMs,
244744
- requestId: source.requestId,
244745
- retryable: source.retryable,
244746
- partialOutput: emittedOutput || tools.size > 0,
244747
- cause: source.cause
244748
- });
244749
- }
244750
- throw new ProviderError(
244751
- source.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
244752
- source.message,
244753
- {
244754
- retryable: source.name === "TimeoutError",
244755
- partialOutput: emittedOutput || tools.size > 0,
244756
- cause: source
244757
- }
244807
+ const abortReason = controller.signal.aborted ? controller.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244808
+ throw normalizeProviderStreamError(
244809
+ abortReason ?? error,
244810
+ [options.apiKey],
244811
+ emittedOutput || tools.size > 0
244758
244812
  );
244759
244813
  } finally {
244760
244814
  if (timeoutId) clearTimeout(timeoutId);
@@ -245876,22 +245930,11 @@ ${jsonInstruction}`;
245876
245930
  yield { type: "done" };
245877
245931
  }
245878
245932
  } catch (error) {
245879
- const sanitized = sanitizeProviderError(error, [key]);
245880
- const streamError = isProviderError(sanitized) ? new ProviderError(sanitized.code, sanitized.message, {
245881
- status: sanitized.status,
245882
- retryAfterMs: sanitized.retryAfterMs,
245883
- requestId: sanitized.requestId,
245884
- retryable: sanitized.retryable,
245885
- partialOutput: emittedOutput || streamingTools.size > 0,
245886
- cause: sanitized.cause
245887
- }) : new ProviderError(
245888
- sanitized.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
245889
- sanitized.message,
245890
- {
245891
- retryable: sanitized.name === "TimeoutError",
245892
- partialOutput: emittedOutput || streamingTools.size > 0,
245893
- cause: sanitized
245894
- }
245933
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
245934
+ const streamError = normalizeProviderStreamError(
245935
+ abortReason ?? error,
245936
+ [key],
245937
+ emittedOutput || streamingTools.size > 0
245895
245938
  );
245896
245939
  yield {
245897
245940
  type: "error",
@@ -249646,7 +249689,7 @@ var BashInputSchema = z17.object({
249646
249689
  });
249647
249690
  var BashTool = class {
249648
249691
  name = "bash";
249649
- 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. 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. Set background=true only for dev servers, watchers, or long builds.";
249692
+ 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.";
249650
249693
  inputSchema = BashInputSchema;
249651
249694
  risk = "execute";
249652
249695
  async execute(input, ctx) {
@@ -250988,7 +251031,6 @@ var WebSearchTool = class {
250988
251031
  const controller = new AbortController();
250989
251032
  const abort = () => controller.abort();
250990
251033
  const timeoutId = setTimeout(abort, timeoutMs);
250991
- timeoutId.unref?.();
250992
251034
  if (parentSignal) {
250993
251035
  if (parentSignal.aborted) {
250994
251036
  controller.abort();
@@ -251746,7 +251788,6 @@ async function waitWithTimeout(promise, timeoutMs, abortSignal) {
251746
251788
  promise.then(() => true),
251747
251789
  new Promise((resolve43) => {
251748
251790
  timeout = setTimeout(() => resolve43(false), timeoutMs);
251749
- timeout.unref?.();
251750
251791
  }),
251751
251792
  new Promise((resolve43) => {
251752
251793
  if (!abortSignal) return;
@@ -253934,6 +253975,28 @@ var CODEBASE_FORCE_MARKER_ALL = /@codebase\b/gi;
253934
253975
  var CODEBASE_DISABLE_MARKER_ALL = /@no-codebase\b/gi;
253935
253976
  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;
253936
253977
  var SOURCE_REFERENCE = /(?:^|[\s`'"(])[^\s`'"()]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyw)(?=$|[\s`'"),:])/i;
253978
+ var CODEBASE_CONTEXT_BUDGETS = {
253979
+ automatic: {
253980
+ queryTokens: 256,
253981
+ searchTokens: 3072,
253982
+ referenceTokens: 1024,
253983
+ repoMapTokens: 512,
253984
+ totalTokens: 6144,
253985
+ resultLimit: 4,
253986
+ referencesPerSymbol: 2,
253987
+ totalReferences: 6
253988
+ },
253989
+ explicit: {
253990
+ queryTokens: 512,
253991
+ searchTokens: 8192,
253992
+ referenceTokens: 4096,
253993
+ repoMapTokens: 2048,
253994
+ totalTokens: 16384,
253995
+ resultLimit: 8,
253996
+ referencesPerSymbol: 3,
253997
+ totalReferences: 12
253998
+ }
253999
+ };
253937
254000
  function selectCodebaseRetrievalMode(userQuery, autoEnabled) {
253938
254001
  if (!userQuery || CODEBASE_DISABLE_MARKER.test(userQuery)) return "off";
253939
254002
  if (CODEBASE_FORCE_MARKER.test(userQuery)) {
@@ -253955,9 +254018,13 @@ var CodebaseContextRetriever = class {
253955
254018
  cwd;
253956
254019
  retrieval;
253957
254020
  async retrieve(userQuery, config, mode) {
254021
+ const budget = CODEBASE_CONTEXT_BUDGETS[mode];
253958
254022
  const cleanQuery = cleanCodebaseQuery(userQuery);
253959
- const searchQuery = cleanQuery || "repository architecture and entrypoints";
253960
- const prepared = await this.retrieval.prepare(2048);
254023
+ const searchQuery = truncateTextToTokenBudget(
254024
+ cleanQuery || "repository architecture and entrypoints",
254025
+ budget.queryTokens
254026
+ );
254027
+ const prepared = await this.retrieval.prepare(budget.repoMapTokens);
253961
254028
  let chunksText = "";
253962
254029
  let referencesText = "";
253963
254030
  try {
@@ -253973,14 +254040,17 @@ var CodebaseContextRetriever = class {
253973
254040
  return provider.embed(texts, { model: modelName });
253974
254041
  };
253975
254042
  const results = await prepared.search.search(searchQuery, embedFn, {
253976
- limit: 5
254043
+ limit: budget.resultLimit
253977
254044
  });
253978
254045
  if (results.length > 0) {
253979
- chunksText = results.map(
253980
- (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
254046
+ chunksText = truncateTextToTokenBudget(
254047
+ results.map(
254048
+ (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
253981
254049
  ${result.text}
253982
254050
  `
253983
- ).join("\n");
254051
+ ).join("\n"),
254052
+ budget.searchTokens
254053
+ );
253984
254054
  const referencedSymbols = Array.from(
253985
254055
  new Set(
253986
254056
  results.map((result) => result.metadata.symbolName).filter((name) => Boolean(name))
@@ -253989,7 +254059,15 @@ ${result.text}
253989
254059
  if (referencedSymbols.length > 0) {
253990
254060
  referencesText = await new ReferencesRetriever(
253991
254061
  this.cwd
253992
- ).getReferencesContext(referencedSymbols);
254062
+ ).getReferencesContext(
254063
+ referencedSymbols,
254064
+ budget.referencesPerSymbol,
254065
+ budget.totalReferences
254066
+ );
254067
+ referencesText = truncateTextToTokenBudget(
254068
+ referencesText,
254069
+ budget.referenceTokens
254070
+ );
253993
254071
  }
253994
254072
  } else {
253995
254073
  chunksText = "(No relevant code matches found in search index.)\n";
@@ -254001,13 +254079,18 @@ ${result.text}
254001
254079
  chunksText = `(RAG retrieval failed: ${message2})
254002
254080
  `;
254003
254081
  }
254004
- return `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
254082
+ const repoMap = truncateTextToTokenBudget(
254083
+ prepared.repoMap || "(No landmarks mapped.)",
254084
+ budget.repoMapTokens
254085
+ );
254086
+ const context = `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
254005
254087
  Use the following repository evidence when it is relevant; verify files before editing.
254006
254088
 
254007
254089
  ${chunksText}
254008
254090
  ${referencesText}=== Codebase Landmark Repo Map ===
254009
- ${prepared.repoMap || "(No landmarks mapped.)"}
254091
+ ${repoMap}
254010
254092
  ================================================================`;
254093
+ return truncateTextToTokenBudget(context, budget.totalTokens);
254011
254094
  }
254012
254095
  };
254013
254096
  var IGNORED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
@@ -254053,6 +254136,7 @@ var WEAK_TERM_SCORE = 1;
254053
254136
  var NAME_MENTION_SCORE = 8;
254054
254137
  var STRONG_TERM_MIN_LENGTH = 5;
254055
254138
  var MIN_AUTO_SCORE = 3;
254139
+ var MIN_AUTO_MATCHED_TERMS = 2;
254056
254140
  function normalizePath3(path9) {
254057
254141
  return path9.replace(/\\/g, "/");
254058
254142
  }
@@ -254397,13 +254481,18 @@ function selectSkills(skills, userQuery, config) {
254397
254481
  if (!explicit2 && config.activation === "auto" && skill.allowImplicitInvocation) {
254398
254482
  const metadata = normalize2(`${skill.name} ${skill.description}`);
254399
254483
  const metadataTerms = new Set(terms(metadata));
254484
+ let matchedTerms = 0;
254400
254485
  for (const term of queryTerms) {
254401
254486
  if (metadataTerms.has(term)) {
254487
+ matchedTerms += 1;
254402
254488
  score += term.length >= STRONG_TERM_MIN_LENGTH ? STRONG_TERM_SCORE : WEAK_TERM_SCORE;
254403
254489
  }
254404
254490
  }
254405
- if (mentionsName(query, name)) score += NAME_MENTION_SCORE;
254406
- if (score < MIN_AUTO_SCORE) score = 0;
254491
+ const nameMentioned = mentionsName(query, name);
254492
+ if (nameMentioned) score += NAME_MENTION_SCORE;
254493
+ if (score < MIN_AUTO_SCORE || !nameMentioned && matchedTerms < MIN_AUTO_MATCHED_TERMS) {
254494
+ score = 0;
254495
+ }
254407
254496
  }
254408
254497
  return { skill, explicit: explicit2, score };
254409
254498
  }).filter(({ score }) => score > 0).sort(
@@ -254974,7 +255063,7 @@ import { z as z83 } from "zod";
254974
255063
  import picocolors3 from "picocolors";
254975
255064
  import path7 from "path";
254976
255065
  import fs32 from "fs";
254977
- import { randomUUID as randomUUID52 } from "crypto";
255066
+ import { randomUUID as randomUUID62 } from "crypto";
254978
255067
  import { exec as exec2, execFile as execFile3 } from "child_process";
254979
255068
  import { promisify as promisify3 } from "util";
254980
255069
  import { z as z46 } from "zod";
@@ -255359,6 +255448,12 @@ var MCPResponseSchema = z36.object({
255359
255448
  }).refine((message2) => message2.result !== void 0 || message2.error, {
255360
255449
  message: "MCP response requires a result or error."
255361
255450
  });
255451
+ var MCP_CATALOG_KINDS = ["tools", "resources", "prompts"];
255452
+ var MCPNotificationSchema = z36.object({
255453
+ jsonrpc: z36.literal("2.0"),
255454
+ method: z36.string().min(1).max(256),
255455
+ params: z36.record(z36.unknown()).optional()
255456
+ });
255362
255457
  async function collectMcpPaginatedItems(options) {
255363
255458
  try {
255364
255459
  return await collectMcpPaginationAttempt(options);
@@ -255492,6 +255587,8 @@ var MCPClient = class {
255492
255587
  resources: false,
255493
255588
  prompts: false
255494
255589
  };
255590
+ catalogListeners = /* @__PURE__ */ new Set();
255591
+ lastError;
255495
255592
  get effectiveRequestTimeoutMs() {
255496
255593
  return this.requestTimeoutMs ?? MCP_REQUEST_TIMEOUT_MS;
255497
255594
  }
@@ -255512,6 +255609,7 @@ var MCPClient = class {
255512
255609
  this.stdoutBuffer = Buffer.alloc(0);
255513
255610
  this.stderrTail = "";
255514
255611
  this.negotiatedProtocol = void 0;
255612
+ this.lastError = void 0;
255515
255613
  child.on("error", (error) => {
255516
255614
  this.cleanup(
255517
255615
  new Error(
@@ -255598,6 +255696,17 @@ var MCPClient = class {
255598
255696
  getNegotiatedProtocol() {
255599
255697
  return this.negotiatedProtocol ? { ...this.negotiatedProtocol } : void 0;
255600
255698
  }
255699
+ onCatalogChanged(listener) {
255700
+ this.catalogListeners.add(listener);
255701
+ return () => this.catalogListeners.delete(listener);
255702
+ }
255703
+ getRuntimeHealth() {
255704
+ return {
255705
+ connected: this.isConnected,
255706
+ recoveryCount: 0,
255707
+ ...this.lastError ? { lastError: this.lastError } : {}
255708
+ };
255709
+ }
255601
255710
  /** List resources when the server advertises them; empty list otherwise. */
255602
255711
  async listResources(abortSignal) {
255603
255712
  if (!this.serverCapabilities.resources) return [];
@@ -255847,12 +255956,26 @@ var MCPClient = class {
255847
255956
  }
255848
255957
  }
255849
255958
  handleIncomingMessage(line) {
255850
- let response;
255959
+ let raw;
255851
255960
  try {
255852
- response = MCPResponseSchema.parse(JSON.parse(line));
255961
+ raw = JSON.parse(line);
255853
255962
  } catch {
255854
255963
  return;
255855
255964
  }
255965
+ const notification = MCPNotificationSchema.safeParse(raw);
255966
+ if (notification.success && typeof raw === "object" && raw !== null && !("id" in raw)) {
255967
+ const kinds = catalogKindsFromNotification(
255968
+ notification.data.method,
255969
+ notification.data.params
255970
+ );
255971
+ if (kinds.length > 0) {
255972
+ for (const listener of this.catalogListeners) listener(kinds);
255973
+ }
255974
+ return;
255975
+ }
255976
+ const parsed = MCPResponseSchema.safeParse(raw);
255977
+ if (!parsed.success) return;
255978
+ const response = parsed.data;
255856
255979
  const pending = this.pendingRequests.get(response.id);
255857
255980
  if (!pending) return;
255858
255981
  clearTimeout(pending.timeout);
@@ -255872,6 +255995,7 @@ var MCPClient = class {
255872
255995
  }
255873
255996
  cleanup(error) {
255874
255997
  this.isConnected = false;
255998
+ this.lastError = safeMessage(error);
255875
255999
  for (const pending of this.pendingRequests.values()) {
255876
256000
  clearTimeout(pending.timeout);
255877
256001
  pending.removeAbortListener?.();
@@ -255880,6 +256004,24 @@ var MCPClient = class {
255880
256004
  this.pendingRequests.clear();
255881
256005
  }
255882
256006
  };
256007
+ function catalogKindsFromNotification(method, params) {
256008
+ const direct = {
256009
+ "notifications/tools/list_changed": "tools",
256010
+ "notifications/resources/list_changed": "resources",
256011
+ "notifications/prompts/list_changed": "prompts"
256012
+ };
256013
+ if (direct[method]) return [direct[method]];
256014
+ if (method !== "notifications/list_changed" && method !== "notifications/catalog_changed") {
256015
+ return [];
256016
+ }
256017
+ const candidates = [
256018
+ params?.collection,
256019
+ ...Array.isArray(params?.collections) ? params.collections : []
256020
+ ];
256021
+ return [...new Set(candidates)].filter(
256022
+ (value) => typeof value === "string" && MCP_CATALOG_KINDS.includes(value)
256023
+ );
256024
+ }
255883
256025
  function waitForChildExit(child, timeoutMs) {
255884
256026
  if (child.exitCode !== null || child.signalCode !== null) {
255885
256027
  return Promise.resolve(true);
@@ -256081,6 +256223,8 @@ var StreamableHttpMCPClient = class {
256081
256223
  started = false;
256082
256224
  negotiatedProtocol;
256083
256225
  reinitializePromise;
256226
+ recoveryCount = 0;
256227
+ lastError;
256084
256228
  mirroredToolParameters = /* @__PURE__ */ new Map();
256085
256229
  protocolWarnings = [];
256086
256230
  serverCapabilities = {
@@ -256146,6 +256290,13 @@ var StreamableHttpMCPClient = class {
256146
256290
  getProtocolWarnings() {
256147
256291
  return [...this.protocolWarnings];
256148
256292
  }
256293
+ getRuntimeHealth() {
256294
+ return {
256295
+ connected: this.started,
256296
+ recoveryCount: this.recoveryCount,
256297
+ ...this.lastError ? { lastError: this.lastError } : {}
256298
+ };
256299
+ }
256149
256300
  /** List resources when the server advertises them; empty list otherwise. */
256150
256301
  async listResources(abortSignal) {
256151
256302
  if (!this.serverCapabilities.resources) return [];
@@ -256263,6 +256414,8 @@ var StreamableHttpMCPClient = class {
256263
256414
  );
256264
256415
  } catch (error) {
256265
256416
  if (error instanceof McpSessionExpiredError && allowSessionRecovery && this.started && this.negotiatedProtocol?.era === "legacy" && method !== "initialize") {
256417
+ this.recoveryCount += 1;
256418
+ this.lastError = safeMessage2(error);
256266
256419
  await this.reinitialize(abortSignal);
256267
256420
  if ("cursor" in params) {
256268
256421
  throw new McpPaginationSessionResetError(this.serverName);
@@ -256294,6 +256447,7 @@ var StreamableHttpMCPClient = class {
256294
256447
  if (modernVersion && method !== "server/discover") {
256295
256448
  assertCompleteModernResult(parsed.data.result, method);
256296
256449
  }
256450
+ this.lastError = void 0;
256297
256451
  return parsed.data.result;
256298
256452
  }
256299
256453
  async negotiateProtocol(abortSignal) {
@@ -257989,8 +258143,13 @@ var WorktreeManager = class {
257989
258143
  );
257990
258144
  }
257991
258145
  }
258146
+ const baseCommit = this.git(["rev-parse", "HEAD"]).trim();
257992
258147
  this.git(["worktree", "add", "-b", branchName, worktreePath, "HEAD"]);
257993
- const session = { path: worktreePath, branchName };
258148
+ const session = {
258149
+ path: worktreePath,
258150
+ branchName,
258151
+ baseCommit
258152
+ };
257994
258153
  if (options.snapshotWorkingTree) {
257995
258154
  try {
257996
258155
  session.baselineCommit = this.snapshotWorkingTree(worktreePath);
@@ -258020,19 +258179,7 @@ var WorktreeManager = class {
258020
258179
  };
258021
258180
  }
258022
258181
  try {
258023
- this.git(["add", "-A"], session.path);
258024
- if (this.git(["status", "--porcelain"], session.path).trim()) {
258025
- this.git(
258026
- [
258027
- "commit",
258028
- "--no-verify",
258029
- "--no-gpg-sign",
258030
- "-m",
258031
- "subagent automatic worktree commit"
258032
- ],
258033
- session.path
258034
- );
258035
- }
258182
+ this.commitWorktreeChanges(session);
258036
258183
  } catch (error) {
258037
258184
  return {
258038
258185
  success: false,
@@ -258075,6 +258222,97 @@ var WorktreeManager = class {
258075
258222
  }
258076
258223
  return { success: true };
258077
258224
  }
258225
+ /**
258226
+ * Combine independent writer deltas inside another managed worktree. The
258227
+ * main workspace remains untouched until the integration worktree passes
258228
+ * review and is merged with `mergeAndCleanup`.
258229
+ */
258230
+ integrateWorktrees(sources, target) {
258231
+ try {
258232
+ this.assertManagedSession(target);
258233
+ for (const source of sources) {
258234
+ this.assertManagedSession(source);
258235
+ if (path4.resolve(source.path) === path4.resolve(target.path) || source.branchName === target.branchName) {
258236
+ throw new Error("A writer worktree cannot integrate into itself.");
258237
+ }
258238
+ }
258239
+ } catch (error) {
258240
+ return { success: false, error: toErrorMessage2(error), preserved: true };
258241
+ }
258242
+ let integratedCount = 0;
258243
+ try {
258244
+ for (const source of sources) {
258245
+ this.commitWorktreeChanges(source);
258246
+ const baseline = source.baselineCommit || source.baseCommit;
258247
+ if (!baseline) {
258248
+ throw new Error(
258249
+ `Writer worktree has no trusted baseline: ${source.branchName}`
258250
+ );
258251
+ }
258252
+ const delta = this.gitBuffer(
258253
+ ["diff", "--binary", baseline, source.branchName],
258254
+ source.path
258255
+ );
258256
+ if (delta.length > 0) {
258257
+ execFileSync4("git", ["apply", "--whitespace=nowarn", "-"], {
258258
+ ...HIDDEN_CHILD_PROCESS_OPTIONS,
258259
+ cwd: target.path,
258260
+ input: delta,
258261
+ stdio: ["pipe", "pipe", "pipe"],
258262
+ maxBuffer: 64 * 1024 * 1024
258263
+ });
258264
+ }
258265
+ integratedCount += 1;
258266
+ }
258267
+ } catch (error) {
258268
+ try {
258269
+ this.git(["reset", "--hard", "HEAD"], target.path);
258270
+ this.git(["clean", "-fd"], target.path);
258271
+ } catch {
258272
+ }
258273
+ return {
258274
+ success: false,
258275
+ integratedCount,
258276
+ error: `Failed to integrate writer changes: ${toErrorMessage2(error)}`,
258277
+ preserved: true
258278
+ };
258279
+ }
258280
+ const cleanupErrors = [];
258281
+ for (const source of sources) {
258282
+ try {
258283
+ this.discardWorktree(source);
258284
+ } catch (error) {
258285
+ cleanupErrors.push(`${source.branchName}: ${toErrorMessage2(error)}`);
258286
+ }
258287
+ }
258288
+ return {
258289
+ success: true,
258290
+ integratedCount,
258291
+ ...cleanupErrors.length ? {
258292
+ preserved: true,
258293
+ error: `Writer changes were integrated, but cleanup is incomplete: ${cleanupErrors.join(" | ")}`
258294
+ } : {}
258295
+ };
258296
+ }
258297
+ /** List the complete writer delta before integration or review. */
258298
+ listChangedFiles(session) {
258299
+ this.assertManagedSession(session);
258300
+ const baseline = session.baselineCommit || session.baseCommit;
258301
+ if (!baseline) {
258302
+ throw new Error(
258303
+ `Managed worktree has no trusted baseline: ${session.branchName}`
258304
+ );
258305
+ }
258306
+ const tracked = this.git(
258307
+ ["diff", "--name-only", "-z", baseline],
258308
+ session.path
258309
+ ).split("\0").filter(Boolean);
258310
+ const untracked = this.git(
258311
+ ["ls-files", "--others", "--exclude-standard", "-z"],
258312
+ session.path
258313
+ ).split("\0").filter(Boolean);
258314
+ return Array.from(/* @__PURE__ */ new Set([...tracked, ...untracked])).map((file) => file.replace(/\\/g, "/")).filter((file) => file !== ".orbit" && !file.startsWith(".orbit/")).sort();
258315
+ }
258078
258316
  discardWorktree(session) {
258079
258317
  this.assertManagedSession(session);
258080
258318
  if (fs4.existsSync(session.path)) {
@@ -258105,6 +258343,20 @@ var WorktreeManager = class {
258105
258343
  return [];
258106
258344
  }
258107
258345
  }
258346
+ commitWorktreeChanges(session) {
258347
+ this.git(["add", "-A"], session.path);
258348
+ if (!this.git(["status", "--porcelain"], session.path).trim()) return;
258349
+ this.git(
258350
+ [
258351
+ "commit",
258352
+ "--no-verify",
258353
+ "--no-gpg-sign",
258354
+ "-m",
258355
+ "subagent automatic worktree commit"
258356
+ ],
258357
+ session.path
258358
+ );
258359
+ }
258108
258360
  /** Copy the user's tracked and safe untracked state into the isolated branch. */
258109
258361
  snapshotWorkingTree(worktreePath) {
258110
258362
  const patch = this.gitBuffer(["diff", "HEAD", "--binary", "--no-ext-diff"]);
@@ -260350,12 +260602,14 @@ function isNodeError2(error) {
260350
260602
  import { randomUUID as randomUUID42 } from "crypto";
260351
260603
  import path52 from "path";
260352
260604
  import { z as z73 } from "zod";
260605
+ import { randomUUID as randomUUID52 } from "crypto";
260353
260606
  import { z as z103 } from "zod";
260354
260607
  import { z as z93 } from "zod";
260608
+ import { z as z112 } from "zod";
260355
260609
  import path8 from "path";
260356
260610
  import { existsSync as existsSync34, statSync as statSync3 } from "fs";
260357
- import { z as z112 } from "zod";
260358
260611
  import { z as z122 } from "zod";
260612
+ import { z as z132 } from "zod";
260359
260613
  function createInitialState(sessionId, task, maxAttempts = 8) {
260360
260614
  return {
260361
260615
  sessionId,
@@ -261682,6 +261936,25 @@ var VerificationEndedEventSchema = z38.object({
261682
261936
  results: z38.unknown().optional()
261683
261937
  })
261684
261938
  });
261939
+ var HookStartedEventSchema = z38.object({
261940
+ type: z38.literal("hook_started"),
261941
+ payload: z38.object({
261942
+ hookId: z38.string(),
261943
+ event: LifecycleHookEventSchema,
261944
+ legacy: z38.boolean()
261945
+ })
261946
+ });
261947
+ var HookCompletedEventSchema = z38.object({
261948
+ type: z38.literal("hook_completed"),
261949
+ payload: z38.object({
261950
+ hookId: z38.string(),
261951
+ event: LifecycleHookEventSchema,
261952
+ success: z38.boolean(),
261953
+ durationMs: z38.number().nonnegative(),
261954
+ action: z38.enum(["continue", "warn", "blocked", "ignored"]),
261955
+ error: z38.string().optional()
261956
+ })
261957
+ });
261685
261958
  var SessionForkEventSchema = z38.object({
261686
261959
  type: z38.literal("session_fork"),
261687
261960
  payload: z38.object({
@@ -261748,6 +262021,8 @@ var OrbitEventSchema = z38.discriminatedUnion("type", [
261748
262021
  CheckpointCreatedEventSchema,
261749
262022
  VerificationStartedEventSchema,
261750
262023
  VerificationEndedEventSchema,
262024
+ HookStartedEventSchema,
262025
+ HookCompletedEventSchema,
261751
262026
  SessionForkEventSchema,
261752
262027
  SessionEndedEventSchema,
261753
262028
  InfoEventSchema,
@@ -262840,6 +263115,10 @@ var McpRuntimeManager = class {
262840
263115
  clients = [];
262841
263116
  registeredTools = /* @__PURE__ */ new Map();
262842
263117
  promptsByServer = /* @__PURE__ */ new Map();
263118
+ runtimes = /* @__PURE__ */ new Map();
263119
+ healthByServer = /* @__PURE__ */ new Map();
263120
+ pendingRefreshKinds = /* @__PURE__ */ new Map();
263121
+ refreshTimers = /* @__PURE__ */ new Map();
262843
263122
  async start(servers, report) {
262844
263123
  await this.stop();
262845
263124
  const result = {
@@ -262896,6 +263175,27 @@ var McpRuntimeManager = class {
262896
263175
  report
262897
263176
  );
262898
263177
  this.clients.push(client);
263178
+ const runtime = {
263179
+ serverName,
263180
+ config: serverConfig,
263181
+ client,
263182
+ report,
263183
+ toolNames: new Set(registeredForClient)
263184
+ };
263185
+ runtime.unsubscribeCatalog = client.onCatalogChanged?.((kinds) => {
263186
+ this.scheduleCatalogRefresh(serverName, kinds);
263187
+ });
263188
+ this.runtimes.set(serverName, runtime);
263189
+ const runtimeHealth = client.getRuntimeHealth?.();
263190
+ this.healthByServer.set(serverName, {
263191
+ serverName,
263192
+ status: "healthy",
263193
+ connected: runtimeHealth?.connected ?? true,
263194
+ registeredTools: runtime.toolNames.size,
263195
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263196
+ ...protocol ? { protocol: protocol.version } : {},
263197
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263198
+ });
262899
263199
  result.startedServers += 1;
262900
263200
  } catch (error) {
262901
263201
  for (const toolName of registeredForClient) {
@@ -262909,6 +263209,14 @@ var McpRuntimeManager = class {
262909
263209
  this.promptsByServer.delete(serverName);
262910
263210
  await client?.stop().catch(() => void 0);
262911
263211
  const message2 = safeMcpRuntimeMessage(error);
263212
+ this.healthByServer.set(serverName, {
263213
+ serverName,
263214
+ status: "failed",
263215
+ connected: false,
263216
+ registeredTools: 0,
263217
+ recoveryCount: 0,
263218
+ lastError: message2
263219
+ });
262912
263220
  result.failures.push({ serverName, message: message2 });
262913
263221
  report(` \u2716 Failed to start MCP server "${serverName}": ${message2}`);
262914
263222
  }
@@ -262925,6 +263233,31 @@ var McpRuntimeManager = class {
262925
263233
  }
262926
263234
  return descriptors2;
262927
263235
  }
263236
+ /** Return a stable, credential-redacted snapshot for doctor and UI surfaces. */
263237
+ listHealth() {
263238
+ return [...this.healthByServer.values()].map((health) => {
263239
+ const runtimeHealth = this.runtimes.get(health.serverName)?.client.getRuntimeHealth?.();
263240
+ return {
263241
+ ...health,
263242
+ status: runtimeHealth && !runtimeHealth.connected ? "degraded" : health.status,
263243
+ connected: runtimeHealth?.connected ?? health.connected,
263244
+ recoveryCount: runtimeHealth?.recoveryCount ?? health.recoveryCount,
263245
+ ...runtimeHealth?.lastError ? { lastError: safeMcpRuntimeMessage(runtimeHealth.lastError) } : {}
263246
+ };
263247
+ }).sort((left, right) => left.serverName.localeCompare(right.serverName));
263248
+ }
263249
+ /** Refresh live catalogs without restarting healthy MCP processes. */
263250
+ async refreshCatalogs(serverName) {
263251
+ const runtimes = serverName ? [this.runtimes.get(serverName)].filter(
263252
+ (runtime) => Boolean(runtime)
263253
+ ) : [...this.runtimes.values()];
263254
+ await Promise.all(
263255
+ runtimes.map(
263256
+ (runtime) => this.refreshServerCatalog(runtime, ["tools", "resources", "prompts"])
263257
+ )
263258
+ );
263259
+ return this.listHealth();
263260
+ }
262928
263261
  /** Resolve one discovered prompt into expanded prompt text. */
262929
263262
  async expandPrompt(serverName, promptName, args) {
262930
263263
  const entry = this.promptsByServer.get(serverName);
@@ -262937,11 +263270,19 @@ var McpRuntimeManager = class {
262937
263270
  return entry.client.getPrompt(prompt.name, args);
262938
263271
  }
262939
263272
  async stop() {
263273
+ for (const timer of this.refreshTimers.values()) clearTimeout(timer);
263274
+ this.refreshTimers.clear();
263275
+ this.pendingRefreshKinds.clear();
263276
+ for (const runtime of this.runtimes.values()) {
263277
+ runtime.unsubscribeCatalog?.();
263278
+ }
263279
+ this.runtimes.clear();
262940
263280
  for (const [toolName, tool] of this.registeredTools) {
262941
263281
  this.registry.unregister(toolName, tool);
262942
263282
  }
262943
263283
  this.registeredTools.clear();
262944
263284
  this.promptsByServer.clear();
263285
+ this.healthByServer.clear();
262945
263286
  const clients = this.clients.splice(0);
262946
263287
  await Promise.allSettled(clients.map((client) => client.stop()));
262947
263288
  }
@@ -262979,12 +263320,182 @@ var McpRuntimeManager = class {
262979
263320
  return;
262980
263321
  }
262981
263322
  const prompts = await client.listPrompts();
263323
+ this.promptsByServer.delete(serverName);
262982
263324
  if (!prompts.length) return;
262983
263325
  this.promptsByServer.set(serverName, { client, prompts });
262984
263326
  report(
262985
263327
  ` \u2714 Discovered ${prompts.length} MCP prompt${prompts.length === 1 ? "" : "s"} on "${serverName}"`
262986
263328
  );
262987
263329
  }
263330
+ scheduleCatalogRefresh(serverName, kinds) {
263331
+ const runtime = this.runtimes.get(serverName);
263332
+ if (!runtime) return;
263333
+ const pending = this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set();
263334
+ for (const kind of kinds) pending.add(kind);
263335
+ this.pendingRefreshKinds.set(serverName, pending);
263336
+ if (this.refreshTimers.has(serverName)) return;
263337
+ const timer = setTimeout(() => {
263338
+ this.refreshTimers.delete(serverName);
263339
+ const nextKinds = [
263340
+ ...this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set()
263341
+ ];
263342
+ this.pendingRefreshKinds.delete(serverName);
263343
+ void this.refreshServerCatalog(runtime, nextKinds);
263344
+ }, 100);
263345
+ timer.unref?.();
263346
+ this.refreshTimers.set(serverName, timer);
263347
+ }
263348
+ async refreshServerCatalog(runtime, kinds) {
263349
+ const current = this.healthByServer.get(runtime.serverName);
263350
+ this.healthByServer.set(runtime.serverName, {
263351
+ ...current ?? {
263352
+ serverName: runtime.serverName,
263353
+ connected: true,
263354
+ registeredTools: runtime.toolNames.size,
263355
+ recoveryCount: 0
263356
+ },
263357
+ status: "refreshing"
263358
+ });
263359
+ try {
263360
+ if (kinds.includes("tools") && runtime.client.listTools) {
263361
+ await this.refreshTools(runtime, await runtime.client.listTools());
263362
+ }
263363
+ if (kinds.includes("resources")) {
263364
+ await this.refreshResourceTool(runtime);
263365
+ }
263366
+ if (kinds.includes("prompts")) {
263367
+ await this.captureServerPrompts(
263368
+ runtime.serverName,
263369
+ runtime.config,
263370
+ runtime.client,
263371
+ runtime.report
263372
+ );
263373
+ }
263374
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263375
+ this.healthByServer.set(runtime.serverName, {
263376
+ serverName: runtime.serverName,
263377
+ status: "healthy",
263378
+ connected: runtimeHealth?.connected ?? true,
263379
+ registeredTools: runtime.toolNames.size,
263380
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263381
+ ...runtime.client.getNegotiatedProtocol?.()?.version ? { protocol: runtime.client.getNegotiatedProtocol?.()?.version } : {},
263382
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263383
+ });
263384
+ runtime.report(
263385
+ ` \u2714 Refreshed MCP catalog for "${runtime.serverName}" (${kinds.join(", ")})`
263386
+ );
263387
+ } catch (error) {
263388
+ const message2 = safeMcpRuntimeMessage(error);
263389
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263390
+ this.healthByServer.set(runtime.serverName, {
263391
+ serverName: runtime.serverName,
263392
+ status: "degraded",
263393
+ connected: runtimeHealth?.connected ?? true,
263394
+ registeredTools: runtime.toolNames.size,
263395
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263396
+ ...current?.protocol ? { protocol: current.protocol } : {},
263397
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString(),
263398
+ lastError: message2
263399
+ });
263400
+ runtime.report(
263401
+ ` \u26A0\uFE0F MCP catalog refresh failed for "${runtime.serverName}": ${message2}`
263402
+ );
263403
+ }
263404
+ }
263405
+ async refreshTools(runtime, definitions) {
263406
+ const resourceToolName = createMcpToolName(
263407
+ runtime.serverName,
263408
+ "read_resource"
263409
+ );
263410
+ const oldNames = [...runtime.toolNames].filter(
263411
+ (name) => name !== resourceToolName
263412
+ );
263413
+ const oldTools = new Map(
263414
+ oldNames.flatMap((name) => {
263415
+ const tool = this.registeredTools.get(name);
263416
+ return tool ? [[name, tool]] : [];
263417
+ })
263418
+ );
263419
+ const replacements = definitions.map((definition) => {
263420
+ const risk = runtime.config.tools?.[definition.name]?.risk ?? "execute";
263421
+ return new DynamicMCPTool(
263422
+ runtime.serverName,
263423
+ definition,
263424
+ risk,
263425
+ runtime.client
263426
+ );
263427
+ });
263428
+ const replacementNames = /* @__PURE__ */ new Set();
263429
+ for (const tool of replacements) {
263430
+ if (replacementNames.has(tool.name)) {
263431
+ throw new Error(`MCP refresh produced duplicate tool ${tool.name}.`);
263432
+ }
263433
+ replacementNames.add(tool.name);
263434
+ const collision = this.registry.get(tool.name);
263435
+ if (collision && !oldTools.has(tool.name)) {
263436
+ throw new Error(`MCP refresh collided with tool ${tool.name}.`);
263437
+ }
263438
+ }
263439
+ for (const [name, tool] of oldTools) {
263440
+ this.registry.unregister(name, tool);
263441
+ this.registeredTools.delete(name);
263442
+ runtime.toolNames.delete(name);
263443
+ }
263444
+ const registered = [];
263445
+ try {
263446
+ for (const tool of replacements) {
263447
+ this.registry.register(tool);
263448
+ this.registeredTools.set(tool.name, tool);
263449
+ runtime.toolNames.add(tool.name);
263450
+ registered.push(tool);
263451
+ }
263452
+ } catch (error) {
263453
+ for (const tool of registered) {
263454
+ this.registry.unregister(tool.name, tool);
263455
+ this.registeredTools.delete(tool.name);
263456
+ runtime.toolNames.delete(tool.name);
263457
+ }
263458
+ for (const [name, tool] of oldTools) {
263459
+ this.registry.register(tool);
263460
+ this.registeredTools.set(name, tool);
263461
+ runtime.toolNames.add(name);
263462
+ }
263463
+ throw error;
263464
+ }
263465
+ }
263466
+ async refreshResourceTool(runtime) {
263467
+ const resourceName = createMcpToolName(runtime.serverName, "read_resource");
263468
+ const oldTool = this.registeredTools.get(resourceName);
263469
+ if (oldTool) {
263470
+ this.registry.unregister(resourceName, oldTool);
263471
+ this.registeredTools.delete(resourceName);
263472
+ runtime.toolNames.delete(resourceName);
263473
+ }
263474
+ const result = {
263475
+ startedServers: 1,
263476
+ registeredTools: runtime.toolNames.size,
263477
+ failures: []
263478
+ };
263479
+ const registered = [];
263480
+ try {
263481
+ await this.registerResourceTool(
263482
+ runtime.serverName,
263483
+ runtime.config,
263484
+ runtime.client,
263485
+ registered,
263486
+ result,
263487
+ runtime.report
263488
+ );
263489
+ for (const name of registered) runtime.toolNames.add(name);
263490
+ } catch (error) {
263491
+ if (oldTool) {
263492
+ this.registry.register(oldTool);
263493
+ this.registeredTools.set(resourceName, oldTool);
263494
+ runtime.toolNames.add(resourceName);
263495
+ }
263496
+ throw error;
263497
+ }
263498
+ }
262988
263499
  };
262989
263500
  function safeMcpRuntimeMessage(error) {
262990
263501
  const raw = error instanceof Error ? error.message : String(error);
@@ -263278,17 +263789,27 @@ var NETWORK_SUMMARY_CHARS = 280;
263278
263789
  var NETWORK_RESULT_CHARS = 6e3;
263279
263790
  var TOOL_RESULT_MAX_CHARS = 24e3;
263280
263791
  var TOOL_STATUS_MAX_CHARS = 2e3;
263792
+ var TOOL_ERROR_MAX_CHARS = 8e3;
263281
263793
  function buildToolResultContent(toolName, result) {
263282
- const content = result.ok ? serializeToolResultData(result.data, result.display) : result.error || "Unknown error";
263794
+ const content = result.ok ? serializeToolResultData(result.data, result.display) : serializeToolFailure(result.error, result.display);
263283
263795
  const redacted = redactSecrets(content);
263284
263796
  if (!result.ok || toolName !== "web_search") {
263285
263797
  return truncateToolText(
263286
263798
  redacted,
263287
- result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_STATUS_MAX_CHARS
263799
+ result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_ERROR_MAX_CHARS
263288
263800
  );
263289
263801
  }
263290
263802
  return compactSearchResult(redacted, redactSecrets(result.display || ""));
263291
263803
  }
263804
+ function serializeToolFailure(error, display) {
263805
+ const message2 = error?.trim() || "Unknown error";
263806
+ const output = display?.trim();
263807
+ if (!output || output === message2) return message2;
263808
+ return `${message2}
263809
+
263810
+ Captured command output:
263811
+ ${output}`;
263812
+ }
263292
263813
  function truncateToolText(text2, maxChars) {
263293
263814
  if (text2.length <= maxChars) return text2;
263294
263815
  const suffix = "\n... [truncated for context budget]";
@@ -263344,6 +263865,113 @@ function parseSearchResultBlocks(content) {
263344
263865
  }
263345
263866
  return results;
263346
263867
  }
263868
+ var WRITE_TOOLS = /* @__PURE__ */ new Set([
263869
+ "write_file",
263870
+ "edit_file",
263871
+ "replace_file_content",
263872
+ "multi_replace_file_content"
263873
+ ]);
263874
+ function selectLifecycleHooks(hooks, event, context) {
263875
+ const configured = hooks.lifecycle?.[event] ?? [];
263876
+ const selected = configured.filter((hook) => matchesLifecycleHook(hook.matcher, event, context)).map((hook) => ({ ...hook, legacy: false }));
263877
+ const isWriteTool = context.toolName ? WRITE_TOOLS.has(context.toolName) : false;
263878
+ if (event === "preToolUse" && isWriteTool && context.filePath && hooks.preEdit) {
263879
+ selected.unshift({
263880
+ command: hooks.preEdit,
263881
+ timeoutMs: 3e4,
263882
+ onFailure: "block",
263883
+ legacy: true
263884
+ });
263885
+ }
263886
+ if (event === "postToolUse" && isWriteTool && context.filePath && hooks.postEdit) {
263887
+ selected.unshift({
263888
+ command: hooks.postEdit,
263889
+ timeoutMs: 3e4,
263890
+ onFailure: "block",
263891
+ legacy: true
263892
+ });
263893
+ }
263894
+ return selected;
263895
+ }
263896
+ function matchesLifecycleHook(matcher, event, context) {
263897
+ if (!matcher) return true;
263898
+ const subject = context.toolName || context.agentRole || context.filePath || context.status || event;
263899
+ return globMatches(matcher, subject);
263900
+ }
263901
+ function buildLifecycleHookEnvironment(event, context) {
263902
+ const safeContext = Object.fromEntries(
263903
+ Object.entries(context).filter(([, value]) => value !== void 0)
263904
+ );
263905
+ const payload = redactSecrets(JSON.stringify(safeContext)).slice(0, 32768);
263906
+ return {
263907
+ ORBIT_HOOK_EVENT: event,
263908
+ ORBIT_HOOK_PAYLOAD: payload,
263909
+ ORBIT_SESSION_ID: context.sessionId,
263910
+ ...context.toolName ? { ORBIT_TOOL_NAME: context.toolName } : {},
263911
+ ...context.filePath ? { ORBIT_FILE: context.filePath } : {},
263912
+ ...context.agentRole ? { ORBIT_AGENT_ROLE: context.agentRole } : {},
263913
+ ...context.status ? { ORBIT_HOOK_STATUS: context.status } : {}
263914
+ };
263915
+ }
263916
+ async function executeLifecycleHooks(options) {
263917
+ const hooks = selectLifecycleHooks(
263918
+ options.hooks,
263919
+ options.event,
263920
+ options.context
263921
+ );
263922
+ for (const hook of hooks) {
263923
+ const hookId = `hook_${randomUUID52()}`;
263924
+ const startedAt = Date.now();
263925
+ eventBus.emitEvent("hook_started", {
263926
+ hookId,
263927
+ event: options.event,
263928
+ legacy: hook.legacy
263929
+ });
263930
+ options.report(`\u25CF Running ${options.event} hook...`);
263931
+ const result = await options.execute(
263932
+ hook,
263933
+ buildLifecycleHookEnvironment(options.event, options.context)
263934
+ );
263935
+ if (result.ok) {
263936
+ eventBus.emitEvent("hook_completed", {
263937
+ hookId,
263938
+ event: options.event,
263939
+ success: true,
263940
+ durationMs: Date.now() - startedAt,
263941
+ action: "continue"
263942
+ });
263943
+ options.report(`\u2714 ${options.event} hook passed.`);
263944
+ continue;
263945
+ }
263946
+ const action = hook.onFailure === "block" ? "blocked" : hook.onFailure === "ignore" ? "ignored" : "warn";
263947
+ eventBus.emitEvent("hook_completed", {
263948
+ hookId,
263949
+ event: options.event,
263950
+ success: false,
263951
+ durationMs: Date.now() - startedAt,
263952
+ action,
263953
+ error: result.output
263954
+ });
263955
+ if (hook.onFailure === "block") {
263956
+ options.report(`\u2716 ${options.event} hook blocked: ${result.output}`);
263957
+ return { ok: false, output: result.output };
263958
+ }
263959
+ if (hook.onFailure === "warn") {
263960
+ options.report(`\u26A0\uFE0F ${options.event} hook warning: ${result.output}`);
263961
+ }
263962
+ }
263963
+ return { ok: true };
263964
+ }
263965
+ function globMatches(pattern, value) {
263966
+ let source = "^";
263967
+ for (const character of pattern) {
263968
+ if (character === "*") source += ".*";
263969
+ else if (character === "?") source += ".";
263970
+ else source += character.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
263971
+ }
263972
+ source += "$";
263973
+ return new RegExp(source, "iu").test(value);
263974
+ }
263347
263975
  var execPromise2 = promisify3(exec2);
263348
263976
  var execFilePromise3 = promisify3(execFile3);
263349
263977
  var DEEPSEEK_CACHE_DEGRADED_HIT_RATE = 0.85;
@@ -263383,7 +264011,6 @@ function waitForAgentRetry(delayMs, signal) {
263383
264011
  cleanup();
263384
264012
  resolve26();
263385
264013
  }, delayMs);
263386
- timeout.unref?.();
263387
264014
  const onAbort = () => {
263388
264015
  clearTimeout(timeout);
263389
264016
  cleanup();
@@ -263548,6 +264175,14 @@ var AgentLoop = class _AgentLoop {
263548
264175
  expandMcpPrompt(serverName, promptName, args) {
263549
264176
  return this.mcpRuntimeManager.expandPrompt(serverName, promptName, args);
263550
264177
  }
264178
+ /** Browser/terminal-safe MCP health snapshots. */
264179
+ listMcpHealth() {
264180
+ return this.mcpRuntimeManager.listHealth();
264181
+ }
264182
+ /** Refresh tool, resource, and prompt catalogs without restarting servers. */
264183
+ refreshMcpCatalogs(serverName) {
264184
+ return this.mcpRuntimeManager.refreshCatalogs(serverName);
264185
+ }
263551
264186
  /** Start configured MCP servers once and retain them for this loop's lifetime. */
263552
264187
  async initializeMcp() {
263553
264188
  if (this.mcpStartResult) return this.mcpStartResult;
@@ -263716,7 +264351,7 @@ var AgentLoop = class _AgentLoop {
263716
264351
  }
263717
264352
  appendBackgroundTaskNotification(tasks, remainingRunning = 0) {
263718
264353
  const message2 = {
263719
- id: `msg_background_tasks_${randomUUID52().replace(/-/g, "")}`,
264354
+ id: `msg_background_tasks_${randomUUID62().replace(/-/g, "")}`,
263720
264355
  role: "user",
263721
264356
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
263722
264357
  content: [
@@ -263814,11 +264449,37 @@ var AgentLoop = class _AgentLoop {
263814
264449
  } finally {
263815
264450
  await this.contextBuilder.settleBackgroundWork().catch(() => void 0);
263816
264451
  }
264452
+ if (this.options.agent?.role) {
264453
+ const subagentStopHooks = await this.runLifecycleHooks("subagentStop", {
264454
+ sessionId: this.state.sessionId,
264455
+ attempt: this.state.attemptCount,
264456
+ agentRole: this.options.agent.role,
264457
+ status: outcome.status
264458
+ });
264459
+ if (!subagentStopHooks.ok && outcome.status === "completed") {
264460
+ outcome = this.createFailedOutcome(
264461
+ "execution_error",
264462
+ subagentStopHooks.output || "A blocking subagent-stop hook failed."
264463
+ );
264464
+ }
264465
+ }
264466
+ const stopHooks = await this.runLifecycleHooks("stop", {
264467
+ sessionId: this.state.sessionId,
264468
+ attempt: this.state.attemptCount,
264469
+ status: outcome.status
264470
+ });
264471
+ if (!stopHooks.ok && outcome.status === "completed") {
264472
+ outcome = this.createFailedOutcome(
264473
+ "execution_error",
264474
+ stopHooks.output || "A blocking stop hook failed."
264475
+ );
264476
+ }
263817
264477
  this.finalizeOutcome(outcome);
263818
264478
  return outcome;
263819
264479
  }
263820
264480
  async executeRun() {
263821
264481
  const runStartedAt = /* @__PURE__ */ new Date();
264482
+ const isNewSession = this.state.history.length === 0;
263822
264483
  let iterationLimitReached = false;
263823
264484
  eventBus.emitEvent("agent_start", {
263824
264485
  taskId: this.state.sessionId,
@@ -263847,8 +264508,48 @@ var AgentLoop = class _AgentLoop {
263847
264508
  this.sessionManager.saveHistory(this.state.history);
263848
264509
  void this.provider.initialize?.().catch(() => {
263849
264510
  });
264511
+ if (isNewSession) {
264512
+ const sessionHooks = await this.runLifecycleHooks("sessionStart", {
264513
+ sessionId: this.state.sessionId,
264514
+ attempt: this.state.attemptCount
264515
+ });
264516
+ if (!sessionHooks.ok) {
264517
+ return this.createFailedOutcome(
264518
+ "execution_error",
264519
+ sessionHooks.output || "A blocking session-start hook failed."
264520
+ );
264521
+ }
264522
+ }
264523
+ const promptHooks = await this.runLifecycleHooks("promptSubmit", {
264524
+ sessionId: this.state.sessionId,
264525
+ attempt: this.state.attemptCount,
264526
+ promptLength: this.state.task.length
264527
+ });
264528
+ if (!promptHooks.ok) {
264529
+ return this.createFailedOutcome(
264530
+ "execution_error",
264531
+ promptHooks.output || "A blocking prompt hook failed."
264532
+ );
264533
+ }
264534
+ if (this.options.agent?.role) {
264535
+ const subagentStartHooks = await this.runLifecycleHooks("subagentStart", {
264536
+ sessionId: this.state.sessionId,
264537
+ attempt: this.state.attemptCount,
264538
+ agentRole: this.options.agent.role
264539
+ });
264540
+ if (!subagentStartHooks.ok) {
264541
+ return this.createFailedOutcome(
264542
+ "execution_error",
264543
+ subagentStartHooks.output || "A blocking subagent-start hook failed."
264544
+ );
264545
+ }
264546
+ }
263850
264547
  void this.contextBuilder.warmCodebaseRetrieval().catch(() => void 0);
264548
+ const mcpWasInitialized = Boolean(this.mcpStartResult);
263851
264549
  await this.initializeMcp();
264550
+ if (mcpWasInitialized) {
264551
+ await this.refreshMcpCatalogs();
264552
+ }
263852
264553
  const sigintListener = () => {
263853
264554
  if (this.abortController) {
263854
264555
  this.interaction.showText(
@@ -264366,9 +265067,14 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
264366
265067
  continue;
264367
265068
  }
264368
265069
  }
264369
- const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? ["RATE_LIMIT", "SERVER", "OVERLOADED", "TIMEOUT"].includes(
264370
- providerFailure.code
264371
- ) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
265070
+ const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? [
265071
+ "RATE_LIMIT",
265072
+ "SERVER",
265073
+ "OVERLOADED",
265074
+ "TIMEOUT",
265075
+ "TRANSPORT",
265076
+ "STREAM_CLOSED"
265077
+ ].includes(providerFailure.code) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
264372
265078
  chatErrorMessage
264373
265079
  ));
264374
265080
  if (canFallbackToFlash) {
@@ -264570,6 +265276,20 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264570
265276
  this.interaction.showText(
264571
265277
  "\n\u25CF Verification: Running contract verification checks..."
264572
265278
  );
265279
+ const verificationStartHooks = await this.runLifecycleHooks(
265280
+ "verificationStart",
265281
+ {
265282
+ sessionId: this.state.sessionId,
265283
+ attempt: this.state.attemptCount,
265284
+ status: "contract"
265285
+ }
265286
+ );
265287
+ if (!verificationStartHooks.ok) {
265288
+ return this.createFailedOutcome(
265289
+ "verification_failed",
265290
+ verificationStartHooks.output || "A blocking verification-start hook failed."
265291
+ );
265292
+ }
264573
265293
  const verificationWorkspaceBefore = await captureWorkspaceMutationSnapshot(this.cwd);
264574
265294
  const verifyResult = await this.verificationManager.runVerification();
264575
265295
  const verificationWorkspaceAfter = await captureWorkspaceMutationSnapshot(this.cwd);
@@ -264585,6 +265305,21 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264585
265305
  );
264586
265306
  }
264587
265307
  this.recordVerificationResult(verifyResult.success);
265308
+ const verificationEndHooks = await this.runLifecycleHooks(
265309
+ "verificationEnd",
265310
+ {
265311
+ sessionId: this.state.sessionId,
265312
+ attempt: this.state.attemptCount,
265313
+ status: verifyResult.success ? "passed" : "failed",
265314
+ verificationPassed: verifyResult.success
265315
+ }
265316
+ );
265317
+ if (!verificationEndHooks.ok) {
265318
+ return this.createFailedOutcome(
265319
+ "verification_failed",
265320
+ verificationEndHooks.output || "A blocking verification-end hook failed."
265321
+ );
265322
+ }
264588
265323
  if (!verifyResult.success) {
264589
265324
  const maxRepairAttempts = this.verificationManager.getMaxRepairAttempts();
264590
265325
  const repairAttempts = countRepairAttemptsForCurrentTask(
@@ -264956,6 +265691,30 @@ Please analyze this failure log, locate the files causing assertion or compile e
264956
265691
  risk: decision2.risk
264957
265692
  };
264958
265693
  }
265694
+ if (decision2.action === "ask") {
265695
+ const permissionHooks = await this.runLifecycleHooks(
265696
+ "permissionRequest",
265697
+ {
265698
+ sessionId: this.state.sessionId,
265699
+ attempt: this.state.attemptCount,
265700
+ toolName: tc.name,
265701
+ filePath: firstStringValue(
265702
+ evalArgsRecord.path,
265703
+ evalArgsRecord.TargetFile,
265704
+ evalArgsRecord.filePath,
265705
+ evalArgsRecord.file
265706
+ ),
265707
+ status: decision2.risk
265708
+ }
265709
+ );
265710
+ if (!permissionHooks.ok) {
265711
+ decision2 = {
265712
+ action: "deny",
265713
+ reason: permissionHooks.output || `A blocking permission hook rejected ${tc.name}.`,
265714
+ risk: decision2.risk
265715
+ };
265716
+ }
265717
+ }
264959
265718
  if (decision2.action === "deny") {
264960
265719
  this.interaction.showText(`\u2716 Blocked: ${decision2.reason}`);
264961
265720
  eventBus.emitEvent("tool_approval", {
@@ -265331,25 +266090,20 @@ ${stdout2.substring(0, 2e4)}`
265331
266090
  )
265332
266091
  );
265333
266092
  }
265334
- if (this.config.hooks?.preEdit) {
265335
- this.interaction.showText(`\u25CF Running pre-edit hook...`);
265336
- const hookRes = await this.runHook(
265337
- this.config.hooks.preEdit,
265338
- targetPath
265339
- );
265340
- if (!hookRes.ok) {
265341
- this.interaction.showText(
265342
- `\u2716 Pre-edit hook failed: ${hookRes.output}`
265343
- );
265344
- hookResult = {
265345
- ok: false,
265346
- error: `Pre-edit hook failed: ${hookRes.output}`
265347
- };
265348
- skipToolExecution = true;
265349
- } else {
265350
- this.interaction.showText(`\u2714 Pre-edit hook passed.`);
265351
- }
265352
- }
266093
+ }
266094
+ const preToolHooks = await this.runLifecycleHooks("preToolUse", {
266095
+ sessionId: this.state.sessionId,
266096
+ attempt: this.state.attemptCount,
266097
+ toolName: tc.name,
266098
+ filePath: targetPath,
266099
+ agentRole: this.options.agent?.role
266100
+ });
266101
+ if (!preToolHooks.ok) {
266102
+ hookResult = {
266103
+ ok: false,
266104
+ error: preToolHooks.output || `A blocking pre-tool hook rejected ${tc.name}.`
266105
+ };
266106
+ skipToolExecution = true;
265353
266107
  }
265354
266108
  this.interaction.progress?.start(
265355
266109
  `Executing tool: ${tc.name}... | Cost: ${this.formatSessionCost()}`
@@ -265397,24 +266151,23 @@ ${stdout2.substring(0, 2e4)}`
265397
266151
  }
265398
266152
  }
265399
266153
  let finalResult = result;
265400
- if (result.ok && !skipToolExecution && (tc.name === "write_file" || tc.name === "edit_file") && targetPath) {
265401
- if (this.config.hooks?.postEdit) {
265402
- this.interaction.showText(`\u25CF Running post-edit hook...`);
265403
- const hookRes = await this.runHook(
265404
- this.config.hooks.postEdit,
265405
- targetPath
265406
- );
265407
- if (!hookRes.ok) {
265408
- this.interaction.showText(
265409
- `\u2716 Post-edit hook failed: ${hookRes.output}`
265410
- );
265411
- finalResult = {
265412
- ok: false,
265413
- error: `Post-edit hook failed: ${hookRes.output}`
265414
- };
265415
- } else {
265416
- this.interaction.showText(`\u2714 Post-edit hook passed.`);
266154
+ if (!skipToolExecution) {
266155
+ const postToolHooks = await this.runLifecycleHooks(
266156
+ result.ok ? "postToolUse" : "postToolFailure",
266157
+ {
266158
+ sessionId: this.state.sessionId,
266159
+ attempt: this.state.attemptCount,
266160
+ toolName: tc.name,
266161
+ filePath: targetPath,
266162
+ agentRole: this.options.agent?.role,
266163
+ status: result.ok ? "success" : "failure"
265417
266164
  }
266165
+ );
266166
+ if (!postToolHooks.ok) {
266167
+ finalResult = {
266168
+ ok: false,
266169
+ error: postToolHooks.output || `A blocking post-tool hook failed for ${tc.name}.`
266170
+ };
265418
266171
  }
265419
266172
  }
265420
266173
  if (finalResult.ok && targetPath && absoluteTargetPath && (tc.name === "write_file" || tc.name === "edit_file" || tc.name === "replace_file_content" || tc.name === "multi_replace_file_content")) {
@@ -265972,6 +266725,10 @@ ${stdout2.substring(0, 2e4)}`
265972
266725
  kind: terminalSuccess
265973
266726
  });
265974
266727
  }
266728
+ const modelVisibleToolResult = buildToolResultContent(
266729
+ tc.name,
266730
+ finalResult
266731
+ );
265975
266732
  if (finalResult.ok) {
265976
266733
  const statusText = truncateToolText(
265977
266734
  redactSecrets(finalResult.display || "Done"),
@@ -265989,7 +266746,7 @@ ${stdout2.substring(0, 2e4)}`
265989
266746
  }
265990
266747
  } else {
265991
266748
  const statusError = truncateToolText(
265992
- redactSecrets(finalResult.error || "Unknown error"),
266749
+ modelVisibleToolResult,
265993
266750
  TOOL_STATUS_MAX_CHARS
265994
266751
  );
265995
266752
  this.interaction.showText(
@@ -266001,7 +266758,7 @@ ${stdout2.substring(0, 2e4)}`
266001
266758
  toolName: tc.name,
266002
266759
  result: finalResult.ok ? redactSensitiveValue(finalResult.data) : void 0,
266003
266760
  display: finalResult.ok ? redactSecrets(finalResult.display || "") : void 0,
266004
- error: finalResult.ok ? void 0 : redactSecrets(finalResult.error || "Unknown error")
266761
+ error: finalResult.ok ? void 0 : modelVisibleToolResult
266005
266762
  });
266006
266763
  const guardNudge = this.progressGuard.record({
266007
266764
  name: tc.name,
@@ -266025,7 +266782,7 @@ ${stdout2.substring(0, 2e4)}`
266025
266782
  toolResult: {
266026
266783
  toolCallId: tc.id,
266027
266784
  name: tc.name,
266028
- content: buildToolResultContent(tc.name, finalResult) + (guardNudge ? `
266785
+ content: modelVisibleToolResult + (guardNudge ? `
266029
266786
 
266030
266787
  ${guardNudge.message}` : ""),
266031
266788
  isError: !finalResult.ok
@@ -266301,11 +267058,41 @@ ${diff.substring(0, 2e4)}`
266301
267058
  output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
266302
267059
  };
266303
267060
  }
266304
- const toolCallId = `hook_${randomUUID52()}`;
267061
+ return this.runHookCommand(
267062
+ hookCommand,
267063
+ { ORBIT_FILE: relativePath },
267064
+ this.config.tools.bash.timeoutMs
267065
+ );
267066
+ }
267067
+ async runLifecycleHooks(event, context) {
267068
+ return executeLifecycleHooks({
267069
+ hooks: this.config.hooks,
267070
+ event,
267071
+ context,
267072
+ execute: (hook, environment) => hook.legacy ? this.runHook(hook.command, context.filePath || "") : this.runHookCommand(
267073
+ hook.command,
267074
+ environment,
267075
+ hook.timeoutMs,
267076
+ event !== "stop" && event !== "subagentStop"
267077
+ ),
267078
+ report: (message2) => this.interaction.showText(message2)
267079
+ });
267080
+ }
267081
+ async runHookCommand(hookCommand, environment, timeoutMs, abortable = true) {
267082
+ if (hookCommand.includes("{file}")) {
267083
+ return {
267084
+ ok: false,
267085
+ output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
267086
+ };
267087
+ }
267088
+ const toolCallId = `hook_${randomUUID62()}`;
266305
267089
  eventBus.emitEvent("tool_proposal", {
266306
267090
  toolCallId,
266307
267091
  toolName: "hook",
266308
- arguments: { filePath: relativePath },
267092
+ arguments: {
267093
+ event: environment.ORBIT_HOOK_EVENT || "legacy",
267094
+ filePath: environment.ORBIT_FILE
267095
+ },
266309
267096
  explanation: "Run a configured Orbit lifecycle hook."
266310
267097
  });
266311
267098
  const decision2 = this.permissionEngine.evaluate(
@@ -266356,12 +267143,9 @@ ${diff.substring(0, 2e4)}`
266356
267143
  const { stdout: stdout2, stderr } = await execPromise2(hookCommand, {
266357
267144
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
266358
267145
  cwd: this.cwd,
266359
- env: this.buildChildProcessEnvironment(
266360
- { ORBIT_FILE: relativePath },
266361
- true
266362
- ),
266363
- timeout: this.config.tools.bash.timeoutMs,
266364
- signal: this.abortController?.signal
267146
+ env: this.buildChildProcessEnvironment(environment, true),
267147
+ timeout: Math.min(timeoutMs, this.config.tools.bash.timeoutMs),
267148
+ signal: abortable ? this.abortController?.signal : void 0
266365
267149
  });
266366
267150
  const output = safeHookOutput(stdout2 + stderr);
266367
267151
  eventBus.emitEvent("tool_result", {
@@ -266419,7 +267203,7 @@ ${diff.substring(0, 2e4)}`
266419
267203
  const now = (/* @__PURE__ */ new Date()).toISOString();
266420
267204
  const plan = this.sessionManager.getTaskPlan();
266421
267205
  const item = {
266422
- id: `step_${randomUUID52()}`,
267206
+ id: `step_${randomUUID62()}`,
266423
267207
  text: text2.trim(),
266424
267208
  status: "pending",
266425
267209
  createdAt: now,
@@ -266550,7 +267334,7 @@ ${diff.substring(0, 2e4)}`
266550
267334
  this.finalResponseOnlyReason = null;
266551
267335
  for (const input of inputs) {
266552
267336
  this.state.history.push({
266553
- id: `msg_user_steer_${randomUUID52().replace(/-/g, "")}`,
267337
+ id: `msg_user_steer_${randomUUID62().replace(/-/g, "")}`,
266554
267338
  role: "user",
266555
267339
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
266556
267340
  content: [{ type: "text", text: input.text }, ...input.attachments],
@@ -266934,6 +267718,16 @@ ${diff.substring(0, 2e4)}`
266934
267718
  * Only fires when Phase 1 alone isn't enough to keep history bounded.
266935
267719
  */
266936
267720
  async compactHistory(mode, targetHistoryTokens) {
267721
+ const preCompactHooks = await this.runLifecycleHooks("preCompact", {
267722
+ sessionId: this.state.sessionId,
267723
+ attempt: this.state.attemptCount,
267724
+ mode
267725
+ });
267726
+ if (!preCompactHooks.ok) {
267727
+ throw new Error(
267728
+ preCompactHooks.output || "A blocking pre-compaction hook failed."
267729
+ );
267730
+ }
266937
267731
  const status = this.getContextWindowStatus();
266938
267732
  const { history, droppedHistory, summaryMessageId, ...result } = compactHistoryMessages(this.state.history, {
266939
267733
  mode,
@@ -266955,10 +267749,22 @@ ${diff.substring(0, 2e4)}`
266955
267749
  this.state.history = history;
266956
267750
  this.sessionManager.saveHistory(this.state.history);
266957
267751
  }
266958
- return {
267752
+ const finalResult = {
266959
267753
  ...this.getContextWindowStatus(),
266960
267754
  ...result
266961
267755
  };
267756
+ const postCompactHooks = await this.runLifecycleHooks("postCompact", {
267757
+ sessionId: this.state.sessionId,
267758
+ attempt: this.state.attemptCount,
267759
+ mode,
267760
+ status: result.changed ? "changed" : "unchanged"
267761
+ });
267762
+ if (!postCompactHooks.ok) {
267763
+ throw new Error(
267764
+ postCompactHooks.output || "A blocking post-compaction hook failed."
267765
+ );
267766
+ }
267767
+ return finalResult;
266962
267768
  }
266963
267769
  /** Compacts older dialogue on demand while preserving the active turn. */
266964
267770
  async compactHistoryPublic() {
@@ -267183,6 +267989,15 @@ function agentOwnershipScopesOverlap(left, right) {
267183
267989
  const comparableRight = comparableScope(normalizedRight);
267184
267990
  return comparableLeft === comparableRight || comparableLeft.startsWith(`${comparableRight}/`) || comparableRight.startsWith(`${comparableLeft}/`);
267185
267991
  }
267992
+ function agentOwnershipScopeContains(scope, filePath) {
267993
+ const normalizedScope = normalizeAgentOwnershipScope(scope);
267994
+ const normalizedFile = normalizeUnchecked(filePath);
267995
+ if (!normalizedFile || normalizedFile === "*") return false;
267996
+ if (normalizedScope === "*") return true;
267997
+ const comparableOwner = comparableScope(normalizedScope);
267998
+ const comparableFile = comparableScope(normalizedFile);
267999
+ return comparableFile === comparableOwner || comparableFile.startsWith(`${comparableOwner}/`);
268000
+ }
267186
268001
  function normalizeUnchecked(scope) {
267187
268002
  const portable = scope.trim().replace(/\\/g, "/");
267188
268003
  if (portable === "*" || portable.toLowerCase() === "workspace") return "*";
@@ -267406,7 +268221,6 @@ var AgentTaskScheduler = class {
267406
268221
  runResult.then(() => void 0),
267407
268222
  new Promise((resolve26) => {
267408
268223
  graceTimer = setTimeout(resolve26, this.abortGraceMs);
267409
- graceTimer.unref?.();
267410
268224
  })
267411
268225
  ]);
267412
268226
  } finally {
@@ -267440,6 +268254,61 @@ function abortError2(signal) {
267440
268254
  function toError2(error) {
267441
268255
  return error instanceof Error ? error : new Error(String(error));
267442
268256
  }
268257
+ var ParallelWriterTaskSchema = z112.object({
268258
+ id: z112.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
268259
+ task: z112.string().trim().min(1).max(2e4),
268260
+ scopes: z112.array(AgentOwnershipScopeSchema).min(1).max(50)
268261
+ });
268262
+ var ParallelWorkPlanSchema = z112.object({
268263
+ summary: z112.string().trim().min(1).max(2e4),
268264
+ tasks: z112.array(ParallelWriterTaskSchema).min(1).max(4)
268265
+ }).superRefine((plan, context) => {
268266
+ const ids = /* @__PURE__ */ new Set();
268267
+ for (const [index, task] of plan.tasks.entries()) {
268268
+ if (ids.has(task.id)) {
268269
+ context.addIssue({
268270
+ code: z112.ZodIssueCode.custom,
268271
+ path: ["tasks", index, "id"],
268272
+ message: `Duplicate writer task id: ${task.id}`
268273
+ });
268274
+ }
268275
+ ids.add(task.id);
268276
+ }
268277
+ if (plan.tasks.length < 2) return;
268278
+ for (let left = 0; left < plan.tasks.length; left++) {
268279
+ for (let right = left + 1; right < plan.tasks.length; right++) {
268280
+ const overlap = plan.tasks[left].scopes.some(
268281
+ (leftScope) => plan.tasks[right].scopes.some(
268282
+ (rightScope) => agentOwnershipScopesOverlap(leftScope, rightScope)
268283
+ )
268284
+ );
268285
+ if (!overlap) continue;
268286
+ context.addIssue({
268287
+ code: z112.ZodIssueCode.custom,
268288
+ path: ["tasks", right, "scopes"],
268289
+ message: `Writer scopes overlap with task ${plan.tasks[left].id}.`
268290
+ });
268291
+ }
268292
+ }
268293
+ });
268294
+ function parseParallelWorkPlan(text2) {
268295
+ const candidate = extractJsonObject(text2);
268296
+ if (!candidate) return void 0;
268297
+ try {
268298
+ const result = ParallelWorkPlanSchema.safeParse(JSON.parse(candidate));
268299
+ return result.success ? result.data : void 0;
268300
+ } catch {
268301
+ return void 0;
268302
+ }
268303
+ }
268304
+ function extractJsonObject(text2) {
268305
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text2)?.[1]?.trim();
268306
+ const source = fenced || text2.trim();
268307
+ const start = source.indexOf("{");
268308
+ const end = source.lastIndexOf("}");
268309
+ if (start < 0 || end <= start) return void 0;
268310
+ return source.slice(start, end + 1);
268311
+ }
267443
268312
  var AgentRunTracker = class {
267444
268313
  constructor(cwd, task, budgetUsd, warn) {
267445
268314
  this.cwd = cwd;
@@ -267588,9 +268457,9 @@ function resolveAgentTeam(config) {
267588
268457
  reviewers
267589
268458
  };
267590
268459
  }
267591
- var ReviewVerdictSchema = z112.object({
267592
- verdict: z112.enum(["approved", "rejected"]),
267593
- feedback: z112.string().default("")
268460
+ var ReviewVerdictSchema = z122.object({
268461
+ verdict: z122.enum(["approved", "rejected"]),
268462
+ feedback: z122.string().default("")
267594
268463
  });
267595
268464
  var Orchestrator = class {
267596
268465
  constructor(cwd, config, provider, task, interaction) {
@@ -267664,8 +268533,10 @@ var Orchestrator = class {
267664
268533
  this.abortedOutcome(0, "Orchestration was interrupted.")
267665
268534
  );
267666
268535
  }
267667
- const planText = planner.plan;
267668
- this.persistPlan(planText);
268536
+ const planText = planner.workPlan?.summary || planner.plan;
268537
+ this.persistPlan(
268538
+ planner.workPlan ? JSON.stringify(planner.workPlan, null, 2) : planner.plan
268539
+ );
267669
268540
  const worktrees = new WorktreeManager(this.cwd);
267670
268541
  let worktree;
267671
268542
  let agentCwd = this.cwd;
@@ -267673,12 +268544,25 @@ var Orchestrator = class {
267673
268544
  let mergeFailureMessage = "";
267674
268545
  let completed = false;
267675
268546
  let completedAttempts = 0;
268547
+ let parallelPrepared = false;
267676
268548
  if (worktrees.isGitRepo()) {
267677
268549
  try {
267678
- const worktreeId = generateId("wt").slice(0, 12);
267679
- worktree = worktrees.createWorktree(worktreeId, {
267680
- snapshotWorkingTree: true
267681
- });
268550
+ if (planner.workPlan && planner.workPlan.tasks.length > 1) {
268551
+ const prepared = await this.prepareParallelWorkspace(
268552
+ worktrees,
268553
+ planner.workPlan
268554
+ );
268555
+ if (!prepared.success) {
268556
+ return this.finalizeOutcome(prepared.outcome);
268557
+ }
268558
+ worktree = prepared.integration;
268559
+ parallelPrepared = true;
268560
+ } else {
268561
+ const worktreeId = generateId("wt").slice(0, 12);
268562
+ worktree = worktrees.createWorktree(worktreeId, {
268563
+ snapshotWorkingTree: true
268564
+ });
268565
+ }
267682
268566
  if (!existsSync34(worktree.path) || !statSync3(worktree.path).isDirectory()) {
267683
268567
  throw new Error(
267684
268568
  `Worktree manager returned a missing directory: ${worktree.path}`
@@ -267686,7 +268570,7 @@ var Orchestrator = class {
267686
268570
  }
267687
268571
  agentCwd = worktree.path;
267688
268572
  this.interaction.showText(
267689
- ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
268573
+ parallelPrepared ? ` \u25CF Reviewing the combined parallel implementation in: ${agentCwd}` : ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
267690
268574
  );
267691
268575
  } catch (error) {
267692
268576
  if (worktree) {
@@ -267711,15 +268595,17 @@ var Orchestrator = class {
267711
268595
  try {
267712
268596
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
267713
268597
  if (this.aborted) break;
267714
- const coderOutcome = await this.runCoder(
267715
- agentCwd,
267716
- planText,
267717
- feedback,
267718
- attempt,
267719
- maxAttempts
267720
- );
267721
- if (coderOutcome.status !== "completed") {
267722
- return this.finalizeOutcome(coderOutcome);
268598
+ if (!(parallelPrepared && attempt === 1)) {
268599
+ const coderOutcome = await this.runCoder(
268600
+ agentCwd,
268601
+ planText,
268602
+ feedback,
268603
+ attempt,
268604
+ maxAttempts
268605
+ );
268606
+ if (coderOutcome.status !== "completed") {
268607
+ return this.finalizeOutcome(coderOutcome);
268608
+ }
267723
268609
  }
267724
268610
  if (this.aborted) break;
267725
268611
  const review = await this.runReviewer(agentCwd, attempt, maxAttempts);
@@ -267818,8 +268704,10 @@ var Orchestrator = class {
267818
268704
  {
267819
268705
  modelOverride: this.config.models.planner,
267820
268706
  systemPromptOverride: `You are the Orbit Planner Agent.
267821
- Analyze the codebase and produce a detailed implementation plan.
267822
- Do not modify files. Return the plan as plain text.`,
268707
+ Analyze the codebase and produce a bounded implementation plan. Do not modify files.
268708
+ Return ONLY one JSON object with this shape:
268709
+ {"summary":"shared architecture and acceptance criteria","tasks":[{"id":"short-id","task":"self-contained writer assignment","scopes":["workspace-relative/path"]}]}
268710
+ 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.`,
267823
268711
  allowedTools: [
267824
268712
  "read_file",
267825
268713
  "list_files",
@@ -267841,8 +268729,10 @@ Do not modify files. Return the plan as plain text.`,
267841
268729
  let outcome;
267842
268730
  try {
267843
268731
  outcome = await loop.run();
268732
+ const plan = lastAssistantText(loop) || "No plan generated.";
267844
268733
  return {
267845
- plan: lastAssistantText(loop) || "No plan generated.",
268734
+ plan,
268735
+ workPlan: parseParallelWorkPlan(plan),
267846
268736
  outcome
267847
268737
  };
267848
268738
  } catch (error) {
@@ -267865,15 +268755,48 @@ ${feedback}
267865
268755
  Original plan:
267866
268756
  ${plan}` : `Implement the following plan:
267867
268757
  ${plan}`;
267868
- const tracked = this.addTrackedAgent(
268758
+ return this.runWriter(
268759
+ cwd,
268760
+ prompt,
267869
268761
  `coder:${attempt}`,
268762
+ ["workspace"],
268763
+ 0.45 / maxAttempts,
268764
+ `You are the Orbit Coder Agent.
268765
+ Make precise changes in the current isolated workspace. Run focused verification when useful. Do not commit or merge.`
268766
+ );
268767
+ }
268768
+ async runParallelCoder(cwd, plan, task, signal) {
268769
+ this.interaction.showText(
268770
+ `
268771
+ [Phase 2: Parallel writer ${task.id}] Owning ${task.scopes.join(", ")}...`
268772
+ );
268773
+ const prompt = [
268774
+ `Shared plan: ${plan.summary}`,
268775
+ `Your assignment: ${task.task}`,
268776
+ `You exclusively own these write scopes: ${task.scopes.join(", ")}.`,
268777
+ "Do not modify files outside those scopes. Run focused verification for your changes."
268778
+ ].join("\n\n");
268779
+ return this.runWriter(
268780
+ cwd,
268781
+ prompt,
268782
+ `writer:${task.id}`,
268783
+ task.scopes,
268784
+ 0.45 / plan.tasks.length,
268785
+ `You are an Orbit parallel Writer Agent.
268786
+ 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.`,
268787
+ signal
268788
+ );
268789
+ }
268790
+ async runWriter(cwd, prompt, role, scopes, budgetFraction, systemPrompt, signal) {
268791
+ const tracked = this.addTrackedAgent(
268792
+ role,
267870
268793
  prompt,
267871
268794
  this.config.models.coder,
267872
- 0.45 / maxAttempts,
268795
+ budgetFraction,
267873
268796
  "write",
267874
- ["workspace"]
268797
+ scopes
267875
268798
  );
267876
- const activeId = tracked?.id || `coder-${attempt}`;
268799
+ const activeId = tracked?.id || role.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64);
267877
268800
  const loop = AgentLoop.initialize(
267878
268801
  cwd,
267879
268802
  this.config,
@@ -267882,8 +268805,7 @@ ${plan}`;
267882
268805
  this.interaction,
267883
268806
  {
267884
268807
  modelOverride: this.config.models.coder,
267885
- systemPromptOverride: `You are the Orbit Coder Agent.
267886
- Make precise changes in the current isolated workspace. Do not commit or merge.`,
268808
+ systemPromptOverride: systemPrompt,
267887
268809
  allowedTools: [
267888
268810
  "read_file",
267889
268811
  "write_file",
@@ -267892,13 +268814,21 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267892
268814
  "glob",
267893
268815
  "grep",
267894
268816
  "git_status",
267895
- "git_diff"
268817
+ "git_diff",
268818
+ "run_tests",
268819
+ "bash",
268820
+ "get_background_task_output",
268821
+ "kill_background_task",
268822
+ "list_background_tasks"
267896
268823
  ],
267897
268824
  disableMcp: true,
267898
- agent: { id: activeId, role: `coder:${attempt}` },
268825
+ agent: { id: activeId, role },
267899
268826
  sessionStorage: this.agentSessionStorage()
267900
268827
  }
267901
268828
  );
268829
+ const abortLoop = () => loop.abort("immediate");
268830
+ if (signal?.aborted) abortLoop();
268831
+ signal?.addEventListener("abort", abortLoop, { once: true });
267902
268832
  this.agentRunTracker.attachSession(tracked, loop.getSessionId());
267903
268833
  this.activeLoops.set(activeId, loop);
267904
268834
  this.markAgentRunning(tracked);
@@ -267911,10 +268841,131 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267911
268841
  throw error;
267912
268842
  } finally {
267913
268843
  if (outcome) this.markAgentFinished(tracked, loop, outcome);
268844
+ signal?.removeEventListener("abort", abortLoop);
267914
268845
  this.activeLoops.delete(activeId);
267915
268846
  await loop.dispose();
267916
268847
  }
267917
268848
  }
268849
+ async prepareParallelWorkspace(worktrees, plan) {
268850
+ const integration = worktrees.createWorktree(
268851
+ generateId("integration").slice(0, 24),
268852
+ { snapshotWorkingTree: true }
268853
+ );
268854
+ const writers = [];
268855
+ let cleanup = true;
268856
+ try {
268857
+ for (const task of plan.tasks) {
268858
+ writers.push({
268859
+ task,
268860
+ session: worktrees.createWorktree(
268861
+ `${task.id}-${generateId("writer").slice(0, 12)}`.slice(0, 63),
268862
+ { snapshotWorkingTree: true }
268863
+ )
268864
+ });
268865
+ }
268866
+ this.interaction.showText(
268867
+ ` \u25CF Running ${writers.length} isolated writers with disjoint ownership scopes...`
268868
+ );
268869
+ const scheduler = new AgentTaskScheduler({
268870
+ maxConcurrency: Math.min(
268871
+ writers.length,
268872
+ this.config.agent.maxReviewConcurrency
268873
+ )
268874
+ });
268875
+ this.activeTaskScheduler = scheduler;
268876
+ const results = await (async () => {
268877
+ try {
268878
+ return await scheduler.run(
268879
+ writers.map(({ task, session }) => ({
268880
+ id: task.id,
268881
+ timeoutMs: this.reviewerTimeoutMs(),
268882
+ access: { mode: "write", scopes: task.scopes },
268883
+ run: (signal) => this.runParallelCoder(session.path, plan, task, signal)
268884
+ }))
268885
+ );
268886
+ } finally {
268887
+ if (this.activeTaskScheduler === scheduler) {
268888
+ this.activeTaskScheduler = void 0;
268889
+ }
268890
+ }
268891
+ })();
268892
+ for (const [index, result] of results.entries()) {
268893
+ if (result.status !== "completed") {
268894
+ return {
268895
+ success: false,
268896
+ preserved: false,
268897
+ outcome: result.status === "aborted" ? this.abortedOutcome(0, result.error.message) : this.failedOutcome(0, result.error.message)
268898
+ };
268899
+ }
268900
+ if (result.value.status !== "completed") {
268901
+ return { success: false, preserved: false, outcome: result.value };
268902
+ }
268903
+ const { task, session } = writers[index];
268904
+ const changedFiles = worktrees.listChangedFiles(session);
268905
+ const outsideScope = changedFiles.filter(
268906
+ (file) => !task.scopes.some(
268907
+ (scope) => agentOwnershipScopeContains(scope, file)
268908
+ )
268909
+ );
268910
+ if (outsideScope.length > 0) {
268911
+ return {
268912
+ success: false,
268913
+ preserved: false,
268914
+ outcome: this.failedOutcome(
268915
+ 0,
268916
+ `Writer ${task.id} modified files outside its ownership: ${outsideScope.join(", ")}`
268917
+ )
268918
+ };
268919
+ }
268920
+ if (changedFiles.length === 0) {
268921
+ return {
268922
+ success: false,
268923
+ preserved: false,
268924
+ outcome: this.failedOutcome(
268925
+ 0,
268926
+ `Writer ${task.id} completed without producing its assigned change.`
268927
+ )
268928
+ };
268929
+ }
268930
+ }
268931
+ const integrated = worktrees.integrateWorktrees(
268932
+ writers.map(({ session }) => session),
268933
+ integration
268934
+ );
268935
+ if (!integrated.success) {
268936
+ cleanup = false;
268937
+ this.interaction.showText(
268938
+ ` \u2716 Parallel integration failed; worktrees were preserved for recovery: ${errorMessage22(integrated.error || "unknown integration error")}`
268939
+ );
268940
+ return {
268941
+ success: false,
268942
+ preserved: true,
268943
+ outcome: this.failedOutcome(
268944
+ 0,
268945
+ integrated.error || "Parallel writer integration failed."
268946
+ )
268947
+ };
268948
+ }
268949
+ cleanup = false;
268950
+ this.interaction.showText(
268951
+ ` \u2714 Integrated ${integrated.integratedCount || writers.length} writer deltas into one review worktree.`
268952
+ );
268953
+ return { success: true, integration };
268954
+ } finally {
268955
+ if (cleanup) {
268956
+ for (const { session } of writers) {
268957
+ try {
268958
+ worktrees.discardWorktree(session);
268959
+ } catch {
268960
+ }
268961
+ }
268962
+ try {
268963
+ worktrees.discardWorktree(integration);
268964
+ } catch {
268965
+ }
268966
+ }
268967
+ }
268968
+ }
267918
268969
  async runReviewer(cwd, attempt, maxAttempts) {
267919
268970
  const team = resolveAgentTeam(this.config);
267920
268971
  const reviewerNames = team.reviewers.map(({ perspective }) => perspective).join(", ");
@@ -268155,62 +269206,80 @@ function errorMessage22(error) {
268155
269206
  const raw = error instanceof Error ? error.message : String(error);
268156
269207
  return redactSecrets(raw).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 2e3);
268157
269208
  }
268158
- var AcceptanceVerificationSchema = z122.object({
268159
- name: z122.string().trim().min(1).max(120),
268160
- command: z122.string().trim().min(1).max(4e3),
268161
- timeoutMs: z122.number().int().min(1e3).max(30 * 6e4).default(12e4)
269209
+ var AcceptanceVerificationSchema = z132.object({
269210
+ name: z132.string().trim().min(1).max(120),
269211
+ command: z132.string().trim().min(1).max(4e3),
269212
+ timeoutMs: z132.number().int().min(1e3).max(30 * 6e4).default(12e4)
268162
269213
  });
268163
- var AcceptanceTaskSchema = z122.object({
268164
- id: z122.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
268165
- prompt: z122.string().trim().min(1).max(2e4),
268166
- mode: z122.enum(["single", "multi"]).default("single"),
268167
- provider: z122.string().trim().min(1).optional(),
268168
- model: z122.string().trim().min(1).optional(),
268169
- verification: z122.array(AcceptanceVerificationSchema).max(20).default([]),
268170
- requiredChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
268171
- forbiddenChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
268172
- maxChangedFiles: z122.number().int().min(0).max(1e4).optional(),
268173
- limits: z122.object({
268174
- maxDurationMs: z122.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
268175
- maxInputTokens: z122.number().int().nonnegative().optional(),
268176
- maxOutputTokens: z122.number().int().nonnegative().optional(),
268177
- maxCostUsd: z122.number().finite().nonnegative().optional(),
268178
- minCacheHitRate: z122.number().finite().min(0).max(1).optional()
269214
+ var AcceptanceTaskSchema = z132.object({
269215
+ id: z132.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
269216
+ prompt: z132.string().trim().min(1).max(2e4),
269217
+ mode: z132.enum(["single", "multi"]).default("single"),
269218
+ provider: z132.string().trim().min(1).optional(),
269219
+ model: z132.string().trim().min(1).optional(),
269220
+ verification: z132.array(AcceptanceVerificationSchema).max(20).default([]),
269221
+ requiredChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
269222
+ forbiddenChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
269223
+ maxChangedFiles: z132.number().int().min(0).max(1e4).optional(),
269224
+ limits: z132.object({
269225
+ maxDurationMs: z132.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
269226
+ maxInputTokens: z132.number().int().nonnegative().optional(),
269227
+ maxOutputTokens: z132.number().int().nonnegative().optional(),
269228
+ maxCostUsd: z132.number().finite().nonnegative().optional(),
269229
+ minCacheHitRate: z132.number().finite().min(0).max(1).optional(),
269230
+ maxToolFailures: z132.number().int().nonnegative().optional(),
269231
+ maxDeniedTools: z132.number().int().nonnegative().optional(),
269232
+ maxApprovalRequests: z132.number().int().nonnegative().optional(),
269233
+ maxCompactions: z132.number().int().nonnegative().optional(),
269234
+ maxAttempts: z132.number().int().nonnegative().optional(),
269235
+ maxToolFailureRate: z132.number().finite().min(0).max(1).optional()
268179
269236
  }).optional()
268180
269237
  });
268181
- var AcceptanceSuiteSchema = z122.object({
268182
- schemaVersion: z122.literal(1),
268183
- name: z122.string().trim().min(1).max(200),
268184
- description: z122.string().trim().max(2e3).optional(),
268185
- tasks: z122.array(AcceptanceTaskSchema).min(1).max(100)
269238
+ var AcceptanceSuiteSchema = z132.object({
269239
+ schemaVersion: z132.literal(1),
269240
+ name: z132.string().trim().min(1).max(200),
269241
+ description: z132.string().trim().max(2e3).optional(),
269242
+ defaultLimits: AcceptanceTaskSchema.shape.limits,
269243
+ tasks: z132.array(AcceptanceTaskSchema).min(1).max(100)
268186
269244
  });
268187
- var AcceptanceCheckResultSchema = z122.object({
268188
- name: z122.string(),
268189
- passed: z122.boolean(),
268190
- durationMs: z122.number().int().nonnegative(),
268191
- exitCode: z122.number().int().optional(),
268192
- summary: z122.string().max(4e3)
269245
+ var AcceptanceCheckResultSchema = z132.object({
269246
+ name: z132.string(),
269247
+ passed: z132.boolean(),
269248
+ durationMs: z132.number().int().nonnegative(),
269249
+ exitCode: z132.number().int().optional(),
269250
+ summary: z132.string().max(4e3)
268193
269251
  });
268194
- var AcceptanceTaskResultSchema = z122.object({
268195
- taskId: z122.string(),
268196
- sessionId: z122.string().optional(),
268197
- traceFile: z122.string().optional(),
268198
- passed: z122.boolean(),
268199
- agentStatus: z122.enum(["completed", "failed", "aborted"]),
268200
- durationMs: z122.number().int().nonnegative(),
268201
- requestedProvider: z122.string().optional(),
268202
- requestedModel: z122.string().optional(),
268203
- resolvedModels: z122.array(z122.string()).default([]),
268204
- usage: z122.object({
268205
- inputTokens: z122.number().int().nonnegative(),
268206
- outputTokens: z122.number().int().nonnegative(),
268207
- cacheReadTokens: z122.number().int().nonnegative(),
268208
- cacheHitRate: z122.number().finite().min(0).max(1),
268209
- costUsd: z122.number().finite().nonnegative()
269252
+ var AcceptanceTaskResultSchema = z132.object({
269253
+ taskId: z132.string(),
269254
+ sessionId: z132.string().optional(),
269255
+ traceFile: z132.string().optional(),
269256
+ passed: z132.boolean(),
269257
+ agentStatus: z132.enum(["completed", "failed", "aborted"]),
269258
+ durationMs: z132.number().int().nonnegative(),
269259
+ requestedProvider: z132.string().optional(),
269260
+ requestedModel: z132.string().optional(),
269261
+ resolvedModels: z132.array(z132.string()).default([]),
269262
+ usage: z132.object({
269263
+ inputTokens: z132.number().int().nonnegative(),
269264
+ outputTokens: z132.number().int().nonnegative(),
269265
+ cacheReadTokens: z132.number().int().nonnegative(),
269266
+ cacheHitRate: z132.number().finite().min(0).max(1),
269267
+ costUsd: z132.number().finite().nonnegative()
268210
269268
  }).optional(),
268211
- changedFiles: z122.array(z122.string()),
268212
- checks: z122.array(AcceptanceCheckResultSchema),
268213
- failureReasons: z122.array(z122.string())
269269
+ reliability: z132.object({
269270
+ attempts: z132.number().int().nonnegative(),
269271
+ toolRuns: z132.number().int().nonnegative(),
269272
+ toolFailures: z132.number().int().nonnegative(),
269273
+ deniedTools: z132.number().int().nonnegative(),
269274
+ approvalRequests: z132.number().int().nonnegative(),
269275
+ compactions: z132.number().int().nonnegative(),
269276
+ resumedCount: z132.number().int().nonnegative(),
269277
+ verificationRuns: z132.number().int().nonnegative(),
269278
+ checkpoints: z132.number().int().nonnegative()
269279
+ }).optional(),
269280
+ changedFiles: z132.array(z132.string()),
269281
+ checks: z132.array(AcceptanceCheckResultSchema),
269282
+ failureReasons: z132.array(z132.string())
268214
269283
  });
268215
269284
  function scoreAcceptanceTask(input) {
268216
269285
  const task = AcceptanceTaskSchema.parse(input.task);
@@ -268268,6 +269337,19 @@ function scoreAcceptanceTask(input) {
268268
269337
  `duration_limit:${Math.round(input.durationMs)}>${task.limits.maxDurationMs}`
268269
269338
  );
268270
269339
  }
269340
+ const reliabilityLimitsConfigured = [
269341
+ task.limits.maxToolFailures,
269342
+ task.limits.maxDeniedTools,
269343
+ task.limits.maxApprovalRequests,
269344
+ task.limits.maxCompactions,
269345
+ task.limits.maxAttempts,
269346
+ task.limits.maxToolFailureRate
269347
+ ].some((value) => value !== void 0);
269348
+ if (reliabilityLimitsConfigured && !input.reliability) {
269349
+ failureReasons.push("reliability_missing");
269350
+ } else if (input.reliability) {
269351
+ enforceReliabilityLimits(task, input.reliability, failureReasons);
269352
+ }
268271
269353
  }
268272
269354
  return AcceptanceTaskResultSchema.parse({
268273
269355
  taskId: task.id,
@@ -268280,11 +269362,39 @@ function scoreAcceptanceTask(input) {
268280
269362
  requestedModel: task.model,
268281
269363
  resolvedModels: Array.from(new Set(input.resolvedModels || [])),
268282
269364
  usage: input.usage,
269365
+ reliability: input.reliability,
268283
269366
  changedFiles,
268284
269367
  checks: input.checks,
268285
269368
  failureReasons
268286
269369
  });
268287
269370
  }
269371
+ function enforceReliabilityLimits(task, reliability, failureReasons) {
269372
+ const limits = task.limits;
269373
+ if (!limits) return;
269374
+ for (const [name, actual, maximum] of [
269375
+ ["tool_failure_limit", reliability.toolFailures, limits.maxToolFailures],
269376
+ ["denied_tool_limit", reliability.deniedTools, limits.maxDeniedTools],
269377
+ [
269378
+ "approval_request_limit",
269379
+ reliability.approvalRequests,
269380
+ limits.maxApprovalRequests
269381
+ ],
269382
+ ["compaction_limit", reliability.compactions, limits.maxCompactions],
269383
+ ["attempt_limit", reliability.attempts, limits.maxAttempts]
269384
+ ]) {
269385
+ if (maximum !== void 0 && actual > maximum) {
269386
+ failureReasons.push(`${name}:${actual}>${maximum}`);
269387
+ }
269388
+ }
269389
+ if (limits.maxToolFailureRate !== void 0) {
269390
+ const rate = reliability.toolRuns > 0 ? reliability.toolFailures / reliability.toolRuns : 0;
269391
+ if (rate > limits.maxToolFailureRate) {
269392
+ failureReasons.push(
269393
+ `tool_failure_rate:${Number(rate.toFixed(6))}>${limits.maxToolFailureRate}`
269394
+ );
269395
+ }
269396
+ }
269397
+ }
268288
269398
  function normalizeFilePath(value) {
268289
269399
  return value.replace(/\\/g, "/").replace(/^\.\//, "");
268290
269400
  }
@@ -269057,7 +270167,6 @@ async function probeProviderCapabilities(cwd, config, provider, options = {}) {
269057
270167
  () => controller.abort(),
269058
270168
  options.timeoutMs ?? DEFAULT_PROVIDER_PROBE_TIMEOUT_MS
269059
270169
  );
269060
- timeout.unref?.();
269061
270170
  const result = {
269062
270171
  providerId: provider.id,
269063
270172
  model,
@@ -272599,6 +273708,56 @@ var SLASH_COMMAND_DEFINITIONS = [
272599
273708
  },
272600
273709
  webSuggested: true
272601
273710
  },
273711
+ {
273712
+ command: "/workflow",
273713
+ usage: "export <kebab-name> [local|versioned]",
273714
+ category: "session",
273715
+ description: {
273716
+ en: "Compile this session into a reviewable reusable Skill",
273717
+ zh: "\u5C06\u5F53\u524D\u4F1A\u8BDD\u7F16\u8BD1\u4E3A\u53EF\u5BA1\u9605\u7684\u590D\u7528 Skill",
273718
+ "zh-TW": "\u5C07\u76EE\u524D\u5DE5\u4F5C\u968E\u6BB5\u7DE8\u8B6F\u70BA\u53EF\u5BE9\u95B1\u7684\u91CD\u7528 Skill"
273719
+ },
273720
+ suggestions: [
273721
+ {
273722
+ value: "export ",
273723
+ description: {
273724
+ en: "Create a local Skill from the current trace",
273725
+ zh: "\u4ECE\u5F53\u524D\u5BA1\u8BA1\u8BB0\u5F55\u521B\u5EFA\u672C\u5730 Skill",
273726
+ "zh-TW": "\u5F9E\u76EE\u524D\u7A3D\u6838\u8A18\u9304\u5EFA\u7ACB\u672C\u6A5F Skill"
273727
+ }
273728
+ }
273729
+ ],
273730
+ webSuggested: true
273731
+ },
273732
+ {
273733
+ command: "/mcp",
273734
+ usage: "[status|refresh] [server]",
273735
+ category: "system",
273736
+ description: {
273737
+ en: "Inspect MCP health or refresh live catalogs",
273738
+ zh: "\u67E5\u770B MCP \u5065\u5EB7\u72B6\u6001\u6216\u5237\u65B0\u5B9E\u65F6\u76EE\u5F55",
273739
+ "zh-TW": "\u67E5\u770B MCP \u5065\u5EB7\u72C0\u614B\u6216\u91CD\u65B0\u6574\u7406\u5373\u6642\u76EE\u9304"
273740
+ },
273741
+ suggestions: [
273742
+ {
273743
+ value: "status",
273744
+ description: {
273745
+ en: "Show server health",
273746
+ zh: "\u663E\u793A\u670D\u52A1\u5065\u5EB7\u72B6\u6001",
273747
+ "zh-TW": "\u986F\u793A\u670D\u52D9\u5065\u5EB7\u72C0\u614B"
273748
+ }
273749
+ },
273750
+ {
273751
+ value: "refresh",
273752
+ description: {
273753
+ en: "Refresh tools, resources, and prompts",
273754
+ zh: "\u5237\u65B0\u5DE5\u5177\u3001\u8D44\u6E90\u4E0E\u63D0\u793A\u8BCD",
273755
+ "zh-TW": "\u91CD\u65B0\u6574\u7406\u5DE5\u5177\u3001\u8CC7\u6E90\u8207\u63D0\u793A\u8A5E"
273756
+ }
273757
+ }
273758
+ ],
273759
+ webSuggested: false
273760
+ },
272602
273761
  {
272603
273762
  command: "/doctor",
272604
273763
  usage: "",
@@ -276369,7 +277528,7 @@ import { dirname as dirname14, resolve as resolve14 } from "path";
276369
277528
  import { homedir as homedir10 } from "os";
276370
277529
  import http3 from "http";
276371
277530
  import { randomBytes as randomBytes4, randomUUID as randomUUID13, timingSafeEqual as timingSafeEqual2 } from "crypto";
276372
- import { z as z69 } from "zod";
277531
+ import { z as z70 } from "zod";
276373
277532
 
276374
277533
  // src/runtime/CommandRouter.ts
276375
277534
  import picocolors18 from "picocolors";
@@ -283166,6 +284325,23 @@ function sanitizeWebEventPayload(type, payload) {
283166
284325
  return { type: safeWebText(payload.type, 100) };
283167
284326
  case "verification_ended":
283168
284327
  return { success: payload.success === true };
284328
+ case "hook_started":
284329
+ return {
284330
+ hookId: safeWebText(payload.hookId, 200),
284331
+ event: safeWebText(payload.event, 100),
284332
+ legacy: payload.legacy === true
284333
+ };
284334
+ case "hook_completed":
284335
+ return {
284336
+ hookId: safeWebText(payload.hookId, 200),
284337
+ event: safeWebText(payload.event, 100),
284338
+ success: payload.success === true,
284339
+ durationMs: safeNumber(payload.durationMs),
284340
+ action: ["continue", "warn", "blocked", "ignored"].includes(
284341
+ String(payload.action)
284342
+ ) ? String(payload.action) : "warn",
284343
+ error: safeWebText(payload.error, 1e3)
284344
+ };
283169
284345
  case "checkpoint_created":
283170
284346
  return {
283171
284347
  timestamp: safeWebText(payload.timestamp, 100),
@@ -296165,19 +297341,127 @@ async function confirmUpdate(prompt) {
296165
297341
  }
296166
297342
  }
296167
297343
 
296168
- // src/runtime/review/ReviewCommand.ts
297344
+ // src/commands/workflow.ts
296169
297345
  import { z as z67 } from "zod";
296170
- var ReviewPresetSchema = z67.enum([
297346
+
297347
+ // src/runtime/WorkflowCompiler.ts
297348
+ function compileWorkflowSkill(trace, descriptionOverride) {
297349
+ const observedTools = [
297350
+ ...new Set(trace.toolCalls.map((call) => call.toolName))
297351
+ ].sort().slice(0, 100);
297352
+ const successfulTools = trace.toolCalls.filter(
297353
+ (call) => call.status === "success"
297354
+ );
297355
+ const failedTools = trace.toolCalls.filter(
297356
+ (call) => call.status === "failed" || call.status === "denied"
297357
+ );
297358
+ const verificationEvents = trace.events.filter(
297359
+ (event) => event.type === "verification_ended"
297360
+ );
297361
+ const planSteps = (trace.plan?.items ?? []).map((item) => redactSecrets(item.text).trim()).filter(Boolean).slice(0, 50);
297362
+ const workflowSteps = planSteps.length > 0 ? planSteps : deriveWorkflowSteps(observedTools);
297363
+ const title = redactSecrets(trace.session.title || "Recorded Orbit workflow").replace(/\s+/g, " ").trim().slice(0, 180);
297364
+ const description = redactSecrets(descriptionOverride || title).replace(/[\r\n]+/g, " ").trim().slice(0, 240);
297365
+ const instructions = [
297366
+ "# Objective",
297367
+ "",
297368
+ redactSecrets(trace.session.goal || title).slice(0, 2e3),
297369
+ "",
297370
+ "# Reusable workflow",
297371
+ "",
297372
+ ...workflowSteps.map((step, index) => `${index + 1}. ${step}`),
297373
+ "",
297374
+ "# Execution contract",
297375
+ "",
297376
+ "- Re-inspect the current workspace before acting; recorded paths, commands, outputs, and assumptions are historical evidence only.",
297377
+ "- Never replay a recorded shell command or tool argument verbatim. Reconstruct the smallest current operation and route it through Orbit permissions.",
297378
+ "- Keep writes inside the authorized workspace and preserve unrelated dirty or staged changes.",
297379
+ "- Run the repository's current verification contract after edits. Repair the earliest root failure, then rerun the wider gate.",
297380
+ "- Stop and report a blocker when required authority, credentials, or external state is missing.",
297381
+ "",
297382
+ "# Observed strategy",
297383
+ "",
297384
+ `- Successful tool actions in the source run: ${successfulTools.length}.`,
297385
+ `- Failed or denied actions in the source run: ${failedTools.length}. Treat these as signals to inspect assumptions before retrying.`,
297386
+ `- Verification runs observed: ${verificationEvents.length}.`,
297387
+ `- Tool families observed: ${observedTools.join(", ") || "none"}.`,
297388
+ "",
297389
+ "This Skill was derived from a credential-redacted Orbit trace. It intentionally excludes raw prompts, tool arguments, command output, diffs, and local absolute paths."
297390
+ ].join("\n").slice(0, 24e3);
297391
+ return {
297392
+ description: description || "A reviewable workflow compiled from Orbit trace evidence.",
297393
+ instructions,
297394
+ observedTools,
297395
+ verificationRuns: verificationEvents.length
297396
+ };
297397
+ }
297398
+ function deriveWorkflowSteps(observedTools) {
297399
+ const steps = [
297400
+ "Clarify the requested outcome, constraints, authorized workspace, and acceptance evidence."
297401
+ ];
297402
+ if (observedTools.some((tool) => /read|search|list|symbol/i.test(tool))) {
297403
+ steps.push(
297404
+ "Inspect repository landmarks and the smallest relevant files before proposing changes."
297405
+ );
297406
+ }
297407
+ if (observedTools.some((tool) => /write|edit|replace|patch/i.test(tool))) {
297408
+ steps.push(
297409
+ "Apply scoped, reviewable edits while preserving unrelated user changes."
297410
+ );
297411
+ }
297412
+ if (observedTools.some((tool) => /test|bash|shell|command/i.test(tool))) {
297413
+ steps.push(
297414
+ "Execute the smallest relevant verification first, then expand according to risk."
297415
+ );
297416
+ }
297417
+ steps.push(
297418
+ "Inspect the final diff, summarize verified outcomes, and disclose any remaining uncertainty."
297419
+ );
297420
+ return steps;
297421
+ }
297422
+
297423
+ // src/commands/workflow.ts
297424
+ var WorkflowExportOptionsSchema = z67.object({
297425
+ name: z67.string().trim().min(1).max(48).regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),
297426
+ description: z67.string().trim().min(1).max(240).optional(),
297427
+ scope: z67.enum(["local", "versioned"]).default("local"),
297428
+ json: z67.boolean().default(false)
297429
+ });
297430
+ async function runWorkflowExport(cwd, sessionId, options) {
297431
+ const value = WorkflowExportOptionsSchema.parse(options);
297432
+ const trace = new SessionStore(cwd).exportTrace(sessionId, {
297433
+ includeHistory: false
297434
+ });
297435
+ const compiled = compileWorkflowSkill(trace, value.description);
297436
+ const created = await createProjectCapability(cwd, {
297437
+ kind: "skill",
297438
+ name: value.name,
297439
+ description: compiled.description,
297440
+ instructions: compiled.instructions,
297441
+ scope: value.scope
297442
+ });
297443
+ const result = {
297444
+ schemaVersion: 1,
297445
+ name: created.name,
297446
+ path: created.path
297447
+ };
297448
+ if (value.json) console.log(JSON.stringify(result, null, 2));
297449
+ return result;
297450
+ }
297451
+
297452
+ // src/runtime/review/ReviewCommand.ts
297453
+ import { z as z68 } from "zod";
297454
+ var ReviewPresetSchema = z68.enum([
296171
297455
  "comprehensive",
296172
297456
  "security",
296173
297457
  "tests",
296174
297458
  "performance",
296175
297459
  "accessibility"
296176
297460
  ]);
296177
- var ReviewScopeSchema = z67.discriminatedUnion("kind", [
296178
- z67.object({ kind: z67.literal("working-tree") }),
296179
- z67.object({ kind: z67.literal("commit"), ref: z67.string().min(1).max(200) }),
296180
- z67.object({ kind: z67.literal("branch"), ref: z67.string().min(1).max(200) })
297461
+ var ReviewScopeSchema = z68.discriminatedUnion("kind", [
297462
+ z68.object({ kind: z68.literal("working-tree") }),
297463
+ z68.object({ kind: z68.literal("commit"), ref: z68.string().min(1).max(200) }),
297464
+ z68.object({ kind: z68.literal("branch"), ref: z68.string().min(1).max(200) })
296181
297465
  ]);
296182
297466
  var SAFE_GIT_REF = /^[A-Za-z0-9][A-Za-z0-9._/@{}~^:+-]{0,199}$/;
296183
297467
  function parseReviewCommand(rawArguments) {
@@ -296401,6 +297685,58 @@ var CommandRouter = class {
296401
297685
  }
296402
297686
  }
296403
297687
  }
297688
+ if (/^\/mcp(?:\s|$)/i.test(trimmed)) {
297689
+ const [, action = "status", serverName] = trimmed.split(/\s+/, 3);
297690
+ if (!["status", "refresh"].includes(action.toLowerCase())) {
297691
+ this.printOutput(
297692
+ picocolors18.yellow("Usage: /mcp [status|refresh] [server]")
297693
+ );
297694
+ return { shouldExit: false, processed: true };
297695
+ }
297696
+ await loop.initializeMcp();
297697
+ const health = action.toLowerCase() === "refresh" ? await loop.refreshMcpCatalogs(serverName) : loop.listMcpHealth();
297698
+ if (health.length === 0) {
297699
+ this.printOutput(
297700
+ config.language === "en" ? "\u25CF No MCP servers are running." : "\u25CF \u5F53\u524D\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684 MCP \u670D\u52A1\u3002"
297701
+ );
297702
+ } else {
297703
+ this.printOutput(
297704
+ health.map(
297705
+ (server2) => `${server2.status === "healthy" ? "\u2714" : server2.status === "refreshing" ? "\u25CF" : "\u26A0\uFE0F"} ${server2.serverName} \xB7 ${server2.status} \xB7 tools=${server2.registeredTools} \xB7 recoveries=${server2.recoveryCount}${server2.protocol ? ` \xB7 ${server2.protocol}` : ""}${server2.lastError ? ` \xB7 ${server2.lastError}` : ""}`
297706
+ ).join("\n")
297707
+ );
297708
+ }
297709
+ return { shouldExit: false, processed: true };
297710
+ }
297711
+ if (/^\/workflow(?:\s|$)/i.test(trimmed)) {
297712
+ const [, action = "", name = "", scope = "local"] = trimmed.split(
297713
+ /\s+/,
297714
+ 4
297715
+ );
297716
+ if (action.toLowerCase() !== "export" || !name || !["local", "versioned"].includes(scope)) {
297717
+ this.printOutput(
297718
+ picocolors18.yellow(
297719
+ "Usage: /workflow export <kebab-name> [local|versioned]"
297720
+ )
297721
+ );
297722
+ return { shouldExit: false, processed: true };
297723
+ }
297724
+ try {
297725
+ const result = await runWorkflowExport(cwd, loop.getSessionId(), {
297726
+ name,
297727
+ scope
297728
+ });
297729
+ loop.invalidateSkillsCache();
297730
+ this.printOutput(`\u2714 Workflow Skill created: ${result.path}`);
297731
+ } catch (error) {
297732
+ this.printOutput(
297733
+ picocolors18.red(
297734
+ `\u2716 ${error instanceof Error ? error.message : String(error)}`
297735
+ )
297736
+ );
297737
+ }
297738
+ return { shouldExit: false, processed: true };
297739
+ }
296404
297740
  if (/^\/review(?:\s|$)/i.test(trimmed)) {
296405
297741
  try {
296406
297742
  const rawArguments = trimmed.replace(/^\/review\b/i, "").trim();
@@ -298152,21 +299488,21 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
298152
299488
  };
298153
299489
 
298154
299490
  // src/runtime/LocalRuntimeState.ts
298155
- import { z as z68 } from "zod";
299491
+ import { z as z69 } from "zod";
298156
299492
  var LOCAL_RUNTIME_STATE_MAX_BYTES = 1048576;
298157
- var LocalSkillsStateSchema = z68.object({
298158
- enabled: z68.boolean().optional(),
298159
- activation: z68.enum(["auto", "explicit"]).optional(),
298160
- maxActive: z68.number().int().min(0).max(8).optional(),
298161
- disabled: z68.array(z68.string().min(1).max(128)).max(1e3).optional()
299493
+ var LocalSkillsStateSchema = z69.object({
299494
+ enabled: z69.boolean().optional(),
299495
+ activation: z69.enum(["auto", "explicit"]).optional(),
299496
+ maxActive: z69.number().int().min(0).max(8).optional(),
299497
+ disabled: z69.array(z69.string().min(1).max(128)).max(1e3).optional()
298162
299498
  });
298163
- var LocalRuntimeStateSchema = z68.object({
298164
- lastSessionId: z68.string().min(1).max(1e3).optional(),
298165
- lastProvider: z68.string().min(1).max(256).optional(),
298166
- lastModel: z68.string().max(512).optional(),
299499
+ var LocalRuntimeStateSchema = z69.object({
299500
+ lastSessionId: z69.string().min(1).max(1e3).optional(),
299501
+ lastProvider: z69.string().min(1).max(256).optional(),
299502
+ lastModel: z69.string().max(512).optional(),
298167
299503
  language: OrbitLanguageSchema.optional(),
298168
- permissionMode: z68.enum(["strict", "normal", "auto", "plan"]).optional(),
298169
- agentMaxIterations: z68.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
299504
+ permissionMode: z69.enum(["strict", "normal", "auto", "plan"]).optional(),
299505
+ agentMaxIterations: z69.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
298170
299506
  skills: LocalSkillsStateSchema.optional()
298171
299507
  });
298172
299508
  function readLocalRuntimeState(cwd) {
@@ -298197,16 +299533,16 @@ function writeLocalRuntimeState(cwd, patch) {
298197
299533
  }
298198
299534
 
298199
299535
  // src/runtime/ReplController.ts
298200
- var AutocompleteRequestSchema = z69.object({
298201
- prefix: z69.string().max(2e4),
298202
- suffix: z69.string().max(2e4),
298203
- windowId: z69.string().max(1e3).optional()
299536
+ var AutocompleteRequestSchema = z70.object({
299537
+ prefix: z70.string().max(2e4),
299538
+ suffix: z70.string().max(2e4),
299539
+ windowId: z70.string().max(1e3).optional()
298204
299540
  });
298205
299541
  var AUTOCOMPLETE_BODY_LIMIT_BYTES = 1e5;
298206
299542
  var AUTOCOMPLETE_MAX_CONCURRENCY = 4;
298207
- var AutocompleteEndpointSchema = z69.object({
298208
- port: z69.number().int().min(1).max(65535),
298209
- token: z69.string().min(32).max(256)
299543
+ var AutocompleteEndpointSchema = z70.object({
299544
+ port: z70.number().int().min(1).max(65535),
299545
+ token: z70.string().min(32).max(256)
298210
299546
  });
298211
299547
  function getRunOutcomeMessage2(outcome) {
298212
299548
  if (!outcome || outcome.status === "completed") return void 0;
@@ -299246,36 +300582,36 @@ function isRecord8(value) {
299246
300582
  }
299247
300583
 
299248
300584
  // src/commands/LSPServer.ts
299249
- import { z as z70 } from "zod";
300585
+ import { z as z71 } from "zod";
299250
300586
  var MAX_LSP_HEADER_BYTES = 8 * 1024;
299251
300587
  var MAX_LSP_BODY_BYTES = 8 * 1024 * 1024;
299252
- var JsonRpcIdSchema = z70.union([z70.string(), z70.number(), z70.null()]);
299253
- var JSONRPCMessageSchema = z70.object({
299254
- jsonrpc: z70.literal("2.0"),
300588
+ var JsonRpcIdSchema = z71.union([z71.string(), z71.number(), z71.null()]);
300589
+ var JSONRPCMessageSchema = z71.object({
300590
+ jsonrpc: z71.literal("2.0"),
299255
300591
  id: JsonRpcIdSchema.optional(),
299256
- method: z70.string().min(1).max(512),
299257
- params: z70.unknown().optional()
300592
+ method: z71.string().min(1).max(512),
300593
+ params: z71.unknown().optional()
299258
300594
  }).strict();
299259
- var TextDocumentIdentifierSchema = z70.object({
299260
- uri: z70.string().min(1).max(16384)
300595
+ var TextDocumentIdentifierSchema = z71.object({
300596
+ uri: z71.string().min(1).max(16384)
299261
300597
  });
299262
- var DidOpenParamsSchema = z70.object({
300598
+ var DidOpenParamsSchema = z71.object({
299263
300599
  textDocument: TextDocumentIdentifierSchema.extend({
299264
- text: z70.string().max(MAX_LSP_BODY_BYTES)
300600
+ text: z71.string().max(MAX_LSP_BODY_BYTES)
299265
300601
  }).passthrough()
299266
300602
  });
299267
- var DidChangeParamsSchema = z70.object({
300603
+ var DidChangeParamsSchema = z71.object({
299268
300604
  textDocument: TextDocumentIdentifierSchema,
299269
- contentChanges: z70.array(z70.object({ text: z70.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
300605
+ contentChanges: z71.array(z71.object({ text: z71.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
299270
300606
  });
299271
- var DidCloseParamsSchema = z70.object({
300607
+ var DidCloseParamsSchema = z71.object({
299272
300608
  textDocument: TextDocumentIdentifierSchema
299273
300609
  });
299274
- var CompletionParamsSchema = z70.object({
300610
+ var CompletionParamsSchema = z71.object({
299275
300611
  textDocument: TextDocumentIdentifierSchema,
299276
- position: z70.object({
299277
- line: z70.number().int().nonnegative(),
299278
- character: z70.number().int().nonnegative()
300612
+ position: z71.object({
300613
+ line: z71.number().int().nonnegative(),
300614
+ character: z71.number().int().nonnegative()
299279
300615
  })
299280
300616
  });
299281
300617
  var JSONRPCReader = class {
@@ -299521,7 +300857,7 @@ ${completion}
299521
300857
  );
299522
300858
  }
299523
300859
  } catch (error) {
299524
- if (error instanceof z70.ZodError) {
300860
+ if (error instanceof z71.ZodError) {
299525
300861
  sendError(message2.id, -32602, "Invalid method parameters.");
299526
300862
  return;
299527
300863
  }
@@ -299943,8 +301279,8 @@ async function runMcpLogin(serverName, options = {}) {
299943
301279
 
299944
301280
  // src/commands/skills.ts
299945
301281
  import picocolors24 from "picocolors";
299946
- import { z as z71 } from "zod";
299947
- var SkillDirectoryOverrideSchema = z71.array(z71.string().trim().min(1).max(4096)).min(1).max(50);
301282
+ import { z as z74 } from "zod";
301283
+ var SkillDirectoryOverrideSchema = z74.array(z74.string().trim().min(1).max(4096)).min(1).max(50);
299948
301284
  async function runSkillsCommand(action, options = {}) {
299949
301285
  const cwd = options.cwd ?? process.cwd();
299950
301286
  const config = ConfigLoader.loadSync(cwd);
@@ -300071,10 +301407,10 @@ import {
300071
301407
  } from "fs";
300072
301408
  import { dirname as dirname15, resolve as resolve15 } from "path";
300073
301409
  import { randomUUID as randomUUID14 } from "crypto";
300074
- import { z as z74 } from "zod";
300075
- var TraceOptionsSchema = z74.object({
300076
- full: z74.boolean().default(false),
300077
- out: z74.string().trim().min(1).max(4096).optional()
301410
+ import { z as z75 } from "zod";
301411
+ var TraceOptionsSchema = z75.object({
301412
+ full: z75.boolean().default(false),
301413
+ out: z75.string().trim().min(1).max(4096).optional()
300078
301414
  });
300079
301415
  function runTraceExport(cwd, sessionId, options = {}) {
300080
301416
  const value = TraceOptionsSchema.parse(options);
@@ -300129,16 +301465,16 @@ import { randomUUID as randomUUID15 } from "crypto";
300129
301465
  import { promisify as promisify5 } from "util";
300130
301466
  import picocolors25 from "picocolors";
300131
301467
  import { parse as parseYaml4 } from "yaml";
300132
- import { z as z75 } from "zod";
301468
+ import { z as z76 } from "zod";
300133
301469
  var exec5 = promisify5(execCallback);
300134
301470
  var MAX_SUITE_BYTES = 1024 * 1024;
300135
301471
  var MAX_VERIFICATION_OUTPUT = 4e3;
300136
- var EvalOptionsSchema = z75.object({
300137
- provider: z75.string().trim().min(1).optional(),
300138
- model: z75.string().trim().min(1).optional(),
300139
- task: z75.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
300140
- allowCommands: z75.boolean().default(false),
300141
- json: z75.boolean().default(false)
301472
+ var EvalOptionsSchema = z76.object({
301473
+ provider: z76.string().trim().min(1).optional(),
301474
+ model: z76.string().trim().min(1).optional(),
301475
+ task: z76.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
301476
+ allowCommands: z76.boolean().default(false),
301477
+ json: z76.boolean().default(false)
300142
301478
  });
300143
301479
  async function runEval(cwd, suiteFile, options = {}) {
300144
301480
  const value = EvalOptionsSchema.parse(options);
@@ -300170,6 +301506,9 @@ async function runEval(cwd, suiteFile, options = {}) {
300170
301506
  `eval-${task.id}`.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 60)
300171
301507
  );
300172
301508
  snapshotWorkspaceIntoWorktree(cwd, worktree.path);
301509
+ if (value.allowCommands) {
301510
+ writeAcceptanceVerificationContract(worktree.path, task);
301511
+ }
300173
301512
  const outcome = await runAgent(
300174
301513
  worktree.path,
300175
301514
  task.prompt,
@@ -300182,6 +301521,12 @@ async function runEval(cwd, suiteFile, options = {}) {
300182
301521
  requireApprovalForWrite: false,
300183
301522
  requireApprovalForBash: !value.allowCommands
300184
301523
  },
301524
+ security: {
301525
+ ...DEFAULT_CONFIG.security,
301526
+ // The suite commands were explicitly reviewed and authorized by
301527
+ // --allow-commands, and execute only in this disposable worktree.
301528
+ trustProjectExecutables: value.allowCommands
301529
+ },
300185
301530
  agent: {
300186
301531
  ...DEFAULT_CONFIG.agent,
300187
301532
  // Acceptance tasks commonly include implementation plus their
@@ -300204,6 +301549,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300204
301549
  const sessionId = outcome?.sessionId || void 0;
300205
301550
  let resolvedModels = [];
300206
301551
  let usage2;
301552
+ let reliability;
300207
301553
  let traceFile;
300208
301554
  if (sessionId) {
300209
301555
  const store = new SessionStore(worktree.path);
@@ -300223,6 +301569,23 @@ async function runEval(cwd, suiteFile, options = {}) {
300223
301569
  cacheHitRate: inputTokens > 0 ? Math.min(1, cacheReadTokens / inputTokens) : 0,
300224
301570
  costUsd: trace.session.totalCostEstimate
300225
301571
  };
301572
+ reliability = {
301573
+ attempts: trace.journal?.attempt ?? 0,
301574
+ toolRuns: trace.metrics.toolRuns,
301575
+ toolFailures: trace.metrics.toolFailures,
301576
+ deniedTools: trace.metrics.deniedTools,
301577
+ approvalRequests: trace.toolCalls.filter(
301578
+ (call) => call.permissionDecision === "ask"
301579
+ ).length,
301580
+ compactions: trace.metrics.compactions,
301581
+ resumedCount: trace.metrics.resumedCount,
301582
+ verificationRuns: trace.events.filter(
301583
+ (event) => event.type === "verification_ended"
301584
+ ).length,
301585
+ checkpoints: trace.events.filter(
301586
+ (event) => event.type === "checkpoint_created"
301587
+ ).length
301588
+ };
300226
301589
  traceFile = writeEvaluationTrace(cwd, runId, task.id, trace);
300227
301590
  }
300228
301591
  results.push(
@@ -300230,7 +301593,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300230
301593
  task: {
300231
301594
  ...task,
300232
301595
  provider: task.provider || value.provider,
300233
- model: task.model || value.model
301596
+ model: task.model || value.model,
301597
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300234
301598
  },
300235
301599
  agentStatus: outcome?.status || "failed",
300236
301600
  durationMs: Date.now() - taskStartedAt,
@@ -300238,6 +301602,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300238
301602
  checks,
300239
301603
  resolvedModels,
300240
301604
  usage: usage2,
301605
+ reliability,
300241
301606
  sessionId,
300242
301607
  traceFile
300243
301608
  })
@@ -300248,7 +301613,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300248
301613
  task: {
300249
301614
  ...task,
300250
301615
  provider: task.provider || value.provider,
300251
- model: task.model || value.model
301616
+ model: task.model || value.model,
301617
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300252
301618
  },
300253
301619
  agentStatus: "failed",
300254
301620
  durationMs: Date.now() - taskStartedAt,
@@ -300277,6 +301643,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300277
301643
  passed: passedTasks === results.length,
300278
301644
  passedTasks,
300279
301645
  totalTasks: results.length,
301646
+ summary: buildAcceptanceSummary(results),
300280
301647
  results
300281
301648
  };
300282
301649
  const reportPath = writeEvaluationReport(cwd, runId, report);
@@ -300295,6 +301662,43 @@ async function runEval(cwd, suiteFile, options = {}) {
300295
301662
  if (!report.passed) process.exitCode = 1;
300296
301663
  return report;
300297
301664
  }
301665
+ function buildAcceptanceSummary(results) {
301666
+ const total = results.length;
301667
+ const durations = results.map((result) => result.durationMs).sort((left, right) => left - right);
301668
+ const midpoint = Math.floor(durations.length / 2);
301669
+ const medianDurationMs = durations.length === 0 ? 0 : durations.length % 2 === 1 ? durations[midpoint] : Math.round((durations[midpoint - 1] + durations[midpoint]) / 2);
301670
+ const verificationChecks = results.flatMap((result) => result.checks);
301671
+ const verificationPasses = verificationChecks.filter(
301672
+ (check) => check.passed
301673
+ ).length;
301674
+ const sumUsage = (field) => results.reduce((sum, result) => {
301675
+ const value = result.usage?.[field];
301676
+ return sum + (typeof value === "number" ? value : 0);
301677
+ }, 0);
301678
+ return {
301679
+ completionRate: total > 0 ? results.filter((result) => result.passed).length / total : 0,
301680
+ verificationPassRate: verificationChecks.length > 0 ? verificationPasses / verificationChecks.length : 0,
301681
+ crashOrAbortRate: total > 0 ? results.filter((result) => result.agentStatus !== "completed").length / total : 0,
301682
+ medianDurationMs,
301683
+ totalInputTokens: sumUsage("inputTokens"),
301684
+ totalOutputTokens: sumUsage("outputTokens"),
301685
+ totalCacheReadTokens: sumUsage("cacheReadTokens"),
301686
+ totalApprovalRequests: results.reduce(
301687
+ (sum, result) => sum + (result.reliability?.approvalRequests ?? 0),
301688
+ 0
301689
+ ),
301690
+ totalToolFailures: results.reduce(
301691
+ (sum, result) => sum + (result.reliability?.toolFailures ?? 0),
301692
+ 0
301693
+ ),
301694
+ unintendedFileChangeFindings: results.reduce(
301695
+ (sum, result) => sum + result.failureReasons.filter(
301696
+ (reason) => reason.startsWith("forbidden_file_changed:")
301697
+ ).length,
301698
+ 0
301699
+ )
301700
+ };
301701
+ }
300298
301702
  function loadAcceptanceSuite(cwd, suiteFile) {
300299
301703
  const filePath = resolveSafePath(cwd, suiteFile);
300300
301704
  const stats = lstatSync9(filePath);
@@ -300309,6 +301713,22 @@ function loadAcceptanceSuite(cwd, suiteFile) {
300309
301713
  const raw = filePath.endsWith(".json") ? JSON.parse(text2) : parseYaml4(text2);
300310
301714
  return AcceptanceSuiteSchema.parse(raw);
300311
301715
  }
301716
+ function writeAcceptanceVerificationContract(cwd, task) {
301717
+ if (task.verification.length === 0) return void 0;
301718
+ const suites = Object.fromEntries(
301719
+ task.verification.map((check, index) => [
301720
+ `${String(index + 1).padStart(2, "0")}-${check.name}`,
301721
+ check.command
301722
+ ])
301723
+ );
301724
+ const contract = VerificationContractSchema.parse({
301725
+ suites,
301726
+ maxRepairAttempts: 3
301727
+ });
301728
+ const filePath = resolveSafePath(cwd, join19(".orbit", "verification.json"));
301729
+ writeJsonAtomically2(filePath, contract);
301730
+ return filePath;
301731
+ }
300312
301732
  async function runVerificationChecks(cwd, checks) {
300313
301733
  const results = [];
300314
301734
  for (const check of checks) {
@@ -300486,7 +301906,7 @@ function safeSummary(value) {
300486
301906
  import readline6 from "readline";
300487
301907
  import picocolors26 from "picocolors";
300488
301908
  import { resolve as resolve17 } from "path";
300489
- import { z as z77 } from "zod";
301909
+ import { z as z78 } from "zod";
300490
301910
 
300491
301911
  // src/runtime/CleanupManager.ts
300492
301912
  import {
@@ -300498,10 +301918,10 @@ import {
300498
301918
  } from "fs";
300499
301919
  import { homedir as homedir11 } from "os";
300500
301920
  import { basename as basename6, join as join20, parse as parse5, resolve as resolve16 } from "path";
300501
- import { z as z76 } from "zod";
300502
- var CleanupScopeSchema = z76.enum(["user", "project"]);
301921
+ import { z as z77 } from "zod";
301922
+ var CleanupScopeSchema = z77.enum(["user", "project"]);
300503
301923
  function buildCleanupPlan(options) {
300504
- const scopes = z76.array(CleanupScopeSchema).min(1).parse(options.scopes);
301924
+ const scopes = z77.array(CleanupScopeSchema).min(1).parse(options.scopes);
300505
301925
  const homeDirectory = resolve16(options.homeDirectory ?? homedir11());
300506
301926
  const projectDirectory = resolve16(options.projectDirectory ?? options.cwd);
300507
301927
  const candidates = scopes.map((scope) => ({
@@ -300659,12 +302079,12 @@ function safeInventoryWarning(targetPath, error) {
300659
302079
  }
300660
302080
 
300661
302081
  // src/commands/clean.ts
300662
- var CleanCommandOptionsSchema = z77.object({
300663
- user: z77.boolean().default(false),
300664
- project: z77.union([z77.boolean(), z77.string().min(1).max(4096)]).optional(),
300665
- all: z77.boolean().default(false),
300666
- yes: z77.boolean().default(false),
300667
- json: z77.boolean().default(false)
302082
+ var CleanCommandOptionsSchema = z78.object({
302083
+ user: z78.boolean().default(false),
302084
+ project: z78.union([z78.boolean(), z78.string().min(1).max(4096)]).optional(),
302085
+ all: z78.boolean().default(false),
302086
+ yes: z78.boolean().default(false),
302087
+ json: z78.boolean().default(false)
300668
302088
  }).strict();
300669
302089
  async function runClean(cwd, rawOptions, dependencies = {}) {
300670
302090
  const options = CleanCommandOptionsSchema.parse(rawOptions);
@@ -300779,7 +302199,7 @@ async function confirmDeletion(prompt) {
300779
302199
  // src/commands/backup.ts
300780
302200
  import { basename as basename7, resolve as resolve19 } from "path";
300781
302201
  import picocolors27 from "picocolors";
300782
- import { z as z79 } from "zod";
302202
+ import { z as z80 } from "zod";
300783
302203
 
300784
302204
  // src/runtime/ProjectBackup.ts
300785
302205
  import {
@@ -300793,25 +302213,25 @@ import {
300793
302213
  } from "fs";
300794
302214
  import { createHash as createHash10, randomUUID as randomUUID16 } from "crypto";
300795
302215
  import { dirname as dirname17, isAbsolute as isAbsolute9, join as join21, relative as relative10, resolve as resolve18, sep as sep2 } from "path";
300796
- import { z as z78 } from "zod";
302216
+ import { z as z79 } from "zod";
300797
302217
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
300798
302218
  var MAX_SERIALIZED_BACKUP_BYTES = 96 * 1024 * 1024;
300799
302219
  var MAX_BACKUP_FILES = 1e4;
300800
302220
  var MAX_BACKUP_TREE_ENTRIES = 5e4;
300801
302221
  var MAX_BACKUP_TREE_DEPTH = 64;
300802
302222
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
300803
- var BackupFileSchema = z78.object({
300804
- path: z78.string().min(1).max(4096),
300805
- size: z78.number().int().min(0).max(MAX_BACKUP_BYTES),
300806
- sha256: z78.string().regex(SHA256_PATTERN),
300807
- content: z78.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
302223
+ var BackupFileSchema = z79.object({
302224
+ path: z79.string().min(1).max(4096),
302225
+ size: z79.number().int().min(0).max(MAX_BACKUP_BYTES),
302226
+ sha256: z79.string().regex(SHA256_PATTERN),
302227
+ content: z79.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
300808
302228
  });
300809
- var ProjectBackupBundleSchema = z78.object({
300810
- schemaVersion: z78.literal(1),
300811
- kind: z78.literal("orbit-project-backup"),
300812
- createdAt: z78.string().datetime(),
300813
- sourceName: z78.string().min(1).max(512),
300814
- files: z78.array(BackupFileSchema).max(MAX_BACKUP_FILES)
302229
+ var ProjectBackupBundleSchema = z79.object({
302230
+ schemaVersion: z79.literal(1),
302231
+ kind: z79.literal("orbit-project-backup"),
302232
+ createdAt: z79.string().datetime(),
302233
+ sourceName: z79.string().min(1).max(512),
302234
+ files: z79.array(BackupFileSchema).max(MAX_BACKUP_FILES)
300815
302235
  }).superRefine((bundle, context) => {
300816
302236
  let totalBytes = 0;
300817
302237
  const seen = /* @__PURE__ */ new Set();
@@ -300819,7 +302239,7 @@ var ProjectBackupBundleSchema = z78.object({
300819
302239
  totalBytes += file.size;
300820
302240
  if (totalBytes > MAX_BACKUP_BYTES) {
300821
302241
  context.addIssue({
300822
- code: z78.ZodIssueCode.custom,
302242
+ code: z79.ZodIssueCode.custom,
300823
302243
  message: `Backup exceeds ${MAX_BACKUP_BYTES} bytes.`
300824
302244
  });
300825
302245
  break;
@@ -300827,14 +302247,14 @@ var ProjectBackupBundleSchema = z78.object({
300827
302247
  const normalized = normalizeBundlePath(file.path);
300828
302248
  if (!normalized || normalized !== file.path) {
300829
302249
  context.addIssue({
300830
- code: z78.ZodIssueCode.custom,
302250
+ code: z79.ZodIssueCode.custom,
300831
302251
  message: `Unsafe backup path: ${file.path}`
300832
302252
  });
300833
302253
  continue;
300834
302254
  }
300835
302255
  if (seen.has(normalized.toLowerCase())) {
300836
302256
  context.addIssue({
300837
- code: z78.ZodIssueCode.custom,
302257
+ code: z79.ZodIssueCode.custom,
300838
302258
  message: `Duplicate backup path: ${file.path}`
300839
302259
  });
300840
302260
  }
@@ -301067,9 +302487,9 @@ function formatBytes2(bytes) {
301067
302487
  }
301068
302488
 
301069
302489
  // src/commands/backup.ts
301070
- var BackupOptionsSchema = z79.object({
301071
- output: z79.string().min(1).max(4096).optional(),
301072
- json: z79.boolean().default(false)
302490
+ var BackupOptionsSchema = z80.object({
302491
+ output: z80.string().min(1).max(4096).optional(),
302492
+ json: z80.boolean().default(false)
301073
302493
  }).strict();
301074
302494
  function runBackupCreate(cwd, rawOptions = {}) {
301075
302495
  const options = BackupOptionsSchema.parse(rawOptions);
@@ -301169,21 +302589,21 @@ import {
301169
302589
  import { randomUUID as randomUUID17 } from "crypto";
301170
302590
  import { dirname as dirname18, isAbsolute as isAbsolute10, join as join26, relative as relative11, resolve as resolve20, sep as sep3 } from "path";
301171
302591
  import { homedir as homedir12 } from "os";
301172
- import { z as z80 } from "zod";
301173
- var InstalledExtensionSchema2 = z80.object({
302592
+ import { z as z81 } from "zod";
302593
+ var InstalledExtensionSchema2 = z81.object({
301174
302594
  id: InstalledExtensionIdSchema,
301175
- displayName: z80.string().min(1).max(256),
301176
- version: z80.string().min(1).max(128),
301177
- digest: z80.string().regex(/^[a-f0-9]{64}$/),
302595
+ displayName: z81.string().min(1).max(256),
302596
+ version: z81.string().min(1).max(128),
302597
+ digest: z81.string().regex(/^[a-f0-9]{64}$/),
301178
302598
  digestAlgorithm: ExtensionDigestAlgorithmSchema.default("sha256-v1"),
301179
- installedAt: z80.string().datetime(),
301180
- trusted: z80.boolean(),
301181
- path: z80.string().min(1).max(4096),
301182
- manifestFile: z80.string().min(1).max(4096).default("extension.yaml")
302599
+ installedAt: z81.string().datetime(),
302600
+ trusted: z81.boolean(),
302601
+ path: z81.string().min(1).max(4096),
302602
+ manifestFile: z81.string().min(1).max(4096).default("extension.yaml")
301183
302603
  });
301184
- var ExtensionRegistrySchema2 = z80.object({
301185
- schemaVersion: z80.literal(1),
301186
- extensions: z80.array(InstalledExtensionSchema2).max(500).default([])
302604
+ var ExtensionRegistrySchema2 = z81.object({
302605
+ schemaVersion: z81.literal(1),
302606
+ extensions: z81.array(InstalledExtensionSchema2).max(500).default([])
301187
302607
  });
301188
302608
  var ExtensionManager = class {
301189
302609
  orbitDir;
@@ -301859,6 +303279,15 @@ program.command("trace").description("export a redacted, versioned session audit
301859
303279
  });
301860
303280
  if (output) console.log(`Trace exported to ${output}`);
301861
303281
  });
303282
+ program.command("workflow-export").description("compile a redacted session trace into a reviewable Skill").argument("<session>", "session id to compile").requiredOption("--name <name>", "lowercase kebab-case Skill name").option("--description <text>", "short reusable workflow description").option("--scope <scope>", "local or versioned", "local").option("--json", "print a machine-readable result").action(async (session, options) => {
303283
+ const result = await runWorkflowExport(process.cwd(), session, {
303284
+ name: options.name,
303285
+ description: options.description,
303286
+ scope: options.scope,
303287
+ json: !!options.json
303288
+ });
303289
+ if (!options.json) console.log(`\u2714 Workflow Skill created: ${result.path}`);
303290
+ });
301862
303291
  program.command("lsp").description("start the local LSP autocomplete server").action(async () => {
301863
303292
  await runLSPServer(process.cwd());
301864
303293
  });