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

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 (55) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +154 -132
  3. package/dist/agent/commands.d.ts +6 -0
  4. package/dist/agent/job-manager.js +6 -10
  5. package/dist/agent/progress-formatter.js +3 -3
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.js +2 -1
  8. package/dist/main.js +2 -1
  9. package/dist/memory/extraction.js +0 -1
  10. package/dist/memory/maintenance-gates.d.ts +1 -1
  11. package/dist/memory/maintenance-jobs.js +2 -3
  12. package/dist/memory/metadata.d.ts +0 -15
  13. package/dist/memory/metadata.js +0 -7
  14. package/dist/memory/probation.d.ts +1 -5
  15. package/dist/memory/probation.js +2 -6
  16. package/dist/models/auth-cli.d.ts +1 -1
  17. package/dist/models/auth-cli.js +3 -2
  18. package/dist/paths.d.ts +0 -6
  19. package/dist/paths.js +0 -6
  20. package/dist/runtime/app-home.d.ts +32 -0
  21. package/dist/runtime/app-home.js +319 -0
  22. package/dist/runtime/bootstrap.d.ts +1 -67
  23. package/dist/runtime/bootstrap.js +106 -508
  24. package/dist/runtime/delivery.js +1 -1
  25. package/dist/runtime/dingtalk.d.ts +7 -6
  26. package/dist/runtime/dingtalk.js +5 -13
  27. package/dist/runtime/task-wake.d.ts +54 -0
  28. package/dist/runtime/task-wake.js +99 -0
  29. package/dist/shared/wake-claim.d.ts +23 -0
  30. package/dist/shared/wake-claim.js +26 -0
  31. package/dist/subagents/discovery.d.ts +1 -1
  32. package/dist/subagents/discovery.js +5 -0
  33. package/dist/subagents/external/claude-code.js +3 -2
  34. package/dist/subagents/external/harness.js +18 -3
  35. package/dist/subagents/external/run.js +3 -0
  36. package/dist/subagents/runs.js +7 -10
  37. package/dist/tools/memory-manage.js +0 -1
  38. package/dist/tui/app.d.ts +1 -1
  39. package/dist/tui/app.js +3 -2
  40. package/dist/tui/cli.d.ts +1 -1
  41. package/dist/tui/cli.js +1 -1
  42. package/dist/tui/terminal-media-sender.d.ts +1 -1
  43. package/examples/sub-agents/README.md +15 -14
  44. package/examples/sub-agents/builder-hard.md +9 -8
  45. package/examples/sub-agents/builder.md +12 -11
  46. package/examples/sub-agents/documenter.md +11 -12
  47. package/examples/sub-agents/explorer.md +16 -13
  48. package/examples/sub-agents/git-committer.md +17 -16
  49. package/examples/sub-agents/log-sifter.md +19 -16
  50. package/examples/sub-agents/planner.md +17 -17
  51. package/examples/sub-agents/reviewer.md +13 -21
  52. package/examples/sub-agents/scout.md +5 -4
  53. package/examples/sub-agents/verifier.md +8 -12
  54. package/examples/sub-agents/worker.md +7 -6
  55. package/package.json +1 -1
@@ -128,7 +128,7 @@ class ChannelDeliveryController {
128
128
  if (this.progressStartedAt === 0) {
129
129
  this.progressStartedAt = Date.now();
130
130
  }
131
- if (text.startsWith("▶ ")) {
131
+ if (text.startsWith("➜ ")) {
132
132
  this.toolCallCount++;
133
133
  }
134
134
  if (this.progressSegments.length > 0) {
@@ -1,3 +1,4 @@
1
+ import { type RuntimeCommandName } from "../agent/commands.js";
1
2
  import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
2
3
  import type { ChannelObservation } from "./channel-index.js";
3
4
  export type BusyMessageMode = "steer" | "followUp";
@@ -81,12 +82,12 @@ export interface DingTalkHandler {
81
82
  reserveEvent?(event: DingTalkEvent): void;
82
83
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
83
84
  handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
84
- handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
85
- handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
86
- handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
87
- handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
88
- handleContextCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
89
- handleSubagentsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
85
+ /**
86
+ * Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
87
+ * text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
88
+ * switch — both used to hand-copy the same six-case table.
89
+ */
90
+ runRuntimeCommand(event: DingTalkEvent, name: RuntimeCommandName, args: string): Promise<string>;
90
91
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
91
92
  }
92
93
  export declare class DingTalkBot implements MediaSender {
@@ -11,7 +11,7 @@ import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp } from "../agent/commands.js";
14
+ import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
16
  import { errorMessage } from "../shared/text-utils.js";
17
17
  import { isRecord } from "../shared/type-guards.js";
@@ -1094,23 +1094,15 @@ export class DingTalkBot {
1094
1094
  return;
1095
1095
  }
1096
1096
  case "events":
1097
- await this.handler.handleEventsCommand(event, this, builtInCommand.args);
1098
- return;
1099
1097
  case "tasks":
1100
- await this.handler.handleTasksCommand(event, this, builtInCommand.args);
1101
- return;
1102
1098
  case "status":
1103
- await this.handler.handleStatusCommand(event, this);
1104
- return;
1105
1099
  case "usage":
1106
- await this.handler.handleUsageCommand(event, this, builtInCommand.args);
1107
- return;
1108
1100
  case "context":
1109
- await this.handler.handleContextCommand(event, this, builtInCommand.args);
1110
- return;
1111
- case "subagents":
1112
- await this.handler.handleSubagentsCommand(event, this, builtInCommand.args);
1101
+ case "subagents": {
1102
+ const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
1103
+ await this.sendPlain(channelId, response);
1113
1104
  return;
1105
+ }
1114
1106
  }
1115
1107
  }
1116
1108
  // Session commands (/model, /new, …) and unknown slash commands cannot
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Verifying and claiming a background job's or delegation run's completion wake before it may
3
+ * activate a task parked with `waitingFor` (spec 040, D7/T9). Split out of `bootstrap.ts`: these
4
+ * are pure functions over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
+ * `createRuntimeContext`'s closures.
6
+ */
7
+ import { type JobSnapshot } from "../agent/job-manager.js";
8
+ import type { Executor } from "../executor.js";
9
+ import { type RunRecord } from "../subagents/runs.js";
10
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
11
+ import type { DingTalkEvent } from "./dingtalk.js";
12
+ /**
13
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
15
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
16
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
17
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
18
+ * untrusted stdout.
19
+ */
20
+ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
21
+ /**
22
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
23
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
24
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
25
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
26
+ */
27
+ export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
28
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
29
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
30
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
31
+ export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
32
+ dispatchId: string;
33
+ };
34
+ export interface ClaimedDelegationWake {
35
+ taskId: string;
36
+ generation?: number;
37
+ activated: boolean;
38
+ finish(): Promise<void>;
39
+ rollback(): Promise<void>;
40
+ }
41
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
42
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
43
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
44
+ export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
45
+ export interface ClaimedJobWake {
46
+ taskId: string;
47
+ generation?: number;
48
+ activated: boolean;
49
+ finish(): Promise<void>;
50
+ }
51
+ /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
52
+ * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
53
+ * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
54
+ export declare function claimVerifiedJobWake(event: DingTalkEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Verifying and claiming a background job's or delegation run's completion wake before it may
3
+ * activate a task parked with `waitingFor` (spec 040, D7/T9). Split out of `bootstrap.ts`: these
4
+ * are pure functions over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
+ * `createRuntimeContext`'s closures.
6
+ */
7
+ import { getChannelJobManager } from "../agent/job-manager.js";
8
+ import { getSubAgentRunManager } from "../subagents/runs.js";
9
+ import { activateWaitingTaskAndClaimAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
10
+ import { getChannelDir } from "./channel-paths.js";
11
+ /**
12
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
13
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
14
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
15
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
16
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
17
+ * untrusted stdout.
18
+ */
19
+ export function isVerifiedJobWake(jobs, jobId, taskId) {
20
+ const job = jobs.find((candidate) => candidate.id === jobId);
21
+ return job !== undefined && job.status !== "running" && job.taskId === taskId;
22
+ }
23
+ /**
24
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
25
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
26
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
27
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
28
+ */
29
+ export function isVerifiedDelegationWake(record, taskId) {
30
+ return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
31
+ }
32
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
33
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
34
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
35
+ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
36
+ const wake = event.internalWake;
37
+ return (wake?.kind === kind &&
38
+ wake.resourceId === resourceId &&
39
+ wake.taskId === taskId &&
40
+ typeof event.dispatchId === "string" &&
41
+ wake.dispatchId === event.dispatchId);
42
+ }
43
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
44
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
45
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
46
+ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
47
+ const wake = event.internalWake;
48
+ if (wake?.kind !== "subagent")
49
+ return undefined;
50
+ const runManager = getSubAgentRunManager(event.channelId);
51
+ const record = runManager.get(wake.resourceId);
52
+ if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
53
+ !isVerifiedDelegationWake(record, wake.taskId) ||
54
+ !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
55
+ return undefined;
56
+ }
57
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
58
+ const handoff = {
59
+ kind: "subagent",
60
+ resourceId: wake.resourceId,
61
+ dispatchId: event.dispatchId,
62
+ };
63
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "external-signal", new Date(), hooks, handoff);
64
+ return {
65
+ taskId: wake.taskId,
66
+ generation: activated?.generation,
67
+ activated: activated !== undefined,
68
+ finish: async () => {
69
+ await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
70
+ await finishWakeTaskActivation(channelDir, wake.taskId, handoff);
71
+ },
72
+ rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
73
+ };
74
+ }
75
+ /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
76
+ * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
77
+ * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
78
+ export async function claimVerifiedJobWake(event, workspaceDir, executor, hooks) {
79
+ const wake = event.internalWake;
80
+ if (wake?.kind !== "job")
81
+ return undefined;
82
+ const jobManager = getChannelJobManager(event.channelId, executor);
83
+ const jobs = await jobManager.list();
84
+ if (!isTrustedInternalWake(event, "job", wake.resourceId, wake.taskId) ||
85
+ !isVerifiedJobWake(jobs, wake.resourceId, wake.taskId) ||
86
+ !(await jobManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
87
+ return undefined;
88
+ }
89
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
90
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "job", new Date(), hooks);
91
+ return {
92
+ taskId: wake.taskId,
93
+ generation: activated?.generation,
94
+ activated: activated !== undefined,
95
+ finish: async () => {
96
+ await jobManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
97
+ },
98
+ };
99
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The two-phase "claim, then finish" decision shared by `job-manager.ts` and `subagents/runs.ts`
3
+ * for reserving a completion wake exactly once (spec 040, D7/T9). Both managers persist a
4
+ * `RunRecord`/`JobRecord` differently and gate eligibility on a different terminal condition
5
+ * (job: `status !== "running"`; run: `settledAt` set), so only the claim/consume decision on the
6
+ * two shared fields is factored out here — not the queue, the persistence, or the eligibility check.
7
+ */
8
+ export interface WakeClaimFields {
9
+ wakeClaimDispatchId?: string;
10
+ wakeConsumedAt?: number;
11
+ }
12
+ /**
13
+ * Reserve `dispatchId` as the claim on `fields`, if `eligible` (the caller's terminal/taskId/
14
+ * dispatch-id-match check) holds and no conflicting claim or consumption already exists. Mutates
15
+ * `fields` in place and returns whether the claim was taken; the caller persists the result and
16
+ * rolls the mutation back on a failed write.
17
+ */
18
+ export declare function beginWakeClaim(fields: WakeClaimFields, eligible: boolean, dispatchId: string): boolean;
19
+ /**
20
+ * Mark a previously claimed wake consumed, if `dispatchId` matches the outstanding claim and it
21
+ * has not already been consumed. Mutates `fields` in place and returns whether it changed.
22
+ */
23
+ export declare function finishWakeClaim(fields: WakeClaimFields, dispatchId: string): boolean;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Reserve `dispatchId` as the claim on `fields`, if `eligible` (the caller's terminal/taskId/
3
+ * dispatch-id-match check) holds and no conflicting claim or consumption already exists. Mutates
4
+ * `fields` in place and returns whether the claim was taken; the caller persists the result and
5
+ * rolls the mutation back on a failed write.
6
+ */
7
+ export function beginWakeClaim(fields, eligible, dispatchId) {
8
+ if (!eligible ||
9
+ fields.wakeConsumedAt !== undefined ||
10
+ (fields.wakeClaimDispatchId !== undefined && fields.wakeClaimDispatchId !== dispatchId)) {
11
+ return false;
12
+ }
13
+ fields.wakeClaimDispatchId = dispatchId;
14
+ return true;
15
+ }
16
+ /**
17
+ * Mark a previously claimed wake consumed, if `dispatchId` matches the outstanding claim and it
18
+ * has not already been consumed. Mutates `fields` in place and returns whether it changed.
19
+ */
20
+ export function finishWakeClaim(fields, dispatchId) {
21
+ if (fields.wakeClaimDispatchId !== dispatchId || fields.wakeConsumedAt !== undefined) {
22
+ return false;
23
+ }
24
+ fields.wakeConsumedAt = Date.now();
25
+ return true;
26
+ }
@@ -85,7 +85,7 @@ export interface SubAgentConfig {
85
85
  /** External only: the raw, unvalidated command line. Tokenized by the harness at invocation
86
86
  * time (D4), never by discovery — discovery only checks that it is non-empty. */
87
87
  command?: string;
88
- /** External only: run `command` through `/bin/sh -lc` instead of argv-direct spawn (D4). */
88
+ /** exec harness only: run `command` through `/bin/sh -lc` instead of argv-direct spawn (D4). */
89
89
  shell?: boolean;
90
90
  /** External only: env vars appended to (and overriding) the inherited environment (D8.2). */
91
91
  env?: Record<string, string>;
@@ -451,6 +451,11 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
451
451
  const shell = parseBooleanField(frontmatter.shell, "shell");
452
452
  if (shell.error)
453
453
  return { warning: `${entryName}: ${shell.error}` };
454
+ if (shell.value && harness.value !== "exec") {
455
+ return {
456
+ warning: `${entryName}: "shell: true" is only supported with harness: exec; structured harnesses must assemble their own argv`,
457
+ };
458
+ }
454
459
  const env = parseEnvMap(frontmatter.env);
455
460
  if (env.error)
456
461
  return { warning: `${entryName}: ${env.error}` };
@@ -37,8 +37,6 @@ export const claudeCodeHarness = {
37
37
  }
38
38
  const [executable, ...rest] = input.argv;
39
39
  const existing = detectExistingFlags(rest);
40
- // D4's addendum table lists no auto-appended effort flag for claude-code — only $EFFORT
41
- // expansion for a role author whose wrapper accepts one.
42
40
  const effort = toClaudeEffort(input.thinkingLevel);
43
41
  const { argv: expandedRest, used } = expandPlaceholders(rest, {
44
42
  $MODEL: input.model,
@@ -50,6 +48,9 @@ export const claudeCodeHarness = {
50
48
  if (!existing.model && input.model && !used.has("$MODEL")) {
51
49
  args.push("--model", input.model);
52
50
  }
51
+ if (!existing.effort && effort && !used.has("$EFFORT")) {
52
+ args.push("--effort", effort);
53
+ }
53
54
  if (!used.has("$SYSTEM_PROMPT_FILE")) {
54
55
  args.push("--append-system-prompt-file", input.systemPromptFile);
55
56
  }
@@ -33,7 +33,8 @@ export function classifyExternalOutcome(harnessId, outcome) {
33
33
  }
34
34
  const MODEL_FLAG_PATTERN = /^(--model|-m)$/;
35
35
  const EFFORT_FLAG_PATTERN = /^(--effort|--thinking)$/;
36
- const CODEX_EFFORT_FLAG_PATTERN = /^-c$/;
36
+ const CODEX_CONFIG_FLAG_PATTERN = /^(-c|--config)$/;
37
+ const CODEX_MODEL_VALUE_PREFIX = "model=";
37
38
  const CODEX_EFFORT_VALUE_PREFIX = "model_reasoning_effort=";
38
39
  /** Which flags the user's own `command` already spells out, so a harness never injects a duplicate (D4). */
39
40
  export function detectExistingFlags(argv) {
@@ -45,10 +46,24 @@ export function detectExistingFlags(argv) {
45
46
  model = true;
46
47
  if (EFFORT_FLAG_PATTERN.test(token))
47
48
  effort = true;
48
- if (CODEX_EFFORT_FLAG_PATTERN.test(token) && argv[i + 1]?.startsWith(CODEX_EFFORT_VALUE_PREFIX))
49
- effort = true;
49
+ if (CODEX_CONFIG_FLAG_PATTERN.test(token)) {
50
+ const value = argv[i + 1];
51
+ if (value?.startsWith(CODEX_MODEL_VALUE_PREFIX))
52
+ model = true;
53
+ if (value?.startsWith(CODEX_EFFORT_VALUE_PREFIX))
54
+ effort = true;
55
+ }
50
56
  if (token.startsWith("--model=") || token.startsWith("-m="))
51
57
  model = true;
58
+ if (token.startsWith("--effort=") || token.startsWith("--thinking="))
59
+ effort = true;
60
+ if (token.startsWith("-c=") || token.startsWith("--config=")) {
61
+ const value = token.slice(token.indexOf("=") + 1);
62
+ if (value.startsWith(CODEX_MODEL_VALUE_PREFIX))
63
+ model = true;
64
+ if (value.startsWith(CODEX_EFFORT_VALUE_PREFIX))
65
+ effort = true;
66
+ }
52
67
  }
53
68
  return { model, effort };
54
69
  }
@@ -29,6 +29,9 @@ export async function launchExternalRun(input) {
29
29
  if (!harness) {
30
30
  throw new Error(`Unknown external harness "${input.harness}".`);
31
31
  }
32
+ if (input.shell && harness.id !== "exec") {
33
+ throw new Error(`External harness "${harness.id}" cannot use shell mode because it would bypass protocol argv assembly. Use a wrapper script as command, or use harness: exec.`);
34
+ }
32
35
  // `tool.ts` already creates the artifact dir for a fresh run; `follow_up` (subagent-manage.ts)
33
36
  // mints a new runId/artifactDir on the spot, so this is the one place that must be reliable
34
37
  // either way.
@@ -7,6 +7,7 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
7
7
  import { createSerialQueue } from "../shared/serial-queue.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
+ import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
10
11
  import { classifyExternalOutcome } from "./external/harness.js";
11
12
  import { getExternalHarness } from "./external/registry.js";
12
13
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
@@ -264,16 +265,13 @@ export class SubAgentRunManager {
264
265
  async beginWakeConsumption(runId, taskId, dispatchId) {
265
266
  return this.queue.run(runId, async () => {
266
267
  const record = this.runs.get(runId);
267
- const expected = `subagent:${record?.channelId}:${runId}:done`;
268
- if (!record?.settledAt ||
269
- record.taskId !== taskId ||
270
- dispatchId !== expected ||
271
- record.wakeConsumedAt ||
272
- (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
268
+ if (!record)
273
269
  return false;
274
- }
270
+ const expected = `subagent:${record.channelId}:${runId}:done`;
271
+ const eligible = record.settledAt !== undefined && record.taskId === taskId && dispatchId === expected;
275
272
  const previousClaim = record.wakeClaimDispatchId;
276
- record.wakeClaimDispatchId = dispatchId;
273
+ if (!beginWakeClaim(record, eligible, dispatchId))
274
+ return false;
277
275
  try {
278
276
  await this.persist(record, true);
279
277
  }
@@ -287,9 +285,8 @@ export class SubAgentRunManager {
287
285
  async finishWakeConsumption(runId, dispatchId) {
288
286
  await this.queue.run(runId, async () => {
289
287
  const record = this.runs.get(runId);
290
- if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
288
+ if (!record || !finishWakeClaim(record, dispatchId))
291
289
  return;
292
- record.wakeConsumedAt = Date.now();
293
290
  try {
294
291
  await this.persist(record, true);
295
292
  }
@@ -96,7 +96,6 @@ export function createMemoryManageTool(options) {
96
96
  metadata: {
97
97
  kind: normalizeMemoryKind(kind),
98
98
  sourceType: "user",
99
- trust: "explicit",
100
99
  probationUntil: null,
101
100
  },
102
101
  },
package/dist/tui/app.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
2
2
  export interface TuiAppOptions {
3
3
  channel?: string;
4
4
  /** One-shot, non-interactive run: process a single prompt then exit. */
package/dist/tui/app.js CHANGED
@@ -12,7 +12,8 @@ import { getOrCreateRunner } from "../agent/index.js";
12
12
  import { resetRunner } from "../agent/runner-factory.js";
13
13
  import * as log from "../log.js";
14
14
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
15
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
15
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
16
+ import { prepareAppServices } from "../runtime/bootstrap.js";
16
17
  import { ensureChannelDir } from "../runtime/channel-paths.js";
17
18
  import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
18
19
  import { handleEventsCommand } from "../runtime/event-commands.js";
@@ -70,7 +71,7 @@ export async function runTuiApp(options) {
70
71
  // Transport-neutral init. Unlike the DingTalk path, the TUI ignores
71
72
  // channelTemplateCreated (it needs no channel.json) and shares app services
72
73
  // (settings, diagnostics) with bootstrap via prepareAppServices.
73
- printBootstrapSummary(bootstrapAppHome(paths, io), io, paths);
74
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
74
75
  const { settingsManager } = prepareAppServices(paths);
75
76
  log.configureLogging(settingsManager.getLoggingSettings());
76
77
  log.logStartup(paths.workspaceDir);
package/dist/tui/cli.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * `pipiclaw tui` CLI: argument parsing and entry. Parsing is a pure function
3
3
  * (`parseTuiArgs`) so it can be unit-tested; `runTui` wires it to `runTuiApp`.
4
4
  */
5
- import { type BootstrapIO } from "../runtime/bootstrap.js";
5
+ import { type BootstrapIO } from "../runtime/app-home.js";
6
6
  export type ParsedTui = {
7
7
  kind: "run";
8
8
  channel?: string;
package/dist/tui/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * `pipiclaw tui` CLI: argument parsing and entry. Parsing is a pure function
3
3
  * (`parseTuiArgs`) so it can be unit-tested; `runTui` wires it to `runTuiApp`.
4
4
  */
5
- import { BootstrapExitError, readCliVersion } from "../runtime/bootstrap.js";
5
+ import { BootstrapExitError, readCliVersion } from "../runtime/app-home.js";
6
6
  import { runTuiApp } from "./app.js";
7
7
  /** Parse `pipiclaw tui` arguments (everything after the `tui` subcommand). */
8
8
  export function parseTuiArgs(args) {
@@ -1,4 +1,4 @@
1
- import type { BootstrapIO } from "../runtime/bootstrap.js";
1
+ import type { BootstrapIO } from "../runtime/app-home.js";
2
2
  import type { MediaSender } from "../runtime/channel-context.js";
3
3
  /**
4
4
  * Terminal implementation of the `MediaSender` port. There is no chat surface to
@@ -39,29 +39,30 @@ planner(需求 / 方案 / 验收 / 拆解)
39
39
  → builder(代码 + 单元测试) ← 卡住时换 builder-hard
40
40
  → reviewer(实现评审)
41
41
  → verifier(实际运行取证)
42
- → documenter(文档 / 变更记录 / 交付,随任务顺带提交)
42
+ → documenter(文档 / 变更记录)
43
+ → git-committer(用户明确要求时提交)
43
44
  ```
44
45
 
45
46
  reviewer 发现的问题回流给产出角色;verifier 失败回流给 builder,不在验证环节就地修复。闭环之外:worker 承接通用多步分析与产出,scout 只做单点事实查询。
46
47
 
47
48
  | 角色 | harness | `mutates` | `thinkingLevel` | 用途 |
48
49
  |---|---|---|---|---|
49
- | `planner` | claude-code (opus) | `write` | high | 需求收敛、方案设计、验收定义、任务拆解 |
50
+ | `planner` | claude-code (opus) | `read` | high | 只读需求收敛、方案设计、验收定义、任务拆解 |
50
51
  | `builder` | claude-code (sonnet) | `write` | medium | 边界清晰、验收已定义的实现 + 单元测试 |
51
52
  | `builder-hard` | claude-code (opus) | `write` | xhigh | builder 已失败、根因难定位或多契约耦合的实现 |
52
- | `reviewer` | codex-cli | `write` | high | 与产出者分离的方案 / 代码 / 文档挑错,并落盘评审报告 |
53
- | `verifier` | codex-cli(无沙箱) | `write` | medium | 实际运行系统、复现、冒烟、回归、取证 |
53
+ | `reviewer` | codex-cli(只读沙箱) | `read` | high | 与产出者分离的方案 / 代码 / 文档挑错,也可承担只读 `purpose=verify` |
54
+ | `verifier` | codex-cli(工作区写沙箱) | `write` | medium | 实际运行系统、复现、冒烟、回归、取证 |
54
55
  | `scout` | codex-cli(只读沙箱) | `read` | low | 大仓库里的单点事实查询 |
55
- | `worker` | codex-cli(无沙箱) | `write` | medium | 闭环外的数据对比、指标计算、批量处理、专项报告 |
56
- | `documenter` | codex-cli(无沙箱) | `write` | medium | 文档、变更记录,随文档任务顺带 commit 与最终交付;独立提交任务用 `git-committer` |
56
+ | `worker` | codex-cli(工作区写沙箱) | `write` | medium | 闭环外的数据对比、指标计算、批量处理、专项报告 |
57
+ | `documenter` | codex-cli(工作区写沙箱) | `write` | medium | 文档、变更记录和迁移说明;提交统一用 `git-committer` |
57
58
 
58
- `scout` 用 `--sandbox read-only` 启动 codex,因此它的 `mutates: read` 是被目标 CLI 真正强制的,而不只是一个声明——这也是它不参与工作区写锁、可以与 builder 并行的原因。
59
+ `planner` 用 Claude 的 `--permission-mode plan`,`reviewer` / `scout` 用 Codex 的 `--sandbox read-only`;三者的 `mutates: read` 都有目标 CLI 的权限模式支撑,而不只是提示词声明。它们不占工作区写锁,但评审仍应针对稳定的 diff / commit,不要一边让 builder 改同一工作树、一边评审移动中的目标。
59
60
 
60
- `reviewer` 需要落盘评审报告,因此用 `--sandbox workspace-write` 并如实声明 `mutates: write`:它的正文约束「只写报告、不改被评对象」,但那是提示词纪律而非沙箱边界。代价有两处——它会取工作区写锁(不能与 builder / verifier 并发指向同一棵工作树,并行评审请先 `git worktree add`),并且不能承担 `purpose=verify`。
61
+ `reviewer` 的完整输出由 runtime 自动保存在 run 的 `output.md`,无需为了“落盘报告”给它工作区写权限。它可以承担 `purpose=verify`;runtime 会追加验收协议并检查工作区 subject 未变化。不过外部 attestation 仍是 `advisory`,而且只读沙箱会阻止产生工作区构建产物的测试,主代理需要按风险补充抽查或另派 verifier。
61
62
 
62
- `purpose=verify` 只接受 `mutates: read` 的外部角色,本目录里没有这样的验收角色(`scout` 的定位是单点查询,不适合终验)。需要外部独立验收时,自行复制一份 `reviewer` 改成 `--sandbox read-only` + `mutates: read` 并去掉报告落盘;外部验收的 attestation 强度是 `advisory`,主代理仍需按风险抽查。
63
+ `verifier`、`worker`、`documenter` 使用 `--sandbox workspace-write`:足以在 checkout 和系统临时目录中生成测试或文档产物,同时不授予任意宿主文件访问。模板不让这些角色操作 Git 历史或外部系统;如任务确实需要网络、额外可写目录或更高权限,请复制角色后按目标 CLI 的能力最小化放宽,而不是把通用模板整体改成无沙箱。
63
64
 
64
- `documenter`、`verifier`、`worker` 用 `--sandbox danger-full-access --ask-for-approval never`,即完全不沙箱化,而不是 `workspace-write`。原因:Codex 的 `workspace-write` 沙箱把 `.git/` 强制设为只读(这是 Codex 自身的安全策略,与 pipiclaw 无关),`git add` 需要创建 `.git/index.lock` 会直接失败,`git commit` 还需要写 `objects`、`refs`、`logs`。三者的正文都把「任务明确授权时执行 git commit / push」列为职责的一部分,`workspace-write` 会让这个职责始终不可用,所以只能退到 `danger-full-access`;这意味着目标 CLI 对文件系统和网络完全不设限,唯一的边界回到正文纪律和派发时给出的授权范围。`reviewer` 正文明确「不改配置、依赖和 git 历史」,从不需要提交,因此仍用 `--sandbox workspace-write`,不做这个放宽。
65
+ `builder` / `builder-hard` 仍用 Claude 的 `--dangerously-skip-permissions`,因为它们需要非交互地完成实现;这是本目录权限最高的默认配置。务必在可信 checkout、最小权限宿主账号中使用。角色文件只声明 `model` 和 `thinkingLevel`,具体的 `--model` / `--effort` 参数由 claude-code harness 自动拼接,不应重复写进 `command`。
65
66
 
66
67
  ## 使用原则
67
68
 
@@ -72,15 +73,15 @@ reviewer 发现的问题回流给产出角色;verifier 失败回流给 builder
72
73
  - 内置角色的 `tools`、上下文模式和四个数值预算在模板中显式配置,方便审查和按成本调整。这四个数值只在 frontmatter 里精确设置——调用时主代理只能选 `effort` 的 quick/standard/deep 三档,传了就整组替换这里的数值。
73
74
  - `tools` 只是工具白名单,不等同于只读沙箱。拥有 `bash` 的内置角色仍须遵守正文和应用级 `security.json` 的限制。
74
75
  - 外部角色**没有** `tools` 字段(写了会被驳回)。外部进程不受 pipiclaw 的命令与路径守卫约束,唯一的强边界是你在 `command` 里写下的目标 CLI sandbox flag。
75
- - `git-committer` 和 `documenter` 只有在任务明确转述用户要求 push 时才能推送;创建了 commit 不代表自动获得 push 授权。
76
- - `documenter` 和 `git-committer` 的提交职责按任务性质分:任务同时要求文档/变更记录与提交时派 `documenter`,commit 是文档交付的收尾;与文档无关的独立提交任务派 `git-committer`。
76
+ - 所有 Git 提交统一交给 `git-committer`;它只有在任务明确转述用户要求 push 时才可推送。创建 commit 不会自动获得 push 授权。
77
77
 
78
78
  Pipiclaw 只加载工作区 `sub-agents/` 中实际存在且有效的 Markdown 文件。空目录是合法配置;没有合适的预定义角色时仍可使用 inline `systemPrompt`。`purpose: verify` 的验收约束由 runtime 执行,不要求配置文件必须名为 `verifier`。
79
79
 
80
80
  ## 需要按本机调整的地方
81
81
 
82
82
  - **`command` 用的是裸命令**(`claude` / `codex`),它们必须在 pipiclaw 进程的 `PATH` 上。如果你本机用的是包装脚本(换 base URL、换额度账号、注入环境变量),把 `command` 换成那个脚本即可——pipiclaw 只做 shell 词法分词,不解释命令内容。找不到可执行文件时角色不会消失,而是标为 `unavailable` 并在调用时给出安装提示。
83
- - **`model` 原样透传给目标 CLI,pipiclaw 不校验**。claude 角色用了 `opus` / `sonnet`;codex 角色**没有写 `model`**,交给 CLI 自身的默认配置——请按你的账号可用模型自行填写。
84
- - **`--dangerously-skip-permissions`** 是 claude-code 自身的权限跳过标记,pipiclaw 不解释、不校验,原样传给目标 CLI。这样写是因为 pipiclaw 本身不沙箱化外部进程(见 [../../docs/sub-agents.md](../../docs/sub-agents.md) 的「授权与安全边界」一节)。如果不接受这个权衡,改成该 CLI 自己的确认模式或只读 flag,或者只用 `mutates: read` 的角色。
83
+ - **`model` 原样透传给目标 CLI,pipiclaw 不校验**。Claude 角色用了 `opus` / `sonnet`;Codex 角色**没有写 `model`**,交给 CLI 自身的默认配置——请按你的账号可用模型自行填写。
84
+ - **目标 CLI 参数会变化**。模板按当前 Claude Code / Codex CLI 维护;升级 CLI 后先用 `claude --help`、`codex exec --help` 核对命令。Pipiclaw 只分词和追加协议参数,不会替你校验 flag 是否仍受支持。
85
+ - **`--dangerously-skip-permissions`** 是 Claude Code 自身的权限跳过标记,Pipiclaw 原样传入。若不接受这个边界,只使用只读角色,或为写角色换成你已验证可在非交互模式工作的更严格权限配置。
85
86
  - **`maxWallTimeSec` 是墙钟上限**,超时会杀进程组但仍解析并回传已产生的输出。按仓库规模和任务量级调整,不要把示例值当成固定答案。
86
87
  - 第三种 harness `exec`(任意脚本,无协议终态)本目录不提供示例:它没有完成事件,`usageKnown` / `costKnown` 恒为 false,且不能承担 `purpose=verify`。需要接入其他 CLI 时再参考 [../../docs/sub-agents.md](../../docs/sub-agents.md)。
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: builder-hard
3
- description: 高强度产品实现者(外部 claude-code,异步,高成本)。用于 builder 已经失败并留下具体证据、根因难以定位,或实现必须同时迁移多个契约的任务;派发时除 builder 任务契约外,还要附上可复现命令、关键输出、历次尝试和已排除方向,它先建立根因证据链再做最小完整修复。不要作为默认实现入口——边界清晰的常规实现用 builder,成本低得多。它会写文件,派发后返回 runId,完成时唤醒本频道;并行实现必须为每个 run 指定不同的 workingDirectory(`git worktree add`)。
3
+ description: >-
4
+ 高强度疑难实现(外部 Claude)。仅用于已有失败证据、根因难定位或需要跨契约迁移的任务;常规编码用 builder。会先建立根因证据再修改工作区,成本高且异步返回。
4
5
  runtime: external
5
6
  harness: claude-code
6
7
  command: claude --dangerously-skip-permissions
@@ -11,21 +12,21 @@ mutates: write
11
12
  maxWallTimeSec: 5400
12
13
  ---
13
14
 
14
- 你是被编排调用的高强度产品实现者,专门接手已经失败过或多契约耦合的任务。你的职责重心与 builder 一致:交付产品代码和单元测试,并按任务同步必要的文档、验证产物或提交。
15
+ 你是高强度疑难实现者,接手已有失败证据、根因不清或多契约耦合的编码任务。你的交付仍然是范围受控的产品改动、回归测试和证据清楚的报告。
15
16
 
16
17
  ## 接手姿势
17
18
 
18
- - 任务里给出的失败证据和已确认约束是既成事实。直接以它们为起点,不要从零重复调查已经排除的方向。
19
- - 先定位根因再改代码。能用一条命令复现就先复现,让现象可观察。禁止靠猜测同时改动多处;每一处改动都要能说清它对应哪条证据。
19
+ - 从任务提供的失败证据、尝试记录和已确认约束开始;先快速核对关键前提,不重复已经有可靠证据排除的方向。
20
+ - 先复现并定位根因,再改代码。让每处改动对应具体证据或契约,不靠同时修改多处来碰运气。
20
21
  - 跨模块改动先搜出全部调用方和契约使用点,一次把受影响处改齐,不要留下半迁移状态。
21
- - 两轮定向实验后仍无法解释现象,就停下来报告:已排除的假设及排除依据、剩余最可能的方向、需要的最小外部信息。不要把整个 run 耗在无方向的试错上。
22
+ - 当现有证据无法继续区分剩余假设时,停止无方向试错,报告已排除项、剩余方向和能解除阻塞的最小信息或实验。
22
23
 
23
24
  ## 工作方式与边界
24
25
 
25
- - 动手前读当前工作目录适用的仓库指令(`CLAUDE.md` / `AGENTS.md` 等)和相关代码,遵循既有风格。完成修复必需的依赖、迁移说明、开发文档或示例可以一并更新,但不要把无关重构混入根因修复。
26
+ - 动手前读当前目录适用的仓库指令和相关代码,遵循既有风格。完成修复必需的依赖、迁移说明或示例可以更新,不混入无关重构。
26
27
  - 先检查工作树状态,不覆盖或回退既有改动。每个修复都映射到验收标准或根因证据,并为修复的缺陷补上「修复前失败、修复后通过」的回归性单元测试。
27
- - git commit / push、部署和外部系统写入只在任务明确授权时执行,并在交接中说明影响。
28
- - 没有人在旁边等你提问。信息不足时显式写出假设并继续;只有继续可能造成破坏性或不可逆后果时才停下来提问。
28
+ - 不 commit、push、切分支、部署或写外部系统;保留可审查的工作树改动,提交交给 git-committer。
29
+ - 信息不足但可以安全推进时,写明假设并继续;缺口会改变对外语义、数据安全或修复方向时,报告阻塞而不猜测。
29
30
 
30
31
  ## 单元验证
31
32