@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.2

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.
@@ -24,6 +24,9 @@ export interface JobSnapshot {
24
24
  startedAt: number;
25
25
  durationMs: number;
26
26
  exitCode?: number;
27
+ /** The task this job's completion wake belongs to, if any — lets a caller verify that a
28
+ * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
29
+ taskId?: string;
27
30
  }
28
31
  /** What should happen when the job finishes. */
29
32
  export interface JobWakeContract {
@@ -66,6 +69,7 @@ export declare class ChannelJobManager {
66
69
  private readonly channelId;
67
70
  private readonly executor;
68
71
  private readonly jobs;
72
+ private readonly wakeQueue;
69
73
  private sweepTimer?;
70
74
  private garbageCollectionTimer?;
71
75
  private sweeping;
@@ -133,6 +137,8 @@ export declare class ChannelJobManager {
133
137
  private announce;
134
138
  private kill;
135
139
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
140
+ beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
141
+ finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
136
142
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
137
143
  id: string;
138
144
  status: JobStatus | "not_found";
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import * as log from "../log.js";
6
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
7
+ import { createSerialQueue } from "../shared/serial-queue.js";
7
8
  import { shellEscape } from "../shared/shell-escape.js";
8
9
  import { errorMessage } from "../shared/text-utils.js";
9
10
  import { isRecord } from "../shared/type-guards.js";
@@ -67,6 +68,7 @@ function toSnapshot(record) {
67
68
  startedAt: record.startedAt,
68
69
  durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
69
70
  exitCode: record.exitCode,
71
+ taskId: record.contract.taskId,
70
72
  };
71
73
  }
72
74
  export class ChannelJobManager {
@@ -74,6 +76,7 @@ export class ChannelJobManager {
74
76
  this.channelId = channelId;
75
77
  this.executor = executor;
76
78
  this.jobs = new Map();
79
+ this.wakeQueue = createSerialQueue();
77
80
  this.sweeping = false;
78
81
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
79
82
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
@@ -83,7 +86,7 @@ export class ChannelJobManager {
83
86
  return this.options.stateDir ? join(this.options.stateDir, `${id}.json`) : undefined;
84
87
  }
85
88
  /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
86
- async persist(record) {
89
+ async persist(record, required = false) {
87
90
  const path = this.recordPath(record.id);
88
91
  if (!path)
89
92
  return;
@@ -93,6 +96,8 @@ export class ChannelJobManager {
93
96
  await chmod(path, 0o600).catch(() => undefined);
94
97
  }
95
98
  catch (error) {
99
+ if (required)
100
+ throw error;
96
101
  log.logWarning(`Failed to persist background job ${record.id}`, errorMessage(error));
97
102
  }
98
103
  }
@@ -353,6 +358,16 @@ export class ChannelJobManager {
353
358
  conversationId: "",
354
359
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
355
360
  dispatchId: `job:${this.channelId}:${record.id}:done`,
361
+ ...(record.contract.taskId
362
+ ? {
363
+ internalWake: {
364
+ kind: "job",
365
+ resourceId: record.id,
366
+ taskId: record.contract.taskId,
367
+ dispatchId: `job:${this.channelId}:${record.id}:done`,
368
+ },
369
+ }
370
+ : {}),
356
371
  };
357
372
  try {
358
373
  await this.options.dispatch(event);
@@ -375,6 +390,45 @@ export class ChannelJobManager {
375
390
  }
376
391
  return Array.from(this.jobs.values()).map(toSnapshot);
377
392
  }
393
+ async beginWakeConsumption(id, taskId, dispatchId) {
394
+ return this.wakeQueue.run(id, async () => {
395
+ const record = this.jobs.get(id);
396
+ const expected = `job:${this.channelId}:${id}:done`;
397
+ if (!record ||
398
+ record.status === "running" ||
399
+ record.contract.taskId !== taskId ||
400
+ dispatchId !== expected ||
401
+ record.wakeConsumedAt ||
402
+ (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
403
+ return false;
404
+ }
405
+ const previousClaim = record.wakeClaimDispatchId;
406
+ record.wakeClaimDispatchId = dispatchId;
407
+ try {
408
+ await this.persist(record, true);
409
+ }
410
+ catch (error) {
411
+ record.wakeClaimDispatchId = previousClaim;
412
+ throw error;
413
+ }
414
+ return true;
415
+ });
416
+ }
417
+ async finishWakeConsumption(id, dispatchId) {
418
+ await this.wakeQueue.run(id, async () => {
419
+ const record = this.jobs.get(id);
420
+ if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
421
+ return;
422
+ record.wakeConsumedAt = Date.now();
423
+ try {
424
+ await this.persist(record, true);
425
+ }
426
+ catch (error) {
427
+ record.wakeConsumedAt = undefined;
428
+ throw error;
429
+ }
430
+ });
431
+ }
378
432
  async cancel(ids, signal) {
379
433
  const results = [];
380
434
  for (const id of ids) {
@@ -1,5 +1,8 @@
1
+ import { type JobSnapshot } from "../agent/job-manager.js";
1
2
  import { type Executor } from "../executor.js";
2
3
  import { PipiclawSettingsManager } from "../settings.js";
4
+ import { type RunRecord } from "../subagents/runs.js";
5
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
3
6
  import { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler } from "./dingtalk.js";
4
7
  import { ChannelStore } from "./store.js";
5
8
  export interface BootstrapPaths {
@@ -72,6 +75,39 @@ export declare function bootstrapAppHome(paths?: BootstrapPaths, io?: BootstrapI
72
75
  export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
73
76
  export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
74
77
  export declare function parseArgs(argv: string[], paths?: BootstrapPaths, io?: BootstrapIO): void;
78
+ /**
79
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
80
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
81
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
82
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
83
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
84
+ * untrusted stdout.
85
+ */
86
+ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
87
+ /**
88
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
89
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
90
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
91
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
92
+ */
93
+ export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
94
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
95
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
96
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
97
+ export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
98
+ dispatchId: string;
99
+ };
100
+ export interface ClaimedDelegationWake {
101
+ taskId: string;
102
+ generation?: number;
103
+ activated: boolean;
104
+ finish(): Promise<void>;
105
+ rollback(): Promise<void>;
106
+ }
107
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
108
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
109
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
110
+ export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
75
111
  interface RuntimeContextOptions {
76
112
  paths: BootstrapPaths;
77
113
  dingtalkConfig: DingTalkConfig;
@@ -97,6 +133,8 @@ interface RuntimeContextOptions {
97
133
  onTaskDriverDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
98
134
  startServices?: boolean;
99
135
  registerSignalHandlers?: boolean;
136
+ /** Test-only fault seams for the atomic structured-wake task transition. */
137
+ wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
100
138
  }
101
139
  export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
102
140
  bot: DingTalkBot;
@@ -3,7 +3,7 @@ import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
4
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
5
5
  import { getOrCreateRunner } from "../agent/index.js";
6
- import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
6
+ import { configureJobRuntime, getChannelJobManager, restoreChannelJobs, } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
8
  import { resetRunner } from "../agent/runner-factory.js";
9
9
  import { renderStatus } from "../agent/status-render.js";
@@ -18,9 +18,9 @@ import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
19
19
  import { fileStamp } from "../shared/file-stamp.js";
20
20
  import { errorMessage } from "../shared/text-utils.js";
21
- import { configureSubAgentRuntime, restoreAllSubAgentRuns } from "../subagents/runs.js";
21
+ import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, } from "../subagents/runs.js";
22
22
  import { readActiveTasks } from "../tasks/ledger.js";
23
- import { activateWaitingTask, claimTaskAttempt, finishTaskAttempt } from "../tasks/store.js";
23
+ import { activateWaitingTaskAndClaimAttempt, finishTaskAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
24
24
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
25
25
  import { getUsageLedger } from "../usage/ledger.js";
26
26
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
@@ -401,6 +401,70 @@ function flushInactiveChannelMemory(channelRunners) {
401
401
  function isNoRunningTaskQueueError(err) {
402
402
  return err instanceof Error && err.message === "No task is currently running.";
403
403
  }
404
+ /**
405
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
406
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
407
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
408
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
409
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
410
+ * untrusted stdout.
411
+ */
412
+ export function isVerifiedJobWake(jobs, jobId, taskId) {
413
+ const job = jobs.find((candidate) => candidate.id === jobId);
414
+ return job !== undefined && job.status !== "running" && job.taskId === taskId;
415
+ }
416
+ /**
417
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
418
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
419
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
420
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
421
+ */
422
+ export function isVerifiedDelegationWake(record, taskId) {
423
+ return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
424
+ }
425
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
426
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
427
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
428
+ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
429
+ const wake = event.internalWake;
430
+ return (wake?.kind === kind &&
431
+ wake.resourceId === resourceId &&
432
+ wake.taskId === taskId &&
433
+ typeof event.dispatchId === "string" &&
434
+ wake.dispatchId === event.dispatchId);
435
+ }
436
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
437
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
438
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
439
+ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
440
+ const wake = event.internalWake;
441
+ if (wake?.kind !== "subagent")
442
+ return undefined;
443
+ const runManager = getSubAgentRunManager(event.channelId);
444
+ const record = runManager.get(wake.resourceId);
445
+ if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
446
+ !isVerifiedDelegationWake(record, wake.taskId) ||
447
+ !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
448
+ return undefined;
449
+ }
450
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
451
+ const handoff = {
452
+ kind: "subagent",
453
+ resourceId: wake.resourceId,
454
+ dispatchId: event.dispatchId,
455
+ };
456
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "external-signal", new Date(), hooks, handoff);
457
+ return {
458
+ taskId: wake.taskId,
459
+ generation: activated?.generation,
460
+ activated: activated !== undefined,
461
+ finish: async () => {
462
+ await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
463
+ await finishWakeTaskActivation(channelDir, wake.taskId, handoff);
464
+ },
465
+ rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
466
+ };
467
+ }
404
468
  export function createRuntimeContext(options) {
405
469
  const startServices = options.startServices ?? true;
406
470
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
@@ -619,6 +683,7 @@ export function createRuntimeContext(options) {
619
683
  }
620
684
  const runner = getRunner(event.channelId);
621
685
  await durableDispatch?.markStarted(event.dispatchId);
686
+ let structuredWakeFinalized = event.internalWake === undefined;
622
687
  const task = (async () => {
623
688
  try {
624
689
  await archiveIncomingMessage(event.channelId, {
@@ -682,33 +747,74 @@ export function createRuntimeContext(options) {
682
747
  // task-driver turn is measured as a delta (turns on a channel are serialized)
683
748
  // and credited to the task it was dispatched for.
684
749
  const effectsBefore = channelEffectCount(event.channelId);
685
- const jobTaskId = /^\[JOB:[^\]]+\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text)?.[1];
750
+ // Both wake formats below carry an unauthenticated claim in plain text: anything
751
+ // that can put a message on this channel can *write* "[JOB:x] ... belongs to task
752
+ // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
753
+ // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
754
+ // treats external output as untrusted). Activating a waiting task on text pattern
755
+ // alone lets that forged claim advance an unrelated task's attempt generation. The
756
+ // pattern match only extracts a *candidate* id pair now; both paths verify the
757
+ // named run/job actually exists, is done, and really is the one that names this
758
+ // taskId before ever calling `activateWaitingTask` (T9).
759
+ const jobTextMatch = /^\[JOB:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
760
+ const jobMatch = event.internalWake?.kind === "job"
761
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
762
+ : jobTextMatch;
686
763
  let recoveredJobTaskId;
687
- if (jobTaskId) {
688
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
689
- const activated = await activateWaitingTask(channelDir, jobTaskId, "job");
690
- if (activated)
691
- recoveredJobTaskId = jobTaskId;
692
- if (activated?.fields.control) {
693
- const claim = await claimTaskAttempt(channelDir, jobTaskId, new Date());
694
- if (claim)
695
- event.taskAttemptGeneration = claim.generation;
764
+ if (jobMatch) {
765
+ const [, jobId, jobTaskId] = jobMatch;
766
+ const jobManager = getChannelJobManager(event.channelId, executor);
767
+ const jobs = await jobManager.list();
768
+ const verified = isTrustedInternalWake(event, "job", jobId, jobTaskId) &&
769
+ isVerifiedJobWake(jobs, jobId, jobTaskId) &&
770
+ (await jobManager.beginWakeConsumption(jobId, jobTaskId, event.dispatchId));
771
+ if (verified) {
772
+ const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
773
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, jobTaskId, "job", new Date(), options.wakeTransitionHooks?.job);
774
+ if (activated) {
775
+ recoveredJobTaskId = jobTaskId;
776
+ event.taskAttemptGeneration = activated.generation;
777
+ }
778
+ await jobManager.finishWakeConsumption(jobId, event.dispatchId);
779
+ structuredWakeFinalized = true;
780
+ if (event.internalWake?.kind === "job" && !activated)
781
+ return;
782
+ }
783
+ else {
784
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [JOB:${jobId}] wake claiming task ${jobTaskId}`);
785
+ if (event.internalWake?.kind === "job") {
786
+ structuredWakeFinalized = true;
787
+ return;
788
+ }
696
789
  }
697
790
  }
698
791
  // Spec 040, D7: a delegation run's completion wake carries the same "belongs to
699
792
  // task" contract as a background job's, and reactivates a task parked with
700
- // waitingFor="external-signal" the same way.
701
- const delegationTaskId = /^\[SUBAGENT:[^\]]+\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text)?.[1];
793
+ // waitingFor="external-signal" the same way — verified the same way (T9).
794
+ const delegationTextMatch = /^\[SUBAGENT:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
795
+ const delegationMatch = event.internalWake?.kind === "subagent"
796
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
797
+ : delegationTextMatch;
702
798
  let recoveredDelegationTaskId;
703
- if (delegationTaskId) {
704
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
705
- const activated = await activateWaitingTask(channelDir, delegationTaskId, "external-signal");
706
- if (activated)
707
- recoveredDelegationTaskId = delegationTaskId;
708
- if (activated?.fields.control) {
709
- const claim = await claimTaskAttempt(channelDir, delegationTaskId, new Date());
710
- if (claim)
711
- event.taskAttemptGeneration = claim.generation;
799
+ if (delegationMatch) {
800
+ const [, runId, delegationTaskId] = delegationMatch;
801
+ const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
802
+ if (claimed) {
803
+ if (claimed.activated)
804
+ recoveredDelegationTaskId = claimed.taskId;
805
+ if (claimed.generation !== undefined)
806
+ event.taskAttemptGeneration = claimed.generation;
807
+ await claimed.finish();
808
+ structuredWakeFinalized = true;
809
+ if (event.internalWake?.kind === "subagent" && !claimed.activated)
810
+ return;
811
+ }
812
+ else {
813
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [SUBAGENT:${runId}] wake claiming task ${delegationTaskId}`);
814
+ if (event.internalWake?.kind === "subagent") {
815
+ structuredWakeFinalized = true;
816
+ return;
817
+ }
712
818
  }
713
819
  }
714
820
  const result = await runner.run(ctx, store);
@@ -746,7 +852,10 @@ export function createRuntimeContext(options) {
746
852
  });
747
853
  }
748
854
  finally {
749
- await durableDispatch?.markCompleted(event.dispatchId);
855
+ if (structuredWakeFinalized)
856
+ await durableDispatch?.markCompleted(event.dispatchId);
857
+ else
858
+ await durableDispatch?.markRetryable(event.dispatchId);
750
859
  runner.endTurn();
751
860
  // A finished turn may have written task files (progress/complete/set); rescan
752
861
  // now so a continuing task chain advances immediately instead of after a full sleep.
@@ -37,6 +37,14 @@ export interface DingTalkEvent {
37
37
  channelName?: string;
38
38
  /** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
39
39
  dispatchId?: string;
40
+ /** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
41
+ * never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
42
+ internalWake?: {
43
+ kind: "job" | "subagent";
44
+ resourceId: string;
45
+ taskId: string;
46
+ dispatchId: string;
47
+ };
40
48
  /**
41
49
  * The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
42
50
  * Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
@@ -34,6 +34,10 @@ export declare class DurableDispatchService {
34
34
  cancelChannel(channelId: string): Promise<number>;
35
35
  markStarted(id: string | undefined): Promise<void>;
36
36
  markCompleted(id: string | undefined): Promise<void>;
37
+ /** Release a failed handler's in-process claim without deleting its durable record. Structured
38
+ * wake activation uses this for transient task/job/run persistence failures so the next drain
39
+ * can retry the same dispatch id instead of losing the only completion signal. */
40
+ markRetryable(id: string | undefined): Promise<void>;
37
41
  drainOnce(now?: number): Promise<void>;
38
42
  private read;
39
43
  private write;
@@ -160,6 +160,22 @@ export class DurableDispatchService {
160
160
  await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
161
161
  });
162
162
  }
163
+ /** Release a failed handler's in-process claim without deleting its durable record. Structured
164
+ * wake activation uses this for transient task/job/run persistence failures so the next drain
165
+ * can retry the same dispatch id instead of losing the only completion signal. */
166
+ async markRetryable(id) {
167
+ if (!id)
168
+ return;
169
+ this.running.delete(id);
170
+ await this.queue.run(id, async () => {
171
+ const record = await this.read(id);
172
+ if (!record)
173
+ return;
174
+ record.status = "pending";
175
+ record.leaseExpiresAt = undefined;
176
+ await this.write(record);
177
+ });
178
+ }
163
179
  async drainOnce(now = Date.now()) {
164
180
  let filenames;
165
181
  try {
@@ -24,6 +24,13 @@ export async function logSecurityEvent(workspaceDir, config, event) {
24
24
  // disappear just because the operator only wants blocked-action logging.
25
25
  if (!config.audit.logBlocked && event.type !== "external-agent")
26
26
  return;
27
+ if (event.type === "external-agent") {
28
+ // External agents bypass command-guard. Their complete dispatch record is therefore a
29
+ // security gate, not best-effort observability: do not return until it is on disk, and let
30
+ // capacity/permission/I/O failures reject the dispatch before a child can be spawned.
31
+ await getAppender(getLogPath(workspaceDir, config)).appendStrict({ date: formatLocalTime(), ...event });
32
+ return;
33
+ }
27
34
  let timer;
28
35
  try {
29
36
  await Promise.race([
@@ -8,8 +8,14 @@
8
8
  /** True if `pid` names a live process this user can at least see, without sending a real signal. */
9
9
  export declare function isProcessAlive(pid: number): boolean;
10
10
  /**
11
- * SIGTERM the process group, then SIGKILL it after a short grace period if it is still alive.
11
+ * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
12
12
  * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
13
13
  * it and everything it spawned.
14
+ *
15
+ * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
16
+ * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
17
+ * report false while the descendant is still alive and still holding the workspace, so probing
18
+ * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
19
+ * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
14
20
  */
15
21
  export declare function killProcessGroup(pid: number, graceMs?: number): Promise<void>;
@@ -17,9 +17,15 @@ export function isProcessAlive(pid) {
17
17
  }
18
18
  }
19
19
  /**
20
- * SIGTERM the process group, then SIGKILL it after a short grace period if it is still alive.
20
+ * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
21
21
  * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
22
22
  * it and everything it spawned.
23
+ *
24
+ * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
25
+ * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
26
+ * report false while the descendant is still alive and still holding the workspace, so probing
27
+ * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
28
+ * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
23
29
  */
24
30
  export async function killProcessGroup(pid, graceMs = 300) {
25
31
  try {
@@ -28,8 +34,6 @@ export async function killProcessGroup(pid, graceMs = 300) {
28
34
  catch {
29
35
  return; // Already gone.
30
36
  }
31
- if (!isProcessAlive(pid))
32
- return;
33
37
  await new Promise((resolve) => setTimeout(resolve, graceMs));
34
38
  try {
35
39
  process.kill(-pid, "SIGKILL");
@@ -26,6 +26,8 @@ export interface JsonlAppenderOptions {
26
26
  export interface JsonlAppender {
27
27
  /** Queue and await one record. Never throws; a full or closed writer drops it. */
28
28
  append(record: unknown, priority?: JsonlPriority): Promise<void>;
29
+ /** Queue and durably append one record, rejecting on serialization, capacity, closure, or I/O failure. */
30
+ appendStrict(record: unknown, priority?: JsonlPriority): Promise<void>;
29
31
  /** Queue one record without waiting for disk. Returns false when it cannot be accepted. */
30
32
  tryAppend(record: unknown, priority?: JsonlPriority): boolean;
31
33
  /** Wait until every currently accepted record has finished. */
@@ -93,7 +93,7 @@ export function createJsonlAppender(options) {
93
93
  await appendFile(filePath, line, { encoding: "utf-8", mode });
94
94
  sizes.set(filePath, (await currentSize(filePath)) + lineBytes);
95
95
  };
96
- const serialize = (record) => {
96
+ const serialize = (record, strict) => {
97
97
  try {
98
98
  const json = JSON.stringify(options.recordForWrite ? options.recordForWrite(record) : record);
99
99
  if (json === undefined)
@@ -101,7 +101,9 @@ export function createJsonlAppender(options) {
101
101
  const line = `${json}\n`;
102
102
  return { filePath: resolvePath(new Date(), record), line, bytes: Buffer.byteLength(line) };
103
103
  }
104
- catch {
104
+ catch (error) {
105
+ if (strict)
106
+ throw error;
105
107
  if (!warnedDrop) {
106
108
  warnedDrop = true;
107
109
  fallbackWarning("runtime.log_sink.dropped", "Failed to serialize JSONL record; record was dropped");
@@ -109,15 +111,20 @@ export function createJsonlAppender(options) {
109
111
  return null;
110
112
  }
111
113
  };
112
- const enqueue = (record, priority) => {
113
- if (closed)
114
+ const enqueue = (record, priority, strict = false) => {
115
+ if (closed) {
116
+ if (strict)
117
+ throw new Error("JSONL appender is closed");
114
118
  return null;
115
- const serialized = serialize(record);
119
+ }
120
+ const serialized = serialize(record, strict);
116
121
  if (!serialized)
117
122
  return null;
118
123
  const recordLimit = priority === "critical" ? maxPendingRecords : maxPendingRecords - reservedCriticalRecords;
119
124
  const byteLimit = priority === "critical" ? maxPendingBytes : maxPendingBytes - reservedCriticalBytes;
120
125
  if (pending.size >= recordLimit || pendingBytes + serialized.bytes > byteLimit) {
126
+ if (strict)
127
+ throw new Error("JSONL queue limit reached");
121
128
  if (!warnedDrop) {
122
129
  warnedDrop = true;
123
130
  fallbackWarning("runtime.log_sink.dropped", "JSONL queue limit reached; record was dropped");
@@ -125,20 +132,19 @@ export function createJsonlAppender(options) {
125
132
  return null;
126
133
  }
127
134
  const previous = chains.get(serialized.filePath) ?? Promise.resolve();
128
- const result = previous
135
+ const writeResult = previous
129
136
  .catch(() => undefined)
130
- .then(async () => {
131
- try {
132
- await write(serialized.filePath, serialized.line, serialized.bytes);
137
+ .then(() => write(serialized.filePath, serialized.line, serialized.bytes));
138
+ const result = strict
139
+ ? writeResult
140
+ : writeResult.then(() => {
133
141
  warnedWrite = false;
134
- }
135
- catch {
142
+ }, () => {
136
143
  if (!warnedWrite) {
137
144
  warnedWrite = true;
138
145
  fallbackWarning("runtime.log_sink.failed", "Failed to append JSONL record; continuing without it");
139
146
  }
140
- }
141
- });
147
+ });
142
148
  const completion = result.finally(() => {
143
149
  pending.delete(completion);
144
150
  pendingBytes -= serialized.bytes;
@@ -161,6 +167,12 @@ export function createJsonlAppender(options) {
161
167
  async append(record, priority = "critical") {
162
168
  await enqueue(record, priority)?.completion;
163
169
  },
170
+ async appendStrict(record, priority = "critical") {
171
+ const pendingLine = enqueue(record, priority, true);
172
+ if (!pendingLine)
173
+ throw new Error("JSONL record was not accepted");
174
+ await pendingLine.completion;
175
+ },
164
176
  tryAppend(record, priority = "normal") {
165
177
  return enqueue(record, priority) !== null;
166
178
  },
@@ -1,5 +1,7 @@
1
1
  import { spawn as nodeSpawn } from "node:child_process";
2
+ import type { SecurityConfig } from "../../security/types.js";
2
3
  import type { SubAgentThinkingLevel } from "../discovery.js";
4
+ import { type RunMutates } from "../runs.js";
3
5
  /**
4
6
  * The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
5
7
  * detached process. The launch order matters (D1): admission and the lease are the caller's job
@@ -31,6 +33,14 @@ export interface LaunchExternalRunInput {
31
33
  taskId?: string;
32
34
  leaseKey?: string;
33
35
  resumeSessionId?: string;
36
+ /** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
37
+ mutates?: RunMutates;
38
+ /** Where the audit trail lives (`<workspaceDir>/.pipiclaw/security.log` by default) and whether
39
+ * it is enabled — every external dispatch writes an `external-agent` audit event (D8.1), since
40
+ * external processes never pass through command-guard and this is the only record of what
41
+ * actually ran. */
42
+ workspaceDir: string;
43
+ securityConfig: SecurityConfig;
34
44
  /** Test seam: inject a fake `child_process.spawn`. */
35
45
  spawnFn?: typeof nodeSpawn;
36
46
  }