@oyasmi/pipiclaw 0.9.0-beta.5 → 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 (76) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +8 -0
  3. package/dist/agent/channel-runner.js +154 -132
  4. package/dist/agent/commands.d.ts +6 -0
  5. package/dist/agent/job-manager.js +6 -10
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +2 -1
  9. package/dist/main.js +2 -1
  10. package/dist/memory/extraction.js +0 -1
  11. package/dist/memory/maintenance-gates.d.ts +1 -1
  12. package/dist/memory/maintenance-jobs.js +2 -3
  13. package/dist/memory/metadata.d.ts +0 -15
  14. package/dist/memory/metadata.js +0 -7
  15. package/dist/memory/probation.d.ts +1 -5
  16. package/dist/memory/probation.js +2 -6
  17. package/dist/models/auth-cli.d.ts +1 -1
  18. package/dist/models/auth-cli.js +3 -2
  19. package/dist/paths.d.ts +0 -6
  20. package/dist/paths.js +0 -6
  21. package/dist/playbooks/agent-delegation.md +9 -8
  22. package/dist/playbooks/background-jobs.md +1 -1
  23. package/dist/playbooks/catalog.d.ts +2 -2
  24. package/dist/playbooks/catalog.js +20 -9
  25. package/dist/playbooks/event-scheduling.md +1 -1
  26. package/dist/playbooks/memory-and-learning.md +1 -1
  27. package/dist/playbooks/outbound-media.md +5 -5
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-driving.md +1 -1
  30. package/dist/playbooks/task-planning.md +1 -1
  31. package/dist/runtime/app-home.d.ts +32 -0
  32. package/dist/runtime/app-home.js +319 -0
  33. package/dist/runtime/bootstrap.d.ts +3 -69
  34. package/dist/runtime/bootstrap.js +113 -511
  35. package/dist/runtime/delivery.js +1 -1
  36. package/dist/runtime/dingtalk.d.ts +7 -6
  37. package/dist/runtime/dingtalk.js +5 -13
  38. package/dist/runtime/task-wake.d.ts +54 -0
  39. package/dist/runtime/task-wake.js +99 -0
  40. package/dist/shared/host-process.d.ts +5 -5
  41. package/dist/shared/host-process.js +19 -0
  42. package/dist/shared/wake-claim.d.ts +23 -0
  43. package/dist/shared/wake-claim.js +26 -0
  44. package/dist/subagents/discovery.d.ts +9 -1
  45. package/dist/subagents/discovery.js +37 -9
  46. package/dist/subagents/external/claude-code.js +4 -5
  47. package/dist/subagents/external/codex-cli.js +1 -7
  48. package/dist/subagents/external/exec.js +7 -2
  49. package/dist/subagents/external/harness.d.ts +0 -3
  50. package/dist/subagents/external/harness.js +18 -3
  51. package/dist/subagents/external/run.d.ts +5 -0
  52. package/dist/subagents/external/run.js +70 -31
  53. package/dist/subagents/runs.d.ts +40 -9
  54. package/dist/subagents/runs.js +194 -31
  55. package/dist/subagents/tool.d.ts +3 -1
  56. package/dist/subagents/tool.js +33 -14
  57. package/dist/tools/memory-manage.js +0 -1
  58. package/dist/tools/subagent-manage.js +18 -1
  59. package/dist/tui/app.d.ts +1 -1
  60. package/dist/tui/app.js +3 -2
  61. package/dist/tui/cli.d.ts +1 -1
  62. package/dist/tui/cli.js +1 -1
  63. package/dist/tui/terminal-media-sender.d.ts +1 -1
  64. package/examples/sub-agents/README.md +25 -16
  65. package/examples/sub-agents/builder-hard.md +9 -8
  66. package/examples/sub-agents/builder.md +12 -11
  67. package/examples/sub-agents/documenter.md +11 -14
  68. package/examples/sub-agents/explorer.md +16 -13
  69. package/examples/sub-agents/git-committer.md +18 -16
  70. package/examples/sub-agents/log-sifter.md +19 -16
  71. package/examples/sub-agents/planner.md +17 -17
  72. package/examples/sub-agents/reviewer.md +13 -23
  73. package/examples/sub-agents/scout.md +5 -6
  74. package/examples/sub-agents/verifier.md +8 -14
  75. package/examples/sub-agents/worker.md +7 -8
  76. package/package.json +1 -1
@@ -1,20 +1,20 @@
1
1
  ---
2
2
  name: agent-delegation
3
- description: 委派内部子代理(subagent)或外部 AI Agent,编写任务指令、选人、并行隔离、等待、纠偏与验收时。
4
- priority: 36
3
+ description: 委派内部子智能体(subagent,子代理)或外部 AI Agent,编写任务指令、选智能体角色、并行隔离、等待、纠偏与验收。
4
+ order: 36
5
5
  ---
6
6
 
7
7
  # AI Agent 委派
8
8
 
9
9
  只委派真正可分离、可独立验收的工作。选择分片、决定工作目录、整合结果、核对真实产物和最终交付**始终是你的责任**,不随委派转移。
10
10
 
11
- 一次委派的完整流程:**选人 → 写任务契约 → 定工作目录 → 派发 → 结束回合等唤醒 → 独立验收**。下面按这个顺序展开。
11
+ 一次委派的完整流程:**选角色 → 写任务契约 → 定工作目录 → 派发 → 结束回合等唤醒 → 独立验收**。下面按这个顺序展开。
12
12
 
13
- ## 一、选人
13
+ ## 一、选角色
14
14
 
15
- 看活的**轻重**,选目录里对应的角色:只读定位、单点事实、小范围检查交给 `light`;跨多文件实现、需要自测、要跑几十分钟的重活交给 `heavy`。系统提示里的目录已按 `light`/`heavy` 和 `read`/`write` 分好组,`description` 说明各自的适用面,照着挑即可,**不要按底层 harness(claude-code / codex-cli / exec)选**——harness 只决定命令怎么拼,不改变角色能做什么。
15
+ 看活的**轻重**,选目录里对应的角色:只读定位、单点事实、小范围检查交给 `light`;跨多文件实现、需要自测、要跑几十分钟的重活交给 `heavy`。系统提示里的目录已按 `light`/`heavy` 和 `read`/`write` 分好组,`description` 说明各自的适用面,照着挑即可,**不要按底层 harness(claude-code / codex-cli / exec)选**——harness 只决定调用的一些细节,如命令怎么拼,不改变角色能做什么。
16
16
 
17
- 顺带知道三件事就够了:`light` 通常是内置角色,同回合就返回(超 120 秒自动转异步,这是降级不是失败);`heavy` 通常是外部角色,一律异步;标了 `write` 的角色会改宿主文件,因此要单独想清楚工作目录(第三节)。
17
+ 顺带知道三件事就够了:`light` 通常是内置角色,同回合就返回(超 120 秒自动转异步,这是交互方式优化不是失败);`heavy` 通常是外部角色,一律异步;标了 `write` 的角色可以改宿主文件,因此要单独想清楚工作目录(第三节)。
18
18
 
19
19
  角色不可用(对应 CLI 没装)时仍会列在目录里并标 `unavailable`,调用会失败并给出安装指引。**这时不要拿内置角色顶替**:轻量角色做不了重活,静默降级只会产出一份看起来完成了的劣质结果。把缺什么告诉用户。
20
20
 
@@ -32,7 +32,7 @@ priority: 36
32
32
 
33
33
  只保留会改变结果的要求,删掉泛化人设、重复警告、无效示例和过细流程。追加指令(`follow_up`)只写相对原契约的**变化**:观察到的偏差、期望修正、要保持的部分、如何重新验证。
34
34
 
35
- `effort` 只是预算档位:对内置角色是轮次/工具调用/时钟三件套,对外部角色只放宽墙钟时间。它不会让 Agent 更聪明,不要用它替代写清楚的契约。
35
+ `effort` 只是预算档位:对内置角色是轮次/工具调用/时钟三件套,对外部角色高effort也要放宽墙钟时间。它不会让 Agent 更聪明,不要用它替代写清楚的契约。
36
36
 
37
37
  ## 三、工作目录:每次委派现场决定
38
38
 
@@ -42,6 +42,7 @@ priority: 36
42
42
  - **并行的写入分片各自 `git worktree add` 后指向不同 checkout**,绝不让两个写入者共享一棵树。
43
43
  - runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。
44
44
  - **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
45
+ - **创建的 worktree 在使用结束后要记得关闭**
45
46
 
46
47
  ## 四、派发之后:结束回合,等唤醒
47
48
 
@@ -50,7 +51,7 @@ priority: 36
50
51
  1. **不要轮询,也不要用后台作业包一层等待。** 委派结束时 runtime 会唤醒本频道,带回状态、耗时、结果尾部和产物路径。这是 runtime 保证。
51
52
  2. **立即结束当前回合。** 属于某个 task 时,派发就带上 `taskId`,并用 `task_manage progress` 置 `waiting` + `waitingFor=external-signal`——唤醒事件会据此恢复该任务。
52
53
  3. 想看进度用 `subagent_manage op=list`(人可用 `/subagents list`),不要靠反复调用委派工具来"检查"。
53
- 4. 每个频道最多 5 个同时在跑的委派(宿主全局 20 个)。被上限拒绝时先等一个结束或 `cancel` 一个,不要改小任务再试。
54
+ 4. 每个频道最多 6 个同时在跑的委派(宿主全局 20 个)。被上限拒绝时先等一个结束或 `cancel` 一个,不要改小任务再试。
54
55
  5. daemon 重启时外部 run 继续跑,内置 run 会被判 `lost` 并唤醒说明。收到 `lost` 就是"结局未知":先查真实产物,再决定重派,不要假设它已经做完。
55
56
 
56
57
  ## 五、纠偏与续接
@@ -2,7 +2,7 @@
2
2
  name: background-jobs
3
3
  description: 用 bash async 启动长跑命令、轮询后台作业(job),或作业跨回合仍未完成时。
4
4
  requires-tools: job
5
- priority: 35
5
+ order: 35
6
6
  ---
7
7
 
8
8
  # 后台作业(background jobs)
@@ -11,8 +11,8 @@ export interface RuntimePlaybookMetadata {
11
11
  * (Prompt sections gate the other way: see `requiresAllTools` in agent/prompt/types.ts.)
12
12
  */
13
13
  requiresAnyTool: string[];
14
- /** Ascending; ties break on filename. */
15
- priority: number;
14
+ /** Ascending catalog position. Values must be unique non-negative integers. */
15
+ order: number;
16
16
  }
17
17
  /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
18
18
  export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimePlaybookMetadata[];
@@ -2,7 +2,7 @@ import { readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { PLAYBOOKS_DIR } from "../paths.js";
4
4
  import { TOOL_NAMES } from "../tools/registry.js";
5
- const DEFAULT_PRIORITY = 100;
5
+ const DEFAULT_ORDER = 100;
6
6
  /** A catalog entry is a single trigger, not a summary; longer descriptions are clipped in the prompt (spec 026 §10.5). */
7
7
  export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 100;
8
8
  function parseList(value) {
@@ -45,23 +45,34 @@ function parseFrontmatter(content, filename) {
45
45
  throw new Error(`Runtime playbook ${filename} requires unknown tool "${tool}".`);
46
46
  }
47
47
  }
48
- const priorityField = fields.get("priority");
49
- const priority = priorityField ? Number(priorityField) : DEFAULT_PRIORITY;
50
- if (!Number.isFinite(priority)) {
51
- throw new Error(`Runtime playbook ${filename} has a non-numeric priority "${priorityField}".`);
48
+ if (fields.has("priority")) {
49
+ throw new Error(`Runtime playbook ${filename} uses unsupported metadata "priority"; rename it to "order".`);
52
50
  }
53
- return { name, description, requiresAnyTool, priority };
51
+ const orderField = fields.get("order");
52
+ const order = orderField === undefined ? DEFAULT_ORDER : orderField === "" ? Number.NaN : Number(orderField);
53
+ if (!Number.isInteger(order) || order < 0) {
54
+ throw new Error(`Runtime playbook ${filename} order must be a non-negative integer; received "${orderField ?? DEFAULT_ORDER}".`);
55
+ }
56
+ return { name, description, requiresAnyTool, order };
54
57
  }
55
58
  /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
56
59
  export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
57
- return readdirSync(directory)
60
+ const catalog = readdirSync(directory)
58
61
  .filter((filename) => filename.endsWith(".md"))
59
62
  .sort()
60
63
  .map((filename) => {
61
64
  const path = join(directory, filename);
62
65
  return { ...parseFrontmatter(readFileSync(path, "utf-8"), filename), filename, path };
63
- })
64
- .sort((a, b) => a.priority - b.priority || a.filename.localeCompare(b.filename));
66
+ });
67
+ const orderOwners = new Map();
68
+ for (const playbook of catalog) {
69
+ const owner = orderOwners.get(playbook.order);
70
+ if (owner) {
71
+ throw new Error(`Runtime playbooks ${owner} and ${playbook.filename} use duplicate order ${playbook.order}; assign each playbook a unique order.`);
72
+ }
73
+ orderOwners.set(playbook.order, playbook.filename);
74
+ }
75
+ return catalog.sort((a, b) => a.order - b.order || a.filename.localeCompare(b.filename));
65
76
  }
66
77
  /**
67
78
  * Drop playbooks whose mechanism is unreachable with the current tool set: the task
@@ -2,7 +2,7 @@
2
2
  name: event-scheduling
3
3
  description: 创建、调整或退役提醒、定时调度(cron)、preAction 传感器门控,或跨回合的回访事件(event)。
4
4
  requires-tools: event_manage
5
- priority: 30
5
+ order: 30
6
6
  ---
7
7
 
8
8
  # 事件与调度
@@ -2,7 +2,7 @@
2
2
  name: memory-and-learning
3
3
  description: 记住或忘记事实(memory)、在记忆文件之间取舍,或把经验沉淀成技能(skill)。
4
4
  requires-tools: memory_manage, skill_manage
5
- priority: 20
5
+ order: 20
6
6
  ---
7
7
 
8
8
  # 记忆、状态与程序性学习
@@ -2,18 +2,18 @@
2
2
  name: outbound-media
3
3
  description: 把生成的文件、图片、报表或导出物作为附件(attachment / media)交付给用户时。
4
4
  requires-tools: send_media
5
- priority: 25
5
+ order: 25
6
6
  ---
7
7
 
8
8
  # 附件交付(outbound media)
9
9
 
10
- 产物真正到了用户手里才算交付。使用 `send_media` 发送 workspace 内的文件;成功后把附件名、目标 channel、message id 和时间写进任务 Current Cycle 或 completion evidence。
10
+ 产物真正通过当前 transport 发出才算交付。使用 `send_media` 发送 workspace 内的文件;成功后把工具返回的 receipt(附件名、类型、大小和已发送到当前 channel)及记录时间写进任务 Current Cycle 或 completion evidence。
11
11
 
12
12
  发送前检查:
13
13
 
14
14
  - 文件已经生成且非空;
15
15
  - 目标仍在 task Goal 范围内;
16
- - 查询或记录已有 message/request id,避免 crash replay 重复发送;
17
- - 发送后查询真实投递状态,失败则 progress 为 active/waiting 并写 recovery source。
16
+ - 查询任务 Current Cycle 或 completion evidence 中是否已有同一附件的成功 receipt,避免明显的重复发送;
17
+ - 只有 `send_media` 返回成功 receipt 才记录已发送;失败则 progress 为 active/waiting 并写 recovery source。
18
18
 
19
- send_media 的 path guard、文件类型和 transport 失败信息会给出可执行 next step。不要把主机路径当作用户可下载附件;不要因为一次调用返回成功就跳过真实结果核对。
19
+ `send_media` 的 path guard、文件类型和 transport 失败信息会给出可执行 next step。不要把主机路径当作用户可下载附件。当前接口不返回 message/request id,也不提供二次投递状态查询;不要虚构这些证据。若任务要求更强的送达确认,明确记录现有 receipt 的证据边界,并向用户确认或等待 transport 增强。
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: runtime-orientation
3
3
  description: 定位 app / workspace / channel / task 的配置与状态文件,或判断机制、团队规则和工具知识该归哪一层。
4
- priority: 10
4
+ order: 10
5
5
  ---
6
6
 
7
7
  # Pipiclaw 运行时导航
@@ -2,7 +2,7 @@
2
2
  name: task-driving
3
3
  description: 被 TASK_DRIVER 唤醒推进任务,或处理任务等待、验收(verify)、闭环、停滞、停用及元数据损坏时。
4
4
  requires-tools: task_manage
5
- priority: 41
5
+ order: 41
6
6
  ---
7
7
 
8
8
  # 任务推进、验收、闭环与修复
@@ -2,7 +2,7 @@
2
2
  name: task-planning
3
3
  description: 创建或重构长程任务(task)、选择 task 与事件(event),或设定周期节奏(schedule)。
4
4
  requires-tools: task_manage
5
- priority: 40
5
+ order: 40
6
6
  ---
7
7
 
8
8
  # 长程任务(task)规划与建档
@@ -0,0 +1,32 @@
1
+ import { type DingTalkConfig } from "./dingtalk.js";
2
+ export interface BootstrapPaths {
3
+ appName: string;
4
+ appHomeDir: string;
5
+ workspaceDir: string;
6
+ authConfigPath: string;
7
+ channelConfigPath: string;
8
+ modelsConfigPath: string;
9
+ settingsConfigPath: string;
10
+ toolsConfigPath: string;
11
+ securityConfigPath: string;
12
+ eventHistoryPath: string;
13
+ }
14
+ export interface BootstrapIO {
15
+ log: (...args: unknown[]) => void;
16
+ error: (...args: unknown[]) => void;
17
+ }
18
+ export interface BootstrapResult {
19
+ created: string[];
20
+ channelTemplateCreated: boolean;
21
+ }
22
+ export declare const DEFAULT_BOOTSTRAP_PATHS: BootstrapPaths;
23
+ export declare class BootstrapExitError extends Error {
24
+ readonly code: number;
25
+ constructor(code: number, message?: string);
26
+ }
27
+ export declare function isBootstrapExitError(error: unknown): error is BootstrapExitError;
28
+ export declare function readCliVersion(): string;
29
+ export declare function bootstrapAppHome(paths?: BootstrapPaths): BootstrapResult;
30
+ export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
31
+ export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
32
+ export declare function parseArgs(argv: string[], paths?: BootstrapPaths, io?: BootstrapIO): void;
@@ -0,0 +1,319 @@
1
+ /**
2
+ * App-home scaffolding: create `~/.pipiclaw` (or `PIPICLAW_HOME`) on first run, validate
3
+ * `channel.json`, and parse CLI args shared by every entrypoint. Pure functions over explicit
4
+ * `paths`/`io` parameters — no dependency on the runtime wiring in `bootstrap.ts`.
5
+ */
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
7
+ import { join } from "path";
8
+ import * as log from "../log.js";
9
+ import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
10
+ import { errorMessage } from "../shared/text-utils.js";
11
+ import { isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
12
+ import { DEFAULT_AGENTS, DEFAULT_SOUL } from "./workspace-templates.js";
13
+ const DEFAULT_MEMORY = `# Workspace Memory
14
+
15
+ This file stores stable workspace-level memory.
16
+
17
+ - It is intended to be managed by a human administrator.
18
+ - It is not automatically rewritten by normal runtime consolidation.
19
+ - Store durable shared background here when it should apply across channels.
20
+ - Keep this file focused on stable facts, policies, and shared context, not transient conversation history.
21
+
22
+ ## Shared Context
23
+
24
+ <!-- Put team-wide or workspace-wide background here. -->
25
+
26
+ ## Tooling And Environment
27
+
28
+ <!-- Put durable tool usage rules, environment assumptions, or shared operational conventions here. -->
29
+
30
+ ## Project Notes
31
+
32
+ <!-- Put long-lived project facts here. -->
33
+ `;
34
+ const DEFAULT_ENVIRONMENT = `# Environment
35
+
36
+ This file records durable environment facts and notable machine-level changes.
37
+
38
+ - Record installed tools, runtime prerequisites, and important config changes here.
39
+ - Keep entries concise and factual.
40
+ - Do not use this file for task progress, conversation summaries, or project-specific decisions.
41
+
42
+ ## Environment Facts
43
+
44
+ <!-- Put stable machine or runtime facts here. -->
45
+
46
+ ## Installed Tools
47
+
48
+ <!-- Record durable tools or dependencies that were installed for this workspace. -->
49
+
50
+ ## Config Changes
51
+
52
+ <!-- Record important config or environment changes that affect future work. -->
53
+ `;
54
+ const CHANNEL_CONFIG_TEMPLATE = {
55
+ clientId: "your-dingtalk-client-id",
56
+ clientSecret: "your-dingtalk-client-secret",
57
+ robotCode: "your-robot-code",
58
+ cardTemplateId: "your-card-template-id",
59
+ cardTemplateKey: "content",
60
+ allowFrom: ["your-staff-id"],
61
+ busyMessageDefault: "steer",
62
+ responseMode: "full_progress_then_plain_final",
63
+ cardAutoLayout: true,
64
+ };
65
+ const MODELS_CONFIG_TEMPLATE = { providers: {} };
66
+ const TOOLS_CONFIG_TEMPLATE = {
67
+ tools: {
68
+ web: {
69
+ enable: false,
70
+ proxy: null,
71
+ search: {
72
+ provider: "brave",
73
+ apiKey: "",
74
+ maxResults: 5,
75
+ },
76
+ },
77
+ tasks: {
78
+ enabled: true,
79
+ },
80
+ },
81
+ _examples: {
82
+ proxy: "http://127.0.0.1:7890",
83
+ apiKey: "BSA...",
84
+ },
85
+ _notes: [
86
+ "Set tools.web.enable to true to register web_search and web_fetch.",
87
+ "Replace tools.web.search.apiKey with your Brave API key before enabling web tools.",
88
+ "If needed, copy _examples.proxy to tools.web.proxy.",
89
+ "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_manage tool + task driver + task digest).",
90
+ ],
91
+ };
92
+ const SECURITY_CONFIG_TEMPLATE = {
93
+ pathGuard: {
94
+ enabled: true,
95
+ },
96
+ commandGuard: {
97
+ enabled: true,
98
+ },
99
+ networkGuard: {
100
+ enabled: false,
101
+ },
102
+ };
103
+ export const DEFAULT_BOOTSTRAP_PATHS = {
104
+ appName: APP_NAME,
105
+ appHomeDir: APP_HOME_DIR,
106
+ workspaceDir: WORKSPACE_DIR,
107
+ authConfigPath: AUTH_CONFIG_PATH,
108
+ channelConfigPath: CHANNEL_CONFIG_PATH,
109
+ modelsConfigPath: MODELS_CONFIG_PATH,
110
+ settingsConfigPath: SETTINGS_CONFIG_PATH,
111
+ toolsConfigPath: TOOLS_CONFIG_PATH,
112
+ securityConfigPath: SECURITY_CONFIG_PATH,
113
+ eventHistoryPath: EVENT_HISTORY_PATH,
114
+ };
115
+ export class BootstrapExitError extends Error {
116
+ constructor(code, message) {
117
+ super(message ?? `Bootstrap requested exit with code ${code}`);
118
+ this.code = code;
119
+ this.name = "BootstrapExitError";
120
+ }
121
+ }
122
+ export function isBootstrapExitError(error) {
123
+ return error instanceof BootstrapExitError;
124
+ }
125
+ export function readCliVersion() {
126
+ try {
127
+ const raw = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf-8"));
128
+ return typeof raw.version === "string" && raw.version.trim() ? raw.version : "0.0.0";
129
+ }
130
+ catch {
131
+ return "0.0.0";
132
+ }
133
+ }
134
+ function writeTextFileIfMissing(path, content, label, created, mode) {
135
+ if (existsSync(path)) {
136
+ return false;
137
+ }
138
+ writeFileSync(path, content, mode !== undefined ? { encoding: "utf-8", mode } : "utf-8");
139
+ created.push(label);
140
+ return true;
141
+ }
142
+ function writeJsonFileIfMissing(path, value, label, created, mode) {
143
+ return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created, mode);
144
+ }
145
+ // App-level config files that may hold secrets (DingTalk client secret, provider
146
+ // API keys, Brave key). They are created owner-only, and any pre-existing file with
147
+ // looser bits is tightened on startup.
148
+ const SECRET_FILE_MODE = 0o600;
149
+ function hardenExistingSecretFile(path) {
150
+ if (!existsSync(path)) {
151
+ return;
152
+ }
153
+ try {
154
+ const mode = statSync(path).mode & 0o777;
155
+ if ((mode & 0o077) !== 0) {
156
+ chmodSync(path, SECRET_FILE_MODE);
157
+ log.logInfo(`Tightened permissions on ${path} to 0600`);
158
+ }
159
+ }
160
+ catch (err) {
161
+ log.logWarning(`Failed to tighten permissions on ${path}`, errorMessage(err));
162
+ }
163
+ }
164
+ export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
165
+ const created = [];
166
+ if (!existsSync(paths.appHomeDir)) {
167
+ mkdirSync(paths.appHomeDir, { recursive: true });
168
+ created.push("app home");
169
+ }
170
+ if (!existsSync(paths.workspaceDir)) {
171
+ mkdirSync(paths.workspaceDir, { recursive: true });
172
+ created.push("workspace/");
173
+ }
174
+ for (const dir of ["skills", "events", "sub-agents"]) {
175
+ const dirPath = join(paths.workspaceDir, dir);
176
+ if (!existsSync(dirPath)) {
177
+ mkdirSync(dirPath, { recursive: true });
178
+ created.push(`workspace/${dir}/`);
179
+ }
180
+ }
181
+ writeTextFileIfMissing(join(paths.workspaceDir, "SOUL.md"), DEFAULT_SOUL, "workspace/SOUL.md", created);
182
+ writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, "workspace/AGENTS.md", created);
183
+ writeTextFileIfMissing(join(paths.workspaceDir, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
184
+ writeTextFileIfMissing(join(paths.workspaceDir, "ENVIRONMENT.md"), DEFAULT_ENVIRONMENT, "workspace/ENVIRONMENT.md", created);
185
+ const secretConfigPaths = [
186
+ paths.channelConfigPath,
187
+ paths.authConfigPath,
188
+ paths.modelsConfigPath,
189
+ paths.settingsConfigPath,
190
+ paths.toolsConfigPath,
191
+ paths.securityConfigPath,
192
+ ];
193
+ const channelTemplateCreated = writeJsonFileIfMissing(paths.channelConfigPath, CHANNEL_CONFIG_TEMPLATE, "channel.json", created, SECRET_FILE_MODE);
194
+ writeJsonFileIfMissing(paths.authConfigPath, {}, "auth.json", created, SECRET_FILE_MODE);
195
+ writeJsonFileIfMissing(paths.modelsConfigPath, MODELS_CONFIG_TEMPLATE, "models.json", created, SECRET_FILE_MODE);
196
+ writeJsonFileIfMissing(paths.settingsConfigPath, {}, "settings.json", created, SECRET_FILE_MODE);
197
+ writeJsonFileIfMissing(paths.toolsConfigPath, TOOLS_CONFIG_TEMPLATE, "tools.json", created, SECRET_FILE_MODE);
198
+ writeJsonFileIfMissing(paths.securityConfigPath, SECURITY_CONFIG_TEMPLATE, "security.json", created, SECRET_FILE_MODE);
199
+ // Tighten any pre-existing config that predates owner-only creation.
200
+ for (const secretPath of secretConfigPaths) {
201
+ hardenExistingSecretFile(secretPath);
202
+ }
203
+ return { created, channelTemplateCreated };
204
+ }
205
+ function isPlaceholderString(value) {
206
+ return value.trim().startsWith("your-");
207
+ }
208
+ function listChannelConfigIssues(config) {
209
+ const issues = [];
210
+ if (!config.clientId) {
211
+ issues.push("Missing required field `clientId`.");
212
+ }
213
+ else if (isPlaceholderString(config.clientId)) {
214
+ issues.push("Replace placeholder value for `clientId`.");
215
+ }
216
+ if (!config.clientSecret) {
217
+ issues.push("Missing required field `clientSecret`.");
218
+ }
219
+ else if (isPlaceholderString(config.clientSecret)) {
220
+ issues.push("Replace placeholder value for `clientSecret`.");
221
+ }
222
+ if (config.robotCode && isPlaceholderString(config.robotCode)) {
223
+ issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
224
+ }
225
+ if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
226
+ issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
227
+ }
228
+ if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
229
+ issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
230
+ }
231
+ const busyMessageDefault = config.busyMessageDefault;
232
+ if (busyMessageDefault !== undefined && !isBusyMessageDefaultConfig(busyMessageDefault)) {
233
+ issues.push('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
234
+ }
235
+ const responseMode = config.responseMode;
236
+ if (responseMode !== undefined && !isResponseModeConfig(responseMode)) {
237
+ issues.push('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
238
+ }
239
+ const cardAutoLayout = config.cardAutoLayout;
240
+ if (cardAutoLayout !== undefined && typeof cardAutoLayout !== "boolean") {
241
+ issues.push("Invalid `cardAutoLayout`: expected boolean.");
242
+ }
243
+ return issues;
244
+ }
245
+ export function printBootstrapSummary(result, io = console, paths = DEFAULT_BOOTSTRAP_PATHS) {
246
+ if (result.created.length === 0) {
247
+ return;
248
+ }
249
+ io.log(`Initialized ${paths.appName} under ${paths.appHomeDir}:`);
250
+ for (const item of result.created) {
251
+ io.log(` - ${item}`);
252
+ }
253
+ io.log("");
254
+ }
255
+ export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
256
+ let parsed;
257
+ try {
258
+ parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
259
+ }
260
+ catch (err) {
261
+ io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
262
+ io.error(errorMessage(err));
263
+ throw new BootstrapExitError(1);
264
+ }
265
+ const issues = listChannelConfigIssues(parsed);
266
+ if (issues.length > 0) {
267
+ io.error(`Configuration is not ready: ${paths.channelConfigPath}`);
268
+ for (const issue of issues) {
269
+ io.error(` - ${issue}`);
270
+ }
271
+ io.error("");
272
+ io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
273
+ throw new BootstrapExitError(1);
274
+ }
275
+ parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
276
+ parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
277
+ parsed.busyMessageDefault = normalizeBusyMessageDefault(parsed.busyMessageDefault);
278
+ parsed.responseMode = normalizeResponseMode(parsed.responseMode);
279
+ parsed.cardAutoLayout = parsed.cardAutoLayout ?? true;
280
+ if (Array.isArray(parsed.allowFrom)) {
281
+ parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
282
+ }
283
+ return parsed;
284
+ }
285
+ export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
286
+ const args = argv.slice(2);
287
+ for (let index = 0; index < args.length; index += 1) {
288
+ const arg = args[index];
289
+ if (index === 0 && arg === "run") {
290
+ // Explicit name for the default daemon mode (`pipiclaw run` == `pipiclaw`).
291
+ continue;
292
+ }
293
+ if (arg === "--help" || arg === "-h") {
294
+ io.log(`Usage: ${paths.appName} [command] [options]`);
295
+ io.log("");
296
+ io.log("Commands:");
297
+ io.log(" run Run the long-lived DingTalk daemon (default)");
298
+ io.log(" tui [prompt] Chat with the agent in the terminal");
299
+ io.log(" auth status|login|logout Manage provider credentials");
300
+ io.log("");
301
+ io.log("Options:");
302
+ io.log(" --version Print the current version and exit");
303
+ io.log(" --help, -h Show this help and exit");
304
+ io.log("");
305
+ io.log(`Config: ${paths.channelConfigPath}`);
306
+ io.log(`Workspace: ${paths.workspaceDir}`);
307
+ throw new BootstrapExitError(0);
308
+ }
309
+ else if (arg === "--version") {
310
+ io.log(readCliVersion());
311
+ throw new BootstrapExitError(0);
312
+ }
313
+ else {
314
+ io.error(`Unknown option: ${arg}`);
315
+ io.error(`Run \`${paths.appName} --help\` for usage.`);
316
+ throw new BootstrapExitError(1);
317
+ }
318
+ }
319
+ }
@@ -1,27 +1,10 @@
1
1
  import { type AgentRunner } from "../agent/index.js";
2
- import { type JobSnapshot } from "../agent/job-manager.js";
3
2
  import { type Executor } from "../executor.js";
4
3
  import { PipiclawSettingsManager } from "../settings.js";
5
- import { type RunRecord } from "../subagents/runs.js";
6
4
  import { type WakeTaskTransitionHooks } from "../tasks/store.js";
5
+ import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
7
6
  import { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler } from "./dingtalk.js";
8
7
  import { ChannelStore } from "./store.js";
9
- export interface BootstrapPaths {
10
- appName: string;
11
- appHomeDir: string;
12
- workspaceDir: string;
13
- authConfigPath: string;
14
- channelConfigPath: string;
15
- modelsConfigPath: string;
16
- settingsConfigPath: string;
17
- toolsConfigPath: string;
18
- securityConfigPath: string;
19
- eventHistoryPath: string;
20
- }
21
- export interface BootstrapIO {
22
- log: (...args: unknown[]) => void;
23
- error: (...args: unknown[]) => void;
24
- }
25
8
  export interface BootstrapOptions {
26
9
  env?: NodeJS.ProcessEnv;
27
10
  io?: BootstrapIO;
@@ -29,10 +12,6 @@ export interface BootstrapOptions {
29
12
  registerSignalHandlers?: boolean;
30
13
  startServices?: boolean;
31
14
  }
32
- export interface BootstrapResult {
33
- created: string[];
34
- channelTemplateCreated: boolean;
35
- }
36
15
  export interface AppContext {
37
16
  bot: DingTalkBot;
38
17
  store: ChannelStore;
@@ -64,51 +43,6 @@ export interface RuntimeContext {
64
43
  };
65
44
  shutdown: (reason?: NodeJS.Signals | "manual") => Promise<void>;
66
45
  }
67
- export declare const DEFAULT_BOOTSTRAP_PATHS: BootstrapPaths;
68
- export declare class BootstrapExitError extends Error {
69
- readonly code: number;
70
- constructor(code: number, message?: string);
71
- }
72
- export declare function isBootstrapExitError(error: unknown): error is BootstrapExitError;
73
- export declare function readCliVersion(): string;
74
- export declare function migrateLegacyAppHome(targetDir: string, legacyDir: string, io: BootstrapIO): boolean;
75
- export declare function bootstrapAppHome(paths?: BootstrapPaths, io?: BootstrapIO): BootstrapResult;
76
- export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
77
- export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
78
- export declare function parseArgs(argv: string[], paths?: BootstrapPaths, io?: BootstrapIO): void;
79
- /**
80
- * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
81
- * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
82
- * accepting it anyway would let a message merely mentioning a live job's id activate a task
83
- * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
84
- * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
85
- * untrusted stdout.
86
- */
87
- export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
88
- /**
89
- * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
90
- * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
91
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
92
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
93
- */
94
- export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
95
- /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
96
- * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
97
- * not populate `internalWake`, so copying a real wake's text is insufficient. */
98
- export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
99
- dispatchId: string;
100
- };
101
- export interface ClaimedDelegationWake {
102
- taskId: string;
103
- generation?: number;
104
- activated: boolean;
105
- finish(): Promise<void>;
106
- rollback(): Promise<void>;
107
- }
108
- /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
109
- * final marker separate lets transports such as TUI mark it consumed only after they have accepted
110
- * the corresponding turn; a rejected submit remains replayable in the same or next process. */
111
- export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
112
46
  /**
113
47
  * Watchdog for `/stop`: release the channel if the stopped turn has not ended
114
48
  * once the grace window elapses. Returns true when it had to force the release.
@@ -150,9 +84,9 @@ interface RuntimeContextOptions {
150
84
  /** Override the `/stop` watchdog's grace window (tests use a short one). */
151
85
  stopForceEndGraceMs?: number;
152
86
  }
153
- export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
87
+ export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
154
88
  bot: DingTalkBot;
155
- };
89
+ }>;
156
90
  /**
157
91
  * Transport-neutral app services shared by the DingTalk runtime and the terminal
158
92
  * TUI: loads settings (surfacing load errors) and reports tool/security config