@oyasmi/pipiclaw 0.9.0-beta.9 → 0.9.0
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 +7 -0
- package/dist/agent/channel-runner.js +52 -8
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +9 -0
- package/dist/agent/job-manager.d.ts +20 -0
- package/dist/agent/job-manager.js +14 -0
- package/dist/agent/turn-recovery.d.ts +72 -0
- package/dist/agent/turn-recovery.js +193 -0
- package/dist/playbooks/agent-delegation.md +3 -3
- package/dist/playbooks/runtime-orientation.md +5 -0
- package/dist/runtime/active-session-store.d.ts +42 -0
- package/dist/runtime/active-session-store.js +100 -0
- package/dist/runtime/bootstrap.js +48 -3
- package/dist/runtime/dingtalk.js +2 -1
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +112 -0
- package/dist/runtime/project-scope-store.d.ts +31 -0
- package/dist/runtime/project-scope-store.js +102 -0
- package/dist/security/config.js +10 -0
- package/dist/security/path-guard.js +34 -9
- package/dist/security/project-scope.d.ts +45 -0
- package/dist/security/project-scope.js +107 -0
- package/dist/security/types.d.ts +20 -2
- package/dist/subagents/tool.d.ts +2 -0
- package/dist/subagents/tool.js +8 -2
- package/dist/tools/bash.js +3 -3
- package/dist/tools/edit.js +3 -3
- package/dist/tools/grep.js +3 -3
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/read.js +3 -3
- package/dist/tools/registry.js +1 -1
- package/dist/tools/send-media.js +2 -2
- package/dist/tools/write-content.js +3 -3
- package/dist/tui/app.js +47 -1
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
4
|
+
const REF_FILENAME = "active-session.json";
|
|
5
|
+
const DEFAULT_SESSION_FILENAME = "context.jsonl";
|
|
6
|
+
export function getActiveSessionRefPath(channelDir) {
|
|
7
|
+
return join(channelDir, REF_FILENAME);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The ref's `file` is opened for append under `channelDir`, and the ref itself lives in a
|
|
11
|
+
* directory a chat participant can otherwise influence the contents of. Reject anything that
|
|
12
|
+
* isn't a plain, single-segment `.jsonl` name so this can never be used to open or create a file
|
|
13
|
+
* outside the channel directory.
|
|
14
|
+
*/
|
|
15
|
+
export function isValidSessionRefBasename(file) {
|
|
16
|
+
return (typeof file === "string" &&
|
|
17
|
+
file.length > 0 &&
|
|
18
|
+
file.endsWith(".jsonl") &&
|
|
19
|
+
!file.includes("/") &&
|
|
20
|
+
!file.includes("\\") &&
|
|
21
|
+
!file.includes("\0") &&
|
|
22
|
+
file !== "." &&
|
|
23
|
+
file !== "..");
|
|
24
|
+
}
|
|
25
|
+
function readActiveSessionRef(channelDir) {
|
|
26
|
+
const refPath = getActiveSessionRefPath(channelDir);
|
|
27
|
+
if (!existsSync(refPath)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
let raw;
|
|
31
|
+
try {
|
|
32
|
+
raw = JSON.parse(readFileSync(refPath, "utf-8"));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (!raw ||
|
|
38
|
+
typeof raw !== "object" ||
|
|
39
|
+
raw.version !== 1 ||
|
|
40
|
+
typeof raw.file !== "string" ||
|
|
41
|
+
typeof raw.sessionId !== "string" ||
|
|
42
|
+
typeof raw.updatedAt !== "string") {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const ref = raw;
|
|
46
|
+
return isValidSessionRefBasename(ref.file) ? ref : undefined;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* An existing-but-empty file makes the SDK's `SessionManager._setSessionFile()` write the header
|
|
50
|
+
* and flip `flushed = true` synchronously, instead of the deferred-flush path it takes for a file
|
|
51
|
+
* that doesn't exist yet. Materializing this before `SessionManager.open()` closes the delay
|
|
52
|
+
* window described in spec 043 F4/D1.2 without touching SDK internals.
|
|
53
|
+
*/
|
|
54
|
+
function materializeSessionFile(channelDir, file) {
|
|
55
|
+
const target = join(channelDir, file);
|
|
56
|
+
if (!existsSync(target)) {
|
|
57
|
+
closeSync(openSync(target, "a"));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Resolves which session file a channel should open (runner construction / restart), migrating a
|
|
62
|
+
* channel with no ref to `context.jsonl` and materializing that file. Never writes the ref
|
|
63
|
+
* itself — a missing ref stays missing until a session-topology operation commits one.
|
|
64
|
+
*/
|
|
65
|
+
export function resolveActiveSessionFile(channelDir) {
|
|
66
|
+
const ref = readActiveSessionRef(channelDir);
|
|
67
|
+
const file = ref?.file ?? DEFAULT_SESSION_FILENAME;
|
|
68
|
+
materializeSessionFile(channelDir, file);
|
|
69
|
+
return file;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Commits the active-session ref for a session a topology operation (`/new`, fork, switch) has
|
|
73
|
+
* already created/opened. The SDK writes that session's durable header synchronously before
|
|
74
|
+
* invoking the caller's rebuild callback, so by the time this is called the target file already
|
|
75
|
+
* exists on disk; this only records the pointer. Callers must not rebind their live `AgentSession`
|
|
76
|
+
* until this resolves (spec 043, D1.3) — on throw, nothing is written and the old ref (and thus
|
|
77
|
+
* the old session) remains authoritative.
|
|
78
|
+
*/
|
|
79
|
+
export async function commitActiveSessionRef(channelDir, session) {
|
|
80
|
+
const sessionFile = session.getSessionFile();
|
|
81
|
+
if (!sessionFile) {
|
|
82
|
+
throw new Error("Cannot commit active-session ref: session has no backing file (not persisted).");
|
|
83
|
+
}
|
|
84
|
+
const resolvedDir = resolve(channelDir);
|
|
85
|
+
const resolvedFile = resolve(sessionFile);
|
|
86
|
+
if (dirname(resolvedFile) !== resolvedDir) {
|
|
87
|
+
throw new Error(`Session file must live directly under the channel directory: ${sessionFile}`);
|
|
88
|
+
}
|
|
89
|
+
const file = basename(resolvedFile);
|
|
90
|
+
if (!isValidSessionRefBasename(file)) {
|
|
91
|
+
throw new Error(`Invalid session file name for active-session ref: ${file}`);
|
|
92
|
+
}
|
|
93
|
+
const ref = {
|
|
94
|
+
version: 1,
|
|
95
|
+
file,
|
|
96
|
+
sessionId: session.getSessionId(),
|
|
97
|
+
updatedAt: new Date().toISOString(),
|
|
98
|
+
};
|
|
99
|
+
await writeFileAtomically(getActiveSessionRefPath(channelDir), `${JSON.stringify(ref, null, 2)}\n`);
|
|
100
|
+
}
|
|
@@ -3,13 +3,15 @@ import { join } from "path";
|
|
|
3
3
|
import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
|
|
4
4
|
import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
|
|
5
5
|
import { createRunner } from "../agent/index.js";
|
|
6
|
-
import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
6
|
+
import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
7
7
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
8
8
|
import { renderStatus } from "../agent/status-render.js";
|
|
9
|
+
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
9
10
|
import { createExecutor } from "../executor.js";
|
|
10
11
|
import * as log from "../log.js";
|
|
11
12
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
12
13
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
14
|
+
import { defaultModel } from "../models/utils.js";
|
|
13
15
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
14
16
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
15
17
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
@@ -17,7 +19,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
|
17
19
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
18
20
|
import { errorMessage } from "../shared/text-utils.js";
|
|
19
21
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
20
|
-
import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentGarbageCollector } from "../subagents/runs.js";
|
|
22
|
+
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
|
|
21
23
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
22
24
|
import { finishTaskAttempt } from "../tasks/store.js";
|
|
23
25
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -31,6 +33,7 @@ import { DingTalkBot, } from "./dingtalk.js";
|
|
|
31
33
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
32
34
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
33
35
|
import { createEventsWatcher } from "./events.js";
|
|
36
|
+
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
34
37
|
import { installLlmProxy } from "./proxy.js";
|
|
35
38
|
import { ChannelStore } from "./store.js";
|
|
36
39
|
import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
@@ -90,7 +93,7 @@ function isNoRunningTaskQueueError(err) {
|
|
|
90
93
|
* idle answers it through the runner's ChannelContext-aware command path (thread-reply, delete
|
|
91
94
|
* semantics) instead, so it is not part of this stateless-report dispatch here.
|
|
92
95
|
*/
|
|
93
|
-
const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents"]);
|
|
96
|
+
const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents", "project"]);
|
|
94
97
|
function isIdleRuntimeCommandName(name) {
|
|
95
98
|
return IDLE_RUNTIME_COMMAND_NAMES.has(name);
|
|
96
99
|
}
|
|
@@ -304,6 +307,31 @@ export async function createRuntimeContext(options) {
|
|
|
304
307
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
305
308
|
}),
|
|
306
309
|
});
|
|
310
|
+
case "project":
|
|
311
|
+
return runProjectCommand({
|
|
312
|
+
args,
|
|
313
|
+
channelId: event.channelId,
|
|
314
|
+
channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
|
|
315
|
+
appHomeDir: options.paths.appHomeDir,
|
|
316
|
+
actor: "dingtalk-command",
|
|
317
|
+
isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
|
|
318
|
+
listActiveBlockers: () => [
|
|
319
|
+
...getSubAgentRunManager(event.channelId)
|
|
320
|
+
.list()
|
|
321
|
+
.filter((record) => record.status === "running")
|
|
322
|
+
.map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
|
|
323
|
+
...channelRunningJobLines(event.channelId),
|
|
324
|
+
],
|
|
325
|
+
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
326
|
+
// The active-session ref is untouched — same session, new project root.
|
|
327
|
+
onScopeChanged: async () => {
|
|
328
|
+
const runner = channelRunners.get(event.channelId);
|
|
329
|
+
channelRunners.delete(event.channelId);
|
|
330
|
+
await runner?.dispose().catch((err) => {
|
|
331
|
+
log.logWarning(`[${event.channelId}] Failed to dispose runner after /project`, errorMessage(err));
|
|
332
|
+
});
|
|
333
|
+
},
|
|
334
|
+
});
|
|
307
335
|
}
|
|
308
336
|
},
|
|
309
337
|
async handleBusyMessage(event, bot, mode, queueText) {
|
|
@@ -563,6 +591,23 @@ export async function createRuntimeContext(options) {
|
|
|
563
591
|
// for background jobs.
|
|
564
592
|
await restoreChannelJobs(executor);
|
|
565
593
|
await restoreAllSubAgentRuns();
|
|
594
|
+
// Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
|
|
595
|
+
// admission — a message routed to a still-dangling session would 400 against the provider on
|
|
596
|
+
// every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
|
|
597
|
+
// the job/run restores above: admission must see a structurally legal session, not a partial one.
|
|
598
|
+
const recoveryReport = await scanWorkspaceForInterruptedTurns(options.paths.workspaceDir, {
|
|
599
|
+
api: defaultModel.api,
|
|
600
|
+
provider: defaultModel.provider,
|
|
601
|
+
model: defaultModel.id,
|
|
602
|
+
});
|
|
603
|
+
if (recoveryReport.repaired.length > 0) {
|
|
604
|
+
log.logWarning("Repaired interrupted turns on restart", `${recoveryReport.repaired.length}/${recoveryReport.scanned} channel(s): ${recoveryReport.repaired
|
|
605
|
+
.map((r) => r.channelDir)
|
|
606
|
+
.join(", ")}`);
|
|
607
|
+
}
|
|
608
|
+
if (recoveryReport.blocked.length > 0) {
|
|
609
|
+
log.logWarning("Some channels have an unrecoverable session and will refuse new turns", recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "));
|
|
610
|
+
}
|
|
566
611
|
const eventsWatcher = options.createEventsWatcher
|
|
567
612
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
568
613
|
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -1098,7 +1098,8 @@ export class DingTalkBot {
|
|
|
1098
1098
|
case "status":
|
|
1099
1099
|
case "usage":
|
|
1100
1100
|
case "context":
|
|
1101
|
-
case "subagents":
|
|
1101
|
+
case "subagents":
|
|
1102
|
+
case "project": {
|
|
1102
1103
|
const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
|
|
1103
1104
|
await this.sendPlain(channelId, response);
|
|
1104
1105
|
return;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface HandleProjectCommandOptions {
|
|
2
|
+
args: string;
|
|
3
|
+
channelId: string;
|
|
4
|
+
channelDir: string;
|
|
5
|
+
appHomeDir: string;
|
|
6
|
+
actor: "dingtalk-command" | "tui-command";
|
|
7
|
+
/** True while a turn is in flight for this channel; blocks `set`/`reset` (D1.3/D4.2). */
|
|
8
|
+
isBusy: () => boolean;
|
|
9
|
+
/** Non-empty user-facing lines naming a running job/subagent that must finish or be cancelled
|
|
10
|
+
* first (D4.3) — sleeping tasks are deliberately not included here. */
|
|
11
|
+
listActiveBlockers: () => Promise<string[]> | string[];
|
|
12
|
+
/** Runs after a successful commit so the caller can dispose its cached runner for this channel
|
|
13
|
+
* and let the next access rebuild it under the new scope (D4.2). Not called on any failure path. */
|
|
14
|
+
onScopeChanged?: () => Promise<void> | void;
|
|
15
|
+
}
|
|
16
|
+
export declare function handleProjectCommand(options: HandleProjectCommandOptions): Promise<string>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
2
|
+
import { currentProjectSandboxStatus, isWithinAllowedRoots, resolveExistingDirectory, resolveProjectAccessPolicy, } from "../security/project-scope.js";
|
|
3
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
import { commitProjectSelection, readProjectSelection } from "./project-scope-store.js";
|
|
5
|
+
function usage() {
|
|
6
|
+
return `# 项目作用域
|
|
7
|
+
|
|
8
|
+
用法:
|
|
9
|
+
|
|
10
|
+
- \`/project\` — 查看当前频道的项目目录与访问边界
|
|
11
|
+
- \`/project set <absolute-path>\` — 切换项目目录(需频道空闲,且目录在允许的可选根内)
|
|
12
|
+
- \`/project reset\` — 切回 app 默认项目目录`;
|
|
13
|
+
}
|
|
14
|
+
function parseProjectCommand(args) {
|
|
15
|
+
const trimmed = args.trim();
|
|
16
|
+
if (!trimmed)
|
|
17
|
+
return { action: "show" };
|
|
18
|
+
const parts = trimmed.split(/\s+/);
|
|
19
|
+
if (parts[0] === "set") {
|
|
20
|
+
if (!parts[1] || parts.length > 2)
|
|
21
|
+
throw new Error("用法:/project set <absolute-path>");
|
|
22
|
+
return { action: "set", path: parts[1] };
|
|
23
|
+
}
|
|
24
|
+
if (parts[0] === "reset") {
|
|
25
|
+
if (parts.length > 1)
|
|
26
|
+
throw new Error("用法:/project reset");
|
|
27
|
+
return { action: "reset" };
|
|
28
|
+
}
|
|
29
|
+
throw new Error(`未知的 /project 子命令:${parts[0]}`);
|
|
30
|
+
}
|
|
31
|
+
function formatShow(options) {
|
|
32
|
+
const securityLoad = loadSecurityConfigWithDiagnostics(options.appHomeDir);
|
|
33
|
+
const resolution = resolveProjectAccessPolicy(securityLoad.config, process.cwd());
|
|
34
|
+
const sandbox = currentProjectSandboxStatus();
|
|
35
|
+
const selection = readProjectSelection(options.channelDir);
|
|
36
|
+
const lines = ["# 项目作用域", ""];
|
|
37
|
+
if (!selection) {
|
|
38
|
+
lines.push(`项目目录:\`${resolution.policy.defaultRoot}\`(尚未选择过,将在下次准入时采用 app 默认值)`);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
lines.push(`项目目录:\`${selection.projectRoot}\`(${selection.updatedBy},更新于 ${selection.updatedAt})`);
|
|
42
|
+
}
|
|
43
|
+
lines.push(`边界:${resolution.configured ? "project(文件工具被约束在此目录内)" : "unbounded(沿用旧的全局文件权限)"}`);
|
|
44
|
+
lines.push(`Enforcement:${sandbox.level}(${sandbox.summary})`);
|
|
45
|
+
if (!resolution.configured) {
|
|
46
|
+
lines.push("", `未配置 projectAccess:\`/project set\` 不可用。在 \`security.json\` 写入 projectAccess 段后即可使用。`);
|
|
47
|
+
}
|
|
48
|
+
else if (!resolution.mutable) {
|
|
49
|
+
lines.push("", "projectAccess.defaultRoot 配置有误,项目切换已被禁用,见启动诊断。");
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
lines.push("", `可选根:${resolution.policy.allowedRoots.map((root) => `\`${root}\``).join("、")}`);
|
|
53
|
+
}
|
|
54
|
+
for (const diagnostic of resolution.diagnostics) {
|
|
55
|
+
lines.push(`⚠ ${diagnostic.message}`);
|
|
56
|
+
}
|
|
57
|
+
return lines.join("\n");
|
|
58
|
+
}
|
|
59
|
+
async function applyScopeChange(options, requestedPath, label) {
|
|
60
|
+
const securityLoad = loadSecurityConfigWithDiagnostics(options.appHomeDir);
|
|
61
|
+
const resolution = resolveProjectAccessPolicy(securityLoad.config, process.cwd());
|
|
62
|
+
if (!resolution.configured) {
|
|
63
|
+
return `无法切换项目:未配置 projectAccess。在 \`security.json\` 写入 projectAccess 段(defaultRoot/allowedRoots)后重试。`;
|
|
64
|
+
}
|
|
65
|
+
if (!resolution.mutable) {
|
|
66
|
+
return `无法切换项目:projectAccess.defaultRoot 配置有误(见启动诊断),项目切换已被禁用直到修复。`;
|
|
67
|
+
}
|
|
68
|
+
const real = resolveExistingDirectory(requestedPath);
|
|
69
|
+
if (!real) {
|
|
70
|
+
return `无法切换项目:\`${requestedPath}\` 不是一个存在的绝对目录。`;
|
|
71
|
+
}
|
|
72
|
+
if (!isWithinAllowedRoots(real, resolution.policy)) {
|
|
73
|
+
return `无法切换项目:\`${real}\` 不在允许的可选根内。可选根:${resolution.policy.allowedRoots
|
|
74
|
+
.map((root) => `\`${root}\``)
|
|
75
|
+
.join("、")}。`;
|
|
76
|
+
}
|
|
77
|
+
if (options.isBusy()) {
|
|
78
|
+
return "无法切换项目:当前频道有回合正在进行,请等待结束后重试。";
|
|
79
|
+
}
|
|
80
|
+
const blockers = await options.listActiveBlockers();
|
|
81
|
+
if (blockers.length > 0) {
|
|
82
|
+
return `无法切换项目:\n${blockers.map((line) => `- ${line}`).join("\n")}\n\n结束或取消上述项后重试。`;
|
|
83
|
+
}
|
|
84
|
+
await commitProjectSelection(options.channelDir, real, options.actor);
|
|
85
|
+
await options.onScopeChanged?.();
|
|
86
|
+
return `${label}:\`${real}\`。下一次消息将在新的项目目录下运行。`;
|
|
87
|
+
}
|
|
88
|
+
export async function handleProjectCommand(options) {
|
|
89
|
+
let command;
|
|
90
|
+
try {
|
|
91
|
+
command = parseProjectCommand(options.args);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
return `${errorMessage(error)}\n\n${usage()}`;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
switch (command.action) {
|
|
98
|
+
case "show":
|
|
99
|
+
return formatShow(options);
|
|
100
|
+
case "set":
|
|
101
|
+
return await applyScopeChange(options, command.path, "已切换项目");
|
|
102
|
+
case "reset": {
|
|
103
|
+
const securityLoad = loadSecurityConfigWithDiagnostics(options.appHomeDir);
|
|
104
|
+
const resolution = resolveProjectAccessPolicy(securityLoad.config, process.cwd());
|
|
105
|
+
return await applyScopeChange(options, resolution.policy.defaultRoot, "已重置项目");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
return `执行 /project ${command.action} 失败:${errorMessage(error)}`;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ProjectAccessPolicy, type ProjectScope } from "../security/project-scope.js";
|
|
2
|
+
/** A channel's persisted project selection (D3.3). Never holds messages, only the choice itself. */
|
|
3
|
+
export interface PersistedProjectSelectionV1 {
|
|
4
|
+
version: 1;
|
|
5
|
+
/** Realpath. */
|
|
6
|
+
projectRoot: string;
|
|
7
|
+
updatedAt: string;
|
|
8
|
+
updatedBy: "migration" | "dingtalk-command" | "tui-command";
|
|
9
|
+
}
|
|
10
|
+
export declare function getProjectSelectionPath(channelDir: string): string;
|
|
11
|
+
export declare function readProjectSelection(channelDir: string): PersistedProjectSelectionV1 | undefined;
|
|
12
|
+
export declare function commitProjectSelection(channelDir: string, projectRoot: string, updatedBy: PersistedProjectSelectionV1["updatedBy"]): Promise<PersistedProjectSelectionV1>;
|
|
13
|
+
export type ProjectScopeOutcome = {
|
|
14
|
+
kind: "ready";
|
|
15
|
+
scope: ProjectScope;
|
|
16
|
+
selection: PersistedProjectSelectionV1;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "blocked";
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Resolves the effective `ProjectScope` for a channel: its persisted selection if present and
|
|
23
|
+
* still valid, else the app default — materialized as the channel's first selection so a later
|
|
24
|
+
* daemon restart from a different startup cwd cannot silently move the channel (D3.3). Never
|
|
25
|
+
* falls back to a different root once one has been persisted (P7): a stale or now-disallowed
|
|
26
|
+
* selection blocks instead of guessing.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveProjectScope(channelDir: string, resolution: {
|
|
29
|
+
policy: ProjectAccessPolicy;
|
|
30
|
+
configured: boolean;
|
|
31
|
+
}): ProjectScopeOutcome;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { currentProjectSandboxStatus, isWithinAllowedRoots, } from "../security/project-scope.js";
|
|
5
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
|
+
const SELECTION_FILENAME = "project.json";
|
|
7
|
+
export function getProjectSelectionPath(channelDir) {
|
|
8
|
+
return join(channelDir, SELECTION_FILENAME);
|
|
9
|
+
}
|
|
10
|
+
export function readProjectSelection(channelDir) {
|
|
11
|
+
const path = getProjectSelectionPath(channelDir);
|
|
12
|
+
if (!existsSync(path)) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
let raw;
|
|
16
|
+
try {
|
|
17
|
+
raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
if (!raw ||
|
|
23
|
+
typeof raw !== "object" ||
|
|
24
|
+
raw.version !== 1 ||
|
|
25
|
+
typeof raw.projectRoot !== "string" ||
|
|
26
|
+
typeof raw.updatedAt !== "string" ||
|
|
27
|
+
typeof raw.updatedBy !== "string") {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
return raw;
|
|
31
|
+
}
|
|
32
|
+
/** Same durability tradeoff as every other atomic writer in this codebase (temp + rename), minus
|
|
33
|
+
* the fsync `writeFileAtomically` does — used only for the one-time, in-constructor migration
|
|
34
|
+
* write (D3.3); every explicit mutation (`/project set|reset`) goes through the fsync'd async
|
|
35
|
+
* `writeFileAtomically` in `commitProjectSelection` instead. */
|
|
36
|
+
function writeProjectSelectionSync(channelDir, selection) {
|
|
37
|
+
const path = getProjectSelectionPath(channelDir);
|
|
38
|
+
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
39
|
+
writeFileSync(tempPath, `${JSON.stringify(selection, null, 2)}\n`, "utf-8");
|
|
40
|
+
renameSync(tempPath, path);
|
|
41
|
+
}
|
|
42
|
+
export async function commitProjectSelection(channelDir, projectRoot, updatedBy) {
|
|
43
|
+
const selection = {
|
|
44
|
+
version: 1,
|
|
45
|
+
projectRoot,
|
|
46
|
+
updatedAt: new Date().toISOString(),
|
|
47
|
+
updatedBy,
|
|
48
|
+
};
|
|
49
|
+
await writeFileAtomically(getProjectSelectionPath(channelDir), `${JSON.stringify(selection, null, 2)}\n`);
|
|
50
|
+
return selection;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Resolves the effective `ProjectScope` for a channel: its persisted selection if present and
|
|
54
|
+
* still valid, else the app default — materialized as the channel's first selection so a later
|
|
55
|
+
* daemon restart from a different startup cwd cannot silently move the channel (D3.3). Never
|
|
56
|
+
* falls back to a different root once one has been persisted (P7): a stale or now-disallowed
|
|
57
|
+
* selection blocks instead of guessing.
|
|
58
|
+
*/
|
|
59
|
+
export function resolveProjectScope(channelDir, resolution) {
|
|
60
|
+
const sandbox = currentProjectSandboxStatus();
|
|
61
|
+
const boundary = resolution.configured ? "project" : "unbounded";
|
|
62
|
+
const existing = readProjectSelection(channelDir);
|
|
63
|
+
if (!existing) {
|
|
64
|
+
const selection = {
|
|
65
|
+
version: 1,
|
|
66
|
+
projectRoot: resolution.policy.defaultRoot,
|
|
67
|
+
updatedAt: new Date().toISOString(),
|
|
68
|
+
updatedBy: "migration",
|
|
69
|
+
};
|
|
70
|
+
writeProjectSelectionSync(channelDir, selection);
|
|
71
|
+
return { kind: "ready", scope: { projectRoot: resolution.policy.defaultRoot, boundary, sandbox }, selection };
|
|
72
|
+
}
|
|
73
|
+
if (!existsSync(existing.projectRoot)) {
|
|
74
|
+
return {
|
|
75
|
+
kind: "blocked",
|
|
76
|
+
reason: `项目目录已不存在:${existing.projectRoot}。请恢复该目录,或在频道空闲时执行 /project set <path> 或 /project reset。`,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
let real;
|
|
80
|
+
try {
|
|
81
|
+
real = realpathSync(existing.projectRoot);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return {
|
|
85
|
+
kind: "blocked",
|
|
86
|
+
reason: `项目目录不可读:${existing.projectRoot}。请检查权限,或在频道空闲时执行 /project set <path>。`,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (real !== existing.projectRoot) {
|
|
90
|
+
return {
|
|
91
|
+
kind: "blocked",
|
|
92
|
+
reason: `项目目录 ${existing.projectRoot} 现在指向 ${real}(symlink 已被重新指向),与上次选择不一致。请在频道空闲时执行 /project set <path> 确认新目标,或 /project reset。`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (resolution.configured && !isWithinAllowedRoots(real, resolution.policy)) {
|
|
96
|
+
return {
|
|
97
|
+
kind: "blocked",
|
|
98
|
+
reason: `项目目录 ${real} 已不在允许的可选根内(security.json 的 projectAccess 已变更)。请在频道空闲时执行 /project set <path> 或 /project reset。`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return { kind: "ready", scope: { projectRoot: real, boundary, sandbox }, selection: existing };
|
|
102
|
+
}
|
package/dist/security/config.js
CHANGED
|
@@ -67,6 +67,10 @@ function mergeSecurityConfig(source, configPath, diagnostics) {
|
|
|
67
67
|
const pathGuard = isRecord(source.pathGuard) ? source.pathGuard : {};
|
|
68
68
|
const networkGuard = isRecord(source.networkGuard) ? source.networkGuard : {};
|
|
69
69
|
const audit = isRecord(source.audit) ? source.audit : {};
|
|
70
|
+
// Unlike the sections above, presence itself is meaningful (D3.2): a missing `projectAccess`
|
|
71
|
+
// key must stay `undefined`, not fall back to `{}`, so the resolver in project-scope.ts can
|
|
72
|
+
// tell "never configured" apart from "configured with defaults".
|
|
73
|
+
const projectAccess = isRecord(source.projectAccess) ? source.projectAccess : undefined;
|
|
70
74
|
if (networkGuard.maxRedirects !== undefined) {
|
|
71
75
|
const maxRedirects = networkGuard.maxRedirects;
|
|
72
76
|
const isValidMaxRedirects = typeof maxRedirects === "number" && Number.isFinite(maxRedirects) && maxRedirects > 0;
|
|
@@ -112,6 +116,12 @@ function mergeSecurityConfig(source, configPath, diagnostics) {
|
|
|
112
116
|
logBlocked: typeof audit.logBlocked === "boolean" ? audit.logBlocked : DEFAULT_SECURITY_CONFIG.audit.logBlocked,
|
|
113
117
|
logFile: asOptionalString(audit.logFile),
|
|
114
118
|
},
|
|
119
|
+
projectAccess: projectAccess
|
|
120
|
+
? {
|
|
121
|
+
defaultRoot: asOptionalString(projectAccess.defaultRoot),
|
|
122
|
+
allowedRoots: asStringArray(projectAccess.allowedRoots),
|
|
123
|
+
}
|
|
124
|
+
: undefined,
|
|
115
125
|
};
|
|
116
126
|
}
|
|
117
127
|
export function getSecurityConfigPath(appHomeDir = APP_HOME_DIR) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { existsSync, lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
|
-
import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
|
|
4
4
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
5
5
|
const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
6
6
|
const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
|
|
@@ -71,11 +71,11 @@ function resolveConfiguredPath(rawPath, ctx) {
|
|
|
71
71
|
if (isAbsolute(expanded)) {
|
|
72
72
|
return normalize(expanded);
|
|
73
73
|
}
|
|
74
|
-
return resolve(ctx.
|
|
74
|
+
return resolve(ctx.agentWorkspaceDir, expanded);
|
|
75
75
|
}
|
|
76
76
|
function resolveTargetPath(rawPath, ctx) {
|
|
77
77
|
const homeDir = ctx.homeDir ?? homedir();
|
|
78
|
-
const cwd = ctx.
|
|
78
|
+
const cwd = ctx.projectRoot ?? process.cwd();
|
|
79
79
|
const normalized = stripNullAndNormalize(rawPath);
|
|
80
80
|
const expanded = maybeExpandHome(normalized, homeDir);
|
|
81
81
|
if (isAbsolute(expanded)) {
|
|
@@ -205,8 +205,24 @@ function isWithinTemp(path) {
|
|
|
205
205
|
function isWithinHome(path, homeDir) {
|
|
206
206
|
return startsWithPathPrefix(path, normalize(homeDir));
|
|
207
207
|
}
|
|
208
|
-
function
|
|
209
|
-
return startsWithPathPrefix(path, normalize(
|
|
208
|
+
function isWithinAgentWorkspace(path, agentWorkspaceDir) {
|
|
209
|
+
return startsWithPathPrefix(path, normalize(agentWorkspaceDir));
|
|
210
|
+
}
|
|
211
|
+
function isWithinProjectRoot(path, ctx) {
|
|
212
|
+
const root = ctx.projectRoot;
|
|
213
|
+
if (!root) {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
return startsWithPathPrefix(path, normalize(root));
|
|
217
|
+
}
|
|
218
|
+
/** Runtime-owned, read-only exception: the AgentWorkspace's `skills/` tree stays readable under
|
|
219
|
+
* `boundary: "project"` so the model can load a skill's playbook regardless of which project it
|
|
220
|
+
* has selected (spec 043, D6.2). Never a write exception. */
|
|
221
|
+
function isAgentWorkspaceSkillsRead(path, operation, ctx) {
|
|
222
|
+
if (operation !== "read") {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
return startsWithPathPrefix(path, normalize(join(ctx.agentWorkspaceDir, "skills")));
|
|
210
226
|
}
|
|
211
227
|
function isDeniedSystemPath(path) {
|
|
212
228
|
if (isWithinTemp(path)) {
|
|
@@ -224,8 +240,11 @@ function matchesConfiguredPath(path, entries, ctx) {
|
|
|
224
240
|
.some((entry) => startsWithPathPrefix(path, entry));
|
|
225
241
|
}
|
|
226
242
|
function pathAllowedByDefaults(path, ctx) {
|
|
243
|
+
if (ctx.boundary === "project") {
|
|
244
|
+
return isWithinProjectRoot(path, ctx);
|
|
245
|
+
}
|
|
227
246
|
const homeDir = ctx.homeDir ?? homedir();
|
|
228
|
-
return
|
|
247
|
+
return isWithinAgentWorkspace(path, ctx.agentWorkspaceDir) || isWithinTemp(path) || isWithinHome(path, homeDir);
|
|
229
248
|
}
|
|
230
249
|
/** The runtime's own bundled playbooks are readable regardless of where the package is installed. */
|
|
231
250
|
function isBundledPlaybookRead(path, operation) {
|
|
@@ -248,8 +267,9 @@ export function guardPath(rawPath, operation, ctx) {
|
|
|
248
267
|
const homeDir = ctx.homeDir ?? homedir();
|
|
249
268
|
const effectiveCtx = {
|
|
250
269
|
...ctx,
|
|
251
|
-
|
|
270
|
+
agentWorkspaceDir: resolveRootForGuard(ctx.agentWorkspaceDir, ctx),
|
|
252
271
|
homeDir: resolveRootForGuard(homeDir, ctx),
|
|
272
|
+
projectRoot: ctx.projectRoot ? resolveRootForGuard(ctx.projectRoot, ctx) : ctx.projectRoot,
|
|
253
273
|
};
|
|
254
274
|
const resolvedTarget = resolveTargetPath(rawPath, ctx);
|
|
255
275
|
const guardedPath = resolveForGuard(resolvedTarget, ctx);
|
|
@@ -272,10 +292,15 @@ export function guardPath(rawPath, operation, ctx) {
|
|
|
272
292
|
// Ignore lstat races and continue with resolved-path checks.
|
|
273
293
|
}
|
|
274
294
|
}
|
|
275
|
-
if (matchesConfiguredPath(guardedPath, operation === "read" ? effectiveCtx.config.readAllow : effectiveCtx.config.writeAllow, effectiveCtx)
|
|
295
|
+
if (matchesConfiguredPath(guardedPath, operation === "read" ? effectiveCtx.config.readAllow : effectiveCtx.config.writeAllow, effectiveCtx) &&
|
|
296
|
+
// D6.2: `boundary: "project"` is pathGuard's outer bound — a configured allow entry can
|
|
297
|
+
// narrow within the project but never widen a generic tool past it.
|
|
298
|
+
(effectiveCtx.boundary !== "project" || isWithinProjectRoot(guardedPath, effectiveCtx))) {
|
|
276
299
|
return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
|
|
277
300
|
}
|
|
278
|
-
if (pathAllowedByDefaults(guardedPath, effectiveCtx) ||
|
|
301
|
+
if (pathAllowedByDefaults(guardedPath, effectiveCtx) ||
|
|
302
|
+
isBundledPlaybookRead(guardedPath, operation) ||
|
|
303
|
+
isAgentWorkspaceSkillsRead(guardedPath, operation, effectiveCtx)) {
|
|
279
304
|
return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
|
|
280
305
|
}
|
|
281
306
|
if (isDeniedSystemPath(guardedPath)) {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
2
|
+
import type { SecurityConfig } from "./types.js";
|
|
3
|
+
/** Spec 043, D6.3: the runtime must never claim `system` without an explicit bootstrap-injected
|
|
4
|
+
* host sandbox. Nothing wires that injection point yet, so this is the only reachable value today. */
|
|
5
|
+
export interface ProjectSandboxStatus {
|
|
6
|
+
level: "application" | "system";
|
|
7
|
+
provider: string;
|
|
8
|
+
summary: string;
|
|
9
|
+
}
|
|
10
|
+
/** The effective result a runner generation uses; see D2.1. Not the raw request. */
|
|
11
|
+
export interface ProjectScope {
|
|
12
|
+
/** Realpath of an existing directory. */
|
|
13
|
+
projectRoot: string;
|
|
14
|
+
/** `project`: generic file tools are bounded to `projectRoot`. `unbounded`: today's global pathGuard defaults. */
|
|
15
|
+
boundary: "project" | "unbounded";
|
|
16
|
+
sandbox: ProjectSandboxStatus;
|
|
17
|
+
}
|
|
18
|
+
/** The app-level policy resolved from `security.json`'s `projectAccess` section (D3.1). */
|
|
19
|
+
export interface ProjectAccessPolicy {
|
|
20
|
+
/** Realpath. Always a member of `allowedRoots`. */
|
|
21
|
+
defaultRoot: string;
|
|
22
|
+
/** Realpaths. */
|
|
23
|
+
allowedRoots: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
export interface ProjectAccessResolution {
|
|
26
|
+
policy: ProjectAccessPolicy;
|
|
27
|
+
/** False in the unconfigured-compat state, or when `defaultRoot` itself fails to canonicalize. */
|
|
28
|
+
mutable: boolean;
|
|
29
|
+
/** Whether `security.json` had a `projectAccess` key at all (distinct from mutable — see D3.2). */
|
|
30
|
+
configured: boolean;
|
|
31
|
+
diagnostics: ConfigDiagnostic[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolves the app's project-access policy for a fresh runner generation. `startupCwd` is only
|
|
35
|
+
* used as the implicit default when `projectAccess` is configured but omits `defaultRoot` (D3.2
|
|
36
|
+
* row 3) — the unconfigured-compat row (row 1) also uses it, but never persists it as a "chosen"
|
|
37
|
+
* default the way a configured policy's `defaultRoot` is.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveProjectAccessPolicy(config: SecurityConfig, startupCwd: string): ProjectAccessResolution;
|
|
40
|
+
/** Prefix match with a path-separator boundary, so `/repo-ab` is not treated as within `/repo-a`. */
|
|
41
|
+
export declare function isWithinAllowedRoots(root: string, policy: ProjectAccessPolicy): boolean;
|
|
42
|
+
/** True until a host sandbox injection point exists (D6.3, D9 risk #2) — see `ProjectSandboxStatus`. */
|
|
43
|
+
export declare function currentProjectSandboxStatus(): ProjectSandboxStatus;
|
|
44
|
+
/** True if `raw` resolves (after `~`-expansion) to an existing directory — used by `/project set` validation. */
|
|
45
|
+
export declare function resolveExistingDirectory(raw: string): string | undefined;
|