@oyasmi/pipiclaw 0.7.5 → 0.7.7
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/README.md +11 -1
- package/dist/agent/channel-runner.js +7 -3
- package/dist/agent/commands.js +2 -1
- package/dist/agent/job-manager.d.ts +79 -0
- package/dist/agent/job-manager.js +241 -0
- package/dist/agent/prompt-builder.js +13 -4
- package/dist/agent/session-events.js +5 -0
- package/dist/memory/recall.js +6 -0
- package/dist/memory/review-log.d.ts +1 -1
- package/dist/models/api-keys.d.ts +5 -1
- package/dist/models/api-keys.js +10 -4
- package/dist/runtime/bootstrap.js +2 -0
- package/dist/runtime/dingtalk.js +13 -1
- package/dist/runtime/task-commands.d.ts +3 -0
- package/dist/runtime/task-commands.js +148 -2
- package/dist/shared/atomic-file.js +23 -3
- package/dist/shared/task-events.d.ts +32 -0
- package/dist/shared/task-events.js +29 -0
- package/dist/shared/task-ledger.d.ts +26 -0
- package/dist/shared/task-ledger.js +38 -0
- package/dist/subagents/tool.js +26 -4
- package/dist/tools/bash.d.ts +12 -0
- package/dist/tools/bash.js +67 -1
- package/dist/tools/config.d.ts +9 -0
- package/dist/tools/config.js +23 -0
- package/dist/tools/edit.js +0 -0
- package/dist/tools/grep.d.ts +19 -0
- package/dist/tools/grep.js +262 -0
- package/dist/tools/index.js +5 -0
- package/dist/tools/job.d.ts +13 -0
- package/dist/tools/job.js +92 -0
- package/dist/tools/memory-manage.d.ts +24 -0
- package/dist/tools/memory-manage.js +150 -0
- package/dist/tools/read.js +103 -16
- package/dist/tools/registry.d.ts +7 -1
- package/dist/tools/registry.js +31 -23
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill-manage.d.ts +12 -5
- package/dist/tools/skill-manage.js +113 -15
- package/dist/tools/task-manage.d.ts +16 -2
- package/dist/tools/task-manage.js +119 -22
- package/dist/tools/web-cache.d.ts +11 -0
- package/dist/tools/web-cache.js +62 -0
- package/dist/tools/web-fetch.d.ts +3 -0
- package/dist/tools/web-fetch.js +73 -5
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.js +1 -1
- package/package.json +1 -1
- package/dist/tools/memory-save.d.ts +0 -16
- package/dist/tools/memory-save.js +0 -42
- package/dist/tools/skill-list.d.ts +0 -18
- package/dist/tools/skill-list.js +0 -86
- package/dist/tools/skill-view.d.ts +0 -13
- package/dist/tools/skill-view.js +0 -44
package/README.md
CHANGED
|
@@ -24,7 +24,11 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
|
|
|
24
24
|
- 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
|
|
25
25
|
- 支持立即、单次、周期三类事件调度
|
|
26
26
|
- 支持自定义模型提供方(provider)和模型(model)配置
|
|
27
|
-
- 内建 `web_search` / `web_fetch
|
|
27
|
+
- 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取;`web_fetch` 支持结果缓存与分页续读,长网页被截断后可直接续读、不重抓
|
|
28
|
+
- 内建 `grep` 结构化搜索工具:按文件分组、分页、token 有界的内容检索,优于裸 `bash grep`
|
|
29
|
+
- 支持后台作业:`bash async` + `job` 工具,长命令后台运行、不阻塞频道,可 poll / cancel
|
|
30
|
+
- 内建 `memory_manage` 记忆管理:按需保存 / 检索 / 忘记稳定记忆,写操作串行化,避免与后台整理竞态
|
|
31
|
+
- `read` 支持读取目录树与 PDF 文档(`pdftotext`)
|
|
28
32
|
- 内建 `session_search`,可按需检索当前会话通道的冷存储历史
|
|
29
33
|
- 内建 workspace skill 管理工具,可查看、创建和维护 `workspace/skills/`
|
|
30
34
|
- 内置工具层安全防护:`bash` 命令守卫、文件路径守卫、敏感路径拒绝、阻断审计日志
|
|
@@ -454,6 +458,9 @@ Pipiclaw 有两层命令。
|
|
|
454
458
|
| `/events show <name>` | 查看指定事件文件的完整 JSON |
|
|
455
459
|
| `/events delete <name>` | 删除指定事件文件 |
|
|
456
460
|
| `/events history [name]` | 查看事件调度历史,可按事件名过滤 |
|
|
461
|
+
| `/tasks [all\|archived]` | 查看当前通道的 active 或 archived 任务台账 |
|
|
462
|
+
| `/tasks show <id>` | 查看指定任务台账 |
|
|
463
|
+
| `/tasks doctor` | 诊断任务台账与 task event 的一致性问题 |
|
|
457
464
|
| `/status` | 查看运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
|
|
458
465
|
| `/usage [7d\|month]` | 查看本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
|
|
459
466
|
|
|
@@ -509,6 +516,7 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
|
|
|
509
516
|
│ ├── SESSION.md
|
|
510
517
|
│ ├── MEMORY.md
|
|
511
518
|
│ ├── HISTORY.md
|
|
519
|
+
│ ├── tasks/
|
|
512
520
|
│ ├── .channel-meta.json
|
|
513
521
|
│ ├── context.jsonl
|
|
514
522
|
│ ├── log.jsonl
|
|
@@ -529,6 +537,8 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
|
|
|
529
537
|
稳定事实、决策和偏好
|
|
530
538
|
- `HISTORY.md`
|
|
531
539
|
更早上下文的摘要
|
|
540
|
+
- `<channel>/tasks/`
|
|
541
|
+
当前通道的长程任务台账;active 任务位于目录根部,完成后的任务归档到 `tasks/archive/`
|
|
532
542
|
|
|
533
543
|
## 记忆模型(Memory Model)
|
|
534
544
|
|
|
@@ -16,7 +16,6 @@ import { createExecutor } from "../sandbox.js";
|
|
|
16
16
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
17
17
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
18
18
|
import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
|
|
19
|
-
import { HAN_REGEX } from "../shared/text-utils.js";
|
|
20
19
|
import { isRecord } from "../shared/type-guards.js";
|
|
21
20
|
import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
|
|
22
21
|
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -169,7 +168,6 @@ export class ChannelRunner {
|
|
|
169
168
|
const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS);
|
|
170
169
|
const userMessage = this.formatUserMessage(clippedInput, ctx.message.userName);
|
|
171
170
|
const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
|
|
172
|
-
await this.maybeRunPreventiveCompactionForIncomingText(preserveRawInput ? clippedInput : userMessage);
|
|
173
171
|
// Ensure channel directory exists
|
|
174
172
|
await mkdir(this.channelDir, { recursive: true });
|
|
175
173
|
let promptText = preserveRawInput ? clippedInput : userMessage;
|
|
@@ -188,7 +186,9 @@ export class ChannelRunner {
|
|
|
188
186
|
maxInjected: recallSettings.maxInjected,
|
|
189
187
|
maxChars: recallSettings.maxChars,
|
|
190
188
|
rerankWithModel: recallSettings.rerankWithModel,
|
|
191
|
-
|
|
189
|
+
// Let shouldUseModelRerank's own memory-intent gate decide (it already handles
|
|
190
|
+
// Chinese phrasing) — forcing autoRerank for every Han-script message triggered a
|
|
191
|
+
// model rerank (up to 8s) on nearly every Chinese turn once memory filled up.
|
|
192
192
|
model: this.session.model ?? this.activeModel,
|
|
193
193
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
194
194
|
candidateStore: this.memoryCandidateStore,
|
|
@@ -217,6 +217,10 @@ export class ChannelRunner {
|
|
|
217
217
|
this.firstTurnMemoryBootstrapPending = false;
|
|
218
218
|
}
|
|
219
219
|
}
|
|
220
|
+
// Estimated against the fully assembled prompt (recall + task digest + bootstrap all
|
|
221
|
+
// prepended above), not just the bare user message — those pieces can add thousands of
|
|
222
|
+
// characters and must count against the projected context usage this guard is checking.
|
|
223
|
+
await this.maybeRunPreventiveCompactionForIncomingText(promptText);
|
|
220
224
|
// Debug: write context to last_prompt.json (only with PIPICLAW_DEBUG=1)
|
|
221
225
|
if (process.env.PIPICLAW_DEBUG) {
|
|
222
226
|
const debugContext = {
|
package/dist/agent/commands.js
CHANGED
|
@@ -24,11 +24,12 @@ These are handled directly by the DingTalk transport/runtime layer.
|
|
|
24
24
|
Example: \`/events show weekly-review\`
|
|
25
25
|
Example: \`/events delete weekly-review\`
|
|
26
26
|
Example: \`/events history weekly-review\`
|
|
27
|
-
- \`/tasks [show <id>|archive]\`
|
|
27
|
+
- \`/tasks [show <id>|archive|doctor]\`
|
|
28
28
|
View the channel's task ledger (read-only); to change a task, just tell me in plain language
|
|
29
29
|
Example: \`/tasks\`
|
|
30
30
|
Example: \`/tasks show weekly-report\`
|
|
31
31
|
Example: \`/tasks archive\`
|
|
32
|
+
Example: \`/tasks doctor\`
|
|
32
33
|
- \`/status\`
|
|
33
34
|
Show runtime status: run state, current model, context usage, uptime, version
|
|
34
35
|
Example: \`/status\`
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Executor } from "../sandbox.js";
|
|
2
|
+
/**
|
|
3
|
+
* Per-channel manager for background bash jobs. A long command that ran synchronously would hold
|
|
4
|
+
* the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
|
|
5
|
+
* message. A background job instead returns immediately; the model can end its turn (freeing the
|
|
6
|
+
* queue) and check back later — typically by scheduling a check-in with `event_manage`, or by
|
|
7
|
+
* calling the `job` tool to poll.
|
|
8
|
+
*
|
|
9
|
+
* Jobs live entirely in the executor's world (host or Docker), managed through shell commands
|
|
10
|
+
* (`nohup` to launch, `kill -0` to probe, `kill` to cancel), so this works identically in both
|
|
11
|
+
* sandboxes with no in-process child handles. Manager state is in-memory and not persisted: after a
|
|
12
|
+
* process restart, prior jobs surface as `lost` rather than being falsely resurrected.
|
|
13
|
+
*/
|
|
14
|
+
export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
|
|
15
|
+
export interface JobSnapshot {
|
|
16
|
+
id: string;
|
|
17
|
+
label: string;
|
|
18
|
+
command: string;
|
|
19
|
+
status: JobStatus;
|
|
20
|
+
startedAt: number;
|
|
21
|
+
durationMs: number;
|
|
22
|
+
exitCode?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
|
|
25
|
+
export declare const MAX_RUNNING_JOBS = 5;
|
|
26
|
+
/** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
|
|
27
|
+
export declare const POLL_WAIT_MS = 30000;
|
|
28
|
+
/**
|
|
29
|
+
* How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
|
|
30
|
+
* finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
|
|
31
|
+
* so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
|
|
32
|
+
* The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
|
|
33
|
+
* channel, so it stays within the design's "no automatic completion delivery" decision.
|
|
34
|
+
*/
|
|
35
|
+
export declare const SWEEP_INTERVAL_MS = 10000;
|
|
36
|
+
export declare class ChannelJobManager {
|
|
37
|
+
private readonly channelId;
|
|
38
|
+
private readonly executor;
|
|
39
|
+
private readonly sweepIntervalMs;
|
|
40
|
+
private readonly jobs;
|
|
41
|
+
private sweepTimer?;
|
|
42
|
+
private sweeping;
|
|
43
|
+
constructor(channelId: string, executor: Executor, sweepIntervalMs?: number);
|
|
44
|
+
get channel(): string;
|
|
45
|
+
runningCount(): number;
|
|
46
|
+
/**
|
|
47
|
+
* Launch a command in the background and return its job id. The wrapper writes merged
|
|
48
|
+
* stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
|
|
49
|
+
* `echo $!` hands back the nohup PID for later probing/cancellation.
|
|
50
|
+
*/
|
|
51
|
+
start(command: string, label: string, timeoutSeconds: number, signal?: AbortSignal): Promise<JobSnapshot>;
|
|
52
|
+
/**
|
|
53
|
+
* Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
|
|
54
|
+
* so their slots free up even when the model never polls, and stops itself once nothing is running.
|
|
55
|
+
*/
|
|
56
|
+
private ensureSweeper;
|
|
57
|
+
private stopSweeper;
|
|
58
|
+
private sweep;
|
|
59
|
+
/** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
|
|
60
|
+
private refresh;
|
|
61
|
+
private kill;
|
|
62
|
+
list(signal?: AbortSignal): Promise<JobSnapshot[]>;
|
|
63
|
+
cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
|
|
64
|
+
id: string;
|
|
65
|
+
status: JobStatus | "not_found";
|
|
66
|
+
}>>;
|
|
67
|
+
/**
|
|
68
|
+
* Wait until at least one watched job finishes or the wait window elapses, then return a
|
|
69
|
+
* snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
|
|
70
|
+
* running jobs.
|
|
71
|
+
*/
|
|
72
|
+
poll(ids: string[] | undefined, signal?: AbortSignal): Promise<JobSnapshot[]>;
|
|
73
|
+
/** Read the (possibly truncated) captured output of a finished or running job. */
|
|
74
|
+
readOutput(id: string, signal?: AbortSignal): Promise<{
|
|
75
|
+
spillFile: string;
|
|
76
|
+
text: string;
|
|
77
|
+
} | undefined>;
|
|
78
|
+
}
|
|
79
|
+
export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
3
|
+
/** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
|
|
4
|
+
export const MAX_RUNNING_JOBS = 5;
|
|
5
|
+
/** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
|
|
6
|
+
export const POLL_WAIT_MS = 30_000;
|
|
7
|
+
const POLL_CHECK_INTERVAL_MS = 3_000;
|
|
8
|
+
/**
|
|
9
|
+
* How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
|
|
10
|
+
* finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
|
|
11
|
+
* so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
|
|
12
|
+
* The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
|
|
13
|
+
* channel, so it stays within the design's "no automatic completion delivery" decision.
|
|
14
|
+
*/
|
|
15
|
+
export const SWEEP_INTERVAL_MS = 10_000;
|
|
16
|
+
function jobSpillPath(id) {
|
|
17
|
+
return `/tmp/pipiclaw-job-${id}.log`;
|
|
18
|
+
}
|
|
19
|
+
function sleep(ms, signal) {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
const timer = setTimeout(resolve, ms);
|
|
22
|
+
signal?.addEventListener("abort", () => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
resolve();
|
|
25
|
+
}, { once: true });
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function toSnapshot(record) {
|
|
29
|
+
return {
|
|
30
|
+
id: record.id,
|
|
31
|
+
label: record.label,
|
|
32
|
+
command: record.command,
|
|
33
|
+
status: record.status,
|
|
34
|
+
startedAt: record.startedAt,
|
|
35
|
+
durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
|
|
36
|
+
exitCode: record.exitCode,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export class ChannelJobManager {
|
|
40
|
+
constructor(channelId, executor, sweepIntervalMs = SWEEP_INTERVAL_MS) {
|
|
41
|
+
this.channelId = channelId;
|
|
42
|
+
this.executor = executor;
|
|
43
|
+
this.sweepIntervalMs = sweepIntervalMs;
|
|
44
|
+
this.jobs = new Map();
|
|
45
|
+
this.sweeping = false;
|
|
46
|
+
}
|
|
47
|
+
get channel() {
|
|
48
|
+
return this.channelId;
|
|
49
|
+
}
|
|
50
|
+
runningCount() {
|
|
51
|
+
return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Launch a command in the background and return its job id. The wrapper writes merged
|
|
55
|
+
* stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
|
|
56
|
+
* `echo $!` hands back the nohup PID for later probing/cancellation.
|
|
57
|
+
*/
|
|
58
|
+
async start(command, label, timeoutSeconds, signal) {
|
|
59
|
+
if (this.runningCount() >= MAX_RUNNING_JOBS) {
|
|
60
|
+
throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
|
|
61
|
+
}
|
|
62
|
+
const id = randomBytes(6).toString("hex");
|
|
63
|
+
const spillFile = jobSpillPath(id);
|
|
64
|
+
const exitFile = `${spillFile}.exit`;
|
|
65
|
+
// Run the user command inside a subshell so its own `exit` only leaves the subshell and the
|
|
66
|
+
// exit-capture line still runs; otherwise a command ending in `exit N` would skip it and the
|
|
67
|
+
// job would look `lost` instead of finished.
|
|
68
|
+
const inner = `( ${command} )\n__pc_rc=$?; echo "$__pc_rc" > ${shellEscape(exitFile)}`;
|
|
69
|
+
const launch = `rm -f ${shellEscape(exitFile)}; nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
|
|
70
|
+
const result = await this.executor.exec(launch, { signal });
|
|
71
|
+
const pid = Number.parseInt(result.stdout.trim(), 10);
|
|
72
|
+
if (!Number.isFinite(pid) || pid <= 0) {
|
|
73
|
+
throw new Error(`Failed to start background job: ${result.stderr.trim() || "no PID returned"}`);
|
|
74
|
+
}
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const record = {
|
|
77
|
+
id,
|
|
78
|
+
label,
|
|
79
|
+
command,
|
|
80
|
+
status: "running",
|
|
81
|
+
startedAt: now,
|
|
82
|
+
durationMs: 0,
|
|
83
|
+
pid,
|
|
84
|
+
spillFile,
|
|
85
|
+
exitFile,
|
|
86
|
+
timeoutSeconds,
|
|
87
|
+
};
|
|
88
|
+
this.jobs.set(id, record);
|
|
89
|
+
this.ensureSweeper();
|
|
90
|
+
return toSnapshot(record);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
|
|
94
|
+
* so their slots free up even when the model never polls, and stops itself once nothing is running.
|
|
95
|
+
*/
|
|
96
|
+
ensureSweeper() {
|
|
97
|
+
if (this.sweepTimer || this.runningCount() === 0) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
this.sweepTimer = setInterval(() => {
|
|
101
|
+
void this.sweep();
|
|
102
|
+
}, this.sweepIntervalMs);
|
|
103
|
+
// Do not keep the process alive just for the sweeper.
|
|
104
|
+
this.sweepTimer.unref?.();
|
|
105
|
+
}
|
|
106
|
+
stopSweeper() {
|
|
107
|
+
if (this.sweepTimer) {
|
|
108
|
+
clearInterval(this.sweepTimer);
|
|
109
|
+
this.sweepTimer = undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async sweep() {
|
|
113
|
+
if (this.sweeping) {
|
|
114
|
+
return; // A prior sweep is still awaiting the executor; skip this tick.
|
|
115
|
+
}
|
|
116
|
+
this.sweeping = true;
|
|
117
|
+
try {
|
|
118
|
+
for (const record of this.jobs.values()) {
|
|
119
|
+
if (record.status === "running") {
|
|
120
|
+
await this.refresh(record).catch(() => { });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
this.sweeping = false;
|
|
126
|
+
if (this.runningCount() === 0) {
|
|
127
|
+
this.stopSweeper();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
|
|
132
|
+
async refresh(record, signal) {
|
|
133
|
+
if (record.status !== "running") {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
// Read the exit-code file if present, and separately check whether the PID is still alive.
|
|
137
|
+
const probe = await this.executor.exec(`if [ -f ${shellEscape(record.exitFile)} ]; then echo "EXIT:$(cat ${shellEscape(record.exitFile)})"; ` +
|
|
138
|
+
`elif kill -0 ${record.pid} 2>/dev/null; then echo ALIVE; else echo GONE; fi`, { signal });
|
|
139
|
+
const out = probe.stdout.trim();
|
|
140
|
+
if (out.startsWith("EXIT:")) {
|
|
141
|
+
const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
|
|
142
|
+
record.exitCode = Number.isFinite(code) ? code : undefined;
|
|
143
|
+
record.status = code === 0 ? "completed" : "failed";
|
|
144
|
+
record.durationMs = Date.now() - record.startedAt;
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (out === "GONE") {
|
|
148
|
+
// Process vanished without writing an exit code (killed externally, or manager restarted).
|
|
149
|
+
record.status = "lost";
|
|
150
|
+
record.durationMs = Date.now() - record.startedAt;
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
// Still alive: enforce the wall-clock budget from JS so we do not depend on a `timeout` binary.
|
|
154
|
+
if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
|
|
155
|
+
await this.kill(record, signal);
|
|
156
|
+
record.status = "failed";
|
|
157
|
+
record.exitCode = 124;
|
|
158
|
+
record.durationMs = Date.now() - record.startedAt;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async kill(record, signal) {
|
|
162
|
+
await this.executor
|
|
163
|
+
.exec(`kill ${record.pid} 2>/dev/null; sleep 0.2; kill -9 ${record.pid} 2>/dev/null; true`, { signal })
|
|
164
|
+
.catch(() => { });
|
|
165
|
+
}
|
|
166
|
+
async list(signal) {
|
|
167
|
+
for (const record of this.jobs.values()) {
|
|
168
|
+
await this.refresh(record, signal);
|
|
169
|
+
}
|
|
170
|
+
return Array.from(this.jobs.values()).map(toSnapshot);
|
|
171
|
+
}
|
|
172
|
+
async cancel(ids, signal) {
|
|
173
|
+
const results = [];
|
|
174
|
+
for (const id of ids) {
|
|
175
|
+
const record = this.jobs.get(id);
|
|
176
|
+
if (!record) {
|
|
177
|
+
results.push({ id, status: "not_found" });
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
await this.refresh(record, signal);
|
|
181
|
+
if (record.status !== "running") {
|
|
182
|
+
results.push({ id, status: record.status });
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
await this.kill(record, signal);
|
|
186
|
+
record.status = "cancelled";
|
|
187
|
+
record.durationMs = Date.now() - record.startedAt;
|
|
188
|
+
results.push({ id, status: "cancelled" });
|
|
189
|
+
}
|
|
190
|
+
return results;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Wait until at least one watched job finishes or the wait window elapses, then return a
|
|
194
|
+
* snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
|
|
195
|
+
* running jobs.
|
|
196
|
+
*/
|
|
197
|
+
async poll(ids, signal) {
|
|
198
|
+
const deadline = Date.now() + POLL_WAIT_MS;
|
|
199
|
+
const watchIds = () => ids && ids.length > 0
|
|
200
|
+
? ids.filter((id) => this.jobs.has(id))
|
|
201
|
+
: Array.from(this.jobs.values())
|
|
202
|
+
.filter((job) => job.status === "running")
|
|
203
|
+
.map((job) => job.id);
|
|
204
|
+
while (true) {
|
|
205
|
+
for (const id of watchIds()) {
|
|
206
|
+
const record = this.jobs.get(id);
|
|
207
|
+
if (record) {
|
|
208
|
+
await this.refresh(record, signal);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const watched = watchIds()
|
|
212
|
+
.map((id) => this.jobs.get(id))
|
|
213
|
+
.filter((record) => record !== undefined);
|
|
214
|
+
const anyDone = watched.some((record) => record.status !== "running");
|
|
215
|
+
if (watched.length === 0 || anyDone || Date.now() >= deadline || signal?.aborted) {
|
|
216
|
+
return watched.map(toSnapshot);
|
|
217
|
+
}
|
|
218
|
+
await sleep(POLL_CHECK_INTERVAL_MS, signal);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Read the (possibly truncated) captured output of a finished or running job. */
|
|
222
|
+
async readOutput(id, signal) {
|
|
223
|
+
const record = this.jobs.get(id);
|
|
224
|
+
if (!record) {
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
const result = await this.executor.exec(`cat ${shellEscape(record.spillFile)} 2>/dev/null || true`, { signal });
|
|
228
|
+
return { spillFile: record.spillFile, text: result.stdout };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// One manager per channel, shared across tool rebuilds so job records survive a resource reload —
|
|
232
|
+
// mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
|
|
233
|
+
const managers = new Map();
|
|
234
|
+
export function getChannelJobManager(channelId, executor) {
|
|
235
|
+
let manager = managers.get(channelId);
|
|
236
|
+
if (!manager) {
|
|
237
|
+
manager = new ChannelJobManager(channelId, executor);
|
|
238
|
+
managers.set(channelId, manager);
|
|
239
|
+
}
|
|
240
|
+
return manager;
|
|
241
|
+
}
|
|
@@ -81,7 +81,16 @@ You can schedule events that wake you up at specific times or when external thin
|
|
|
81
81
|
### Cron Format
|
|
82
82
|
\`minute hour day-of-month month day-of-week\`
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
${hasTool("event_manage")
|
|
85
|
+
? `### Creating Events
|
|
86
|
+
Prefer the event_manage tool to create, update, or delete your own scheduled events: it validates the payload on write (an invalid event would otherwise be silently dropped) and enforces the scheduling guards below. Editing the JSON files directly with the file tools still works but skips that validation.
|
|
87
|
+
|
|
88
|
+
### Silent Completion
|
|
89
|
+
For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
|
|
90
|
+
|
|
91
|
+
### Limits
|
|
92
|
+
event_manage rejects self-triggering loops: no immediate events (do that work in the current turn), one-shot at least 2 minutes out, periodic no more often than every 30 minutes (5 minutes when it carries a preAction gate), and at most 50 event files. Name task-owned events \`task.<channelId>.<taskId>.<use>\` so they clean up together.`
|
|
93
|
+
: `### Creating Events
|
|
85
94
|
Create a JSON file under \`${workspacePath}/events/\` with the appropriate event payload.
|
|
86
95
|
Prefer the file tools for creating or editing the event file. Use shell commands only when they are the clearest option.
|
|
87
96
|
|
|
@@ -89,14 +98,14 @@ Prefer the file tools for creating or editing the event file. Use shell commands
|
|
|
89
98
|
For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
|
|
90
99
|
|
|
91
100
|
### Limits
|
|
92
|
-
|
|
101
|
+
The scheduler ignores invalid files and de-duplicates by filename; keep the events directory tidy.`}`);
|
|
93
102
|
const runtimeBehaviorLines = [
|
|
94
103
|
"- The runtime may inject a small amount of relevant memory context from SESSION.md / MEMORY.md / HISTORY.md into a turn when it is clearly useful.",
|
|
95
104
|
"- SESSION.md is the primary runtime-managed working-state artifact for current active work.",
|
|
96
105
|
"- The runtime automatically consolidates channel MEMORY.md and HISTORY.md before compaction or session trimming, and sweeps durable facts into MEMORY.md in the background.",
|
|
97
106
|
];
|
|
98
|
-
if (hasTool("
|
|
99
|
-
runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call
|
|
107
|
+
if (hasTool("memory_manage")) {
|
|
108
|
+
runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call memory_manage (op: save) right away instead of waiting for background consolidation. Use it only for durable facts/preferences/decisions/constraints, not transient task state.", "- When the user asks you to forget or drop something durable, use memory_manage (op: forget) rather than editing MEMORY.md directly, so the change serializes with background consolidation. To look something up mid-task, use memory_manage (op: search).", "- Do not use edit or write to change channel MEMORY.md or HISTORY.md directly; those files are runtime-managed and must go through memory_manage, which serializes with background consolidation.");
|
|
100
109
|
}
|
|
101
110
|
runtimeBehaviorLines.push("- Workspace MEMORY.md is not updated by normal runtime consolidation.", "- ENVIRONMENT.md is not normal conversational memory. Read it only when environment history or machine state matters.");
|
|
102
111
|
const coldStorageLines = [
|
|
@@ -216,6 +216,11 @@ export async function handleSessionEvent(event, context) {
|
|
|
216
216
|
.join("\n");
|
|
217
217
|
const trimmedFinalText = finalText.trim();
|
|
218
218
|
if (!trimmedFinalText) {
|
|
219
|
+
// No tool calls and no text: leaving finalOutcome at its "none" default means no
|
|
220
|
+
// delivery branch in channel-runner fires, so the progress card is stuck on
|
|
221
|
+
// "thinking…" forever. Treat it the same as an explicit [SILENT] turn.
|
|
222
|
+
runState.finalOutcome = { kind: "silent" };
|
|
223
|
+
memoryLifecycle.noteCompletedAssistantTurn();
|
|
219
224
|
return;
|
|
220
225
|
}
|
|
221
226
|
if (trimmedFinalText === "[SILENT]" || trimmedFinalText.startsWith("[SILENT]")) {
|
package/dist/memory/recall.js
CHANGED
|
@@ -488,6 +488,7 @@ function renderRecallResult(items, maxChars) {
|
|
|
488
488
|
"Relevant context for this turn:",
|
|
489
489
|
];
|
|
490
490
|
let usedChars = clippedLines.join("\n").length + "</runtime_context>".length + 2;
|
|
491
|
+
let includedCount = 0;
|
|
491
492
|
for (const item of items) {
|
|
492
493
|
const block = ["", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content].join("\n");
|
|
493
494
|
if (usedChars + block.length > maxChars) {
|
|
@@ -495,6 +496,11 @@ function renderRecallResult(items, maxChars) {
|
|
|
495
496
|
}
|
|
496
497
|
clippedLines.push("", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content);
|
|
497
498
|
usedChars += block.length;
|
|
499
|
+
includedCount++;
|
|
500
|
+
}
|
|
501
|
+
const omittedCount = items.length - includedCount;
|
|
502
|
+
if (omittedCount > 0) {
|
|
503
|
+
clippedLines.push("", `[- ${omittedCount} more item(s) omitted for length; use memory_manage search or session_search to look them up.]`);
|
|
498
504
|
}
|
|
499
505
|
clippedLines.push("</runtime_context>");
|
|
500
506
|
return clippedLines.join("\n");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job";
|
|
1
|
+
export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job" | "user-forget";
|
|
2
2
|
export interface MemoryReviewLogEntry {
|
|
3
3
|
timestamp: string;
|
|
4
4
|
channelId: string;
|
|
@@ -2,6 +2,10 @@ import type { Api, Model } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
/**
|
|
4
4
|
* Resolve an API key for the given model's provider.
|
|
5
|
-
*
|
|
5
|
+
* `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
|
|
6
|
+
* variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
|
|
7
|
+
* credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
|
|
8
|
+
* the model itself is Anthropic — falling back for other providers would silently send an
|
|
9
|
+
* Anthropic key to e.g. OpenAI and fail with a confusing 401.
|
|
6
10
|
*/
|
|
7
11
|
export declare function getApiKeyForModel(modelRegistry: ModelRegistry, model: Model<Api>): Promise<string>;
|
package/dist/models/api-keys.js
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resolve an API key for the given model's provider.
|
|
3
|
-
*
|
|
3
|
+
* `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
|
|
4
|
+
* variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
|
|
5
|
+
* credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
|
|
6
|
+
* the model itself is Anthropic — falling back for other providers would silently send an
|
|
7
|
+
* Anthropic key to e.g. OpenAI and fail with a confusing 401.
|
|
4
8
|
*/
|
|
5
9
|
export async function getApiKeyForModel(modelRegistry, model) {
|
|
6
10
|
const key = await modelRegistry.getApiKeyForProvider(model.provider);
|
|
7
11
|
if (key) {
|
|
8
12
|
return key;
|
|
9
13
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
if (model.provider === "anthropic") {
|
|
15
|
+
const envKey = process.env.ANTHROPIC_API_KEY;
|
|
16
|
+
if (envKey) {
|
|
17
|
+
return envKey;
|
|
18
|
+
}
|
|
13
19
|
}
|
|
14
20
|
throw new Error(`No API key found for provider: ${model.provider}.\n\n` +
|
|
15
21
|
"Configure credentials in ~/.pi/pipiclaw/auth.json or ~/.pi/pipiclaw/models.json, or set the matching provider environment variable.");
|
|
@@ -471,6 +471,8 @@ export function createRuntimeContext(options) {
|
|
|
471
471
|
const response = await runTasksCommand({
|
|
472
472
|
args,
|
|
473
473
|
channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
|
|
474
|
+
workspaceDir: options.paths.workspaceDir,
|
|
475
|
+
channelId: event.channelId,
|
|
474
476
|
});
|
|
475
477
|
await bot.sendPlain(event.channelId, response);
|
|
476
478
|
},
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -110,6 +110,12 @@ const DINGTALK_API = "https://api.dingtalk.com";
|
|
|
110
110
|
// (discardCard / replay / sendPlain) already handle.
|
|
111
111
|
const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
|
|
112
112
|
const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
|
|
113
|
+
// Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
|
|
114
|
+
// existing cap on enqueueEvent. Without a limit, a busy channel getting flooded with
|
|
115
|
+
// messages (or repeated followUp requeues) grows this queue without bound — each item
|
|
116
|
+
// still runs a full serialized turn, so an unbounded queue means unbounded backlog time
|
|
117
|
+
// and unbounded memory, not just a slow channel.
|
|
118
|
+
const USER_MESSAGE_QUEUE_LIMIT = 20;
|
|
113
119
|
const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
|
|
114
120
|
const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
|
|
115
121
|
const SOCKET_CLOSE_GRACE_MS = 1_000;
|
|
@@ -560,7 +566,13 @@ export class DingTalkBot {
|
|
|
560
566
|
}
|
|
561
567
|
enqueueStreamMessage(event, textOverride) {
|
|
562
568
|
const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
|
|
563
|
-
this.getQueue(event.channelId)
|
|
569
|
+
const queue = this.getQueue(event.channelId);
|
|
570
|
+
if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
|
|
571
|
+
log.logWarning(`Message queue full for ${event.channelId} (limit ${USER_MESSAGE_QUEUE_LIMIT}), discarding: ${queuedEvent.text.substring(0, 50)}`);
|
|
572
|
+
this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
queue.enqueue(async () => {
|
|
564
576
|
this.activeMessageProcessing = true;
|
|
565
577
|
try {
|
|
566
578
|
await this.handler.handleEvent(queuedEvent, this);
|
|
@@ -2,5 +2,8 @@ export interface HandleTasksCommandOptions {
|
|
|
2
2
|
args: string;
|
|
3
3
|
/** The channel directory; tasks live in `<channelDir>/tasks/`. */
|
|
4
4
|
channelDir: string;
|
|
5
|
+
/** Workspace directory; required for `/tasks doctor` because events are workspace-scoped. */
|
|
6
|
+
workspaceDir?: string;
|
|
7
|
+
channelId?: string;
|
|
5
8
|
}
|
|
6
9
|
export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;
|