@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.2
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.en.md +300 -142
- package/README.md +295 -140
- package/dist/agent/builtin-commands.d.ts +1 -1
- package/dist/agent/builtin-commands.js +1 -1
- package/dist/agent/channel-runner.d.ts +4 -3
- package/dist/agent/channel-runner.js +17 -28
- package/dist/agent/maintenance-context.js +2 -2
- package/dist/agent/prompt/builder.d.ts +1 -1
- package/dist/agent/prompt/builder.js +1 -1
- package/dist/agent/prompt/extension.d.ts +1 -1
- package/dist/agent/prompt/extension.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +12 -5
- package/dist/agent/prompt/resources.d.ts +0 -3
- package/dist/agent/prompt/resources.js +0 -6
- package/dist/agent/prompt/sections.d.ts +2 -2
- package/dist/agent/prompt/sections.js +36 -26
- package/dist/agent/prompt/types.d.ts +3 -2
- package/dist/agent/runner-factory.js +1 -1
- package/dist/agent/session/command-extension.js +3 -1
- package/dist/agent/session/compaction-summary.js +3 -6
- package/dist/agent/session/compaction.d.ts +2 -0
- package/dist/agent/session/compaction.js +22 -14
- package/dist/agent/session/event-guards.d.ts +2 -1
- package/dist/agent/session/event-guards.js +6 -0
- package/dist/agent/session/model-selection.d.ts +2 -1
- package/dist/agent/session/model-selection.js +5 -5
- package/dist/agent/session/session-events.js +31 -4
- package/dist/agent/session/session-host.d.ts +5 -3
- package/dist/agent/session/session-host.js +20 -16
- package/dist/agent/status-render.js +3 -0
- package/dist/agent/stop-watchdog.js +5 -1
- package/dist/agent/turn/task-digest.d.ts +2 -5
- package/dist/agent/turn/task-digest.js +25 -45
- package/dist/agent/turn/turn-context.js +4 -6
- package/dist/agent/turn/turn-error.d.ts +1 -1
- package/dist/agent/turn/turn-error.js +9 -0
- package/dist/agent/turn/turn-pipeline.d.ts +10 -5
- package/dist/agent/turn/turn-pipeline.js +36 -7
- package/dist/agent/turn/turn-prompt.d.ts +2 -0
- package/dist/agent/turn/turn-prompt.js +2 -1
- package/dist/agent/turn/turn-recovery.js +4 -1
- package/dist/agent/turn/turn-state.d.ts +2 -0
- package/dist/agent/turn/turn-state.js +2 -1
- package/dist/agent/types.d.ts +23 -3
- package/dist/agent/types.js +2 -0
- package/dist/app/auth-command.d.ts +25 -0
- package/dist/app/auth-command.js +200 -67
- package/dist/app/home.d.ts +7 -8
- package/dist/app/home.js +143 -56
- package/dist/channel/attachments.d.ts +4 -0
- package/dist/channel/attachments.js +4 -0
- package/dist/channel/channel-context.d.ts +6 -0
- package/dist/channel/config.d.ts +3 -0
- package/dist/channel/config.js +11 -5
- package/dist/channel/store.d.ts +1 -1
- package/dist/commands/catalog.js +42 -10
- package/dist/commands/router.js +5 -1
- package/dist/desk/commands.d.ts +44 -5
- package/dist/desk/commands.js +162 -28
- package/dist/desk/paths.d.ts +6 -0
- package/dist/desk/paths.js +21 -1
- package/dist/desk/registry.d.ts +17 -2
- package/dist/desk/registry.js +122 -12
- package/dist/desk/types.d.ts +83 -1
- package/dist/dingtalk/bot.d.ts +1 -1
- package/dist/dingtalk/bot.js +4 -3
- package/dist/dingtalk/config.js +10 -10
- package/dist/dingtalk/delivery.js +15 -8
- package/dist/dingtalk/inbound-media.d.ts +36 -14
- package/dist/dingtalk/inbound-media.js +71 -12
- package/dist/dingtalk/inbound.d.ts +9 -2
- package/dist/dingtalk/inbound.js +17 -2
- package/dist/dingtalk/media.d.ts +4 -10
- package/dist/dingtalk/media.js +58 -32
- package/dist/events/commands.d.ts +2 -0
- package/dist/events/commands.js +13 -8
- package/dist/events/history.d.ts +9 -0
- package/dist/events/history.js +66 -0
- package/dist/events/parse.js +7 -3
- package/dist/events/types.d.ts +3 -0
- package/dist/events/watcher.d.ts +4 -8
- package/dist/events/watcher.js +53 -58
- package/dist/jobs/kill.d.ts +23 -0
- package/dist/jobs/kill.js +65 -0
- package/dist/jobs/manager.d.ts +19 -18
- package/dist/jobs/manager.js +36 -103
- package/dist/main.js +15 -3
- package/dist/memory/boundary-work.d.ts +2 -1
- package/dist/memory/boundary-work.js +1 -1
- package/dist/memory/lifecycle.d.ts +2 -1
- package/dist/memory/lifecycle.js +2 -2
- package/dist/memory/reflect-job.d.ts +2 -1
- package/dist/memory/reflect-job.js +1 -1
- package/dist/memory/reflect.d.ts +2 -1
- package/dist/memory/reflect.js +25 -4
- package/dist/memory/scheduler.d.ts +2 -1
- package/dist/memory/scheduler.js +1 -1
- package/dist/memory/session-corpus.d.ts +1 -1
- package/dist/memory/session-corpus.js +76 -1
- package/dist/memory/session-search.d.ts +2 -1
- package/dist/memory/session-search.js +14 -12
- package/dist/memory/sidecar-worker.d.ts +2 -1
- package/dist/memory/sidecar-worker.js +2 -4
- package/dist/memory/store.d.ts +2 -0
- package/dist/memory/store.js +19 -9
- package/dist/models/credential-work.d.ts +7 -0
- package/dist/models/credential-work.js +36 -0
- package/dist/models/login-ui.js +4 -4
- package/dist/models/provider-login.js +7 -6
- package/dist/models/requests.d.ts +8 -0
- package/dist/models/requests.js +69 -0
- package/dist/models/runtime.d.ts +3 -1
- package/dist/models/runtime.js +9 -2
- package/dist/playbooks/agent-delegation.md +20 -45
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/delegation-inline.md +25 -0
- package/dist/playbooks/delegation-recovery.md +28 -0
- package/dist/playbooks/event-scheduling.md +18 -37
- package/dist/playbooks/event-sensors.md +26 -0
- package/dist/playbooks/event-task-template.md +22 -0
- package/dist/playbooks/learning-and-skills.md +26 -0
- package/dist/playbooks/memory-operations.md +36 -0
- package/dist/playbooks/outbound-media.md +2 -2
- package/dist/playbooks/runtime-files.md +29 -0
- package/dist/playbooks/runtime-operations.md +25 -0
- package/dist/playbooks/runtime-orientation.md +18 -53
- package/dist/playbooks/task-lead.md +22 -68
- package/dist/playbooks/task-manage.md +38 -0
- package/dist/playbooks/task-recovery.md +24 -0
- package/dist/playbooks/task-verify.md +22 -0
- package/dist/runtime/bootstrap.d.ts +10 -0
- package/dist/runtime/bootstrap.js +93 -29
- package/dist/runtime/daemon-lock.js +3 -3
- package/dist/runtime/desk-runtime.d.ts +40 -7
- package/dist/runtime/desk-runtime.js +330 -44
- package/dist/runtime/durable-dispatch.d.ts +14 -2
- package/dist/runtime/durable-dispatch.js +207 -65
- package/dist/runtime/ingress-busy.js +17 -8
- package/dist/runtime/ingress-commands.js +24 -4
- package/dist/runtime/ingress-deps.d.ts +4 -1
- package/dist/runtime/ingress.js +6 -1
- package/dist/runtime/request-execution.js +7 -6
- package/dist/runtime/shutdown.d.ts +4 -1
- package/dist/runtime/shutdown.js +88 -35
- package/dist/runtime/task-close.d.ts +1 -1
- package/dist/runtime/task-close.js +6 -3
- package/dist/runtime/task-control.d.ts +2 -3
- package/dist/runtime/task-control.js +38 -11
- package/dist/runtime/task-input.js +1 -1
- package/dist/runtime/task-lane-types.d.ts +12 -2
- package/dist/runtime/task-lane-types.js +9 -0
- package/dist/runtime/task-lane.d.ts +2 -0
- package/dist/runtime/task-lane.js +38 -20
- package/dist/runtime/task-step.d.ts +3 -3
- package/dist/runtime/task-step.js +34 -16
- package/dist/runtime/transports.js +6 -5
- package/dist/runtime/turn-run.js +103 -66
- package/dist/security/command-guard.d.ts +1 -1
- package/dist/security/command-guard.js +259 -314
- package/dist/security/path-guard.js +48 -7
- package/dist/security/shell-parse.d.ts +10 -0
- package/dist/security/shell-parse.js +224 -0
- package/dist/security/types.d.ts +2 -0
- package/dist/subagents/commands.d.ts +1 -1
- package/dist/subagents/commands.js +14 -5
- package/dist/subagents/completion-wake.js +6 -0
- package/dist/subagents/detached-discovery.d.ts +1 -1
- package/dist/subagents/discovery.d.ts +18 -199
- package/dist/subagents/discovery.js +35 -289
- package/dist/subagents/dispatch.d.ts +1 -2
- package/dist/subagents/dispatch.js +50 -29
- package/dist/subagents/external/antigravity-cli.d.ts +2 -0
- package/dist/subagents/external/antigravity-cli.js +517 -0
- package/dist/subagents/external/claude-code.js +8 -17
- package/dist/subagents/external/codex-cli.js +8 -18
- package/dist/subagents/external/cursor-cli.js +34 -31
- package/dist/subagents/external/dispatch.d.ts +21 -7
- package/dist/subagents/external/dispatch.js +146 -12
- package/dist/subagents/external/exec.js +3 -0
- package/dist/subagents/external/harness.d.ts +57 -33
- package/dist/subagents/external/harness.js +69 -40
- package/dist/subagents/external/reconciliation.js +1 -0
- package/dist/subagents/external/registry.js +4 -1
- package/dist/subagents/external/role-warnings.d.ts +4 -13
- package/dist/subagents/external/role-warnings.js +4 -28
- package/dist/subagents/external/run.d.ts +1 -2
- package/dist/subagents/external/run.js +16 -26
- package/dist/subagents/external/settlement.d.ts +2 -0
- package/dist/subagents/external/settlement.js +13 -3
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/internal/outcome.d.ts +1 -2
- package/dist/subagents/internal/outcome.js +19 -12
- package/dist/subagents/internal/provider-retry.d.ts +1 -2
- package/dist/subagents/internal/provider-retry.js +2 -4
- package/dist/subagents/internal/run.d.ts +2 -3
- package/dist/subagents/internal/run.js +27 -4
- package/dist/subagents/internal/state.d.ts +2 -5
- package/dist/subagents/internal/state.js +1 -2
- package/dist/subagents/internal/worker.d.ts +1 -2
- package/dist/subagents/internal/worker.js +20 -10
- package/dist/subagents/resolve.d.ts +56 -0
- package/dist/subagents/resolve.js +202 -0
- package/dist/subagents/result.d.ts +6 -4
- package/dist/subagents/result.js +39 -6
- package/dist/subagents/run-record.d.ts +54 -2
- package/dist/subagents/run-record.js +7 -0
- package/dist/subagents/runs.d.ts +6 -31
- package/dist/subagents/runs.js +26 -31
- package/dist/subagents/task-envelope.d.ts +1 -2
- package/dist/subagents/task-envelope.js +13 -4
- package/dist/subagents/task-settlement.js +1 -0
- package/dist/subagents/types.d.ts +105 -6
- package/dist/subagents/types.js +16 -1
- package/dist/subagents/workspace-lease.d.ts +41 -24
- package/dist/subagents/workspace-lease.js +159 -24
- package/dist/subagents/worktree.d.ts +52 -0
- package/dist/subagents/worktree.js +363 -0
- package/dist/tasks/archive.js +4 -0
- package/dist/tasks/brief.d.ts +5 -1
- package/dist/tasks/brief.js +19 -5
- package/dist/tasks/commands.d.ts +6 -1
- package/dist/tasks/commands.js +32 -7
- package/dist/tasks/control.d.ts +11 -0
- package/dist/tasks/delivery.d.ts +2 -0
- package/dist/tasks/delivery.js +141 -21
- package/dist/tasks/loop-log.d.ts +12 -0
- package/dist/tasks/loop-log.js +10 -1
- package/dist/tasks/receipts.d.ts +7 -3
- package/dist/tasks/receipts.js +34 -5
- package/dist/tools/bash.d.ts +3 -0
- package/dist/tools/bash.js +29 -15
- package/dist/tools/contract/presentation.js +7 -5
- package/dist/tools/edit-diff.d.ts +11 -0
- package/dist/tools/edit-diff.js +148 -0
- package/dist/tools/edit-match.d.ts +18 -0
- package/dist/tools/edit-match.js +242 -0
- package/dist/tools/edit.d.ts +10 -2
- package/dist/tools/edit.js +91 -361
- package/dist/tools/event-manage.d.ts +2 -1
- package/dist/tools/event-manage.js +46 -39
- package/dist/tools/file-observations.d.ts +9 -0
- package/dist/tools/file-observations.js +50 -0
- package/dist/tools/glob-match.d.ts +3 -1
- package/dist/tools/glob-match.js +40 -17
- package/dist/tools/glob.d.ts +1 -0
- package/dist/tools/glob.js +39 -19
- package/dist/tools/grep-command.d.ts +13 -0
- package/dist/tools/grep-command.js +77 -0
- package/dist/tools/grep.js +96 -201
- package/dist/tools/index.d.ts +6 -2
- package/dist/tools/index.js +9 -4
- package/dist/tools/job.js +12 -11
- package/dist/tools/read.d.ts +2 -0
- package/dist/tools/read.js +10 -2
- package/dist/tools/registry.d.ts +16 -11
- package/dist/tools/registry.js +32 -12
- package/dist/tools/send-media.js +9 -5
- package/dist/tools/session-search.d.ts +2 -1
- package/dist/tools/session-search.js +15 -5
- package/dist/tools/skill.js +13 -12
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +25 -152
- package/dist/tools/subagent.d.ts +24 -2
- package/dist/tools/subagent.js +24 -18
- package/dist/tools/task-manage/control-tools.js +1 -1
- package/dist/tools/task-manage/factory.d.ts +2 -2
- package/dist/tools/task-manage/factory.js +40 -4
- package/dist/tools/task-manage/lifecycle.d.ts +3 -3
- package/dist/tools/task-manage/lifecycle.js +56 -13
- package/dist/tools/task-manage/schema.d.ts +4 -1
- package/dist/tools/task-manage/schema.js +4 -1
- package/dist/tools/task-manage/shared.d.ts +1 -1
- package/dist/tools/task-manage/types.d.ts +5 -1
- package/dist/tools/write-content.d.ts +7 -1
- package/dist/tools/write-content.js +18 -6
- package/dist/tools/write.d.ts +3 -0
- package/dist/tools/write.js +6 -2
- package/dist/tui/cli.d.ts +6 -6
- package/dist/tui/cli.js +120 -28
- package/dist/tui/client.d.ts +7 -0
- package/dist/tui/client.js +67 -16
- package/dist/tui/frontend.d.ts +2 -0
- package/dist/tui/pitui-frontend.d.ts +4 -0
- package/dist/tui/pitui-frontend.js +27 -0
- package/dist/tui/render.d.ts +1 -0
- package/dist/tui/render.js +5 -0
- package/dist/tui/session.js +6 -0
- package/dist/usage/ledger.d.ts +1 -1
- package/dist/usage/render.js +1 -1
- package/dist/web/client.d.ts +1 -0
- package/dist/web/client.js +11 -0
- package/dist/web/fetch.js +6 -3
- package/dist/webapi/auth.d.ts +0 -3
- package/dist/webapi/auth.js +3 -7
- package/dist/webapi/config.js +17 -14
- package/dist/webapi/key-command.js +41 -41
- package/dist/webapi/response-state.d.ts +7 -1
- package/dist/webapi/response-state.js +166 -3
- package/dist/webapi/routes/websocket.js +24 -1
- package/dist/webapi/server.d.ts +3 -1
- package/dist/webapi/server.js +32 -1
- package/dist/webapi/service.js +8 -0
- package/dist/webapi/transport.d.ts +2 -0
- package/dist/webapi/transport.js +11 -1
- package/examples/sub-agents/README.md +43 -75
- package/examples/sub-agents/agy-main.md +21 -0
- package/examples/sub-agents/claude-high.md +21 -0
- package/examples/sub-agents/claude-main.md +21 -0
- package/examples/sub-agents/codex-flash.md +21 -0
- package/examples/sub-agents/codex-high.md +21 -0
- package/examples/sub-agents/codex-main.md +21 -0
- package/examples/sub-agents/codex-review.md +20 -0
- package/examples/sub-agents/cursor-high.md +20 -0
- package/examples/sub-agents/cursor-main.md +20 -0
- package/examples/sub-agents/glm-flash.md +21 -0
- package/examples/sub-agents/glm-high.md +21 -0
- package/examples/sub-agents/pi-scout.md +20 -0
- package/package.json +11 -12
- package/dist/agent/session/request-tools.d.ts +0 -3
- package/dist/agent/session/request-tools.js +0 -20
- package/dist/models/api-keys.d.ts +0 -11
- package/dist/models/api-keys.js +0 -22
- package/dist/playbooks/memory-and-learning.md +0 -55
- package/examples/sub-agents/agents/claude-high.md +0 -23
- package/examples/sub-agents/agents/claude-main.md +0 -23
- package/examples/sub-agents/agents/codex-flash.md +0 -23
- package/examples/sub-agents/agents/codex-high.md +0 -23
- package/examples/sub-agents/agents/codex-main.md +0 -23
- package/examples/sub-agents/agents/codex-review.md +0 -23
- package/examples/sub-agents/agents/cursor-high.md +0 -22
- package/examples/sub-agents/agents/cursor-main.md +0 -22
- package/examples/sub-agents/agents/glm-flash.md +0 -23
- package/examples/sub-agents/agents/glm-high.md +0 -23
- package/examples/sub-agents/agents/scout.md +0 -30
- package/examples/sub-agents/roles/builder-hard.md +0 -34
- package/examples/sub-agents/roles/builder.md +0 -34
- package/examples/sub-agents/roles/explorer.md +0 -39
- package/examples/sub-agents/roles/git-committer.md +0 -43
- package/examples/sub-agents/roles/planner.md +0 -33
- package/examples/sub-agents/roles/reviewer.md +0 -33
- package/examples/sub-agents/roles/verifier.md +0 -35
- package/examples/sub-agents/roles/worker.md +0 -34
package/dist/jobs/manager.js
CHANGED
|
@@ -5,7 +5,6 @@ import { join } from "node:path";
|
|
|
5
5
|
import { createFileStore } from "../file-store.js";
|
|
6
6
|
import * as log from "../log.js";
|
|
7
7
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
8
|
-
import { shellEscape } from "../shared/os.js";
|
|
9
8
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
10
9
|
import { errorMessage } from "../shared/text-utils.js";
|
|
11
10
|
import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
|
|
@@ -13,16 +12,10 @@ import { readStoredTask } from "../tasks/store.js";
|
|
|
13
12
|
import { JobCompletionObserver } from "./completion-observer.js";
|
|
14
13
|
import { CompletionSignal } from "./completion-signal.js";
|
|
15
14
|
import { buildJobCompletionWake } from "./completion-wake.js";
|
|
15
|
+
import { KILL_CONFIRMED_GONE, killJob } from "./kill.js";
|
|
16
16
|
import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
|
|
17
17
|
import { probeJobs } from "./probe.js";
|
|
18
18
|
import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
|
|
19
|
-
/** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
|
|
20
|
-
const KILL_CONFIRMED_GONE = new Set([
|
|
21
|
-
"terminated",
|
|
22
|
-
"gone",
|
|
23
|
-
"identity-mismatch",
|
|
24
|
-
"no-target",
|
|
25
|
-
]);
|
|
26
19
|
/** Cap on concurrently running jobs per desk, so a runaway model can't spawn unbounded processes. */
|
|
27
20
|
export const MAX_RUNNING_JOBS = 5;
|
|
28
21
|
/** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
|
|
@@ -161,9 +154,8 @@ export class DeskJobManager {
|
|
|
161
154
|
.filter((record) => isTerminal(record.status) && record.finishedAt)
|
|
162
155
|
.map((record) => record.finishedAt + FINISHED_JOB_RETENTION_MS)
|
|
163
156
|
.reduce((earliest, expiry) => (earliest === undefined ? expiry : Math.min(earliest, expiry)), undefined);
|
|
164
|
-
if (nextExpiry === undefined)
|
|
157
|
+
if (nextExpiry === undefined)
|
|
165
158
|
return;
|
|
166
|
-
}
|
|
167
159
|
this.garbageCollectionTimer = setTimeout(() => {
|
|
168
160
|
this.garbageCollectionTimer = undefined;
|
|
169
161
|
void this.collectGarbage().finally(() => this.scheduleGarbageCollection());
|
|
@@ -188,16 +180,16 @@ export class DeskJobManager {
|
|
|
188
180
|
throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
|
|
189
181
|
}
|
|
190
182
|
const id = randomBytes(6).toString("hex");
|
|
191
|
-
if (this.options.spillDir)
|
|
183
|
+
if (this.options.spillDir)
|
|
192
184
|
await mkdir(this.options.spillDir, { recursive: true }).catch(() => undefined);
|
|
193
|
-
}
|
|
194
185
|
const spillFile = jobSpillPath(id, this.options.spillDir);
|
|
195
186
|
const art = jobArtifacts(spillFile);
|
|
196
187
|
const launch = buildLaunchScript(command, art);
|
|
188
|
+
const cwd = options.cwd ?? this.target.deskDir;
|
|
197
189
|
this.observer.add(id, art.exitFile);
|
|
198
190
|
let result;
|
|
199
191
|
try {
|
|
200
|
-
result = await this.executor.exec(launch, { signal: options.signal });
|
|
192
|
+
result = await this.executor.exec(launch, { signal: options.signal, ...(cwd ? { cwd } : {}) });
|
|
201
193
|
}
|
|
202
194
|
catch (error) {
|
|
203
195
|
// The launch was aborted (or the executor could not run it). A detached child may
|
|
@@ -258,7 +250,7 @@ export class DeskJobManager {
|
|
|
258
250
|
// not inherit the caller's AbortSignal (it may already be aborted).
|
|
259
251
|
const reason = `its record could not be persisted (${errorMessage(error)})`;
|
|
260
252
|
const failure = await this.reconcileQueue.run(id, async () => {
|
|
261
|
-
const outcome = await this.
|
|
253
|
+
const outcome = await killJob(this.executor, record);
|
|
262
254
|
if (!KILL_CONFIRMED_GONE.has(outcome)) {
|
|
263
255
|
// The process could not be confirmed gone (kill unconfirmed, or the executor could
|
|
264
256
|
// not run it). Deleting the only trace of a live process is exactly the orphan this
|
|
@@ -326,7 +318,7 @@ export class DeskJobManager {
|
|
|
326
318
|
...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
|
|
327
319
|
...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
|
|
328
320
|
};
|
|
329
|
-
const outcome = await this.
|
|
321
|
+
const outcome = await killJob(this.executor, provisional); // deliberately no signal
|
|
330
322
|
await this.unlinkArtifacts(art);
|
|
331
323
|
const tail = KILL_CONFIRMED_GONE.has(outcome)
|
|
332
324
|
? outcome === "terminated"
|
|
@@ -381,41 +373,40 @@ export class DeskJobManager {
|
|
|
381
373
|
log.logEvent("debug", "job.completion.hinted", "Background job completion check requested", {
|
|
382
374
|
fields: { desk: this.target.desk, jobIds: running.map((r) => r.id), trigger: "sweep" },
|
|
383
375
|
});
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
376
|
+
await this.refreshBatch(running);
|
|
377
|
+
await this.collectGarbage();
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
this.sweeping = false;
|
|
381
|
+
if (this.runningCount() === 0 && this.pendingCompletion.size === 0) {
|
|
382
|
+
this.stopSweeper();
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
async refreshBatch(running, signal) {
|
|
387
|
+
if (running.length > 0) {
|
|
388
|
+
const probes = await this.probeAll(running, signal);
|
|
387
389
|
for (const record of running) {
|
|
388
|
-
// The batched probe is a read; the state transition it implies still goes through the
|
|
389
|
-
// per-job slot so it cannot race a concurrent list/poll/cancel.
|
|
390
390
|
await this.reconcileQueue
|
|
391
391
|
.run(record.id, async () => {
|
|
392
392
|
if (this.stopped || record.status !== "running")
|
|
393
393
|
return;
|
|
394
|
-
await this.applyProbe(record, probes.get(record.id) ?? "");
|
|
394
|
+
await this.applyProbe(record, probes.get(record.id) ?? "", signal);
|
|
395
395
|
})
|
|
396
|
-
.catch((error) => {
|
|
397
|
-
log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
|
|
398
|
-
reason: errorMessage(error),
|
|
399
|
-
fields: { jobId: record.id },
|
|
400
|
-
});
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
for (const id of this.pendingCompletion) {
|
|
404
|
-
const record = this.jobs.get(id);
|
|
405
|
-
if (!record || this.stopped)
|
|
406
|
-
break;
|
|
407
|
-
await this.refresh(record).catch((error) => log.logWarn("job.completion.retry_failed", "Background job completion failed", {
|
|
396
|
+
.catch((error) => log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
|
|
408
397
|
reason: errorMessage(error),
|
|
409
|
-
fields: { jobId: id },
|
|
398
|
+
fields: { jobId: record.id },
|
|
410
399
|
}));
|
|
411
400
|
}
|
|
412
|
-
await this.collectGarbage();
|
|
413
401
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
if (
|
|
417
|
-
|
|
418
|
-
|
|
402
|
+
for (const id of this.pendingCompletion) {
|
|
403
|
+
const record = this.jobs.get(id);
|
|
404
|
+
if (!record || this.stopped)
|
|
405
|
+
break;
|
|
406
|
+
await this.refresh(record, signal).catch((error) => log.logWarn("job.completion.retry_failed", "Background job completion failed", {
|
|
407
|
+
reason: errorMessage(error),
|
|
408
|
+
fields: { jobId: id },
|
|
409
|
+
}));
|
|
419
410
|
}
|
|
420
411
|
}
|
|
421
412
|
/**
|
|
@@ -496,7 +487,7 @@ export class DeskJobManager {
|
|
|
496
487
|
// Still running (ALIVE / UNKNOWN / torn-EXIT). A cancel or timeout whose kill could not be
|
|
497
488
|
// confirmed earlier retries here every sweep until the process is proven gone.
|
|
498
489
|
if (record.pendingKill) {
|
|
499
|
-
const outcome = await this.
|
|
490
|
+
const outcome = await killJob(this.executor, record, signal);
|
|
500
491
|
if (record.status === "running" && KILL_CONFIRMED_GONE.has(outcome)) {
|
|
501
492
|
const t = this.takePendingTerminal(record, "lost", undefined);
|
|
502
493
|
record.exitCode = t.exitCode;
|
|
@@ -508,7 +499,7 @@ export class DeskJobManager {
|
|
|
508
499
|
// to a terminal status once the kill is confirmed; otherwise mark it pending and keep
|
|
509
500
|
// managing it (the sweeper retries).
|
|
510
501
|
if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
|
|
511
|
-
const outcome = await this.
|
|
502
|
+
const outcome = await killJob(this.executor, record, signal);
|
|
512
503
|
if (record.status !== "running")
|
|
513
504
|
return;
|
|
514
505
|
if (KILL_CONFIRMED_GONE.has(outcome)) {
|
|
@@ -629,67 +620,9 @@ export class DeskJobManager {
|
|
|
629
620
|
record.notified = true;
|
|
630
621
|
await this.persist(record);
|
|
631
622
|
}
|
|
632
|
-
/**
|
|
633
|
-
* The shell command that terminates `record`'s process and prints one token describing what
|
|
634
|
-
* happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
|
|
635
|
-
* there is no pid we can safely signal.
|
|
636
|
-
*
|
|
637
|
-
* A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
|
|
638
|
-
* the command spawned dies with it). When a start time was captured it is checked first: a
|
|
639
|
-
* recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
|
|
640
|
-
* that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
|
|
641
|
-
* ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
|
|
642
|
-
*/
|
|
643
|
-
killCommand(record) {
|
|
644
|
-
const pid = record.pid;
|
|
645
|
-
if (!Number.isFinite(pid) || pid <= 1)
|
|
646
|
-
return undefined;
|
|
647
|
-
const groupSafe = record.pgid !== undefined && record.pgid === pid;
|
|
648
|
-
const target = groupSafe ? `"-${pid}"` : `${pid}`;
|
|
649
|
-
const gate = record.pidStartedAt
|
|
650
|
-
? `__pc_cur="$(ps -o lstart= -p ${pid} 2>/dev/null)"; ` +
|
|
651
|
-
`if [ -z "$__pc_cur" ]; then ` +
|
|
652
|
-
`if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; exit 0; else printf 'GONE\\n'; exit 0; fi; fi; ` +
|
|
653
|
-
`if [ "$__pc_cur" != ${shellEscape(record.pidStartedAt)} ]; then printf 'IDENTITY_MISMATCH\\n'; exit 0; fi; `
|
|
654
|
-
: `if ! kill -0 ${pid} 2>/dev/null; then printf 'GONE\\n'; exit 0; fi; `;
|
|
655
|
-
return (gate +
|
|
656
|
-
`kill -TERM ${target} 2>/dev/null; sleep 0.2; kill -KILL ${target} 2>/dev/null; sleep 0.05; ` +
|
|
657
|
-
`if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; else printf 'TERMINATED\\n'; fi`);
|
|
658
|
-
}
|
|
659
|
-
/**
|
|
660
|
-
* Run one kill attempt and classify it from the printed token plus the executor result — never
|
|
661
|
-
* from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
|
|
662
|
-
* interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
|
|
663
|
-
*/
|
|
664
|
-
async runKill(record, signal) {
|
|
665
|
-
const command = this.killCommand(record);
|
|
666
|
-
if (!command)
|
|
667
|
-
return "no-target";
|
|
668
|
-
let result;
|
|
669
|
-
try {
|
|
670
|
-
result = await this.executor.exec(command, signal ? { signal } : {});
|
|
671
|
-
}
|
|
672
|
-
catch {
|
|
673
|
-
return "not-submitted";
|
|
674
|
-
}
|
|
675
|
-
const token = result.stdout.trim().split("\n").pop()?.trim() ?? "";
|
|
676
|
-
switch (token) {
|
|
677
|
-
case "TERMINATED":
|
|
678
|
-
return "terminated";
|
|
679
|
-
case "GONE":
|
|
680
|
-
return "gone";
|
|
681
|
-
case "IDENTITY_MISMATCH":
|
|
682
|
-
return "identity-mismatch";
|
|
683
|
-
case "UNCONFIRMED":
|
|
684
|
-
return "unconfirmed";
|
|
685
|
-
default:
|
|
686
|
-
return "not-submitted";
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
623
|
async list(signal) {
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
}
|
|
624
|
+
const running = Array.from(this.jobs.values()).filter((r) => r.status === "running");
|
|
625
|
+
await this.refreshBatch(running, signal);
|
|
693
626
|
return Array.from(this.jobs.values()).map(toSnapshot);
|
|
694
627
|
}
|
|
695
628
|
async cancel(ids, signal) {
|
|
@@ -709,7 +642,7 @@ export class DeskJobManager {
|
|
|
709
642
|
}
|
|
710
643
|
// An explicit cancel is the model's own decision, so it needs no wake to learn about it.
|
|
711
644
|
record.contract.notify = false;
|
|
712
|
-
const outcome = await this.
|
|
645
|
+
const outcome = await killJob(this.executor, record, signal);
|
|
713
646
|
if (KILL_CONFIRMED_GONE.has(outcome)) {
|
|
714
647
|
// A timeout kill already pending (`failed`/124) outranks this cancel — the job did
|
|
715
648
|
// overrun its budget. `takePendingTerminal` applies that precedence and only falls
|
package/dist/main.js
CHANGED
|
@@ -39,6 +39,18 @@ function handleError(error) {
|
|
|
39
39
|
console.error(error instanceof StartupRefusal ? error.message : error);
|
|
40
40
|
process.exit(1);
|
|
41
41
|
}
|
|
42
|
+
const MIN_NODE_MAJOR = 22;
|
|
43
|
+
const MIN_NODE_MINOR = 19;
|
|
44
|
+
function ensureSupportedNodeVersion() {
|
|
45
|
+
const [majorRaw = "0", minorRaw = "0"] = process.versions.node.split(".");
|
|
46
|
+
const major = Number.parseInt(majorRaw, 10);
|
|
47
|
+
const minor = Number.parseInt(minorRaw, 10);
|
|
48
|
+
if (major > MIN_NODE_MAJOR || (major === MIN_NODE_MAJOR && minor >= MIN_NODE_MINOR))
|
|
49
|
+
return;
|
|
50
|
+
console.error(`错误:Pipiclaw 需要 Node.js >= ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}.0(当前版本:v${process.versions.node})。请升级 Node.js 后重试。`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
ensureSupportedNodeVersion();
|
|
42
54
|
const command = process.argv[2];
|
|
43
55
|
if (command === "tui") {
|
|
44
56
|
// The TUI resolves when the user exits (Ctrl-C / Ctrl-D / /exit) or a one-shot
|
|
@@ -58,7 +70,7 @@ else if (command === "auth") {
|
|
|
58
70
|
runAuth(process.argv).then(() => process.exit(0), handleError);
|
|
59
71
|
}
|
|
60
72
|
else if (command === undefined || command === "run" || command.startsWith("-")) {
|
|
61
|
-
// Default mode: the long-lived
|
|
73
|
+
// Default mode: the long-lived daemon. `run` names it explicitly;
|
|
62
74
|
// a bare `pipiclaw` still runs it, and leading flags (--version/--help) are
|
|
63
75
|
// handled by bootstrap's parseArgs. The daemon does not resolve, so there is
|
|
64
76
|
// no success path to exit on — only surface fatal errors.
|
|
@@ -66,9 +78,9 @@ else if (command === undefined || command === "run" || command.startsWith("-"))
|
|
|
66
78
|
bootstrap(process.argv).catch(handleError);
|
|
67
79
|
}
|
|
68
80
|
else {
|
|
69
|
-
console.error(
|
|
81
|
+
console.error(`未知子命令:${command}`);
|
|
70
82
|
for (const line of formatCliCommandsHelp("pipiclaw"))
|
|
71
83
|
console.error(line);
|
|
72
|
-
console.error("
|
|
84
|
+
console.error("运行 `pipiclaw --help` 查看完整用法。");
|
|
73
85
|
process.exit(1);
|
|
74
86
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
2
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { DeskConversation } from "../desk/types.js";
|
|
4
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
4
5
|
import { type DeskMemoryQueue } from "./desk-memory-queue.js";
|
|
5
6
|
export declare function hasBoundaryReflectWork(conversation: DeskConversation): Promise<boolean>;
|
|
6
7
|
/** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
|
|
@@ -12,7 +13,7 @@ export interface BoundaryReflectOptions {
|
|
|
12
13
|
workspaceDir: string;
|
|
13
14
|
appHomeDir: string;
|
|
14
15
|
model: Model<Api>;
|
|
15
|
-
|
|
16
|
+
modelRequests: ModelRequests;
|
|
16
17
|
queue?: DeskMemoryQueue;
|
|
17
18
|
}
|
|
18
19
|
/** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
|
|
@@ -139,7 +139,7 @@ export async function drainBoundaryReflectWork(options) {
|
|
|
139
139
|
deskDir: conversation.deskDir,
|
|
140
140
|
workspaceDir: options.workspaceDir,
|
|
141
141
|
model: options.model,
|
|
142
|
-
|
|
142
|
+
modelRequests: options.modelRequests,
|
|
143
143
|
messages: batch.messages,
|
|
144
144
|
sourceClosed: true,
|
|
145
145
|
usageContext: {
|
|
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { ExtensionFactory, SessionBeforeCompactEvent, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import type { DeskConversation } from "../desk/types.js";
|
|
5
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
5
6
|
import { type DeskMemoryQueue } from "./desk-memory-queue.js";
|
|
6
7
|
import { type MemoryActivityEvent } from "./maintenance-state.js";
|
|
7
8
|
/** Boundaries `MemoryLifecycle` reflects on directly, outside the scheduled idle job (spec 050, D7). */
|
|
@@ -16,7 +17,7 @@ export interface MemoryLifecycleOptions {
|
|
|
16
17
|
getMessages: () => AgentMessage[];
|
|
17
18
|
getSessionEntries: () => SessionEntry[];
|
|
18
19
|
getModel: () => Model<Api>;
|
|
19
|
-
|
|
20
|
+
modelRequests: ModelRequests;
|
|
20
21
|
recordMemoryActivity?: (event: MemoryActivityEvent) => Promise<void> | void;
|
|
21
22
|
memoryQueue?: DeskMemoryQueue;
|
|
22
23
|
}
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -129,7 +129,7 @@ export class MemoryLifecycle {
|
|
|
129
129
|
deskDir: this.options.conversation.deskDir,
|
|
130
130
|
workspaceDir: this.options.workspaceDir,
|
|
131
131
|
model: this.options.getModel(),
|
|
132
|
-
|
|
132
|
+
modelRequests: this.options.modelRequests,
|
|
133
133
|
messages: sourceWindow.messages,
|
|
134
134
|
sourceClosed: true,
|
|
135
135
|
usageContext: {
|
|
@@ -189,7 +189,7 @@ export class MemoryLifecycle {
|
|
|
189
189
|
workspaceDir: this.options.workspaceDir,
|
|
190
190
|
appHomeDir: this.options.appHomeDir,
|
|
191
191
|
model: this.options.getModel(),
|
|
192
|
-
|
|
192
|
+
modelRequests: this.options.modelRequests,
|
|
193
193
|
queue: this.memoryQueue,
|
|
194
194
|
});
|
|
195
195
|
}
|
|
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import type { DeskConversation } from "../desk/types.js";
|
|
5
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
5
6
|
import { type DeskMemoryQueue } from "./desk-memory-queue.js";
|
|
6
7
|
import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
|
|
7
8
|
/**
|
|
@@ -21,7 +22,7 @@ export interface ReflectJobInput {
|
|
|
21
22
|
memoryMaintenance: MemoryMaintenanceInput;
|
|
22
23
|
};
|
|
23
24
|
model: Model<Api>;
|
|
24
|
-
|
|
25
|
+
modelRequests: ModelRequests;
|
|
25
26
|
/** Transcript accessors: only called once the gate has decided the job may actually run. */
|
|
26
27
|
messages: () => AgentMessage[];
|
|
27
28
|
sessionEntries: () => SessionEntry[];
|
|
@@ -67,7 +67,7 @@ export async function runReflectJob(input) {
|
|
|
67
67
|
deskDir: deskDir,
|
|
68
68
|
workspaceDir: input.workspaceDir,
|
|
69
69
|
model: input.model,
|
|
70
|
-
|
|
70
|
+
modelRequests: input.modelRequests,
|
|
71
71
|
messages: sourceWindow.messages,
|
|
72
72
|
usageContext: { channelId, desk: conversation.desk, correlationId: sourceWindow.windowId },
|
|
73
73
|
});
|
package/dist/memory/reflect.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
3
4
|
export interface ReflectRunOptions {
|
|
4
5
|
channelId?: string;
|
|
5
6
|
deskDir: string;
|
|
6
7
|
workspaceDir: string;
|
|
7
8
|
model: Model<Api>;
|
|
8
|
-
|
|
9
|
+
modelRequests: ModelRequests;
|
|
9
10
|
/** The conversation window to reflect on (already extracted by the caller's source window). */
|
|
10
11
|
messages: AgentMessage[];
|
|
11
12
|
timeoutMs?: number;
|
package/dist/memory/reflect.js
CHANGED
|
@@ -56,6 +56,7 @@ ${MEMORY_INPUT_SAFETY_RULES}
|
|
|
56
56
|
- "feedback": corrections about how to work, and lessons learned from a mistake.
|
|
57
57
|
- "project": stable facts, decisions, and constraints about what you're working on.
|
|
58
58
|
- "reference": pointers — paths, URLs, commands, contacts, ids.
|
|
59
|
+
- An explicit standing rule from the user is a high-necessity project constraint when future work must follow it. Extract it even if it was mentioned alongside a one-off request, tool output, or unrelated chat.
|
|
59
60
|
- Never write in-progress task state, transient debugging notes, or anything with a natural end date as memory — that belongs in "journal", or the user should be told to use a task if it needs tracking. If the whole window is just progress on something, "ops" should be empty.
|
|
60
61
|
- Prefer "update" over adding a near-duplicate of an existing entry (the index is given to you in full below); prefer "delete" over leaving a fact that the conversation shows is no longer true.
|
|
61
62
|
- "touch" lists the names of existing entries this window's conversation depended on or confirmed — do this whenever relevant, it costs nothing and is how a probationary entry becomes permanent.
|
|
@@ -157,7 +158,7 @@ export async function runReflect(options) {
|
|
|
157
158
|
const response = await runRetriedSidecarTask({
|
|
158
159
|
name: "memory-reflect",
|
|
159
160
|
model: options.model,
|
|
160
|
-
|
|
161
|
+
modelRequests: options.modelRequests,
|
|
161
162
|
systemPrompt: REFLECT_SYSTEM_PROMPT,
|
|
162
163
|
prompt,
|
|
163
164
|
timeoutMs: options.timeoutMs ?? REFLECT_DEFAULT_TIMEOUT_MS,
|
|
@@ -292,13 +293,23 @@ export async function runReflect(options) {
|
|
|
292
293
|
// entire automatic deletion phase unsafe; delaying unrelated cleanup is intentional.
|
|
293
294
|
const writes = storeOps.filter((op) => op.op !== "delete");
|
|
294
295
|
const deletes = storeOps.filter((op) => op.op === "delete");
|
|
295
|
-
const updatedTargets = new Set(writes.flatMap((op) => (op.op === "update" ? [op.name] : [])));
|
|
296
296
|
const applied = await applyMemoryOps(options.deskDir, writes, { today });
|
|
297
|
+
// A reused add can be the original itself. Protect actual identities, not requested slugs.
|
|
298
|
+
// Conflicting later writes also cannot serve as evidence for the earlier replacement.
|
|
299
|
+
const live = new Map((await listMemoryEntries(options.deskDir)).map((entry) => [entry.name, entry]));
|
|
300
|
+
const retainedNames = new Set(applied.retained.map((entry) => entry.name));
|
|
301
|
+
const lostReplacement = applied.retained.some((entry) => {
|
|
302
|
+
const current = live.get(entry.name);
|
|
303
|
+
return (!current ||
|
|
304
|
+
current.description !== entry.description ||
|
|
305
|
+
current.type !== entry.type ||
|
|
306
|
+
current.body !== entry.body);
|
|
307
|
+
});
|
|
297
308
|
const unsafe = rejected.some((op) => op.op === "add" || op.op === "update") ||
|
|
298
309
|
applied.skippedSecret > 0 ||
|
|
299
310
|
applied.skippedTombstone > 0 ||
|
|
300
311
|
applied.missingTarget > 0 ||
|
|
301
|
-
|
|
312
|
+
lostReplacement;
|
|
302
313
|
if (unsafe) {
|
|
303
314
|
rejected.push(...deletes.map((op) => ({
|
|
304
315
|
op: "delete",
|
|
@@ -307,7 +318,17 @@ export async function runReflect(options) {
|
|
|
307
318
|
})));
|
|
308
319
|
}
|
|
309
320
|
else {
|
|
310
|
-
const
|
|
321
|
+
const safeDeletes = deletes.filter((op) => {
|
|
322
|
+
if (!retainedNames.has(op.name))
|
|
323
|
+
return true;
|
|
324
|
+
rejected.push({
|
|
325
|
+
op: "delete",
|
|
326
|
+
name: op.name,
|
|
327
|
+
reason: "deletion deferred: live replacement identity must be retained",
|
|
328
|
+
});
|
|
329
|
+
return false;
|
|
330
|
+
});
|
|
331
|
+
const removed = await applyMemoryOps(options.deskDir, safeDeletes, { today });
|
|
311
332
|
applied.deleted.push(...removed.deleted);
|
|
312
333
|
}
|
|
313
334
|
// Keep the accepted destructive decisions inspectable, not just a list of names.
|
|
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import type { DeskConversation } from "../desk/types.js";
|
|
5
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
5
6
|
import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
|
|
6
7
|
export interface MemoryMaintenanceRuntimeContext {
|
|
7
8
|
conversation: DeskConversation;
|
|
@@ -14,7 +15,7 @@ export interface MemoryMaintenanceRuntimeContext {
|
|
|
14
15
|
messages: () => AgentMessage[];
|
|
15
16
|
sessionEntries: () => SessionEntry[];
|
|
16
17
|
model: Model<Api>;
|
|
17
|
-
|
|
18
|
+
modelRequests: ModelRequests;
|
|
18
19
|
settings: {
|
|
19
20
|
memoryMaintenance: MemoryMaintenanceInput;
|
|
20
21
|
};
|
package/dist/memory/scheduler.js
CHANGED
|
@@ -108,7 +108,7 @@ export class MemoryMaintenanceScheduler {
|
|
|
108
108
|
now,
|
|
109
109
|
settings: context.settings,
|
|
110
110
|
model: context.model,
|
|
111
|
-
|
|
111
|
+
modelRequests: context.modelRequests,
|
|
112
112
|
messages: context.messages,
|
|
113
113
|
sessionEntries: context.sessionEntries,
|
|
114
114
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type SessionSearchSource = "context" | "session" | "log";
|
|
1
|
+
export type SessionSearchSource = "context" | "session" | "log" | "task";
|
|
2
2
|
export type SessionSearchRole = "user" | "assistant" | "tool" | "system" | "unknown";
|
|
3
3
|
export interface SessionSearchDocument {
|
|
4
4
|
id: string;
|
|
@@ -247,6 +247,77 @@ async function listSessionJsonlFiles(conversationDirs, maxFiles) {
|
|
|
247
247
|
.slice(0, Math.max(0, maxFiles))
|
|
248
248
|
.map(({ conversation, path }) => ({ conversation, path }));
|
|
249
249
|
}
|
|
250
|
+
async function readArchivedTaskDocuments(deskDir, maxFiles, maxChars) {
|
|
251
|
+
const archiveDir = join(deskDir, "tasks", "archive");
|
|
252
|
+
let names;
|
|
253
|
+
try {
|
|
254
|
+
names = (await readdir(archiveDir)).filter((name) => name.endsWith(".md"));
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (isNodeError(error) && error.code === "ENOENT")
|
|
258
|
+
return [];
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
const stated = await Promise.all(names.map(async (name) => {
|
|
262
|
+
const path = join(archiveDir, name);
|
|
263
|
+
try {
|
|
264
|
+
const stats = await stat(path);
|
|
265
|
+
return stats.isFile() ? { name, path, mtimeMs: stats.mtimeMs } : null;
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}));
|
|
271
|
+
const files = stated
|
|
272
|
+
.filter((entry) => entry !== null)
|
|
273
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
274
|
+
.slice(0, Math.min(200, Math.max(20, maxFiles * 10)));
|
|
275
|
+
const docs = [];
|
|
276
|
+
for (const file of files) {
|
|
277
|
+
const id = file.name.slice(0, -".md".length);
|
|
278
|
+
const markdown = await readOptionalTextFile(file.path);
|
|
279
|
+
if (!markdown.trim())
|
|
280
|
+
continue;
|
|
281
|
+
const logContent = await readOptionalTextFile(join(archiveDir, `${id}.jsonl`));
|
|
282
|
+
const logNotes = [];
|
|
283
|
+
let closedAt;
|
|
284
|
+
for (const line of logContent.split(/\r?\n/)) {
|
|
285
|
+
const parsed = parseJsonLine(line);
|
|
286
|
+
if (!isRecord(parsed))
|
|
287
|
+
continue;
|
|
288
|
+
if (parsed.kind === "report" && typeof parsed.text === "string" && parsed.text.trim()) {
|
|
289
|
+
logNotes.push(`[汇报] ${parsed.text.trim()}`);
|
|
290
|
+
}
|
|
291
|
+
else if (parsed.kind === "ask" && typeof parsed.question === "string" && parsed.question.trim()) {
|
|
292
|
+
logNotes.push(`[提问] ${parsed.question.trim()}`);
|
|
293
|
+
}
|
|
294
|
+
else if (parsed.kind === "message" && typeof parsed.text === "string" && parsed.text.trim()) {
|
|
295
|
+
logNotes.push(`[用户消息] ${parsed.text.trim()}`);
|
|
296
|
+
}
|
|
297
|
+
else if (parsed.kind === "close" || parsed.kind === "closed") {
|
|
298
|
+
closedAt = getStringField(parsed, "ts") ?? closedAt;
|
|
299
|
+
const outcome = getStringField(parsed, "outcome") ?? "closed";
|
|
300
|
+
const note = getStringField(parsed, "note");
|
|
301
|
+
logNotes.push(`[结项 ${outcome}]${note ? ` ${note}` : ""}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const frontmatterClosedAt = /^closedAt:\s*["']?([^"'\r\n]+)["']?\s*$/m.exec(markdown)?.[1]?.trim();
|
|
305
|
+
const timestamp = closedAt ?? frontmatterClosedAt ?? new Date(file.mtimeMs).toISOString();
|
|
306
|
+
const combined = logNotes.length > 0 ? `${markdown.trim()}\n\n${logNotes.join("\n")}` : markdown.trim();
|
|
307
|
+
const document = createDocument({
|
|
308
|
+
id: `tasks/archive/${file.name}`,
|
|
309
|
+
source: "task",
|
|
310
|
+
path: file.path,
|
|
311
|
+
timestamp,
|
|
312
|
+
role: "assistant",
|
|
313
|
+
text: `[归档任务 ${id}]\n${combined}`,
|
|
314
|
+
maxChars,
|
|
315
|
+
});
|
|
316
|
+
if (document)
|
|
317
|
+
docs.push(document);
|
|
318
|
+
}
|
|
319
|
+
return docs.reverse();
|
|
320
|
+
}
|
|
250
321
|
export async function buildSessionCorpus(options) {
|
|
251
322
|
const maxFiles = Math.max(1, Math.floor(options.maxFiles));
|
|
252
323
|
const maxChars = options.maxCharsPerDocument ?? DEFAULT_MAX_CHARS_PER_DOCUMENT;
|
|
@@ -277,7 +348,11 @@ export async function buildSessionCorpus(options) {
|
|
|
277
348
|
docs = docs.slice(-maxDocuments);
|
|
278
349
|
byConversation.set(item.conversation, docs);
|
|
279
350
|
}
|
|
280
|
-
|
|
351
|
+
const archivedTasks = await readArchivedTaskDocuments(options.deskDir, maxFiles, maxChars);
|
|
352
|
+
const groups = [...byConversation.values()];
|
|
353
|
+
if (archivedTasks.length > 0)
|
|
354
|
+
groups.push(archivedTasks);
|
|
355
|
+
return shareBudget(groups.map(deduplicate), maxDocuments);
|
|
281
356
|
}
|
|
282
357
|
function deduplicate(docs) {
|
|
283
358
|
const deduplicated = [];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ModelRequests } from "../models/requests.js";
|
|
2
3
|
import { type SessionSearchRole } from "./session-corpus.js";
|
|
3
4
|
export interface SearchDeskSessionsRequest {
|
|
4
5
|
channelId?: string;
|
|
@@ -17,7 +18,7 @@ export interface SearchDeskSessionsRequest {
|
|
|
17
18
|
summarizeWithModel: boolean;
|
|
18
19
|
timeoutMs: number;
|
|
19
20
|
model: Model<Api>;
|
|
20
|
-
|
|
21
|
+
modelRequests: ModelRequests;
|
|
21
22
|
}
|
|
22
23
|
export interface SessionSearchResult {
|
|
23
24
|
source: string;
|
|
@@ -44,6 +44,12 @@ function getDocumentTokens(document) {
|
|
|
44
44
|
}
|
|
45
45
|
function scoreDocument(document, lowerQuery, queryTokens) {
|
|
46
46
|
const lowerText = document.text.toLowerCase();
|
|
47
|
+
const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
|
|
48
|
+
// Every token emitted by `tokenizeRecallText` is a contiguous substring of `lowerText`, so a
|
|
49
|
+
// document that contains neither `lowerQuery` nor any query token cannot match after tokenizing.
|
|
50
|
+
if (!exactHit && !queryTokens.some((token) => lowerText.includes(token))) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
47
53
|
const documentTokens = getDocumentTokens(document);
|
|
48
54
|
const matches = [];
|
|
49
55
|
let matchedTokens = 0;
|
|
@@ -57,7 +63,6 @@ function scoreDocument(document, lowerQuery, queryTokens) {
|
|
|
57
63
|
// dominant `matchedTokens * 1.4` term. Normalizing by query length alone would make detailed
|
|
58
64
|
// queries score worse the more context they give, so it must stay a tiebreaker.
|
|
59
65
|
const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
|
|
60
|
-
const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
|
|
61
66
|
const score = matchedTokens * 1.4 + coverage * 2 + (exactHit ? 1 : 0) + computeRecencyBoost(document.timestamp);
|
|
62
67
|
return {
|
|
63
68
|
document,
|
|
@@ -108,7 +113,7 @@ async function summarizeHit(request, document, query, queryTokens) {
|
|
|
108
113
|
const result = await runSidecarTask({
|
|
109
114
|
name: "session-search-summary",
|
|
110
115
|
model: request.model,
|
|
111
|
-
|
|
116
|
+
modelRequests: request.modelRequests,
|
|
112
117
|
systemPrompt: SESSION_SEARCH_SUMMARY_SYSTEM_PROMPT,
|
|
113
118
|
prompt: `Query:
|
|
114
119
|
${query}
|
|
@@ -172,10 +177,10 @@ export async function searchDeskSessions(request) {
|
|
|
172
177
|
const maxChunks = clampInteger(request.maxChunks, 1, 500);
|
|
173
178
|
const query = request.query.trim();
|
|
174
179
|
const roleFilter = normalizeRoleFilter(request.roleFilter);
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
180
|
+
const corpus = (await getCachedCorpus(request.deskDir, request.maxFiles, request.maxCharsPerChunk)).filter((document) => roleFilter.size === 0 || roleFilter.has(document.role));
|
|
181
|
+
// Score the full desk corpus when searching by query: slicing to `maxChunks` by recency before
|
|
182
|
+
// scoring made every message older than the newest ~80 turns permanently unreachable.
|
|
183
|
+
const documents = query ? corpus : [...corpus].sort(sortRecentDocuments).slice(0, maxChunks);
|
|
179
184
|
// Both derived once, not per document: `tokenizeRecallText` is milliseconds on real input and
|
|
180
185
|
// this loop runs over the whole corpus.
|
|
181
186
|
const queryTokens = query ? tokenizeRecallText(query) : [];
|
|
@@ -186,13 +191,10 @@ export async function searchDeskSessions(request) {
|
|
|
186
191
|
// Require actual match evidence: recency alone used to lift a completely unrelated
|
|
187
192
|
// recent message above 0 and return it with an empty `matches` array — wasted tokens
|
|
188
193
|
// and a misleading "hit". Recency now only ranks among documents that did match.
|
|
189
|
-
.filter((entry) => entry.matches.length > 0 || entry.exactHit)
|
|
190
|
-
.sort((a, b) => b.score - a.score)
|
|
191
|
-
.slice(0, limit)
|
|
192
|
-
: documents
|
|
193
|
-
.sort(sortRecentDocuments)
|
|
194
|
+
.filter((entry) => entry !== null && (entry.matches.length > 0 || entry.exactHit))
|
|
195
|
+
.sort((a, b) => b.score - a.score || sortRecentDocuments(a.document, b.document))
|
|
194
196
|
.slice(0, limit)
|
|
195
|
-
|
|
197
|
+
: documents.slice(0, limit).map((document) => ({
|
|
196
198
|
document,
|
|
197
199
|
score: computeRecencyBoost(document.timestamp),
|
|
198
200
|
matches: [],
|