@oyasmi/pipiclaw 0.9.0-beta.8 → 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.
Files changed (80) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +73 -10
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/index.d.ts +1 -1
  6. package/dist/agent/index.js +1 -1
  7. package/dist/agent/job-manager.d.ts +23 -3
  8. package/dist/agent/job-manager.js +14 -1
  9. package/dist/agent/runner-factory.d.ts +16 -4
  10. package/dist/agent/runner-factory.js +9 -23
  11. package/dist/agent/turn-recovery.d.ts +72 -0
  12. package/dist/agent/turn-recovery.js +193 -0
  13. package/dist/agent/types.d.ts +9 -1
  14. package/dist/agent/types.js +3 -16
  15. package/dist/playbooks/agent-delegation.md +3 -3
  16. package/dist/playbooks/runtime-orientation.md +5 -0
  17. package/dist/runtime/active-session-store.d.ts +42 -0
  18. package/dist/runtime/active-session-store.js +100 -0
  19. package/dist/runtime/bootstrap.d.ts +10 -2
  20. package/dist/runtime/bootstrap.js +122 -53
  21. package/dist/runtime/channel-event.d.ts +41 -0
  22. package/dist/runtime/channel-event.js +1 -0
  23. package/dist/runtime/delivery.d.ts +3 -2
  24. package/dist/runtime/dingtalk.d.ts +9 -31
  25. package/dist/runtime/dingtalk.js +2 -1
  26. package/dist/runtime/durable-dispatch.d.ts +3 -2
  27. package/dist/runtime/events.d.ts +3 -2
  28. package/dist/runtime/events.js +2 -3
  29. package/dist/runtime/project-commands.d.ts +16 -0
  30. package/dist/runtime/project-commands.js +112 -0
  31. package/dist/runtime/project-scope-store.d.ts +31 -0
  32. package/dist/runtime/project-scope-store.js +102 -0
  33. package/dist/runtime/task-commands.js +2 -2
  34. package/dist/runtime/task-driver.d.ts +7 -7
  35. package/dist/runtime/task-driver.js +1 -4
  36. package/dist/runtime/task-migration.js +1 -1
  37. package/dist/runtime/task-wake.d.ts +4 -4
  38. package/dist/security/config.js +10 -0
  39. package/dist/security/path-guard.js +34 -9
  40. package/dist/security/project-scope.d.ts +45 -0
  41. package/dist/security/project-scope.js +107 -0
  42. package/dist/security/types.d.ts +20 -2
  43. package/dist/settings.d.ts +0 -106
  44. package/dist/settings.js +0 -224
  45. package/dist/shared/types.d.ts +1 -0
  46. package/dist/shared/types.js +10 -1
  47. package/dist/subagents/external/run.js +2 -8
  48. package/dist/subagents/runs.d.ts +3 -3
  49. package/dist/subagents/runs.js +2 -12
  50. package/dist/subagents/tool.d.ts +13 -4
  51. package/dist/subagents/tool.js +9 -15
  52. package/dist/tasks/ledger.js +1 -1
  53. package/dist/{shared → tasks}/task-schedule.js +1 -1
  54. package/dist/tools/bash.js +4 -4
  55. package/dist/tools/edit.js +3 -3
  56. package/dist/tools/event-manage.js +1 -4
  57. package/dist/tools/grep.js +5 -6
  58. package/dist/tools/index.d.ts +3 -0
  59. package/dist/tools/index.js +7 -2
  60. package/dist/tools/job.js +5 -5
  61. package/dist/tools/memory-manage.js +3 -6
  62. package/dist/tools/read.js +3 -3
  63. package/dist/tools/registry.js +1 -1
  64. package/dist/tools/send-media.js +2 -2
  65. package/dist/tools/session-search.js +0 -1
  66. package/dist/tools/skill-manage.js +3 -3
  67. package/dist/tools/subagent-manage.js +3 -3
  68. package/dist/tools/task-manage/shared.js +2 -2
  69. package/dist/tools/task-manage.js +1 -4
  70. package/dist/tools/web-fetch.js +0 -1
  71. package/dist/tools/write-content.js +3 -3
  72. package/dist/tui/app.js +50 -4
  73. package/dist/tui/commands.d.ts +1 -0
  74. package/dist/tui/commands.js +2 -0
  75. package/dist/tui/turn-controller.d.ts +1 -0
  76. package/dist/tui/turn-controller.js +1 -0
  77. package/package.json +1 -1
  78. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  79. /package/dist/{shared → tasks}/task-events.js +0 -0
  80. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -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;
@@ -1,4 +1,5 @@
1
- import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
1
+ import type { ChannelEvent } from "./channel-event.js";
2
+ import type { DingTalkBot } from "./dingtalk.js";
2
3
  export interface DurableDispatchOptions {
3
4
  stateDir: string;
4
5
  bot: Pick<DingTalkBot, "enqueueEvent">;
@@ -29,7 +30,7 @@ export declare class DurableDispatchService {
29
30
  constructor(options: DurableDispatchOptions);
30
31
  start(): void;
31
32
  stop(): void;
32
- dispatch(event: DingTalkEvent): Promise<boolean>;
33
+ dispatch(event: ChannelEvent): Promise<boolean>;
33
34
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
34
35
  cancelChannel(channelId: string): Promise<number>;
35
36
  markStarted(id: string | undefined): Promise<void>;
@@ -1,6 +1,7 @@
1
1
  import type { Executor } from "../executor.js";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
- import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
3
+ import type { ChannelEvent } from "./channel-event.js";
4
+ import type { DingTalkBot } from "./dingtalk.js";
4
5
  export interface EventAction {
5
6
  type: "bash";
6
7
  command: string;
@@ -56,7 +57,7 @@ export interface EventHistoryRecord {
56
57
  export interface EventsWatcherOptions {
57
58
  historyPath?: string;
58
59
  /** Persist synthetic work before it enters the in-memory channel queue. */
59
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
60
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
60
61
  }
61
62
  export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
62
63
  export declare class EventsWatcher {
@@ -6,9 +6,9 @@ import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
7
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
8
8
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
- import { taskEventPrefix } from "../shared/task-events.js";
10
9
  import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
10
  import { parseTaskFrontmatter } from "../tasks/ledger.js";
11
+ import { taskEventPrefix } from "../tasks/task-events.js";
12
12
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
13
  // ============================================================================
14
14
  // EventsWatcher
@@ -567,7 +567,7 @@ export class EventsWatcher {
567
567
  ? " This is a periodic runtime wake. If it produces no user-visible change or result, reply with exactly [SILENT]."
568
568
  : "";
569
569
  const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}${periodicContract}`;
570
- // Create synthetic DingTalkEvent
570
+ // Create synthetic ChannelEvent
571
571
  const syntheticEvent = {
572
572
  type: "dm",
573
573
  channelId: event.channelId,
@@ -575,7 +575,6 @@ export class EventsWatcher {
575
575
  userName: "EVENT",
576
576
  text: message,
577
577
  ts: Date.now().toString(),
578
- conversationId: "",
579
578
  conversationType: "1",
580
579
  dispatchId: eventDispatchId(filename, event, occurrence),
581
580
  };
@@ -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
+ }
@@ -3,8 +3,6 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { channelJobTaskIds } from "../agent/job-manager.js";
5
5
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
6
- import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
7
- import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
8
6
  import { errorMessage } from "../shared/text-utils.js";
9
7
  import { isRecord } from "../shared/type-guards.js";
10
8
  import { channelDelegationTaskIds } from "../subagents/runs.js";
@@ -12,6 +10,8 @@ import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys
12
10
  import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
13
11
  import { withTaskMutation } from "../tasks/mutation-lock.js";
14
12
  import { claimTaskAttempt, openRecurringTaskCycle, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
13
+ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
14
+ import { nextTaskWake, validateTaskSchedule } from "../tasks/task-schedule.js";
15
15
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
16
16
  import { readVerificationAttestation } from "../tasks/verification.js";
17
17
  import { parseScheduledEventContent } from "./events.js";
@@ -1,13 +1,13 @@
1
1
  import type { PipiclawTaskDriverSettings } from "../settings.js";
2
2
  import { type TaskLedgerEntry } from "../tasks/ledger.js";
3
- import type { DingTalkEvent } from "./dingtalk.js";
3
+ import type { ChannelEvent } from "./channel-event.js";
4
4
  export interface TaskDriverOptions {
5
5
  workspaceDir: string;
6
6
  getKnownChannelIds?: () => Iterable<string>;
7
7
  isChannelActive: (channelId: string) => boolean;
8
- dispatch: (event: DingTalkEvent) => boolean | Promise<boolean>;
8
+ dispatch: (event: ChannelEvent) => boolean | Promise<boolean>;
9
9
  /** Optional observability hook. It runs after every production dispatch attempt. */
10
- onDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
10
+ onDispatch?: (event: ChannelEvent, accepted: boolean) => void;
11
11
  getSettings: () => PipiclawTaskDriverSettings;
12
12
  /**
13
13
  * Externally visible effects produced by this task's own turns so far (spec 031, D7).
@@ -19,13 +19,13 @@ export interface TaskDriverOptions {
19
19
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
20
20
  intervalMs?: number;
21
21
  /** Direct, non-LLM receipt for deterministic governor stops. */
22
- notify?: (event: DingTalkEvent) => boolean | Promise<boolean>;
22
+ notify?: (event: ChannelEvent) => boolean | Promise<boolean>;
23
23
  }
24
24
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
25
- export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): DingTalkEvent;
25
+ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number, attemptGeneration?: number): ChannelEvent;
26
26
  /** Durable checker wake created by request-verification; it is a normal main-agent turn. */
27
- export declare function createTaskVerificationEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): DingTalkEvent;
28
- export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): DingTalkEvent;
27
+ export declare function createTaskVerificationEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): ChannelEvent;
28
+ export declare function taskGovernorReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
29
29
  /**
30
30
  * Native, token-gated driver for the persistent task ledger.
31
31
  *
@@ -3,11 +3,11 @@ import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { PLAYBOOKS_DIR } from "../paths.js";
5
5
  import { parseLocalTime } from "../shared/local-time.js";
6
- import { nextTaskWake } from "../shared/task-schedule.js";
7
6
  import { errorMessage } from "../shared/text-utils.js";
8
7
  import { taskBudgetViolation } from "../tasks/control.js";
9
8
  import { normalizeTaskFields, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
10
9
  import { activateWaitingTask, claimTaskAttempt, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
10
+ import { nextTaskWake } from "../tasks/task-schedule.js";
11
11
  import { discoverWorkspaceChannelIds } from "./channel-index.js";
12
12
  import { isChannelId } from "./channel-paths.js";
13
13
  /** Short debounce so a burst of nudges collapses into a single rescan. */
@@ -146,7 +146,6 @@ export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration
146
146
  "For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_manage skip with the reason, then respond with exactly [SILENT]. " +
147
147
  "If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
148
148
  ts: String(nowMs),
149
- conversationId: "",
150
149
  conversationType: channelId.startsWith("group_") ? "2" : "1",
151
150
  dispatchId: taskDispatchId(channelId, entry, nowMs),
152
151
  taskAttemptGeneration: attemptGeneration,
@@ -165,7 +164,6 @@ export function createTaskVerificationEvent(channelId, entry, nowMs) {
165
164
  `subagent with purpose=verify. Import its attestation with task_manage verify using the returned run id. ` +
166
165
  `Do not modify the workspace or task contract; if verification fails, record the failure and leave the task recoverable.`,
167
166
  ts: String(nowMs),
168
- conversationId: "",
169
167
  conversationType: channelId.startsWith("group_") ? "2" : "1",
170
168
  dispatchId: `task:${channelId}:${entry.id}:verification:${control?.cycleId ?? `t${nowMs}`}`,
171
169
  };
@@ -192,7 +190,6 @@ export function taskGovernorReceipt(channelId, entry, reason, nowMs) {
192
190
  `当前阶段:${entry.frontmatter.status ?? "active"}${entry.frontmatter.control?.cycleId ? `;周期:${entry.frontmatter.control.cycleId}` : ""}\n` +
193
191
  `继续:/tasks resume ${entry.id}\n立即执行:/tasks run ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
194
192
  ts: String(nowMs),
195
- conversationId: "",
196
193
  conversationType: channelId.startsWith("group_") ? "2" : "1",
197
194
  // Keyed on the cause, not the moment: re-detecting the same violation before the user has
198
195
  // acted must not queue a second identical escalation, while a different cause still does.
@@ -2,12 +2,12 @@ import { mkdir, readdir, readFile, rename, stat, unlink } from "node:fs/promises
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { formatLocalTime } from "../shared/local-time.js";
5
- import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
6
5
  import { errorMessage } from "../shared/text-utils.js";
7
6
  import { createDefaultTaskControl } from "../tasks/control.js";
8
7
  import { appendCurrentCycleNote, parseTaskFrontmatter } from "../tasks/ledger.js";
9
8
  import { withTaskMutation } from "../tasks/mutation-lock.js";
10
9
  import { readStoredTask, updateStoredTask, writeStoredTask } from "../tasks/store.js";
10
+ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
11
11
  import { parseScheduledEventContent } from "./events.js";
12
12
  import { discoverTaskChannels } from "./task-driver.js";
13
13
  /**
@@ -8,7 +8,7 @@ import { type JobSnapshot } from "../agent/job-manager.js";
8
8
  import type { Executor } from "../executor.js";
9
9
  import { type RunRecord } from "../subagents/runs.js";
10
10
  import { type WakeTaskTransitionHooks } from "../tasks/store.js";
11
- import type { DingTalkEvent } from "./dingtalk.js";
11
+ import type { ChannelEvent } from "./channel-event.js";
12
12
  /**
13
13
  * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
14
  * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
@@ -28,7 +28,7 @@ export declare function isVerifiedDelegationWake(record: RunRecord | undefined,
28
28
  /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
29
29
  * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
30
30
  * not populate `internalWake`, so copying a real wake's text is insufficient. */
31
- export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
31
+ export declare function isTrustedInternalWake(event: ChannelEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is ChannelEvent & {
32
32
  dispatchId: string;
33
33
  };
34
34
  export interface ClaimedDelegationWake {
@@ -41,7 +41,7 @@ export interface ClaimedDelegationWake {
41
41
  /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
42
42
  * final marker separate lets transports such as TUI mark it consumed only after they have accepted
43
43
  * the corresponding turn; a rejected submit remains replayable in the same or next process. */
44
- export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
44
+ export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
45
45
  export interface ClaimedJobWake {
46
46
  taskId: string;
47
47
  generation?: number;
@@ -51,4 +51,4 @@ export interface ClaimedJobWake {
51
51
  /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
52
52
  * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
53
53
  * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
54
- export declare function claimVerifiedJobWake(event: DingTalkEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
54
+ export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
@@ -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.workspaceDir, expanded);
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.cwd ?? process.cwd();
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 isWithinWorkspace(path, workspaceDir) {
209
- return startsWithPathPrefix(path, normalize(workspaceDir));
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 isWithinWorkspace(path, ctx.workspaceDir) || isWithinTemp(path) || isWithinHome(path, homeDir);
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
- workspaceDir: resolveRootForGuard(ctx.workspaceDir, ctx),
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) || isBundledPlaybookRead(guardedPath, operation)) {
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;