@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.
- package/dist/agent/channel-runner.d.ts +8 -0
- package/dist/agent/channel-runner.js +73 -10
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +9 -0
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/job-manager.d.ts +23 -3
- package/dist/agent/job-manager.js +14 -1
- package/dist/agent/runner-factory.d.ts +16 -4
- package/dist/agent/runner-factory.js +9 -23
- package/dist/agent/turn-recovery.d.ts +72 -0
- package/dist/agent/turn-recovery.js +193 -0
- package/dist/agent/types.d.ts +9 -1
- package/dist/agent/types.js +3 -16
- 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.d.ts +10 -2
- package/dist/runtime/bootstrap.js +122 -53
- package/dist/runtime/channel-event.d.ts +41 -0
- package/dist/runtime/channel-event.js +1 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/dingtalk.d.ts +9 -31
- package/dist/runtime/dingtalk.js +2 -1
- package/dist/runtime/durable-dispatch.d.ts +3 -2
- package/dist/runtime/events.d.ts +3 -2
- package/dist/runtime/events.js +2 -3
- 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/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +7 -7
- package/dist/runtime/task-driver.js +1 -4
- package/dist/runtime/task-migration.js +1 -1
- package/dist/runtime/task-wake.d.ts +4 -4
- 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/settings.d.ts +0 -106
- package/dist/settings.js +0 -224
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.js +10 -1
- package/dist/subagents/external/run.js +2 -8
- package/dist/subagents/runs.d.ts +3 -3
- package/dist/subagents/runs.js +2 -12
- package/dist/subagents/tool.d.ts +13 -4
- package/dist/subagents/tool.js +9 -15
- package/dist/tasks/ledger.js +1 -1
- package/dist/{shared → tasks}/task-schedule.js +1 -1
- package/dist/tools/bash.js +4 -4
- package/dist/tools/edit.js +3 -3
- package/dist/tools/event-manage.js +1 -4
- package/dist/tools/grep.js +5 -6
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/job.js +5 -5
- package/dist/tools/memory-manage.js +3 -6
- 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/session-search.js +0 -1
- package/dist/tools/skill-manage.js +3 -3
- package/dist/tools/subagent-manage.js +3 -3
- package/dist/tools/task-manage/shared.js +2 -2
- package/dist/tools/task-manage.js +1 -4
- package/dist/tools/web-fetch.js +0 -1
- package/dist/tools/write-content.js +3 -3
- package/dist/tui/app.js +50 -4
- 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
- /package/dist/{shared → tasks}/task-events.d.ts +0 -0
- /package/dist/{shared → tasks}/task-events.js +0 -0
- /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
package/dist/agent/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
2
|
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
3
3
|
import type { ChannelStore } from "../runtime/store.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type UsageTotals } from "../shared/types.js";
|
|
5
5
|
import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
|
|
6
6
|
import type { RunnerBuiltInCommand } from "./commands.js";
|
|
7
7
|
export interface RunnerStatusSnapshot {
|
|
@@ -77,6 +77,14 @@ export interface AgentRunner {
|
|
|
77
77
|
/** Mark the current turn as user-stopped (no-op when idle). */
|
|
78
78
|
requestStop(): void;
|
|
79
79
|
getTurnStatus(): TurnStatus;
|
|
80
|
+
/**
|
|
81
|
+
* Release this runner's resources: flush pending memory, unsubscribe from session events, and
|
|
82
|
+
* dispose the underlying SDK session. A no-op (memory still flushed) while `isBusy()` — disposing
|
|
83
|
+
* the SDK session aborts in-flight work, so a caller must never call this on a busy runner and
|
|
84
|
+
* expect the turn to survive. The owning cache (daemon runtime map, TUI's single runner) must
|
|
85
|
+
* drop its own reference after calling this; a disposed runner is not reusable.
|
|
86
|
+
*/
|
|
87
|
+
dispose(): Promise<void>;
|
|
80
88
|
}
|
|
81
89
|
export type FinalOutcome = {
|
|
82
90
|
kind: "none";
|
package/dist/agent/types.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createEmptyUsageTotals } from "../shared/types.js";
|
|
1
2
|
export function createEmptyRunState() {
|
|
2
3
|
return {
|
|
3
4
|
ctx: null,
|
|
@@ -5,22 +6,8 @@ export function createEmptyRunState() {
|
|
|
5
6
|
store: null,
|
|
6
7
|
queue: null,
|
|
7
8
|
pendingTools: new Map(),
|
|
8
|
-
totalUsage:
|
|
9
|
-
|
|
10
|
-
output: 0,
|
|
11
|
-
cacheRead: 0,
|
|
12
|
-
cacheWrite: 0,
|
|
13
|
-
total: 0,
|
|
14
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
15
|
-
},
|
|
16
|
-
assistantUsage: {
|
|
17
|
-
input: 0,
|
|
18
|
-
output: 0,
|
|
19
|
-
cacheRead: 0,
|
|
20
|
-
cacheWrite: 0,
|
|
21
|
-
total: 0,
|
|
22
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
23
|
-
},
|
|
9
|
+
totalUsage: createEmptyUsageTotals(),
|
|
10
|
+
assistantUsage: createEmptyUsageTotals(),
|
|
24
11
|
costKnown: true,
|
|
25
12
|
usageSources: 0,
|
|
26
13
|
stopReason: "stop",
|
|
@@ -36,10 +36,10 @@ order: 36
|
|
|
36
36
|
|
|
37
37
|
## 三、工作目录:每次委派现场决定
|
|
38
38
|
|
|
39
|
-
角色文件里没有默认工作目录,也不会有——同一个角色这次改 A 仓库、下次改 B
|
|
39
|
+
角色文件里没有默认工作目录,也不会有——同一个角色这次改 A 仓库、下次改 B 仓库,一个写死在角色定义里的默认值只会让人跳过该做的判断。省略 `workingDirectory` 时委派落到**当前频道的项目目录**(本回合你自己的工作面),这不是"没有默认值",只是默认值等于你此刻所在的地方;并行写入分片仍然必须各自显式指定,否则两个 run 会悄悄落到同一棵树上。因此:
|
|
40
40
|
|
|
41
|
-
-
|
|
42
|
-
-
|
|
41
|
+
- **并行的写入分片各自显式传 `workingDirectory`(`git worktree add` 后指向不同 checkout)**,不要依赖默认值让它们自动分开——它们不会。
|
|
42
|
+
- 频道配置了项目边界时,`workingDirectory` 必须落在当前项目目录内;传一个目录外的路径会被直接拒绝(`workingDirectory "..." must be inside the project root`),不是先派发再核实。
|
|
43
43
|
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。**这把锁只保护声明了 `mutates: write` 的委派**——内置角色的 `mutates` 是按 `tools` 推定(只看 `write`/`edit`,不看 `bash`),外部角色是自述,两者都可能与角色实际行为不符,写清楚 `mutates` 是你的责任,不是 runtime 能替你核实的事。
|
|
44
44
|
- **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
|
|
45
45
|
- **创建的 worktree 在使用结束后要记得关闭**
|
|
@@ -39,6 +39,11 @@ Workspace 根目录:
|
|
|
39
39
|
- `sub-agents/`:工作区配置的子代理;只加载实际存在的 Markdown 文件。
|
|
40
40
|
- `events/`:全 workspace 的调度事件。
|
|
41
41
|
|
|
42
|
+
项目目录(ProjectRoot):
|
|
43
|
+
|
|
44
|
+
- 与上面的 workspace 根目录是两个不同的东西。`read` / `write` / `edit` / `grep` / `bash` 等通用文件工具和 shell 的 cwd 都以**项目目录**为准,不是 workspace 根目录——workspace 根目录下的文件(`SOUL.md`/`AGENTS.md`/`skills/` 等)要用各自的专用工具(`skill_manage` 等)或只读注入访问,不能假设通用文件工具能直接读写到那里。
|
|
45
|
+
- 频道配置了项目边界(`security.json` 的 `projectAccess`)时,通用文件工具与 sub-agent 默认工作目录都被限制在这个目录内,越界会被直接拒绝;未配置时沿用旧的全局文件权限。人可以用 `/project` 查看或切换当前项目目录,这是运行时命令,不经过模型。
|
|
46
|
+
|
|
42
47
|
当前 channel 目录:
|
|
43
48
|
|
|
44
49
|
- `SESSION.md`:当前工作状态,runtime 维护。
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Points a channel at the one session file it currently considers active. Spec 043, D1.
|
|
3
|
+
*
|
|
4
|
+
* Only the pointer is persisted here — never messages, branches, or project state. A missing ref
|
|
5
|
+
* means "this channel has never run a session-topology operation"; it is interpreted as
|
|
6
|
+
* `context.jsonl` (today's fixed name) rather than written eagerly, so a channel that never calls
|
|
7
|
+
* `/new`/fork/switch never gains an `active-session.json` at all.
|
|
8
|
+
*/
|
|
9
|
+
export interface ActiveSessionRefV1 {
|
|
10
|
+
version: 1;
|
|
11
|
+
/** Basename only — see `isValidSessionRefBasename`. */
|
|
12
|
+
file: string;
|
|
13
|
+
sessionId: string;
|
|
14
|
+
updatedAt: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function getActiveSessionRefPath(channelDir: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* The ref's `file` is opened for append under `channelDir`, and the ref itself lives in a
|
|
19
|
+
* directory a chat participant can otherwise influence the contents of. Reject anything that
|
|
20
|
+
* isn't a plain, single-segment `.jsonl` name so this can never be used to open or create a file
|
|
21
|
+
* outside the channel directory.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isValidSessionRefBasename(file: string): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Resolves which session file a channel should open (runner construction / restart), migrating a
|
|
26
|
+
* channel with no ref to `context.jsonl` and materializing that file. Never writes the ref
|
|
27
|
+
* itself — a missing ref stays missing until a session-topology operation commits one.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveActiveSessionFile(channelDir: string): string;
|
|
30
|
+
export interface SessionFileHandle {
|
|
31
|
+
getSessionFile(): string | undefined;
|
|
32
|
+
getSessionId(): string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Commits the active-session ref for a session a topology operation (`/new`, fork, switch) has
|
|
36
|
+
* already created/opened. The SDK writes that session's durable header synchronously before
|
|
37
|
+
* invoking the caller's rebuild callback, so by the time this is called the target file already
|
|
38
|
+
* exists on disk; this only records the pointer. Callers must not rebind their live `AgentSession`
|
|
39
|
+
* until this resolves (spec 043, D1.3) — on throw, nothing is written and the old ref (and thus
|
|
40
|
+
* the old session) remains authoritative.
|
|
41
|
+
*/
|
|
42
|
+
export declare function commitActiveSessionRef(channelDir: string, session: SessionFileHandle): Promise<void>;
|
|
@@ -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,7 +3,8 @@ import { type Executor } from "../executor.js";
|
|
|
3
3
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
4
4
|
import { type WakeTaskTransitionHooks } from "../tasks/store.js";
|
|
5
5
|
import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
|
|
6
|
-
import
|
|
6
|
+
import type { ChannelEvent } from "./channel-event.js";
|
|
7
|
+
import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
|
|
7
8
|
import { ChannelStore } from "./store.js";
|
|
8
9
|
export interface BootstrapOptions {
|
|
9
10
|
env?: NodeJS.ProcessEnv;
|
|
@@ -76,13 +77,20 @@ interface RuntimeContextOptions {
|
|
|
76
77
|
/** Receives raw SDK session events after subscription, without changing runtime handling. */
|
|
77
78
|
observer?: (event: unknown, channelId: string) => void;
|
|
78
79
|
/** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */
|
|
79
|
-
onTaskDriverDispatch?: (event:
|
|
80
|
+
onTaskDriverDispatch?: (event: ChannelEvent, accepted: boolean) => void;
|
|
80
81
|
startServices?: boolean;
|
|
81
82
|
registerSignalHandlers?: boolean;
|
|
82
83
|
/** Test-only fault seams for the atomic structured-wake task transition. */
|
|
83
84
|
wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
|
|
84
85
|
/** Override the `/stop` watchdog's grace window (tests use a short one). */
|
|
85
86
|
stopForceEndGraceMs?: number;
|
|
87
|
+
/**
|
|
88
|
+
* The app-level settings manager, shared by every channel's runner (see
|
|
89
|
+
* `agent/runner-factory.ts`'s `RunnerFactoryPaths.settingsManager`). `bootstrap()` passes the
|
|
90
|
+
* same instance `prepareAppServices()` already constructed and diagnosed; a caller that skips
|
|
91
|
+
* `prepareAppServices()` (tests) gets one built here instead.
|
|
92
|
+
*/
|
|
93
|
+
settingsManager?: PipiclawSettingsManager;
|
|
86
94
|
}
|
|
87
95
|
export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
|
|
88
96
|
bot: DingTalkBot;
|
|
@@ -2,15 +2,16 @@ import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
|
2
2
|
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
|
-
import {
|
|
6
|
-
import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
5
|
+
import { createRunner } from "../agent/index.js";
|
|
6
|
+
import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
7
7
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
8
|
-
import { resetRunner } from "../agent/runner-factory.js";
|
|
9
8
|
import { renderStatus } from "../agent/status-render.js";
|
|
9
|
+
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
10
10
|
import { createExecutor } from "../executor.js";
|
|
11
11
|
import * as log from "../log.js";
|
|
12
12
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
13
13
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
14
|
+
import { defaultModel } from "../models/utils.js";
|
|
14
15
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
15
16
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
16
17
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
@@ -18,7 +19,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
|
18
19
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
19
20
|
import { errorMessage } from "../shared/text-utils.js";
|
|
20
21
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
21
|
-
import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentGarbageCollector } from "../subagents/runs.js";
|
|
22
|
+
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
|
|
22
23
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
23
24
|
import { finishTaskAttempt } from "../tasks/store.js";
|
|
24
25
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -32,6 +33,7 @@ import { DingTalkBot, } from "./dingtalk.js";
|
|
|
32
33
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
33
34
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
34
35
|
import { createEventsWatcher } from "./events.js";
|
|
36
|
+
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
35
37
|
import { installLlmProxy } from "./proxy.js";
|
|
36
38
|
import { ChannelStore } from "./store.js";
|
|
37
39
|
import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
@@ -56,17 +58,32 @@ function waitForTasks(tasks, timeoutMs) {
|
|
|
56
58
|
});
|
|
57
59
|
});
|
|
58
60
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
|
|
63
|
+
* `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
|
|
64
|
+
* from, unbounded, for the life of the process. Eviction below only ever touches idle runners —
|
|
65
|
+
* a busy one is left cached past the cap rather than mid-turn disposed.
|
|
66
|
+
*/
|
|
67
|
+
const MAX_CACHED_RUNNERS = 50;
|
|
68
|
+
/**
|
|
69
|
+
* Drop the least-recently-used *idle* runners until the cache is back at the cap, disposing each
|
|
70
|
+
* one (flush memory, unsubscribe, release the SDK session) before dropping it. `channelRunners`
|
|
71
|
+
* is a `Map`, so insertion order is iteration order; `getRunner` below re-inserts on every cache
|
|
72
|
+
* hit to keep that order equal to recency of use — the standard "LRU via Map" idiom.
|
|
73
|
+
*/
|
|
74
|
+
async function evictIdleRunnersOverCap(channelRunners) {
|
|
75
|
+
if (channelRunners.size <= MAX_CACHED_RUNNERS)
|
|
76
|
+
return;
|
|
61
77
|
for (const [channelId, runner] of channelRunners) {
|
|
62
|
-
if (
|
|
78
|
+
if (channelRunners.size <= MAX_CACHED_RUNNERS)
|
|
79
|
+
break;
|
|
80
|
+
if (runner.isBusy())
|
|
63
81
|
continue;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
log.logWarning(`[${channelId}] Failed to
|
|
67
|
-
})
|
|
82
|
+
channelRunners.delete(channelId);
|
|
83
|
+
await runner.dispose().catch((err) => {
|
|
84
|
+
log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
|
|
85
|
+
});
|
|
68
86
|
}
|
|
69
|
-
return flushes;
|
|
70
87
|
}
|
|
71
88
|
function isNoRunningTaskQueueError(err) {
|
|
72
89
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
@@ -76,7 +93,7 @@ function isNoRunningTaskQueueError(err) {
|
|
|
76
93
|
* idle answers it through the runner's ChannelContext-aware command path (thread-reply, delete
|
|
77
94
|
* semantics) instead, so it is not part of this stateless-report dispatch here.
|
|
78
95
|
*/
|
|
79
|
-
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"]);
|
|
80
97
|
function isIdleRuntimeCommandName(name) {
|
|
81
98
|
return IDLE_RUNTIME_COMMAND_NAMES.has(name);
|
|
82
99
|
}
|
|
@@ -117,7 +134,7 @@ export async function createRuntimeContext(options) {
|
|
|
117
134
|
const startServices = options.startServices ?? true;
|
|
118
135
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
119
136
|
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
120
|
-
const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
137
|
+
const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
121
138
|
log.configureLogging(runtimeSettingsManager.getLoggingSettings());
|
|
122
139
|
const startedAt = Date.now();
|
|
123
140
|
const cliVersion = readCliVersion();
|
|
@@ -140,30 +157,37 @@ export async function createRuntimeContext(options) {
|
|
|
140
157
|
}
|
|
141
158
|
};
|
|
142
159
|
const getRunner = (channelId) => {
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
modelsConfigPath: options.paths.modelsConfigPath,
|
|
151
|
-
onSessionEvent: options.observer,
|
|
152
|
-
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
153
|
-
// `bot` is defined below in this same scope and initialized before any message
|
|
154
|
-
// (and thus any getRunner call) can arrive.
|
|
155
|
-
mediaSender: bot,
|
|
156
|
-
dispatchVerification: async (taskId) => {
|
|
157
|
-
const entries = await readActiveTasks(join(channelDir, "tasks"));
|
|
158
|
-
const entry = entries.find((candidate) => candidate.id === taskId);
|
|
159
|
-
if (!entry)
|
|
160
|
-
return false;
|
|
161
|
-
const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
|
|
162
|
-
return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
|
|
163
|
-
},
|
|
164
|
-
});
|
|
165
|
-
channelRunners.set(channelId, runner);
|
|
160
|
+
const existing = channelRunners.get(channelId);
|
|
161
|
+
if (existing) {
|
|
162
|
+
// Re-insert to move this channel to the end (most-recently-used) of the Map's
|
|
163
|
+
// iteration order, which evictIdleRunnersOverCap relies on.
|
|
164
|
+
channelRunners.delete(channelId);
|
|
165
|
+
channelRunners.set(channelId, existing);
|
|
166
|
+
return existing;
|
|
166
167
|
}
|
|
168
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
169
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
170
|
+
const runner = createRunner(channelId, channelDir, {
|
|
171
|
+
appHomeDir: options.paths.appHomeDir,
|
|
172
|
+
authConfigPath: options.paths.authConfigPath,
|
|
173
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
174
|
+
settingsManager: runtimeSettingsManager,
|
|
175
|
+
onSessionEvent: options.observer,
|
|
176
|
+
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
177
|
+
// `bot` is defined below in this same scope and initialized before any message
|
|
178
|
+
// (and thus any getRunner call) can arrive.
|
|
179
|
+
mediaSender: bot,
|
|
180
|
+
dispatchVerification: async (taskId) => {
|
|
181
|
+
const entries = await readActiveTasks(join(channelDir, "tasks"));
|
|
182
|
+
const entry = entries.find((candidate) => candidate.id === taskId);
|
|
183
|
+
if (!entry)
|
|
184
|
+
return false;
|
|
185
|
+
const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
|
|
186
|
+
return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
channelRunners.set(channelId, runner);
|
|
190
|
+
void evictIdleRunnersOverCap(channelRunners);
|
|
167
191
|
return runner;
|
|
168
192
|
};
|
|
169
193
|
const handler = {
|
|
@@ -283,6 +307,31 @@ export async function createRuntimeContext(options) {
|
|
|
283
307
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
284
308
|
}),
|
|
285
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
|
+
});
|
|
286
335
|
}
|
|
287
336
|
},
|
|
288
337
|
async handleBusyMessage(event, bot, mode, queueText) {
|
|
@@ -542,6 +591,23 @@ export async function createRuntimeContext(options) {
|
|
|
542
591
|
// for background jobs.
|
|
543
592
|
await restoreChannelJobs(executor);
|
|
544
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
|
+
}
|
|
545
611
|
const eventsWatcher = options.createEventsWatcher
|
|
546
612
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
547
613
|
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
|
@@ -646,23 +712,25 @@ export async function createRuntimeContext(options) {
|
|
|
646
712
|
}
|
|
647
713
|
}
|
|
648
714
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
715
|
+
// Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
|
|
716
|
+
// still-busy one — its turn already aborted above — is just dropped from the cache and
|
|
717
|
+
// left to unwind on its own as the process exits.
|
|
718
|
+
const disposals = [];
|
|
719
|
+
for (const [channelId, runner] of channelRunners) {
|
|
720
|
+
if (runner.isBusy())
|
|
721
|
+
continue;
|
|
722
|
+
disposals.push(runner.dispose().catch((err) => {
|
|
723
|
+
log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
|
|
724
|
+
}));
|
|
656
725
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
onSessionEvent: options.observer,
|
|
664
|
-
}, channelDir);
|
|
726
|
+
if (disposals.length > 0) {
|
|
727
|
+
log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
|
|
728
|
+
const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
|
|
729
|
+
if (!disposed) {
|
|
730
|
+
log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
|
|
731
|
+
}
|
|
665
732
|
}
|
|
733
|
+
channelRunners.clear();
|
|
666
734
|
const storageFlushes = [
|
|
667
735
|
store.close(),
|
|
668
736
|
// Cancels the debounce timer and lands the last activity times.
|
|
@@ -775,13 +843,14 @@ export async function bootstrap(argv, options = {}) {
|
|
|
775
843
|
}
|
|
776
844
|
const dingtalkConfig = loadConfig(paths, io);
|
|
777
845
|
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
778
|
-
prepareAppServices(paths);
|
|
846
|
+
const { settingsManager } = prepareAppServices(paths);
|
|
779
847
|
log.logStartup(paths.workspaceDir);
|
|
780
848
|
const runtime = await createRuntimeContext({
|
|
781
849
|
paths,
|
|
782
850
|
dingtalkConfig,
|
|
783
851
|
registerSignalHandlers,
|
|
784
852
|
startServices,
|
|
853
|
+
settingsManager,
|
|
785
854
|
});
|
|
786
855
|
return {
|
|
787
856
|
bot: runtime.bot,
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message or wake, from any producer: a real inbound DingTalk message, a scheduled event, a
|
|
3
|
+
* task-driver wake, or a job/subagent completion. `conversationId` is the one field genuinely
|
|
4
|
+
* DingTalk-specific (needed to reply into the right conversation); every synthetic producer
|
|
5
|
+
* (job-manager, task-driver, events, subagents/runs) leaves it unset rather than faking a value,
|
|
6
|
+
* since it has no DingTalk conversation to route into. `conversationType` is not DingTalk-specific
|
|
7
|
+
* in practice — every producer, real or synthetic, can derive "1"/"2" from the channelId prefix —
|
|
8
|
+
* so it stays required.
|
|
9
|
+
*/
|
|
10
|
+
export interface ChannelEvent {
|
|
11
|
+
type: "dm" | "group";
|
|
12
|
+
channelId: string;
|
|
13
|
+
ts: string;
|
|
14
|
+
user: string;
|
|
15
|
+
userName: string;
|
|
16
|
+
text: string;
|
|
17
|
+
/** DingTalk conversation id; absent on synthetic events, which have no DingTalk conversation. */
|
|
18
|
+
conversationId?: string;
|
|
19
|
+
conversationType: string;
|
|
20
|
+
/**
|
|
21
|
+
* Human-readable channel name: the group title, or the peer's nickname for a DM. Absent on
|
|
22
|
+
* synthetic events (scheduled events, task-driver wakes), which carry no conversation payload.
|
|
23
|
+
*/
|
|
24
|
+
channelName?: string;
|
|
25
|
+
/** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
|
|
26
|
+
dispatchId?: string;
|
|
27
|
+
/** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
|
|
28
|
+
* never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
|
|
29
|
+
internalWake?: {
|
|
30
|
+
kind: "job" | "subagent";
|
|
31
|
+
resourceId: string;
|
|
32
|
+
taskId: string;
|
|
33
|
+
dispatchId: string;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
|
|
37
|
+
* Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
|
|
38
|
+
* turn from the current one, even when redelivery or claim races reorder completions.
|
|
39
|
+
*/
|
|
40
|
+
taskAttemptGeneration?: number;
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ChannelContext, ProgressStyle } from "./channel-context.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelEvent } from "./channel-event.js";
|
|
3
|
+
import type { DingTalkBot } from "./dingtalk.js";
|
|
3
4
|
import type { ChannelStore } from "./store.js";
|
|
4
5
|
/**
|
|
5
6
|
* Build the delivery contract for one turn.
|
|
@@ -11,4 +12,4 @@ import type { ChannelStore } from "./store.js";
|
|
|
11
12
|
* final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
|
|
12
13
|
* background turn that has something to say still says it.
|
|
13
14
|
*/
|
|
14
|
-
export declare function createDingTalkContext(event:
|
|
15
|
+
export declare function createDingTalkContext(event: ChannelEvent, bot: DingTalkBot, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type RuntimeCommandName } from "../agent/commands.js";
|
|
2
2
|
import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
|
|
3
|
+
import type { ChannelEvent } from "./channel-event.js";
|
|
3
4
|
import type { ChannelObservation } from "./channel-index.js";
|
|
4
5
|
export type BusyMessageMode = "steer" | "followUp";
|
|
5
6
|
export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
|
|
@@ -22,37 +23,14 @@ export interface DingTalkConfig {
|
|
|
22
23
|
responseMode?: ResponseMode;
|
|
23
24
|
cardAutoLayout?: boolean;
|
|
24
25
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
conversationType: string;
|
|
34
|
-
/**
|
|
35
|
-
* Human-readable channel name: the group title, or the peer's nickname for a DM. Absent on
|
|
36
|
-
* synthetic events (scheduled events, task-driver wakes), which carry no conversation payload.
|
|
37
|
-
*/
|
|
38
|
-
channelName?: string;
|
|
39
|
-
/** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
|
|
40
|
-
dispatchId?: string;
|
|
41
|
-
/** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
|
|
42
|
-
* never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
|
|
43
|
-
internalWake?: {
|
|
44
|
-
kind: "job" | "subagent";
|
|
45
|
-
resourceId: string;
|
|
46
|
-
taskId: string;
|
|
47
|
-
dispatchId: string;
|
|
48
|
-
};
|
|
49
|
-
/**
|
|
50
|
-
* The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
|
|
51
|
-
* Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
|
|
52
|
-
* turn from the current one, even when redelivery or claim races reorder completions.
|
|
53
|
-
*/
|
|
54
|
-
taskAttemptGeneration?: number;
|
|
55
|
-
}
|
|
26
|
+
/**
|
|
27
|
+
* `DingTalkEvent` is kept as the public name (spec 035 D4: `src/index.ts`'s barrel is a
|
|
28
|
+
* compatibility promise, so exported names there stay stable). Internally the type now lives in
|
|
29
|
+
* `channel-event.ts` as `ChannelEvent`: most producers of this shape are not DingTalk at all
|
|
30
|
+
* (job-manager, task-driver, events, subagents/runs all synthesize wakes), so `ChannelEvent` is
|
|
31
|
+
* what the rest of the runtime imports.
|
|
32
|
+
*/
|
|
33
|
+
export type DingTalkEvent = ChannelEvent;
|
|
56
34
|
export type BusyMessageResult = {
|
|
57
35
|
kind: "handled";
|
|
58
36
|
} | {
|