@orbit-build/cli 0.8.6 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +4 -0
  2. package/dist/index.js +1142 -154
  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({
@@ -255029,7 +255063,7 @@ import { z as z83 } from "zod";
255029
255063
  import picocolors3 from "picocolors";
255030
255064
  import path7 from "path";
255031
255065
  import fs32 from "fs";
255032
- import { randomUUID as randomUUID52 } from "crypto";
255066
+ import { randomUUID as randomUUID62 } from "crypto";
255033
255067
  import { exec as exec2, execFile as execFile3 } from "child_process";
255034
255068
  import { promisify as promisify3 } from "util";
255035
255069
  import { z as z46 } from "zod";
@@ -255414,6 +255448,12 @@ var MCPResponseSchema = z36.object({
255414
255448
  }).refine((message2) => message2.result !== void 0 || message2.error, {
255415
255449
  message: "MCP response requires a result or error."
255416
255450
  });
255451
+ var MCP_CATALOG_KINDS = ["tools", "resources", "prompts"];
255452
+ var MCPNotificationSchema = z36.object({
255453
+ jsonrpc: z36.literal("2.0"),
255454
+ method: z36.string().min(1).max(256),
255455
+ params: z36.record(z36.unknown()).optional()
255456
+ });
255417
255457
  async function collectMcpPaginatedItems(options) {
255418
255458
  try {
255419
255459
  return await collectMcpPaginationAttempt(options);
@@ -255547,6 +255587,8 @@ var MCPClient = class {
255547
255587
  resources: false,
255548
255588
  prompts: false
255549
255589
  };
255590
+ catalogListeners = /* @__PURE__ */ new Set();
255591
+ lastError;
255550
255592
  get effectiveRequestTimeoutMs() {
255551
255593
  return this.requestTimeoutMs ?? MCP_REQUEST_TIMEOUT_MS;
255552
255594
  }
@@ -255567,6 +255609,7 @@ var MCPClient = class {
255567
255609
  this.stdoutBuffer = Buffer.alloc(0);
255568
255610
  this.stderrTail = "";
255569
255611
  this.negotiatedProtocol = void 0;
255612
+ this.lastError = void 0;
255570
255613
  child.on("error", (error) => {
255571
255614
  this.cleanup(
255572
255615
  new Error(
@@ -255653,6 +255696,17 @@ var MCPClient = class {
255653
255696
  getNegotiatedProtocol() {
255654
255697
  return this.negotiatedProtocol ? { ...this.negotiatedProtocol } : void 0;
255655
255698
  }
255699
+ onCatalogChanged(listener) {
255700
+ this.catalogListeners.add(listener);
255701
+ return () => this.catalogListeners.delete(listener);
255702
+ }
255703
+ getRuntimeHealth() {
255704
+ return {
255705
+ connected: this.isConnected,
255706
+ recoveryCount: 0,
255707
+ ...this.lastError ? { lastError: this.lastError } : {}
255708
+ };
255709
+ }
255656
255710
  /** List resources when the server advertises them; empty list otherwise. */
255657
255711
  async listResources(abortSignal) {
255658
255712
  if (!this.serverCapabilities.resources) return [];
@@ -255902,12 +255956,26 @@ var MCPClient = class {
255902
255956
  }
255903
255957
  }
255904
255958
  handleIncomingMessage(line) {
255905
- let response;
255959
+ let raw;
255906
255960
  try {
255907
- response = MCPResponseSchema.parse(JSON.parse(line));
255961
+ raw = JSON.parse(line);
255908
255962
  } catch {
255909
255963
  return;
255910
255964
  }
255965
+ const notification = MCPNotificationSchema.safeParse(raw);
255966
+ if (notification.success && typeof raw === "object" && raw !== null && !("id" in raw)) {
255967
+ const kinds = catalogKindsFromNotification(
255968
+ notification.data.method,
255969
+ notification.data.params
255970
+ );
255971
+ if (kinds.length > 0) {
255972
+ for (const listener of this.catalogListeners) listener(kinds);
255973
+ }
255974
+ return;
255975
+ }
255976
+ const parsed = MCPResponseSchema.safeParse(raw);
255977
+ if (!parsed.success) return;
255978
+ const response = parsed.data;
255911
255979
  const pending = this.pendingRequests.get(response.id);
255912
255980
  if (!pending) return;
255913
255981
  clearTimeout(pending.timeout);
@@ -255927,6 +255995,7 @@ var MCPClient = class {
255927
255995
  }
255928
255996
  cleanup(error) {
255929
255997
  this.isConnected = false;
255998
+ this.lastError = safeMessage(error);
255930
255999
  for (const pending of this.pendingRequests.values()) {
255931
256000
  clearTimeout(pending.timeout);
255932
256001
  pending.removeAbortListener?.();
@@ -255935,6 +256004,24 @@ var MCPClient = class {
255935
256004
  this.pendingRequests.clear();
255936
256005
  }
255937
256006
  };
256007
+ function catalogKindsFromNotification(method, params) {
256008
+ const direct = {
256009
+ "notifications/tools/list_changed": "tools",
256010
+ "notifications/resources/list_changed": "resources",
256011
+ "notifications/prompts/list_changed": "prompts"
256012
+ };
256013
+ if (direct[method]) return [direct[method]];
256014
+ if (method !== "notifications/list_changed" && method !== "notifications/catalog_changed") {
256015
+ return [];
256016
+ }
256017
+ const candidates = [
256018
+ params?.collection,
256019
+ ...Array.isArray(params?.collections) ? params.collections : []
256020
+ ];
256021
+ return [...new Set(candidates)].filter(
256022
+ (value) => typeof value === "string" && MCP_CATALOG_KINDS.includes(value)
256023
+ );
256024
+ }
255938
256025
  function waitForChildExit(child, timeoutMs) {
255939
256026
  if (child.exitCode !== null || child.signalCode !== null) {
255940
256027
  return Promise.resolve(true);
@@ -256136,6 +256223,8 @@ var StreamableHttpMCPClient = class {
256136
256223
  started = false;
256137
256224
  negotiatedProtocol;
256138
256225
  reinitializePromise;
256226
+ recoveryCount = 0;
256227
+ lastError;
256139
256228
  mirroredToolParameters = /* @__PURE__ */ new Map();
256140
256229
  protocolWarnings = [];
256141
256230
  serverCapabilities = {
@@ -256201,6 +256290,13 @@ var StreamableHttpMCPClient = class {
256201
256290
  getProtocolWarnings() {
256202
256291
  return [...this.protocolWarnings];
256203
256292
  }
256293
+ getRuntimeHealth() {
256294
+ return {
256295
+ connected: this.started,
256296
+ recoveryCount: this.recoveryCount,
256297
+ ...this.lastError ? { lastError: this.lastError } : {}
256298
+ };
256299
+ }
256204
256300
  /** List resources when the server advertises them; empty list otherwise. */
256205
256301
  async listResources(abortSignal) {
256206
256302
  if (!this.serverCapabilities.resources) return [];
@@ -256318,6 +256414,8 @@ var StreamableHttpMCPClient = class {
256318
256414
  );
256319
256415
  } catch (error) {
256320
256416
  if (error instanceof McpSessionExpiredError && allowSessionRecovery && this.started && this.negotiatedProtocol?.era === "legacy" && method !== "initialize") {
256417
+ this.recoveryCount += 1;
256418
+ this.lastError = safeMessage2(error);
256321
256419
  await this.reinitialize(abortSignal);
256322
256420
  if ("cursor" in params) {
256323
256421
  throw new McpPaginationSessionResetError(this.serverName);
@@ -256349,6 +256447,7 @@ var StreamableHttpMCPClient = class {
256349
256447
  if (modernVersion && method !== "server/discover") {
256350
256448
  assertCompleteModernResult(parsed.data.result, method);
256351
256449
  }
256450
+ this.lastError = void 0;
256352
256451
  return parsed.data.result;
256353
256452
  }
256354
256453
  async negotiateProtocol(abortSignal) {
@@ -260503,6 +260602,7 @@ function isNodeError2(error) {
260503
260602
  import { randomUUID as randomUUID42 } from "crypto";
260504
260603
  import path52 from "path";
260505
260604
  import { z as z73 } from "zod";
260605
+ import { randomUUID as randomUUID52 } from "crypto";
260506
260606
  import { z as z103 } from "zod";
260507
260607
  import { z as z93 } from "zod";
260508
260608
  import { z as z112 } from "zod";
@@ -261836,6 +261936,25 @@ var VerificationEndedEventSchema = z38.object({
261836
261936
  results: z38.unknown().optional()
261837
261937
  })
261838
261938
  });
261939
+ var HookStartedEventSchema = z38.object({
261940
+ type: z38.literal("hook_started"),
261941
+ payload: z38.object({
261942
+ hookId: z38.string(),
261943
+ event: LifecycleHookEventSchema,
261944
+ legacy: z38.boolean()
261945
+ })
261946
+ });
261947
+ var HookCompletedEventSchema = z38.object({
261948
+ type: z38.literal("hook_completed"),
261949
+ payload: z38.object({
261950
+ hookId: z38.string(),
261951
+ event: LifecycleHookEventSchema,
261952
+ success: z38.boolean(),
261953
+ durationMs: z38.number().nonnegative(),
261954
+ action: z38.enum(["continue", "warn", "blocked", "ignored"]),
261955
+ error: z38.string().optional()
261956
+ })
261957
+ });
261839
261958
  var SessionForkEventSchema = z38.object({
261840
261959
  type: z38.literal("session_fork"),
261841
261960
  payload: z38.object({
@@ -261902,6 +262021,8 @@ var OrbitEventSchema = z38.discriminatedUnion("type", [
261902
262021
  CheckpointCreatedEventSchema,
261903
262022
  VerificationStartedEventSchema,
261904
262023
  VerificationEndedEventSchema,
262024
+ HookStartedEventSchema,
262025
+ HookCompletedEventSchema,
261905
262026
  SessionForkEventSchema,
261906
262027
  SessionEndedEventSchema,
261907
262028
  InfoEventSchema,
@@ -262994,6 +263115,10 @@ var McpRuntimeManager = class {
262994
263115
  clients = [];
262995
263116
  registeredTools = /* @__PURE__ */ new Map();
262996
263117
  promptsByServer = /* @__PURE__ */ new Map();
263118
+ runtimes = /* @__PURE__ */ new Map();
263119
+ healthByServer = /* @__PURE__ */ new Map();
263120
+ pendingRefreshKinds = /* @__PURE__ */ new Map();
263121
+ refreshTimers = /* @__PURE__ */ new Map();
262997
263122
  async start(servers, report) {
262998
263123
  await this.stop();
262999
263124
  const result = {
@@ -263050,6 +263175,27 @@ var McpRuntimeManager = class {
263050
263175
  report
263051
263176
  );
263052
263177
  this.clients.push(client);
263178
+ const runtime = {
263179
+ serverName,
263180
+ config: serverConfig,
263181
+ client,
263182
+ report,
263183
+ toolNames: new Set(registeredForClient)
263184
+ };
263185
+ runtime.unsubscribeCatalog = client.onCatalogChanged?.((kinds) => {
263186
+ this.scheduleCatalogRefresh(serverName, kinds);
263187
+ });
263188
+ this.runtimes.set(serverName, runtime);
263189
+ const runtimeHealth = client.getRuntimeHealth?.();
263190
+ this.healthByServer.set(serverName, {
263191
+ serverName,
263192
+ status: "healthy",
263193
+ connected: runtimeHealth?.connected ?? true,
263194
+ registeredTools: runtime.toolNames.size,
263195
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263196
+ ...protocol ? { protocol: protocol.version } : {},
263197
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263198
+ });
263053
263199
  result.startedServers += 1;
263054
263200
  } catch (error) {
263055
263201
  for (const toolName of registeredForClient) {
@@ -263063,6 +263209,14 @@ var McpRuntimeManager = class {
263063
263209
  this.promptsByServer.delete(serverName);
263064
263210
  await client?.stop().catch(() => void 0);
263065
263211
  const message2 = safeMcpRuntimeMessage(error);
263212
+ this.healthByServer.set(serverName, {
263213
+ serverName,
263214
+ status: "failed",
263215
+ connected: false,
263216
+ registeredTools: 0,
263217
+ recoveryCount: 0,
263218
+ lastError: message2
263219
+ });
263066
263220
  result.failures.push({ serverName, message: message2 });
263067
263221
  report(` \u2716 Failed to start MCP server "${serverName}": ${message2}`);
263068
263222
  }
@@ -263079,6 +263233,31 @@ var McpRuntimeManager = class {
263079
263233
  }
263080
263234
  return descriptors2;
263081
263235
  }
263236
+ /** Return a stable, credential-redacted snapshot for doctor and UI surfaces. */
263237
+ listHealth() {
263238
+ return [...this.healthByServer.values()].map((health) => {
263239
+ const runtimeHealth = this.runtimes.get(health.serverName)?.client.getRuntimeHealth?.();
263240
+ return {
263241
+ ...health,
263242
+ status: runtimeHealth && !runtimeHealth.connected ? "degraded" : health.status,
263243
+ connected: runtimeHealth?.connected ?? health.connected,
263244
+ recoveryCount: runtimeHealth?.recoveryCount ?? health.recoveryCount,
263245
+ ...runtimeHealth?.lastError ? { lastError: safeMcpRuntimeMessage(runtimeHealth.lastError) } : {}
263246
+ };
263247
+ }).sort((left, right) => left.serverName.localeCompare(right.serverName));
263248
+ }
263249
+ /** Refresh live catalogs without restarting healthy MCP processes. */
263250
+ async refreshCatalogs(serverName) {
263251
+ const runtimes = serverName ? [this.runtimes.get(serverName)].filter(
263252
+ (runtime) => Boolean(runtime)
263253
+ ) : [...this.runtimes.values()];
263254
+ await Promise.all(
263255
+ runtimes.map(
263256
+ (runtime) => this.refreshServerCatalog(runtime, ["tools", "resources", "prompts"])
263257
+ )
263258
+ );
263259
+ return this.listHealth();
263260
+ }
263082
263261
  /** Resolve one discovered prompt into expanded prompt text. */
263083
263262
  async expandPrompt(serverName, promptName, args) {
263084
263263
  const entry = this.promptsByServer.get(serverName);
@@ -263091,11 +263270,19 @@ var McpRuntimeManager = class {
263091
263270
  return entry.client.getPrompt(prompt.name, args);
263092
263271
  }
263093
263272
  async stop() {
263273
+ for (const timer of this.refreshTimers.values()) clearTimeout(timer);
263274
+ this.refreshTimers.clear();
263275
+ this.pendingRefreshKinds.clear();
263276
+ for (const runtime of this.runtimes.values()) {
263277
+ runtime.unsubscribeCatalog?.();
263278
+ }
263279
+ this.runtimes.clear();
263094
263280
  for (const [toolName, tool] of this.registeredTools) {
263095
263281
  this.registry.unregister(toolName, tool);
263096
263282
  }
263097
263283
  this.registeredTools.clear();
263098
263284
  this.promptsByServer.clear();
263285
+ this.healthByServer.clear();
263099
263286
  const clients = this.clients.splice(0);
263100
263287
  await Promise.allSettled(clients.map((client) => client.stop()));
263101
263288
  }
@@ -263133,12 +263320,182 @@ var McpRuntimeManager = class {
263133
263320
  return;
263134
263321
  }
263135
263322
  const prompts = await client.listPrompts();
263323
+ this.promptsByServer.delete(serverName);
263136
263324
  if (!prompts.length) return;
263137
263325
  this.promptsByServer.set(serverName, { client, prompts });
263138
263326
  report(
263139
263327
  ` \u2714 Discovered ${prompts.length} MCP prompt${prompts.length === 1 ? "" : "s"} on "${serverName}"`
263140
263328
  );
263141
263329
  }
263330
+ scheduleCatalogRefresh(serverName, kinds) {
263331
+ const runtime = this.runtimes.get(serverName);
263332
+ if (!runtime) return;
263333
+ const pending = this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set();
263334
+ for (const kind of kinds) pending.add(kind);
263335
+ this.pendingRefreshKinds.set(serverName, pending);
263336
+ if (this.refreshTimers.has(serverName)) return;
263337
+ const timer = setTimeout(() => {
263338
+ this.refreshTimers.delete(serverName);
263339
+ const nextKinds = [
263340
+ ...this.pendingRefreshKinds.get(serverName) ?? /* @__PURE__ */ new Set()
263341
+ ];
263342
+ this.pendingRefreshKinds.delete(serverName);
263343
+ void this.refreshServerCatalog(runtime, nextKinds);
263344
+ }, 100);
263345
+ timer.unref?.();
263346
+ this.refreshTimers.set(serverName, timer);
263347
+ }
263348
+ async refreshServerCatalog(runtime, kinds) {
263349
+ const current = this.healthByServer.get(runtime.serverName);
263350
+ this.healthByServer.set(runtime.serverName, {
263351
+ ...current ?? {
263352
+ serverName: runtime.serverName,
263353
+ connected: true,
263354
+ registeredTools: runtime.toolNames.size,
263355
+ recoveryCount: 0
263356
+ },
263357
+ status: "refreshing"
263358
+ });
263359
+ try {
263360
+ if (kinds.includes("tools") && runtime.client.listTools) {
263361
+ await this.refreshTools(runtime, await runtime.client.listTools());
263362
+ }
263363
+ if (kinds.includes("resources")) {
263364
+ await this.refreshResourceTool(runtime);
263365
+ }
263366
+ if (kinds.includes("prompts")) {
263367
+ await this.captureServerPrompts(
263368
+ runtime.serverName,
263369
+ runtime.config,
263370
+ runtime.client,
263371
+ runtime.report
263372
+ );
263373
+ }
263374
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263375
+ this.healthByServer.set(runtime.serverName, {
263376
+ serverName: runtime.serverName,
263377
+ status: "healthy",
263378
+ connected: runtimeHealth?.connected ?? true,
263379
+ registeredTools: runtime.toolNames.size,
263380
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263381
+ ...runtime.client.getNegotiatedProtocol?.()?.version ? { protocol: runtime.client.getNegotiatedProtocol?.()?.version } : {},
263382
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString()
263383
+ });
263384
+ runtime.report(
263385
+ ` \u2714 Refreshed MCP catalog for "${runtime.serverName}" (${kinds.join(", ")})`
263386
+ );
263387
+ } catch (error) {
263388
+ const message2 = safeMcpRuntimeMessage(error);
263389
+ const runtimeHealth = runtime.client.getRuntimeHealth?.();
263390
+ this.healthByServer.set(runtime.serverName, {
263391
+ serverName: runtime.serverName,
263392
+ status: "degraded",
263393
+ connected: runtimeHealth?.connected ?? true,
263394
+ registeredTools: runtime.toolNames.size,
263395
+ recoveryCount: runtimeHealth?.recoveryCount ?? 0,
263396
+ ...current?.protocol ? { protocol: current.protocol } : {},
263397
+ lastRefreshAt: (/* @__PURE__ */ new Date()).toISOString(),
263398
+ lastError: message2
263399
+ });
263400
+ runtime.report(
263401
+ ` \u26A0\uFE0F MCP catalog refresh failed for "${runtime.serverName}": ${message2}`
263402
+ );
263403
+ }
263404
+ }
263405
+ async refreshTools(runtime, definitions) {
263406
+ const resourceToolName = createMcpToolName(
263407
+ runtime.serverName,
263408
+ "read_resource"
263409
+ );
263410
+ const oldNames = [...runtime.toolNames].filter(
263411
+ (name) => name !== resourceToolName
263412
+ );
263413
+ const oldTools = new Map(
263414
+ oldNames.flatMap((name) => {
263415
+ const tool = this.registeredTools.get(name);
263416
+ return tool ? [[name, tool]] : [];
263417
+ })
263418
+ );
263419
+ const replacements = definitions.map((definition) => {
263420
+ const risk = runtime.config.tools?.[definition.name]?.risk ?? "execute";
263421
+ return new DynamicMCPTool(
263422
+ runtime.serverName,
263423
+ definition,
263424
+ risk,
263425
+ runtime.client
263426
+ );
263427
+ });
263428
+ const replacementNames = /* @__PURE__ */ new Set();
263429
+ for (const tool of replacements) {
263430
+ if (replacementNames.has(tool.name)) {
263431
+ throw new Error(`MCP refresh produced duplicate tool ${tool.name}.`);
263432
+ }
263433
+ replacementNames.add(tool.name);
263434
+ const collision = this.registry.get(tool.name);
263435
+ if (collision && !oldTools.has(tool.name)) {
263436
+ throw new Error(`MCP refresh collided with tool ${tool.name}.`);
263437
+ }
263438
+ }
263439
+ for (const [name, tool] of oldTools) {
263440
+ this.registry.unregister(name, tool);
263441
+ this.registeredTools.delete(name);
263442
+ runtime.toolNames.delete(name);
263443
+ }
263444
+ const registered = [];
263445
+ try {
263446
+ for (const tool of replacements) {
263447
+ this.registry.register(tool);
263448
+ this.registeredTools.set(tool.name, tool);
263449
+ runtime.toolNames.add(tool.name);
263450
+ registered.push(tool);
263451
+ }
263452
+ } catch (error) {
263453
+ for (const tool of registered) {
263454
+ this.registry.unregister(tool.name, tool);
263455
+ this.registeredTools.delete(tool.name);
263456
+ runtime.toolNames.delete(tool.name);
263457
+ }
263458
+ for (const [name, tool] of oldTools) {
263459
+ this.registry.register(tool);
263460
+ this.registeredTools.set(name, tool);
263461
+ runtime.toolNames.add(name);
263462
+ }
263463
+ throw error;
263464
+ }
263465
+ }
263466
+ async refreshResourceTool(runtime) {
263467
+ const resourceName = createMcpToolName(runtime.serverName, "read_resource");
263468
+ const oldTool = this.registeredTools.get(resourceName);
263469
+ if (oldTool) {
263470
+ this.registry.unregister(resourceName, oldTool);
263471
+ this.registeredTools.delete(resourceName);
263472
+ runtime.toolNames.delete(resourceName);
263473
+ }
263474
+ const result = {
263475
+ startedServers: 1,
263476
+ registeredTools: runtime.toolNames.size,
263477
+ failures: []
263478
+ };
263479
+ const registered = [];
263480
+ try {
263481
+ await this.registerResourceTool(
263482
+ runtime.serverName,
263483
+ runtime.config,
263484
+ runtime.client,
263485
+ registered,
263486
+ result,
263487
+ runtime.report
263488
+ );
263489
+ for (const name of registered) runtime.toolNames.add(name);
263490
+ } catch (error) {
263491
+ if (oldTool) {
263492
+ this.registry.register(oldTool);
263493
+ this.registeredTools.set(resourceName, oldTool);
263494
+ runtime.toolNames.add(resourceName);
263495
+ }
263496
+ throw error;
263497
+ }
263498
+ }
263142
263499
  };
263143
263500
  function safeMcpRuntimeMessage(error) {
263144
263501
  const raw = error instanceof Error ? error.message : String(error);
@@ -263508,6 +263865,113 @@ function parseSearchResultBlocks(content) {
263508
263865
  }
263509
263866
  return results;
263510
263867
  }
263868
+ var WRITE_TOOLS = /* @__PURE__ */ new Set([
263869
+ "write_file",
263870
+ "edit_file",
263871
+ "replace_file_content",
263872
+ "multi_replace_file_content"
263873
+ ]);
263874
+ function selectLifecycleHooks(hooks, event, context) {
263875
+ const configured = hooks.lifecycle?.[event] ?? [];
263876
+ const selected = configured.filter((hook) => matchesLifecycleHook(hook.matcher, event, context)).map((hook) => ({ ...hook, legacy: false }));
263877
+ const isWriteTool = context.toolName ? WRITE_TOOLS.has(context.toolName) : false;
263878
+ if (event === "preToolUse" && isWriteTool && context.filePath && hooks.preEdit) {
263879
+ selected.unshift({
263880
+ command: hooks.preEdit,
263881
+ timeoutMs: 3e4,
263882
+ onFailure: "block",
263883
+ legacy: true
263884
+ });
263885
+ }
263886
+ if (event === "postToolUse" && isWriteTool && context.filePath && hooks.postEdit) {
263887
+ selected.unshift({
263888
+ command: hooks.postEdit,
263889
+ timeoutMs: 3e4,
263890
+ onFailure: "block",
263891
+ legacy: true
263892
+ });
263893
+ }
263894
+ return selected;
263895
+ }
263896
+ function matchesLifecycleHook(matcher, event, context) {
263897
+ if (!matcher) return true;
263898
+ const subject = context.toolName || context.agentRole || context.filePath || context.status || event;
263899
+ return globMatches(matcher, subject);
263900
+ }
263901
+ function buildLifecycleHookEnvironment(event, context) {
263902
+ const safeContext = Object.fromEntries(
263903
+ Object.entries(context).filter(([, value]) => value !== void 0)
263904
+ );
263905
+ const payload = redactSecrets(JSON.stringify(safeContext)).slice(0, 32768);
263906
+ return {
263907
+ ORBIT_HOOK_EVENT: event,
263908
+ ORBIT_HOOK_PAYLOAD: payload,
263909
+ ORBIT_SESSION_ID: context.sessionId,
263910
+ ...context.toolName ? { ORBIT_TOOL_NAME: context.toolName } : {},
263911
+ ...context.filePath ? { ORBIT_FILE: context.filePath } : {},
263912
+ ...context.agentRole ? { ORBIT_AGENT_ROLE: context.agentRole } : {},
263913
+ ...context.status ? { ORBIT_HOOK_STATUS: context.status } : {}
263914
+ };
263915
+ }
263916
+ async function executeLifecycleHooks(options) {
263917
+ const hooks = selectLifecycleHooks(
263918
+ options.hooks,
263919
+ options.event,
263920
+ options.context
263921
+ );
263922
+ for (const hook of hooks) {
263923
+ const hookId = `hook_${randomUUID52()}`;
263924
+ const startedAt = Date.now();
263925
+ eventBus.emitEvent("hook_started", {
263926
+ hookId,
263927
+ event: options.event,
263928
+ legacy: hook.legacy
263929
+ });
263930
+ options.report(`\u25CF Running ${options.event} hook...`);
263931
+ const result = await options.execute(
263932
+ hook,
263933
+ buildLifecycleHookEnvironment(options.event, options.context)
263934
+ );
263935
+ if (result.ok) {
263936
+ eventBus.emitEvent("hook_completed", {
263937
+ hookId,
263938
+ event: options.event,
263939
+ success: true,
263940
+ durationMs: Date.now() - startedAt,
263941
+ action: "continue"
263942
+ });
263943
+ options.report(`\u2714 ${options.event} hook passed.`);
263944
+ continue;
263945
+ }
263946
+ const action = hook.onFailure === "block" ? "blocked" : hook.onFailure === "ignore" ? "ignored" : "warn";
263947
+ eventBus.emitEvent("hook_completed", {
263948
+ hookId,
263949
+ event: options.event,
263950
+ success: false,
263951
+ durationMs: Date.now() - startedAt,
263952
+ action,
263953
+ error: result.output
263954
+ });
263955
+ if (hook.onFailure === "block") {
263956
+ options.report(`\u2716 ${options.event} hook blocked: ${result.output}`);
263957
+ return { ok: false, output: result.output };
263958
+ }
263959
+ if (hook.onFailure === "warn") {
263960
+ options.report(`\u26A0\uFE0F ${options.event} hook warning: ${result.output}`);
263961
+ }
263962
+ }
263963
+ return { ok: true };
263964
+ }
263965
+ function globMatches(pattern, value) {
263966
+ let source = "^";
263967
+ for (const character of pattern) {
263968
+ if (character === "*") source += ".*";
263969
+ else if (character === "?") source += ".";
263970
+ else source += character.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
263971
+ }
263972
+ source += "$";
263973
+ return new RegExp(source, "iu").test(value);
263974
+ }
263511
263975
  var execPromise2 = promisify3(exec2);
263512
263976
  var execFilePromise3 = promisify3(execFile3);
263513
263977
  var DEEPSEEK_CACHE_DEGRADED_HIT_RATE = 0.85;
@@ -263711,6 +264175,14 @@ var AgentLoop = class _AgentLoop {
263711
264175
  expandMcpPrompt(serverName, promptName, args) {
263712
264176
  return this.mcpRuntimeManager.expandPrompt(serverName, promptName, args);
263713
264177
  }
264178
+ /** Browser/terminal-safe MCP health snapshots. */
264179
+ listMcpHealth() {
264180
+ return this.mcpRuntimeManager.listHealth();
264181
+ }
264182
+ /** Refresh tool, resource, and prompt catalogs without restarting servers. */
264183
+ refreshMcpCatalogs(serverName) {
264184
+ return this.mcpRuntimeManager.refreshCatalogs(serverName);
264185
+ }
263714
264186
  /** Start configured MCP servers once and retain them for this loop's lifetime. */
263715
264187
  async initializeMcp() {
263716
264188
  if (this.mcpStartResult) return this.mcpStartResult;
@@ -263879,7 +264351,7 @@ var AgentLoop = class _AgentLoop {
263879
264351
  }
263880
264352
  appendBackgroundTaskNotification(tasks, remainingRunning = 0) {
263881
264353
  const message2 = {
263882
- id: `msg_background_tasks_${randomUUID52().replace(/-/g, "")}`,
264354
+ id: `msg_background_tasks_${randomUUID62().replace(/-/g, "")}`,
263883
264355
  role: "user",
263884
264356
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
263885
264357
  content: [
@@ -263977,11 +264449,37 @@ var AgentLoop = class _AgentLoop {
263977
264449
  } finally {
263978
264450
  await this.contextBuilder.settleBackgroundWork().catch(() => void 0);
263979
264451
  }
264452
+ if (this.options.agent?.role) {
264453
+ const subagentStopHooks = await this.runLifecycleHooks("subagentStop", {
264454
+ sessionId: this.state.sessionId,
264455
+ attempt: this.state.attemptCount,
264456
+ agentRole: this.options.agent.role,
264457
+ status: outcome.status
264458
+ });
264459
+ if (!subagentStopHooks.ok && outcome.status === "completed") {
264460
+ outcome = this.createFailedOutcome(
264461
+ "execution_error",
264462
+ subagentStopHooks.output || "A blocking subagent-stop hook failed."
264463
+ );
264464
+ }
264465
+ }
264466
+ const stopHooks = await this.runLifecycleHooks("stop", {
264467
+ sessionId: this.state.sessionId,
264468
+ attempt: this.state.attemptCount,
264469
+ status: outcome.status
264470
+ });
264471
+ if (!stopHooks.ok && outcome.status === "completed") {
264472
+ outcome = this.createFailedOutcome(
264473
+ "execution_error",
264474
+ stopHooks.output || "A blocking stop hook failed."
264475
+ );
264476
+ }
263980
264477
  this.finalizeOutcome(outcome);
263981
264478
  return outcome;
263982
264479
  }
263983
264480
  async executeRun() {
263984
264481
  const runStartedAt = /* @__PURE__ */ new Date();
264482
+ const isNewSession = this.state.history.length === 0;
263985
264483
  let iterationLimitReached = false;
263986
264484
  eventBus.emitEvent("agent_start", {
263987
264485
  taskId: this.state.sessionId,
@@ -264010,8 +264508,48 @@ var AgentLoop = class _AgentLoop {
264010
264508
  this.sessionManager.saveHistory(this.state.history);
264011
264509
  void this.provider.initialize?.().catch(() => {
264012
264510
  });
264511
+ if (isNewSession) {
264512
+ const sessionHooks = await this.runLifecycleHooks("sessionStart", {
264513
+ sessionId: this.state.sessionId,
264514
+ attempt: this.state.attemptCount
264515
+ });
264516
+ if (!sessionHooks.ok) {
264517
+ return this.createFailedOutcome(
264518
+ "execution_error",
264519
+ sessionHooks.output || "A blocking session-start hook failed."
264520
+ );
264521
+ }
264522
+ }
264523
+ const promptHooks = await this.runLifecycleHooks("promptSubmit", {
264524
+ sessionId: this.state.sessionId,
264525
+ attempt: this.state.attemptCount,
264526
+ promptLength: this.state.task.length
264527
+ });
264528
+ if (!promptHooks.ok) {
264529
+ return this.createFailedOutcome(
264530
+ "execution_error",
264531
+ promptHooks.output || "A blocking prompt hook failed."
264532
+ );
264533
+ }
264534
+ if (this.options.agent?.role) {
264535
+ const subagentStartHooks = await this.runLifecycleHooks("subagentStart", {
264536
+ sessionId: this.state.sessionId,
264537
+ attempt: this.state.attemptCount,
264538
+ agentRole: this.options.agent.role
264539
+ });
264540
+ if (!subagentStartHooks.ok) {
264541
+ return this.createFailedOutcome(
264542
+ "execution_error",
264543
+ subagentStartHooks.output || "A blocking subagent-start hook failed."
264544
+ );
264545
+ }
264546
+ }
264013
264547
  void this.contextBuilder.warmCodebaseRetrieval().catch(() => void 0);
264548
+ const mcpWasInitialized = Boolean(this.mcpStartResult);
264014
264549
  await this.initializeMcp();
264550
+ if (mcpWasInitialized) {
264551
+ await this.refreshMcpCatalogs();
264552
+ }
264015
264553
  const sigintListener = () => {
264016
264554
  if (this.abortController) {
264017
264555
  this.interaction.showText(
@@ -264738,6 +265276,20 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264738
265276
  this.interaction.showText(
264739
265277
  "\n\u25CF Verification: Running contract verification checks..."
264740
265278
  );
265279
+ const verificationStartHooks = await this.runLifecycleHooks(
265280
+ "verificationStart",
265281
+ {
265282
+ sessionId: this.state.sessionId,
265283
+ attempt: this.state.attemptCount,
265284
+ status: "contract"
265285
+ }
265286
+ );
265287
+ if (!verificationStartHooks.ok) {
265288
+ return this.createFailedOutcome(
265289
+ "verification_failed",
265290
+ verificationStartHooks.output || "A blocking verification-start hook failed."
265291
+ );
265292
+ }
264741
265293
  const verificationWorkspaceBefore = await captureWorkspaceMutationSnapshot(this.cwd);
264742
265294
  const verifyResult = await this.verificationManager.runVerification();
264743
265295
  const verificationWorkspaceAfter = await captureWorkspaceMutationSnapshot(this.cwd);
@@ -264753,6 +265305,21 @@ Orbit: ${this.interaction.formatMarkdown?.(responseText) || responseText}`
264753
265305
  );
264754
265306
  }
264755
265307
  this.recordVerificationResult(verifyResult.success);
265308
+ const verificationEndHooks = await this.runLifecycleHooks(
265309
+ "verificationEnd",
265310
+ {
265311
+ sessionId: this.state.sessionId,
265312
+ attempt: this.state.attemptCount,
265313
+ status: verifyResult.success ? "passed" : "failed",
265314
+ verificationPassed: verifyResult.success
265315
+ }
265316
+ );
265317
+ if (!verificationEndHooks.ok) {
265318
+ return this.createFailedOutcome(
265319
+ "verification_failed",
265320
+ verificationEndHooks.output || "A blocking verification-end hook failed."
265321
+ );
265322
+ }
264756
265323
  if (!verifyResult.success) {
264757
265324
  const maxRepairAttempts = this.verificationManager.getMaxRepairAttempts();
264758
265325
  const repairAttempts = countRepairAttemptsForCurrentTask(
@@ -265124,6 +265691,30 @@ Please analyze this failure log, locate the files causing assertion or compile e
265124
265691
  risk: decision2.risk
265125
265692
  };
265126
265693
  }
265694
+ if (decision2.action === "ask") {
265695
+ const permissionHooks = await this.runLifecycleHooks(
265696
+ "permissionRequest",
265697
+ {
265698
+ sessionId: this.state.sessionId,
265699
+ attempt: this.state.attemptCount,
265700
+ toolName: tc.name,
265701
+ filePath: firstStringValue(
265702
+ evalArgsRecord.path,
265703
+ evalArgsRecord.TargetFile,
265704
+ evalArgsRecord.filePath,
265705
+ evalArgsRecord.file
265706
+ ),
265707
+ status: decision2.risk
265708
+ }
265709
+ );
265710
+ if (!permissionHooks.ok) {
265711
+ decision2 = {
265712
+ action: "deny",
265713
+ reason: permissionHooks.output || `A blocking permission hook rejected ${tc.name}.`,
265714
+ risk: decision2.risk
265715
+ };
265716
+ }
265717
+ }
265127
265718
  if (decision2.action === "deny") {
265128
265719
  this.interaction.showText(`\u2716 Blocked: ${decision2.reason}`);
265129
265720
  eventBus.emitEvent("tool_approval", {
@@ -265499,25 +266090,20 @@ ${stdout2.substring(0, 2e4)}`
265499
266090
  )
265500
266091
  );
265501
266092
  }
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
- }
266093
+ }
266094
+ const preToolHooks = await this.runLifecycleHooks("preToolUse", {
266095
+ sessionId: this.state.sessionId,
266096
+ attempt: this.state.attemptCount,
266097
+ toolName: tc.name,
266098
+ filePath: targetPath,
266099
+ agentRole: this.options.agent?.role
266100
+ });
266101
+ if (!preToolHooks.ok) {
266102
+ hookResult = {
266103
+ ok: false,
266104
+ error: preToolHooks.output || `A blocking pre-tool hook rejected ${tc.name}.`
266105
+ };
266106
+ skipToolExecution = true;
265521
266107
  }
265522
266108
  this.interaction.progress?.start(
265523
266109
  `Executing tool: ${tc.name}... | Cost: ${this.formatSessionCost()}`
@@ -265565,24 +266151,23 @@ ${stdout2.substring(0, 2e4)}`
265565
266151
  }
265566
266152
  }
265567
266153
  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.`);
266154
+ if (!skipToolExecution) {
266155
+ const postToolHooks = await this.runLifecycleHooks(
266156
+ result.ok ? "postToolUse" : "postToolFailure",
266157
+ {
266158
+ sessionId: this.state.sessionId,
266159
+ attempt: this.state.attemptCount,
266160
+ toolName: tc.name,
266161
+ filePath: targetPath,
266162
+ agentRole: this.options.agent?.role,
266163
+ status: result.ok ? "success" : "failure"
265585
266164
  }
266165
+ );
266166
+ if (!postToolHooks.ok) {
266167
+ finalResult = {
266168
+ ok: false,
266169
+ error: postToolHooks.output || `A blocking post-tool hook failed for ${tc.name}.`
266170
+ };
265586
266171
  }
265587
266172
  }
265588
266173
  if (finalResult.ok && targetPath && absoluteTargetPath && (tc.name === "write_file" || tc.name === "edit_file" || tc.name === "replace_file_content" || tc.name === "multi_replace_file_content")) {
@@ -266473,11 +267058,41 @@ ${diff.substring(0, 2e4)}`
266473
267058
  output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
266474
267059
  };
266475
267060
  }
266476
- const toolCallId = `hook_${randomUUID52()}`;
267061
+ return this.runHookCommand(
267062
+ hookCommand,
267063
+ { ORBIT_FILE: relativePath },
267064
+ this.config.tools.bash.timeoutMs
267065
+ );
267066
+ }
267067
+ async runLifecycleHooks(event, context) {
267068
+ return executeLifecycleHooks({
267069
+ hooks: this.config.hooks,
267070
+ event,
267071
+ context,
267072
+ execute: (hook, environment) => hook.legacy ? this.runHook(hook.command, context.filePath || "") : this.runHookCommand(
267073
+ hook.command,
267074
+ environment,
267075
+ hook.timeoutMs,
267076
+ event !== "stop" && event !== "subagentStop"
267077
+ ),
267078
+ report: (message2) => this.interaction.showText(message2)
267079
+ });
267080
+ }
267081
+ async runHookCommand(hookCommand, environment, timeoutMs, abortable = true) {
267082
+ if (hookCommand.includes("{file}")) {
267083
+ return {
267084
+ ok: false,
267085
+ output: 'Unsafe hook placeholder "{file}" is no longer supported. Read the ORBIT_FILE environment variable instead.'
267086
+ };
267087
+ }
267088
+ const toolCallId = `hook_${randomUUID62()}`;
266477
267089
  eventBus.emitEvent("tool_proposal", {
266478
267090
  toolCallId,
266479
267091
  toolName: "hook",
266480
- arguments: { filePath: relativePath },
267092
+ arguments: {
267093
+ event: environment.ORBIT_HOOK_EVENT || "legacy",
267094
+ filePath: environment.ORBIT_FILE
267095
+ },
266481
267096
  explanation: "Run a configured Orbit lifecycle hook."
266482
267097
  });
266483
267098
  const decision2 = this.permissionEngine.evaluate(
@@ -266528,12 +267143,9 @@ ${diff.substring(0, 2e4)}`
266528
267143
  const { stdout: stdout2, stderr } = await execPromise2(hookCommand, {
266529
267144
  ...HIDDEN_CHILD_PROCESS_OPTIONS,
266530
267145
  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
267146
+ env: this.buildChildProcessEnvironment(environment, true),
267147
+ timeout: Math.min(timeoutMs, this.config.tools.bash.timeoutMs),
267148
+ signal: abortable ? this.abortController?.signal : void 0
266537
267149
  });
266538
267150
  const output = safeHookOutput(stdout2 + stderr);
266539
267151
  eventBus.emitEvent("tool_result", {
@@ -266591,7 +267203,7 @@ ${diff.substring(0, 2e4)}`
266591
267203
  const now = (/* @__PURE__ */ new Date()).toISOString();
266592
267204
  const plan = this.sessionManager.getTaskPlan();
266593
267205
  const item = {
266594
- id: `step_${randomUUID52()}`,
267206
+ id: `step_${randomUUID62()}`,
266595
267207
  text: text2.trim(),
266596
267208
  status: "pending",
266597
267209
  createdAt: now,
@@ -266722,7 +267334,7 @@ ${diff.substring(0, 2e4)}`
266722
267334
  this.finalResponseOnlyReason = null;
266723
267335
  for (const input of inputs) {
266724
267336
  this.state.history.push({
266725
- id: `msg_user_steer_${randomUUID52().replace(/-/g, "")}`,
267337
+ id: `msg_user_steer_${randomUUID62().replace(/-/g, "")}`,
266726
267338
  role: "user",
266727
267339
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
266728
267340
  content: [{ type: "text", text: input.text }, ...input.attachments],
@@ -267106,6 +267718,16 @@ ${diff.substring(0, 2e4)}`
267106
267718
  * Only fires when Phase 1 alone isn't enough to keep history bounded.
267107
267719
  */
267108
267720
  async compactHistory(mode, targetHistoryTokens) {
267721
+ const preCompactHooks = await this.runLifecycleHooks("preCompact", {
267722
+ sessionId: this.state.sessionId,
267723
+ attempt: this.state.attemptCount,
267724
+ mode
267725
+ });
267726
+ if (!preCompactHooks.ok) {
267727
+ throw new Error(
267728
+ preCompactHooks.output || "A blocking pre-compaction hook failed."
267729
+ );
267730
+ }
267109
267731
  const status = this.getContextWindowStatus();
267110
267732
  const { history, droppedHistory, summaryMessageId, ...result } = compactHistoryMessages(this.state.history, {
267111
267733
  mode,
@@ -267127,10 +267749,22 @@ ${diff.substring(0, 2e4)}`
267127
267749
  this.state.history = history;
267128
267750
  this.sessionManager.saveHistory(this.state.history);
267129
267751
  }
267130
- return {
267752
+ const finalResult = {
267131
267753
  ...this.getContextWindowStatus(),
267132
267754
  ...result
267133
267755
  };
267756
+ const postCompactHooks = await this.runLifecycleHooks("postCompact", {
267757
+ sessionId: this.state.sessionId,
267758
+ attempt: this.state.attemptCount,
267759
+ mode,
267760
+ status: result.changed ? "changed" : "unchanged"
267761
+ });
267762
+ if (!postCompactHooks.ok) {
267763
+ throw new Error(
267764
+ postCompactHooks.output || "A blocking post-compaction hook failed."
267765
+ );
267766
+ }
267767
+ return finalResult;
267134
267768
  }
267135
267769
  /** Compacts older dialogue on demand while preserving the active turn. */
267136
267770
  async compactHistoryPublic() {
@@ -268592,13 +269226,20 @@ var AcceptanceTaskSchema = z132.object({
268592
269226
  maxInputTokens: z132.number().int().nonnegative().optional(),
268593
269227
  maxOutputTokens: z132.number().int().nonnegative().optional(),
268594
269228
  maxCostUsd: z132.number().finite().nonnegative().optional(),
268595
- minCacheHitRate: z132.number().finite().min(0).max(1).optional()
269229
+ minCacheHitRate: z132.number().finite().min(0).max(1).optional(),
269230
+ maxToolFailures: z132.number().int().nonnegative().optional(),
269231
+ maxDeniedTools: z132.number().int().nonnegative().optional(),
269232
+ maxApprovalRequests: z132.number().int().nonnegative().optional(),
269233
+ maxCompactions: z132.number().int().nonnegative().optional(),
269234
+ maxAttempts: z132.number().int().nonnegative().optional(),
269235
+ maxToolFailureRate: z132.number().finite().min(0).max(1).optional()
268596
269236
  }).optional()
268597
269237
  });
268598
269238
  var AcceptanceSuiteSchema = z132.object({
268599
269239
  schemaVersion: z132.literal(1),
268600
269240
  name: z132.string().trim().min(1).max(200),
268601
269241
  description: z132.string().trim().max(2e3).optional(),
269242
+ defaultLimits: AcceptanceTaskSchema.shape.limits,
268602
269243
  tasks: z132.array(AcceptanceTaskSchema).min(1).max(100)
268603
269244
  });
268604
269245
  var AcceptanceCheckResultSchema = z132.object({
@@ -268625,6 +269266,17 @@ var AcceptanceTaskResultSchema = z132.object({
268625
269266
  cacheHitRate: z132.number().finite().min(0).max(1),
268626
269267
  costUsd: z132.number().finite().nonnegative()
268627
269268
  }).optional(),
269269
+ reliability: z132.object({
269270
+ attempts: z132.number().int().nonnegative(),
269271
+ toolRuns: z132.number().int().nonnegative(),
269272
+ toolFailures: z132.number().int().nonnegative(),
269273
+ deniedTools: z132.number().int().nonnegative(),
269274
+ approvalRequests: z132.number().int().nonnegative(),
269275
+ compactions: z132.number().int().nonnegative(),
269276
+ resumedCount: z132.number().int().nonnegative(),
269277
+ verificationRuns: z132.number().int().nonnegative(),
269278
+ checkpoints: z132.number().int().nonnegative()
269279
+ }).optional(),
268628
269280
  changedFiles: z132.array(z132.string()),
268629
269281
  checks: z132.array(AcceptanceCheckResultSchema),
268630
269282
  failureReasons: z132.array(z132.string())
@@ -268685,6 +269337,19 @@ function scoreAcceptanceTask(input) {
268685
269337
  `duration_limit:${Math.round(input.durationMs)}>${task.limits.maxDurationMs}`
268686
269338
  );
268687
269339
  }
269340
+ const reliabilityLimitsConfigured = [
269341
+ task.limits.maxToolFailures,
269342
+ task.limits.maxDeniedTools,
269343
+ task.limits.maxApprovalRequests,
269344
+ task.limits.maxCompactions,
269345
+ task.limits.maxAttempts,
269346
+ task.limits.maxToolFailureRate
269347
+ ].some((value) => value !== void 0);
269348
+ if (reliabilityLimitsConfigured && !input.reliability) {
269349
+ failureReasons.push("reliability_missing");
269350
+ } else if (input.reliability) {
269351
+ enforceReliabilityLimits(task, input.reliability, failureReasons);
269352
+ }
268688
269353
  }
268689
269354
  return AcceptanceTaskResultSchema.parse({
268690
269355
  taskId: task.id,
@@ -268697,11 +269362,39 @@ function scoreAcceptanceTask(input) {
268697
269362
  requestedModel: task.model,
268698
269363
  resolvedModels: Array.from(new Set(input.resolvedModels || [])),
268699
269364
  usage: input.usage,
269365
+ reliability: input.reliability,
268700
269366
  changedFiles,
268701
269367
  checks: input.checks,
268702
269368
  failureReasons
268703
269369
  });
268704
269370
  }
269371
+ function enforceReliabilityLimits(task, reliability, failureReasons) {
269372
+ const limits = task.limits;
269373
+ if (!limits) return;
269374
+ for (const [name, actual, maximum] of [
269375
+ ["tool_failure_limit", reliability.toolFailures, limits.maxToolFailures],
269376
+ ["denied_tool_limit", reliability.deniedTools, limits.maxDeniedTools],
269377
+ [
269378
+ "approval_request_limit",
269379
+ reliability.approvalRequests,
269380
+ limits.maxApprovalRequests
269381
+ ],
269382
+ ["compaction_limit", reliability.compactions, limits.maxCompactions],
269383
+ ["attempt_limit", reliability.attempts, limits.maxAttempts]
269384
+ ]) {
269385
+ if (maximum !== void 0 && actual > maximum) {
269386
+ failureReasons.push(`${name}:${actual}>${maximum}`);
269387
+ }
269388
+ }
269389
+ if (limits.maxToolFailureRate !== void 0) {
269390
+ const rate = reliability.toolRuns > 0 ? reliability.toolFailures / reliability.toolRuns : 0;
269391
+ if (rate > limits.maxToolFailureRate) {
269392
+ failureReasons.push(
269393
+ `tool_failure_rate:${Number(rate.toFixed(6))}>${limits.maxToolFailureRate}`
269394
+ );
269395
+ }
269396
+ }
269397
+ }
268705
269398
  function normalizeFilePath(value) {
268706
269399
  return value.replace(/\\/g, "/").replace(/^\.\//, "");
268707
269400
  }
@@ -273015,6 +273708,56 @@ var SLASH_COMMAND_DEFINITIONS = [
273015
273708
  },
273016
273709
  webSuggested: true
273017
273710
  },
273711
+ {
273712
+ command: "/workflow",
273713
+ usage: "export <kebab-name> [local|versioned]",
273714
+ category: "session",
273715
+ description: {
273716
+ en: "Compile this session into a reviewable reusable Skill",
273717
+ zh: "\u5C06\u5F53\u524D\u4F1A\u8BDD\u7F16\u8BD1\u4E3A\u53EF\u5BA1\u9605\u7684\u590D\u7528 Skill",
273718
+ "zh-TW": "\u5C07\u76EE\u524D\u5DE5\u4F5C\u968E\u6BB5\u7DE8\u8B6F\u70BA\u53EF\u5BE9\u95B1\u7684\u91CD\u7528 Skill"
273719
+ },
273720
+ suggestions: [
273721
+ {
273722
+ value: "export ",
273723
+ description: {
273724
+ en: "Create a local Skill from the current trace",
273725
+ zh: "\u4ECE\u5F53\u524D\u5BA1\u8BA1\u8BB0\u5F55\u521B\u5EFA\u672C\u5730 Skill",
273726
+ "zh-TW": "\u5F9E\u76EE\u524D\u7A3D\u6838\u8A18\u9304\u5EFA\u7ACB\u672C\u6A5F Skill"
273727
+ }
273728
+ }
273729
+ ],
273730
+ webSuggested: true
273731
+ },
273732
+ {
273733
+ command: "/mcp",
273734
+ usage: "[status|refresh] [server]",
273735
+ category: "system",
273736
+ description: {
273737
+ en: "Inspect MCP health or refresh live catalogs",
273738
+ zh: "\u67E5\u770B MCP \u5065\u5EB7\u72B6\u6001\u6216\u5237\u65B0\u5B9E\u65F6\u76EE\u5F55",
273739
+ "zh-TW": "\u67E5\u770B MCP \u5065\u5EB7\u72C0\u614B\u6216\u91CD\u65B0\u6574\u7406\u5373\u6642\u76EE\u9304"
273740
+ },
273741
+ suggestions: [
273742
+ {
273743
+ value: "status",
273744
+ description: {
273745
+ en: "Show server health",
273746
+ zh: "\u663E\u793A\u670D\u52A1\u5065\u5EB7\u72B6\u6001",
273747
+ "zh-TW": "\u986F\u793A\u670D\u52D9\u5065\u5EB7\u72C0\u614B"
273748
+ }
273749
+ },
273750
+ {
273751
+ value: "refresh",
273752
+ description: {
273753
+ en: "Refresh tools, resources, and prompts",
273754
+ zh: "\u5237\u65B0\u5DE5\u5177\u3001\u8D44\u6E90\u4E0E\u63D0\u793A\u8BCD",
273755
+ "zh-TW": "\u91CD\u65B0\u6574\u7406\u5DE5\u5177\u3001\u8CC7\u6E90\u8207\u63D0\u793A\u8A5E"
273756
+ }
273757
+ }
273758
+ ],
273759
+ webSuggested: false
273760
+ },
273018
273761
  {
273019
273762
  command: "/doctor",
273020
273763
  usage: "",
@@ -276785,7 +277528,7 @@ import { dirname as dirname14, resolve as resolve14 } from "path";
276785
277528
  import { homedir as homedir10 } from "os";
276786
277529
  import http3 from "http";
276787
277530
  import { randomBytes as randomBytes4, randomUUID as randomUUID13, timingSafeEqual as timingSafeEqual2 } from "crypto";
276788
- import { z as z69 } from "zod";
277531
+ import { z as z70 } from "zod";
276789
277532
 
276790
277533
  // src/runtime/CommandRouter.ts
276791
277534
  import picocolors18 from "picocolors";
@@ -283582,6 +284325,23 @@ function sanitizeWebEventPayload(type, payload) {
283582
284325
  return { type: safeWebText(payload.type, 100) };
283583
284326
  case "verification_ended":
283584
284327
  return { success: payload.success === true };
284328
+ case "hook_started":
284329
+ return {
284330
+ hookId: safeWebText(payload.hookId, 200),
284331
+ event: safeWebText(payload.event, 100),
284332
+ legacy: payload.legacy === true
284333
+ };
284334
+ case "hook_completed":
284335
+ return {
284336
+ hookId: safeWebText(payload.hookId, 200),
284337
+ event: safeWebText(payload.event, 100),
284338
+ success: payload.success === true,
284339
+ durationMs: safeNumber(payload.durationMs),
284340
+ action: ["continue", "warn", "blocked", "ignored"].includes(
284341
+ String(payload.action)
284342
+ ) ? String(payload.action) : "warn",
284343
+ error: safeWebText(payload.error, 1e3)
284344
+ };
283585
284345
  case "checkpoint_created":
283586
284346
  return {
283587
284347
  timestamp: safeWebText(payload.timestamp, 100),
@@ -296581,19 +297341,127 @@ async function confirmUpdate(prompt) {
296581
297341
  }
296582
297342
  }
296583
297343
 
296584
- // src/runtime/review/ReviewCommand.ts
297344
+ // src/commands/workflow.ts
296585
297345
  import { z as z67 } from "zod";
296586
- var ReviewPresetSchema = z67.enum([
297346
+
297347
+ // src/runtime/WorkflowCompiler.ts
297348
+ function compileWorkflowSkill(trace, descriptionOverride) {
297349
+ const observedTools = [
297350
+ ...new Set(trace.toolCalls.map((call) => call.toolName))
297351
+ ].sort().slice(0, 100);
297352
+ const successfulTools = trace.toolCalls.filter(
297353
+ (call) => call.status === "success"
297354
+ );
297355
+ const failedTools = trace.toolCalls.filter(
297356
+ (call) => call.status === "failed" || call.status === "denied"
297357
+ );
297358
+ const verificationEvents = trace.events.filter(
297359
+ (event) => event.type === "verification_ended"
297360
+ );
297361
+ const planSteps = (trace.plan?.items ?? []).map((item) => redactSecrets(item.text).trim()).filter(Boolean).slice(0, 50);
297362
+ const workflowSteps = planSteps.length > 0 ? planSteps : deriveWorkflowSteps(observedTools);
297363
+ const title = redactSecrets(trace.session.title || "Recorded Orbit workflow").replace(/\s+/g, " ").trim().slice(0, 180);
297364
+ const description = redactSecrets(descriptionOverride || title).replace(/[\r\n]+/g, " ").trim().slice(0, 240);
297365
+ const instructions = [
297366
+ "# Objective",
297367
+ "",
297368
+ redactSecrets(trace.session.goal || title).slice(0, 2e3),
297369
+ "",
297370
+ "# Reusable workflow",
297371
+ "",
297372
+ ...workflowSteps.map((step, index) => `${index + 1}. ${step}`),
297373
+ "",
297374
+ "# Execution contract",
297375
+ "",
297376
+ "- Re-inspect the current workspace before acting; recorded paths, commands, outputs, and assumptions are historical evidence only.",
297377
+ "- Never replay a recorded shell command or tool argument verbatim. Reconstruct the smallest current operation and route it through Orbit permissions.",
297378
+ "- Keep writes inside the authorized workspace and preserve unrelated dirty or staged changes.",
297379
+ "- Run the repository's current verification contract after edits. Repair the earliest root failure, then rerun the wider gate.",
297380
+ "- Stop and report a blocker when required authority, credentials, or external state is missing.",
297381
+ "",
297382
+ "# Observed strategy",
297383
+ "",
297384
+ `- Successful tool actions in the source run: ${successfulTools.length}.`,
297385
+ `- Failed or denied actions in the source run: ${failedTools.length}. Treat these as signals to inspect assumptions before retrying.`,
297386
+ `- Verification runs observed: ${verificationEvents.length}.`,
297387
+ `- Tool families observed: ${observedTools.join(", ") || "none"}.`,
297388
+ "",
297389
+ "This Skill was derived from a credential-redacted Orbit trace. It intentionally excludes raw prompts, tool arguments, command output, diffs, and local absolute paths."
297390
+ ].join("\n").slice(0, 24e3);
297391
+ return {
297392
+ description: description || "A reviewable workflow compiled from Orbit trace evidence.",
297393
+ instructions,
297394
+ observedTools,
297395
+ verificationRuns: verificationEvents.length
297396
+ };
297397
+ }
297398
+ function deriveWorkflowSteps(observedTools) {
297399
+ const steps = [
297400
+ "Clarify the requested outcome, constraints, authorized workspace, and acceptance evidence."
297401
+ ];
297402
+ if (observedTools.some((tool) => /read|search|list|symbol/i.test(tool))) {
297403
+ steps.push(
297404
+ "Inspect repository landmarks and the smallest relevant files before proposing changes."
297405
+ );
297406
+ }
297407
+ if (observedTools.some((tool) => /write|edit|replace|patch/i.test(tool))) {
297408
+ steps.push(
297409
+ "Apply scoped, reviewable edits while preserving unrelated user changes."
297410
+ );
297411
+ }
297412
+ if (observedTools.some((tool) => /test|bash|shell|command/i.test(tool))) {
297413
+ steps.push(
297414
+ "Execute the smallest relevant verification first, then expand according to risk."
297415
+ );
297416
+ }
297417
+ steps.push(
297418
+ "Inspect the final diff, summarize verified outcomes, and disclose any remaining uncertainty."
297419
+ );
297420
+ return steps;
297421
+ }
297422
+
297423
+ // src/commands/workflow.ts
297424
+ var WorkflowExportOptionsSchema = z67.object({
297425
+ name: z67.string().trim().min(1).max(48).regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),
297426
+ description: z67.string().trim().min(1).max(240).optional(),
297427
+ scope: z67.enum(["local", "versioned"]).default("local"),
297428
+ json: z67.boolean().default(false)
297429
+ });
297430
+ async function runWorkflowExport(cwd, sessionId, options) {
297431
+ const value = WorkflowExportOptionsSchema.parse(options);
297432
+ const trace = new SessionStore(cwd).exportTrace(sessionId, {
297433
+ includeHistory: false
297434
+ });
297435
+ const compiled = compileWorkflowSkill(trace, value.description);
297436
+ const created = await createProjectCapability(cwd, {
297437
+ kind: "skill",
297438
+ name: value.name,
297439
+ description: compiled.description,
297440
+ instructions: compiled.instructions,
297441
+ scope: value.scope
297442
+ });
297443
+ const result = {
297444
+ schemaVersion: 1,
297445
+ name: created.name,
297446
+ path: created.path
297447
+ };
297448
+ if (value.json) console.log(JSON.stringify(result, null, 2));
297449
+ return result;
297450
+ }
297451
+
297452
+ // src/runtime/review/ReviewCommand.ts
297453
+ import { z as z68 } from "zod";
297454
+ var ReviewPresetSchema = z68.enum([
296587
297455
  "comprehensive",
296588
297456
  "security",
296589
297457
  "tests",
296590
297458
  "performance",
296591
297459
  "accessibility"
296592
297460
  ]);
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) })
297461
+ var ReviewScopeSchema = z68.discriminatedUnion("kind", [
297462
+ z68.object({ kind: z68.literal("working-tree") }),
297463
+ z68.object({ kind: z68.literal("commit"), ref: z68.string().min(1).max(200) }),
297464
+ z68.object({ kind: z68.literal("branch"), ref: z68.string().min(1).max(200) })
296597
297465
  ]);
296598
297466
  var SAFE_GIT_REF = /^[A-Za-z0-9][A-Za-z0-9._/@{}~^:+-]{0,199}$/;
296599
297467
  function parseReviewCommand(rawArguments) {
@@ -296817,6 +297685,58 @@ var CommandRouter = class {
296817
297685
  }
296818
297686
  }
296819
297687
  }
297688
+ if (/^\/mcp(?:\s|$)/i.test(trimmed)) {
297689
+ const [, action = "status", serverName] = trimmed.split(/\s+/, 3);
297690
+ if (!["status", "refresh"].includes(action.toLowerCase())) {
297691
+ this.printOutput(
297692
+ picocolors18.yellow("Usage: /mcp [status|refresh] [server]")
297693
+ );
297694
+ return { shouldExit: false, processed: true };
297695
+ }
297696
+ await loop.initializeMcp();
297697
+ const health = action.toLowerCase() === "refresh" ? await loop.refreshMcpCatalogs(serverName) : loop.listMcpHealth();
297698
+ if (health.length === 0) {
297699
+ this.printOutput(
297700
+ config.language === "en" ? "\u25CF No MCP servers are running." : "\u25CF \u5F53\u524D\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684 MCP \u670D\u52A1\u3002"
297701
+ );
297702
+ } else {
297703
+ this.printOutput(
297704
+ health.map(
297705
+ (server2) => `${server2.status === "healthy" ? "\u2714" : server2.status === "refreshing" ? "\u25CF" : "\u26A0\uFE0F"} ${server2.serverName} \xB7 ${server2.status} \xB7 tools=${server2.registeredTools} \xB7 recoveries=${server2.recoveryCount}${server2.protocol ? ` \xB7 ${server2.protocol}` : ""}${server2.lastError ? ` \xB7 ${server2.lastError}` : ""}`
297706
+ ).join("\n")
297707
+ );
297708
+ }
297709
+ return { shouldExit: false, processed: true };
297710
+ }
297711
+ if (/^\/workflow(?:\s|$)/i.test(trimmed)) {
297712
+ const [, action = "", name = "", scope = "local"] = trimmed.split(
297713
+ /\s+/,
297714
+ 4
297715
+ );
297716
+ if (action.toLowerCase() !== "export" || !name || !["local", "versioned"].includes(scope)) {
297717
+ this.printOutput(
297718
+ picocolors18.yellow(
297719
+ "Usage: /workflow export <kebab-name> [local|versioned]"
297720
+ )
297721
+ );
297722
+ return { shouldExit: false, processed: true };
297723
+ }
297724
+ try {
297725
+ const result = await runWorkflowExport(cwd, loop.getSessionId(), {
297726
+ name,
297727
+ scope
297728
+ });
297729
+ loop.invalidateSkillsCache();
297730
+ this.printOutput(`\u2714 Workflow Skill created: ${result.path}`);
297731
+ } catch (error) {
297732
+ this.printOutput(
297733
+ picocolors18.red(
297734
+ `\u2716 ${error instanceof Error ? error.message : String(error)}`
297735
+ )
297736
+ );
297737
+ }
297738
+ return { shouldExit: false, processed: true };
297739
+ }
296820
297740
  if (/^\/review(?:\s|$)/i.test(trimmed)) {
296821
297741
  try {
296822
297742
  const rawArguments = trimmed.replace(/^\/review\b/i, "").trim();
@@ -298568,21 +299488,21 @@ ${picocolors18.green("\u2714")} Switched security mode to: ${picocolors18.green(
298568
299488
  };
298569
299489
 
298570
299490
  // src/runtime/LocalRuntimeState.ts
298571
- import { z as z68 } from "zod";
299491
+ import { z as z69 } from "zod";
298572
299492
  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()
299493
+ var LocalSkillsStateSchema = z69.object({
299494
+ enabled: z69.boolean().optional(),
299495
+ activation: z69.enum(["auto", "explicit"]).optional(),
299496
+ maxActive: z69.number().int().min(0).max(8).optional(),
299497
+ disabled: z69.array(z69.string().min(1).max(128)).max(1e3).optional()
298578
299498
  });
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(),
299499
+ var LocalRuntimeStateSchema = z69.object({
299500
+ lastSessionId: z69.string().min(1).max(1e3).optional(),
299501
+ lastProvider: z69.string().min(1).max(256).optional(),
299502
+ lastModel: z69.string().max(512).optional(),
298583
299503
  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(),
299504
+ permissionMode: z69.enum(["strict", "normal", "auto", "plan"]).optional(),
299505
+ agentMaxIterations: z69.number().int().min(1).max(MAX_AGENT_MAX_ITERATIONS).optional(),
298586
299506
  skills: LocalSkillsStateSchema.optional()
298587
299507
  });
298588
299508
  function readLocalRuntimeState(cwd) {
@@ -298613,16 +299533,16 @@ function writeLocalRuntimeState(cwd, patch) {
298613
299533
  }
298614
299534
 
298615
299535
  // 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()
299536
+ var AutocompleteRequestSchema = z70.object({
299537
+ prefix: z70.string().max(2e4),
299538
+ suffix: z70.string().max(2e4),
299539
+ windowId: z70.string().max(1e3).optional()
298620
299540
  });
298621
299541
  var AUTOCOMPLETE_BODY_LIMIT_BYTES = 1e5;
298622
299542
  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)
299543
+ var AutocompleteEndpointSchema = z70.object({
299544
+ port: z70.number().int().min(1).max(65535),
299545
+ token: z70.string().min(32).max(256)
298626
299546
  });
298627
299547
  function getRunOutcomeMessage2(outcome) {
298628
299548
  if (!outcome || outcome.status === "completed") return void 0;
@@ -299662,36 +300582,36 @@ function isRecord8(value) {
299662
300582
  }
299663
300583
 
299664
300584
  // src/commands/LSPServer.ts
299665
- import { z as z70 } from "zod";
300585
+ import { z as z71 } from "zod";
299666
300586
  var MAX_LSP_HEADER_BYTES = 8 * 1024;
299667
300587
  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"),
300588
+ var JsonRpcIdSchema = z71.union([z71.string(), z71.number(), z71.null()]);
300589
+ var JSONRPCMessageSchema = z71.object({
300590
+ jsonrpc: z71.literal("2.0"),
299671
300591
  id: JsonRpcIdSchema.optional(),
299672
- method: z70.string().min(1).max(512),
299673
- params: z70.unknown().optional()
300592
+ method: z71.string().min(1).max(512),
300593
+ params: z71.unknown().optional()
299674
300594
  }).strict();
299675
- var TextDocumentIdentifierSchema = z70.object({
299676
- uri: z70.string().min(1).max(16384)
300595
+ var TextDocumentIdentifierSchema = z71.object({
300596
+ uri: z71.string().min(1).max(16384)
299677
300597
  });
299678
- var DidOpenParamsSchema = z70.object({
300598
+ var DidOpenParamsSchema = z71.object({
299679
300599
  textDocument: TextDocumentIdentifierSchema.extend({
299680
- text: z70.string().max(MAX_LSP_BODY_BYTES)
300600
+ text: z71.string().max(MAX_LSP_BODY_BYTES)
299681
300601
  }).passthrough()
299682
300602
  });
299683
- var DidChangeParamsSchema = z70.object({
300603
+ var DidChangeParamsSchema = z71.object({
299684
300604
  textDocument: TextDocumentIdentifierSchema,
299685
- contentChanges: z70.array(z70.object({ text: z70.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
300605
+ contentChanges: z71.array(z71.object({ text: z71.string().max(MAX_LSP_BODY_BYTES) }).passthrough()).min(1).max(100)
299686
300606
  });
299687
- var DidCloseParamsSchema = z70.object({
300607
+ var DidCloseParamsSchema = z71.object({
299688
300608
  textDocument: TextDocumentIdentifierSchema
299689
300609
  });
299690
- var CompletionParamsSchema = z70.object({
300610
+ var CompletionParamsSchema = z71.object({
299691
300611
  textDocument: TextDocumentIdentifierSchema,
299692
- position: z70.object({
299693
- line: z70.number().int().nonnegative(),
299694
- character: z70.number().int().nonnegative()
300612
+ position: z71.object({
300613
+ line: z71.number().int().nonnegative(),
300614
+ character: z71.number().int().nonnegative()
299695
300615
  })
299696
300616
  });
299697
300617
  var JSONRPCReader = class {
@@ -299937,7 +300857,7 @@ ${completion}
299937
300857
  );
299938
300858
  }
299939
300859
  } catch (error) {
299940
- if (error instanceof z70.ZodError) {
300860
+ if (error instanceof z71.ZodError) {
299941
300861
  sendError(message2.id, -32602, "Invalid method parameters.");
299942
300862
  return;
299943
300863
  }
@@ -300359,8 +301279,8 @@ async function runMcpLogin(serverName, options = {}) {
300359
301279
 
300360
301280
  // src/commands/skills.ts
300361
301281
  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);
301282
+ import { z as z74 } from "zod";
301283
+ var SkillDirectoryOverrideSchema = z74.array(z74.string().trim().min(1).max(4096)).min(1).max(50);
300364
301284
  async function runSkillsCommand(action, options = {}) {
300365
301285
  const cwd = options.cwd ?? process.cwd();
300366
301286
  const config = ConfigLoader.loadSync(cwd);
@@ -300487,10 +301407,10 @@ import {
300487
301407
  } from "fs";
300488
301408
  import { dirname as dirname15, resolve as resolve15 } from "path";
300489
301409
  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()
301410
+ import { z as z75 } from "zod";
301411
+ var TraceOptionsSchema = z75.object({
301412
+ full: z75.boolean().default(false),
301413
+ out: z75.string().trim().min(1).max(4096).optional()
300494
301414
  });
300495
301415
  function runTraceExport(cwd, sessionId, options = {}) {
300496
301416
  const value = TraceOptionsSchema.parse(options);
@@ -300545,16 +301465,16 @@ import { randomUUID as randomUUID15 } from "crypto";
300545
301465
  import { promisify as promisify5 } from "util";
300546
301466
  import picocolors25 from "picocolors";
300547
301467
  import { parse as parseYaml4 } from "yaml";
300548
- import { z as z75 } from "zod";
301468
+ import { z as z76 } from "zod";
300549
301469
  var exec5 = promisify5(execCallback);
300550
301470
  var MAX_SUITE_BYTES = 1024 * 1024;
300551
301471
  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)
301472
+ var EvalOptionsSchema = z76.object({
301473
+ provider: z76.string().trim().min(1).optional(),
301474
+ model: z76.string().trim().min(1).optional(),
301475
+ task: z76.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
301476
+ allowCommands: z76.boolean().default(false),
301477
+ json: z76.boolean().default(false)
300558
301478
  });
300559
301479
  async function runEval(cwd, suiteFile, options = {}) {
300560
301480
  const value = EvalOptionsSchema.parse(options);
@@ -300629,6 +301549,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300629
301549
  const sessionId = outcome?.sessionId || void 0;
300630
301550
  let resolvedModels = [];
300631
301551
  let usage2;
301552
+ let reliability;
300632
301553
  let traceFile;
300633
301554
  if (sessionId) {
300634
301555
  const store = new SessionStore(worktree.path);
@@ -300648,6 +301569,23 @@ async function runEval(cwd, suiteFile, options = {}) {
300648
301569
  cacheHitRate: inputTokens > 0 ? Math.min(1, cacheReadTokens / inputTokens) : 0,
300649
301570
  costUsd: trace.session.totalCostEstimate
300650
301571
  };
301572
+ reliability = {
301573
+ attempts: trace.journal?.attempt ?? 0,
301574
+ toolRuns: trace.metrics.toolRuns,
301575
+ toolFailures: trace.metrics.toolFailures,
301576
+ deniedTools: trace.metrics.deniedTools,
301577
+ approvalRequests: trace.toolCalls.filter(
301578
+ (call) => call.permissionDecision === "ask"
301579
+ ).length,
301580
+ compactions: trace.metrics.compactions,
301581
+ resumedCount: trace.metrics.resumedCount,
301582
+ verificationRuns: trace.events.filter(
301583
+ (event) => event.type === "verification_ended"
301584
+ ).length,
301585
+ checkpoints: trace.events.filter(
301586
+ (event) => event.type === "checkpoint_created"
301587
+ ).length
301588
+ };
300651
301589
  traceFile = writeEvaluationTrace(cwd, runId, task.id, trace);
300652
301590
  }
300653
301591
  results.push(
@@ -300655,7 +301593,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300655
301593
  task: {
300656
301594
  ...task,
300657
301595
  provider: task.provider || value.provider,
300658
- model: task.model || value.model
301596
+ model: task.model || value.model,
301597
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300659
301598
  },
300660
301599
  agentStatus: outcome?.status || "failed",
300661
301600
  durationMs: Date.now() - taskStartedAt,
@@ -300663,6 +301602,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300663
301602
  checks,
300664
301603
  resolvedModels,
300665
301604
  usage: usage2,
301605
+ reliability,
300666
301606
  sessionId,
300667
301607
  traceFile
300668
301608
  })
@@ -300673,7 +301613,8 @@ async function runEval(cwd, suiteFile, options = {}) {
300673
301613
  task: {
300674
301614
  ...task,
300675
301615
  provider: task.provider || value.provider,
300676
- model: task.model || value.model
301616
+ model: task.model || value.model,
301617
+ limits: suite.defaultLimits || task.limits ? { ...suite.defaultLimits, ...task.limits } : void 0
300677
301618
  },
300678
301619
  agentStatus: "failed",
300679
301620
  durationMs: Date.now() - taskStartedAt,
@@ -300702,6 +301643,7 @@ async function runEval(cwd, suiteFile, options = {}) {
300702
301643
  passed: passedTasks === results.length,
300703
301644
  passedTasks,
300704
301645
  totalTasks: results.length,
301646
+ summary: buildAcceptanceSummary(results),
300705
301647
  results
300706
301648
  };
300707
301649
  const reportPath = writeEvaluationReport(cwd, runId, report);
@@ -300720,6 +301662,43 @@ async function runEval(cwd, suiteFile, options = {}) {
300720
301662
  if (!report.passed) process.exitCode = 1;
300721
301663
  return report;
300722
301664
  }
301665
+ function buildAcceptanceSummary(results) {
301666
+ const total = results.length;
301667
+ const durations = results.map((result) => result.durationMs).sort((left, right) => left - right);
301668
+ const midpoint = Math.floor(durations.length / 2);
301669
+ const medianDurationMs = durations.length === 0 ? 0 : durations.length % 2 === 1 ? durations[midpoint] : Math.round((durations[midpoint - 1] + durations[midpoint]) / 2);
301670
+ const verificationChecks = results.flatMap((result) => result.checks);
301671
+ const verificationPasses = verificationChecks.filter(
301672
+ (check) => check.passed
301673
+ ).length;
301674
+ const sumUsage = (field) => results.reduce((sum, result) => {
301675
+ const value = result.usage?.[field];
301676
+ return sum + (typeof value === "number" ? value : 0);
301677
+ }, 0);
301678
+ return {
301679
+ completionRate: total > 0 ? results.filter((result) => result.passed).length / total : 0,
301680
+ verificationPassRate: verificationChecks.length > 0 ? verificationPasses / verificationChecks.length : 0,
301681
+ crashOrAbortRate: total > 0 ? results.filter((result) => result.agentStatus !== "completed").length / total : 0,
301682
+ medianDurationMs,
301683
+ totalInputTokens: sumUsage("inputTokens"),
301684
+ totalOutputTokens: sumUsage("outputTokens"),
301685
+ totalCacheReadTokens: sumUsage("cacheReadTokens"),
301686
+ totalApprovalRequests: results.reduce(
301687
+ (sum, result) => sum + (result.reliability?.approvalRequests ?? 0),
301688
+ 0
301689
+ ),
301690
+ totalToolFailures: results.reduce(
301691
+ (sum, result) => sum + (result.reliability?.toolFailures ?? 0),
301692
+ 0
301693
+ ),
301694
+ unintendedFileChangeFindings: results.reduce(
301695
+ (sum, result) => sum + result.failureReasons.filter(
301696
+ (reason) => reason.startsWith("forbidden_file_changed:")
301697
+ ).length,
301698
+ 0
301699
+ )
301700
+ };
301701
+ }
300723
301702
  function loadAcceptanceSuite(cwd, suiteFile) {
300724
301703
  const filePath = resolveSafePath(cwd, suiteFile);
300725
301704
  const stats = lstatSync9(filePath);
@@ -300927,7 +301906,7 @@ function safeSummary(value) {
300927
301906
  import readline6 from "readline";
300928
301907
  import picocolors26 from "picocolors";
300929
301908
  import { resolve as resolve17 } from "path";
300930
- import { z as z77 } from "zod";
301909
+ import { z as z78 } from "zod";
300931
301910
 
300932
301911
  // src/runtime/CleanupManager.ts
300933
301912
  import {
@@ -300939,10 +301918,10 @@ import {
300939
301918
  } from "fs";
300940
301919
  import { homedir as homedir11 } from "os";
300941
301920
  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"]);
301921
+ import { z as z77 } from "zod";
301922
+ var CleanupScopeSchema = z77.enum(["user", "project"]);
300944
301923
  function buildCleanupPlan(options) {
300945
- const scopes = z76.array(CleanupScopeSchema).min(1).parse(options.scopes);
301924
+ const scopes = z77.array(CleanupScopeSchema).min(1).parse(options.scopes);
300946
301925
  const homeDirectory = resolve16(options.homeDirectory ?? homedir11());
300947
301926
  const projectDirectory = resolve16(options.projectDirectory ?? options.cwd);
300948
301927
  const candidates = scopes.map((scope) => ({
@@ -301100,12 +302079,12 @@ function safeInventoryWarning(targetPath, error) {
301100
302079
  }
301101
302080
 
301102
302081
  // 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)
302082
+ var CleanCommandOptionsSchema = z78.object({
302083
+ user: z78.boolean().default(false),
302084
+ project: z78.union([z78.boolean(), z78.string().min(1).max(4096)]).optional(),
302085
+ all: z78.boolean().default(false),
302086
+ yes: z78.boolean().default(false),
302087
+ json: z78.boolean().default(false)
301109
302088
  }).strict();
301110
302089
  async function runClean(cwd, rawOptions, dependencies = {}) {
301111
302090
  const options = CleanCommandOptionsSchema.parse(rawOptions);
@@ -301220,7 +302199,7 @@ async function confirmDeletion(prompt) {
301220
302199
  // src/commands/backup.ts
301221
302200
  import { basename as basename7, resolve as resolve19 } from "path";
301222
302201
  import picocolors27 from "picocolors";
301223
- import { z as z79 } from "zod";
302202
+ import { z as z80 } from "zod";
301224
302203
 
301225
302204
  // src/runtime/ProjectBackup.ts
301226
302205
  import {
@@ -301234,25 +302213,25 @@ import {
301234
302213
  } from "fs";
301235
302214
  import { createHash as createHash10, randomUUID as randomUUID16 } from "crypto";
301236
302215
  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";
302216
+ import { z as z79 } from "zod";
301238
302217
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
301239
302218
  var MAX_SERIALIZED_BACKUP_BYTES = 96 * 1024 * 1024;
301240
302219
  var MAX_BACKUP_FILES = 1e4;
301241
302220
  var MAX_BACKUP_TREE_ENTRIES = 5e4;
301242
302221
  var MAX_BACKUP_TREE_DEPTH = 64;
301243
302222
  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)
302223
+ var BackupFileSchema = z79.object({
302224
+ path: z79.string().min(1).max(4096),
302225
+ size: z79.number().int().min(0).max(MAX_BACKUP_BYTES),
302226
+ sha256: z79.string().regex(SHA256_PATTERN),
302227
+ content: z79.string().max(Math.ceil(MAX_BACKUP_BYTES * 4 / 3) + 8)
301249
302228
  });
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)
302229
+ var ProjectBackupBundleSchema = z79.object({
302230
+ schemaVersion: z79.literal(1),
302231
+ kind: z79.literal("orbit-project-backup"),
302232
+ createdAt: z79.string().datetime(),
302233
+ sourceName: z79.string().min(1).max(512),
302234
+ files: z79.array(BackupFileSchema).max(MAX_BACKUP_FILES)
301256
302235
  }).superRefine((bundle, context) => {
301257
302236
  let totalBytes = 0;
301258
302237
  const seen = /* @__PURE__ */ new Set();
@@ -301260,7 +302239,7 @@ var ProjectBackupBundleSchema = z78.object({
301260
302239
  totalBytes += file.size;
301261
302240
  if (totalBytes > MAX_BACKUP_BYTES) {
301262
302241
  context.addIssue({
301263
- code: z78.ZodIssueCode.custom,
302242
+ code: z79.ZodIssueCode.custom,
301264
302243
  message: `Backup exceeds ${MAX_BACKUP_BYTES} bytes.`
301265
302244
  });
301266
302245
  break;
@@ -301268,14 +302247,14 @@ var ProjectBackupBundleSchema = z78.object({
301268
302247
  const normalized = normalizeBundlePath(file.path);
301269
302248
  if (!normalized || normalized !== file.path) {
301270
302249
  context.addIssue({
301271
- code: z78.ZodIssueCode.custom,
302250
+ code: z79.ZodIssueCode.custom,
301272
302251
  message: `Unsafe backup path: ${file.path}`
301273
302252
  });
301274
302253
  continue;
301275
302254
  }
301276
302255
  if (seen.has(normalized.toLowerCase())) {
301277
302256
  context.addIssue({
301278
- code: z78.ZodIssueCode.custom,
302257
+ code: z79.ZodIssueCode.custom,
301279
302258
  message: `Duplicate backup path: ${file.path}`
301280
302259
  });
301281
302260
  }
@@ -301508,9 +302487,9 @@ function formatBytes2(bytes) {
301508
302487
  }
301509
302488
 
301510
302489
  // src/commands/backup.ts
301511
- var BackupOptionsSchema = z79.object({
301512
- output: z79.string().min(1).max(4096).optional(),
301513
- json: z79.boolean().default(false)
302490
+ var BackupOptionsSchema = z80.object({
302491
+ output: z80.string().min(1).max(4096).optional(),
302492
+ json: z80.boolean().default(false)
301514
302493
  }).strict();
301515
302494
  function runBackupCreate(cwd, rawOptions = {}) {
301516
302495
  const options = BackupOptionsSchema.parse(rawOptions);
@@ -301610,21 +302589,21 @@ import {
301610
302589
  import { randomUUID as randomUUID17 } from "crypto";
301611
302590
  import { dirname as dirname18, isAbsolute as isAbsolute10, join as join26, relative as relative11, resolve as resolve20, sep as sep3 } from "path";
301612
302591
  import { homedir as homedir12 } from "os";
301613
- import { z as z80 } from "zod";
301614
- var InstalledExtensionSchema2 = z80.object({
302592
+ import { z as z81 } from "zod";
302593
+ var InstalledExtensionSchema2 = z81.object({
301615
302594
  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}$/),
302595
+ displayName: z81.string().min(1).max(256),
302596
+ version: z81.string().min(1).max(128),
302597
+ digest: z81.string().regex(/^[a-f0-9]{64}$/),
301619
302598
  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")
302599
+ installedAt: z81.string().datetime(),
302600
+ trusted: z81.boolean(),
302601
+ path: z81.string().min(1).max(4096),
302602
+ manifestFile: z81.string().min(1).max(4096).default("extension.yaml")
301624
302603
  });
301625
- var ExtensionRegistrySchema2 = z80.object({
301626
- schemaVersion: z80.literal(1),
301627
- extensions: z80.array(InstalledExtensionSchema2).max(500).default([])
302604
+ var ExtensionRegistrySchema2 = z81.object({
302605
+ schemaVersion: z81.literal(1),
302606
+ extensions: z81.array(InstalledExtensionSchema2).max(500).default([])
301628
302607
  });
301629
302608
  var ExtensionManager = class {
301630
302609
  orbitDir;
@@ -302300,6 +303279,15 @@ program.command("trace").description("export a redacted, versioned session audit
302300
303279
  });
302301
303280
  if (output) console.log(`Trace exported to ${output}`);
302302
303281
  });
303282
+ program.command("workflow-export").description("compile a redacted session trace into a reviewable Skill").argument("<session>", "session id to compile").requiredOption("--name <name>", "lowercase kebab-case Skill name").option("--description <text>", "short reusable workflow description").option("--scope <scope>", "local or versioned", "local").option("--json", "print a machine-readable result").action(async (session, options) => {
303283
+ const result = await runWorkflowExport(process.cwd(), session, {
303284
+ name: options.name,
303285
+ description: options.description,
303286
+ scope: options.scope,
303287
+ json: !!options.json
303288
+ });
303289
+ if (!options.json) console.log(`\u2714 Workflow Skill created: ${result.path}`);
303290
+ });
302303
303291
  program.command("lsp").description("start the local LSP autocomplete server").action(async () => {
302304
303292
  await runLSPServer(process.cwd());
302305
303293
  });