@oyasmi/pipiclaw 0.9.4-beta.2 → 0.9.5-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 +28 -22
- package/README.md +27 -21
- package/dist/agent/builtin-commands.d.ts +7 -2
- package/dist/agent/builtin-commands.js +19 -23
- package/dist/agent/channel-runner.d.ts +13 -13
- package/dist/agent/channel-runner.js +93 -76
- package/dist/agent/maintenance-context.d.ts +6 -5
- package/dist/agent/maintenance-context.js +15 -15
- package/dist/agent/prompt/manifest.js +1 -1
- package/dist/agent/prompt/resources.d.ts +1 -1
- package/dist/agent/prompt/resources.js +1 -1
- package/dist/agent/prompt/sections.js +4 -4
- package/dist/agent/runner-factory.d.ts +6 -6
- package/dist/agent/runner-factory.js +6 -7
- package/dist/agent/session/compaction-input.d.ts +6 -0
- package/dist/agent/session/compaction-input.js +75 -0
- package/dist/agent/session/compaction-snapshot.d.ts +30 -0
- package/dist/agent/session/compaction-snapshot.js +154 -0
- package/dist/agent/session/compaction-summary.d.ts +39 -0
- package/dist/agent/session/compaction-summary.js +158 -0
- package/dist/agent/session/compaction.d.ts +35 -0
- package/dist/agent/session/compaction.js +294 -0
- package/dist/agent/session/context-input.d.ts +15 -0
- package/dist/agent/session/context-input.js +82 -0
- package/dist/agent/session/context-snapshot.d.ts +11 -0
- package/dist/agent/session/context-snapshot.js +72 -0
- package/dist/agent/session/event-guards.d.ts +2 -0
- package/dist/agent/session/event-guards.js +4 -0
- package/dist/agent/session/request-tools.d.ts +3 -0
- package/dist/agent/session/request-tools.js +20 -0
- package/dist/agent/session/session-adapter.d.ts +2 -1
- package/dist/agent/session/session-adapter.js +6 -3
- package/dist/agent/session/session-events.d.ts +5 -4
- package/dist/agent/session/session-events.js +46 -59
- package/dist/agent/session/session-host.d.ts +29 -41
- package/dist/agent/session/session-host.js +86 -69
- package/dist/agent/session/settings-diagnostics.d.ts +5 -0
- package/dist/agent/session/settings-diagnostics.js +21 -0
- package/dist/agent/status-render.js +5 -2
- package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
- package/dist/{runtime → agent}/stop-watchdog.js +7 -3
- package/dist/agent/turn/progress-formatter.d.ts +1 -3
- package/dist/agent/turn/progress-formatter.js +3 -22
- package/dist/agent/turn/task-digest.d.ts +4 -2
- package/dist/agent/turn/task-digest.js +7 -4
- package/dist/agent/turn/turn-context.d.ts +11 -7
- package/dist/agent/turn/turn-context.js +26 -18
- package/dist/agent/turn/turn-finish.d.ts +17 -5
- package/dist/agent/turn/turn-finish.js +51 -77
- package/dist/agent/turn/turn-input.d.ts +2 -2
- package/dist/agent/turn/turn-input.js +4 -3
- package/dist/agent/turn/turn-output.d.ts +19 -0
- package/dist/agent/turn/turn-output.js +41 -0
- package/dist/agent/turn/turn-pipeline.d.ts +11 -8
- package/dist/agent/turn/turn-pipeline.js +54 -55
- package/dist/agent/turn/turn-prompt.d.ts +1 -1
- package/dist/agent/turn/turn-recovery.d.ts +11 -10
- package/dist/agent/turn/turn-recovery.js +14 -29
- package/dist/agent/types.d.ts +31 -12
- package/dist/agent/types.js +2 -1
- package/dist/app/auth-command.js +1 -1
- package/dist/app/home.js +31 -15
- package/dist/channel/active-session-store.d.ts +14 -12
- package/dist/channel/active-session-store.js +29 -25
- package/dist/channel/attachments.d.ts +25 -0
- package/dist/channel/attachments.js +56 -0
- package/dist/channel/channel-context.d.ts +87 -96
- package/dist/channel/channel-context.js +1 -66
- package/dist/channel/channel-event.d.ts +51 -41
- package/dist/channel/channel-event.js +6 -11
- package/dist/channel/channel-id.d.ts +22 -0
- package/dist/channel/channel-id.js +13 -0
- package/dist/channel/channel-index.d.ts +17 -34
- package/dist/channel/channel-index.js +41 -80
- package/dist/channel/config.d.ts +10 -0
- package/dist/channel/config.js +55 -0
- package/dist/channel/ingress.d.ts +101 -0
- package/dist/channel/ingress.js +5 -0
- package/dist/channel/store.d.ts +13 -15
- package/dist/channel/store.js +21 -25
- package/dist/channel/transport.d.ts +99 -0
- package/dist/channel/turn-context.d.ts +23 -0
- package/dist/channel/turn-context.js +1 -0
- package/dist/commands/catalog.d.ts +4 -7
- package/dist/commands/catalog.js +24 -31
- package/dist/commands/router.d.ts +23 -12
- package/dist/commands/router.js +22 -24
- package/dist/config/settings.d.ts +5 -4
- package/dist/desk/bindings.d.ts +6 -0
- package/dist/desk/bindings.js +105 -0
- package/dist/desk/commands.d.ts +81 -0
- package/dist/desk/commands.js +145 -0
- package/dist/desk/default.d.ts +4 -0
- package/dist/desk/default.js +11 -0
- package/dist/desk/paths.d.ts +41 -0
- package/dist/desk/paths.js +81 -0
- package/dist/desk/registry.d.ts +17 -0
- package/dist/desk/registry.js +191 -0
- package/dist/desk/startup-error.d.ts +4 -0
- package/dist/desk/startup-error.js +7 -0
- package/dist/desk/types.d.ts +72 -0
- package/dist/desk/types.js +7 -0
- package/dist/dingtalk/bot.d.ts +18 -35
- package/dist/dingtalk/bot.js +21 -204
- package/dist/dingtalk/channel-ids.d.ts +15 -0
- package/dist/dingtalk/channel-ids.js +39 -0
- package/dist/dingtalk/config.d.ts +6 -3
- package/dist/dingtalk/config.js +13 -25
- package/dist/dingtalk/connection.d.ts +1 -0
- package/dist/dingtalk/connection.js +5 -4
- package/dist/dingtalk/conversation-meta.d.ts +10 -5
- package/dist/dingtalk/conversation-meta.js +72 -50
- package/dist/dingtalk/delivery.d.ts +30 -14
- package/dist/dingtalk/delivery.js +189 -62
- package/dist/dingtalk/inbound-media.d.ts +2 -18
- package/dist/dingtalk/inbound-media.js +0 -53
- package/dist/dingtalk/inbound.d.ts +10 -11
- package/dist/dingtalk/inbound.js +12 -19
- package/dist/dingtalk/media.d.ts +9 -11
- package/dist/dingtalk/media.js +18 -31
- package/dist/dingtalk/progress.d.ts +8 -0
- package/dist/dingtalk/progress.js +20 -0
- package/dist/dingtalk/response-mode.d.ts +13 -0
- package/dist/dingtalk/response-mode.js +31 -0
- package/dist/dingtalk/transport.d.ts +47 -0
- package/dist/dingtalk/transport.js +71 -0
- package/dist/events/commands.d.ts +7 -2
- package/dist/events/commands.js +40 -22
- package/dist/events/pre-action-error.d.ts +10 -0
- package/dist/events/pre-action-error.js +10 -0
- package/dist/events/types.d.ts +20 -2
- package/dist/events/watcher.d.ts +14 -7
- package/dist/events/watcher.js +49 -26
- package/dist/index.d.ts +4 -2
- package/dist/jobs/completion-wake.d.ts +14 -0
- package/dist/jobs/completion-wake.js +36 -0
- package/dist/jobs/manager.d.ts +27 -22
- package/dist/jobs/manager.js +58 -91
- package/dist/jobs/record.d.ts +2 -0
- package/dist/jobs/record.js +2 -0
- package/dist/log.d.ts +0 -1
- package/dist/log.js +1 -1
- package/dist/main.js +10 -3
- package/dist/memory/boundary-work.d.ts +17 -0
- package/dist/memory/boundary-work.js +162 -0
- package/dist/memory/commands.d.ts +4 -3
- package/dist/memory/commands.js +16 -16
- package/dist/memory/desk-memory-queue.d.ts +18 -0
- package/dist/memory/desk-memory-queue.js +33 -0
- package/dist/memory/index-budget.d.ts +3 -3
- package/dist/memory/index-budget.js +3 -3
- package/dist/memory/journal.d.ts +6 -6
- package/dist/memory/journal.js +14 -14
- package/dist/memory/lifecycle.d.ts +14 -21
- package/dist/memory/lifecycle.js +73 -103
- package/dist/memory/maintenance-state.d.ts +14 -15
- package/dist/memory/maintenance-state.js +43 -42
- package/dist/memory/reflect-job.d.ts +5 -4
- package/dist/memory/reflect-job.js +21 -15
- package/dist/memory/reflect.d.ts +2 -1
- package/dist/memory/reflect.js +13 -12
- package/dist/memory/render.d.ts +1 -1
- package/dist/memory/render.js +2 -2
- package/dist/memory/review-log.d.ts +4 -4
- package/dist/memory/review-log.js +5 -5
- package/dist/memory/scheduler.d.ts +12 -19
- package/dist/memory/scheduler.js +28 -64
- package/dist/memory/session-corpus.d.ts +4 -1
- package/dist/memory/session-corpus.js +70 -29
- package/dist/memory/session-search.d.ts +11 -3
- package/dist/memory/session-search.js +14 -11
- package/dist/memory/sidecar-worker.d.ts +1 -0
- package/dist/memory/sidecar-worker.js +57 -76
- package/dist/memory/source-window.d.ts +0 -6
- package/dist/memory/source-window.js +0 -20
- package/dist/memory/store.d.ts +12 -12
- package/dist/memory/store.js +44 -44
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +2 -0
- package/dist/playbooks/agent-delegation.md +16 -16
- package/dist/playbooks/background-jobs.md +5 -3
- package/dist/playbooks/event-scheduling.md +7 -5
- package/dist/playbooks/memory-and-learning.md +16 -12
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +35 -23
- package/dist/playbooks/task-lead.md +13 -11
- package/dist/runtime/bootstrap.d.ts +36 -13
- package/dist/runtime/bootstrap.js +310 -138
- package/dist/runtime/channel-queue.d.ts +23 -0
- package/dist/{dingtalk → runtime}/channel-queue.js +20 -9
- package/dist/runtime/daemon-lock.d.ts +12 -0
- package/dist/runtime/daemon-lock.js +28 -0
- package/dist/runtime/desk-runtime.d.ts +131 -0
- package/dist/runtime/desk-runtime.js +402 -0
- package/dist/runtime/durable-dispatch.d.ts +11 -5
- package/dist/runtime/durable-dispatch.js +20 -8
- package/dist/runtime/inbound-images.d.ts +32 -10
- package/dist/runtime/inbound-images.js +95 -21
- package/dist/runtime/ingress-busy.d.ts +26 -0
- package/dist/runtime/ingress-busy.js +211 -0
- package/dist/runtime/ingress-commands.d.ts +7 -0
- package/dist/runtime/ingress-commands.js +162 -0
- package/dist/runtime/ingress-deps.d.ts +62 -0
- package/dist/runtime/ingress-deps.js +1 -0
- package/dist/runtime/ingress.d.ts +22 -0
- package/dist/runtime/ingress.js +376 -0
- package/dist/runtime/request-execution.d.ts +19 -0
- package/dist/runtime/request-execution.js +88 -0
- package/dist/runtime/shutdown.d.ts +13 -5
- package/dist/runtime/shutdown.js +10 -4
- package/dist/runtime/task-driver.d.ts +38 -22
- package/dist/runtime/task-driver.js +142 -116
- package/dist/runtime/task-spawn.d.ts +4 -4
- package/dist/runtime/task-spawn.js +6 -5
- package/dist/runtime/task-wake.d.ts +6 -4
- package/dist/runtime/task-wake.js +7 -7
- package/dist/runtime/transports.d.ts +32 -0
- package/dist/runtime/transports.js +101 -0
- package/dist/runtime/turn-run.d.ts +18 -9
- package/dist/runtime/turn-run.js +302 -71
- package/dist/runtime/wake-coalescing.d.ts +11 -3
- package/dist/runtime/wake-coalescing.js +10 -0
- package/dist/security/config.js +5 -10
- package/dist/security/logger.js +1 -1
- package/dist/security/path-guard.js +7 -63
- package/dist/security/types.d.ts +27 -30
- package/dist/security/types.js +0 -1
- package/dist/shared/atomic-file.d.ts +2 -0
- package/dist/shared/atomic-file.js +14 -1
- package/dist/shared/file-lock.d.ts +35 -0
- package/dist/shared/file-lock.js +195 -0
- package/dist/shared/with-timeout.d.ts +2 -0
- package/dist/shared/with-timeout.js +21 -0
- package/dist/skills/loader.d.ts +1 -1
- package/dist/skills/loader.js +2 -2
- package/dist/skills/workspace.js +2 -2
- package/dist/subagents/completion-wake.d.ts +11 -2
- package/dist/subagents/completion-wake.js +22 -9
- package/dist/subagents/discovery.js +1 -1
- package/dist/subagents/dispatch.d.ts +0 -10
- package/dist/subagents/dispatch.js +10 -28
- package/dist/subagents/external/dispatch.js +1 -1
- package/dist/subagents/external/run.d.ts +1 -1
- package/dist/subagents/external/run.js +3 -3
- package/dist/subagents/internal/run.js +1 -1
- package/dist/subagents/internal/worker.js +6 -14
- package/dist/subagents/run-archive.d.ts +11 -0
- package/dist/subagents/run-archive.js +49 -0
- package/dist/subagents/run-record.d.ts +9 -8
- package/dist/subagents/run-record.js +3 -3
- package/dist/subagents/run-registry.d.ts +5 -3
- package/dist/subagents/run-registry.js +22 -45
- package/dist/subagents/runs.d.ts +23 -13
- package/dist/subagents/runs.js +75 -82
- package/dist/subagents/task-envelope.js +9 -11
- package/dist/subagents/types.d.ts +6 -5
- package/dist/tasks/board.d.ts +1 -1
- package/dist/tasks/board.js +2 -2
- package/dist/tasks/bound-work.d.ts +2 -2
- package/dist/tasks/bound-work.js +7 -7
- package/dist/tasks/brief.d.ts +1 -1
- package/dist/tasks/brief.js +9 -9
- package/dist/tasks/commands.d.ts +11 -2
- package/dist/tasks/commands.js +66 -41
- package/dist/tasks/contract.d.ts +0 -2
- package/dist/tasks/contract.js +1 -3
- package/dist/tasks/create.d.ts +3 -1
- package/dist/tasks/create.js +10 -4
- package/dist/tasks/frontmatter.d.ts +6 -2
- package/dist/tasks/frontmatter.js +10 -10
- package/dist/tasks/loop-log.d.ts +7 -13
- package/dist/tasks/loop-log.js +14 -17
- package/dist/tasks/mutation-lock.d.ts +7 -5
- package/dist/tasks/mutation-lock.js +32 -9
- package/dist/tasks/session-path.d.ts +3 -3
- package/dist/tasks/session-path.js +5 -5
- package/dist/tasks/steer.d.ts +5 -5
- package/dist/tasks/steer.js +42 -40
- package/dist/tasks/store.d.ts +11 -11
- package/dist/tasks/store.js +32 -29
- package/dist/tools/bash.d.ts +5 -5
- package/dist/tools/bash.js +19 -18
- package/dist/tools/contract/names.d.ts +7 -0
- package/dist/tools/contract/names.js +22 -0
- package/dist/tools/edit.js +1 -1
- package/dist/tools/event-manage.d.ts +3 -1
- package/dist/tools/event-manage.js +34 -33
- package/dist/tools/glob.js +5 -5
- package/dist/tools/grep.js +2 -2
- package/dist/tools/index.d.ts +9 -8
- package/dist/tools/index.js +12 -16
- package/dist/tools/job.d.ts +4 -2
- package/dist/tools/job.js +11 -8
- package/dist/tools/memory-manage.d.ts +5 -3
- package/dist/tools/memory-manage.js +24 -24
- package/dist/tools/read.js +1 -1
- package/dist/tools/registry.d.ts +12 -8
- package/dist/tools/registry.js +13 -9
- package/dist/tools/send-media.d.ts +2 -2
- package/dist/tools/send-media.js +3 -3
- package/dist/tools/session-search.d.ts +3 -1
- package/dist/tools/session-search.js +8 -6
- package/dist/tools/subagent-manage.d.ts +2 -8
- package/dist/tools/subagent-manage.js +19 -15
- package/dist/tools/subagent.js +1 -1
- package/dist/tools/task-manage/create.js +1 -1
- package/dist/tools/task-manage/factory.js +2 -2
- package/dist/tools/task-manage/lifecycle.js +3 -1
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +3 -3
- package/dist/tools/task-manage/types.d.ts +8 -3
- package/dist/tools/web-cache.d.ts +3 -3
- package/dist/tools/web-cache.js +12 -12
- package/dist/tools/web-fetch.d.ts +2 -2
- package/dist/tools/web-fetch.js +7 -7
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/cli.d.ts +17 -5
- package/dist/tui/cli.js +90 -27
- package/dist/tui/client.d.ts +26 -0
- package/dist/tui/client.js +157 -0
- package/dist/tui/colors.d.ts +0 -1
- package/dist/tui/colors.js +0 -1
- package/dist/tui/commands.d.ts +10 -51
- package/dist/tui/commands.js +16 -39
- package/dist/tui/frontend.d.ts +2 -2
- package/dist/tui/frontend.js +2 -2
- package/dist/tui/pitui-frontend.d.ts +0 -2
- package/dist/tui/pitui-frontend.js +1 -6
- package/dist/tui/render.d.ts +62 -0
- package/dist/tui/render.js +123 -0
- package/dist/tui/session.d.ts +92 -0
- package/dist/tui/session.js +317 -0
- package/dist/usage/ledger.d.ts +5 -0
- package/dist/usage/ledger.js +2 -0
- package/dist/usage/render.d.ts +6 -1
- package/dist/usage/render.js +18 -13
- package/dist/webapi/auth.d.ts +13 -0
- package/dist/webapi/auth.js +29 -0
- package/dist/webapi/config.d.ts +29 -0
- package/dist/webapi/config.js +100 -0
- package/dist/webapi/errors.d.ts +39 -0
- package/dist/webapi/errors.js +32 -0
- package/dist/webapi/http.d.ts +25 -0
- package/dist/webapi/http.js +4 -0
- package/dist/webapi/ids.d.ts +9 -0
- package/dist/webapi/ids.js +20 -0
- package/dist/webapi/input.d.ts +17 -0
- package/dist/webapi/input.js +229 -0
- package/dist/webapi/items.d.ts +37 -0
- package/dist/webapi/items.js +48 -0
- package/dist/webapi/key-command.d.ts +2 -0
- package/dist/webapi/key-command.js +110 -0
- package/dist/webapi/limits.d.ts +47 -0
- package/dist/webapi/limits.js +48 -0
- package/dist/webapi/request-policy.d.ts +17 -0
- package/dist/webapi/request-policy.js +160 -0
- package/dist/webapi/response-record.d.ts +68 -0
- package/dist/webapi/response-record.js +58 -0
- package/dist/webapi/response-state.d.ts +90 -0
- package/dist/webapi/response-state.js +347 -0
- package/dist/webapi/routes/conversations.d.ts +8 -0
- package/dist/webapi/routes/conversations.js +80 -0
- package/dist/webapi/routes/models.d.ts +3 -0
- package/dist/webapi/routes/models.js +12 -0
- package/dist/webapi/routes/responses.d.ts +8 -0
- package/dist/webapi/routes/responses.js +118 -0
- package/dist/webapi/routes/websocket.d.ts +9 -0
- package/dist/webapi/routes/websocket.js +328 -0
- package/dist/webapi/server.d.ts +24 -0
- package/dist/webapi/server.js +229 -0
- package/dist/webapi/service.d.ts +130 -0
- package/dist/webapi/service.js +588 -0
- package/dist/webapi/store.d.ts +46 -0
- package/dist/webapi/store.js +245 -0
- package/dist/webapi/stream.d.ts +13 -0
- package/dist/webapi/stream.js +76 -0
- package/dist/webapi/transport.d.ts +43 -0
- package/dist/webapi/transport.js +100 -0
- package/package.json +9 -2
- package/dist/channel/channel-paths.d.ts +0 -16
- package/dist/channel/channel-paths.js +0 -53
- package/dist/channel/commands.d.ts +0 -32
- package/dist/channel/commands.js +0 -109
- package/dist/channel/project-scope-store.d.ts +0 -51
- package/dist/channel/project-scope-store.js +0 -112
- package/dist/dingtalk/channel-queue.d.ts +0 -19
- package/dist/dingtalk/handler.d.ts +0 -90
- package/dist/memory/channel-maintenance-queue.d.ts +0 -5
- package/dist/memory/channel-maintenance-queue.js +0 -8
- package/dist/runtime/task-migration.d.ts +0 -30
- package/dist/runtime/task-migration.js +0 -465
- package/dist/runtime/turn-handler.d.ts +0 -47
- package/dist/runtime/turn-handler.js +0 -318
- package/dist/security/project-scope.d.ts +0 -45
- package/dist/security/project-scope.js +0 -105
- package/dist/tui/app.d.ts +0 -16
- package/dist/tui/app.js +0 -166
- package/dist/tui/terminal-context.d.ts +0 -27
- package/dist/tui/terminal-context.js +0 -84
- package/dist/tui/terminal-media-sender.d.ts +0 -9
- package/dist/tui/terminal-media-sender.js +0 -15
- package/dist/tui/turn-controller.d.ts +0 -64
- package/dist/tui/turn-controller.js +0 -311
- /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
package/dist/jobs/manager.js
CHANGED
|
@@ -2,7 +2,7 @@ import { randomBytes } from "node:crypto";
|
|
|
2
2
|
import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import {
|
|
5
|
+
import { getDeskDir, getDeskLogsDir, isDeskName } from "../desk/paths.js";
|
|
6
6
|
import { createFileStore } from "../file-store.js";
|
|
7
7
|
import * as log from "../log.js";
|
|
8
8
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
@@ -11,6 +11,8 @@ import { createSerialQueue } from "../shared/serial-queue.js";
|
|
|
11
11
|
import { errorMessage } from "../shared/text-utils.js";
|
|
12
12
|
import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
|
|
13
13
|
import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
|
|
14
|
+
import { redeemTicket } from "../tasks/store.js";
|
|
15
|
+
import { buildJobCompletionWake, jobWakeDispatchId } from "./completion-wake.js";
|
|
14
16
|
import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
|
|
15
17
|
import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
|
|
16
18
|
/** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
|
|
@@ -20,7 +22,7 @@ const KILL_CONFIRMED_GONE = new Set([
|
|
|
20
22
|
"identity-mismatch",
|
|
21
23
|
"no-target",
|
|
22
24
|
]);
|
|
23
|
-
/** Cap on concurrently running jobs per
|
|
25
|
+
/** Cap on concurrently running jobs per desk, so a runaway model can't spawn unbounded processes. */
|
|
24
26
|
export const MAX_RUNNING_JOBS = 5;
|
|
25
27
|
/** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
|
|
26
28
|
export const POLL_WAIT_MS = 30_000;
|
|
@@ -55,9 +57,10 @@ function sleep(ms, signal) {
|
|
|
55
57
|
}, { once: true });
|
|
56
58
|
});
|
|
57
59
|
}
|
|
58
|
-
export class
|
|
59
|
-
|
|
60
|
-
|
|
60
|
+
export class DeskJobManager {
|
|
61
|
+
/** `target` owns these jobs (task logs live in its directory); each job's own channel gets its wake. */
|
|
62
|
+
constructor(target, executor, options = {}) {
|
|
63
|
+
this.target = target;
|
|
61
64
|
this.executor = executor;
|
|
62
65
|
this.jobs = new Map();
|
|
63
66
|
this.wakeQueue = createSerialQueue();
|
|
@@ -156,25 +159,12 @@ export class ChannelJobManager {
|
|
|
156
159
|
}, Math.max(0, nextExpiry - now));
|
|
157
160
|
this.garbageCollectionTimer.unref?.();
|
|
158
161
|
}
|
|
159
|
-
get channel() {
|
|
160
|
-
return this.channelId;
|
|
161
|
-
}
|
|
162
162
|
runningCount() {
|
|
163
163
|
return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
|
|
164
164
|
}
|
|
165
165
|
listRunning() {
|
|
166
166
|
return Array.from(this.jobs.values()).filter((job) => job.status === "running");
|
|
167
167
|
}
|
|
168
|
-
/** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
|
|
169
|
-
runningTaskIds() {
|
|
170
|
-
const ids = new Set();
|
|
171
|
-
for (const job of this.jobs.values()) {
|
|
172
|
-
if (job.status === "running" && job.contract.notify && job.contract.taskId) {
|
|
173
|
-
ids.add(job.contract.taskId);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
return ids;
|
|
177
|
-
}
|
|
178
168
|
/**
|
|
179
169
|
* Launch a command in the background and return its snapshot. The wrapper (`buildLaunchScript`)
|
|
180
170
|
* runs a readiness handshake before the command executes: only after the inner shell proves it
|
|
@@ -182,7 +172,7 @@ export class ChannelJobManager {
|
|
|
182
172
|
* 0. A failed handshake, a non-zero launch, or an interrupted launch never creates a `running`
|
|
183
173
|
* record; a persist failure right after a successful launch terminates the process (see below).
|
|
184
174
|
*/
|
|
185
|
-
async start(command, label, timeoutSeconds, options
|
|
175
|
+
async start(command, label, timeoutSeconds, options) {
|
|
186
176
|
if (this.runningCount() >= MAX_RUNNING_JOBS) {
|
|
187
177
|
throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
|
|
188
178
|
}
|
|
@@ -200,7 +190,7 @@ export class ChannelJobManager {
|
|
|
200
190
|
catch (error) {
|
|
201
191
|
// The launch was aborted (or the executor could not run it). A detached child may
|
|
202
192
|
// already be running — try to recover its pid and clean it up honestly.
|
|
203
|
-
throw await this.recoverInterruptedLaunch(
|
|
193
|
+
throw await this.recoverInterruptedLaunch(art, error);
|
|
204
194
|
}
|
|
205
195
|
const launched = parseLaunchOutput(result.stdout);
|
|
206
196
|
if (result.code !== 0 || launched.handshakeFailed) {
|
|
@@ -237,6 +227,7 @@ export class ChannelJobManager {
|
|
|
237
227
|
exitFile: art.exitFile,
|
|
238
228
|
timeoutSeconds,
|
|
239
229
|
contract: { notify: options.notify ?? true, ...(options.taskId ? { taskId: options.taskId } : {}) },
|
|
230
|
+
channelId: options.channelId,
|
|
240
231
|
};
|
|
241
232
|
this.jobs.set(id, record);
|
|
242
233
|
// The persisted record is the only thing that survives a restart — a detached process
|
|
@@ -270,8 +261,8 @@ export class ChannelJobManager {
|
|
|
270
261
|
});
|
|
271
262
|
throw failure;
|
|
272
263
|
}
|
|
273
|
-
if (options.taskId && this.
|
|
274
|
-
await logTaskDispatch(this.
|
|
264
|
+
if (options.taskId && this.target.deskDir) {
|
|
265
|
+
await logTaskDispatch(this.target.deskDir, options.taskId, {
|
|
275
266
|
ref: id,
|
|
276
267
|
agent: "job",
|
|
277
268
|
label,
|
|
@@ -291,7 +282,7 @@ export class ChannelJobManager {
|
|
|
291
282
|
* its readiness handshake, so even an interrupted launch usually leaves a recoverable pid;
|
|
292
283
|
* clean it up with no caller signal and return an error that is honest about what is known.
|
|
293
284
|
*/
|
|
294
|
-
async recoverInterruptedLaunch(
|
|
285
|
+
async recoverInterruptedLaunch(art, error) {
|
|
295
286
|
const cause = errorMessage(error);
|
|
296
287
|
const partialStdout = typeof error.stdout === "string" ? error.stdout : "";
|
|
297
288
|
let launched = parseLaunchOutput(partialStdout);
|
|
@@ -311,19 +302,9 @@ export class ChannelJobManager {
|
|
|
311
302
|
return new Error(`Background job launch was interrupted (${cause}); no pid could be recovered, so whether the command actually started cannot be confirmed. No job was created.`);
|
|
312
303
|
}
|
|
313
304
|
const provisional = {
|
|
314
|
-
id: "(interrupted-launch)",
|
|
315
|
-
label: "(interrupted launch)",
|
|
316
|
-
command,
|
|
317
|
-
status: "running",
|
|
318
|
-
startedAt: Date.now(),
|
|
319
|
-
durationMs: 0,
|
|
320
305
|
pid,
|
|
321
306
|
...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
|
|
322
307
|
...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
|
|
323
|
-
spillFile: art.spillFile,
|
|
324
|
-
exitFile: art.exitFile,
|
|
325
|
-
timeoutSeconds: 0,
|
|
326
|
-
contract: { notify: false },
|
|
327
308
|
};
|
|
328
309
|
const outcome = await this.runKill(provisional); // deliberately no signal
|
|
329
310
|
await this.unlinkArtifacts(art);
|
|
@@ -566,12 +547,12 @@ export class ChannelJobManager {
|
|
|
566
547
|
*/
|
|
567
548
|
async logSettlementToTask(record) {
|
|
568
549
|
const taskId = record.contract.taskId;
|
|
569
|
-
const
|
|
570
|
-
if (!taskId || !
|
|
550
|
+
const deskDir = this.target.deskDir;
|
|
551
|
+
if (!taskId || !deskDir || record.taskLogged)
|
|
571
552
|
return;
|
|
572
553
|
record.taskLogged = true;
|
|
573
554
|
const output = await this.readOutput(record.id).catch(() => undefined);
|
|
574
|
-
await logTaskSettlement(
|
|
555
|
+
await logTaskSettlement(deskDir, taskId, {
|
|
575
556
|
ref: record.id,
|
|
576
557
|
status: record.status,
|
|
577
558
|
exitCode: record.exitCode,
|
|
@@ -597,37 +578,14 @@ export class ChannelJobManager {
|
|
|
597
578
|
if (!this.options.dispatch || !record.contract.notify || record.notified) {
|
|
598
579
|
return;
|
|
599
580
|
}
|
|
581
|
+
const channelId = record.channelId;
|
|
582
|
+
if (this.options.isBoundTo && !this.options.isBoundTo(channelId, this.target.desk)) {
|
|
583
|
+
await this.suppressWake(record);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
600
586
|
const output = await this.readOutput(record.id, signal);
|
|
601
587
|
const tail = output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim();
|
|
602
|
-
const
|
|
603
|
-
const seconds = Math.round(record.durationMs / 1000);
|
|
604
|
-
const belongsTo = record.contract.taskId ? ` It belongs to task ${record.contract.taskId}.` : "";
|
|
605
|
-
const event = {
|
|
606
|
-
type: this.channelId.startsWith("group_") ? "group" : "dm",
|
|
607
|
-
channelId: this.channelId,
|
|
608
|
-
user: "JOB",
|
|
609
|
-
userName: "JOB",
|
|
610
|
-
text: `[JOB:${record.id}] Background job "${record.label}" finished: ${record.status} (${exit}, ${seconds}s).${belongsTo} ` +
|
|
611
|
-
`Command: ${record.command}\n` +
|
|
612
|
-
`Output tail:\n${tail || "(no output)"}\n` +
|
|
613
|
-
`Full output: ${record.spillFile}\n` +
|
|
614
|
-
"Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
|
|
615
|
-
ts: String(Date.now()),
|
|
616
|
-
conversationType: this.channelId.startsWith("group_") ? "2" : "1",
|
|
617
|
-
dispatchId: `job:${this.channelId}:${record.id}:done`,
|
|
618
|
-
// The result is awaited; the wake itself still runs without a progress card.
|
|
619
|
-
presentation: "awaited",
|
|
620
|
-
...(record.contract.taskId
|
|
621
|
-
? {
|
|
622
|
-
internalWake: {
|
|
623
|
-
kind: "job",
|
|
624
|
-
resourceId: record.id,
|
|
625
|
-
taskId: record.contract.taskId,
|
|
626
|
-
dispatchId: `job:${this.channelId}:${record.id}:done`,
|
|
627
|
-
},
|
|
628
|
-
}
|
|
629
|
-
: {}),
|
|
630
|
-
};
|
|
588
|
+
const event = buildJobCompletionWake({ desk: this.target.desk, channelId, record, tail });
|
|
631
589
|
try {
|
|
632
590
|
await this.options.dispatch(event);
|
|
633
591
|
}
|
|
@@ -641,6 +599,24 @@ export class ChannelJobManager {
|
|
|
641
599
|
record.notified = true;
|
|
642
600
|
await this.persist(record);
|
|
643
601
|
}
|
|
602
|
+
/** Same contract as `SubAgentRunManager.suppressWake`: drop the wake, still redeem the `work` ticket. */
|
|
603
|
+
async suppressWake(record) {
|
|
604
|
+
log.logInfoEvent("job.wake.suppressed", "Completion wake dropped: channel not bound to the job's desk", {
|
|
605
|
+
channelId: record.channelId,
|
|
606
|
+
fields: { jobId: record.id, desk: this.target.desk, taskId: record.contract.taskId },
|
|
607
|
+
});
|
|
608
|
+
const taskId = record.contract.taskId;
|
|
609
|
+
if (taskId && this.target.deskDir) {
|
|
610
|
+
await redeemTicket(this.target.deskDir, taskId, (ticket) => ticket.kind === "work").catch((error) => {
|
|
611
|
+
log.logWarn("job.wake.redeem_failed", "Work ticket redeem for a dropped wake failed", {
|
|
612
|
+
reason: errorMessage(error),
|
|
613
|
+
fields: { jobId: record.id, taskId },
|
|
614
|
+
});
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
record.notified = true;
|
|
618
|
+
await this.persist(record);
|
|
619
|
+
}
|
|
644
620
|
/**
|
|
645
621
|
* The shell command that terminates `record`'s process and prints one token describing what
|
|
646
622
|
* happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
|
|
@@ -707,7 +683,7 @@ export class ChannelJobManager {
|
|
|
707
683
|
async beginWakeConsumption(id, taskId, dispatchId) {
|
|
708
684
|
return this.wakeQueue.run(id, async () => {
|
|
709
685
|
const record = this.jobs.get(id);
|
|
710
|
-
const expected =
|
|
686
|
+
const expected = jobWakeDispatchId(this.target.desk, id);
|
|
711
687
|
if (!record)
|
|
712
688
|
return false;
|
|
713
689
|
const eligible = record.status !== "running" && record.contract.taskId === taskId && dispatchId === expected;
|
|
@@ -892,45 +868,37 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
892
868
|
const config = { ...options };
|
|
893
869
|
const managers = new Map();
|
|
894
870
|
let stopped = false;
|
|
895
|
-
function
|
|
896
|
-
|
|
897
|
-
if (!manager)
|
|
898
|
-
return [];
|
|
899
|
-
return manager.listRunning().map((job) => `后台作业 \`${job.id}\` 仍在运行:${job.command.slice(0, 80)}`);
|
|
900
|
-
}
|
|
901
|
-
function get(channelId) {
|
|
902
|
-
let manager = managers.get(channelId);
|
|
871
|
+
function get(desk) {
|
|
872
|
+
let manager = managers.get(desk);
|
|
903
873
|
if (!manager) {
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
...(config.
|
|
907
|
-
|
|
908
|
-
spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs"),
|
|
909
|
-
channelDir: getChannelDir(config.workspaceDir, channelId),
|
|
910
|
-
}
|
|
911
|
-
: {}),
|
|
874
|
+
const deskDir = config.workspaceDir ? getDeskDir(config.workspaceDir, desk) : undefined;
|
|
875
|
+
manager = new DeskJobManager({ desk, deskDir }, executor, {
|
|
876
|
+
...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, desk) } : {}),
|
|
877
|
+
...(deskDir ? { spillDir: getDeskLogsDir(deskDir) } : {}),
|
|
912
878
|
...(config.dispatch ? { dispatch: config.dispatch } : {}),
|
|
879
|
+
...(config.isBoundTo ? { isBoundTo: config.isBoundTo } : {}),
|
|
913
880
|
...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
|
|
914
881
|
});
|
|
915
|
-
managers.set(
|
|
882
|
+
managers.set(desk, manager);
|
|
916
883
|
if (stopped)
|
|
917
884
|
manager.stop();
|
|
918
885
|
}
|
|
919
886
|
return manager;
|
|
920
887
|
}
|
|
921
888
|
/**
|
|
922
|
-
* Re-adopt every
|
|
923
|
-
*
|
|
889
|
+
* Re-adopt every desk's persisted jobs at startup. Desks are the record directories themselves,
|
|
890
|
+
* and restore does not depend on bindings (spec 058, D6): a job still running when its desk went
|
|
891
|
+
* dormant survives the restart too.
|
|
924
892
|
*/
|
|
925
893
|
async function restore() {
|
|
926
894
|
const jobsStateDir = config.jobsStateDir;
|
|
927
895
|
if (!jobsStateDir)
|
|
928
896
|
return 0;
|
|
929
|
-
let
|
|
897
|
+
let desks;
|
|
930
898
|
try {
|
|
931
899
|
await mkdir(jobsStateDir, { recursive: true });
|
|
932
|
-
|
|
933
|
-
.filter((entry) => entry.isDirectory())
|
|
900
|
+
desks = (await readdir(jobsStateDir, { withFileTypes: true }))
|
|
901
|
+
.filter((entry) => entry.isDirectory() && isDeskName(entry.name))
|
|
934
902
|
.map((entry) => entry.name);
|
|
935
903
|
}
|
|
936
904
|
catch (error) {
|
|
@@ -938,8 +906,8 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
938
906
|
return 0;
|
|
939
907
|
}
|
|
940
908
|
let restored = 0;
|
|
941
|
-
for (const
|
|
942
|
-
restored += await get(
|
|
909
|
+
for (const desk of desks) {
|
|
910
|
+
restored += await get(desk).restore();
|
|
943
911
|
}
|
|
944
912
|
if (restored > 0) {
|
|
945
913
|
log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
|
|
@@ -948,7 +916,6 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
948
916
|
}
|
|
949
917
|
return {
|
|
950
918
|
get,
|
|
951
|
-
runningLines,
|
|
952
919
|
restore,
|
|
953
920
|
stop: () => {
|
|
954
921
|
stopped = true;
|
package/dist/jobs/record.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface JobSnapshot {
|
|
|
12
12
|
/** The task this job's completion wake belongs to, if any — lets a caller verify that a
|
|
13
13
|
* `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
|
|
14
14
|
taskId?: string;
|
|
15
|
+
/** The channel that started the job, where its completion wake goes; jobs are shared per desk. */
|
|
16
|
+
channelId: string;
|
|
15
17
|
}
|
|
16
18
|
/** What should happen when the job finishes. */
|
|
17
19
|
export interface JobWakeContract {
|
package/dist/jobs/record.js
CHANGED
|
@@ -11,6 +11,7 @@ export function parseJobRecord(raw) {
|
|
|
11
11
|
const value = JSON.parse(raw);
|
|
12
12
|
if (!isRecord(value) ||
|
|
13
13
|
typeof value.id !== "string" ||
|
|
14
|
+
typeof value.channelId !== "string" ||
|
|
14
15
|
typeof value.pid !== "number" ||
|
|
15
16
|
typeof value.spillFile !== "string" ||
|
|
16
17
|
typeof value.exitFile !== "string" ||
|
|
@@ -32,5 +33,6 @@ export function toSnapshot(record) {
|
|
|
32
33
|
exitCode: record.exitCode,
|
|
33
34
|
timeoutSeconds: record.timeoutSeconds,
|
|
34
35
|
taskId: record.contract.taskId,
|
|
36
|
+
channelId: record.channelId,
|
|
35
37
|
};
|
|
36
38
|
}
|
package/dist/log.d.ts
CHANGED
package/dist/log.js
CHANGED
|
@@ -217,7 +217,7 @@ export function logResponse(ctx, text) {
|
|
|
217
217
|
}
|
|
218
218
|
// Compatibility helpers keep lower-risk call sites centralized while they use
|
|
219
219
|
// the same output contract as structured events. The channel prefix accepts any non-blank id:
|
|
220
|
-
// a group channel is `
|
|
220
|
+
// a group channel is `dingtalk:group:<conversationId>`, and DingTalk conversation ids are base64 (`+`, `/`,
|
|
221
221
|
// `=`), which a word-character class silently failed to match — group logs lost their `channel`.
|
|
222
222
|
function legacyContext(message) {
|
|
223
223
|
const match = /^\[([^\]\s]+)\]\s*/.exec(message);
|
package/dist/main.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { runAuth } from "./app/auth-command.js";
|
|
3
3
|
import { formatCliCommandsHelp, isBootstrapExitError } from "./app/home.js";
|
|
4
|
+
import { StartupRefusal } from "./desk/startup-error.js";
|
|
4
5
|
import * as log from "./log.js";
|
|
5
|
-
import { bootstrap } from "./runtime/bootstrap.js";
|
|
6
|
+
import { bootstrap, bootstrapEmbedded } from "./runtime/bootstrap.js";
|
|
6
7
|
import { errorMessage } from "./shared/text-utils.js";
|
|
7
8
|
import { runTui } from "./tui/cli.js";
|
|
8
9
|
/**
|
|
@@ -35,7 +36,7 @@ function handleError(error) {
|
|
|
35
36
|
if (isBootstrapExitError(error)) {
|
|
36
37
|
process.exit(error.code);
|
|
37
38
|
}
|
|
38
|
-
console.error(error);
|
|
39
|
+
console.error(error instanceof StartupRefusal ? error.message : error);
|
|
39
40
|
process.exit(1);
|
|
40
41
|
}
|
|
41
42
|
const command = process.argv[2];
|
|
@@ -44,7 +45,13 @@ if (command === "tui") {
|
|
|
44
45
|
// --print finishes. Exit explicitly: raw-mode stdin and the runner session
|
|
45
46
|
// keep the event loop alive, so the process would otherwise hang after the UI
|
|
46
47
|
// tears down.
|
|
47
|
-
runTui(process.argv).then(() => process.exit(0), handleError);
|
|
48
|
+
runTui(process.argv, { startEmbeddedRuntime: bootstrapEmbedded }).then(() => process.exit(0), handleError);
|
|
49
|
+
}
|
|
50
|
+
else if (command === "webapi") {
|
|
51
|
+
// Only the key commands live here; the Web API itself is loaded by the daemon, if channel.json turns it on.
|
|
52
|
+
import("./webapi/key-command.js")
|
|
53
|
+
.then(({ runWebApiCommand }) => runWebApiCommand(process.argv))
|
|
54
|
+
.then(() => process.exit(0), handleError);
|
|
48
55
|
}
|
|
49
56
|
else if (command === "auth") {
|
|
50
57
|
// readline keeps stdin open, so exit explicitly on success too.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { DeskConversation } from "../desk/types.js";
|
|
4
|
+
import { type DeskMemoryQueue } from "./desk-memory-queue.js";
|
|
5
|
+
export declare function hasBoundaryReflectWork(conversation: DeskConversation): Promise<boolean>;
|
|
6
|
+
/** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
|
|
7
|
+
export declare function enqueueBoundaryReflectWork(conversation: DeskConversation, entries: SessionEntry[], firstKeptEntryId: string, signal: AbortSignal): Promise<void>;
|
|
8
|
+
export interface BoundaryReflectOptions {
|
|
9
|
+
conversation: DeskConversation;
|
|
10
|
+
workspaceDir: string;
|
|
11
|
+
appHomeDir: string;
|
|
12
|
+
model: Model<Api>;
|
|
13
|
+
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
14
|
+
queue?: DeskMemoryQueue;
|
|
15
|
+
}
|
|
16
|
+
/** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
|
|
17
|
+
export declare function drainBoundaryReflectWork(options: BoundaryReflectOptions): Promise<void>;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/** Durable pre-compaction reflect snapshots. Inference never holds up the compaction hook. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { access, readdir, readFile, unlink } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { getMemoryWorkDir } from "../desk/paths.js";
|
|
6
|
+
import * as log from "../log.js";
|
|
7
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
8
|
+
import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
|
|
9
|
+
import { isNodeError } from "../shared/os.js";
|
|
10
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
11
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
12
|
+
import { getDeskMemoryQueue } from "./desk-memory-queue.js";
|
|
13
|
+
import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
|
|
14
|
+
import { runReflect } from "./reflect.js";
|
|
15
|
+
import { appendMemoryReviewLog } from "./review-log.js";
|
|
16
|
+
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
17
|
+
function workDir(conversation) {
|
|
18
|
+
return join(getMemoryWorkDir(conversation.deskDir), conversation.conversation);
|
|
19
|
+
}
|
|
20
|
+
async function pendingFiles(conversation) {
|
|
21
|
+
try {
|
|
22
|
+
return (await readdir(workDir(conversation))).filter((name) => /^[a-f0-9]{32}\.json$/.test(name)).sort();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (isNodeError(error) && error.code === "ENOENT")
|
|
26
|
+
return [];
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function completed(conversation, id) {
|
|
31
|
+
try {
|
|
32
|
+
await access(join(workDir(conversation), `${id}.done`));
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (isNodeError(error) && error.code === "ENOENT")
|
|
37
|
+
return false;
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function hasBoundaryReflectWork(conversation) {
|
|
42
|
+
return (await pendingFiles(conversation)).length > 0;
|
|
43
|
+
}
|
|
44
|
+
/** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
|
|
45
|
+
export async function enqueueBoundaryReflectWork(conversation, entries, firstKeptEntryId, signal) {
|
|
46
|
+
signal.throwIfAborted();
|
|
47
|
+
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
48
|
+
if (cut < 0)
|
|
49
|
+
throw new Error("Cannot preserve compaction memory: kept entry is missing. Use /new to recover.");
|
|
50
|
+
const prefix = entries.slice(0, cut);
|
|
51
|
+
if (prefix.length === 0)
|
|
52
|
+
return;
|
|
53
|
+
const id = createHash("sha256")
|
|
54
|
+
.update(prefix.map((entry) => entry.id).join("\0"))
|
|
55
|
+
.digest("hex")
|
|
56
|
+
.slice(0, 32);
|
|
57
|
+
if (await completed(conversation, id))
|
|
58
|
+
return;
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
const work = {
|
|
61
|
+
version: 1,
|
|
62
|
+
id,
|
|
63
|
+
createdAt: Date.now(),
|
|
64
|
+
entryIds: prefix.map((entry) => entry.id),
|
|
65
|
+
messages: prefix.flatMap((entry) => entry.type === "message"
|
|
66
|
+
? sanitizeMessagesForMemory([entry.message]).map((message) => ({ entryId: entry.id, message }))
|
|
67
|
+
: []),
|
|
68
|
+
};
|
|
69
|
+
await writeFileAtomically(join(workDir(conversation), `${id}.json`), `${JSON.stringify(work)}\n`);
|
|
70
|
+
signal.throwIfAborted();
|
|
71
|
+
}
|
|
72
|
+
/** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
|
|
73
|
+
export async function drainBoundaryReflectWork(options) {
|
|
74
|
+
const { conversation, appHomeDir } = options;
|
|
75
|
+
try {
|
|
76
|
+
if (!(await hasBoundaryReflectWork(conversation)))
|
|
77
|
+
return;
|
|
78
|
+
const queue = options.queue ?? getDeskMemoryQueue();
|
|
79
|
+
await queue.run(conversation, async () => {
|
|
80
|
+
const maintenance = await readMemoryMaintenanceState(appHomeDir, conversation);
|
|
81
|
+
const retryAt = maintenance.failureBackoffUntil ? parseLocalTime(maintenance.failureBackoffUntil) : undefined;
|
|
82
|
+
if (retryAt !== undefined && retryAt > Date.now())
|
|
83
|
+
return;
|
|
84
|
+
const files = await pendingFiles(conversation);
|
|
85
|
+
const work = [];
|
|
86
|
+
for (const file of files) {
|
|
87
|
+
if (await completed(conversation, file.slice(0, -5))) {
|
|
88
|
+
await unlink(join(workDir(conversation), file));
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const value = JSON.parse(await readFile(join(workDir(conversation), file), "utf8"));
|
|
92
|
+
if (!isRecord(value) ||
|
|
93
|
+
value.version !== 1 ||
|
|
94
|
+
typeof value.createdAt !== "number" ||
|
|
95
|
+
!Number.isFinite(value.createdAt) ||
|
|
96
|
+
value.id !== file.slice(0, -5) ||
|
|
97
|
+
!Array.isArray(value.entryIds) ||
|
|
98
|
+
value.entryIds.length === 0 ||
|
|
99
|
+
!value.entryIds.every((id) => typeof id === "string") ||
|
|
100
|
+
!Array.isArray(value.messages) ||
|
|
101
|
+
!value.messages.every((item) => isRecord(item) &&
|
|
102
|
+
typeof item.entryId === "string" &&
|
|
103
|
+
isRecord(item.message) &&
|
|
104
|
+
["user", "assistant"].includes(String(item.message.role)))) {
|
|
105
|
+
throw new Error(`Corrupt memory work ${file}; inspect it on the server before retrying.`);
|
|
106
|
+
}
|
|
107
|
+
work.push(value);
|
|
108
|
+
}
|
|
109
|
+
work.sort((a, b) => a.createdAt - b.createdAt);
|
|
110
|
+
for (const item of work) {
|
|
111
|
+
const state = await readMemoryMaintenanceState(appHomeDir, conversation);
|
|
112
|
+
const cursor = state.lastReflectedEntryId ? item.entryIds.indexOf(state.lastReflectedEntryId) : -1;
|
|
113
|
+
const remaining = new Set(item.entryIds.slice(cursor + 1));
|
|
114
|
+
const messages = item.messages
|
|
115
|
+
.filter((entry) => remaining.has(entry.entryId))
|
|
116
|
+
.map((entry) => entry.message);
|
|
117
|
+
// A crash after checkpointing but before removing the work must not repeat inference.
|
|
118
|
+
if (cursor !== item.entryIds.length - 1) {
|
|
119
|
+
const result = await runReflect({
|
|
120
|
+
channelId: conversation.channelId,
|
|
121
|
+
deskDir: conversation.deskDir,
|
|
122
|
+
workspaceDir: options.workspaceDir,
|
|
123
|
+
model: options.model,
|
|
124
|
+
resolveApiKey: options.resolveApiKey,
|
|
125
|
+
messages,
|
|
126
|
+
usageContext: { channelId: conversation.channelId, desk: conversation.desk, correlationId: item.id },
|
|
127
|
+
});
|
|
128
|
+
await appendMemoryReviewLog(conversation.deskDir, {
|
|
129
|
+
timestamp: formatLocalTime(),
|
|
130
|
+
channelId: conversation.channelId,
|
|
131
|
+
reason: "reflect-boundary",
|
|
132
|
+
correlationId: item.id,
|
|
133
|
+
actions: [{ target: "memory", action: "reflect", added: result.added, updated: result.updated }],
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
|
|
137
|
+
...current,
|
|
138
|
+
// A later session/idle pass may already be ahead of this snapshot.
|
|
139
|
+
lastReflectedEntryId: !current.lastReflectedEntryId || item.entryIds.includes(current.lastReflectedEntryId)
|
|
140
|
+
? item.entryIds.at(-1)
|
|
141
|
+
: current.lastReflectedEntryId,
|
|
142
|
+
}));
|
|
143
|
+
await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
|
|
144
|
+
...current,
|
|
145
|
+
failureBackoffUntil: null,
|
|
146
|
+
}));
|
|
147
|
+
await writeFileAtomically(join(workDir(conversation), `${item.id}.done`), `${item.id}\n`);
|
|
148
|
+
await unlink(join(workDir(conversation), `${item.id}.json`));
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
|
|
154
|
+
...current,
|
|
155
|
+
failureBackoffUntil: formatLocalTime(new Date(Date.now() + 30 * 60_000)),
|
|
156
|
+
})).catch(() => undefined);
|
|
157
|
+
log.logWarn("memory.boundary.failed", "Boundary memory reflect failed", {
|
|
158
|
+
channelId: conversation.channelId,
|
|
159
|
+
reason: errorMessage(error),
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
import type { DeskConversation } from "../desk/types.js";
|
|
1
2
|
/**
|
|
2
3
|
* Spec 050, D10: `/memory` is the no-LLM control surface — it must work even when the model or
|
|
3
4
|
* the reflect pass is unavailable. `status` / `list` / `show` / `journal` are pure reads over
|
|
4
|
-
* `store.ts` / `journal.ts`; `forget` is the one write, going through the same
|
|
5
|
+
* `store.ts` / `journal.ts`; `forget` is the one write, going through the same desk memory
|
|
5
6
|
* queue as the tool and reflect so it never races them.
|
|
6
7
|
*/
|
|
7
8
|
interface MemoryCommandOptions {
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
/** The asking conversation: memory is read from its desk, maintenance state from it. */
|
|
10
|
+
conversation: DeskConversation;
|
|
10
11
|
appHomeDir?: string;
|
|
11
12
|
args: string;
|
|
12
13
|
}
|