@oyasmi/pipiclaw 0.9.0-beta.9 → 0.9.1-beta.1
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 +12 -0
- package/dist/agent/channel-runner.js +88 -8
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +12 -1
- 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/agent/types.d.ts +6 -0
- package/dist/memory/lifecycle.d.ts +15 -0
- package/dist/memory/lifecycle.js +60 -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 +54 -0
- package/dist/runtime/active-session-store.js +126 -0
- package/dist/runtime/bootstrap.js +122 -3
- package/dist/runtime/delivery.js +1 -1
- package/dist/runtime/dingtalk.d.ts +7 -0
- package/dist/runtime/dingtalk.js +24 -4
- 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
package/dist/memory/lifecycle.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
1
2
|
import * as log from "../log.js";
|
|
2
3
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
4
|
+
import { clipTextByPromptUnits } from "../shared/prompt-units.js";
|
|
3
5
|
import { errorMessage } from "../shared/text-utils.js";
|
|
4
6
|
import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
5
7
|
import { runInlineConsolidation, } from "./consolidation.js";
|
|
@@ -7,6 +9,51 @@ import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./mai
|
|
|
7
9
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
8
10
|
import { updateChannelSessionMemory } from "./session.js";
|
|
9
11
|
import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow, } from "./source-window.js";
|
|
12
|
+
const COMPACTION_INPUT_MAX_UNITS = 48_000;
|
|
13
|
+
const COMPACTION_INPUT_MIN_UNITS = 4_000;
|
|
14
|
+
const COMPACTION_INPUT_CHARS_PER_TOKEN = 3;
|
|
15
|
+
const COMPACTION_INPUT_HEAD_RATIO = 0.35;
|
|
16
|
+
/**
|
|
17
|
+
* Bound one standalone summarization request. Provider limits can be lower than a model's
|
|
18
|
+
* advertised context window; sending the whole pre-compaction transcript is therefore not safe.
|
|
19
|
+
* The head preserves the original goal and the larger tail preserves current work. Durable
|
|
20
|
+
* memory is refreshed before this runs, so the omitted middle is still available outside the
|
|
21
|
+
* provider request.
|
|
22
|
+
*/
|
|
23
|
+
export function boundCompactionMessages(messages, contextWindow, reserveTokens) {
|
|
24
|
+
if (messages.length === 0) {
|
|
25
|
+
return { messages, truncated: false, originalChars: 0, boundedChars: 0 };
|
|
26
|
+
}
|
|
27
|
+
const safeWindow = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : 128_000;
|
|
28
|
+
const safeReserve = Number.isFinite(reserveTokens) && reserveTokens > 0 ? Math.floor(reserveTokens) : 16_384;
|
|
29
|
+
const maxUnits = Math.min(COMPACTION_INPUT_MAX_UNITS, Math.max(COMPACTION_INPUT_MIN_UNITS, safeWindow - safeReserve - 8_192));
|
|
30
|
+
const serialized = serializeConversation(convertToLlm(messages));
|
|
31
|
+
const clipped = clipTextByPromptUnits(serialized, maxUnits, {
|
|
32
|
+
headRatio: COMPACTION_INPUT_HEAD_RATIO,
|
|
33
|
+
maxChars: maxUnits * COMPACTION_INPUT_CHARS_PER_TOKEN,
|
|
34
|
+
marker: "\n\n[... middle omitted from this compaction request; durable channel memory was refreshed before compaction ...]\n\n",
|
|
35
|
+
});
|
|
36
|
+
if (!clipped.truncated) {
|
|
37
|
+
return {
|
|
38
|
+
messages,
|
|
39
|
+
truncated: false,
|
|
40
|
+
originalChars: serialized.length,
|
|
41
|
+
boundedChars: serialized.length,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
messages: [
|
|
46
|
+
{
|
|
47
|
+
role: "user",
|
|
48
|
+
content: [{ type: "text", text: clipped.text }],
|
|
49
|
+
timestamp: Date.now(),
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
truncated: true,
|
|
53
|
+
originalChars: serialized.length,
|
|
54
|
+
boundedChars: clipped.text.length,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
10
57
|
export class MemoryLifecycle {
|
|
11
58
|
constructor(options) {
|
|
12
59
|
this.options = options;
|
|
@@ -243,6 +290,14 @@ export class MemoryLifecycle {
|
|
|
243
290
|
}
|
|
244
291
|
async handleSessionBeforeCompact(event) {
|
|
245
292
|
await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
|
|
293
|
+
const model = this.options.getModel();
|
|
294
|
+
for (const key of ["messagesToSummarize", "turnPrefixMessages"]) {
|
|
295
|
+
const bounded = boundCompactionMessages(event.preparation[key] ?? [], model.contextWindow, event.preparation.settings?.reserveTokens ?? 16_384);
|
|
296
|
+
if (!bounded.truncated)
|
|
297
|
+
continue;
|
|
298
|
+
event.preparation[key] = bounded.messages;
|
|
299
|
+
log.logWarning(`[${this.options.channelId}] Bounded oversized compaction input (${key})`, `${bounded.originalChars} -> ${bounded.boundedChars} chars; model=${model.provider}/${model.id}`);
|
|
300
|
+
}
|
|
246
301
|
}
|
|
247
302
|
handleSessionCompact(_event) {
|
|
248
303
|
this.recordActivity("boundary");
|
|
@@ -251,6 +306,10 @@ export class MemoryLifecycle {
|
|
|
251
306
|
if (event.reason !== "new") {
|
|
252
307
|
return;
|
|
253
308
|
}
|
|
309
|
+
this.noteNewSessionBoundary();
|
|
310
|
+
}
|
|
311
|
+
/** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
|
|
312
|
+
noteNewSessionBoundary() {
|
|
254
313
|
// Snapshot the outgoing session synchronously: the switch has not happened
|
|
255
314
|
// yet, so getMessages()/getSessionEntries() still reference the session that
|
|
256
315
|
// is about to be replaced. Once we yield, this.session is rebound to the new
|
|
@@ -265,6 +324,7 @@ export class MemoryLifecycle {
|
|
|
265
324
|
const message = errorMessage(error);
|
|
266
325
|
log.logWarning(`[${this.options.channelId}] Background new-session consolidation rejected`, message);
|
|
267
326
|
});
|
|
327
|
+
this.recordActivity("boundary");
|
|
268
328
|
}
|
|
269
329
|
/** Await any in-flight detached new-session consolidation (shutdown/tests). */
|
|
270
330
|
async whenNewSessionConsolidationSettled() {
|
|
@@ -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,54 @@
|
|
|
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>;
|
|
43
|
+
/**
|
|
44
|
+
* Create a durable empty session and atomically make it active for a channel.
|
|
45
|
+
*
|
|
46
|
+
* This deliberately does not touch a live AgentSession. It is the transport-level `/new`
|
|
47
|
+
* primitive: a wedged provider request or compaction in the old runner cannot delay the
|
|
48
|
+
* commit. Materializing and reopening the file makes the SDK write the session header before
|
|
49
|
+
* the active ref points at it, preserving the same file-before-pointer ordering as normal SDK
|
|
50
|
+
* topology changes.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createFreshActiveSession(channelDir: string, cwd: string): Promise<{
|
|
53
|
+
sessionId: string;
|
|
54
|
+
}>;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
+
const REF_FILENAME = "active-session.json";
|
|
6
|
+
const DEFAULT_SESSION_FILENAME = "context.jsonl";
|
|
7
|
+
export function getActiveSessionRefPath(channelDir) {
|
|
8
|
+
return join(channelDir, REF_FILENAME);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The ref's `file` is opened for append under `channelDir`, and the ref itself lives in a
|
|
12
|
+
* directory a chat participant can otherwise influence the contents of. Reject anything that
|
|
13
|
+
* isn't a plain, single-segment `.jsonl` name so this can never be used to open or create a file
|
|
14
|
+
* outside the channel directory.
|
|
15
|
+
*/
|
|
16
|
+
export function isValidSessionRefBasename(file) {
|
|
17
|
+
return (typeof file === "string" &&
|
|
18
|
+
file.length > 0 &&
|
|
19
|
+
file.endsWith(".jsonl") &&
|
|
20
|
+
!file.includes("/") &&
|
|
21
|
+
!file.includes("\\") &&
|
|
22
|
+
!file.includes("\0") &&
|
|
23
|
+
file !== "." &&
|
|
24
|
+
file !== "..");
|
|
25
|
+
}
|
|
26
|
+
function readActiveSessionRef(channelDir) {
|
|
27
|
+
const refPath = getActiveSessionRefPath(channelDir);
|
|
28
|
+
if (!existsSync(refPath)) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
let raw;
|
|
32
|
+
try {
|
|
33
|
+
raw = JSON.parse(readFileSync(refPath, "utf-8"));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
if (!raw ||
|
|
39
|
+
typeof raw !== "object" ||
|
|
40
|
+
raw.version !== 1 ||
|
|
41
|
+
typeof raw.file !== "string" ||
|
|
42
|
+
typeof raw.sessionId !== "string" ||
|
|
43
|
+
typeof raw.updatedAt !== "string") {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const ref = raw;
|
|
47
|
+
return isValidSessionRefBasename(ref.file) ? ref : undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* An existing-but-empty file makes the SDK's `SessionManager._setSessionFile()` write the header
|
|
51
|
+
* and flip `flushed = true` synchronously, instead of the deferred-flush path it takes for a file
|
|
52
|
+
* that doesn't exist yet. Materializing this before `SessionManager.open()` closes the delay
|
|
53
|
+
* window described in spec 043 F4/D1.2 without touching SDK internals.
|
|
54
|
+
*/
|
|
55
|
+
function materializeSessionFile(channelDir, file) {
|
|
56
|
+
const target = join(channelDir, file);
|
|
57
|
+
if (!existsSync(target)) {
|
|
58
|
+
closeSync(openSync(target, "a"));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Resolves which session file a channel should open (runner construction / restart), migrating a
|
|
63
|
+
* channel with no ref to `context.jsonl` and materializing that file. Never writes the ref
|
|
64
|
+
* itself — a missing ref stays missing until a session-topology operation commits one.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveActiveSessionFile(channelDir) {
|
|
67
|
+
const ref = readActiveSessionRef(channelDir);
|
|
68
|
+
const file = ref?.file ?? DEFAULT_SESSION_FILENAME;
|
|
69
|
+
materializeSessionFile(channelDir, file);
|
|
70
|
+
return file;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Commits the active-session ref for a session a topology operation (`/new`, fork, switch) has
|
|
74
|
+
* already created/opened. The SDK writes that session's durable header synchronously before
|
|
75
|
+
* invoking the caller's rebuild callback, so by the time this is called the target file already
|
|
76
|
+
* exists on disk; this only records the pointer. Callers must not rebind their live `AgentSession`
|
|
77
|
+
* until this resolves (spec 043, D1.3) — on throw, nothing is written and the old ref (and thus
|
|
78
|
+
* the old session) remains authoritative.
|
|
79
|
+
*/
|
|
80
|
+
export async function commitActiveSessionRef(channelDir, session) {
|
|
81
|
+
const sessionFile = session.getSessionFile();
|
|
82
|
+
if (!sessionFile) {
|
|
83
|
+
throw new Error("Cannot commit active-session ref: session has no backing file (not persisted).");
|
|
84
|
+
}
|
|
85
|
+
const resolvedDir = resolve(channelDir);
|
|
86
|
+
const resolvedFile = resolve(sessionFile);
|
|
87
|
+
if (dirname(resolvedFile) !== resolvedDir) {
|
|
88
|
+
throw new Error(`Session file must live directly under the channel directory: ${sessionFile}`);
|
|
89
|
+
}
|
|
90
|
+
const file = basename(resolvedFile);
|
|
91
|
+
if (!isValidSessionRefBasename(file)) {
|
|
92
|
+
throw new Error(`Invalid session file name for active-session ref: ${file}`);
|
|
93
|
+
}
|
|
94
|
+
const ref = {
|
|
95
|
+
version: 1,
|
|
96
|
+
file,
|
|
97
|
+
sessionId: session.getSessionId(),
|
|
98
|
+
updatedAt: new Date().toISOString(),
|
|
99
|
+
};
|
|
100
|
+
await writeFileAtomically(getActiveSessionRefPath(channelDir), `${JSON.stringify(ref, null, 2)}\n`);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Create a durable empty session and atomically make it active for a channel.
|
|
104
|
+
*
|
|
105
|
+
* This deliberately does not touch a live AgentSession. It is the transport-level `/new`
|
|
106
|
+
* primitive: a wedged provider request or compaction in the old runner cannot delay the
|
|
107
|
+
* commit. Materializing and reopening the file makes the SDK write the session header before
|
|
108
|
+
* the active ref points at it, preserving the same file-before-pointer ordering as normal SDK
|
|
109
|
+
* topology changes.
|
|
110
|
+
*/
|
|
111
|
+
export async function createFreshActiveSession(channelDir, cwd) {
|
|
112
|
+
const provisional = SessionManager.create(cwd, channelDir);
|
|
113
|
+
const sessionFile = provisional.getSessionFile();
|
|
114
|
+
if (!sessionFile) {
|
|
115
|
+
throw new Error("Cannot create a new session: the SDK did not allocate a backing file.");
|
|
116
|
+
}
|
|
117
|
+
const resolvedDir = resolve(channelDir);
|
|
118
|
+
const resolvedFile = resolve(sessionFile);
|
|
119
|
+
if (dirname(resolvedFile) !== resolvedDir) {
|
|
120
|
+
throw new Error(`New session file must live directly under the channel directory: ${sessionFile}`);
|
|
121
|
+
}
|
|
122
|
+
materializeSessionFile(channelDir, basename(resolvedFile));
|
|
123
|
+
const durable = SessionManager.open(resolvedFile, channelDir, cwd);
|
|
124
|
+
await commitActiveSessionRef(channelDir, durable);
|
|
125
|
+
return { sessionId: durable.getSessionId() };
|
|
126
|
+
}
|
|
@@ -3,26 +3,30 @@ 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";
|
|
17
|
+
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
15
18
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
16
19
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
17
20
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
18
21
|
import { errorMessage } from "../shared/text-utils.js";
|
|
19
22
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
20
|
-
import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentGarbageCollector } from "../subagents/runs.js";
|
|
23
|
+
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
|
|
21
24
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
22
25
|
import { finishTaskAttempt } from "../tasks/store.js";
|
|
23
26
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
24
27
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
25
28
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
29
|
+
import { createFreshActiveSession } from "./active-session-store.js";
|
|
26
30
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
|
|
27
31
|
import { createChannelIndex } from "./channel-index.js";
|
|
28
32
|
import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
|
|
@@ -31,6 +35,8 @@ import { DingTalkBot, } from "./dingtalk.js";
|
|
|
31
35
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
32
36
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
33
37
|
import { createEventsWatcher } from "./events.js";
|
|
38
|
+
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
39
|
+
import { resolveProjectScope } from "./project-scope-store.js";
|
|
34
40
|
import { installLlmProxy } from "./proxy.js";
|
|
35
41
|
import { ChannelStore } from "./store.js";
|
|
36
42
|
import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
@@ -90,7 +96,7 @@ function isNoRunningTaskQueueError(err) {
|
|
|
90
96
|
* idle answers it through the runner's ChannelContext-aware command path (thread-reply, delete
|
|
91
97
|
* semantics) instead, so it is not part of this stateless-report dispatch here.
|
|
92
98
|
*/
|
|
93
|
-
const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents"]);
|
|
99
|
+
const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents", "project"]);
|
|
94
100
|
function isIdleRuntimeCommandName(name) {
|
|
95
101
|
return IDLE_RUNTIME_COMMAND_NAMES.has(name);
|
|
96
102
|
}
|
|
@@ -136,6 +142,7 @@ export async function createRuntimeContext(options) {
|
|
|
136
142
|
const startedAt = Date.now();
|
|
137
143
|
const cliVersion = readCliVersion();
|
|
138
144
|
const channelRunners = new Map();
|
|
145
|
+
const sessionResetChains = new Map();
|
|
139
146
|
const activeTasks = new Set();
|
|
140
147
|
/** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
|
|
141
148
|
const stopWatchdogs = new Set();
|
|
@@ -248,6 +255,69 @@ export async function createRuntimeContext(options) {
|
|
|
248
255
|
}
|
|
249
256
|
return { pausedTaskId };
|
|
250
257
|
},
|
|
258
|
+
async handleNewSession(event, _bot) {
|
|
259
|
+
if (shuttingDown)
|
|
260
|
+
return;
|
|
261
|
+
const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
|
|
262
|
+
const reset = previous
|
|
263
|
+
.catch(() => undefined)
|
|
264
|
+
.then(async () => {
|
|
265
|
+
try {
|
|
266
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
267
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
268
|
+
const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
|
|
269
|
+
const scope = resolveProjectScope(channelDir, access);
|
|
270
|
+
if (scope.kind === "blocked") {
|
|
271
|
+
throw new Error(scope.reason);
|
|
272
|
+
}
|
|
273
|
+
// The empty session file and active pointer are committed before the old
|
|
274
|
+
// generation is touched. A filesystem failure therefore leaves the live
|
|
275
|
+
// session authoritative and retryable.
|
|
276
|
+
const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
|
|
277
|
+
const oldRunner = channelRunners.get(event.channelId);
|
|
278
|
+
if (oldRunner) {
|
|
279
|
+
channelRunners.delete(event.channelId);
|
|
280
|
+
try {
|
|
281
|
+
oldRunner.retireForNewSession?.();
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
// The active pointer already names the new session. Retirement is
|
|
285
|
+
// best-effort cleanup and must not misreport the committed reset as failed.
|
|
286
|
+
log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const dropped = _bot.resetChannelQueue(event.channelId);
|
|
290
|
+
if (dropped > 0) {
|
|
291
|
+
log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
|
|
292
|
+
}
|
|
293
|
+
await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
|
|
294
|
+
void archiveIncomingMessage(event.channelId, {
|
|
295
|
+
date: new Date().toISOString(),
|
|
296
|
+
ts: event.ts,
|
|
297
|
+
user: event.user,
|
|
298
|
+
userName: event.userName,
|
|
299
|
+
text: event.text,
|
|
300
|
+
isBot: false,
|
|
301
|
+
}, "/new command");
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
const message = errorMessage(error);
|
|
305
|
+
log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
|
|
306
|
+
await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
sessionResetChains.set(event.channelId, reset);
|
|
310
|
+
activeTasks.add(reset);
|
|
311
|
+
try {
|
|
312
|
+
await reset;
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
activeTasks.delete(reset);
|
|
316
|
+
if (sessionResetChains.get(event.channelId) === reset) {
|
|
317
|
+
sessionResetChains.delete(event.channelId);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
},
|
|
251
321
|
async runRuntimeCommand(event, name, args) {
|
|
252
322
|
switch (name) {
|
|
253
323
|
case "events":
|
|
@@ -304,6 +374,31 @@ export async function createRuntimeContext(options) {
|
|
|
304
374
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
305
375
|
}),
|
|
306
376
|
});
|
|
377
|
+
case "project":
|
|
378
|
+
return runProjectCommand({
|
|
379
|
+
args,
|
|
380
|
+
channelId: event.channelId,
|
|
381
|
+
channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
|
|
382
|
+
appHomeDir: options.paths.appHomeDir,
|
|
383
|
+
actor: "dingtalk-command",
|
|
384
|
+
isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
|
|
385
|
+
listActiveBlockers: () => [
|
|
386
|
+
...getSubAgentRunManager(event.channelId)
|
|
387
|
+
.list()
|
|
388
|
+
.filter((record) => record.status === "running")
|
|
389
|
+
.map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
|
|
390
|
+
...channelRunningJobLines(event.channelId),
|
|
391
|
+
],
|
|
392
|
+
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
393
|
+
// The active-session ref is untouched — same session, new project root.
|
|
394
|
+
onScopeChanged: async () => {
|
|
395
|
+
const runner = channelRunners.get(event.channelId);
|
|
396
|
+
channelRunners.delete(event.channelId);
|
|
397
|
+
await runner?.dispose().catch((err) => {
|
|
398
|
+
log.logWarning(`[${event.channelId}] Failed to dispose runner after /project`, errorMessage(err));
|
|
399
|
+
});
|
|
400
|
+
},
|
|
401
|
+
});
|
|
307
402
|
}
|
|
308
403
|
},
|
|
309
404
|
async handleBusyMessage(event, bot, mode, queueText) {
|
|
@@ -317,6 +412,13 @@ export async function createRuntimeContext(options) {
|
|
|
317
412
|
await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
|
|
318
413
|
return { kind: "handled" };
|
|
319
414
|
}
|
|
415
|
+
// Compaction is maintenance, not user work. A new message cancels it and is
|
|
416
|
+
// kept as a normal queued turn instead of trying to steer an agent loop that
|
|
417
|
+
// is currently disconnected for summarization.
|
|
418
|
+
if (runner.interruptCompaction?.()) {
|
|
419
|
+
log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
|
|
420
|
+
return { kind: "requeue", text: trimmedQueueText };
|
|
421
|
+
}
|
|
320
422
|
if (mode === "followUp") {
|
|
321
423
|
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
322
424
|
ctx: { channelId: event.channelId, userName: event.userName },
|
|
@@ -563,6 +665,23 @@ export async function createRuntimeContext(options) {
|
|
|
563
665
|
// for background jobs.
|
|
564
666
|
await restoreChannelJobs(executor);
|
|
565
667
|
await restoreAllSubAgentRuns();
|
|
668
|
+
// Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
|
|
669
|
+
// admission — a message routed to a still-dangling session would 400 against the provider on
|
|
670
|
+
// every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
|
|
671
|
+
// the job/run restores above: admission must see a structurally legal session, not a partial one.
|
|
672
|
+
const recoveryReport = await scanWorkspaceForInterruptedTurns(options.paths.workspaceDir, {
|
|
673
|
+
api: defaultModel.api,
|
|
674
|
+
provider: defaultModel.provider,
|
|
675
|
+
model: defaultModel.id,
|
|
676
|
+
});
|
|
677
|
+
if (recoveryReport.repaired.length > 0) {
|
|
678
|
+
log.logWarning("Repaired interrupted turns on restart", `${recoveryReport.repaired.length}/${recoveryReport.scanned} channel(s): ${recoveryReport.repaired
|
|
679
|
+
.map((r) => r.channelDir)
|
|
680
|
+
.join(", ")}`);
|
|
681
|
+
}
|
|
682
|
+
if (recoveryReport.blocked.length > 0) {
|
|
683
|
+
log.logWarning("Some channels have an unrecoverable session and will refuse new turns", recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "));
|
|
684
|
+
}
|
|
566
685
|
const eventsWatcher = options.createEventsWatcher
|
|
567
686
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
568
687
|
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -63,7 +63,7 @@ class ChannelDeliveryController {
|
|
|
63
63
|
respondPlain: async (text, shouldLog = true) => this.sendFinal(text, shouldLog),
|
|
64
64
|
replaceMessage: async (text) => this.replaceWithFinal(text),
|
|
65
65
|
respondInThread: async (text) => {
|
|
66
|
-
if (!text.trim()) {
|
|
66
|
+
if (this.closed || !text.trim()) {
|
|
67
67
|
return;
|
|
68
68
|
}
|
|
69
69
|
const delivered = await this.bot.sendPlain(this.event.channelId, text);
|
|
@@ -60,6 +60,8 @@ export interface DingTalkHandler {
|
|
|
60
60
|
reserveEvent?(event: DingTalkEvent): void;
|
|
61
61
|
handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
|
|
62
62
|
handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
|
|
63
|
+
/** `/new` bypasses the old per-channel queue and live SDK session. */
|
|
64
|
+
handleNewSession(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
|
|
63
65
|
/**
|
|
64
66
|
* Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
|
|
65
67
|
* text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
|
|
@@ -185,6 +187,11 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
185
187
|
* do not run after the user halts the current task. Returns dropped count.
|
|
186
188
|
*/
|
|
187
189
|
clearPendingMessages(channelId: string): number;
|
|
190
|
+
/**
|
|
191
|
+
* Detach all queued work from the previous session generation. The in-flight callback may
|
|
192
|
+
* still unwind on its old queue object, while subsequent messages get a fresh queue.
|
|
193
|
+
*/
|
|
194
|
+
resetChannelQueue(channelId: string): number;
|
|
188
195
|
private getQueue;
|
|
189
196
|
private getConversationMeta;
|
|
190
197
|
private setConversationMeta;
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -11,7 +11,7 @@ import axios from "axios";
|
|
|
11
11
|
import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
|
|
12
12
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
13
13
|
import { dirname, join } from "path";
|
|
14
|
-
import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, } from "../agent/commands.js";
|
|
14
|
+
import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
|
|
15
15
|
import * as log from "../log.js";
|
|
16
16
|
import { errorMessage } from "../shared/text-utils.js";
|
|
17
17
|
import { isRecord } from "../shared/type-guards.js";
|
|
@@ -1069,6 +1069,13 @@ export class DingTalkBot {
|
|
|
1069
1069
|
};
|
|
1070
1070
|
const builtInCommand = parseBuiltInCommand(content);
|
|
1071
1071
|
const isSlashCommand = content.trim().startsWith("/");
|
|
1072
|
+
// `/new` is an emergency boundary as well as a session command. Route it before
|
|
1073
|
+
// busy checking and before the old channel queue, so a wedged compaction/provider
|
|
1074
|
+
// request cannot prevent recovery.
|
|
1075
|
+
if (slashCommandName(content) === "new") {
|
|
1076
|
+
await this.handler.handleNewSession(event, this);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1072
1079
|
// Check if busy
|
|
1073
1080
|
if (this.handler.isRunning(channelId)) {
|
|
1074
1081
|
// All built-in transport commands are usable while a task streams.
|
|
@@ -1098,17 +1105,18 @@ export class DingTalkBot {
|
|
|
1098
1105
|
case "status":
|
|
1099
1106
|
case "usage":
|
|
1100
1107
|
case "context":
|
|
1101
|
-
case "subagents":
|
|
1108
|
+
case "subagents":
|
|
1109
|
+
case "project": {
|
|
1102
1110
|
const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
|
|
1103
1111
|
await this.sendPlain(channelId, response);
|
|
1104
1112
|
return;
|
|
1105
1113
|
}
|
|
1106
1114
|
}
|
|
1107
1115
|
}
|
|
1108
|
-
//
|
|
1116
|
+
// Other session commands (/model, /compact, …) and unknown slash commands cannot
|
|
1109
1117
|
// run mid-turn: they would need the idle session layer.
|
|
1110
1118
|
if (isSlashCommand) {
|
|
1111
|
-
await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/
|
|
1119
|
+
await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
|
|
1112
1120
|
return;
|
|
1113
1121
|
}
|
|
1114
1122
|
const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
|
|
@@ -1128,6 +1136,18 @@ export class DingTalkBot {
|
|
|
1128
1136
|
const queue = this.queues.get(channelId);
|
|
1129
1137
|
return queue ? queue.clearPending() : 0;
|
|
1130
1138
|
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Detach all queued work from the previous session generation. The in-flight callback may
|
|
1141
|
+
* still unwind on its old queue object, while subsequent messages get a fresh queue.
|
|
1142
|
+
*/
|
|
1143
|
+
resetChannelQueue(channelId) {
|
|
1144
|
+
const queue = this.queues.get(channelId);
|
|
1145
|
+
const dropped = queue?.clearPending() ?? 0;
|
|
1146
|
+
queue?.stop();
|
|
1147
|
+
this.queues.delete(channelId);
|
|
1148
|
+
this.discardCard(channelId);
|
|
1149
|
+
return dropped;
|
|
1150
|
+
}
|
|
1131
1151
|
getQueue(channelId) {
|
|
1132
1152
|
this.touchChannel(channelId);
|
|
1133
1153
|
let queue = this.queues.get(channelId);
|
|
@@ -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>;
|