@oyasmi/pipiclaw 0.9.0-beta.7 → 0.9.0-beta.9

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 (77) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +21 -2
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/agent/job-manager.d.ts +3 -3
  6. package/dist/agent/job-manager.js +0 -1
  7. package/dist/agent/runner-factory.d.ts +16 -4
  8. package/dist/agent/runner-factory.js +9 -23
  9. package/dist/agent/types.d.ts +9 -1
  10. package/dist/agent/types.js +3 -16
  11. package/dist/memory/review-log.js +0 -0
  12. package/dist/memory/scheduler.d.ts +1 -0
  13. package/dist/memory/scheduler.js +64 -6
  14. package/dist/playbooks/agent-delegation.md +2 -2
  15. package/dist/runtime/bootstrap.d.ts +10 -2
  16. package/dist/runtime/bootstrap.js +83 -55
  17. package/dist/runtime/channel-event.d.ts +41 -0
  18. package/dist/runtime/channel-event.js +1 -0
  19. package/dist/runtime/delivery.d.ts +3 -2
  20. package/dist/runtime/dingtalk.d.ts +9 -31
  21. package/dist/runtime/durable-dispatch.d.ts +4 -2
  22. package/dist/runtime/durable-dispatch.js +36 -25
  23. package/dist/runtime/events.d.ts +3 -2
  24. package/dist/runtime/events.js +2 -3
  25. package/dist/runtime/subagent-commands.js +48 -10
  26. package/dist/runtime/task-commands.js +2 -2
  27. package/dist/runtime/task-driver.d.ts +7 -7
  28. package/dist/runtime/task-driver.js +1 -4
  29. package/dist/runtime/task-migration.js +1 -1
  30. package/dist/runtime/task-wake.d.ts +4 -4
  31. package/dist/settings.d.ts +0 -106
  32. package/dist/settings.js +0 -224
  33. package/dist/shared/host-process.d.ts +25 -9
  34. package/dist/shared/host-process.js +59 -10
  35. package/dist/shared/types.d.ts +1 -0
  36. package/dist/shared/types.js +10 -1
  37. package/dist/subagents/discovery.d.ts +24 -0
  38. package/dist/subagents/discovery.js +103 -17
  39. package/dist/subagents/external/claude-code.js +10 -3
  40. package/dist/subagents/external/codex-cli.js +9 -3
  41. package/dist/subagents/external/exec.js +1 -0
  42. package/dist/subagents/external/harness.d.ts +22 -0
  43. package/dist/subagents/external/harness.js +22 -4
  44. package/dist/subagents/external/run.d.ts +23 -3
  45. package/dist/subagents/external/run.js +112 -131
  46. package/dist/subagents/external/settlement.d.ts +50 -0
  47. package/dist/subagents/external/settlement.js +123 -0
  48. package/dist/subagents/format.d.ts +4 -0
  49. package/dist/subagents/format.js +7 -0
  50. package/dist/subagents/runs.d.ts +73 -16
  51. package/dist/subagents/runs.js +197 -120
  52. package/dist/subagents/tool.d.ts +38 -6
  53. package/dist/subagents/tool.js +93 -61
  54. package/dist/subagents/verification-outcome.d.ts +26 -0
  55. package/dist/subagents/verification-outcome.js +16 -0
  56. package/dist/subagents/workspace-lease.d.ts +10 -1
  57. package/dist/subagents/workspace-lease.js +15 -2
  58. package/dist/tasks/ledger.js +1 -1
  59. package/dist/{shared → tasks}/task-schedule.js +1 -1
  60. package/dist/tools/bash.js +1 -1
  61. package/dist/tools/event-manage.js +1 -4
  62. package/dist/tools/grep.js +2 -3
  63. package/dist/tools/index.js +6 -0
  64. package/dist/tools/job.js +5 -5
  65. package/dist/tools/memory-manage.js +3 -6
  66. package/dist/tools/session-search.js +0 -1
  67. package/dist/tools/skill-manage.js +3 -3
  68. package/dist/tools/subagent-manage.d.ts +20 -6
  69. package/dist/tools/subagent-manage.js +88 -18
  70. package/dist/tools/task-manage/shared.js +2 -2
  71. package/dist/tools/task-manage.js +1 -4
  72. package/dist/tools/web-fetch.js +0 -1
  73. package/dist/tui/app.js +4 -4
  74. package/package.json +1 -1
  75. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  76. /package/dist/{shared → tasks}/task-events.js +0 -0
  77. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -0,0 +1,123 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../../log.js";
4
+ import { formatLocalTime } from "../../shared/local-time.js";
5
+ import { errorMessage } from "../../shared/text-utils.js";
6
+ import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
7
+ import { writeVerificationAttestation } from "../../tasks/verification.js";
8
+ import { resolveVerificationOutcome } from "../verification-outcome.js";
9
+ import { classifyExternalOutcome } from "./harness.js";
10
+ import { getExternalHarness } from "./registry.js";
11
+ /**
12
+ * Spec 042 D1: the one place an external run's parsed outcome becomes a `SettleInput`, and the
13
+ * one place its verify verdict gets decided and attested. Before this module existed, that logic
14
+ * was written three times — the live post-exit path (`external/run.ts`), and restart
15
+ * reconciliation (`runs.ts`) — and the third copy was the thinnest: it never read `events.jsonl`
16
+ * at all on a cancelled/timed-out run, and never attempted a verify attestation, because the
17
+ * inputs it would have needed (`verifySubjectBefore`, `channelDir`) were never persisted. Both
18
+ * defects are closed by making this the only path either caller can take.
19
+ */
20
+ const STDERR_TAIL_CHARS = 2_000;
21
+ /**
22
+ * Translate a parsed outcome into the only `SettleInput` this run will get. `terminationReason`
23
+ * overrides `status`/`failureReason` (P1-1: even a CLI that prints a success terminal right before
24
+ * SIGTERM lands does not get credit for finishing) but never touches usage, output text, or
25
+ * session id — those come from whatever the process actually produced, parsed or not.
26
+ */
27
+ export function buildExternalSettleInput(input) {
28
+ const classification = classifyExternalOutcome(input.harnessId, input.outcome);
29
+ const cancelled = input.terminationReason === "cancelled";
30
+ const timedOut = input.terminationReason === "timeout";
31
+ const status = cancelled ? "cancelled" : timedOut ? "failed" : classification.status;
32
+ const failureReason = cancelled
33
+ ? "Cancelled by request."
34
+ : timedOut
35
+ ? `Wall time budget exceeded (${input.maxWallTimeSec}s)`
36
+ : classification.failureReason;
37
+ return {
38
+ status,
39
+ failureReason,
40
+ usage: {
41
+ input: input.outcome.usage?.input ?? 0,
42
+ output: input.outcome.usage?.output ?? 0,
43
+ cacheRead: input.outcome.usage?.cacheRead ?? 0,
44
+ cacheWrite: input.outcome.usage?.cacheWrite ?? 0,
45
+ total: input.outcome.usage?.total ?? 0,
46
+ cost: input.outcome.usage?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
47
+ },
48
+ usageKnown: input.outcome.usageKnown,
49
+ costKnown: input.outcome.costKnown,
50
+ turns: 0,
51
+ toolCalls: 0,
52
+ durationMs: input.durationMs,
53
+ durationEstimated: input.durationEstimated,
54
+ outputText: input.outcome.finalText,
55
+ sessionId: input.outcome.sessionId,
56
+ };
57
+ }
58
+ /**
59
+ * Read this run's artifact files, parse them through its harness, decide its verdict (including a
60
+ * verify attestation when applicable), and hand the result to `settle`. Both the live post-exit
61
+ * path and restart reconciliation call this and only this — there is no second implementation to
62
+ * drift out of sync with the first (spec 042 F1).
63
+ */
64
+ export async function finalizeExternalRun(input, settle, options) {
65
+ const harness = getExternalHarness(input.harnessId);
66
+ const eventsPath = join(input.artifactDir, "events.jsonl");
67
+ const stderrPath = join(input.artifactDir, "stderr.log");
68
+ const eventsText = await readFile(eventsPath, "utf-8").catch(() => "");
69
+ const stderrTail = (await readFile(stderrPath, "utf-8").catch(() => "")).slice(-STDERR_TAIL_CHARS);
70
+ const outcome = harness
71
+ ? harness.parseOutcome({ eventsText, exitCode: input.exitCode, stderrTail })
72
+ : {
73
+ finalText: "",
74
+ terminalSeen: false,
75
+ protocolStatus: "unparsable",
76
+ usageKnown: false,
77
+ costKnown: false,
78
+ stderrTail,
79
+ errorMessage: `Unknown harness "${input.harnessId}"; cannot judge this run.`,
80
+ };
81
+ const settleInput = buildExternalSettleInput({
82
+ harnessId: input.harnessId,
83
+ outcome,
84
+ durationMs: input.durationMs,
85
+ durationEstimated: input.durationEstimated,
86
+ terminationReason: input.terminationReason,
87
+ maxWallTimeSec: input.maxWallTimeSec,
88
+ });
89
+ const shouldVerify = input.purpose === "verify" &&
90
+ input.taskId !== undefined &&
91
+ input.channelDir !== undefined &&
92
+ settleInput.status === "completed";
93
+ if (!shouldVerify) {
94
+ await settle(settleInput, options);
95
+ return;
96
+ }
97
+ // D9: an external verifier's tools cannot be structurally removed, so a before/after subject
98
+ // hash is the only after-the-fact check available. `subjectBefore` came from the launch-time
99
+ // snapshot (persisted so restart reconciliation has it too, spec 042 D1).
100
+ const subjectAfter = await workspaceSubjectHash(input.workingDirectory);
101
+ const verification = resolveVerificationOutcome({
102
+ subjectBefore: input.verifySubjectBefore,
103
+ subjectAfter,
104
+ finalText: outcome.finalText,
105
+ runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
106
+ });
107
+ await writeVerificationAttestation(input.channelDir, {
108
+ runId: input.runId,
109
+ taskId: input.taskId,
110
+ verdict: verification.verdict,
111
+ checkedAt: formatLocalTime(),
112
+ evidence: verification.evidence,
113
+ workspaceChanged: verification.workspaceChanged,
114
+ subjectHash: verification.workspaceChanged ? undefined : subjectAfter,
115
+ subjectDir: input.workingDirectory,
116
+ // External verifiers cannot have their tools structurally removed the way an internal
117
+ // verifier's are — advisory, not enforced (D9).
118
+ verificationStrength: "advisory",
119
+ }).catch((error) => {
120
+ log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
121
+ });
122
+ await settle({ ...settleInput, verificationVerdict: verification.verdict, verificationStrength: "advisory" }, options);
123
+ }
@@ -7,6 +7,10 @@ import type { RunRecord } from "./runs.js";
7
7
  */
8
8
  export declare function formatDuration(ms: number): string;
9
9
  export declare function elapsedMs(record: RunRecord, now?: number): number;
10
+ /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
11
+ * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
12
+ * mistake it for a precise figure. */
13
+ export declare function formatRunDuration(record: RunRecord, now?: number): string;
10
14
  export declare function harnessLabel(record: RunRecord): string;
11
15
  /** `undefined` when cost genuinely is not known (e.g. `codex-cli`, `exec`) — never displayed as $0. */
12
16
  export declare function formatCost(record: RunRecord): string | undefined;
@@ -13,6 +13,13 @@ export function formatDuration(ms) {
13
13
  export function elapsedMs(record, now = Date.now()) {
14
14
  return (record.finishedAt ?? now) - record.startedAt;
15
15
  }
16
+ /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
17
+ * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
18
+ * mistake it for a precise figure. */
19
+ export function formatRunDuration(record, now = Date.now()) {
20
+ const text = formatDuration(elapsedMs(record, now));
21
+ return record.durationEstimated ? `≈${text}` : text;
22
+ }
16
23
  export function harnessLabel(record) {
17
24
  return record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
18
25
  }
@@ -1,6 +1,6 @@
1
- import type { DingTalkEvent } from "../runtime/dingtalk.js";
1
+ import type { ChannelEvent } from "../runtime/channel-event.js";
2
2
  import type { ChannelStore } from "../runtime/store.js";
3
- import type { UsageTotals } from "../shared/types.js";
3
+ import { type UsageTotals } from "../shared/types.js";
4
4
  import type { UsageLedger } from "../usage/ledger.js";
5
5
  /**
6
6
  * The run: one abstraction level for delegation, whether it executes as an in-process sub-agent
@@ -94,13 +94,43 @@ export interface RunRecord extends RunUsage {
94
94
  * enforcing it — an in-process timer dies with the process that set it. */
95
95
  deadlineAt?: number;
96
96
  /** Set before the kill signal is sent, so whichever code path eventually settles this run (the
97
- * live in-process watcher or the cross-restart sweeper) reports why, instead of guessing from
97
+ * live in-process watcher or the cross-restart deadline check) reports why, instead of guessing from
98
98
  * protocol output alone (P1-1). */
99
99
  terminationReason?: "timeout" | "cancelled";
100
100
  argv?: string[];
101
101
  sessionId?: string;
102
102
  leaseKey?: string;
103
103
  mutates?: RunMutates;
104
+ /** Spec 042 D1: persisted at launch so restart reconciliation has the same inputs a live
105
+ * watcher would — the workspace subject hash taken just before an external verify run
106
+ * started, so a restart can still write its attestation instead of silently skipping it. */
107
+ verifySubjectBefore?: string;
108
+ /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
109
+ * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
110
+ maxWallTimeSec?: number;
111
+ /** Spec 042 D1: the real process start time (`setLaunched` time), as opposed to `startedAt`
112
+ * (registration time) — restart reconciliation's duration estimate is measured from here. */
113
+ processStartedAt?: number;
114
+ /** Spec 042 D1: needed only to write a verify attestation from restart reconciliation, which
115
+ * has no other way to reach the channel directory. */
116
+ channelDir?: string;
117
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
118
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
119
+ durationEstimated?: boolean;
120
+ /** Spec 042 D10: non-fatal argv-assembly warnings (e.g. a dropped placeholder token) recorded
121
+ * at launch, shown by `/subagents show`. */
122
+ invocationWarnings?: string[];
123
+ /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell` at launch time
124
+ * (external only) — `follow_up` refuses to resume under a role that has since changed one of
125
+ * these instead of silently reinterpreting the old session under a new harness invocation. */
126
+ roleFingerprint?: string;
127
+ /** Spec 042 D12: the harness adapter's own schema version at launch — lets `/subagents show`
128
+ * distinguish "the target CLI's own protocol changed under an adapter that hasn't caught up"
129
+ * from "the agent itself failed". */
130
+ parserVersion?: number;
131
+ /** Spec 042 D12: best-effort `<executable> --version` output captured at launch (1s timeout,
132
+ * `undefined` if the probe failed or timed out) — the other half of the same diagnosis. */
133
+ cliVersion?: string;
104
134
  }
105
135
  export interface RegisterRunInput {
106
136
  runId: string;
@@ -128,6 +158,9 @@ export interface SettleInput {
128
158
  turns: number;
129
159
  toolCalls: number;
130
160
  durationMs: number;
161
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
162
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
163
+ durationEstimated?: boolean;
131
164
  /** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
132
165
  outputText: string;
133
166
  verificationVerdict?: "pass" | "fail";
@@ -138,7 +171,7 @@ export interface SettleInput {
138
171
  export interface RunManagerOptions {
139
172
  /** Root of the per-channel record directories (`<stateDir>/<channelId>/`). Omit to skip persistence. */
140
173
  stateDir?: string;
141
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
174
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
142
175
  ledger?: UsageLedger;
143
176
  store?: ChannelStore;
144
177
  }
@@ -159,6 +192,9 @@ export declare class SubAgentRunManager {
159
192
  /** External launch intents exist before a safe live child handle does. A cancel in that window
160
193
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
161
194
  private readonly externalLaunches;
195
+ /** One-shot deadline checks for external processes adopted during restore. Unlike a child this
196
+ * daemon spawned itself, an adopted process cannot emit a `close` event to this process. */
197
+ private readonly externalRecoveryTimers;
162
198
  private readonly queue;
163
199
  constructor(channelId: string, options: RunManagerOptions);
164
200
  private recordPath;
@@ -202,6 +238,23 @@ export declare class SubAgentRunManager {
202
238
  argv: string[];
203
239
  deadlineAt: number;
204
240
  sessionId?: string;
241
+ /** Spec 042 D1: everything a restart reconciliation might need if this daemon disappears
242
+ * before the process exits — restore/deadline recovery must have the same inputs a live watcher
243
+ * would, not a thinner subset. */
244
+ verifySubjectBefore?: string;
245
+ maxWallTimeSec?: number;
246
+ processStartedAt?: number;
247
+ channelDir?: string;
248
+ /** Spec 042 D10: non-fatal invocation warnings from argv assembly (e.g. a dropped
249
+ * placeholder token), so they survive on the run rather than only ever hitting a log line. */
250
+ invocationWarnings?: string[];
251
+ /** Spec 042 D7: the role's `command`/`externalModelRef`/`shell` fingerprint at launch. */
252
+ roleFingerprint?: string;
253
+ /** Spec 042 D12: the harness adapter's schema version and a best-effort `--version` probe
254
+ * of the target CLI, so a later failure can be diagnosed as "adapter is stale" vs. "the
255
+ * agent itself failed" instead of looking identical. */
256
+ parserVersion?: number;
257
+ cliVersion?: string;
205
258
  }): Promise<void>;
206
259
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
207
260
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
@@ -254,24 +307,28 @@ export declare class SubAgentRunManager {
254
307
  * ever started, so it is judged `lost` the same as an internal run (D1).
255
308
  * - `pid` alive under the same identity: genuinely still running. Left alone.
256
309
  * - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
257
- * while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
258
- * over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
259
- * live post-exit path uses.
310
+ * while the daemon was down. `finalizeExternalRun` (spec 042 D1) parses whatever the process
311
+ * actually wrote before applying `terminationReason` — the same sequence the live post-exit
312
+ * path uses, so a reconciled run never loses usage, output, session id, or its verify verdict
313
+ * just because the daemon happened to be down when the run finished.
260
314
  */
261
315
  private reconcileExternalRun;
316
+ /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
317
+ * liveness before assigning a timeout lets a process that finished just before the deadline be
318
+ * settled from its artifacts as a normal completion. */
319
+ private reconcileExternalRunAtDeadline;
320
+ private clearExternalRecoveryTimer;
321
+ private scheduleExternalRecovery;
262
322
  /**
263
- * Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
264
- * deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
265
- * previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
266
- * settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
267
- * so sweeping one this process itself launched is harmless, not just adopted ones.
323
+ * Daily retention GC. A settled run and all runtime-managed artifacts are deleted together once
324
+ * they are at least seven days old. Other files deliberately created by the delegated task are
325
+ * not recursively removed from the artifact directory.
268
326
  */
269
- sweep(now?: number): Promise<void>;
270
- /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
271
327
  private collectGarbageIfExpired;
328
+ collectGarbage(now?: number): Promise<void>;
272
329
  }
273
- /** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
274
- export declare function stopSubAgentSweeper(): void;
330
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
331
+ export declare function stopSubAgentGarbageCollector(): void;
275
332
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
276
333
  export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
277
334
  export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;