agent-valley 4.2.0 → 4.2.1

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "av",
4
- "version": "4.2.0",
4
+ "version": "4.2.1",
5
5
  "description": "Delegate repository goals to Agent Valley and inspect mission progress and verification evidence.",
6
6
  "author": {
7
7
  "name": "Agent Valley"
package/dist/index.js CHANGED
@@ -7091,6 +7091,7 @@ var init_contracts = __esm(() => {
7091
7091
  "unknown-effect",
7092
7092
  "budget",
7093
7093
  "interrupted",
7094
+ "service-shutdown",
7094
7095
  "chief-wait",
7095
7096
  "chief-unavailable",
7096
7097
  "integrity"
@@ -7264,7 +7265,7 @@ function recordPause(mission, pause) {
7264
7265
  state.failureKind = pause.kind;
7265
7266
  if (pause.nextRunAt)
7266
7267
  state.nextRunAt = pause.nextRunAt;
7267
- else
7268
+ else if (pause.kind !== "service-shutdown")
7268
7269
  delete state.nextRunAt;
7269
7270
  mission.status = pause.nextRunAt ? "waiting" : "paused";
7270
7271
  mission.error = pause.message;
@@ -70784,6 +70785,7 @@ function validateResumeOptions(goal, options) {
70784
70785
  "resume",
70785
70786
  "worker",
70786
70787
  "supervise",
70788
+ "service",
70787
70789
  "retry",
70788
70790
  "runs",
70789
70791
  "duration",
@@ -71068,7 +71070,7 @@ var operationSchema = strictObject({
71068
71070
  charter: string2().trim().min(1).max(32000),
71069
71071
  settings: record(string2().min(1).max(80), union([string2().max(32000), boolean2()])),
71070
71072
  phase: _enum(["deciding", "running", "accepting", "waiting", "paused", "completed"]),
71071
- pauseKind: _enum(["interrupted", "blocked"]).optional(),
71073
+ pauseKind: _enum(["interrupted", "blocked", "service-shutdown"]).optional(),
71072
71074
  createdAt: timestampSchema,
71073
71075
  updatedAt: timestampSchema,
71074
71076
  completedCycles: number2().int().min(0),
@@ -71699,6 +71701,67 @@ async function collectContainerObservation(input, previous, dependencies = {}) {
71699
71701
  // ../../packages/core/src/chief/continuous-operation.ts
71700
71702
  import { createHash as createHash18, randomUUID as randomUUID12 } from "node:crypto";
71701
71703
  init_execution();
71704
+
71705
+ // ../../packages/core/src/chief/service-shutdown.ts
71706
+ init_execution();
71707
+ function serviceShutdownPause() {
71708
+ return new MissionPause("The OS-owned service is shutting down. Re-observe the saved execution before continuing the same goal within its original limits.", "service-shutdown");
71709
+ }
71710
+ function isServiceShutdown(signal) {
71711
+ return signal?.reason instanceof MissionPause && signal.reason.kind === "service-shutdown";
71712
+ }
71713
+ function interruptionPause(signal, fallback) {
71714
+ return signal?.reason instanceof MissionPause ? signal.reason : new MissionPause(fallback, "interrupted");
71715
+ }
71716
+ function recordServiceShutdown(mission, unconfirmedTermination) {
71717
+ const pause = serviceShutdownPause();
71718
+ if (mission.history.at(-1)?.stage !== "service-shutdown")
71719
+ mission.history.push({ at: new Date().toISOString(), stage: "service-shutdown", message: pause.message });
71720
+ const protectedKinds = ["interrupted", "budget", "integrity", "unknown-effect", "chief-unavailable"];
71721
+ if (protectedKinds.includes(mission.execution?.failureKind ?? ""))
71722
+ return;
71723
+ if (mission.status === "paused" && mission.execution?.failureKind && mission.execution.failureKind !== "service-shutdown")
71724
+ return;
71725
+ if (mission.status === "failed" && mission.execution?.failureKind !== "service-shutdown")
71726
+ return;
71727
+ if (unconfirmedTermination) {
71728
+ recordPause(mission, new MissionPause(unconfirmedTermination.message, "unknown-effect"));
71729
+ return;
71730
+ }
71731
+ if (mission.status === "completed") {
71732
+ if (pendingCodeDelivery(mission)) {
71733
+ try {
71734
+ assertExecutionDeadline(mission);
71735
+ } catch (error) {
71736
+ if (!(error instanceof MissionPause))
71737
+ throw error;
71738
+ if (mission.codeDelivery) {
71739
+ mission.codeDelivery.phase = "blocked";
71740
+ mission.codeDelivery.error = error.message;
71741
+ delete mission.codeDelivery.nextRunAt;
71742
+ }
71743
+ }
71744
+ }
71745
+ } else {
71746
+ for (const run of mission.operations?.runs ?? []) {
71747
+ if (!run.finishedAt && run.executionState !== "settled")
71748
+ markOperatingRunUnknown(run, "Service shutdown interrupted this execution. Matching process-guard proof is required before recovery.");
71749
+ }
71750
+ let disposition = pause;
71751
+ try {
71752
+ assertExecutionBudget(mission);
71753
+ } catch (error) {
71754
+ if (!(error instanceof MissionPause))
71755
+ throw error;
71756
+ disposition = error;
71757
+ }
71758
+ recordPause(mission, disposition);
71759
+ if (disposition.kind === "service-shutdown" && mission.supervision)
71760
+ mission.supervision.pendingRecovery ??= { reason: pause.message };
71761
+ }
71762
+ }
71763
+
71764
+ // ../../packages/core/src/chief/continuous-operation.ts
71702
71765
  function continuousDecisionKey(decision, observationFingerprint, observationRevision) {
71703
71766
  return createHash18("sha256").update(JSON.stringify({ goal: decision.goal, evidence: decision.evidence, observationFingerprint, observationRevision })).digest("hex");
71704
71767
  }
@@ -71713,8 +71776,9 @@ async function runContinuousOperation(operation, ports) {
71713
71776
  if (operation.phase !== "paused" && operation.phase !== "completed")
71714
71777
  operation.resumePhase = operation.phase;
71715
71778
  operation.phase = "paused";
71716
- operation.pauseKind = ports.signal?.aborted ? "interrupted" : "blocked";
71717
- operation.error = message.slice(0, 16000);
71779
+ const shutdown = isServiceShutdown(ports.signal);
71780
+ operation.pauseKind = shutdown ? "service-shutdown" : ports.signal?.aborted ? "interrupted" : "blocked";
71781
+ operation.error = (shutdown ? "The OS-owned service is shutting down. The operation retained its child, decision and recovery checkpoints for automatic resumption within their original limits." : message).slice(0, 16000);
71718
71782
  await save();
71719
71783
  return operation;
71720
71784
  };
@@ -71741,12 +71805,22 @@ async function runContinuousOperation(operation, ports) {
71741
71805
  if (mission)
71742
71806
  assertExecutionDeadline(mission, Date.parse(now()));
71743
71807
  const remaining = mission?.executionPolicy && mission.execution ? Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000 - Date.parse(now()) : Infinity;
71744
- await ports.delay(Math.min(Date.parse(nextRunAt) - Date.parse(now()), remaining, 30000), ports.signal);
71808
+ try {
71809
+ await ports.delay(Math.min(Date.parse(nextRunAt) - Date.parse(now()), remaining, 30000), ports.signal);
71810
+ } catch (error) {
71811
+ if (mission)
71812
+ assertExecutionDeadline(mission, Date.parse(now()));
71813
+ if (error instanceof MissionPause && error.kind !== "interrupted" && error.kind !== "service-shutdown")
71814
+ throw error;
71815
+ if (ports.signal?.aborted)
71816
+ throw interruptionPause(ports.signal, "Operation recovery interrupted.");
71817
+ throw error;
71818
+ }
71745
71819
  }
71746
71820
  if (mission)
71747
71821
  assertExecutionDeadline(mission, Date.parse(now()));
71748
71822
  if (ports.signal?.aborted)
71749
- throw new MissionPause("Operation recovery interrupted.", "interrupted");
71823
+ throw interruptionPause(ports.signal, "Operation recovery interrupted.");
71750
71824
  };
71751
71825
  const recoverChild = async (mission, context) => {
71752
71826
  const disposition = automaticMissionRecovery(mission, Date.parse(now()), context);
@@ -71777,6 +71851,7 @@ async function runContinuousOperation(operation, ports) {
71777
71851
  }
71778
71852
  await save();
71779
71853
  await waitForRecovery(disposition.waitUntil, mission);
71854
+ const pendingRecovery = structuredClone(operation.recovery);
71780
71855
  operation.recovery.attempts += 1;
71781
71856
  if (!continuation)
71782
71857
  operation.recovery.failedAttempts = failedAttempts + 1;
@@ -71785,11 +71860,22 @@ async function runContinuousOperation(operation, ports) {
71785
71860
  await save();
71786
71861
  if (!operation.baseline)
71787
71862
  throw new Error("The original accepted baseline is missing from the recovery checkpoint.");
71788
- await ports.runMission(operation, mission.id, mission.goal, operation.baseline.path);
71863
+ try {
71864
+ const resumed = await ports.runMission(operation, mission.id, mission.goal, operation.baseline.path);
71865
+ if (isServiceShutdown(ports.signal) && resumed.execution?.failureKind === "service-shutdown") {
71866
+ operation.recovery = pendingRecovery;
71867
+ throw interruptionPause(ports.signal, "Operation child recovery interrupted.");
71868
+ }
71869
+ } catch (error) {
71870
+ if (error instanceof MissionPause && error.kind === "service-shutdown")
71871
+ operation.recovery = pendingRecovery;
71872
+ throw error;
71873
+ }
71789
71874
  return true;
71790
71875
  };
71791
71876
  const selectDecision = async (id) => {
71792
71877
  while (true) {
71878
+ const previous = operation.recovery?.target === "decision" && operation.recovery.checkpointId === id ? structuredClone(operation.recovery) : undefined;
71793
71879
  const prior = operation.recovery?.target === "decision" && operation.recovery.checkpointId === id ? operation.recovery.attempts : 0;
71794
71880
  if (prior >= automaticRecoveryLimit)
71795
71881
  throw new Error("Bounded automatic goal-selection recovery exhausted its attempts; the saved decision remains unresolved.");
@@ -71805,6 +71891,16 @@ async function runContinuousOperation(operation, ports) {
71805
71891
  try {
71806
71892
  return continuousDecisionSchema.parse(await ports.decide(operation, id));
71807
71893
  } catch (error) {
71894
+ if (error instanceof MissionPause && error.kind === "service-shutdown") {
71895
+ operation.recovery = previous ?? {
71896
+ target: "decision",
71897
+ checkpointId: id,
71898
+ attempts: prior,
71899
+ disposition: "waiting",
71900
+ reason: error.message.slice(0, 16000)
71901
+ };
71902
+ throw error;
71903
+ }
71808
71904
  const reason = error instanceof Error ? error.message : String(error);
71809
71905
  const kind = error instanceof MissionPause ? error.kind : classifyFailure(reason);
71810
71906
  const invalid = error instanceof Error && (error.name === "ZodError" || reason.startsWith("Invalid Chief decision"));
@@ -71997,7 +72093,7 @@ async function runContinuousOperation(operation, ports) {
71997
72093
  await save();
71998
72094
  }
71999
72095
  } catch (error) {
72000
- if (operation.recovery && error instanceof MissionPause) {
72096
+ if (operation.recovery && error instanceof MissionPause && error.kind !== "service-shutdown") {
72001
72097
  operation.recovery.disposition = "protected";
72002
72098
  operation.recovery.reason = error.message.slice(0, 16000);
72003
72099
  }
@@ -75165,7 +75261,7 @@ function abortableDelay(ms, signal) {
75165
75261
  const abort = () => {
75166
75262
  clearTimeout(timer);
75167
75263
  signal?.removeEventListener("abort", abort);
75168
- reject(new Error("Order supervision interrupted."));
75264
+ reject(signal?.reason instanceof MissionPause ? signal.reason : new Error("Order supervision interrupted."));
75169
75265
  };
75170
75266
  const timer = setTimeout(() => {
75171
75267
  signal?.removeEventListener("abort", abort);
@@ -75181,17 +75277,23 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75181
75277
  const id = options.resume ?? options.missionId ?? randomUUID15();
75182
75278
  const store = new MissionStore(join36(root, ".agent-valley/missions"));
75183
75279
  const controller = new AbortController;
75184
- const interrupt = () => controller.abort();
75280
+ const interrupt = () => controller.abort(dependencies.signal?.reason);
75281
+ const terminate = () => controller.abort(options.service ? serviceShutdownPause() : undefined);
75185
75282
  dependencies.signal?.addEventListener("abort", interrupt, { once: true });
75186
75283
  if (dependencies.signal?.aborted)
75187
75284
  interrupt();
75188
75285
  if (!dependencies.signal) {
75189
75286
  process.once("SIGINT", interrupt);
75190
- process.once("SIGTERM", interrupt);
75287
+ process.once("SIGTERM", terminate);
75191
75288
  }
75192
75289
  const runWorker = createDeadlineWorkerRunner(store, id, controller.signal);
75193
- let args = orderWorkerArgs(goal, options, id);
75290
+ const workerArgs = (goal, current) => orderWorkerArgs(goal, {
75291
+ ...current,
75292
+ ...options.service ? { service: true } : {}
75293
+ }, id);
75294
+ let args = workerArgs(goal, options);
75194
75295
  let returned;
75296
+ let terminationFailure;
75195
75297
  const waitForOwner = async () => {
75196
75298
  let observed = false;
75197
75299
  while (await store.isLocked(id)) {
@@ -75214,7 +75316,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75214
75316
  returned = current;
75215
75317
  if (controller.signal.aborted || current.status === "completed" && !pendingCodeDelivery(current) || ["paused", "failed"].includes(current.status) && !automaticMissionRecovery(current).retry)
75216
75318
  return current;
75217
- args = orderWorkerArgs(undefined, { resume: id }, id);
75319
+ args = workerArgs(undefined, { resume: id });
75218
75320
  }
75219
75321
  if (controller.signal.aborted)
75220
75322
  break;
@@ -75263,7 +75365,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75263
75365
  await (dependencies.delay ?? abortableDelay)(Math.min(Date.parse(mission.codeDelivery.nextRunAt) - Date.now(), 30000), controller.signal);
75264
75366
  }
75265
75367
  assertExecutionDeadline(mission);
75266
- args = orderWorkerArgs(undefined, { resume: id }, id);
75368
+ args = workerArgs(undefined, { resume: id });
75267
75369
  continue;
75268
75370
  }
75269
75371
  const recovery = automaticMissionRecovery(mission);
@@ -75302,13 +75404,15 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75302
75404
  await (dependencies.delay ?? abortableDelay)(Math.min(1000, remainingTime()), controller.signal);
75303
75405
  }
75304
75406
  assertExecutionDeadline(mission);
75305
- args = orderWorkerArgs(undefined, { resume: id }, id);
75407
+ args = workerArgs(undefined, { resume: id });
75306
75408
  }
75307
75409
  returned = await store.load(id);
75308
75410
  return returned;
75309
75411
  } catch (error) {
75310
- if (error instanceof WorkerTerminationError)
75412
+ if (error instanceof WorkerTerminationError) {
75413
+ terminationFailure = error;
75311
75414
  throw error;
75415
+ }
75312
75416
  if (await store.isLocked(id)) {
75313
75417
  if (!controller.signal.aborted)
75314
75418
  await waitForOwner();
@@ -75371,7 +75475,18 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75371
75475
  const existing = await store.load(id).catch(() => {
75372
75476
  return;
75373
75477
  });
75374
- if (existing?.status === "completed" && existing.codeDelivery && pendingCodeDelivery(existing)) {
75478
+ if (existing && isServiceShutdown(controller.signal)) {
75479
+ const unlock = await store.lock(id);
75480
+ try {
75481
+ const latest = await store.load(id);
75482
+ recordServiceShutdown(latest, terminationFailure);
75483
+ await store.save(latest);
75484
+ if (returned)
75485
+ Object.assign(returned, latest);
75486
+ } finally {
75487
+ await unlock();
75488
+ }
75489
+ } else if (existing?.status === "completed" && existing.codeDelivery && pendingCodeDelivery(existing)) {
75375
75490
  const unlock = await store.lock(id);
75376
75491
  try {
75377
75492
  const latest = await store.load(id);
@@ -75409,7 +75524,7 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75409
75524
  dependencies.signal?.removeEventListener("abort", interrupt);
75410
75525
  if (!dependencies.signal) {
75411
75526
  process.removeListener("SIGINT", interrupt);
75412
- process.removeListener("SIGTERM", interrupt);
75527
+ process.removeListener("SIGTERM", terminate);
75413
75528
  }
75414
75529
  }
75415
75530
  }
@@ -75417,13 +75532,13 @@ async function superviseOrder(goal, options, root, dependencies = {}) {
75417
75532
  // src/chief-continuous-recovery.ts
75418
75533
  function assertContinuousDecisionRecovery(mission) {
75419
75534
  const state = executionState(mission);
75420
- if (mission.status === "paused" && state.failureKind !== "implementation" && state.failureKind !== "provider" && state.failureKind !== "rate-limit")
75535
+ if (mission.status === "paused" && state.failureKind !== "implementation" && state.failureKind !== "provider" && state.failureKind !== "rate-limit" && state.failureKind !== "service-shutdown")
75421
75536
  throw new MissionPause(mission.error ?? state.pauseReason ?? "The saved decision remains unresolved.", state.failureKind ?? "implementation");
75422
75537
  }
75423
75538
  async function runContinuousDecision(mission, prompt, run, store, signal, delay = abortableDelay) {
75424
75539
  assertContinuousDecisionRecovery(mission);
75425
75540
  const state = executionState(mission);
75426
- if (mission.status === "paused" && state.retries >= (mission.executionPolicy?.maxRetries ?? 0))
75541
+ if (mission.status === "paused" && state.failureKind !== "service-shutdown" && state.retries >= (mission.executionPolicy?.maxRetries ?? 0))
75427
75542
  throw new MissionPause(mission.error ?? "Bounded Chief decision recovery exhausted its attempts.", state.failureKind ?? "implementation");
75428
75543
  let correction = mission.history.findLast((entry) => entry.stage === "continuous-decision-invalid")?.message;
75429
75544
  while (true) {
@@ -75433,7 +75548,7 @@ async function runContinuousDecision(mission, prompt, run, store, signal, delay
75433
75548
  await delay(Math.min(Date.parse(state.nextRunAt) - Date.now(), remaining, 30000), signal);
75434
75549
  }
75435
75550
  if (signal?.aborted)
75436
- throw new MissionPause("Operation decision interrupted.", "interrupted");
75551
+ throw interruptionPause(signal, "Operation decision interrupted.");
75437
75552
  mission.status = "planning";
75438
75553
  delete mission.error;
75439
75554
  delete state.pauseReason;
@@ -76314,8 +76429,12 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76314
76429
  return parseContinuousDecision(result.message);
76315
76430
  }
76316
76431
  if (mission) {
76432
+ const serviceRuns = mission.history.at(-1)?.stage === "service-shutdown" && mission.execution?.failureKind === "unknown-effect" ? mission.operations?.runs.filter((run) => run.executionState === "unknown") ?? [] : [];
76317
76433
  await store.recoverProcesses(decisionId, mission);
76318
76434
  finalizeAbandonedRuns(mission);
76435
+ if (serviceRuns.length && serviceRuns.every((run) => run.executionRecovery === "local-process" && run.executionState === "settled") && !mission.tasks.some((task) => task.effectState === "unknown") && mission.execution) {
76436
+ mission.execution.failureKind = "service-shutdown";
76437
+ }
76319
76438
  assertContinuousDecisionRecovery(mission);
76320
76439
  await store.save(mission);
76321
76440
  } else {
@@ -76383,7 +76502,7 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76383
76502
  throw new MissionPause("Decision stage changed its saved charter, workspace, Chief Director or pinned evidence.", "integrity");
76384
76503
  }, () => {
76385
76504
  if (dependencies.signal?.aborted)
76386
- throw new MissionPause("Operation decision interrupted.", "interrupted");
76505
+ throw interruptionPause(dependencies.signal, "Operation decision interrupted.");
76387
76506
  });
76388
76507
  await consultContinuousDirectors(mission, ports, run);
76389
76508
  const tools = await (dependencies.tools ?? discoverTools)(operation.repositoryRoot);
@@ -76413,7 +76532,14 @@ async function decideContinuousGoal(operation, decisionId, root, dependencies =
76413
76532
  throw error;
76414
76533
  } finally {
76415
76534
  try {
76416
- await runtime.close();
76535
+ try {
76536
+ await runtime.close();
76537
+ } finally {
76538
+ if (mission && isServiceShutdown(dependencies.signal)) {
76539
+ recordServiceShutdown(mission);
76540
+ await store.save(mission);
76541
+ }
76542
+ }
76417
76543
  } finally {
76418
76544
  await unlock();
76419
76545
  }
@@ -76585,13 +76711,14 @@ async function runOperation(charter, options, root = process.cwd(), dependencies
76585
76711
  const storage = operationStore(root);
76586
76712
  const unlock = await storage.lock(id);
76587
76713
  const controller = new AbortController;
76588
- const stop = () => controller.abort();
76714
+ const stop = () => controller.abort(dependencies.signal?.reason);
76715
+ const terminate = () => controller.abort(options.service ? serviceShutdownPause() : undefined);
76589
76716
  dependencies.signal?.addEventListener("abort", stop, { once: true });
76590
76717
  if (dependencies.signal?.aborted)
76591
76718
  stop();
76592
76719
  if (!dependencies.signal) {
76593
76720
  process.once("SIGINT", stop);
76594
- process.once("SIGTERM", stop);
76721
+ process.once("SIGTERM", terminate);
76595
76722
  }
76596
76723
  try {
76597
76724
  let operation;
@@ -76677,12 +76804,13 @@ Resume: av order --resume ${id}`);
76677
76804
  return;
76678
76805
  throw error;
76679
76806
  });
76680
- return superviseOrder(saved ? undefined : goal, saved ? { resume: missionId, once: true } : {
76807
+ return superviseOrder(saved ? undefined : goal, saved ? { resume: missionId, once: true, ...options.service ? { service: true } : {} } : {
76681
76808
  ...current.settings,
76682
76809
  once: true,
76683
76810
  missionId,
76684
76811
  baselineWorkspace: baselinePath,
76685
- operationId: current.id
76812
+ operationId: current.id,
76813
+ ...options.service ? { service: true } : {}
76686
76814
  }, root, { signal: controller.signal });
76687
76815
  }),
76688
76816
  accept: async (current, mission) => {
@@ -76698,13 +76826,13 @@ Resume: av order --resume ${id}`);
76698
76826
  dependencies.signal?.removeEventListener("abort", stop);
76699
76827
  if (!dependencies.signal) {
76700
76828
  process.removeListener("SIGINT", stop);
76701
- process.removeListener("SIGTERM", stop);
76829
+ process.removeListener("SIGTERM", terminate);
76702
76830
  }
76703
76831
  await unlock();
76704
76832
  }
76705
76833
  }
76706
76834
  function registerContinuousCommands(program) {
76707
- program.command("operate [charter]", { hidden: true }).description("Deprecated alias for av order; resume existing operating charters").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check for each improvement").option("--actor <type>", "Pinned Chief Director CLI").option("--model <id>", "Pinned Chief Director model").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Configured YAML Actor roster").option("--oma", "Require OMA completion receipts for workers").option("--timeout <seconds>", "Timeout per Actor/check").option("--repairs <count>", "Repair limit per task/final review").option("--rounds <count>", "Recovery decision limit per improvement").option("--parallel <count>", "Actor concurrency per improvement").option("--runs <count>", "Initial Actor call limit; on resume, increase the active decision checkpoint limit").option("--duration <seconds>", "Initial wall-time limit; on resume, increase the active decision checkpoint limit").option("--cost <usd>", "Initial estimated cost limit; on resume, increase the active decision checkpoint limit").option("--account-run <run-id>", "On resume, reconcile an active decision run whose usage/cost was lost").option("--account-cost <usd>", "Observed USD cost for the decision --account-run after inspecting billing").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--resume <id>", "Resume the saved charter and accepted work").addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).action(async (charter, options) => {
76835
+ program.command("operate [charter]", { hidden: true }).description("Deprecated alias for av order; resume existing operating charters").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check for each improvement").option("--actor <type>", "Pinned Chief Director CLI").option("--model <id>", "Pinned Chief Director model").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Configured YAML Actor roster").option("--oma", "Require OMA completion receipts for workers").option("--service", "Resume after OS service SIGTERM within saved limits; SIGINT still cancels").option("--timeout <seconds>", "Timeout per Actor/check").option("--repairs <count>", "Repair limit per task/final review").option("--rounds <count>", "Recovery decision limit per improvement").option("--parallel <count>", "Actor concurrency per improvement").option("--runs <count>", "Initial Actor call limit; on resume, increase the active decision checkpoint limit").option("--duration <seconds>", "Initial wall-time limit; on resume, increase the active decision checkpoint limit").option("--cost <usd>", "Initial estimated cost limit; on resume, increase the active decision checkpoint limit").option("--account-run <run-id>", "On resume, reconcile an active decision run whose usage/cost was lost").option("--account-cost <usd>", "Observed USD cost for the decision --account-run after inspecting billing").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--resume <id>", "Resume the saved charter and accepted work").addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).action(async (charter, options) => {
76708
76836
  const operation = await runOperation(charter, options);
76709
76837
  console.log(`Operation ${operation.id}: ${operation.phase}; ${operation.completedCycles} verified improvements.`);
76710
76838
  if (operation.error)
@@ -76831,7 +76959,7 @@ class OperationApi {
76831
76959
  if (checked === "unknown")
76832
76960
  throw new Error("Operation process identity changed. No signal was sent.");
76833
76961
  if (checked === "running")
76834
- (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGTERM")))(job.pid);
76962
+ (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGINT")))(job.pid);
76835
76963
  }
76836
76964
  return { ...await this.status(id), cancelRequested: current === "running" };
76837
76965
  });
@@ -77122,7 +77250,7 @@ class MissionApi {
77122
77250
  throw new Error("Supervisor identity changed during cancellation. Inspect the original process; no signal was sent.");
77123
77251
  if (current === "stopped")
77124
77252
  return { ...await this.status(id), cancelRequested: false };
77125
- (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGTERM")))(job.pid);
77253
+ (this.dependencies.signal ?? ((pid) => process.kill(pid, "SIGINT")))(job.pid);
77126
77254
  }
77127
77255
  return { ...await this.status(id), cancelRequested: liveness === "running" };
77128
77256
  });
@@ -129792,6 +129920,10 @@ async function privateDirectory(root, id) {
129792
129920
  return current;
129793
129921
  }
129794
129922
  function assertLive(mission, signal) {
129923
+ if (isServiceShutdown(signal)) {
129924
+ assertExecutionDeadline(mission);
129925
+ throw interruptionPause(signal, "Code delivery service is shutting down.");
129926
+ }
129795
129927
  if (signal?.aborted)
129796
129928
  throw new DeliveryBlocked("Code delivery was explicitly interrupted. Preserve its checkpoint and inspect the target before resuming.");
129797
129929
  assertExecutionDeadline(mission);
@@ -130004,9 +130136,14 @@ AV-Delivery: ${delivery.nonce}
130004
130136
  delete delivery.error;
130005
130137
  await save();
130006
130138
  } catch (error) {
130139
+ const deadline = mission.execution && mission.executionPolicy && Date.now() >= Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000;
130140
+ if (error instanceof MissionPause && error.kind === "service-shutdown" && !deadline) {
130141
+ delivery.error = error.message;
130142
+ await save();
130143
+ return;
130144
+ }
130007
130145
  if (delivery.attempts === previousAttempts)
130008
130146
  delivery.attempts = Math.min(3, previousAttempts + 1);
130009
- const deadline = mission.execution && mission.executionPolicy && Date.now() >= Date.parse(mission.execution.startedAt) + mission.executionPolicy.maxDurationSec * 1000;
130010
130147
  const blocked = error instanceof DeliveryBlocked || error instanceof MissionPause || signal?.aborted || deadline;
130011
130148
  if (blocked || delivery.attempts >= 3)
130012
130149
  delivery.phase = "blocked";
@@ -130072,13 +130209,14 @@ import { join as join49 } from "node:path";
130072
130209
  async function watchOrders(root = process.cwd(), dependencies = {}) {
130073
130210
  assertNotManagedRun();
130074
130211
  const controller = new AbortController;
130075
- const stop = () => controller.abort();
130212
+ const stop = () => controller.abort(dependencies.signal?.reason);
130213
+ const terminate = () => controller.abort(dependencies.service ? serviceShutdownPause() : undefined);
130076
130214
  dependencies.signal?.addEventListener("abort", stop, { once: true });
130077
130215
  if (dependencies.signal?.aborted)
130078
130216
  stop();
130079
130217
  if (!dependencies.signal) {
130080
130218
  process.once("SIGINT", stop);
130081
- process.once("SIGTERM", stop);
130219
+ process.once("SIGTERM", terminate);
130082
130220
  }
130083
130221
  const missions = new MissionStore(join49(root, ".agent-valley", "missions"));
130084
130222
  try {
@@ -130097,7 +130235,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130097
130235
  if (mission.status === "completed") {
130098
130236
  if (!pendingCodeDelivery(mission) || mission.codeDelivery?.nextRunAt && Date.parse(mission.codeDelivery.nextRunAt) > Date.now())
130099
130237
  continue;
130100
- await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id }, root, {
130238
+ await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id, ...dependencies.service ? { service: true } : {} }, root, {
130101
130239
  signal: controller.signal
130102
130240
  }).then(printOrderOutcome);
130103
130241
  continue;
@@ -130105,7 +130243,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130105
130243
  const recovery = automaticMissionRecovery(mission);
130106
130244
  if (!recovery.retry || recovery.waitUntil && Date.parse(recovery.waitUntil) > Date.now())
130107
130245
  continue;
130108
- await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id }, root, {
130246
+ await (dependencies.mission ?? superviseOrder)(undefined, { resume: mission.id, ...dependencies.service ? { service: true } : {} }, root, {
130109
130247
  signal: controller.signal
130110
130248
  }).then(printOrderOutcome);
130111
130249
  } catch (error) {
@@ -130120,21 +130258,23 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130120
130258
  if (operation.currentMissionId && await missions.isLocked(operation.currentMissionId))
130121
130259
  continue;
130122
130260
  if (operation.phase === "paused") {
130123
- if (operation.pauseKind !== "blocked" || !operation.currentMissionId)
130261
+ if (operation.pauseKind !== "service-shutdown" && (operation.pauseKind !== "blocked" || !operation.currentMissionId))
130124
130262
  continue;
130125
- try {
130126
- const child = await reobserveLocalExecutions(await missions.load(operation.currentMissionId), missions);
130127
- if (child.codeDelivery?.phase === "blocked")
130128
- continue;
130129
- if (!automaticMissionRecovery(child).retry && !(child.status === "completed" && verifiedMissionEvidence(child)))
130263
+ if (operation.currentMissionId) {
130264
+ try {
130265
+ const child = await reobserveLocalExecutions(await missions.load(operation.currentMissionId), missions);
130266
+ if (child.codeDelivery?.phase === "blocked")
130267
+ continue;
130268
+ if (!automaticMissionRecovery(child).retry && !(child.status === "completed" && verifiedMissionEvidence(child)))
130269
+ continue;
130270
+ } catch (error) {
130271
+ console.error(String(error));
130130
130272
  continue;
130131
- } catch (error) {
130132
- console.error(String(error));
130133
- continue;
130273
+ }
130134
130274
  }
130135
130275
  }
130136
130276
  try {
130137
- await (dependencies.operation ?? runOperation)(undefined, { resume: operation.id }, root, {
130277
+ await (dependencies.operation ?? runOperation)(undefined, { resume: operation.id, ...dependencies.service ? { service: true } : {} }, root, {
130138
130278
  signal: controller.signal
130139
130279
  });
130140
130280
  } catch (error) {
@@ -130150,7 +130290,7 @@ async function watchOrders(root = process.cwd(), dependencies = {}) {
130150
130290
  dependencies.signal?.removeEventListener("abort", stop);
130151
130291
  if (!dependencies.signal) {
130152
130292
  process.removeListener("SIGINT", stop);
130153
- process.removeListener("SIGTERM", stop);
130293
+ process.removeListener("SIGTERM", terminate);
130154
130294
  }
130155
130295
  }
130156
130296
  }
@@ -130300,9 +130440,10 @@ async function runOrder(goal, options, root = process.cwd()) {
130300
130440
  const unlock = await store.lock(id);
130301
130441
  const abortController = new AbortController;
130302
130442
  const interrupt = () => abortController.abort(new MissionPause("Operator stopped the order. Its checks and worktree were retained; repair any interrupted effects before resuming with --retry.", "interrupted"));
130443
+ const terminate = () => options.service ? abortController.abort(serviceShutdownPause()) : interrupt();
130303
130444
  const runtime = new ChiefRuntime(store, abortController.signal, (stage, persona) => console.log(`[${stage}] ${persona.name} (${persona.agentType})`));
130304
130445
  process.once("SIGINT", interrupt);
130305
- process.once("SIGTERM", interrupt);
130446
+ process.once("SIGTERM", terminate);
130306
130447
  let mission;
130307
130448
  let capture;
130308
130449
  let reportSaved = false;
@@ -130473,12 +130614,19 @@ Resume: bun av order --resume ${id}`);
130473
130614
  } finally {
130474
130615
  clearTimeout(deadlineTimer);
130475
130616
  process.removeListener("SIGINT", interrupt);
130476
- process.removeListener("SIGTERM", interrupt);
130617
+ process.removeListener("SIGTERM", terminate);
130477
130618
  try {
130478
130619
  try {
130479
130620
  await finishCapture();
130480
130621
  } finally {
130481
- await runtime.close();
130622
+ try {
130623
+ await runtime.close();
130624
+ } finally {
130625
+ if (mission && isServiceShutdown(abortController.signal)) {
130626
+ recordServiceShutdown(mission);
130627
+ await store.save(mission);
130628
+ }
130629
+ }
130482
130630
  }
130483
130631
  } finally {
130484
130632
  await unlock();
@@ -130533,7 +130681,7 @@ async function dispatchOrder(goal, options, root = process.cwd(), dependencies =
130533
130681
  }
130534
130682
  function registerChiefCommands(program) {
130535
130683
  registerContinuousCommands(program);
130536
- program.command("order [goal]").description("Give the Chief Director a goal; continuously select, execute, review and verify improvements").option("--once", "Stop after one verified goal instead of continuing improvements").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check (defaults to av.yaml)").option("--deliver <branch>", "Commit and push only verified, reviewed work to the selected source branch").option("--delivery-paths <json>", "JSON array of exact product files allowed for code delivery").option("--delivery-message <text>", "Commit message for the approved delivery, including required repository trailers").option("--delivery-remote <name>", "Configured Git remote for code delivery (default origin)").option("--delivery-skip-pre-push", "Authorize git push --no-verify for this delivery; commit hooks remain enabled").option("--actor <type>", "Chief Director CLI (default: saved actor.type, otherwise an authenticated CLI)").option("--model <id>", "Chief Director model (default: actor.model from config, otherwise the CLI default)").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Use a configured YAML Actor roster instead of generating goal-specific Actors").addOption(new Option("--agent <type>", "Legacy alias for --actor").hideHelp()).addOption(new Option("--chief <id>", "Legacy alias for --director").hideHelp()).addOption(new Option("--personas <file>", "Legacy alias for --actors").hideHelp()).option("--oma", "Require OMA completion receipts for workers (installed skill selection is automatic)").option("--timeout <seconds>", "Timeout per actor/check (default 600 or actor.timeout)").option("--repairs <count>", "Repair limit per task/final review (default 2)").option("--rounds <count>", "Chief Director recovery decision limit, preserved on resume (default 8, maximum 50)").option("--parallel <count>", "Independent Actor concurrency (default 3, maximum 8)").option("--runs <count>", "Actor call limit per goal/decision; may be increased on saved checkpoint resume (default 200)").option("--duration <seconds>", "Wall-time limit per goal/decision; may be increased on resume (default 86400)").option("--cost <usd>", "Configured-price estimated cost limit; unknown cost pauses further calls").option("--account-run <run-id>", "Reconcile a finished run whose usage/cost was lost").option("--account-cost <usd>", "Operator-observed USD cost for --account-run; stored separately from native usage").option("--retry", "Resume after repairing a blocker; retain prior evidence and spent budget").option("--resolve-effect <task-id>", "Reconcile an interrupted external action before resuming").option("--effect-result <result>", "External destination inspection result: completed or not-applied").option("--no-supervise", "With --once, run directly without worker crash restart or observation polling").addOption(new Option("--worker", "Internal supervised worker").hideHelp()).addOption(new Option("--mission-id <id>", "Internal mission identity").hideHelp()).addOption(new Option("--baseline-workspace <path>", "Internal accepted operation snapshot").hideHelp()).addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).addOption(new Option("--native-model", "Internal pinned Chief native model default").hideHelp()).option("--resume <id>", "Resume the saved continuing order or single mission with its original contract").action(async (goal, options) => {
130684
+ program.command("order [goal]").description("Give the Chief Director a goal; continuously select, execute, review and verify improvements").option("--once", "Stop after one verified goal instead of continuing improvements").option("--cycles <count>", "Cumulative verified improvement limit; default continues until stopped").option("--interval <seconds>", "Wait before selecting again when no new goal is justified (default 300)").option("--workspace <path>", "Target Git repository (defaults to av.yaml)").option("--verify <command>", "Trusted completion check (defaults to av.yaml)").option("--deliver <branch>", "Commit and push only verified, reviewed work to the selected source branch").option("--delivery-paths <json>", "JSON array of exact product files allowed for code delivery").option("--delivery-message <text>", "Commit message for the approved delivery, including required repository trailers").option("--delivery-remote <name>", "Configured Git remote for code delivery (default origin)").option("--delivery-skip-pre-push", "Authorize git push --no-verify for this delivery; commit hooks remain enabled").option("--actor <type>", "Chief Director CLI (default: saved actor.type, otherwise an authenticated CLI)").option("--model <id>", "Chief Director model (default: actor.model from config, otherwise the CLI default)").option("--director <id>", "Chief Director Actor ID").option("--actors <file>", "Use a configured YAML Actor roster instead of generating goal-specific Actors").addOption(new Option("--agent <type>", "Legacy alias for --actor").hideHelp()).addOption(new Option("--chief <id>", "Legacy alias for --director").hideHelp()).addOption(new Option("--personas <file>", "Legacy alias for --actors").hideHelp()).option("--oma", "Require OMA completion receipts for workers (installed skill selection is automatic)").option("--timeout <seconds>", "Timeout per actor/check (default 600 or actor.timeout)").option("--repairs <count>", "Repair limit per task/final review (default 2)").option("--rounds <count>", "Chief Director recovery decision limit, preserved on resume (default 8, maximum 50)").option("--parallel <count>", "Independent Actor concurrency (default 3, maximum 8)").option("--runs <count>", "Actor call limit per goal/decision; may be increased on saved checkpoint resume (default 200)").option("--duration <seconds>", "Wall-time limit per goal/decision; may be increased on resume (default 86400)").option("--cost <usd>", "Configured-price estimated cost limit; unknown cost pauses further calls").option("--account-run <run-id>", "Reconcile a finished run whose usage/cost was lost").option("--account-cost <usd>", "Operator-observed USD cost for --account-run; stored separately from native usage").option("--retry", "Resume after repairing a blocker; retain prior evidence and spent budget").option("--resolve-effect <task-id>", "Reconcile an interrupted external action before resuming").option("--effect-result <result>", "External destination inspection result: completed or not-applied").option("--no-supervise", "With --once, run directly without worker crash restart or observation polling").option("--service", "Resume after OS service SIGTERM within saved limits; SIGINT still cancels").addOption(new Option("--worker", "Internal supervised worker").hideHelp()).addOption(new Option("--mission-id <id>", "Internal mission identity").hideHelp()).addOption(new Option("--baseline-workspace <path>", "Internal accepted operation snapshot").hideHelp()).addOption(new Option("--operation-id <id>", "Internal operation identity").hideHelp()).addOption(new Option("--native-model", "Internal pinned Chief native model default").hideHelp()).option("--resume <id>", "Resume the saved continuing order or single mission with its original contract").action(async (goal, options) => {
130537
130685
  const result = await dispatchOrder(goal, options);
130538
130686
  if ("phase" in result) {
130539
130687
  console.log(`Order ${result.id}: ${result.phase}; ${result.completedCycles} verified improvements.`);
@@ -130546,9 +130694,11 @@ function registerChiefCommands(program) {
130546
130694
  process.exitCode = orderExitCode(result);
130547
130695
  }
130548
130696
  });
130549
- const missions = program.command("missions").description("List saved Chief Director orders and their workspaces").option("--watch", "Resume due or interrupted orders from their saved checkpoints").action(async (options) => {
130697
+ const missions = program.command("missions").description("List saved Chief Director orders and their workspaces").option("--watch", "Resume due or interrupted orders from their saved checkpoints").option("--service", "Treat watcher SIGTERM as recoverable service shutdown; requires --watch").action(async (options) => {
130698
+ if (options.service && !options.watch)
130699
+ throw new Error("Use --service with av missions --watch.");
130550
130700
  if (options.watch) {
130551
- await watchOrders(process.cwd());
130701
+ await watchOrders(process.cwd(), { service: options.service });
130552
130702
  return;
130553
130703
  }
130554
130704
  const missions = await new MissionStore(join51(process.cwd(), ".agent-valley/missions")).list();
@@ -7083,6 +7083,7 @@ var init_contracts = __esm(() => {
7083
7083
  "unknown-effect",
7084
7084
  "budget",
7085
7085
  "interrupted",
7086
+ "service-shutdown",
7086
7087
  "chief-wait",
7087
7088
  "chief-unavailable",
7088
7089
  "integrity"
@@ -7256,7 +7257,7 @@ function recordPause(mission, pause) {
7256
7257
  state.failureKind = pause.kind;
7257
7258
  if (pause.nextRunAt)
7258
7259
  state.nextRunAt = pause.nextRunAt;
7259
- else
7260
+ else if (pause.kind !== "service-shutdown")
7260
7261
  delete state.nextRunAt;
7261
7262
  mission.status = pause.nextRunAt ? "waiting" : "paused";
7262
7263
  mission.error = pause.message;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-valley",
3
- "version": "4.2.0",
3
+ "version": "4.2.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=26.10.0",