@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.5

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 (126) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -18
  4. package/dist/agent/channel-runner.js +26 -121
  5. package/dist/agent/context-budget.js +1 -1
  6. package/dist/agent/job-manager.d.ts +11 -17
  7. package/dist/agent/job-manager.js +77 -67
  8. package/dist/agent/prompt/builder.js +1 -17
  9. package/dist/agent/prompt/manifest.d.ts +0 -1
  10. package/dist/agent/prompt/manifest.js +2 -2
  11. package/dist/agent/prompt/sections.js +0 -9
  12. package/dist/agent/prompt/types.d.ts +2 -18
  13. package/dist/agent/prompt/types.js +1 -1
  14. package/dist/agent/runner-factory.d.ts +4 -0
  15. package/dist/agent/session-adapter.d.ts +19 -0
  16. package/dist/agent/session-adapter.js +77 -0
  17. package/dist/app-services.d.ts +18 -0
  18. package/dist/app-services.js +43 -0
  19. package/dist/channel/channel-context.d.ts +2 -2
  20. package/dist/channel/channel-context.js +2 -2
  21. package/dist/channel/channel-event.d.ts +3 -3
  22. package/dist/{runtime → events}/events.d.ts +1 -1
  23. package/dist/memory/journal.js +1 -1
  24. package/dist/memory/maintenance-gates.d.ts +0 -3
  25. package/dist/memory/maintenance-gates.js +2 -2
  26. package/dist/memory/maintenance-migration.d.ts +5 -0
  27. package/dist/memory/maintenance-migration.js +91 -0
  28. package/dist/memory/maintenance-state.js +5 -44
  29. package/dist/memory/migrate.js +1 -1
  30. package/dist/memory/reflect-job.d.ts +1 -9
  31. package/dist/memory/reflect-job.js +1 -3
  32. package/dist/memory/reflect.js +1 -1
  33. package/dist/memory/session-corpus.js +1 -1
  34. package/dist/memory/store.js +1 -1
  35. package/dist/models/auth-cli.js +1 -1
  36. package/dist/playbooks/agent-delegation.md +15 -11
  37. package/dist/playbooks/background-jobs.md +1 -1
  38. package/dist/playbooks/runtime-orientation.md +2 -0
  39. package/dist/playbooks/task-loop.md +1 -1
  40. package/dist/runtime/bootstrap.d.ts +5 -15
  41. package/dist/runtime/bootstrap.js +44 -65
  42. package/dist/runtime/delivery.d.ts +1 -2
  43. package/dist/runtime/delivery.js +57 -62
  44. package/dist/runtime/dingtalk.d.ts +15 -8
  45. package/dist/runtime/dingtalk.js +101 -35
  46. package/dist/runtime/subagent-commands.d.ts +2 -1
  47. package/dist/runtime/subagent-commands.js +10 -12
  48. package/dist/runtime/task-wake.d.ts +4 -5
  49. package/dist/runtime/task-wake.js +2 -12
  50. package/dist/security/types.d.ts +7 -0
  51. package/dist/security/types.js +16 -1
  52. package/dist/settings.d.ts +8 -0
  53. package/dist/settings.js +24 -1
  54. package/dist/shared/exact-keys.d.ts +13 -0
  55. package/dist/shared/exact-keys.js +1 -0
  56. package/dist/shared/format.d.ts +20 -0
  57. package/dist/shared/format.js +64 -0
  58. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  59. package/dist/shared/{fs-utils.js → os.js} +8 -0
  60. package/dist/subagents/discovery.d.ts +16 -3
  61. package/dist/subagents/discovery.js +13 -9
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +2 -1
  65. package/dist/subagents/external/run.js +13 -5
  66. package/dist/subagents/external/settlement.js +10 -5
  67. package/dist/subagents/format.d.ts +1 -1
  68. package/dist/subagents/format.js +1 -1
  69. package/dist/subagents/runs.d.ts +13 -12
  70. package/dist/subagents/runs.js +109 -91
  71. package/dist/subagents/tool.d.ts +7 -7
  72. package/dist/subagents/tool.js +11 -11
  73. package/dist/tasks/brief.js +1 -0
  74. package/dist/tools/command-optimizer.js +1 -1
  75. package/dist/tools/config.d.ts +7 -0
  76. package/dist/tools/config.js +16 -1
  77. package/dist/tools/event-manage.d.ts +1 -1
  78. package/dist/tools/event-manage.js +3 -3
  79. package/dist/tools/grep.js +1 -1
  80. package/dist/tools/index.d.ts +4 -0
  81. package/dist/tools/index.js +4 -2
  82. package/dist/tools/job.js +1 -1
  83. package/dist/tools/read.js +1 -1
  84. package/dist/tools/registry.d.ts +3 -3
  85. package/dist/tools/registry.js +18 -56
  86. package/dist/tools/skill.js +1 -1
  87. package/dist/tools/subagent-manage.d.ts +2 -0
  88. package/dist/tools/subagent-manage.js +7 -7
  89. package/dist/tools/subagent-tool-names.d.ts +2 -2
  90. package/dist/tools/subagent-tool-names.js +2 -2
  91. package/dist/tools/task-manage/shared.js +4 -9
  92. package/dist/tools/task-manage/types.d.ts +4 -0
  93. package/dist/tui/app.js +22 -7
  94. package/dist/web/config.js +1 -1
  95. package/examples/sub-agents/README.md +65 -81
  96. package/examples/sub-agents/agents/claude-high.md +23 -0
  97. package/examples/sub-agents/agents/claude-main.md +23 -0
  98. package/examples/sub-agents/agents/codex-flash.md +23 -0
  99. package/examples/sub-agents/agents/codex-high.md +23 -0
  100. package/examples/sub-agents/agents/codex-main.md +23 -0
  101. package/examples/sub-agents/agents/glm-flash.md +23 -0
  102. package/examples/sub-agents/agents/glm-high.md +23 -0
  103. package/package.json +2 -1
  104. package/dist/shared/duration.d.ts +0 -2
  105. package/dist/shared/duration.js +0 -7
  106. package/dist/shared/file-stamp.d.ts +0 -10
  107. package/dist/shared/file-stamp.js +0 -19
  108. package/dist/shared/numeric.d.ts +0 -7
  109. package/dist/shared/numeric.js +0 -19
  110. package/dist/shared/shell-escape.d.ts +0 -5
  111. package/dist/shared/shell-escape.js +0 -7
  112. package/dist/shared/token-estimate.d.ts +0 -1
  113. package/dist/shared/token-estimate.js +0 -19
  114. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  115. /package/dist/{runtime → events}/event-commands.js +0 -0
  116. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  117. /package/dist/{runtime → events}/event-validation.js +0 -0
  118. /package/dist/{runtime → events}/events.js +0 -0
  119. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  120. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  121. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  122. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  123. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  124. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  125. /package/examples/sub-agents/{verifier.md → roles/verifier.md} +0 -0
  126. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -74,9 +74,9 @@ export interface ChannelEvent {
74
74
  /**
75
75
  * Purely a display hint: `"awaited"` marks a synthetic wake a human is actually waiting on (a
76
76
  * delegation or background job finishing), as opposed to an autonomous check-in (task-driver
77
- * polling, a scheduled event) that normally has nothing to say. The runtime uses it to decide
78
- * whether the resulting turn renders progress or stays silent until a final answer — it must
79
- * never gate task activation or any other trust decision; that stays on `internalWake` alone.
77
+ * polling, a scheduled event) that normally has nothing to say. All synthetic wakes now
78
+ * deliver only their result; this metadata does not enable progress cards or gate task
79
+ * activation. Trust decisions stay on `internalWake` alone.
80
80
  */
81
81
  presentation?: "awaited";
82
82
  }
@@ -1,7 +1,7 @@
1
1
  import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
+ import type { DingTalkBot } from "../runtime/dingtalk.js";
3
4
  import type { SecurityConfig } from "../security/types.js";
4
- import type { DingTalkBot } from "./dingtalk.js";
5
5
  export interface EventAction {
6
6
  type: "bash";
7
7
  command: string;
@@ -1,8 +1,8 @@
1
1
  import { mkdir, open, readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { writeFileAtomically } from "../shared/atomic-file.js";
4
- import { isNodeError, readOptionalTextFile } from "../shared/fs-utils.js";
5
4
  import { localDayKey } from "../shared/local-time.js";
5
+ import { isNodeError, readOptionalTextFile } from "../shared/os.js";
6
6
  /**
7
7
  * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
8
8
  * `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
@@ -1,11 +1,8 @@
1
1
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
2
2
  import type { MemoryMaintenanceState } from "./maintenance-state.js";
3
- /** Spec 050, D9: the three v1 jobs collapse to one. */
4
- export type MaintenanceJobKind = "reflect";
5
3
  export interface MaintenanceGateDecision {
6
4
  allowed: boolean;
7
5
  skipReason?: string;
8
- jobKind: MaintenanceJobKind;
9
6
  }
10
7
  export interface ReflectMaterial {
11
8
  hasNewEntry: boolean;
@@ -1,8 +1,8 @@
1
1
  import { parseLocalTime } from "../shared/local-time.js";
2
2
  function deny(skipReason) {
3
- return { allowed: false, jobKind: "reflect", skipReason };
3
+ return { allowed: false, skipReason };
4
4
  }
5
- const allow = { allowed: true, jobKind: "reflect" };
5
+ const allow = { allowed: true };
6
6
  function parseTime(value) {
7
7
  if (!value) {
8
8
  return null;
@@ -0,0 +1,5 @@
1
+ /** Upgrade before starting channel readers/writers. Kept through the 0.9.3 upgrade window.
2
+ * Canonical state wins over an obsolete nested copy; old files are removed only after a
3
+ * successful canonical write. Failed I/O aborts startup so no cursor is silently discarded.
4
+ */
5
+ export declare function migrateMemoryMaintenanceStates(appHomeDir: string): Promise<void>;
@@ -0,0 +1,91 @@
1
+ import { readdir, readFile, rmdir, unlink } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { isChannelId } from "../channel/channel-paths.js";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { isRecord } from "../shared/type-guards.js";
6
+ import { getMemoryMaintenanceStateDir, getMemoryMaintenanceStatePath } from "./maintenance-state.js";
7
+ /** Upgrade before starting channel readers/writers. Kept through the 0.9.3 upgrade window.
8
+ * Canonical state wins over an obsolete nested copy; old files are removed only after a
9
+ * successful canonical write. Failed I/O aborts startup so no cursor is silently discarded.
10
+ */
11
+ export async function migrateMemoryMaintenanceStates(appHomeDir) {
12
+ const root = getMemoryMaintenanceStateDir(appHomeDir);
13
+ async function files(dir) {
14
+ const entries = await readdir(dir, { withFileTypes: true });
15
+ const result = [];
16
+ for (const entry of entries) {
17
+ const path = join(dir, entry.name);
18
+ if (entry.isDirectory())
19
+ result.push(...(await files(path)));
20
+ else if (entry.isFile() && entry.name.endsWith(".json"))
21
+ result.push(path);
22
+ }
23
+ return result;
24
+ }
25
+ let paths;
26
+ try {
27
+ paths = await files(root);
28
+ }
29
+ catch (error) {
30
+ if (error.code === "ENOENT")
31
+ return;
32
+ throw error;
33
+ }
34
+ for (const source of paths) {
35
+ let raw;
36
+ try {
37
+ raw = JSON.parse(await readFile(source, "utf8"));
38
+ }
39
+ catch (error) {
40
+ if (error instanceof SyntaxError)
41
+ continue; // normal reader diagnoses corrupt state
42
+ throw error;
43
+ }
44
+ if (!isRecord(raw))
45
+ continue;
46
+ const channelId = typeof raw.channelId === "string" ? raw.channelId : basename(source, ".json");
47
+ if (!isChannelId(channelId))
48
+ continue;
49
+ const target = getMemoryMaintenanceStatePath(appHomeDir, channelId);
50
+ if (source !== target && source !== join(root, `${channelId}.json`))
51
+ continue;
52
+ let canonicalExists = false;
53
+ if (source !== target) {
54
+ try {
55
+ const existing = JSON.parse(await readFile(target, "utf8"));
56
+ if (!isRecord(existing) || (existing.channelId !== undefined && existing.channelId !== channelId)) {
57
+ throw new Error(`Invalid memory maintenance state at ${target}; repair it before restarting. Legacy state retained at ${source}.`);
58
+ }
59
+ canonicalExists = true;
60
+ }
61
+ catch (error) {
62
+ if (error.code !== "ENOENT")
63
+ throw error;
64
+ }
65
+ }
66
+ const hasOldFields = "lastCheckpointAt" in raw || "lastCheckpointEntryId" in raw;
67
+ if (!canonicalExists && (source !== target || hasOldFields)) {
68
+ for (const [current, old] of [
69
+ ["lastReflectAt", "lastCheckpointAt"],
70
+ ["lastReflectedEntryId", "lastCheckpointEntryId"],
71
+ ]) {
72
+ if (typeof raw[current] !== "string" || !raw[current].trim())
73
+ raw[current] = raw[old];
74
+ delete raw[old];
75
+ }
76
+ await writeFileAtomically(target, `${JSON.stringify({ ...raw, channelId }, null, 2)}\n`);
77
+ }
78
+ if (source !== target) {
79
+ await unlink(source);
80
+ // Empty legacy directories only; never remove unrelated state.
81
+ for (let dir = dirname(source); dir !== root; dir = dirname(dir)) {
82
+ try {
83
+ await rmdir(dir);
84
+ }
85
+ catch {
86
+ break;
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
@@ -1,5 +1,5 @@
1
- import { readFile, rmdir, unlink } from "node:fs/promises";
2
- import { dirname, join } from "node:path";
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
3
  import { getChannelDirName } from "../channel/channel-paths.js";
4
4
  import * as log from "../log.js";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -20,19 +20,6 @@ export function getMemoryMaintenanceStateDir(appHomeDir) {
20
20
  export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
21
21
  return join(getMemoryMaintenanceStateDir(appHomeDir), `${getChannelDirName(channelId)}.json`);
22
22
  }
23
- /**
24
- * Where a pre-escaping runtime put the same channel's state. Only differs for ids containing
25
- * `/`, and only matters until the next write moves the state to its canonical path.
26
- *
27
- * RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`: by
28
- * the stable cut, every still-running group channel with a `/` in its id will have had its state
29
- * folded onto the canonical path at least once, so this fallback read finds nothing.
30
- */
31
- function legacyStatePath(appHomeDir, channelId) {
32
- return getChannelDirName(channelId) === channelId
33
- ? undefined
34
- : join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
35
- }
36
23
  function createDefaultState(channelId) {
37
24
  return { channelId, dirty: false, failureBackoffUntil: null };
38
25
  }
@@ -55,11 +42,8 @@ function normalizeState(channelId, value) {
55
42
  dirty: typeof record.dirty === "boolean" ? record.dirty : false,
56
43
  lastActivityAt: normalizeOptionalString(record.lastActivityAt),
57
44
  eligibleAfter: normalizeOptionalString(record.eligibleAfter),
58
- // v1 states carried the checkpoint job's fields under a different name; fold them into
59
- // the reflect cadence/cursor so an upgrade does not re-run reflect on the channel's whole
60
- // history nor lose its due time.
61
- lastReflectAt: normalizeOptionalString(record.lastReflectAt) ?? normalizeOptionalString(record.lastCheckpointAt),
62
- lastReflectedEntryId: normalizeOptionalString(record.lastReflectedEntryId) ?? normalizeOptionalString(record.lastCheckpointEntryId),
45
+ lastReflectAt: normalizeOptionalString(record.lastReflectAt),
46
+ lastReflectedEntryId: normalizeOptionalString(record.lastReflectedEntryId),
63
47
  failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
64
48
  };
65
49
  }
@@ -71,42 +55,19 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
71
55
  }
72
56
  catch (error) {
73
57
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
74
- const legacy = await readLegacyState(appHomeDir, channelId);
75
- return legacy ?? createDefaultState(channelId);
58
+ return createDefaultState(channelId);
76
59
  }
77
60
  const message = errorMessage(error);
78
61
  log.logWarning(`[${channelId}] Failed to read memory maintenance state; rebuilding defaults`, message);
79
62
  return createDefaultState(channelId);
80
63
  }
81
64
  }
82
- async function readLegacyState(appHomeDir, channelId) {
83
- const path = legacyStatePath(appHomeDir, channelId);
84
- if (!path)
85
- return undefined;
86
- try {
87
- return normalizeState(channelId, JSON.parse(await readFile(path, "utf-8")));
88
- }
89
- catch {
90
- return undefined; // absent or unreadable ⇒ the caller falls back to defaults, as before
91
- }
92
- }
93
65
  export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
94
66
  const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
95
67
  return stateUpdateQueue.run(path, async () => {
96
68
  const current = await readMemoryMaintenanceState(appHomeDir, channelId);
97
69
  const next = normalizeState(channelId, update(current));
98
70
  await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
99
- // The canonical file now holds everything the legacy one did; leaving it would keep a
100
- // stale copy around forever, since reads only fall back when the canonical file is gone.
101
- const legacy = legacyStatePath(appHomeDir, channelId);
102
- if (legacy) {
103
- await unlink(legacy).catch(() => { });
104
- // ...along with the directory the raw id created, which `rmdir` leaves alone if
105
- // another channel's state still lives there. Tidying only; failure changes nothing.
106
- const strayDir = dirname(legacy);
107
- if (strayDir !== getMemoryMaintenanceStateDir(appHomeDir))
108
- await rmdir(strayDir).catch(() => { });
109
- }
110
71
  return next;
111
72
  });
112
73
  }
@@ -2,8 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
3
  import { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
- import { readOptionalTextFile } from "../shared/fs-utils.js";
6
5
  import { localDayKey, parseLocalTime } from "../shared/local-time.js";
6
+ import { readOptionalTextFile } from "../shared/os.js";
7
7
  import { dedupeMemoryName, getChannelMemoryDir, getChannelMemoryIndexPath, getMemoryEntryPath, rebuildMemoryIndex, serializeMemoryEntry, slugifyMemoryName, } from "./store.js";
8
8
  import { hashMemoryContent } from "./tombstones.js";
9
9
  /**
@@ -3,7 +3,6 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
5
  import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
6
- import { type MaintenanceJobKind } from "./maintenance-gates.js";
7
6
  import { runReflect } from "./reflect.js";
8
7
  /**
9
8
  * Spec 050, D7/D9: the scheduler's idle-tick entry point into the reflect pass. Boundary
@@ -28,14 +27,7 @@ export interface ReflectJobInput {
28
27
  sessionEntries: () => SessionEntry[];
29
28
  queue?: ChannelMemoryQueue;
30
29
  }
31
- export interface ReflectJobResult {
32
- jobKind: MaintenanceJobKind;
33
- ran: boolean;
34
- skipped: boolean;
35
- skipReason?: string;
36
- error?: string;
37
- }
38
- export declare function runReflectJob(input: ReflectJobInput): Promise<ReflectJobResult>;
30
+ export declare function runReflectJob(input: ReflectJobInput): Promise<void>;
39
31
  /** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
40
32
  export declare function reviewLogEntryFor(result: Awaited<ReturnType<typeof runReflect>>): {
41
33
  actions?: unknown[];
@@ -45,7 +45,7 @@ export async function runReflectJob(input) {
45
45
  reason: "reflect",
46
46
  skipped: [{ target: "reflect", reason: decision.skipReason }],
47
47
  });
48
- return { jobKind: decision.jobKind, ran: false, skipped: true, skipReason: decision.skipReason };
48
+ return;
49
49
  }
50
50
  const sourceWindow = loadSourceWindow();
51
51
  try {
@@ -71,7 +71,6 @@ export async function runReflectJob(input) {
71
71
  correlationId: sourceWindow.windowId,
72
72
  ...reviewLogEntryFor(result),
73
73
  });
74
- return { jobKind: "reflect", ran: !result.skipped, skipped: result.skipped };
75
74
  }
76
75
  catch (error) {
77
76
  await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
@@ -85,7 +84,6 @@ export async function runReflectJob(input) {
85
84
  reason: "reflect",
86
85
  error: message,
87
86
  });
88
- return { jobKind: "reflect", ran: false, skipped: false, error: message };
89
87
  }
90
88
  });
91
89
  }
@@ -1,7 +1,7 @@
1
1
  import { serializeConversation } from "@earendil-works/pi-coding-agent";
2
- import { readOptionalTextFile } from "../shared/fs-utils.js";
3
2
  import { parseJsonObject } from "../shared/llm-json.js";
4
3
  import { localDayKey } from "../shared/local-time.js";
4
+ import { readOptionalTextFile } from "../shared/os.js";
5
5
  import { clipText } from "../shared/text-utils.js";
6
6
  import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS } from "./index-budget.js";
7
7
  import { appendJournalEntries } from "./journal.js";
@@ -1,6 +1,6 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
- import { isNodeError, readOptionalTextFile } from "../shared/fs-utils.js";
3
+ import { isNodeError, readOptionalTextFile } from "../shared/os.js";
4
4
  import { isRecord } from "../shared/type-guards.js";
5
5
  /**
6
6
  * Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
@@ -2,8 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import { appendFile, mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
- import { readOptionalTextFile } from "../shared/fs-utils.js";
6
5
  import { localDayKey } from "../shared/local-time.js";
6
+ import { readOptionalTextFile } from "../shared/os.js";
7
7
  import { containsSecret } from "./secret-redaction.js";
8
8
  import { hashMemoryContent } from "./tombstones.js";
9
9
  const MEMORY_TYPES = ["user", "feedback", "project", "reference"];
@@ -6,9 +6,9 @@
6
6
  * login is a short, one-shot operation (spec 039 §5.1).
7
7
  */
8
8
  import { createInterface } from "node:readline/promises";
9
+ import { prepareAppServices } from "../app-services.js";
9
10
  import * as log from "../log.js";
10
11
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
11
- import { prepareAppServices } from "../runtime/bootstrap.js";
12
12
  import { ReadlineLoginUi } from "./login-ui.js";
13
13
  import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
14
14
  import { createModelRuntime, formatModelReference } from "./utils.js";
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agent-delegation
3
- description: 判断是否值得委派内部子代理(subagent)或外部 AI Agent,选择角色、交代上下文、并行隔离、等待与续接时。
3
+ description: 判断是否值得委派内部子代理(subagent)或外部 AI Agent,按能力与成本选执行器、交代上下文、并行隔离、等待与续接时。
4
4
  order: 60
5
5
  ---
6
6
 
@@ -10,17 +10,21 @@ order: 60
10
10
 
11
11
  普通临时委派无需 task;需要跨回合保留目标、预算和验收状态才建 task。正式验收用 `purpose: verify` 且必须有现存 `taskId`;普通调查和审查用 `purpose: work`,在 task 文本里写清检查要求即可。
12
12
 
13
- ## 选角色
13
+ ## 选执行器
14
14
 
15
- 优先 `subagent` 调用目录里合适的角色;按 description、light/heavy 工作量、read/write 行为和实际能力选择,不按底层 harness 名字选。内置角色通常同步返回,超过 120 秒自动转异步;外部角色一律异步,转换不是失败。
15
+ 把目录条目的 `description`、runtime、工具/模型、成本、`mutates` 和可用状态当作选择依据;条目正文可能包含部署者设定的岗位或流程约束,不能假定所有目录都按某套命名或档位组织。优先选能以最低背景重建和整合成本满足本轮验收的已配置条目:明确重复工作用低成本能力,常规实现与排查用主力能力,只有确需新判断、专用输入或更强推理时才升级。
16
16
 
17
- 没有合适角色且工具可用时才用 `subagent_inline`。按角色调用只提供本次任务、目录与 purpose/taskId,工具、模型、预算、上下文策略由角色文件决定;inline 才自行提供 systemPrompt、工具和 effort 等控制参数。放宽预算不能代替清晰的任务要求。
17
+ 外部条目不经过 Pipiclaw 的工具守卫,实际权限由条目命令、CLI sandbox、宿主账号与环境决定;任务文本只表达授权范围,不能代替强制边界。声明 `mutates: write` 的委派会取得目录写 lease,同一或父子目录的并行写入必须使用独立 worktree。外部或其他 advisory verifier 的 PASS 仍需按风险核对真实产物、diff 和检查输出。
18
18
 
19
- 角色 unavailable 时先判断主代理或其他可用角色能否以相同验收标准完成,必要时拆成真正独立的小分片;缺少必需能力才说明需要部署者补什么。light/heavy 本身不是能力证明。
19
+ 需要独立判断时(评审、验收、复核别人的结论),**独立性必须写进 task**:给同一份要求和验收口径、指明待检版本与检查入口,并写明「你是检查者,不修实现,不把实现者的总结当作预期行为的来源」。换一个条目不会自动带来独立性。
20
+
21
+ 先使用匹配的已配置条目;目录没有合适条目时,才用 `subagent_inline` 做一次性内置工作并自行提供 systemPrompt、工具和 effort。按条目调用只提供 `task`、`workingDirectory` 和 purpose/taskId,模型、推理档和预算由条目文件决定。放宽预算不能代替清晰要求。内置委派通常同步返回,超过 120 秒自动转异步;外部条目一律异步,转换不是失败。
22
+
23
+ 条目 unavailable 时先判断主代理或其他可用条目能否以相同验收标准完成,必要时拆成真正独立的小分片;缺少必需能力才说明需要部署者补什么。light/heavy 本身不是能力证明。
20
24
 
21
25
  ## 任务指令:执行者看不到本会话
22
26
 
23
- 内置从隔离上下文启动,外部是另一个进程;`context: index` 也只有背景索引,没有本次聊天。每次 `task` 都要自足,角色提示词只提供稳定能力。
27
+ 内置从隔离上下文启动,外部是另一个进程;即使配置注入背景索引,也没有本次聊天的完整语义。每次 `task` 都要自足,不能依赖条目正文替你交代本轮目标、范围或验收。
24
28
 
25
29
  紧凑地交代:**本轮结果 → 已有证据 → 适用要求 → 工作入口与边界 → 交付和验收标准**。来源不确定的假设单独标明;给少量关键路径/符号/复现入口,让执行者自己探索,不先重做一遍它的调查。用户要求应同时交给执行者和验收者。
26
30
 
@@ -36,18 +40,18 @@ order: 60
36
40
 
37
41
  ## 每次决定工作目录与写入边界
38
42
 
39
- 省略 workingDirectory 默认当前频道的 ProjectRoot,角色文件没有默认目录。项目边界启用时显式目录也必须在项目内。
43
+ 省略 workingDirectory 默认当前频道的 ProjectRoot,条目文件没有默认目录。项目边界启用时显式目录也必须在项目内。
40
44
 
41
45
  - 并行写分片各建独立 worktree,并显式传 workingDirectory;用完清理自己创建的 worktree。默认目录不会自动隔离。
42
46
  - runtime 只对声明 `mutates: write` 的委派提供排他写 lease;遇到冲突按错误中的持有者 runId 等待或重选工作目录。
43
47
  - 主代理自己的 write/edit/bash 不受 lease 保护;活跃写委派的工作树不要同时修改。
44
- - 内置 mutates 默认从 write/edit 工具推断,bash 也能写但不会被自动识别;外部 mutates 是声明,不是 sandbox。inline 需要写入时显式声明 write;已配置角色声明有误时由部署者改角色文件,模型不能 write/edit `sub-agents/`,也不要换 bash 绕过。
48
+ - 内置 mutates 默认从 write/edit 工具推断,bash 也能写但不会被自动识别;外部 mutates 是声明,不是 sandbox。inline 需要写入时显式声明 write;已配置条目声明有误时由部署者改条目文件,模型不能 write/edit `sub-agents/`,也不要换 bash 绕过。
45
49
 
46
- 外部 Agent 的权限边界是角色命令、CLI sandbox、宿主账号与环境,它不经过 Pipiclaw 的工具守卫。给它的外部动作范围必须清楚。
50
+ 外部 Agent 的权限边界是条目命令、CLI sandbox、宿主账号与环境,它不经过 Pipiclaw 的工具守卫;放开权限运行的条目只剩宿主账号这一层。给它的外部动作范围必须清楚。
47
51
 
48
52
  ## 返回、等待与恢复
49
53
 
50
- **结果已返回**:读取并检查,不再 park 或等第二次通知。**仍在运行**:记录 runId,完成其他独立工作/派发;只剩等待时结束回合,不轮询、重派或用后台 job/event 包一层等待。
54
+ **结果已返回**:读取并检查,不再 park 或等第二次通知。**仍在运行**:记录 runId,完成其他独立工作/派发;在具备完成唤醒的 DingTalk daemon 中,只剩等待时结束回合,不轮询、重派或用后台 job/event 包一层等待。TUI 不负责外部 run 的完成通知或退出后认领,长跑委派不要依赖它托管。
51
55
 
52
56
  关联 task 的委派从首次派发就带 taskId。**在 task 步骤内**等待时,用 `task_step_end` park 到 `{"kind":"run","id":"<runId>"}`;若提示已结算,读取结果并继续。多个 run 同属任务时,票指向当前真正阻塞下一阶段的 run,醒来再查看其余状态。普通聊天没有 task_step_end。
53
57
 
@@ -61,6 +65,6 @@ daemon 重启后内置 run 判 lost,外部通常继续;外部启动信息尚
61
65
 
62
66
  `subagent_run op=follow_up` 只支持已结束的 claude-code/codex-cli run,产生新的 runId;追加内容只写原契约的变化。目标不变、反馈局部、旧上下文可靠时续接,避免重建背景。换方向、反复沿错误假设尝试、需要独立判断时开新委派。
63
67
 
64
- 内置和 exec 不支持续接,带已有产出重新委派。角色 command/model/shell 改过时续接会拒绝,也应新开。明确阻塞、循环、崩溃、需纠偏或用户要求时才 cancel;耗时长本身不是取消理由。取消不再唤醒,用户 `/stop` 不会连带取消委派。
68
+ 内置和 exec 不支持续接,带已有产出重新委派。条目 command/model/shell 改过时续接会拒绝,也应新开。明确阻塞、循环、崩溃、需纠偏或用户要求时才 cancel;耗时长本身不是取消理由。取消不再唤醒,用户 `/stop` 不会连带取消委派。
65
69
 
66
70
  需要正式 task 验收时,再读 `task-loop.md` 的“独立验收”;证明强度、PASS 失效和返工裁决由那里统一说明。普通审查无需走该协议,但同样要核实证据、达标即停。
@@ -17,7 +17,7 @@ order: 50
17
17
 
18
18
  ## 派发与收尾
19
19
 
20
- 启动后先完成互不依赖的工作或派发;只剩等待时结束回合,不连续 poll 或建回访事件。作业终态会带回退出码、耗时、输出尾部和完整输出路径。
20
+ 启动后先完成互不依赖的工作或派发。在具备完成唤醒的 DingTalk daemon 中,只剩等待时结束回合,不连续 poll 或建回访事件;TUI 没有常驻完成投递,退出前不要依赖它托管待返回的作业。作业终态会带回退出码、耗时、输出尾部和完整输出路径。
21
21
 
22
22
  属于 task 的作业启动时传 `taskId`;**当前是 task 步骤时**用 `task_step_end` park 到 `{"kind":"job","id":"<jobId>"}`。若已结束、票被拒,读取输出并继续,不重跑命令。票过期等恢复问题才读 `task-loop.md` 的“等待与恢复”。
23
23
 
@@ -14,6 +14,8 @@ order: 10
14
14
  - **任务步骤**(`[TASK_STEP:<id>]`,有 `task_step_end`):在独立的 cycle 会话里推进当前契约。没有 `task_create`、`memory_save`、`event_manage`;缺少这些工具是执行边界,不要换文件写入来绕过。
15
15
  - **子代理**:不继承聊天历史;上下文与工作目录由本次委派决定。准备委派时读 `agent-delegation.md` 的“任务指令”。
16
16
 
17
+ DingTalk daemon 是长期宿主,负责 task driver、后台 job/委派完成唤醒和外部 run 重启对账。TUI 适合前台回合,不提供这些常驻保证;不要在 TUI 中建立依赖退出后自动恢复的工作。
18
+
17
19
  ## 已有上下文
18
20
 
19
21
  先用已注入的信息,缺什么再查什么:
@@ -56,7 +56,7 @@ run/job 派发时即带 taskId;先完成独立工作和必要的并行派发
56
56
 
57
57
  signal 事件必须在聊天侧预建为 task.<channelId>.<taskId>.<use> 的 periodic;循环先检查条件,未满足才等待。缺少事件且不能自主继续时 blocked 说明缺什么,不绕过工具限制。
58
58
 
59
- 票自带 runtime 兜底。过期后的 brief 会标明等待来源:先检查真实状态,再继续或换票;同 cycle 第二次过期停止并通知用户。预算任一项耗尽也会停止;这些回执由 runtime 发出,无需再花模型回合解释。用户命令 `/tasks resume <id>` 恢复、`/tasks reply <id> ...` 回答阻塞问题。
59
+ 票自带 runtime 兜底。过期后的 brief 会标明等待来源:先检查真实状态,再继续或换票;同 cycle 第二次过期停止并通知用户。预算任一项耗尽也会停止;回执由 runtime 发出。用户用 `/tasks reply <id> ...` 回答阻塞问题;手工暂停或票过期可直接 `/tasks resume <id>`,`steps`/`rounds`/`usd` 耗尽要同时 `+...` 加码,`wallMin`/`until` 耗尽则先让 Agent 用 `task_update` 调整预算再恢复。
60
60
 
61
61
  ## 外部动作
62
62
 
@@ -1,8 +1,10 @@
1
+ import { type JobRuntime } from "../agent/job-manager.js";
1
2
  import type { AgentRunner } from "../agent/types.js";
2
3
  import type { ChannelEvent } from "../channel/channel-event.js";
3
4
  import { ChannelStore } from "../channel/store.js";
4
5
  import { type Executor } from "../executor.js";
5
6
  import { PipiclawSettingsManager } from "../settings.js";
7
+ import { type SubAgentRuntime } from "../subagents/runs.js";
6
8
  import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
7
9
  import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
8
10
  import { TaskDriver } from "./task-driver.js";
@@ -20,6 +22,8 @@ export interface AppContext {
20
22
  shutdown: () => Promise<void>;
21
23
  }
22
24
  export interface RuntimeContext {
25
+ jobs: JobRuntime;
26
+ runs: SubAgentRuntime;
23
27
  handler: DingTalkHandler;
24
28
  store: ChannelStore;
25
29
  /** Production driver instance, exposed so evals can invoke the real scan path. */
@@ -64,6 +68,7 @@ type TaskDriverLike = TaskDriver | {
64
68
  nudge?(): void;
65
69
  };
66
70
  interface RuntimeContextOptions {
71
+ executor?: Executor;
67
72
  paths: BootstrapPaths;
68
73
  dingtalkConfig: DingTalkConfig;
69
74
  createBot?: (handler: DingTalkHandler, config: DingTalkConfig) => DingTalkBot;
@@ -101,20 +106,5 @@ interface RuntimeContextOptions {
101
106
  export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
102
107
  bot: DingTalkBot;
103
108
  }>;
104
- /**
105
- * Transport-neutral app services shared by the DingTalk runtime and the terminal
106
- * TUI: loads settings (surfacing load errors) and reports tool/security config
107
- * diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
108
- * DingTalk credentials.
109
- *
110
- * Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
111
- * position (after `loadConfig`, before `logStartup`) so its behavior is
112
- * unchanged. Logging configuration is intentionally left to each caller
113
- * (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
114
- * existing "diagnostics logged with default logging config" ordering.
115
- */
116
- export declare function prepareAppServices(paths?: BootstrapPaths): {
117
- settingsManager: PipiclawSettingsManager;
118
- };
119
109
  export declare function bootstrap(argv: string[], options?: BootstrapOptions): Promise<AppContext>;
120
110
  export {};