@oyasmi/pipiclaw 0.9.0-beta.6 → 0.9.0-beta.8
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.
- package/dist/agent/channel-runner.d.ts +8 -0
- package/dist/agent/channel-runner.js +154 -132
- package/dist/agent/commands.d.ts +6 -0
- package/dist/agent/job-manager.js +6 -10
- package/dist/agent/progress-formatter.js +3 -3
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/main.js +2 -1
- package/dist/memory/extraction.js +0 -1
- package/dist/memory/maintenance-gates.d.ts +1 -1
- package/dist/memory/maintenance-jobs.js +2 -3
- package/dist/memory/metadata.d.ts +0 -15
- package/dist/memory/metadata.js +0 -7
- package/dist/memory/probation.d.ts +1 -5
- package/dist/memory/probation.js +2 -6
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/scheduler.d.ts +1 -0
- package/dist/memory/scheduler.js +64 -6
- package/dist/models/auth-cli.d.ts +1 -1
- package/dist/models/auth-cli.js +3 -2
- package/dist/paths.d.ts +0 -6
- package/dist/paths.js +0 -6
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/runtime/app-home.d.ts +32 -0
- package/dist/runtime/app-home.js +319 -0
- package/dist/runtime/bootstrap.d.ts +1 -67
- package/dist/runtime/bootstrap.js +114 -512
- package/dist/runtime/delivery.js +1 -1
- package/dist/runtime/dingtalk.d.ts +7 -6
- package/dist/runtime/dingtalk.js +5 -13
- package/dist/runtime/durable-dispatch.d.ts +1 -0
- package/dist/runtime/durable-dispatch.js +36 -25
- package/dist/runtime/subagent-commands.js +48 -10
- package/dist/runtime/task-wake.d.ts +54 -0
- package/dist/runtime/task-wake.js +99 -0
- package/dist/shared/host-process.d.ts +25 -9
- package/dist/shared/host-process.js +59 -10
- package/dist/shared/wake-claim.d.ts +23 -0
- package/dist/shared/wake-claim.js +26 -0
- package/dist/subagents/discovery.d.ts +25 -1
- package/dist/subagents/discovery.js +108 -17
- package/dist/subagents/external/claude-code.js +13 -5
- package/dist/subagents/external/codex-cli.js +9 -3
- package/dist/subagents/external/exec.js +1 -0
- package/dist/subagents/external/harness.d.ts +22 -0
- package/dist/subagents/external/harness.js +40 -7
- package/dist/subagents/external/run.d.ts +23 -3
- package/dist/subagents/external/run.js +113 -123
- package/dist/subagents/external/settlement.d.ts +50 -0
- package/dist/subagents/external/settlement.js +123 -0
- package/dist/subagents/format.d.ts +4 -0
- package/dist/subagents/format.js +7 -0
- package/dist/subagents/runs.d.ts +70 -13
- package/dist/subagents/runs.js +202 -118
- package/dist/subagents/tool.d.ts +27 -2
- package/dist/subagents/tool.js +92 -48
- package/dist/subagents/verification-outcome.d.ts +26 -0
- package/dist/subagents/verification-outcome.js +16 -0
- package/dist/subagents/workspace-lease.d.ts +10 -1
- package/dist/subagents/workspace-lease.js +15 -2
- package/dist/tools/index.js +6 -0
- package/dist/tools/memory-manage.js +0 -1
- package/dist/tools/subagent-manage.d.ts +20 -6
- package/dist/tools/subagent-manage.js +86 -16
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +3 -2
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +1 -1
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/examples/sub-agents/README.md +15 -14
- package/examples/sub-agents/builder-hard.md +9 -8
- package/examples/sub-agents/builder.md +12 -11
- package/examples/sub-agents/documenter.md +11 -12
- package/examples/sub-agents/explorer.md +16 -13
- package/examples/sub-agents/git-committer.md +17 -16
- package/examples/sub-agents/log-sifter.md +19 -16
- package/examples/sub-agents/planner.md +17 -17
- package/examples/sub-agents/reviewer.md +13 -21
- package/examples/sub-agents/scout.md +5 -4
- package/examples/sub-agents/verifier.md +8 -12
- package/examples/sub-agents/worker.md +7 -6
- package/package.json +1 -1
package/dist/memory/scheduler.js
CHANGED
|
@@ -6,9 +6,57 @@ import * as log from "../log.js";
|
|
|
6
6
|
import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
|
|
7
7
|
import { isChannelId } from "../runtime/channel-paths.js";
|
|
8
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
9
|
+
import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
|
|
9
10
|
import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
|
|
10
|
-
import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
|
|
11
|
+
import { getMemoryMaintenanceStateDir, readMemoryMaintenanceState } from "./maintenance-state.js";
|
|
11
12
|
const DEFAULT_TICK_INTERVAL_MS = 60_000;
|
|
13
|
+
/**
|
|
14
|
+
* Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
|
|
15
|
+
* resolution, settings reload) is paid for.
|
|
16
|
+
*
|
|
17
|
+
* Reuses the real gates with optimistic material (transcript-derived checks always pass), so the
|
|
18
|
+
* only work here is one state-file read plus timestamp arithmetic. A gate's material checks are
|
|
19
|
+
* purely additive restrictions on top of the cheap checks (interval/backoff/idle/dirty), so
|
|
20
|
+
* optimistic material can only ever make this predicate *more* permissive than the real job would
|
|
21
|
+
* be — it never wrongly skips a channel that a job would actually run for.
|
|
22
|
+
*/
|
|
23
|
+
async function mightAnyMaintenanceJobBeDue(input) {
|
|
24
|
+
const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
|
|
25
|
+
const sessionRefresh = shouldRunSessionRefresh({
|
|
26
|
+
now: input.now,
|
|
27
|
+
state,
|
|
28
|
+
sessionMemory: input.settings.sessionMemory,
|
|
29
|
+
maintenance: input.settings.memoryMaintenance,
|
|
30
|
+
channelActive: false,
|
|
31
|
+
hasNewSessionEntry: () => true,
|
|
32
|
+
hasMeaningfulMaterial: () => true,
|
|
33
|
+
});
|
|
34
|
+
if (sessionRefresh.allowed)
|
|
35
|
+
return true;
|
|
36
|
+
const checkpoint = shouldRunMemoryCheckpoint({
|
|
37
|
+
now: input.now,
|
|
38
|
+
state,
|
|
39
|
+
maintenance: input.settings.memoryMaintenance,
|
|
40
|
+
channelActive: false,
|
|
41
|
+
material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true, batchSize: Number.MAX_SAFE_INTEGER }),
|
|
42
|
+
});
|
|
43
|
+
if (checkpoint.allowed)
|
|
44
|
+
return true;
|
|
45
|
+
const structural = await shouldRunStructuralMaintenance({
|
|
46
|
+
now: input.now,
|
|
47
|
+
state,
|
|
48
|
+
maintenance: input.settings.memoryMaintenance,
|
|
49
|
+
channelActive: false,
|
|
50
|
+
material: async () => ({
|
|
51
|
+
memoryCleanupNeeded: true,
|
|
52
|
+
historyFoldingNeeded: true,
|
|
53
|
+
hasMemoryContent: true,
|
|
54
|
+
hasHistoryContent: true,
|
|
55
|
+
expiredEntryCount: 1,
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
return structural.allowed;
|
|
59
|
+
}
|
|
12
60
|
async function listStateChannels(appHomeDir) {
|
|
13
61
|
try {
|
|
14
62
|
const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
|
|
@@ -47,9 +95,12 @@ export class MemoryMaintenanceScheduler {
|
|
|
47
95
|
this.nextChannelIndex = 0;
|
|
48
96
|
}
|
|
49
97
|
start() {
|
|
50
|
-
if (this.timer
|
|
98
|
+
if (this.timer) {
|
|
51
99
|
return;
|
|
52
100
|
}
|
|
101
|
+
// `enabled` is re-checked on every tick inside `runOnce`, which is nearly free when
|
|
102
|
+
// disabled (one cached settings read, no channel scan). Gating `start()` on it too would
|
|
103
|
+
// mean flipping `memoryMaintenance.enabled` on at runtime never actually starts the timer.
|
|
53
104
|
this.timer = setInterval(() => {
|
|
54
105
|
void this.runOnce().catch((error) => {
|
|
55
106
|
log.logWarning("Memory maintenance scheduler tick failed", errorMessage(error));
|
|
@@ -65,8 +116,8 @@ export class MemoryMaintenanceScheduler {
|
|
|
65
116
|
this.timer = null;
|
|
66
117
|
}
|
|
67
118
|
async runOnce(now = new Date()) {
|
|
68
|
-
const settings = this.options.getSettings()
|
|
69
|
-
if (!settings.enabled || this.running) {
|
|
119
|
+
const settings = this.options.getSettings();
|
|
120
|
+
if (!settings.memoryMaintenance.enabled || this.running) {
|
|
70
121
|
return;
|
|
71
122
|
}
|
|
72
123
|
this.running = true;
|
|
@@ -76,7 +127,7 @@ export class MemoryMaintenanceScheduler {
|
|
|
76
127
|
workspaceDir: this.options.workspaceDir,
|
|
77
128
|
knownChannelIds: this.options.getKnownChannelIds?.(),
|
|
78
129
|
});
|
|
79
|
-
const maxConcurrent = normalizeMaxConcurrentChannels(settings.maxConcurrentChannels);
|
|
130
|
+
const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
|
|
80
131
|
if (channelIds.length === 0) {
|
|
81
132
|
return;
|
|
82
133
|
}
|
|
@@ -85,7 +136,14 @@ export class MemoryMaintenanceScheduler {
|
|
|
85
136
|
let index = this.nextChannelIndex % channelIds.length;
|
|
86
137
|
while (scanned < channelIds.length && selected.length < maxConcurrent) {
|
|
87
138
|
const channelId = channelIds[index];
|
|
88
|
-
if (channelId &&
|
|
139
|
+
if (channelId &&
|
|
140
|
+
!this.options.isChannelActive(channelId) &&
|
|
141
|
+
(await mightAnyMaintenanceJobBeDue({
|
|
142
|
+
appHomeDir: this.options.appHomeDir,
|
|
143
|
+
channelId,
|
|
144
|
+
settings,
|
|
145
|
+
now,
|
|
146
|
+
}))) {
|
|
89
147
|
selected.push(channelId);
|
|
90
148
|
}
|
|
91
149
|
index = (index + 1) % channelIds.length;
|
package/dist/models/auth-cli.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { createInterface } from "node:readline/promises";
|
|
9
9
|
import * as log from "../log.js";
|
|
10
|
-
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS,
|
|
10
|
+
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
|
|
11
|
+
import { prepareAppServices } from "../runtime/bootstrap.js";
|
|
11
12
|
import { ReadlineLoginUi } from "./login-ui.js";
|
|
12
13
|
import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
|
|
13
14
|
import { createModelRuntime, formatModelReference } from "./utils.js";
|
|
@@ -317,7 +318,7 @@ export async function runAuth(argv, io = console, paths = DEFAULT_BOOTSTRAP_PATH
|
|
|
317
318
|
io.error("pipiclaw auth login/logout requires an interactive terminal (stdin is not a TTY).");
|
|
318
319
|
throw new BootstrapExitError(1);
|
|
319
320
|
}
|
|
320
|
-
printBootstrapSummary(bootstrapAppHome(paths
|
|
321
|
+
printBootstrapSummary(bootstrapAppHome(paths), io, paths);
|
|
321
322
|
prepareAppServices(paths);
|
|
322
323
|
const runtime = await createModelRuntime({
|
|
323
324
|
authConfigPath: paths.authConfigPath,
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
export declare const APP_NAME = "pipiclaw";
|
|
2
2
|
/** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
|
|
3
3
|
export declare const PLAYBOOKS_DIR: string;
|
|
4
|
-
/**
|
|
5
|
-
* Legacy default app home used before the `~/.pipiclaw` default (introduced in
|
|
6
|
-
* 0.8.x). Kept only so bootstrap can migrate an existing install to the new
|
|
7
|
-
* default. FIXME(0.9.0): drop this together with the migration in bootstrap.ts.
|
|
8
|
-
*/
|
|
9
|
-
export declare const LEGACY_APP_HOME_DIR: string;
|
|
10
4
|
/** The built-in default app home, independent of any `PIPICLAW_HOME` override. */
|
|
11
5
|
export declare const DEFAULT_APP_HOME_DIR: string;
|
|
12
6
|
export declare const APP_HOME_DIR: string;
|
package/dist/paths.js
CHANGED
|
@@ -12,12 +12,6 @@ const bundledPlaybooksDir = fileURLToPath(new URL("./playbooks", import.meta.url
|
|
|
12
12
|
const checkoutPlaybooksDir = fileURLToPath(new URL("../src/playbooks", import.meta.url));
|
|
13
13
|
/** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
|
|
14
14
|
export const PLAYBOOKS_DIR = existsSync(checkoutPlaybooksDir) ? checkoutPlaybooksDir : bundledPlaybooksDir;
|
|
15
|
-
/**
|
|
16
|
-
* Legacy default app home used before the `~/.pipiclaw` default (introduced in
|
|
17
|
-
* 0.8.x). Kept only so bootstrap can migrate an existing install to the new
|
|
18
|
-
* default. FIXME(0.9.0): drop this together with the migration in bootstrap.ts.
|
|
19
|
-
*/
|
|
20
|
-
export const LEGACY_APP_HOME_DIR = join(homedir(), ".pi", APP_NAME);
|
|
21
15
|
/** The built-in default app home, independent of any `PIPICLAW_HOME` override. */
|
|
22
16
|
export const DEFAULT_APP_HOME_DIR = join(homedir(), `.${APP_NAME}`);
|
|
23
17
|
export const APP_HOME_DIR = process.env.PIPICLAW_HOME ?? DEFAULT_APP_HOME_DIR;
|
|
@@ -40,7 +40,7 @@ order: 36
|
|
|
40
40
|
|
|
41
41
|
- **每次委派都显式传 `workingDirectory`**,不要依赖默认值。
|
|
42
42
|
- **并行的写入分片各自 `git worktree add` 后指向不同 checkout**,绝不让两个写入者共享一棵树。
|
|
43
|
-
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId
|
|
43
|
+
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。**这把锁只保护声明了 `mutates: write` 的委派**——内置角色的 `mutates` 是按 `tools` 推定(只看 `write`/`edit`,不看 `bash`),外部角色是自述,两者都可能与角色实际行为不符,写清楚 `mutates` 是你的责任,不是 runtime 能替你核实的事。
|
|
44
44
|
- **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
|
|
45
45
|
- **创建的 worktree 在使用结束后要记得关闭**
|
|
46
46
|
|
|
@@ -57,7 +57,7 @@ order: 36
|
|
|
57
57
|
## 五、纠偏与续接
|
|
58
58
|
|
|
59
59
|
- `subagent_manage op=cancel <runId>`:提前终止。**`/stop` 不会连带停止已派发的委派**,这是有意的——停止一个正在写工作区的进程永远需要一次显式决定。取消不产生唤醒,因为那是你自己的决定。
|
|
60
|
-
- `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId
|
|
60
|
+
- `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId`,同样异步唤醒,走与首次派发相同的信封(运行时上下文、上下文块、verify 协议)。内置 run 和 `exec` 不支持续接(内置的隔离上下文本就不持久化),改为带着上一轮产出开一个新委派。角色的 `command`/`model`/`shell` 若在两次派发之间变过,续接会被拒绝——把变化当作"开新任务"而不是想办法绕过去。
|
|
61
61
|
- 不要仅因为耗时长就中断在跑的委派。只在明确阻塞、循环、崩溃、需要纠偏或用户要求时才取消。
|
|
62
62
|
|
|
63
63
|
## 六、产物与验收
|
|
@@ -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.
|