@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.10

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 (186) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +28 -0
  3. package/dist/agent/channel-runner.js +293 -145
  4. package/dist/agent/commands.d.ts +7 -1
  5. package/dist/agent/commands.js +26 -0
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +1 -1
  8. package/dist/agent/job-manager.d.ts +34 -6
  9. package/dist/agent/job-manager.js +73 -7
  10. package/dist/agent/progress-formatter.js +3 -3
  11. package/dist/agent/prompt/sections.js +46 -7
  12. package/dist/agent/prompt/types.d.ts +9 -0
  13. package/dist/agent/run-queue.d.ts +10 -1
  14. package/dist/agent/run-queue.js +19 -2
  15. package/dist/agent/runner-factory.d.ts +16 -4
  16. package/dist/agent/runner-factory.js +9 -23
  17. package/dist/agent/session-events.js +7 -42
  18. package/dist/agent/session-resource-gate.d.ts +17 -0
  19. package/dist/agent/session-resource-gate.js +33 -2
  20. package/dist/agent/status-render.js +1 -3
  21. package/dist/agent/turn-recovery.d.ts +72 -0
  22. package/dist/agent/turn-recovery.js +193 -0
  23. package/dist/agent/types.d.ts +21 -1
  24. package/dist/agent/types.js +3 -16
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +2 -1
  27. package/dist/main.js +2 -1
  28. package/dist/memory/extraction.js +0 -1
  29. package/dist/memory/maintenance-gates.d.ts +1 -1
  30. package/dist/memory/maintenance-jobs.js +2 -3
  31. package/dist/memory/metadata.d.ts +0 -15
  32. package/dist/memory/metadata.js +0 -7
  33. package/dist/memory/probation.d.ts +1 -5
  34. package/dist/memory/probation.js +2 -6
  35. package/dist/memory/review-log.js +0 -0
  36. package/dist/memory/scheduler.d.ts +1 -0
  37. package/dist/memory/scheduler.js +64 -6
  38. package/dist/models/auth-cli.d.ts +1 -1
  39. package/dist/models/auth-cli.js +3 -2
  40. package/dist/paths.d.ts +0 -6
  41. package/dist/paths.js +0 -6
  42. package/dist/playbooks/agent-delegation.md +48 -22
  43. package/dist/playbooks/background-jobs.md +1 -1
  44. package/dist/playbooks/catalog.d.ts +2 -2
  45. package/dist/playbooks/catalog.js +20 -9
  46. package/dist/playbooks/event-scheduling.md +1 -1
  47. package/dist/playbooks/memory-and-learning.md +1 -1
  48. package/dist/playbooks/outbound-media.md +5 -5
  49. package/dist/playbooks/runtime-orientation.md +8 -3
  50. package/dist/playbooks/task-driving.md +1 -1
  51. package/dist/playbooks/task-planning.md +1 -1
  52. package/dist/runtime/active-session-store.d.ts +42 -0
  53. package/dist/runtime/active-session-store.js +100 -0
  54. package/dist/runtime/app-home.d.ts +32 -0
  55. package/dist/runtime/app-home.js +319 -0
  56. package/dist/runtime/bootstrap.d.ts +30 -36
  57. package/dist/runtime/bootstrap.js +359 -473
  58. package/dist/runtime/channel-event.d.ts +41 -0
  59. package/dist/runtime/channel-event.js +1 -0
  60. package/dist/runtime/delivery.d.ts +3 -2
  61. package/dist/runtime/delivery.js +11 -6
  62. package/dist/runtime/dingtalk.d.ts +16 -28
  63. package/dist/runtime/dingtalk.js +6 -10
  64. package/dist/runtime/durable-dispatch.d.ts +8 -2
  65. package/dist/runtime/durable-dispatch.js +52 -25
  66. package/dist/runtime/events.d.ts +3 -2
  67. package/dist/runtime/events.js +2 -3
  68. package/dist/runtime/project-commands.d.ts +16 -0
  69. package/dist/runtime/project-commands.js +112 -0
  70. package/dist/runtime/project-scope-store.d.ts +31 -0
  71. package/dist/runtime/project-scope-store.js +102 -0
  72. package/dist/runtime/store.d.ts +7 -0
  73. package/dist/runtime/subagent-commands.d.ts +17 -0
  74. package/dist/runtime/subagent-commands.js +360 -0
  75. package/dist/runtime/task-commands.js +7 -3
  76. package/dist/runtime/task-driver.d.ts +7 -7
  77. package/dist/runtime/task-driver.js +1 -4
  78. package/dist/runtime/task-migration.js +1 -1
  79. package/dist/runtime/task-wake.d.ts +54 -0
  80. package/dist/runtime/task-wake.js +99 -0
  81. package/dist/security/config.js +10 -0
  82. package/dist/security/logger.js +10 -1
  83. package/dist/security/path-guard.js +34 -9
  84. package/dist/security/project-scope.d.ts +45 -0
  85. package/dist/security/project-scope.js +107 -0
  86. package/dist/security/types.d.ts +37 -3
  87. package/dist/settings.d.ts +0 -106
  88. package/dist/settings.js +0 -224
  89. package/dist/shared/host-process.d.ts +37 -0
  90. package/dist/shared/host-process.js +112 -0
  91. package/dist/shared/jsonl-appender.d.ts +2 -0
  92. package/dist/shared/jsonl-appender.js +25 -13
  93. package/dist/shared/shell-words.d.ts +9 -0
  94. package/dist/shared/shell-words.js +52 -0
  95. package/dist/shared/types.d.ts +1 -0
  96. package/dist/shared/types.js +10 -1
  97. package/dist/shared/wake-claim.d.ts +23 -0
  98. package/dist/shared/wake-claim.js +26 -0
  99. package/dist/shared/with-timeout.d.ts +14 -0
  100. package/dist/shared/with-timeout.js +38 -0
  101. package/dist/subagents/detached-discovery.d.ts +13 -0
  102. package/dist/subagents/detached-discovery.js +17 -0
  103. package/dist/subagents/discovery.d.ts +74 -1
  104. package/dist/subagents/discovery.js +429 -82
  105. package/dist/subagents/external/claude-code.d.ts +2 -0
  106. package/dist/subagents/external/claude-code.js +158 -0
  107. package/dist/subagents/external/codex-cli.d.ts +2 -0
  108. package/dist/subagents/external/codex-cli.js +133 -0
  109. package/dist/subagents/external/exec.d.ts +2 -0
  110. package/dist/subagents/external/exec.js +44 -0
  111. package/dist/subagents/external/harness.d.ts +121 -0
  112. package/dist/subagents/external/harness.js +109 -0
  113. package/dist/subagents/external/registry.d.ts +2 -0
  114. package/dist/subagents/external/registry.js +11 -0
  115. package/dist/subagents/external/run.d.ts +74 -0
  116. package/dist/subagents/external/run.js +286 -0
  117. package/dist/subagents/external/settlement.d.ts +50 -0
  118. package/dist/subagents/external/settlement.js +123 -0
  119. package/dist/subagents/format.d.ts +16 -0
  120. package/dist/subagents/format.js +31 -0
  121. package/dist/subagents/runs.d.ts +342 -0
  122. package/dist/subagents/runs.js +909 -0
  123. package/dist/subagents/tool.d.ts +68 -6
  124. package/dist/subagents/tool.js +547 -206
  125. package/dist/subagents/verification-outcome.d.ts +26 -0
  126. package/dist/subagents/verification-outcome.js +16 -0
  127. package/dist/subagents/workspace-lease.d.ts +45 -0
  128. package/dist/subagents/workspace-lease.js +61 -0
  129. package/dist/tasks/artifact-subject.js +50 -2
  130. package/dist/tasks/control.d.ts +12 -0
  131. package/dist/tasks/control.js +20 -0
  132. package/dist/tasks/ledger.js +1 -1
  133. package/dist/tasks/store.d.ts +21 -0
  134. package/dist/tasks/store.js +80 -0
  135. package/dist/{shared → tasks}/task-schedule.js +1 -1
  136. package/dist/tasks/verification.d.ts +8 -0
  137. package/dist/tasks/verification.js +10 -2
  138. package/dist/tools/bash.js +4 -4
  139. package/dist/tools/edit.js +3 -3
  140. package/dist/tools/event-manage.js +1 -4
  141. package/dist/tools/grep.js +5 -6
  142. package/dist/tools/index.d.ts +4 -1
  143. package/dist/tools/index.js +25 -3
  144. package/dist/tools/job.js +5 -5
  145. package/dist/tools/memory-manage.js +3 -7
  146. package/dist/tools/read.js +3 -3
  147. package/dist/tools/registry.js +2 -1
  148. package/dist/tools/send-media.js +2 -2
  149. package/dist/tools/session-search.js +0 -1
  150. package/dist/tools/skill-manage.js +3 -3
  151. package/dist/tools/subagent-manage.d.ts +37 -0
  152. package/dist/tools/subagent-manage.js +245 -0
  153. package/dist/tools/task-manage/shared.js +2 -2
  154. package/dist/tools/task-manage.js +1 -4
  155. package/dist/tools/tool-details.d.ts +1 -1
  156. package/dist/tools/web-fetch.js +0 -1
  157. package/dist/tools/write-content.js +3 -3
  158. package/dist/tui/app.d.ts +1 -1
  159. package/dist/tui/app.js +55 -6
  160. package/dist/tui/cli.d.ts +1 -1
  161. package/dist/tui/cli.js +1 -1
  162. package/dist/tui/commands.d.ts +2 -0
  163. package/dist/tui/commands.js +4 -0
  164. package/dist/tui/terminal-media-sender.d.ts +1 -1
  165. package/dist/tui/turn-controller.d.ts +2 -0
  166. package/dist/tui/turn-controller.js +2 -0
  167. package/dist/usage/ledger.d.ts +13 -0
  168. package/dist/usage/ledger.js +15 -2
  169. package/dist/usage/render.js +22 -0
  170. package/examples/sub-agents/README.md +75 -14
  171. package/examples/sub-agents/builder-hard.md +46 -0
  172. package/examples/sub-agents/builder.md +42 -0
  173. package/examples/sub-agents/documenter.md +50 -0
  174. package/examples/sub-agents/explorer.md +16 -13
  175. package/examples/sub-agents/git-committer.md +33 -40
  176. package/examples/sub-agents/log-sifter.md +46 -0
  177. package/examples/sub-agents/planner.md +42 -0
  178. package/examples/sub-agents/reviewer.md +31 -41
  179. package/examples/sub-agents/scout.md +30 -0
  180. package/examples/sub-agents/verifier.md +27 -37
  181. package/examples/sub-agents/worker.md +35 -0
  182. package/package.json +1 -1
  183. package/examples/sub-agents/researcher.md +0 -41
  184. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  185. /package/dist/{shared → tasks}/task-events.js +0 -0
  186. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -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,23 +1,11 @@
1
+ import { type AgentRunner } from "../agent/index.js";
1
2
  import { type Executor } from "../executor.js";
2
3
  import { PipiclawSettingsManager } from "../settings.js";
3
- import { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler } from "./dingtalk.js";
4
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
5
+ import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
6
+ import type { ChannelEvent } from "./channel-event.js";
7
+ import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
4
8
  import { ChannelStore } from "./store.js";
5
- export interface BootstrapPaths {
6
- appName: string;
7
- appHomeDir: string;
8
- workspaceDir: string;
9
- authConfigPath: string;
10
- channelConfigPath: string;
11
- modelsConfigPath: string;
12
- settingsConfigPath: string;
13
- toolsConfigPath: string;
14
- securityConfigPath: string;
15
- eventHistoryPath: string;
16
- }
17
- export interface BootstrapIO {
18
- log: (...args: unknown[]) => void;
19
- error: (...args: unknown[]) => void;
20
- }
21
9
  export interface BootstrapOptions {
22
10
  env?: NodeJS.ProcessEnv;
23
11
  io?: BootstrapIO;
@@ -25,10 +13,6 @@ export interface BootstrapOptions {
25
13
  registerSignalHandlers?: boolean;
26
14
  startServices?: boolean;
27
15
  }
28
- export interface BootstrapResult {
29
- created: string[];
30
- channelTemplateCreated: boolean;
31
- }
32
16
  export interface AppContext {
33
17
  bot: DingTalkBot;
34
18
  store: ChannelStore;
@@ -60,18 +44,17 @@ export interface RuntimeContext {
60
44
  };
61
45
  shutdown: (reason?: NodeJS.Signals | "manual") => Promise<void>;
62
46
  }
63
- export declare const DEFAULT_BOOTSTRAP_PATHS: BootstrapPaths;
64
- export declare class BootstrapExitError extends Error {
65
- readonly code: number;
66
- constructor(code: number, message?: string);
67
- }
68
- export declare function isBootstrapExitError(error: unknown): error is BootstrapExitError;
69
- export declare function readCliVersion(): string;
70
- export declare function migrateLegacyAppHome(targetDir: string, legacyDir: string, io: BootstrapIO): boolean;
71
- export declare function bootstrapAppHome(paths?: BootstrapPaths, io?: BootstrapIO): BootstrapResult;
72
- export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
73
- export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
74
- export declare function parseArgs(argv: string[], paths?: BootstrapPaths, io?: BootstrapIO): void;
47
+ /**
48
+ * Watchdog for `/stop`: release the channel if the stopped turn has not ended
49
+ * once the grace window elapses. Returns true when it had to force the release.
50
+ */
51
+ export declare function forceEndStuckTurnAfterStop(input: {
52
+ channelId: string;
53
+ runner: AgentRunner;
54
+ graceMs?: number;
55
+ pollMs?: number;
56
+ notify?: (text: string) => Promise<unknown>;
57
+ }): Promise<boolean>;
75
58
  interface RuntimeContextOptions {
76
59
  paths: BootstrapPaths;
77
60
  dingtalkConfig: DingTalkConfig;
@@ -94,13 +77,24 @@ interface RuntimeContextOptions {
94
77
  /** Receives raw SDK session events after subscription, without changing runtime handling. */
95
78
  observer?: (event: unknown, channelId: string) => void;
96
79
  /** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */
97
- onTaskDriverDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
80
+ onTaskDriverDispatch?: (event: ChannelEvent, accepted: boolean) => void;
98
81
  startServices?: boolean;
99
82
  registerSignalHandlers?: boolean;
83
+ /** Test-only fault seams for the atomic structured-wake task transition. */
84
+ wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
85
+ /** Override the `/stop` watchdog's grace window (tests use a short one). */
86
+ stopForceEndGraceMs?: number;
87
+ /**
88
+ * The app-level settings manager, shared by every channel's runner (see
89
+ * `agent/runner-factory.ts`'s `RunnerFactoryPaths.settingsManager`). `bootstrap()` passes the
90
+ * same instance `prepareAppServices()` already constructed and diagnosed; a caller that skips
91
+ * `prepareAppServices()` (tests) gets one built here instead.
92
+ */
93
+ settingsManager?: PipiclawSettingsManager;
100
94
  }
101
- export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
95
+ export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
102
96
  bot: DingTalkBot;
103
- };
97
+ }>;
104
98
  /**
105
99
  * Transport-neutral app services shared by the DingTalk runtime and the terminal
106
100
  * TUI: loads settings (surfacing load errors) and reports tool/security config