@orbit-build/cli 0.8.6 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +4 -0
  2. package/dist/index.js +1278 -170
  3. package/package.json +1 -1
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({
@@ -243758,7 +243792,13 @@ var AnthropicCompatibleProvider = class {
243758
243792
  signal: chatSignal,
243759
243793
  timeout: this.options.requestTimeoutMs
243760
243794
  },
243761
- this.options.maxRetries ?? (this.isOfficialDeepSeekEndpoint() ? 0 : 2)
243795
+ Math.max(
243796
+ 0,
243797
+ Math.min(
243798
+ 5,
243799
+ input.retryBudget ?? this.options.maxRetries ?? (this.isOfficialDeepSeekEndpoint() ? 0 : 2)
243800
+ )
243801
+ )
243762
243802
  );
243763
243803
  } catch (error) {
243764
243804
  const sanitized = sanitizeProviderError(error, [key]);
@@ -244805,7 +244845,10 @@ async function* chatWithDeepSeekResponses(input, options) {
244805
244845
  signal: controller.signal,
244806
244846
  timeout: options.runtime.requestTimeoutMs
244807
244847
  },
244808
- options.runtime.maxRetries ?? 0
244848
+ Math.max(
244849
+ 0,
244850
+ Math.min(5, input.retryBudget ?? options.runtime.maxRetries ?? 0)
244851
+ )
244809
244852
  );
244810
244853
  if (!response.ok) {
244811
244854
  const detail = await readProviderErrorText(response);
@@ -245500,7 +245543,13 @@ ${jsonInstruction}`;
245500
245543
  signal: chatSignal,
245501
245544
  timeout: this.options.requestTimeoutMs
245502
245545
  },
245503
- this.options.maxRetries ?? (isOfficialDeepSeek ? 0 : 2)
245546
+ Math.max(
245547
+ 0,
245548
+ Math.min(
245549
+ 5,
245550
+ input.retryBudget ?? this.options.maxRetries ?? (isOfficialDeepSeek ? 0 : 2)
245551
+ )
245552
+ )
245504
245553
  );
245505
245554
  } catch (error) {
245506
245555
  const sanitized = sanitizeProviderError(error, [key]);
@@ -252155,6 +252204,7 @@ var JSVectorStore = class {
252155
252204
  loaded = false;
252156
252205
  loading = null;
252157
252206
  cacheState = "uninitialized";
252207
+ persistenceError;
252158
252208
  async addDocuments(docs, persist = true) {
252159
252209
  if (!this.loaded) {
252160
252210
  await this.load();
@@ -252261,7 +252311,13 @@ var JSVectorStore = class {
252261
252311
  await fsPromises2.rm(tmpPath, { force: true }).catch(() => void 0);
252262
252312
  }
252263
252313
  this.cacheState = "valid";
252264
- } catch {
252314
+ this.persistenceError = void 0;
252315
+ } catch (error) {
252316
+ this.cacheState = "invalid";
252317
+ this.persistenceError = error instanceof Error ? error.message : String(error);
252318
+ throw new Error(
252319
+ `Failed to persist the Orbit vector cache: ${this.persistenceError}`
252320
+ );
252265
252321
  }
252266
252322
  }
252267
252323
  async load() {
@@ -252337,6 +252393,10 @@ var JSVectorStore = class {
252337
252393
  hasValidCache() {
252338
252394
  return this.cacheState === "valid";
252339
252395
  }
252396
+ /** Returns the last persistence failure without exposing filesystem details. */
252397
+ getPersistenceError() {
252398
+ return this.persistenceError;
252399
+ }
252340
252400
  initializeCachePath() {
252341
252401
  if (this.cachePathInitialized) return;
252342
252402
  this.dbPath = getOrbitCachePath(this.cwd, "vector_store.json");
@@ -255029,7 +255089,7 @@ import { z as z83 } from "zod";
255029
255089
  import picocolors3 from "picocolors";
255030
255090
  import path7 from "path";
255031
255091
  import fs32 from "fs";
255032
- import { randomUUID as randomUUID52 } from "crypto";
255092
+ import { randomUUID as randomUUID62 } from "crypto";
255033
255093
  import { exec as exec2, execFile as execFile3 } from "child_process";
255034
255094
  import { promisify as promisify3 } from "util";
255035
255095
  import { z as z46 } from "zod";
@@ -255414,6 +255474,12 @@ var MCPResponseSchema = z36.object({
255414
255474
  }).refine((message2) => message2.result !== void 0 || message2.error, {
255415
255475
  message: "MCP response requires a result or error."
255416
255476
  });
255477
+ var MCP_CATALOG_KINDS = ["tools", "resources", "prompts"];
255478
+ var MCPNotificationSchema = z36.object({
255479
+ jsonrpc: z36.literal("2.0"),
255480
+ method: z36.string().min(1).max(256),
255481
+ params: z36.record(z36.unknown()).optional()
255482
+ });
255417
255483
  async function collectMcpPaginatedItems(options) {
255418
255484
  try {
255419
255485
  return await collectMcpPaginationAttempt(options);
@@ -255547,6 +255613,8 @@ var MCPClient = class {
255547
255613
  resources: false,
255548
255614
  prompts: false
255549
255615
  };
255616
+ catalogListeners = /* @__PURE__ */ new Set();
255617
+ lastError;
255550
255618
  get effectiveRequestTimeoutMs() {
255551
255619
  return this.requestTimeoutMs ?? MCP_REQUEST_TIMEOUT_MS;
255552
255620
  }
@@ -255567,6 +255635,7 @@ var MCPClient = class {
255567
255635
  this.stdoutBuffer = Buffer.alloc(0);
255568
255636
  this.stderrTail = "";
255569
255637
  this.negotiatedProtocol = void 0;
255638
+ this.lastError = void 0;
255570
255639
  child.on("error", (error) => {
255571
255640
  this.cleanup(
255572
255641
  new Error(
@@ -255653,6 +255722,17 @@ var MCPClient = class {
255653
255722
  getNegotiatedProtocol() {
255654
255723
  return this.negotiatedProtocol ? { ...this.negotiatedProtocol } : void 0;
255655
255724
  }
255725
+ onCatalogChanged(listener) {
255726
+ this.catalogListeners.add(listener);
255727
+ return () => this.catalogListeners.delete(listener);
255728
+ }
255729
+ getRuntimeHealth() {
255730
+ return {
255731
+ connected: this.isConnected,
255732
+ recoveryCount: 0,
255733
+ ...this.lastError ? { lastError: this.lastError } : {}
255734
+ };
255735
+ }
255656
255736
  /** List resources when the server advertises them; empty list otherwise. */
255657
255737
  async listResources(abortSignal) {
255658
255738
  if (!this.serverCapabilities.resources) return [];
@@ -255902,12 +255982,26 @@ var MCPClient = class {
255902
255982
  }
255903
255983
  }
255904
255984
  handleIncomingMessage(line) {
255905
- let response;
255985
+ let raw;
255906
255986
  try {
255907
- response = MCPResponseSchema.parse(JSON.parse(line));
255987
+ raw = JSON.parse(line);
255908
255988
  } catch {
255909
255989
  return;
255910
255990
  }
255991
+ const notification = MCPNotificationSchema.safeParse(raw);
255992
+ if (notification.success && typeof raw === "object" && raw !== null && !("id" in raw)) {
255993
+ const kinds = catalogKindsFromNotification(
255994
+ notification.data.method,
255995
+ notification.data.params
255996
+ );
255997
+ if (kinds.length > 0) {
255998
+ for (const listener of this.catalogListeners) listener(kinds);
255999
+ }
256000
+ return;
256001
+ }
256002
+ const parsed = MCPResponseSchema.safeParse(raw);
256003
+ if (!parsed.success) return;
256004
+ const response = parsed.data;
255911
256005
  const pending = this.pendingRequests.get(response.id);
255912
256006
  if (!pending) return;
255913
256007
  clearTimeout(pending.timeout);
@@ -255927,6 +256021,7 @@ var MCPClient = class {
255927
256021
  }
255928
256022
  cleanup(error) {
255929
256023
  this.isConnected = false;
256024
+ this.lastError = safeMessage(error);
255930
256025
  for (const pending of this.pendingRequests.values()) {
255931
256026
  clearTimeout(pending.timeout);
255932
256027
  pending.removeAbortListener?.();
@@ -255935,6 +256030,24 @@ var MCPClient = class {
255935
256030
  this.pendingRequests.clear();
255936
256031
  }
255937
256032
  };
256033
+ function catalogKindsFromNotification(method, params) {
256034
+ const direct = {
256035
+ "notifications/tools/list_changed": "tools",
256036
+ "notifications/resources/list_changed": "resources",
256037
+ "notifications/prompts/list_changed": "prompts"
256038
+ };
256039
+ if (direct[method]) return [direct[method]];
256040
+ if (method !== "notifications/list_changed" && method !== "notifications/catalog_changed") {
256041
+ return [];
256042
+ }
256043
+ const candidates = [
256044
+ params?.collection,
256045
+ ...Array.isArray(params?.collections) ? params.collections : []
256046
+ ];
256047
+ return [...new Set(candidates)].filter(
256048
+ (value) => typeof value === "string" && MCP_CATALOG_KINDS.includes(value)
256049
+ );
256050
+ }
255938
256051
  function waitForChildExit(child, timeoutMs) {
255939
256052
  if (child.exitCode !== null || child.signalCode !== null) {
255940
256053
  return Promise.resolve(true);
@@ -256136,6 +256249,8 @@ var StreamableHttpMCPClient = class {
256136
256249
  started = false;
256137
256250
  negotiatedProtocol;
256138
256251
  reinitializePromise;
256252
+ recoveryCount = 0;
256253
+ lastError;
256139
256254
  mirroredToolParameters = /* @__PURE__ */ new Map();
256140
256255
  protocolWarnings = [];
256141
256256
  serverCapabilities = {
@@ -256201,6 +256316,13 @@ var StreamableHttpMCPClient = class {
256201
256316
  getProtocolWarnings() {
256202
256317
  return [...this.protocolWarnings];
256203
256318
  }
256319
+ getRuntimeHealth() {
256320
+ return {
256321
+ connected: this.started,
256322
+ recoveryCount: this.recoveryCount,
256323
+ ...this.lastError ? { lastError: this.lastError } : {}
256324
+ };
256325
+ }
256204
256326
  /** List resources when the server advertises them; empty list otherwise. */
256205
256327
  async listResources(abortSignal) {
256206
256328
  if (!this.serverCapabilities.resources) return [];
@@ -256318,6 +256440,8 @@ var StreamableHttpMCPClient = class {
256318
256440
  );
256319
256441
  } catch (error) {
256320
256442
  if (error instanceof McpSessionExpiredError && allowSessionRecovery && this.started && this.negotiatedProtocol?.era === "legacy" && method !== "initialize") {
256443
+ this.recoveryCount += 1;
256444
+ this.lastError = safeMessage2(error);
256321
256445
  await this.reinitialize(abortSignal);
256322
256446
  if ("cursor" in params) {
256323
256447
  throw new McpPaginationSessionResetError(this.serverName);
@@ -256349,6 +256473,7 @@ var StreamableHttpMCPClient = class {
256349
256473
  if (modernVersion && method !== "server/discover") {
256350
256474
  assertCompleteModernResult(parsed.data.result, method);
256351
256475
  }
256476
+ this.lastError = void 0;
256352
256477
  return parsed.data.result;
256353
256478
  }
256354
256479
  async negotiateProtocol(abortSignal) {
@@ -260309,7 +260434,7 @@ var AgentRunStore = class {
260309
260434
  * The returned cleanup callback is idempotent and the timer never keeps the
260310
260435
  * process alive on its own.
260311
260436
  */
260312
- startLeaseHeartbeat(runId) {
260437
+ startLeaseHeartbeat(runId, options = {}) {
260313
260438
  this.renewLease(runId);
260314
260439
  let active = true;
260315
260440
  const heartbeat = setInterval(
@@ -260317,9 +260442,10 @@ var AgentRunStore = class {
260317
260442
  if (!active) return;
260318
260443
  try {
260319
260444
  this.renewLease(runId);
260320
- } catch {
260445
+ } catch (error) {
260321
260446
  active = false;
260322
260447
  clearInterval(heartbeat);
260448
+ options.onLeaseLost?.(error);
260323
260449
  }
260324
260450
  },
260325
260451
  Math.max(1e3, Math.floor(this.leaseDurationMs / 3))
@@ -260503,6 +260629,7 @@ function isNodeError2(error) {
260503
260629
  import { randomUUID as randomUUID42 } from "crypto";
260504
260630
  import path52 from "path";
260505
260631
  import { z as z73 } from "zod";
260632
+ import { randomUUID as randomUUID52 } from "crypto";
260506
260633
  import { z as z103 } from "zod";
260507
260634
  import { z as z93 } from "zod";
260508
260635
  import { z as z112 } from "zod";
@@ -261044,7 +261171,7 @@ function compactHistoryMessages(sourceHistory, options) {
261044
261171
  }
261045
261172
  var SEMANTIC_SUMMARY_MIN_DIGEST_CHARS = 400;
261046
261173
  var SEMANTIC_SUMMARY_DIGEST_TOKEN_BUDGET = 6e3;
261047
- async function buildSemanticCompactionSummary(dropped, provider, fastModel) {
261174
+ async function buildSemanticCompactionSummary(dropped, provider, fastModel, options = {}) {
261048
261175
  if (!fastModel || dropped.length === 0) return null;
261049
261176
  const digest = buildDroppedHistoryDigest(dropped);
261050
261177
  if (digest.length < SEMANTIC_SUMMARY_MIN_DIGEST_CHARS) return null;
@@ -261076,9 +261203,13 @@ async function buildSemanticCompactionSummary(dropped, provider, fastModel) {
261076
261203
  ],
261077
261204
  tools: [],
261078
261205
  thinking: { enabled: false },
261079
- maxTokens: 1024
261206
+ maxTokens: 1024,
261207
+ abortSignal: options.abortSignal,
261208
+ retryBudget: 0
261080
261209
  })) {
261210
+ if (options.abortSignal?.aborted) return null;
261081
261211
  if (event.type === "text_delta") text2 += event.text;
261212
+ if (event.type === "usage") options.onUsage?.(event.usage);
261082
261213
  if (event.type === "error") return null;
261083
261214
  }
261084
261215
  const cleaned = text2.trim();
@@ -261836,6 +261967,25 @@ var VerificationEndedEventSchema = z38.object({
261836
261967
  results: z38.unknown().optional()
261837
261968
  })
261838
261969
  });
261970
+ var HookStartedEventSchema = z38.object({
261971
+ type: z38.literal("hook_started"),
261972
+ payload: z38.object({
261973
+ hookId: z38.string(),
261974
+ event: LifecycleHookEventSchema,
261975
+ legacy: z38.boolean()
261976
+ })
261977
+ });
261978
+ var HookCompletedEventSchema = z38.object({
261979
+ type: z38.literal("hook_completed"),
261980
+ payload: z38.object({
261981
+ hookId: z38.string(),
261982
+ event: LifecycleHookEventSchema,
261983
+ success: z38.boolean(),
261984
+ durationMs: z38.number().nonnegative(),
261985
+ action: z38.enum(["continue", "warn", "blocked", "ignored"]),
261986
+ error: z38.string().optional()
261987
+ })
261988
+ });
261839
261989
  var SessionForkEventSchema = z38.object({
261840
261990
  type: z38.literal("session_fork"),
261841
261991
  payload: z38.object({
@@ -261902,6 +262052,8 @@ var OrbitEventSchema = z38.discriminatedUnion("type", [
261902
262052
  CheckpointCreatedEventSchema,
261903
262053
  VerificationStartedEventSchema,
261904
262054
  VerificationEndedEventSchema,
262055
+ HookStartedEventSchema,
262056
+ HookCompletedEventSchema,
261905
262057
  SessionForkEventSchema,
261906
262058
  SessionEndedEventSchema,
261907
262059
  InfoEventSchema,
@@ -262994,6 +263146,10 @@ var McpRuntimeManager = class {
262994
263146
  clients = [];
262995
263147
  registeredTools = /* @__PURE__ */ new Map();
262996
263148
  promptsByServer = /* @__PURE__ */ new Map();
263149
+ runtimes = /* @__PURE__ */ new Map();
263150
+ healthByServer = /* @__PURE__ */ new Map();
263151
+ pendingRefreshKinds = /* @__PURE__ */ new Map();
263152
+ refreshTimers = /* @__PURE__ */ new Map();
262997
263153
  async start(servers, report) {
262998
263154
  await this.stop();
262999
263155
  const result = {
@@ -263050,6 +263206,27 @@ var McpRuntimeManager = class {
263050
263206
  report
263051
263207
  );
263052
263208
  this.clients.push(client);
263209
+ const runtime = {
263210
+ serverName,
263211
+ config: serverConfig,
263212
+ client,
263213
+ report,
263214
+ toolNames: new Set(registeredForClient)
263215
+ };
263216
+ runtime.unsubscribeCatalog = client.onCatalogChanged?.((kinds) => {
263217
+ this.scheduleCatalogRefresh(serverName, kinds);
263218
+ });
263219
+ this.runtimes.set(serverName, runtime);
263220
+ const runtimeHealth = client.getRuntimeHealth?.();
263221
+ this.healthByServer.set(serverName, {
263222
+ serverName,
263223
+ status: "healthy",
263224
+ connected: runtimeHealth?.connected ?? true,
263225
+ registeredTools: runtime.toolNames.size,
263226
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263227
+ ...protocol ? { protocol: protocol.version } : {},
263228
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263229
+ });
263053
263230
  result.startedServers += 1;
263054
263231
  } catch (error) {
263055
263232
  for (const toolName of registeredForClient) {
@@ -263063,6 +263240,14 @@ var McpRuntimeManager = class {
263063
263240
  this.promptsByServer.delete(serverName);
263064
263241
  await client?.stop().catch(() => void 0);
263065
263242
  const message2 = safeMcpRuntimeMessage(error);
263243
+ this.healthByServer.set(serverName, {
263244
+ serverName,
263245
+ status: "failed",
263246
+ connected: false,
263247
+ registeredTools: 0,
263248
+ recoveryCount: 0,
263249
+ lastError: message2
263250
+ });
263066
263251
  result.failures.push({ serverName, message: message2 });
263067
263252
  report(` \u2716 Failed to start MCP server "${serverName}": ${message2}`);
263068
263253
  }
@@ -263079,6 +263264,31 @@ var McpRuntimeManager = class {
263079
263264
  }
263080
263265
  return descriptors2;
263081
263266
  }
263267
+ /** Return a stable, credential-redacted snapshot for doctor and UI surfaces. */
263268
+ listHealth() {
263269
+ return [...this.healthByServer.values()].map((health) => {
263270
+ const runtimeHealth = this.runtimes.get(health.serverName)?.client.getRuntimeHealth?.();
263271
+ return {
263272
+ ...health,
263273
+ status: runtimeHealth && !runtimeHealth.connected ? "degraded" : health.status,
263274
+ connected: runtimeHealth?.connected ?? health.connected,
263275
+ recoveryCount: runtimeHealth?.recoveryCount ?? health.recoveryCount,
263276
+ ...runtimeHealth?.lastError ? { lastError: safeMcpRuntimeMessage(runtimeHealth.lastError) } : {}
263277
+ };
263278
+ }).sort((left, right) => left.serverName.localeCompare(right.serverName));
263279
+ }
263280
+ /** Refresh live catalogs without restarting healthy MCP processes. */
263281
+ async refreshCatalogs(serverName) {
263282
+ const runtimes = serverName ? [this.runtimes.get(serverName)].filter(
263283
+ (runtime) => Boolean(runtime)
263284
+ ) : [...this.runtimes.values()];
263285
+ await Promise.all(
263286
+ runtimes.map(
263287
+ (runtime) => this.refreshServerCatalog(runtime, ["tools", "resources", "prompts"])
263288
+ )
263289
+ );
263290
+ return this.listHealth();
263291
+ }
263082
263292
  /** Resolve one discovered prompt into expanded prompt text. */
263083
263293
  async expandPrompt(serverName, promptName, args) {
263084
263294
  const entry = this.promptsByServer.get(serverName);
@@ -263091,11 +263301,19 @@ var McpRuntimeManager = class {
263091
263301
  return entry.client.getPrompt(prompt.name, args);
263092
263302
  }
263093
263303
  async stop() {
263304
+ for (const timer of this.refreshTimers.values()) clearTimeout(timer);
263305
+ this.refreshTimers.clear();
263306
+ this.pendingRefreshKinds.clear();
263307
+ for (const runtime of this.runtimes.values()) {
263308
+ runtime.unsubscribeCatalog?.();
263309
+ }
263310
+ this.runtimes.clear();
263094
263311
  for (const [toolName, tool] of this.registeredTools) {
263095
263312
  this.registry.unregister(toolName, tool);
263096
263313
  }
263097
263314
  this.registeredTools.clear();
263098
263315
  this.promptsByServer.clear();
263316
+ this.healthByServer.clear();
263099
263317
  const clients = this.clients.splice(0);
263100
263318
  await Promise.allSettled(clients.map((client) => client.stop()));
263101
263319
  }
@@ -263133,12 +263351,182 @@ var McpRuntimeManager = class {
263133
263351
  return;
263134
263352
  }
263135
263353
  const prompts = await client.listPrompts();
263354
+ this.promptsByServer.delete(serverName);
263136
263355
  if (!prompts.length) return;
263137
263356
  this.promptsByServer.set(serverName, { client, prompts });
263138
263357
  report(
263139
263358
  ` \u2714 Discovered ${prompts.length} MCP prompt${prompts.length === 1 ? "" : "s"} on "${serverName}"`
263140
263359
  );
263141
263360
  }
263361
+ scheduleCatalogRefresh(serverName, kinds) {
263362
+ const runtime = this.runtimes.get(serverName);
263363
+ if (!runtime) return;
263364
+ const pending = this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set();
263365
+ for (const kind of kinds) pending.add(kind);
263366
+ this.pendingRefreshKinds.set(serverName, pending);
263367
+ if (this.refreshTimers.has(serverName)) return;
263368
+ const timer = setTimeout(() => {
263369
+ this.refreshTimers.delete(serverName);
263370
+ const nextKinds = [
263371
+ ...this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set()
263372
+ ];
263373
+ this.pendingRefreshKinds.delete(serverName);
263374
+ void this.refreshServerCatalog(runtime, nextKinds);
263375
+ }, 100);
263376
+ timer.unref?.();
263377
+ this.refreshTimers.set(serverName, timer);
263378
+ }
263379
+ async refreshServerCatalog(runtime, kinds) {
263380
+ const current = this.healthByServer.get(runtime.serverName);
263381
+ this.healthByServer.set(runtime.serverName, {
263382
+ ...current ?? {
263383
+ serverName: runtime.serverName,
263384
+ connected: true,
263385
+ registeredTools: runtime.toolNames.size,
263386
+ recoveryCount: 0
263387
+ },
263388
+ status: "refreshing"
263389
+ });
263390
+ try {
263391
+ if (kinds.includes("tools") && runtime.client.listTools) {
263392
+ await this.refreshTools(runtime, await runtime.client.listTools());
263393
+ }
263394
+ if (kinds.includes("resources")) {
263395
+ await this.refreshResourceTool(runtime);
263396
+ }
263397
+ if (kinds.includes("prompts")) {
263398
+ await this.captureServerPrompts(
263399
+ runtime.serverName,
263400
+ runtime.config,
263401
+ runtime.client,
263402
+ runtime.report
263403
+ );
263404
+ }
263405
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263406
+ this.healthByServer.set(runtime.serverName, {
263407
+ serverName: runtime.serverName,
263408
+ status: "healthy",
263409
+ connected: runtimeHealth?.connected ?? true,
263410
+ registeredTools: runtime.toolNames.size,
263411
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263412
+ ...runtime.client.getNegotiatedProtocol?.()?.version ? { protocol: runtime.client.getNegotiatedProtocol?.()?.version } : {},
263413
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263414
+ });
263415
+ runtime.report(
263416
+ ` \u2714 Refreshed MCP catalog for "${runtime.serverName}" (${kinds.join(", ")})`
263417
+ );
263418
+ } catch (error) {
263419
+ const message2 = safeMcpRuntimeMessage(error);
263420
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263421
+ this.healthByServer.set(runtime.serverName, {
263422
+ serverName: runtime.serverName,
263423
+ status: "degraded",
263424
+ connected: runtimeHealth?.connected ?? true,
263425
+ registeredTools: runtime.toolNames.size,
263426
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263427
+ ...current?.protocol ? { protocol: current.protocol } : {},
263428
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString(),
263429
+ lastError: message2
263430
+ });
263431
+ runtime.report(
263432
+ ` \u26A0\uFE0F MCP catalog refresh failed for "${runtime.serverName}": ${message2}`
263433
+ );
263434
+ }
263435
+ }
263436
+ async refreshTools(runtime, definitions) {
263437
+ const resourceToolName = createMcpToolName(
263438
+ runtime.serverName,
263439
+ "read_resource"
263440
+ );
263441
+ const oldNames = [...runtime.toolNames].filter(
263442
+ (name) => name !== resourceToolName
263443
+ );
263444
+ const oldTools = new Map(
263445
+ oldNames.flatMap((name) => {
263446
+ const tool = this.registeredTools.get(name);
263447
+ return tool ? [[name, tool]] : [];
263448
+ })
263449
+ );
263450
+ const replacements = definitions.map((definition) => {
263451
+ const risk = runtime.config.tools?.[definition.name]?.risk ?? "execute";
263452
+ return new DynamicMCPTool(
263453
+ runtime.serverName,
263454
+ definition,
263455
+ risk,
263456
+ runtime.client
263457
+ );
263458
+ });
263459
+ const replacementNames = /* @__PURE__ */ new Set();
263460
+ for (const tool of replacements) {
263461
+ if (replacementNames.has(tool.name)) {
263462
+ throw new Error(`MCP refresh produced duplicate tool ${tool.name}.`);
263463
+ }
263464
+ replacementNames.add(tool.name);
263465
+ const collision = this.registry.get(tool.name);
263466
+ if (collision && !oldTools.has(tool.name)) {
263467
+ throw new Error(`MCP refresh collided with tool ${tool.name}.`);
263468
+ }
263469
+ }
263470
+ for (const [name, tool] of oldTools) {
263471
+ this.registry.unregister(name, tool);
263472
+ this.registeredTools.delete(name);
263473
+ runtime.toolNames.delete(name);
263474
+ }
263475
+ const registered = [];
263476
+ try {
263477
+ for (const tool of replacements) {
263478
+ this.registry.register(tool);
263479
+ this.registeredTools.set(tool.name, tool);
263480
+ runtime.toolNames.add(tool.name);
263481
+ registered.push(tool);
263482
+ }
263483
+ } catch (error) {
263484
+ for (const tool of registered) {
263485
+ this.registry.unregister(tool.name, tool);
263486
+ this.registeredTools.delete(tool.name);
263487
+ runtime.toolNames.delete(tool.name);
263488
+ }
263489
+ for (const [name, tool] of oldTools) {
263490
+ this.registry.register(tool);
263491
+ this.registeredTools.set(name, tool);
263492
+ runtime.toolNames.add(name);
263493
+ }
263494
+ throw error;
263495
+ }
263496
+ }
263497
+ async refreshResourceTool(runtime) {
263498
+ const resourceName = createMcpToolName(runtime.serverName, "read_resource");
263499
+ const oldTool = this.registeredTools.get(resourceName);
263500
+ if (oldTool) {
263501
+ this.registry.unregister(resourceName, oldTool);
263502
+ this.registeredTools.delete(resourceName);
263503
+ runtime.toolNames.delete(resourceName);
263504
+ }
263505
+ const result = {
263506
+ startedServers: 1,
263507
+ registeredTools: runtime.toolNames.size,
263508
+ failures: []
263509
+ };
263510
+ const registered = [];
263511
+ try {
263512
+ await this.registerResourceTool(
263513
+ runtime.serverName,
263514
+ runtime.config,
263515
+ runtime.client,
263516
+ registered,
263517
+ result,
263518
+ runtime.report
263519
+ );
263520
+ for (const name of registered) runtime.toolNames.add(name);
263521
+ } catch (error) {
263522
+ if (oldTool) {
263523
+ this.registry.register(oldTool);
263524
+ this.registeredTools.set(resourceName, oldTool);
263525
+ runtime.toolNames.add(resourceName);
263526
+ }
263527
+ throw error;
263528
+ }
263529
+ }
263142
263530
  };
263143
263531
  function safeMcpRuntimeMessage(error) {
263144
263532
  const raw = error instanceof Error ? error.message : String(error);
@@ -263508,6 +263896,113 @@ function parseSearchResultBlocks(content) {
263508
263896
  }
263509
263897
  return results;
263510
263898
  }
263899
+ var WRITE_TOOLS = /* @__PURE__ */ new Set([
263900
+ "write_file",
263901
+ "edit_file",
263902
+ "replace_file_content",
263903
+ "multi_replace_file_content"
263904
+ ]);
263905
+ function selectLifecycleHooks(hooks, event, context) {
263906
+ const configured = hooks.lifecycle?.[event] ?? [];
263907
+ const selected = configured.filter((hook) => matchesLifecycleHook(hook.matcher, event, context)).map((hook) => ({ ...hook, legacy: false }));
263908
+ const isWriteTool = context.toolName ? WRITE_TOOLS.has(context.toolName) : false;
263909
+ if (event === "preToolUse" && isWriteTool && context.filePath && hooks.preEdit) {
263910
+ selected.unshift({
263911
+ command: hooks.preEdit,
263912
+ timeoutMs: 3e4,
263913
+ onFailure: "block",
263914
+ legacy: true
263915
+ });
263916
+ }
263917
+ if (event === "postToolUse" && isWriteTool && context.filePath && hooks.postEdit) {
263918
+ selected.unshift({
263919
+ command: hooks.postEdit,
263920
+ timeoutMs: 3e4,
263921
+ onFailure: "block",
263922
+ legacy: true
263923
+ });
263924
+ }
263925
+ return selected;
263926
+ }
263927
+ function matchesLifecycleHook(matcher, event, context) {
263928
+ if (!matcher) return true;
263929
+ const subject = context.toolName || context.agentRole || context.filePath || context.status || event;
263930
+ return globMatches(matcher, subject);
263931
+ }
263932
+ function buildLifecycleHookEnvironment(event, context) {
263933
+ const safeContext = Object.fromEntries(
263934
+ Object.entries(context).filter(([, value]) => value !== void 0)
263935
+ );
263936
+ const payload = redactSecrets(JSON.stringify(safeContext)).slice(0, 32768);
263937
+ return {
263938
+ ORBIT_HOOK_EVENT: event,
263939
+ ORBIT_HOOK_PAYLOAD: payload,
263940
+ ORBIT_SESSION_ID: context.sessionId,
263941
+ ...context.toolName ? { ORBIT_TOOL_NAME: context.toolName } : {},
263942
+ ...context.filePath ? { ORBIT_FILE: context.filePath } : {},
263943
+ ...context.agentRole ? { ORBIT_AGENT_ROLE: context.agentRole } : {},
263944
+ ...context.status ? { ORBIT_HOOK_STATUS: context.status } : {}
263945
+ };
263946
+ }
263947
+ async function executeLifecycleHooks(options) {
263948
+ const hooks = selectLifecycleHooks(
263949
+ options.hooks,
263950
+ options.event,
263951
+ options.context
263952
+ );
263953
+ for (const hook of hooks) {
263954
+ const hookId = `hook_${randomUUID52()}`;
263955
+ const startedAt = Date.now();
263956
+ eventBus.emitEvent("hook_started", {
263957
+ hookId,
263958
+ event: options.event,
263959
+ legacy: hook.legacy
263960
+ });
263961
+ options.report(`\u25CF Running ${options.event} hook...`);
263962
+ const result = await options.execute(
263963
+ hook,
263964
+ buildLifecycleHookEnvironment(options.event, options.context)
263965
+ );
263966
+ if (result.ok) {
263967
+ eventBus.emitEvent("hook_completed", {
263968
+ hookId,
263969
+ event: options.event,
263970
+ success: true,
263971
+ durationMs: Date.now() - startedAt,
263972
+ action: "continue"
263973
+ });
263974
+ options.report(`\u2714 ${options.event} hook passed.`);
263975
+ continue;
263976
+ }
263977
+ const action = hook.onFailure === "block" ? "blocked" : hook.onFailure === "ignore" ? "ignored" : "warn";
263978
+ eventBus.emitEvent("hook_completed", {
263979
+ hookId,
263980
+ event: options.event,
263981
+ success: false,
263982
+ durationMs: Date.now() - startedAt,
263983
+ action,
263984
+ error: result.output
263985
+ });
263986
+ if (hook.onFailure === "block") {
263987
+ options.report(`\u2716 ${options.event} hook blocked: ${result.output}`);
263988
+ return { ok: false, output: result.output };
263989
+ }
263990
+ if (hook.onFailure === "warn") {
263991
+ options.report(`\u26A0\uFE0F ${options.event} hook warning: ${result.output}`);
263992
+ }
263993
+ }
263994
+ return { ok: true };
263995
+ }
263996
+ function globMatches(pattern, value) {
263997
+ let source = "^";
263998
+ for (const character of pattern) {
263999
+ if (character === "*") source += ".*";
264000
+ else if (character === "?") source += ".";
264001
+ else source += character.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
264002
+ }
264003
+ source += "$";
264004
+ return new RegExp(source, "iu").test(value);
264005
+ }
263511
264006
  var execPromise2 = promisify3(exec2);
263512
264007
  var execFilePromise3 = promisify3(execFile3);
263513
264008
  var DEEPSEEK_CACHE_DEGRADED_HIT_RATE = 0.85;
@@ -263711,6 +264206,14 @@ var AgentLoop = class _AgentLoop {
263711
264206
  expandMcpPrompt(serverName, promptName, args) {
263712
264207
  return this.mcpRuntimeManager.expandPrompt(serverName, promptName, args);
263713
264208
  }
264209
+ /** Browser/terminal-safe MCP health snapshots. */
264210
+ listMcpHealth() {
264211
+ return this.mcpRuntimeManager.listHealth();
264212
+ }
264213
+ /** Refresh tool, resource, and prompt catalogs without restarting servers. */
264214
+ refreshMcpCatalogs(serverName) {
264215
+ return this.mcpRuntimeManager.refreshCatalogs(serverName);
264216
+ }
263714
264217
  /** Start configured MCP servers once and retain them for this loop's lifetime. */
263715
264218
  async initializeMcp() {
263716
264219
  if (this.mcpStartResult) return this.mcpStartResult;
@@ -263879,7 +264382,7 @@ var AgentLoop = class _AgentLoop {
263879
264382
  }
263880
264383
  appendBackgroundTaskNotification(tasks, remainingRunning = 0) {
263881
264384
  const message2 = {
263882
- id: `msg_background_tasks_${randomUUID52().replace(/-/g, "")}`,
264385
+ id: `msg_background_tasks_${randomUUID62().replace(/-/g, "")}`,
263883
264386
  role: "user",
263884
264387
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
263885
264388
  content: [
@@ -263977,11 +264480,37 @@ var AgentLoop = class _AgentLoop {
263977
264480
  } finally {
263978
264481
  await this.contextBuilder.settleBackgroundWork().catch(() => void 0);
263979
264482
  }
264483
+ if (this.options.agent?.role) {
264484
+ const subagentStopHooks = await this.runLifecycleHooks("subagentStop", {
264485
+ sessionId: this.state.sessionId,
264486
+ attempt: this.state.attemptCount,
264487
+ agentRole: this.options.agent.role,
264488
+ status: outcome.status
264489
+ });
264490
+ if (!subagentStopHooks.ok && outcome.status === "completed") {
264491
+ outcome = this.createFailedOutcome(
264492
+ "execution_error",
264493
+ subagentStopHooks.output || "A blocking subagent-stop hook failed."
264494
+ );
264495
+ }
264496
+ }
264497
+ const stopHooks = await this.runLifecycleHooks("stop", {
264498
+ sessionId: this.state.sessionId,
264499
+ attempt: this.state.attemptCount,
264500
+ status: outcome.status
264501
+ });
264502
+ if (!stopHooks.ok && outcome.status === "completed") {
264503
+ outcome = this.createFailedOutcome(
264504
+ "execution_error",
264505
+ stopHooks.output || "A blocking stop hook failed."
264506
+ );
264507
+ }
263980
264508
  this.finalizeOutcome(outcome);
263981
264509
  return outcome;
263982
264510
  }
263983
264511
  async executeRun() {
263984
264512
  const runStartedAt = /* @__PURE__ */ new Date();
264513
+ const isNewSession = this.state.history.length === 0;
263985
264514
  let iterationLimitReached = false;
263986
264515
  eventBus.emitEvent("agent_start", {
263987
264516
  taskId: this.state.sessionId,
@@ -264008,10 +264537,61 @@ var AgentLoop = class _AgentLoop {
264008
264537
  });
264009
264538
  this.verificationManager.initialize();
264010
264539
  this.sessionManager.saveHistory(this.state.history);
264011
- void this.provider.initialize?.().catch(() => {
264540
+ try {
264541
+ await this.provider.initialize?.();
264542
+ } catch (error) {
264543
+ const message2 = safeAgentLoopErrorMessage(error);
264544
+ this.sessionManager.logEvent("provider_initialization_failed", {
264545
+ provider: this.provider.id,
264546
+ message: message2
264547
+ });
264548
+ this.interaction.showText(
264549
+ picocolors3.red(`\u2716 Provider initialization failed: ${message2}`)
264550
+ );
264551
+ return this.createFailedOutcome("provider_error", message2);
264552
+ }
264553
+ if (isNewSession) {
264554
+ const sessionHooks = await this.runLifecycleHooks("sessionStart", {
264555
+ sessionId: this.state.sessionId,
264556
+ attempt: this.state.attemptCount
264557
+ });
264558
+ if (!sessionHooks.ok) {
264559
+ return this.createFailedOutcome(
264560
+ "execution_error",
264561
+ sessionHooks.output || "A blocking session-start hook failed."
264562
+ );
264563
+ }
264564
+ }
264565
+ const promptHooks = await this.runLifecycleHooks("promptSubmit", {
264566
+ sessionId: this.state.sessionId,
264567
+ attempt: this.state.attemptCount,
264568
+ promptLength: this.state.task.length
264012
264569
  });
264570
+ if (!promptHooks.ok) {
264571
+ return this.createFailedOutcome(
264572
+ "execution_error",
264573
+ promptHooks.output || "A blocking prompt hook failed."
264574
+ );
264575
+ }
264576
+ if (this.options.agent?.role) {
264577
+ const subagentStartHooks = await this.runLifecycleHooks("subagentStart", {
264578
+ sessionId: this.state.sessionId,
264579
+ attempt: this.state.attemptCount,
264580
+ agentRole: this.options.agent.role
264581
+ });
264582
+ if (!subagentStartHooks.ok) {
264583
+ return this.createFailedOutcome(
264584
+ "execution_error",
264585
+ subagentStartHooks.output || "A blocking subagent-start hook failed."
264586
+ );
264587
+ }
264588
+ }
264013
264589
  void this.contextBuilder.warmCodebaseRetrieval().catch(() => void 0);
264590
+ const mcpWasInitialized = Boolean(this.mcpStartResult);
264014
264591
  await this.initializeMcp();
264592
+ if (mcpWasInitialized) {
264593
+ await this.refreshMcpCatalogs();
264594
+ }
264015
264595
  const sigintListener = () => {
264016
264596
  if (this.abortController) {
264017
264597
  this.interaction.showText(
@@ -264371,6 +264951,9 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
264371
264951
  maxTokens: this.getContextWindowStatus(activeModel2).reservedOutputTokens,
264372
264952
  userId: this.userId,
264373
264953
  abortSignal: this.abortController.signal,
264954
+ // The Agent owns the retry budget and fallback policy. Prevent a
264955
+ // provider transport from nesting its own retries inside the loop.
264956
+ retryBudget: 0,
264374
264957
  thinking: supportsThinking ? {
264375
264958
  enabled: thinkingEnabled,
264376
264959
  budgetTokens: thinkingBudget,
@@ -264738,6 +265321,20 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264738
265321
  this.interaction.showText(
264739
265322
  "\n\u25CF Verification: Running contract verification checks..."
264740
265323
  );
265324
+ const verificationStartHooks = await this.runLifecycleHooks(
265325
+ "verificationStart",
265326
+ {
265327
+ sessionId: this.state.sessionId,
265328
+ attempt: this.state.attemptCount,
265329
+ status: "contract"
265330
+ }
265331
+ );
265332
+ if (!verificationStartHooks.ok) {
265333
+ return this.createFailedOutcome(
265334
+ "verification_failed",
265335
+ verificationStartHooks.output || "A blocking verification-start hook failed."
265336
+ );
265337
+ }
264741
265338
  const verificationWorkspaceBefore = await captureWorkspaceMutationSnapshot(this.cwd);
264742
265339
  const verifyResult = await this.verificationManager.runVerification();
264743
265340
  const verificationWorkspaceAfter = await captureWorkspaceMutationSnapshot(this.cwd);
@@ -264753,6 +265350,21 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264753
265350
  );
264754
265351
  }
264755
265352
  this.recordVerificationResult(verifyResult.success);
265353
+ const verificationEndHooks = await this.runLifecycleHooks(
265354
+ "verificationEnd",
265355
+ {
265356
+ sessionId: this.state.sessionId,
265357
+ attempt: this.state.attemptCount,
265358
+ status: verifyResult.success ? "passed" : "failed",
265359
+ verificationPassed: verifyResult.success
265360
+ }
265361
+ );
265362
+ if (!verificationEndHooks.ok) {
265363
+ return this.createFailedOutcome(
265364
+ "verification_failed",
265365
+ verificationEndHooks.output || "A blocking verification-end hook failed."
265366
+ );
265367
+ }
264756
265368
  if (!verifyResult.success) {
264757
265369
  const maxRepairAttempts = this.verificationManager.getMaxRepairAttempts();
264758
265370
  const repairAttempts = countRepairAttemptsForCurrentTask(
@@ -265124,6 +265736,30 @@ Please analyze this failure log, locate the files causing assertion or compile e
265124
265736
  risk: decision2.risk
265125
265737
  };
265126
265738
  }
265739
+ if (decision2.action === "ask") {
265740
+ const permissionHooks = await this.runLifecycleHooks(
265741
+ "permissionRequest",
265742
+ {
265743
+ sessionId: this.state.sessionId,
265744
+ attempt: this.state.attemptCount,
265745
+ toolName: tc.name,
265746
+ filePath: firstStringValue(
265747
+ evalArgsRecord.path,
265748
+ evalArgsRecord.TargetFile,
265749
+ evalArgsRecord.filePath,
265750
+ evalArgsRecord.file
265751
+ ),
265752
+ status: decision2.risk
265753
+ }
265754
+ );
265755
+ if (!permissionHooks.ok) {
265756
+ decision2 = {
265757
+ action: "deny",
265758
+ reason: permissionHooks.output || `A blocking permission hook rejected ${tc.name}.`,
265759
+ risk: decision2.risk
265760
+ };
265761
+ }
265762
+ }
265127
265763
  if (decision2.action === "deny") {
265128
265764
  this.interaction.showText(`\u2716 Blocked: ${decision2.reason}`);
265129
265765
  eventBus.emitEvent("tool_approval", {
@@ -265448,9 +266084,9 @@ ${commandError}`,
265448
266084
  content: [
265449
266085
  {
265450
266086
  type: "text",
265451
- text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) for the following git diff. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
266087
+ text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) from the following change summary. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
265452
266088
 
265453
- ${stdout2.substring(0, 2e4)}`
266089
+ ${buildCommitContextForModel(stdout2)}`
265454
266090
  }
265455
266091
  ]
265456
266092
  }
@@ -265499,25 +266135,20 @@ ${stdout2.substring(0, 2e4)}`
265499
266135
  )
265500
266136
  );
265501
266137
  }
265502
- if (this.config.hooks?.preEdit) {
265503
- this.interaction.showText(`\u25CF Running pre-edit hook...`);
265504
- const hookRes = await this.runHook(
265505
- this.config.hooks.preEdit,
265506
- targetPath
265507
- );
265508
- if (!hookRes.ok) {
265509
- this.interaction.showText(
265510
- `\u2716 Pre-edit hook failed: ${hookRes.output}`
265511
- );
265512
- hookResult = {
265513
- ok: false,
265514
- error: `Pre-edit hook failed: ${hookRes.output}`
265515
- };
265516
- skipToolExecution = true;
265517
- } else {
265518
- this.interaction.showText(`\u2714 Pre-edit hook passed.`);
265519
- }
265520
- }
266138
+ }
266139
+ const preToolHooks = await this.runLifecycleHooks("preToolUse", {
266140
+ sessionId: this.state.sessionId,
266141
+ attempt: this.state.attemptCount,
266142
+ toolName: tc.name,
266143
+ filePath: targetPath,
266144
+ agentRole: this.options.agent?.role
266145
+ });
266146
+ if (!preToolHooks.ok) {
266147
+ hookResult = {
266148
+ ok: false,
266149
+ error: preToolHooks.output || `A blocking pre-tool hook rejected ${tc.name}.`
266150
+ };
266151
+ skipToolExecution = true;
265521
266152
  }
265522
266153
  this.interaction.progress?.start(
265523
266154
  `Executing tool: ${tc.name}... | Cost: ${this.formatSessionCost()}`
@@ -265565,24 +266196,23 @@ ${stdout2.substring(0, 2e4)}`
265565
266196
  }
265566
266197
  }
265567
266198
  let finalResult = result;
265568
- if (result.ok && !skipToolExecution && (tc.name === "write_file" || tc.name === "edit_file") && targetPath) {
265569
- if (this.config.hooks?.postEdit) {
265570
- this.interaction.showText(`\u25CF Running post-edit hook...`);
265571
- const hookRes = await this.runHook(
265572
- this.config.hooks.postEdit,
265573
- targetPath
265574
- );
265575
- if (!hookRes.ok) {
265576
- this.interaction.showText(
265577
- `\u2716 Post-edit hook failed: ${hookRes.output}`
265578
- );
265579
- finalResult = {
265580
- ok: false,
265581
- error: `Post-edit hook failed: ${hookRes.output}`
265582
- };
265583
- } else {
265584
- this.interaction.showText(`\u2714 Post-edit hook passed.`);
266199
+ if (!skipToolExecution) {
266200
+ const postToolHooks = await this.runLifecycleHooks(
266201
+ result.ok ? "postToolUse" : "postToolFailure",
266202
+ {
266203
+ sessionId: this.state.sessionId,
266204
+ attempt: this.state.attemptCount,
266205
+ toolName: tc.name,
266206
+ filePath: targetPath,
266207
+ agentRole: this.options.agent?.role,
266208
+ status: result.ok ? "success" : "failure"
265585
266209
  }
266210
+ );
266211
+ if (!postToolHooks.ok) {
266212
+ finalResult = {
266213
+ ok: false,
266214
+ error: postToolHooks.output || `A blocking post-tool hook failed for ${tc.name}.`
266215
+ };
265586
266216
  }
265587
266217
  }
265588
266218
  if (finalResult.ok && targetPath && absoluteTargetPath && (tc.name === "write_file" || tc.name === "edit_file" || tc.name === "replace_file_content" || tc.name === "multi_replace_file_content")) {
@@ -266286,9 +266916,9 @@ ${guardNudge.message}` : ""),
266286
266916
  content: [
266287
266917
  {
266288
266918
  type: "text",
266289
- text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) for the following git diff. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
266919
+ text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) from the following change summary. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
266290
266920
 
266291
- ${diff.substring(0, 2e4)}`
266921
+ ${buildCommitContextForModel(diff)}`
266292
266922
  }
266293
266923
  ]
266294
266924
  }
@@ -266473,11 +267103,41 @@ ${diff.substring(0, 2e4)}`
266473
267103
  output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
266474
267104
  };
266475
267105
  }
266476
- const toolCallId = `hook_${randomUUID52()}`;
267106
+ return this.runHookCommand(
267107
+ hookCommand,
267108
+ { ORBIT_FILE: relativePath },
267109
+ this.config.tools.bash.timeoutMs
267110
+ );
267111
+ }
267112
+ async runLifecycleHooks(event, context) {
267113
+ return executeLifecycleHooks({
267114
+ hooks: this.config.hooks,
267115
+ event,
267116
+ context,
267117
+ execute: (hook, environment) => hook.legacy ? this.runHook(hook.command, context.filePath || "") : this.runHookCommand(
267118
+ hook.command,
267119
+ environment,
267120
+ hook.timeoutMs,
267121
+ event !== "stop" && event !== "subagentStop"
267122
+ ),
267123
+ report: (message2) => this.interaction.showText(message2)
267124
+ });
267125
+ }
267126
+ async runHookCommand(hookCommand, environment, timeoutMs, abortable = true) {
267127
+ if (hookCommand.includes("{file}")) {
267128
+ return {
267129
+ ok: false,
267130
+ output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
267131
+ };
267132
+ }
267133
+ const toolCallId = `hook_${randomUUID62()}`;
266477
267134
  eventBus.emitEvent("tool_proposal", {
266478
267135
  toolCallId,
266479
267136
  toolName: "hook",
266480
- arguments: { filePath: relativePath },
267137
+ arguments: {
267138
+ event: environment.ORBIT_HOOK_EVENT || "legacy",
267139
+ filePath: environment.ORBIT_FILE
267140
+ },
266481
267141
  explanation: "Run a configured Orbit lifecycle hook."
266482
267142
  });
266483
267143
  const decision2 = this.permissionEngine.evaluate(
@@ -266528,12 +267188,9 @@ ${diff.substring(0, 2e4)}`
266528
267188
  const { stdout: stdout2, stderr } = await execPromise2(hookCommand, {
266529
267189
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
266530
267190
  cwd: this.cwd,
266531
- env: this.buildChildProcessEnvironment(
266532
- { ORBIT_FILE: relativePath },
266533
- true
266534
- ),
266535
- timeout: this.config.tools.bash.timeoutMs,
266536
- signal: this.abortController?.signal
267191
+ env: this.buildChildProcessEnvironment(environment, true),
267192
+ timeout: Math.min(timeoutMs, this.config.tools.bash.timeoutMs),
267193
+ signal: abortable ? this.abortController?.signal : void 0
266537
267194
  });
266538
267195
  const output = safeHookOutput(stdout2 + stderr);
266539
267196
  eventBus.emitEvent("tool_result", {
@@ -266591,7 +267248,7 @@ ${diff.substring(0, 2e4)}`
266591
267248
  const now = (/* @__PURE__ */ new Date()).toISOString();
266592
267249
  const plan = this.sessionManager.getTaskPlan();
266593
267250
  const item = {
266594
- id: `step_${randomUUID52()}`,
267251
+ id: `step_${randomUUID62()}`,
266595
267252
  text: text2.trim(),
266596
267253
  status: "pending",
266597
267254
  createdAt: now,
@@ -266722,7 +267379,7 @@ ${diff.substring(0, 2e4)}`
266722
267379
  this.finalResponseOnlyReason = null;
266723
267380
  for (const input of inputs) {
266724
267381
  this.state.history.push({
266725
- id: `msg_user_steer_${randomUUID52().replace(/-/g, "")}`,
267382
+ id: `msg_user_steer_${randomUUID62().replace(/-/g, "")}`,
266726
267383
  role: "user",
266727
267384
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
266728
267385
  content: [{ type: "text", text: input.text }, ...input.attachments],
@@ -267106,6 +267763,16 @@ ${diff.substring(0, 2e4)}`
267106
267763
  * Only fires when Phase 1 alone isn't enough to keep history bounded.
267107
267764
  */
267108
267765
  async compactHistory(mode, targetHistoryTokens) {
267766
+ const preCompactHooks = await this.runLifecycleHooks("preCompact", {
267767
+ sessionId: this.state.sessionId,
267768
+ attempt: this.state.attemptCount,
267769
+ mode
267770
+ });
267771
+ if (!preCompactHooks.ok) {
267772
+ throw new Error(
267773
+ preCompactHooks.output || "A blocking pre-compaction hook failed."
267774
+ );
267775
+ }
267109
267776
  const status = this.getContextWindowStatus();
267110
267777
  const { history, droppedHistory, summaryMessageId, ...result } = compactHistoryMessages(this.state.history, {
267111
267778
  mode,
@@ -267117,7 +267784,11 @@ ${diff.substring(0, 2e4)}`
267117
267784
  const semanticSummary = await buildSemanticCompactionSummary(
267118
267785
  droppedHistory,
267119
267786
  this.provider,
267120
- this.config.models.fast
267787
+ this.config.models.fast,
267788
+ {
267789
+ abortSignal: this.abortController?.signal,
267790
+ onUsage: (usage2) => this.accumulateCost(this.config.models.fast, usage2)
267791
+ }
267121
267792
  );
267122
267793
  const summaryBlock = semanticSummary ? history.find((message2) => message2.id === summaryMessageId)?.content.find((block2) => block2.type === "text") : void 0;
267123
267794
  if (semanticSummary && summaryBlock?.type === "text") {
@@ -267127,10 +267798,22 @@ ${diff.substring(0, 2e4)}`
267127
267798
  this.state.history = history;
267128
267799
  this.sessionManager.saveHistory(this.state.history);
267129
267800
  }
267130
- return {
267801
+ const finalResult = {
267131
267802
  ...this.getContextWindowStatus(),
267132
267803
  ...result
267133
267804
  };
267805
+ const postCompactHooks = await this.runLifecycleHooks("postCompact", {
267806
+ sessionId: this.state.sessionId,
267807
+ attempt: this.state.attemptCount,
267808
+ mode,
267809
+ status: result.changed ? "changed" : "unchanged"
267810
+ });
267811
+ if (!postCompactHooks.ok) {
267812
+ throw new Error(
267813
+ postCompactHooks.output || "A blocking post-compaction hook failed."
267814
+ );
267815
+ }
267816
+ return finalResult;
267134
267817
  }
267135
267818
  /** Compacts older dialogue on demand while preserving the active turn. */
267136
267819
  async compactHistoryPublic() {
@@ -267318,6 +268001,29 @@ ${diff.substring(0, 2e4)}`
267318
268001
  }
267319
268002
  }
267320
268003
  };
268004
+ function buildCommitContextForModel(diff) {
268005
+ const files = /* @__PURE__ */ new Set();
268006
+ let additions = 0;
268007
+ let deletions = 0;
268008
+ for (const line of diff.split(/\r?\n/)) {
268009
+ if (line.startsWith("diff --git ")) {
268010
+ const match = line.match(/ b\/(.+)$/);
268011
+ if (match?.[1]) files.add(match[1]);
268012
+ } else if (line.startsWith("+") && !line.startsWith("+++")) {
268013
+ additions += 1;
268014
+ } else if (line.startsWith("-") && !line.startsWith("---")) {
268015
+ deletions += 1;
268016
+ }
268017
+ }
268018
+ const fileList = [...files].slice(0, 100);
268019
+ return redactSecrets(
268020
+ [
268021
+ `Files changed (${files.size}): ${fileList.join(", ") || "unknown"}`,
268022
+ `Line changes: +${additions} / -${deletions}.`,
268023
+ "Infer the scope from paths and counts only; do not invent implementation details."
268024
+ ].join("\n")
268025
+ ).slice(0, 8e3);
268026
+ }
267321
268027
  function toUnknownRecord(value) {
267322
268028
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
267323
268029
  }
@@ -267698,7 +268404,11 @@ var AgentRunTracker = class {
267698
268404
  task: this.task,
267699
268405
  budgetUsd: this.budgetUsd
267700
268406
  });
267701
- this.stopLeaseHeartbeat = store.startLeaseHeartbeat(this.run.id);
268407
+ this.stopLeaseHeartbeat = store.startLeaseHeartbeat(this.run.id, {
268408
+ onLeaseLost: (error) => this.warn(
268409
+ `Agent run lease was lost; durable state is no longer being renewed: ${errorMessage2(error)}`
268410
+ )
268411
+ });
267702
268412
  } catch (error) {
267703
268413
  this.warn(`Agent run state will be memory-only: ${errorMessage2(error)}`);
267704
268414
  }
@@ -268592,13 +269302,20 @@ var AcceptanceTaskSchema = z132.object({
268592
269302
  maxInputTokens: z132.number().int().nonnegative().optional(),
268593
269303
  maxOutputTokens: z132.number().int().nonnegative().optional(),
268594
269304
  maxCostUsd: z132.number().finite().nonnegative().optional(),
268595
- minCacheHitRate: z132.number().finite().min(0).max(1).optional()
269305
+ minCacheHitRate: z132.number().finite().min(0).max(1).optional(),
269306
+ maxToolFailures: z132.number().int().nonnegative().optional(),
269307
+ maxDeniedTools: z132.number().int().nonnegative().optional(),
269308
+ maxApprovalRequests: z132.number().int().nonnegative().optional(),
269309
+ maxCompactions: z132.number().int().nonnegative().optional(),
269310
+ maxAttempts: z132.number().int().nonnegative().optional(),
269311
+ maxToolFailureRate: z132.number().finite().min(0).max(1).optional()
268596
269312
  }).optional()
268597
269313
  });
268598
269314
  var AcceptanceSuiteSchema = z132.object({
268599
269315
  schemaVersion: z132.literal(1),
268600
269316
  name: z132.string().trim().min(1).max(200),
268601
269317
  description: z132.string().trim().max(2e3).optional(),
269318
+ defaultLimits: AcceptanceTaskSchema.shape.limits,
268602
269319
  tasks: z132.array(AcceptanceTaskSchema).min(1).max(100)
268603
269320
  });
268604
269321
  var AcceptanceCheckResultSchema = z132.object({
@@ -268625,6 +269342,17 @@ var AcceptanceTaskResultSchema = z132.object({
268625
269342
  cacheHitRate: z132.number().finite().min(0).max(1),
268626
269343
  costUsd: z132.number().finite().nonnegative()
268627
269344
  }).optional(),
269345
+ reliability: z132.object({
269346
+ attempts: z132.number().int().nonnegative(),
269347
+ toolRuns: z132.number().int().nonnegative(),
269348
+ toolFailures: z132.number().int().nonnegative(),
269349
+ deniedTools: z132.number().int().nonnegative(),
269350
+ approvalRequests: z132.number().int().nonnegative(),
269351
+ compactions: z132.number().int().nonnegative(),
269352
+ resumedCount: z132.number().int().nonnegative(),
269353
+ verificationRuns: z132.number().int().nonnegative(),
269354
+ checkpoints: z132.number().int().nonnegative()
269355
+ }).optional(),
268628
269356
  changedFiles: z132.array(z132.string()),
268629
269357
  checks: z132.array(AcceptanceCheckResultSchema),
268630
269358
  failureReasons: z132.array(z132.string())
@@ -268685,6 +269413,19 @@ function scoreAcceptanceTask(input) {
268685
269413
  `duration_limit:${Math.round(input.durationMs)}>${task.limits.maxDurationMs}`
268686
269414
  );
268687
269415
  }
269416
+ const reliabilityLimitsConfigured = [
269417
+ task.limits.maxToolFailures,
269418
+ task.limits.maxDeniedTools,
269419
+ task.limits.maxApprovalRequests,
269420
+ task.limits.maxCompactions,
269421
+ task.limits.maxAttempts,
269422
+ task.limits.maxToolFailureRate
269423
+ ].some((value) => value !== void 0);
269424
+ if (reliabilityLimitsConfigured && !input.reliability) {
269425
+ failureReasons.push("reliability_missing");
269426
+ } else if (input.reliability) {
269427
+ enforceReliabilityLimits(task, input.reliability, failureReasons);
269428
+ }
268688
269429
  }
268689
269430
  return AcceptanceTaskResultSchema.parse({
268690
269431
  taskId: task.id,
@@ -268697,11 +269438,39 @@ function scoreAcceptanceTask(input) {
268697
269438
  requestedModel: task.model,
268698
269439
  resolvedModels: Array.from(new Set(input.resolvedModels || [])),
268699
269440
  usage: input.usage,
269441
+ reliability: input.reliability,
268700
269442
  changedFiles,
268701
269443
  checks: input.checks,
268702
269444
  failureReasons
268703
269445
  });
268704
269446
  }
269447
+ function enforceReliabilityLimits(task, reliability, failureReasons) {
269448
+ const limits = task.limits;
269449
+ if (!limits) return;
269450
+ for (const [name, actual, maximum] of [
269451
+ ["tool_failure_limit", reliability.toolFailures, limits.maxToolFailures],
269452
+ ["denied_tool_limit", reliability.deniedTools, limits.maxDeniedTools],
269453
+ [
269454
+ "approval_request_limit",
269455
+ reliability.approvalRequests,
269456
+ limits.maxApprovalRequests
269457
+ ],
269458
+ ["compaction_limit", reliability.compactions, limits.maxCompactions],
269459
+ ["attempt_limit", reliability.attempts, limits.maxAttempts]
269460
+ ]) {
269461
+ if (maximum !== void 0 && actual > maximum) {
269462
+ failureReasons.push(`${name}:${actual}>${maximum}`);
269463
+ }
269464
+ }
269465
+ if (limits.maxToolFailureRate !== void 0) {
269466
+ const rate = reliability.toolRuns > 0 ? reliability.toolFailures / reliability.toolRuns : 0;
269467
+ if (rate > limits.maxToolFailureRate) {
269468
+ failureReasons.push(
269469
+ `tool_failure_rate:${Number(rate.toFixed(6))}>${limits.maxToolFailureRate}`
269470
+ );
269471
+ }
269472
+ }
269473
+ }
268705
269474
  function normalizeFilePath(value) {
268706
269475
  return value.replace(/\\/g, "/").replace(/^\.\//, "");
268707
269476
  }
@@ -273015,6 +273784,56 @@ var SLASH_COMMAND_DEFINITIONS = [
273015
273784
  },
273016
273785
  webSuggested: true
273017
273786
  },
273787
+ {
273788
+ command: "/workflow",
273789
+ usage: "export <kebab-name> [local|versioned]",
273790
+ category: "session",
273791
+ description: {
273792
+ en: "Compile this session into a reviewable reusable Skill",
273793
+ zh: "\u5C06\u5F53\u524D\u4F1A\u8BDD\u7F16\u8BD1\u4E3A\u53EF\u5BA1\u9605\u7684\u590D\u7528 Skill",
273794
+ "zh-TW": "\u5C07\u76EE\u524D\u5DE5\u4F5C\u968E\u6BB5\u7DE8\u8B6F\u70BA\u53EF\u5BE9\u95B1\u7684\u91CD\u7528 Skill"
273795
+ },
273796
+ suggestions: [
273797
+ {
273798
+ value: "export ",
273799
+ description: {
273800
+ en: "Create a local Skill from the current trace",
273801
+ zh: "\u4ECE\u5F53\u524D\u5BA1\u8BA1\u8BB0\u5F55\u521B\u5EFA\u672C\u5730 Skill",
273802
+ "zh-TW": "\u5F9E\u76EE\u524D\u7A3D\u6838\u8A18\u9304\u5EFA\u7ACB\u672C\u6A5F Skill"
273803
+ }
273804
+ }
273805
+ ],
273806
+ webSuggested: true
273807
+ },
273808
+ {
273809
+ command: "/mcp",
273810
+ usage: "[status|refresh] [server]",
273811
+ category: "system",
273812
+ description: {
273813
+ en: "Inspect MCP health or refresh live catalogs",
273814
+ zh: "\u67E5\u770B MCP \u5065\u5EB7\u72B6\u6001\u6216\u5237\u65B0\u5B9E\u65F6\u76EE\u5F55",
273815
+ "zh-TW": "\u67E5\u770B MCP \u5065\u5EB7\u72C0\u614B\u6216\u91CD\u65B0\u6574\u7406\u5373\u6642\u76EE\u9304"
273816
+ },
273817
+ suggestions: [
273818
+ {
273819
+ value: "status",
273820
+ description: {
273821
+ en: "Show server health",
273822
+ zh: "\u663E\u793A\u670D\u52A1\u5065\u5EB7\u72B6\u6001",
273823
+ "zh-TW": "\u986F\u793A\u670D\u52D9\u5065\u5EB7\u72C0\u614B"
273824
+ }
273825
+ },
273826
+ {
273827
+ value: "refresh",
273828
+ description: {
273829
+ en: "Refresh tools, resources, and prompts",
273830
+ zh: "\u5237\u65B0\u5DE5\u5177\u3001\u8D44\u6E90\u4E0E\u63D0\u793A\u8BCD",
273831
+ "zh-TW": "\u91CD\u65B0\u6574\u7406\u5DE5\u5177\u3001\u8CC7\u6E90\u8207\u63D0\u793A\u8A5E"
273832
+ }
273833
+ }
273834
+ ],
273835
+ webSuggested: false
273836
+ },
273018
273837
  {
273019
273838
  command: "/doctor",
273020
273839
  usage: "",
@@ -276785,7 +277604,7 @@ import { dirname as dirname14, resolve as resolve14 } from "path";
276785
277604
  import { homedir as homedir10 } from "os";
276786
277605
  import http3 from "http";
276787
277606
  import { randomBytes as randomBytes4, randomUUID as randomUUID13, timingSafeEqual as timingSafeEqual2 } from "crypto";
276788
- import { z as z69 } from "zod";
277607
+ import { z as z70 } from "zod";
276789
277608
 
276790
277609
  // src/runtime/CommandRouter.ts
276791
277610
  import picocolors18 from "picocolors";
@@ -283110,6 +283929,25 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
283110
283929
  state.ready = true;
283111
283930
  updateSendButtonState();
283112
283931
  setConnection('connected', copy.connected);
283932
+ } else if (event.kind === 'replay_gap') {
283933
+ // The server retained only a bounded replay window. Reconcile the
283934
+ // authoritative snapshot immediately so a reconnect never leaves the
283935
+ // UI presenting a silently incomplete turn or session history.
283936
+ state.ready = false;
283937
+ updateSendButtonState();
283938
+ setConnection(
283939
+ 'connecting',
283940
+ language === 'en'
283941
+ ? 'Some events expired; syncing the latest state…'
283942
+ : chinese('部分事件已过期,正在同步最新状态…', '部分事件已過期,正在同步最新狀態…'),
283943
+ );
283944
+ void reconcileStatus().finally(() => {
283945
+ if (state.eventSource === source && state.ready === false) {
283946
+ state.ready = true;
283947
+ updateSendButtonState();
283948
+ setConnection('connected', copy.connected);
283949
+ }
283950
+ });
283113
283951
  } else if (event.kind === 'turn_started') {
283114
283952
  state.activeTurnId = event.turnId;
283115
283953
  setBusy(true, copy.working);
@@ -283582,6 +284420,23 @@ function sanitizeWebEventPayload(type, payload) {
283582
284420
  return { type: safeWebText(payload.type, 100) };
283583
284421
  case "verification_ended":
283584
284422
  return { success: payload.success === true };
284423
+ case "hook_started":
284424
+ return {
284425
+ hookId: safeWebText(payload.hookId, 200),
284426
+ event: safeWebText(payload.event, 100),
284427
+ legacy: payload.legacy === true
284428
+ };
284429
+ case "hook_completed":
284430
+ return {
284431
+ hookId: safeWebText(payload.hookId, 200),
284432
+ event: safeWebText(payload.event, 100),
284433
+ success: payload.success === true,
284434
+ durationMs: safeNumber(payload.durationMs),
284435
+ action: ["continue", "warn", "blocked", "ignored"].includes(
284436
+ String(payload.action)
284437
+ ) ? String(payload.action) : "warn",
284438
+ error: safeWebText(payload.error, 1e3)
284439
+ };
283585
284440
  case "checkpoint_created":
283586
284441
  return {
283587
284442
  timestamp: safeWebText(payload.timestamp, 100),
@@ -284619,13 +285474,14 @@ var WebUiEventStream = class {
284619
285474
  const payload = sanitizeWebEventPayload(event.type, event.payload);
284620
285475
  if (payload === void 0) return;
284621
285476
  const turn = this.getActiveTurn();
285477
+ const eventSessionId = extractSessionId(payload);
284622
285478
  this.broadcast({
284623
285479
  kind: "orbit_event",
284624
285480
  schemaVersion: event.schemaVersion,
284625
285481
  id: event.eventId,
284626
285482
  timestamp: event.timestamp,
284627
285483
  turnId: turn?.id,
284628
- sessionId: turn?.sessionId,
285484
+ sessionId: eventSessionId || turn?.sessionId,
284629
285485
  type: event.type,
284630
285486
  payload
284631
285487
  });
@@ -284685,6 +285541,19 @@ var WebUiEventStream = class {
284685
285541
  );
284686
285542
  const lastEventId = parseLastEventId(req.headers?.["last-event-id"]);
284687
285543
  if (lastEventId !== void 0) {
285544
+ const firstBufferedId = this.replayBuffer[0]?.id;
285545
+ if (firstBufferedId !== void 0 && lastEventId + 1 < firstBufferedId) {
285546
+ res.write(
285547
+ formatSseEvent({
285548
+ id: firstBufferedId - 1,
285549
+ event: {
285550
+ kind: "replay_gap",
285551
+ afterEventId: lastEventId,
285552
+ firstAvailableEventId: firstBufferedId
285553
+ }
285554
+ })
285555
+ );
285556
+ }
284688
285557
  for (const entry of this.replayBuffer) {
284689
285558
  if (entry.id > lastEventId) res.write(formatSseEvent(entry));
284690
285559
  }
@@ -284741,6 +285610,17 @@ var WebUiEventStream = class {
284741
285610
  if (destroy && !client.destroyed) client.destroy();
284742
285611
  }
284743
285612
  };
285613
+ function extractSessionId(payload) {
285614
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
285615
+ return void 0;
285616
+ }
285617
+ const record = payload;
285618
+ for (const key of ["sessionId", "taskId", "agentId"]) {
285619
+ const value = record[key];
285620
+ if (typeof value === "string" && value.trim()) return value;
285621
+ }
285622
+ return void 0;
285623
+ }
284744
285624
  function parseLastEventId(value) {
284745
285625
  const text2 = Array.isArray(value) ? value[0] : value;
284746
285626
  if (!text2 || !/^\d+$/.test(text2)) return void 0;
@@ -296581,19 +297461,127 @@ async function confirmUpdate(prompt) {
296581
297461
  }
296582
297462
  }
296583
297463
 
296584
- // src/runtime/review/ReviewCommand.ts
297464
+ // src/commands/workflow.ts
296585
297465
  import { z as z67 } from "zod";
296586
- var ReviewPresetSchema = z67.enum([
297466
+
297467
+ // src/runtime/WorkflowCompiler.ts
297468
+ function compileWorkflowSkill(trace, descriptionOverride) {
297469
+ const observedTools = [
297470
+ ...new Set(trace.toolCalls.map((call) => call.toolName))
297471
+ ].sort().slice(0, 100);
297472
+ const successfulTools = trace.toolCalls.filter(
297473
+ (call) => call.status === "success"
297474
+ );
297475
+ const failedTools = trace.toolCalls.filter(
297476
+ (call) => call.status === "failed" || call.status === "denied"
297477
+ );
297478
+ const verificationEvents = trace.events.filter(
297479
+ (event) => event.type === "verification_ended"
297480
+ );
297481
+ const planSteps = (trace.plan?.items ?? []).map((item) => redactSecrets(item.text).trim()).filter(Boolean).slice(0, 50);
297482
+ const workflowSteps = planSteps.length > 0 ? planSteps : deriveWorkflowSteps(observedTools);
297483
+ const title = redactSecrets(trace.session.title || "Recorded Orbit workflow").replace(/\s+/g, " ").trim().slice(0, 180);
297484
+ const description = redactSecrets(descriptionOverride || title).replace(/[\r\n]+/g, " ").trim().slice(0, 240);
297485
+ const instructions = [
297486
+ "# Objective",
297487
+ "",
297488
+ redactSecrets(trace.session.goal || title).slice(0, 2e3),
297489
+ "",
297490
+ "# Reusable workflow",
297491
+ "",
297492
+ ...workflowSteps.map((step, index) => `${index + 1}. ${step}`),
297493
+ "",
297494
+ "# Execution contract",
297495
+ "",
297496
+ "- Re-inspect the current workspace before acting; recorded paths, commands, outputs, and assumptions are historical evidence only.",
297497
+ "- Never replay a recorded shell command or tool argument verbatim. Reconstruct the smallest current operation and route it through Orbit permissions.",
297498
+ "- Keep writes inside the authorized workspace and preserve unrelated dirty or staged changes.",
297499
+ "- Run the repository's current verification contract after edits. Repair the earliest root failure, then rerun the wider gate.",
297500
+ "- Stop and report a blocker when required authority, credentials, or external state is missing.",
297501
+ "",
297502
+ "# Observed strategy",
297503
+ "",
297504
+ `- Successful tool actions in the source run: ${successfulTools.length}.`,
297505
+ `- Failed or denied actions in the source run: ${failedTools.length}. Treat these as signals to inspect assumptions before retrying.`,
297506
+ `- Verification runs observed: ${verificationEvents.length}.`,
297507
+ `- Tool families observed: ${observedTools.join(", ") || "none"}.`,
297508
+ "",
297509
+ "This Skill was derived from a credential-redacted Orbit trace. It intentionally excludes raw prompts, tool arguments, command output, diffs, and local absolute paths."
297510
+ ].join("\n").slice(0, 24e3);
297511
+ return {
297512
+ description: description || "A reviewable workflow compiled from Orbit trace evidence.",
297513
+ instructions,
297514
+ observedTools,
297515
+ verificationRuns: verificationEvents.length
297516
+ };
297517
+ }
297518
+ function deriveWorkflowSteps(observedTools) {
297519
+ const steps = [
297520
+ "Clarify the requested outcome, constraints, authorized workspace, and acceptance evidence."
297521
+ ];
297522
+ if (observedTools.some((tool) => /read|search|list|symbol/i.test(tool))) {
297523
+ steps.push(
297524
+ "Inspect repository landmarks and the smallest relevant files before proposing changes."
297525
+ );
297526
+ }
297527
+ if (observedTools.some((tool) => /write|edit|replace|patch/i.test(tool))) {
297528
+ steps.push(
297529
+ "Apply scoped, reviewable edits while preserving unrelated user changes."
297530
+ );
297531
+ }
297532
+ if (observedTools.some((tool) => /test|bash|shell|command/i.test(tool))) {
297533
+ steps.push(
297534
+ "Execute the smallest relevant verification first, then expand according to risk."
297535
+ );
297536
+ }
297537
+ steps.push(
297538
+ "Inspect the final diff, summarize verified outcomes, and disclose any remaining uncertainty."
297539
+ );
297540
+ return steps;
297541
+ }
297542
+
297543
+ // src/commands/workflow.ts
297544
+ var WorkflowExportOptionsSchema = z67.object({
297545
+ name: z67.string().trim().min(1).max(48).regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),
297546
+ description: z67.string().trim().min(1).max(240).optional(),
297547
+ scope: z67.enum(["local", "versioned"]).default("local"),
297548
+ json: z67.boolean().default(false)
297549
+ });
297550
+ async function runWorkflowExport(cwd, sessionId, options) {
297551
+ const value = WorkflowExportOptionsSchema.parse(options);
297552
+ const trace = new SessionStore(cwd).exportTrace(sessionId, {
297553
+ includeHistory: false
297554
+ });
297555
+ const compiled = compileWorkflowSkill(trace, value.description);
297556
+ const created = await createProjectCapability(cwd, {
297557
+ kind: "skill",
297558
+ name: value.name,
297559
+ description: compiled.description,
297560
+ instructions: compiled.instructions,
297561
+ scope: value.scope
297562
+ });
297563
+ const result = {
297564
+ schemaVersion: 1,
297565
+ name: created.name,
297566
+ path: created.path
297567
+ };
297568
+ if (value.json) console.log(JSON.stringify(result, null, 2));
297569
+ return result;
297570
+ }
297571
+
297572
+ // src/runtime/review/ReviewCommand.ts
297573
+ import { z as z68 } from "zod";
297574
+ var ReviewPresetSchema = z68.enum([
296587
297575
  "comprehensive",
296588
297576
  "security",
296589
297577
  "tests",
296590
297578
  "performance",
296591
297579
  "accessibility"
296592
297580
  ]);
296593
- var ReviewScopeSchema = z67.discriminatedUnion("kind", [
296594
- z67.object({ kind: z67.literal("working-tree") }),
296595
- z67.object({ kind: z67.literal("commit"), ref: z67.string().min(1).max(200) }),
296596
- z67.object({ kind: z67.literal("branch"), ref: z67.string().min(1).max(200) })
297581
+ var ReviewScopeSchema = z68.discriminatedUnion("kind", [
297582
+ z68.object({ kind: z68.literal("working-tree") }),
297583
+ z68.object({ kind: z68.literal("commit"), ref: z68.string().min(1).max(200) }),
297584
+ z68.object({ kind: z68.literal("branch"), ref: z68.string().min(1).max(200) })
296597
297585
  ]);
296598
297586
  var SAFE_GIT_REF = /^[A-Za-z0-9][A-Za-z0-9._/@{}~^:+-]{0,199}$/;
296599
297587
  function parseReviewCommand(rawArguments) {
@@ -296817,6 +297805,58 @@ var CommandRouter = class {
296817
297805
  }
296818
297806
  }
296819
297807
  }
297808
+ if (/^\/mcp(?:\s|$)/i.test(trimmed)) {
297809
+ const [, action = "status", serverName] = trimmed.split(/\s+/, 3);
297810
+ if (!["status", "refresh"].includes(action.toLowerCase())) {
297811
+ this.printOutput(
297812
+ picocolors18.yellow("Usage: /mcp [status|refresh] [server]")
297813
+ );
297814
+ return { shouldExit: false, processed: true };
297815
+ }
297816
+ await loop.initializeMcp();
297817
+ const health = action.toLowerCase() === "refresh" ? await loop.refreshMcpCatalogs(serverName) : loop.listMcpHealth();
297818
+ if (health.length === 0) {
297819
+ this.printOutput(
297820
+ config.language === "en" ? "\u25CF No MCP servers are running." : "\u25CF \u5F53\u524D\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684 MCP \u670D\u52A1\u3002"
297821
+ );
297822
+ } else {
297823
+ this.printOutput(
297824
+ health.map(
297825
+ (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}` : ""}`
297826
+ ).join("\n")
297827
+ );
297828
+ }
297829
+ return { shouldExit: false, processed: true };
297830
+ }
297831
+ if (/^\/workflow(?:\s|$)/i.test(trimmed)) {
297832
+ const [, action = "", name = "", scope = "local"] = trimmed.split(
297833
+ /\s+/,
297834
+ 4
297835
+ );
297836
+ if (action.toLowerCase() !== "export" || !name || !["local", "versioned"].includes(scope)) {
297837
+ this.printOutput(
297838
+ picocolors18.yellow(
297839
+ "Usage: /workflow export <kebab-name> [local|versioned]"
297840
+ )
297841
+ );
297842
+ return { shouldExit: false, processed: true };
297843
+ }
297844
+ try {
297845
+ const result = await runWorkflowExport(cwd, loop.getSessionId(), {
297846
+ name,
297847
+ scope
297848
+ });
297849
+ loop.invalidateSkillsCache();
297850
+ this.printOutput(`\u2714 Workflow Skill created: ${result.path}`);
297851
+ } catch (error) {
297852
+ this.printOutput(
297853
+ picocolors18.red(
297854
+ `\u2716 ${error instanceof Error ? error.message : String(error)}`
297855
+ )
297856
+ );
297857
+ }
297858
+ return { shouldExit: false, processed: true };
297859
+ }
296820
297860
  if (/^\/review(?:\s|$)/i.test(trimmed)) {
296821
297861
  try {
296822
297862
  const rawArguments = trimmed.replace(/^\/review\b/i, "").trim();
@@ -298568,21 +299608,21 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
298568
299608
  };
298569
299609
 
298570
299610
  // src/runtime/LocalRuntimeState.ts
298571
- import { z as z68 } from "zod";
299611
+ import { z as z69 } from "zod";
298572
299612
  var LOCAL_RUNTIME_STATE_MAX_BYTES = 1048576;
298573
- var LocalSkillsStateSchema = z68.object({
298574
- enabled: z68.boolean().optional(),
298575
- activation: z68.enum(["auto", "explicit"]).optional(),
298576
- maxActive: z68.number().int().min(0).max(8).optional(),
298577
- disabled: z68.array(z68.string().min(1).max(128)).max(1e3).optional()
299613
+ var LocalSkillsStateSchema = z69.object({
299614
+ enabled: z69.boolean().optional(),
299615
+ activation: z69.enum(["auto", "explicit"]).optional(),
299616
+ maxActive: z69.number().int().min(0).max(8).optional(),
299617
+ disabled: z69.array(z69.string().min(1).max(128)).max(1e3).optional()
298578
299618
  });
298579
- var LocalRuntimeStateSchema = z68.object({
298580
- lastSessionId: z68.string().min(1).max(1e3).optional(),
298581
- lastProvider: z68.string().min(1).max(256).optional(),
298582
- lastModel: z68.string().max(512).optional(),
299619
+ var LocalRuntimeStateSchema = z69.object({
299620
+ lastSessionId: z69.string().min(1).max(1e3).optional(),
299621
+ lastProvider: z69.string().min(1).max(256).optional(),
299622
+ lastModel: z69.string().max(512).optional(),
298583
299623
  language: OrbitLanguageSchema.optional(),
298584
- permissionMode: z68.enum(["strict", "normal", "auto", "plan"]).optional(),
298585
- agentMaxIterations: z68.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
299624
+ permissionMode: z69.enum(["strict", "normal", "auto", "plan"]).optional(),
299625
+ agentMaxIterations: z69.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
298586
299626
  skills: LocalSkillsStateSchema.optional()
298587
299627
  });
298588
299628
  function readLocalRuntimeState(cwd) {
@@ -298613,16 +299653,16 @@ function writeLocalRuntimeState(cwd, patch) {
298613
299653
  }
298614
299654
 
298615
299655
  // src/runtime/ReplController.ts
298616
- var AutocompleteRequestSchema = z69.object({
298617
- prefix: z69.string().max(2e4),
298618
- suffix: z69.string().max(2e4),
298619
- windowId: z69.string().max(1e3).optional()
299656
+ var AutocompleteRequestSchema = z70.object({
299657
+ prefix: z70.string().max(2e4),
299658
+ suffix: z70.string().max(2e4),
299659
+ windowId: z70.string().max(1e3).optional()
298620
299660
  });
298621
299661
  var AUTOCOMPLETE_BODY_LIMIT_BYTES = 1e5;
298622
299662
  var AUTOCOMPLETE_MAX_CONCURRENCY = 4;
298623
- var AutocompleteEndpointSchema = z69.object({
298624
- port: z69.number().int().min(1).max(65535),
298625
- token: z69.string().min(32).max(256)
299663
+ var AutocompleteEndpointSchema = z70.object({
299664
+ port: z70.number().int().min(1).max(65535),
299665
+ token: z70.string().min(32).max(256)
298626
299666
  });
298627
299667
  function getRunOutcomeMessage2(outcome) {
298628
299668
  if (!outcome || outcome.status === "completed") return void 0;
@@ -299662,36 +300702,36 @@ function isRecord8(value) {
299662
300702
  }
299663
300703
 
299664
300704
  // src/commands/LSPServer.ts
299665
- import { z as z70 } from "zod";
300705
+ import { z as z71 } from "zod";
299666
300706
  var MAX_LSP_HEADER_BYTES = 8 * 1024;
299667
300707
  var MAX_LSP_BODY_BYTES = 8 * 1024 * 1024;
299668
- var JsonRpcIdSchema = z70.union([z70.string(), z70.number(), z70.null()]);
299669
- var JSONRPCMessageSchema = z70.object({
299670
- jsonrpc: z70.literal("2.0"),
300708
+ var JsonRpcIdSchema = z71.union([z71.string(), z71.number(), z71.null()]);
300709
+ var JSONRPCMessageSchema = z71.object({
300710
+ jsonrpc: z71.literal("2.0"),
299671
300711
  id: JsonRpcIdSchema.optional(),
299672
- method: z70.string().min(1).max(512),
299673
- params: z70.unknown().optional()
300712
+ method: z71.string().min(1).max(512),
300713
+ params: z71.unknown().optional()
299674
300714
  }).strict();
299675
- var TextDocumentIdentifierSchema = z70.object({
299676
- uri: z70.string().min(1).max(16384)
300715
+ var TextDocumentIdentifierSchema = z71.object({
300716
+ uri: z71.string().min(1).max(16384)
299677
300717
  });
299678
- var DidOpenParamsSchema = z70.object({
300718
+ var DidOpenParamsSchema = z71.object({
299679
300719
  textDocument: TextDocumentIdentifierSchema.extend({
299680
- text: z70.string().max(MAX_LSP_BODY_BYTES)
300720
+ text: z71.string().max(MAX_LSP_BODY_BYTES)
299681
300721
  }).passthrough()
299682
300722
  });
299683
- var DidChangeParamsSchema = z70.object({
300723
+ var DidChangeParamsSchema = z71.object({
299684
300724
  textDocument: TextDocumentIdentifierSchema,
299685
- contentChanges: z70.array(z70.object({ text: z70.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
300725
+ contentChanges: z71.array(z71.object({ text: z71.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
299686
300726
  });
299687
- var DidCloseParamsSchema = z70.object({
300727
+ var DidCloseParamsSchema = z71.object({
299688
300728
  textDocument: TextDocumentIdentifierSchema
299689
300729
  });
299690
- var CompletionParamsSchema = z70.object({
300730
+ var CompletionParamsSchema = z71.object({
299691
300731
  textDocument: TextDocumentIdentifierSchema,
299692
- position: z70.object({
299693
- line: z70.number().int().nonnegative(),
299694
- character: z70.number().int().nonnegative()
300732
+ position: z71.object({
300733
+ line: z71.number().int().nonnegative(),
300734
+ character: z71.number().int().nonnegative()
299695
300735
  })
299696
300736
  });
299697
300737
  var JSONRPCReader = class {
@@ -299937,7 +300977,7 @@ ${completion}
299937
300977
  );
299938
300978
  }
299939
300979
  } catch (error) {
299940
- if (error instanceof z70.ZodError) {
300980
+ if (error instanceof z71.ZodError) {
299941
300981
  sendError(message2.id, -32602, "Invalid method parameters.");
299942
300982
  return;
299943
300983
  }
@@ -300359,8 +301399,8 @@ async function runMcpLogin(serverName, options = {}) {
300359
301399
 
300360
301400
  // src/commands/skills.ts
300361
301401
  import picocolors24 from "picocolors";
300362
- import { z as z71 } from "zod";
300363
- var SkillDirectoryOverrideSchema = z71.array(z71.string().trim().min(1).max(4096)).min(1).max(50);
301402
+ import { z as z74 } from "zod";
301403
+ var SkillDirectoryOverrideSchema = z74.array(z74.string().trim().min(1).max(4096)).min(1).max(50);
300364
301404
  async function runSkillsCommand(action, options = {}) {
300365
301405
  const cwd = options.cwd ?? process.cwd();
300366
301406
  const config = ConfigLoader.loadSync(cwd);
@@ -300487,10 +301527,10 @@ import {
300487
301527
  } from "fs";
300488
301528
  import { dirname as dirname15, resolve as resolve15 } from "path";
300489
301529
  import { randomUUID as randomUUID14 } from "crypto";
300490
- import { z as z74 } from "zod";
300491
- var TraceOptionsSchema = z74.object({
300492
- full: z74.boolean().default(false),
300493
- out: z74.string().trim().min(1).max(4096).optional()
301530
+ import { z as z75 } from "zod";
301531
+ var TraceOptionsSchema = z75.object({
301532
+ full: z75.boolean().default(false),
301533
+ out: z75.string().trim().min(1).max(4096).optional()
300494
301534
  });
300495
301535
  function runTraceExport(cwd, sessionId, options = {}) {
300496
301536
  const value = TraceOptionsSchema.parse(options);
@@ -300545,16 +301585,16 @@ import { randomUUID as randomUUID15 } from "crypto";
300545
301585
  import { promisify as promisify5 } from "util";
300546
301586
  import picocolors25 from "picocolors";
300547
301587
  import { parse as parseYaml4 } from "yaml";
300548
- import { z as z75 } from "zod";
301588
+ import { z as z76 } from "zod";
300549
301589
  var exec5 = promisify5(execCallback);
300550
301590
  var MAX_SUITE_BYTES = 1024 * 1024;
300551
301591
  var MAX_VERIFICATION_OUTPUT = 4e3;
300552
- var EvalOptionsSchema = z75.object({
300553
- provider: z75.string().trim().min(1).optional(),
300554
- model: z75.string().trim().min(1).optional(),
300555
- task: z75.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
300556
- allowCommands: z75.boolean().default(false),
300557
- json: z75.boolean().default(false)
301592
+ var EvalOptionsSchema = z76.object({
301593
+ provider: z76.string().trim().min(1).optional(),
301594
+ model: z76.string().trim().min(1).optional(),
301595
+ task: z76.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
301596
+ allowCommands: z76.boolean().default(false),
301597
+ json: z76.boolean().default(false)
300558
301598
  });
300559
301599
  async function runEval(cwd, suiteFile, options = {}) {
300560
301600
  const value = EvalOptionsSchema.parse(options);
@@ -300629,6 +301669,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300629
301669
  const sessionId = outcome?.sessionId || void 0;
300630
301670
  let resolvedModels = [];
300631
301671
  let usage2;
301672
+ let reliability;
300632
301673
  let traceFile;
300633
301674
  if (sessionId) {
300634
301675
  const store = new SessionStore(worktree.path);
@@ -300648,6 +301689,23 @@ async function runEval(cwd, suiteFile, options = {}) {
300648
301689
  cacheHitRate: inputTokens > 0 ? Math.min(1, cacheReadTokens / inputTokens) : 0,
300649
301690
  costUsd: trace.session.totalCostEstimate
300650
301691
  };
301692
+ reliability = {
301693
+ attempts: trace.journal?.attempt ?? 0,
301694
+ toolRuns: trace.metrics.toolRuns,
301695
+ toolFailures: trace.metrics.toolFailures,
301696
+ deniedTools: trace.metrics.deniedTools,
301697
+ approvalRequests: trace.toolCalls.filter(
301698
+ (call) => call.permissionDecision === "ask"
301699
+ ).length,
301700
+ compactions: trace.metrics.compactions,
301701
+ resumedCount: trace.metrics.resumedCount,
301702
+ verificationRuns: trace.events.filter(
301703
+ (event) => event.type === "verification_ended"
301704
+ ).length,
301705
+ checkpoints: trace.events.filter(
301706
+ (event) => event.type === "checkpoint_created"
301707
+ ).length
301708
+ };
300651
301709
  traceFile = writeEvaluationTrace(cwd, runId, task.id, trace);
300652
301710
  }
300653
301711
  results.push(
@@ -300655,7 +301713,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300655
301713
  task: {
300656
301714
  ...task,
300657
301715
  provider: task.provider || value.provider,
300658
- model: task.model || value.model
301716
+ model: task.model || value.model,
301717
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300659
301718
  },
300660
301719
  agentStatus: outcome?.status || "failed",
300661
301720
  durationMs: Date.now() - taskStartedAt,
@@ -300663,6 +301722,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300663
301722
  checks,
300664
301723
  resolvedModels,
300665
301724
  usage: usage2,
301725
+ reliability,
300666
301726
  sessionId,
300667
301727
  traceFile
300668
301728
  })
@@ -300673,7 +301733,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300673
301733
  task: {
300674
301734
  ...task,
300675
301735
  provider: task.provider || value.provider,
300676
- model: task.model || value.model
301736
+ model: task.model || value.model,
301737
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300677
301738
  },
300678
301739
  agentStatus: "failed",
300679
301740
  durationMs: Date.now() - taskStartedAt,
@@ -300702,6 +301763,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300702
301763
  passed: passedTasks === results.length,
300703
301764
  passedTasks,
300704
301765
  totalTasks: results.length,
301766
+ summary: buildAcceptanceSummary(results),
300705
301767
  results
300706
301768
  };
300707
301769
  const reportPath = writeEvaluationReport(cwd, runId, report);
@@ -300720,6 +301782,43 @@ async function runEval(cwd, suiteFile, options = {}) {
300720
301782
  if (!report.passed) process.exitCode = 1;
300721
301783
  return report;
300722
301784
  }
301785
+ function buildAcceptanceSummary(results) {
301786
+ const total = results.length;
301787
+ const durations = results.map((result) => result.durationMs).sort((left, right) => left - right);
301788
+ const midpoint = Math.floor(durations.length / 2);
301789
+ const medianDurationMs = durations.length === 0 ? 0 : durations.length % 2 === 1 ? durations[midpoint] : Math.round((durations[midpoint - 1] + durations[midpoint]) / 2);
301790
+ const verificationChecks = results.flatMap((result) => result.checks);
301791
+ const verificationPasses = verificationChecks.filter(
301792
+ (check) => check.passed
301793
+ ).length;
301794
+ const sumUsage = (field) => results.reduce((sum, result) => {
301795
+ const value = result.usage?.[field];
301796
+ return sum + (typeof value === "number" ? value : 0);
301797
+ }, 0);
301798
+ return {
301799
+ completionRate: total > 0 ? results.filter((result) => result.passed).length / total : 0,
301800
+ verificationPassRate: verificationChecks.length > 0 ? verificationPasses / verificationChecks.length : 0,
301801
+ crashOrAbortRate: total > 0 ? results.filter((result) => result.agentStatus !== "completed").length / total : 0,
301802
+ medianDurationMs,
301803
+ totalInputTokens: sumUsage("inputTokens"),
301804
+ totalOutputTokens: sumUsage("outputTokens"),
301805
+ totalCacheReadTokens: sumUsage("cacheReadTokens"),
301806
+ totalApprovalRequests: results.reduce(
301807
+ (sum, result) => sum + (result.reliability?.approvalRequests ?? 0),
301808
+ 0
301809
+ ),
301810
+ totalToolFailures: results.reduce(
301811
+ (sum, result) => sum + (result.reliability?.toolFailures ?? 0),
301812
+ 0
301813
+ ),
301814
+ unintendedFileChangeFindings: results.reduce(
301815
+ (sum, result) => sum + result.failureReasons.filter(
301816
+ (reason) => reason.startsWith("forbidden_file_changed:")
301817
+ ).length,
301818
+ 0
301819
+ )
301820
+ };
301821
+ }
300723
301822
  function loadAcceptanceSuite(cwd, suiteFile) {
300724
301823
  const filePath = resolveSafePath(cwd, suiteFile);
300725
301824
  const stats = lstatSync9(filePath);
@@ -300927,7 +302026,7 @@ function safeSummary(value) {
300927
302026
  import readline6 from "readline";
300928
302027
  import picocolors26 from "picocolors";
300929
302028
  import { resolve as resolve17 } from "path";
300930
- import { z as z77 } from "zod";
302029
+ import { z as z78 } from "zod";
300931
302030
 
300932
302031
  // src/runtime/CleanupManager.ts
300933
302032
  import {
@@ -300939,10 +302038,10 @@ import {
300939
302038
  } from "fs";
300940
302039
  import { homedir as homedir11 } from "os";
300941
302040
  import { basename as basename6, join as join20, parse as parse5, resolve as resolve16 } from "path";
300942
- import { z as z76 } from "zod";
300943
- var CleanupScopeSchema = z76.enum(["user", "project"]);
302041
+ import { z as z77 } from "zod";
302042
+ var CleanupScopeSchema = z77.enum(["user", "project"]);
300944
302043
  function buildCleanupPlan(options) {
300945
- const scopes = z76.array(CleanupScopeSchema).min(1).parse(options.scopes);
302044
+ const scopes = z77.array(CleanupScopeSchema).min(1).parse(options.scopes);
300946
302045
  const homeDirectory = resolve16(options.homeDirectory ?? homedir11());
300947
302046
  const projectDirectory = resolve16(options.projectDirectory ?? options.cwd);
300948
302047
  const candidates = scopes.map((scope) => ({
@@ -301100,12 +302199,12 @@ function safeInventoryWarning(targetPath, error) {
301100
302199
  }
301101
302200
 
301102
302201
  // src/commands/clean.ts
301103
- var CleanCommandOptionsSchema = z77.object({
301104
- user: z77.boolean().default(false),
301105
- project: z77.union([z77.boolean(), z77.string().min(1).max(4096)]).optional(),
301106
- all: z77.boolean().default(false),
301107
- yes: z77.boolean().default(false),
301108
- json: z77.boolean().default(false)
302202
+ var CleanCommandOptionsSchema = z78.object({
302203
+ user: z78.boolean().default(false),
302204
+ project: z78.union([z78.boolean(), z78.string().min(1).max(4096)]).optional(),
302205
+ all: z78.boolean().default(false),
302206
+ yes: z78.boolean().default(false),
302207
+ json: z78.boolean().default(false)
301109
302208
  }).strict();
301110
302209
  async function runClean(cwd, rawOptions, dependencies = {}) {
301111
302210
  const options = CleanCommandOptionsSchema.parse(rawOptions);
@@ -301220,7 +302319,7 @@ async function confirmDeletion(prompt) {
301220
302319
  // src/commands/backup.ts
301221
302320
  import { basename as basename7, resolve as resolve19 } from "path";
301222
302321
  import picocolors27 from "picocolors";
301223
- import { z as z79 } from "zod";
302322
+ import { z as z80 } from "zod";
301224
302323
 
301225
302324
  // src/runtime/ProjectBackup.ts
301226
302325
  import {
@@ -301234,25 +302333,25 @@ import {
301234
302333
  } from "fs";
301235
302334
  import { createHash as createHash10, randomUUID as randomUUID16 } from "crypto";
301236
302335
  import { dirname as dirname17, isAbsolute as isAbsolute9, join as join21, relative as relative10, resolve as resolve18, sep as sep2 } from "path";
301237
- import { z as z78 } from "zod";
302336
+ import { z as z79 } from "zod";
301238
302337
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
301239
302338
  var MAX_SERIALIZED_BACKUP_BYTES = 96 * 1024 * 1024;
301240
302339
  var MAX_BACKUP_FILES = 1e4;
301241
302340
  var MAX_BACKUP_TREE_ENTRIES = 5e4;
301242
302341
  var MAX_BACKUP_TREE_DEPTH = 64;
301243
302342
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
301244
- var BackupFileSchema = z78.object({
301245
- path: z78.string().min(1).max(4096),
301246
- size: z78.number().int().min(0).max(MAX_BACKUP_BYTES),
301247
- sha256: z78.string().regex(SHA256_PATTERN),
301248
- content: z78.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
302343
+ var BackupFileSchema = z79.object({
302344
+ path: z79.string().min(1).max(4096),
302345
+ size: z79.number().int().min(0).max(MAX_BACKUP_BYTES),
302346
+ sha256: z79.string().regex(SHA256_PATTERN),
302347
+ content: z79.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
301249
302348
  });
301250
- var ProjectBackupBundleSchema = z78.object({
301251
- schemaVersion: z78.literal(1),
301252
- kind: z78.literal("orbit-project-backup"),
301253
- createdAt: z78.string().datetime(),
301254
- sourceName: z78.string().min(1).max(512),
301255
- files: z78.array(BackupFileSchema).max(MAX_BACKUP_FILES)
302349
+ var ProjectBackupBundleSchema = z79.object({
302350
+ schemaVersion: z79.literal(1),
302351
+ kind: z79.literal("orbit-project-backup"),
302352
+ createdAt: z79.string().datetime(),
302353
+ sourceName: z79.string().min(1).max(512),
302354
+ files: z79.array(BackupFileSchema).max(MAX_BACKUP_FILES)
301256
302355
  }).superRefine((bundle, context) => {
301257
302356
  let totalBytes = 0;
301258
302357
  const seen = /* @__PURE__ */ new Set();
@@ -301260,7 +302359,7 @@ var ProjectBackupBundleSchema = z78.object({
301260
302359
  totalBytes += file.size;
301261
302360
  if (totalBytes > MAX_BACKUP_BYTES) {
301262
302361
  context.addIssue({
301263
- code: z78.ZodIssueCode.custom,
302362
+ code: z79.ZodIssueCode.custom,
301264
302363
  message: `Backup exceeds ${MAX_BACKUP_BYTES} bytes.`
301265
302364
  });
301266
302365
  break;
@@ -301268,14 +302367,14 @@ var ProjectBackupBundleSchema = z78.object({
301268
302367
  const normalized = normalizeBundlePath(file.path);
301269
302368
  if (!normalized || normalized !== file.path) {
301270
302369
  context.addIssue({
301271
- code: z78.ZodIssueCode.custom,
302370
+ code: z79.ZodIssueCode.custom,
301272
302371
  message: `Unsafe backup path: ${file.path}`
301273
302372
  });
301274
302373
  continue;
301275
302374
  }
301276
302375
  if (seen.has(normalized.toLowerCase())) {
301277
302376
  context.addIssue({
301278
- code: z78.ZodIssueCode.custom,
302377
+ code: z79.ZodIssueCode.custom,
301279
302378
  message: `Duplicate backup path: ${file.path}`
301280
302379
  });
301281
302380
  }
@@ -301508,9 +302607,9 @@ function formatBytes2(bytes) {
301508
302607
  }
301509
302608
 
301510
302609
  // src/commands/backup.ts
301511
- var BackupOptionsSchema = z79.object({
301512
- output: z79.string().min(1).max(4096).optional(),
301513
- json: z79.boolean().default(false)
302610
+ var BackupOptionsSchema = z80.object({
302611
+ output: z80.string().min(1).max(4096).optional(),
302612
+ json: z80.boolean().default(false)
301514
302613
  }).strict();
301515
302614
  function runBackupCreate(cwd, rawOptions = {}) {
301516
302615
  const options = BackupOptionsSchema.parse(rawOptions);
@@ -301610,21 +302709,21 @@ import {
301610
302709
  import { randomUUID as randomUUID17 } from "crypto";
301611
302710
  import { dirname as dirname18, isAbsolute as isAbsolute10, join as join26, relative as relative11, resolve as resolve20, sep as sep3 } from "path";
301612
302711
  import { homedir as homedir12 } from "os";
301613
- import { z as z80 } from "zod";
301614
- var InstalledExtensionSchema2 = z80.object({
302712
+ import { z as z81 } from "zod";
302713
+ var InstalledExtensionSchema2 = z81.object({
301615
302714
  id: InstalledExtensionIdSchema,
301616
- displayName: z80.string().min(1).max(256),
301617
- version: z80.string().min(1).max(128),
301618
- digest: z80.string().regex(/^[a-f0-9]{64}$/),
302715
+ displayName: z81.string().min(1).max(256),
302716
+ version: z81.string().min(1).max(128),
302717
+ digest: z81.string().regex(/^[a-f0-9]{64}$/),
301619
302718
  digestAlgorithm: ExtensionDigestAlgorithmSchema.default("sha256-v1"),
301620
- installedAt: z80.string().datetime(),
301621
- trusted: z80.boolean(),
301622
- path: z80.string().min(1).max(4096),
301623
- manifestFile: z80.string().min(1).max(4096).default("extension.yaml")
302719
+ installedAt: z81.string().datetime(),
302720
+ trusted: z81.boolean(),
302721
+ path: z81.string().min(1).max(4096),
302722
+ manifestFile: z81.string().min(1).max(4096).default("extension.yaml")
301624
302723
  });
301625
- var ExtensionRegistrySchema2 = z80.object({
301626
- schemaVersion: z80.literal(1),
301627
- extensions: z80.array(InstalledExtensionSchema2).max(500).default([])
302724
+ var ExtensionRegistrySchema2 = z81.object({
302725
+ schemaVersion: z81.literal(1),
302726
+ extensions: z81.array(InstalledExtensionSchema2).max(500).default([])
301628
302727
  });
301629
302728
  var ExtensionManager = class {
301630
302729
  orbitDir;
@@ -302300,6 +303399,15 @@ program.command("trace").description("export a redacted, versioned session audit
302300
303399
  });
302301
303400
  if (output) console.log(`Trace exported to ${output}`);
302302
303401
  });
303402
+ 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) => {
303403
+ const result = await runWorkflowExport(process.cwd(), session, {
303404
+ name: options.name,
303405
+ description: options.description,
303406
+ scope: options.scope,
303407
+ json: !!options.json
303408
+ });
303409
+ if (!options.json) console.log(`\u2714 Workflow Skill created: ${result.path}`);
303410
+ });
302303
303411
  program.command("lsp").description("start the local LSP autocomplete server").action(async () => {
302304
303412
  await runLSPServer(process.cwd());
302305
303413
  });