@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/memory/lifecycle.js
CHANGED
|
@@ -1,59 +1,13 @@
|
|
|
1
|
-
import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
2
1
|
import * as log from "../log.js";
|
|
3
2
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
4
|
-
import { clipTextByPromptUnits } from "../shared/prompt-units.js";
|
|
5
3
|
import { errorMessage } from "../shared/text-utils.js";
|
|
6
|
-
import {
|
|
4
|
+
import { drainBoundaryReflectWork, enqueueBoundaryReflectWork } from "./boundary-work.js";
|
|
5
|
+
import { getDeskMemoryQueue } from "./desk-memory-queue.js";
|
|
7
6
|
import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./maintenance-state.js";
|
|
8
7
|
import { runReflect } from "./reflect.js";
|
|
9
8
|
import { reviewLogEntryFor } from "./reflect-job.js";
|
|
10
9
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
11
|
-
import {
|
|
12
|
-
const COMPACTION_INPUT_MAX_UNITS = 48_000;
|
|
13
|
-
const COMPACTION_INPUT_MIN_UNITS = 4_000;
|
|
14
|
-
const COMPACTION_INPUT_CHARS_PER_TOKEN = 3;
|
|
15
|
-
const COMPACTION_INPUT_HEAD_RATIO = 0.35;
|
|
16
|
-
/**
|
|
17
|
-
* Bound one standalone summarization request. Provider limits can be lower than a model's
|
|
18
|
-
* advertised context window; sending the whole pre-compaction transcript is therefore not safe.
|
|
19
|
-
* The head preserves the original goal and the larger tail preserves current work. Durable
|
|
20
|
-
* memory is refreshed before this runs, so the omitted middle is still available outside the
|
|
21
|
-
* provider request.
|
|
22
|
-
*/
|
|
23
|
-
export function boundCompactionMessages(messages, contextWindow, reserveTokens) {
|
|
24
|
-
if (messages.length === 0) {
|
|
25
|
-
return { messages, truncated: false, originalChars: 0, boundedChars: 0 };
|
|
26
|
-
}
|
|
27
|
-
const safeWindow = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : 128_000;
|
|
28
|
-
const safeReserve = Number.isFinite(reserveTokens) && reserveTokens > 0 ? Math.floor(reserveTokens) : 16_384;
|
|
29
|
-
const maxUnits = Math.min(COMPACTION_INPUT_MAX_UNITS, Math.max(COMPACTION_INPUT_MIN_UNITS, safeWindow - safeReserve - 8_192));
|
|
30
|
-
const serialized = serializeConversation(convertToLlm(messages));
|
|
31
|
-
const clipped = clipTextByPromptUnits(serialized, maxUnits, {
|
|
32
|
-
headRatio: COMPACTION_INPUT_HEAD_RATIO,
|
|
33
|
-
maxChars: maxUnits * COMPACTION_INPUT_CHARS_PER_TOKEN,
|
|
34
|
-
marker: "\n\n[... middle omitted from this compaction request; durable channel memory was refreshed before compaction ...]\n\n",
|
|
35
|
-
});
|
|
36
|
-
if (!clipped.truncated) {
|
|
37
|
-
return {
|
|
38
|
-
messages,
|
|
39
|
-
truncated: false,
|
|
40
|
-
originalChars: serialized.length,
|
|
41
|
-
boundedChars: serialized.length,
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
return {
|
|
45
|
-
messages: [
|
|
46
|
-
{
|
|
47
|
-
role: "user",
|
|
48
|
-
content: [{ type: "text", text: clipped.text }],
|
|
49
|
-
timestamp: Date.now(),
|
|
50
|
-
},
|
|
51
|
-
],
|
|
52
|
-
truncated: true,
|
|
53
|
-
originalChars: serialized.length,
|
|
54
|
-
boundedChars: clipped.text.length,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
10
|
+
import { buildIncrementalMemorySourceWindow } from "./source-window.js";
|
|
57
11
|
export class MemoryLifecycle {
|
|
58
12
|
constructor(options) {
|
|
59
13
|
this.options = options;
|
|
@@ -62,16 +16,18 @@ export class MemoryLifecycle {
|
|
|
62
16
|
this.lastDurableConsolidationRevision = 0;
|
|
63
17
|
// Tracks the detached new-session reflect run so shutdown/tests can await it.
|
|
64
18
|
this.backgroundNewSessionReflect = Promise.resolve();
|
|
65
|
-
this.
|
|
19
|
+
this.memoryQueue = options.memoryQueue ?? getDeskMemoryQueue();
|
|
66
20
|
}
|
|
67
21
|
createExtensionFactory() {
|
|
68
22
|
return (pi) => {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
});
|
|
23
|
+
if (this.options.enabled === false)
|
|
24
|
+
return;
|
|
72
25
|
pi.on("session_compact", async (event) => {
|
|
73
26
|
this.handleSessionCompact(event);
|
|
74
27
|
});
|
|
28
|
+
pi.on("session_compact_failed", () => {
|
|
29
|
+
this.startBoundaryReflect();
|
|
30
|
+
});
|
|
75
31
|
pi.on("session_before_switch", (event) => {
|
|
76
32
|
this.handleSessionBeforeSwitch(event);
|
|
77
33
|
});
|
|
@@ -84,16 +40,23 @@ export class MemoryLifecycle {
|
|
|
84
40
|
this.recordActivity("user-turn-started");
|
|
85
41
|
}
|
|
86
42
|
noteToolCall() {
|
|
43
|
+
if (this.options.enabled === false)
|
|
44
|
+
return;
|
|
87
45
|
this.durableDirty = true;
|
|
88
46
|
this.durableRevision++;
|
|
89
47
|
this.recordActivity("tool-call");
|
|
90
48
|
}
|
|
91
49
|
noteCompletedAssistantTurn() {
|
|
50
|
+
if (this.options.enabled === false)
|
|
51
|
+
return;
|
|
92
52
|
this.durableDirty = true;
|
|
93
53
|
this.durableRevision++;
|
|
94
54
|
this.recordActivity("assistant-turn-completed");
|
|
95
55
|
}
|
|
96
56
|
async flushForShutdown() {
|
|
57
|
+
if (this.options.enabled === false)
|
|
58
|
+
return;
|
|
59
|
+
await this.resumeBoundaryReflect();
|
|
97
60
|
// Let any detached new-session reflect run finish (and update the durable checkpoint)
|
|
98
61
|
// before deciding whether a final flush is still needed.
|
|
99
62
|
await this.whenNewSessionReflectSettled();
|
|
@@ -111,7 +74,7 @@ export class MemoryLifecycle {
|
|
|
111
74
|
});
|
|
112
75
|
}
|
|
113
76
|
runDurableMemoryJobSerial(job) {
|
|
114
|
-
return this.
|
|
77
|
+
return this.memoryQueue.run(this.options.conversation, job);
|
|
115
78
|
}
|
|
116
79
|
// Any unconsolidated durable activity since the last checkpoint, regardless of whether it
|
|
117
80
|
// ended on an assistant turn. Used only for the shutdown flush.
|
|
@@ -125,68 +88,65 @@ export class MemoryLifecycle {
|
|
|
125
88
|
logReflectResult(reason, result) {
|
|
126
89
|
if (result.skipped) {
|
|
127
90
|
log.logEvent("debug", "memory.reflect.skipped", "No meaningful snapshot", {
|
|
128
|
-
ctx: { channelId: this.options.channelId },
|
|
91
|
+
ctx: { channelId: this.options.conversation.channelId },
|
|
129
92
|
fields: { reason },
|
|
130
93
|
});
|
|
131
94
|
return;
|
|
132
95
|
}
|
|
133
|
-
log.logInfo(`[${this.options.channelId}] Memory reflect finished (${reason}): added=${result.added.length} updated=${result.updated.length} deleted=${result.deleted.length} touched=${result.touched.length} journal+=${result.journalAppended}`);
|
|
96
|
+
log.logInfo(`[${this.options.conversation.channelId}] Memory reflect finished (${reason}): added=${result.added.length} updated=${result.updated.length} deleted=${result.deleted.length} touched=${result.touched.length} journal+=${result.journalAppended}`);
|
|
134
97
|
}
|
|
135
98
|
async appendReviewLog(entry) {
|
|
136
99
|
try {
|
|
137
|
-
await appendMemoryReviewLog(this.options.
|
|
100
|
+
await appendMemoryReviewLog(this.options.conversation.deskDir, {
|
|
138
101
|
timestamp: formatLocalTime(),
|
|
139
|
-
channelId: this.options.channelId,
|
|
102
|
+
channelId: this.options.conversation.channelId,
|
|
140
103
|
...entry,
|
|
141
104
|
});
|
|
142
105
|
}
|
|
143
106
|
catch (error) {
|
|
144
107
|
const message = errorMessage(error);
|
|
145
108
|
log.logWarn("memory.review_log.write_failed", "Memory review log write failed", {
|
|
146
|
-
channelId: this.options.channelId,
|
|
109
|
+
channelId: this.options.conversation.channelId,
|
|
147
110
|
reason: message,
|
|
148
111
|
});
|
|
149
112
|
}
|
|
150
113
|
}
|
|
151
|
-
async runBoundaryReflect(reason, messages, sessionEntries
|
|
114
|
+
async runBoundaryReflect(reason, messages, sessionEntries) {
|
|
152
115
|
const messageSnapshot = [...(messages ?? this.options.getMessages())];
|
|
153
116
|
const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
|
|
154
117
|
const revisionSnapshot = this.durableRevision;
|
|
155
118
|
await this.runDurableMemoryJobSerial(async () => {
|
|
156
|
-
await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot
|
|
119
|
+
await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot);
|
|
157
120
|
});
|
|
158
121
|
}
|
|
159
|
-
async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision
|
|
122
|
+
async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision) {
|
|
160
123
|
try {
|
|
161
124
|
const maintenanceState = this.options.appHomeDir
|
|
162
|
-
? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.
|
|
125
|
+
? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.conversation)
|
|
163
126
|
: undefined;
|
|
164
127
|
const lastEntryId = maintenanceState?.lastReflectedEntryId;
|
|
165
|
-
const sourceWindow =
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
: buildIncrementalMemorySourceWindow({
|
|
173
|
-
entries: sessionEntrySnapshot,
|
|
174
|
-
lastEntryId,
|
|
175
|
-
sourceKind: reason,
|
|
176
|
-
fallbackMessages: messageSnapshot,
|
|
177
|
-
});
|
|
178
|
-
log.logInfo(`[${this.options.channelId}] Memory reflect starting (${reason})`);
|
|
128
|
+
const sourceWindow = buildIncrementalMemorySourceWindow({
|
|
129
|
+
entries: sessionEntrySnapshot,
|
|
130
|
+
lastEntryId,
|
|
131
|
+
sourceKind: reason,
|
|
132
|
+
fallbackMessages: messageSnapshot,
|
|
133
|
+
});
|
|
134
|
+
log.logInfo(`[${this.options.conversation.channelId}] Memory reflect starting (${reason})`);
|
|
179
135
|
const result = await runReflect({
|
|
180
|
-
channelId: this.options.channelId,
|
|
181
|
-
|
|
136
|
+
channelId: this.options.conversation.channelId,
|
|
137
|
+
deskDir: this.options.conversation.deskDir,
|
|
182
138
|
workspaceDir: this.options.workspaceDir,
|
|
183
139
|
model: this.options.getModel(),
|
|
184
140
|
resolveApiKey: this.options.resolveApiKey,
|
|
185
141
|
messages: sourceWindow.messages,
|
|
186
|
-
usageContext: {
|
|
142
|
+
usageContext: {
|
|
143
|
+
channelId: this.options.conversation.channelId,
|
|
144
|
+
desk: this.options.conversation.desk,
|
|
145
|
+
correlationId: sourceWindow.windowId,
|
|
146
|
+
},
|
|
187
147
|
});
|
|
188
148
|
if (this.options.appHomeDir && sourceWindow.throughEntryId) {
|
|
189
|
-
await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.
|
|
149
|
+
await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.conversation, (current) => ({
|
|
190
150
|
...current,
|
|
191
151
|
lastReflectedEntryId: sourceWindow.throughEntryId,
|
|
192
152
|
lastReflectAt: formatLocalTime(),
|
|
@@ -204,7 +164,7 @@ export class MemoryLifecycle {
|
|
|
204
164
|
catch (error) {
|
|
205
165
|
const message = errorMessage(error);
|
|
206
166
|
log.logWarn("memory.reflect.failed", "Memory reflect failed", {
|
|
207
|
-
channelId: this.options.channelId,
|
|
167
|
+
channelId: this.options.conversation.channelId,
|
|
208
168
|
reason: message,
|
|
209
169
|
fields: { trigger: reason },
|
|
210
170
|
});
|
|
@@ -215,27 +175,33 @@ export class MemoryLifecycle {
|
|
|
215
175
|
});
|
|
216
176
|
}
|
|
217
177
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
178
|
+
/** The agent's bounded compaction operation awaits only durable snapshot persistence. */
|
|
179
|
+
async prepareCompaction(event) {
|
|
180
|
+
if (this.options.enabled === false)
|
|
181
|
+
return;
|
|
182
|
+
await enqueueBoundaryReflectWork(this.options.conversation, event.branchEntries, event.preparation.firstKeptEntryId, event.signal);
|
|
183
|
+
}
|
|
184
|
+
resumeBoundaryReflect() {
|
|
185
|
+
this.startBoundaryReflect();
|
|
186
|
+
return this.backgroundNewSessionReflect;
|
|
187
|
+
}
|
|
188
|
+
startBoundaryReflect() {
|
|
189
|
+
if (this.options.enabled === false)
|
|
190
|
+
return;
|
|
191
|
+
if (!this.options.appHomeDir)
|
|
192
|
+
return;
|
|
193
|
+
this.backgroundNewSessionReflect = drainBoundaryReflectWork({
|
|
194
|
+
conversation: this.options.conversation,
|
|
195
|
+
workspaceDir: this.options.workspaceDir,
|
|
196
|
+
appHomeDir: this.options.appHomeDir,
|
|
197
|
+
model: this.options.getModel(),
|
|
198
|
+
resolveApiKey: this.options.resolveApiKey,
|
|
199
|
+
queue: this.memoryQueue,
|
|
200
|
+
});
|
|
236
201
|
}
|
|
237
202
|
handleSessionCompact(_event) {
|
|
238
203
|
this.recordActivity("boundary");
|
|
204
|
+
this.startBoundaryReflect();
|
|
239
205
|
}
|
|
240
206
|
handleSessionBeforeSwitch(event) {
|
|
241
207
|
if (event.reason !== "new") {
|
|
@@ -245,6 +211,8 @@ export class MemoryLifecycle {
|
|
|
245
211
|
}
|
|
246
212
|
/** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
|
|
247
213
|
noteNewSessionBoundary() {
|
|
214
|
+
if (this.options.enabled === false)
|
|
215
|
+
return;
|
|
248
216
|
// Snapshot the outgoing session synchronously: the switch has not happened yet, so
|
|
249
217
|
// getMessages()/getSessionEntries() still reference the session about to be replaced.
|
|
250
218
|
// Once we yield, this.session is rebound to the new (empty) session and the snapshot
|
|
@@ -257,7 +225,7 @@ export class MemoryLifecycle {
|
|
|
257
225
|
this.backgroundNewSessionReflect = this.runBoundaryReflect("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
|
|
258
226
|
const message = errorMessage(error);
|
|
259
227
|
log.logWarn("memory.reflect.rejected", "Background new-session reflect rejected", {
|
|
260
|
-
channelId: this.options.channelId,
|
|
228
|
+
channelId: this.options.conversation.channelId,
|
|
261
229
|
reason: message,
|
|
262
230
|
});
|
|
263
231
|
});
|
|
@@ -274,10 +242,12 @@ export class MemoryLifecycle {
|
|
|
274
242
|
this.recordActivity("boundary");
|
|
275
243
|
}
|
|
276
244
|
recordActivity(kind) {
|
|
245
|
+
if (this.options.enabled === false)
|
|
246
|
+
return;
|
|
277
247
|
const now = new Date();
|
|
278
248
|
const event = {
|
|
279
249
|
kind,
|
|
280
|
-
|
|
250
|
+
ref: this.options.conversation,
|
|
281
251
|
timestamp: formatLocalTime(now),
|
|
282
252
|
};
|
|
283
253
|
try {
|
|
@@ -286,7 +256,7 @@ export class MemoryLifecycle {
|
|
|
286
256
|
catch (error) {
|
|
287
257
|
const message = errorMessage(error);
|
|
288
258
|
log.logWarn("memory.activity.record_failed", "Memory activity record failed", {
|
|
289
|
-
channelId: this.options.channelId,
|
|
259
|
+
channelId: this.options.conversation.channelId,
|
|
290
260
|
reason: message,
|
|
291
261
|
});
|
|
292
262
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DeskConversation } from "../desk/types.js";
|
|
1
2
|
/** Spec 050, D9: one job (reflect), one small state shape. */
|
|
2
3
|
export interface MemoryMaintenanceState {
|
|
3
4
|
channelId: string;
|
|
@@ -8,25 +9,23 @@ export interface MemoryMaintenanceState {
|
|
|
8
9
|
lastReflectedEntryId?: string;
|
|
9
10
|
failureBackoffUntil?: string | null;
|
|
10
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Which conversation a maintenance state belongs to (spec 058, D12): reflect works one
|
|
14
|
+
* conversation at a time, so its dirty flag, idle clock and checkpoint are per conversation.
|
|
15
|
+
*/
|
|
16
|
+
export type MaintenanceStateRef = Pick<DeskConversation, "desk" | "conversation" | "channelId">;
|
|
11
17
|
export type MemoryActivityKind = "user-turn-started" | "tool-call" | "assistant-turn-completed" | "boundary";
|
|
12
18
|
export interface MemoryActivityEvent {
|
|
13
19
|
kind: MemoryActivityKind;
|
|
14
|
-
|
|
20
|
+
ref: MaintenanceStateRef;
|
|
15
21
|
timestamp: string;
|
|
16
22
|
eligibleAfter?: string;
|
|
17
23
|
}
|
|
18
24
|
export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string;
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* it raw put the file in a subdirectory of the state dir — `group_a/b==.json`. Reads and writes
|
|
24
|
-
* agreed, so nothing was lost, but {@link getMemoryMaintenanceStateDir}'s only listing walks the
|
|
25
|
-
* top level: every such channel was invisible to the scheduler's state-derived discovery.
|
|
26
|
-
*/
|
|
27
|
-
export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
|
|
28
|
-
export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
|
|
29
|
-
export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
|
|
25
|
+
/** `state/memory/<desk>/<conversation>.json`: both segments are validated names, never a channel id. */
|
|
26
|
+
export declare function getMemoryMaintenanceStatePath(appHomeDir: string, ref: MaintenanceStateRef): string;
|
|
27
|
+
export declare function readMemoryMaintenanceState(appHomeDir: string, ref: MaintenanceStateRef): Promise<MemoryMaintenanceState>;
|
|
28
|
+
export declare function updateMemoryMaintenanceState(appHomeDir: string, ref: MaintenanceStateRef, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
|
|
30
29
|
/** Apply a single activity event. The buffered path folds a whole burst through the same core. */
|
|
31
30
|
export declare function applyMemoryActivityToState(state: MemoryMaintenanceState, event: MemoryActivityEvent): MemoryMaintenanceState;
|
|
32
31
|
/**
|
|
@@ -46,14 +45,14 @@ export declare function applyMemoryActivityToState(state: MemoryMaintenanceState
|
|
|
46
45
|
*/
|
|
47
46
|
export interface MemoryActivityRecorder {
|
|
48
47
|
record(event: MemoryActivityEvent): void;
|
|
49
|
-
/** Write out buffered activity for one
|
|
50
|
-
flush(
|
|
48
|
+
/** Write out buffered activity for one conversation, or for all of them when `ref` is omitted. */
|
|
49
|
+
flush(ref?: MaintenanceStateRef): Promise<void>;
|
|
51
50
|
}
|
|
52
51
|
export declare const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5000;
|
|
53
52
|
export interface CreateMemoryActivityRecorderOptions {
|
|
54
53
|
appHomeDir: string;
|
|
55
54
|
/** Override the flush debounce; tests use a short one. */
|
|
56
55
|
debounceMs?: number;
|
|
57
|
-
onError?: (
|
|
56
|
+
onError?: (ref: MaintenanceStateRef, error: unknown) => void;
|
|
58
57
|
}
|
|
59
58
|
export declare function createMemoryActivityRecorder(options: CreateMemoryActivityRecorderOptions): MemoryActivityRecorder;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { getChannelDirName } from "../channel/channel-paths.js";
|
|
4
3
|
import * as log from "../log.js";
|
|
5
4
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
5
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
@@ -9,16 +8,12 @@ const stateUpdateQueue = createSerialQueue();
|
|
|
9
8
|
export function getMemoryMaintenanceStateDir(appHomeDir) {
|
|
10
9
|
return join(appHomeDir, "state", "memory");
|
|
11
10
|
}
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
* top level: every such channel was invisible to the scheduler's state-derived discovery.
|
|
19
|
-
*/
|
|
20
|
-
export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
|
|
21
|
-
return join(getMemoryMaintenanceStateDir(appHomeDir), `${getChannelDirName(channelId)}.json`);
|
|
11
|
+
/** `state/memory/<desk>/<conversation>.json`: both segments are validated names, never a channel id. */
|
|
12
|
+
export function getMemoryMaintenanceStatePath(appHomeDir, ref) {
|
|
13
|
+
return join(getMemoryMaintenanceStateDir(appHomeDir), ref.desk, `${ref.conversation}.json`);
|
|
14
|
+
}
|
|
15
|
+
function refKey(ref) {
|
|
16
|
+
return `${ref.desk}/${ref.conversation}`;
|
|
22
17
|
}
|
|
23
18
|
function createDefaultState(channelId) {
|
|
24
19
|
return { channelId, dirty: false, failureBackoffUntil: null };
|
|
@@ -47,8 +42,9 @@ function normalizeState(channelId, value) {
|
|
|
47
42
|
failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
|
|
48
43
|
};
|
|
49
44
|
}
|
|
50
|
-
export async function readMemoryMaintenanceState(appHomeDir,
|
|
51
|
-
const
|
|
45
|
+
export async function readMemoryMaintenanceState(appHomeDir, ref) {
|
|
46
|
+
const { channelId } = ref;
|
|
47
|
+
const path = getMemoryMaintenanceStatePath(appHomeDir, ref);
|
|
52
48
|
try {
|
|
53
49
|
const raw = await readFile(path, "utf-8");
|
|
54
50
|
return normalizeState(channelId, JSON.parse(raw));
|
|
@@ -61,15 +57,16 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
|
|
|
61
57
|
log.logWarn("memory.state.read_failed", "Memory maintenance state unreadable; rebuilding defaults", {
|
|
62
58
|
channelId: channelId,
|
|
63
59
|
reason: message,
|
|
60
|
+
fields: { desk: ref.desk, conversation: ref.conversation },
|
|
64
61
|
});
|
|
65
62
|
return createDefaultState(channelId);
|
|
66
63
|
}
|
|
67
64
|
}
|
|
68
|
-
export async function updateMemoryMaintenanceState(appHomeDir,
|
|
69
|
-
const path = getMemoryMaintenanceStatePath(appHomeDir,
|
|
65
|
+
export async function updateMemoryMaintenanceState(appHomeDir, ref, update) {
|
|
66
|
+
const path = getMemoryMaintenanceStatePath(appHomeDir, ref);
|
|
70
67
|
return stateUpdateQueue.run(path, async () => {
|
|
71
|
-
const current = await readMemoryMaintenanceState(appHomeDir,
|
|
72
|
-
const next = normalizeState(channelId, update(current));
|
|
68
|
+
const current = await readMemoryMaintenanceState(appHomeDir, ref);
|
|
69
|
+
const next = normalizeState(ref.channelId, update(current));
|
|
73
70
|
await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
74
71
|
return next;
|
|
75
72
|
});
|
|
@@ -94,64 +91,68 @@ function applyPendingActivityToState(state, channelId, pending) {
|
|
|
94
91
|
}
|
|
95
92
|
/** Apply a single activity event. The buffered path folds a whole burst through the same core. */
|
|
96
93
|
export function applyMemoryActivityToState(state, event) {
|
|
97
|
-
return applyPendingActivityToState(state, event.channelId, mergeMemoryActivity(undefined, event));
|
|
94
|
+
return applyPendingActivityToState(state, event.ref.channelId, mergeMemoryActivity(undefined, event));
|
|
98
95
|
}
|
|
99
96
|
export const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5_000;
|
|
100
97
|
export function createMemoryActivityRecorder(options) {
|
|
101
98
|
const debounceMs = options.debounceMs ?? DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS;
|
|
102
99
|
const pending = new Map();
|
|
100
|
+
const refs = new Map();
|
|
103
101
|
const timers = new Map();
|
|
104
|
-
/** The most recent write per
|
|
102
|
+
/** The most recent write per conversation, so `flush` can await work another caller started. */
|
|
105
103
|
const inFlight = new Map();
|
|
106
|
-
const cancelTimer = (
|
|
107
|
-
const timer = timers.get(
|
|
104
|
+
const cancelTimer = (key) => {
|
|
105
|
+
const timer = timers.get(key);
|
|
108
106
|
if (timer) {
|
|
109
107
|
clearTimeout(timer);
|
|
110
|
-
timers.delete(
|
|
108
|
+
timers.delete(key);
|
|
111
109
|
}
|
|
112
110
|
};
|
|
113
|
-
const
|
|
114
|
-
cancelTimer(
|
|
115
|
-
const delta = pending.get(
|
|
116
|
-
|
|
117
|
-
|
|
111
|
+
const flushConversation = (key) => {
|
|
112
|
+
cancelTimer(key);
|
|
113
|
+
const delta = pending.get(key);
|
|
114
|
+
const ref = refs.get(key);
|
|
115
|
+
if (!delta || !ref) {
|
|
116
|
+
return inFlight.get(key) ?? Promise.resolve();
|
|
118
117
|
}
|
|
119
118
|
// Cleared before the await so events arriving during the write start a fresh batch
|
|
120
119
|
// instead of being swallowed by this one.
|
|
121
|
-
pending.delete(
|
|
122
|
-
const write = updateMemoryMaintenanceState(options.appHomeDir,
|
|
120
|
+
pending.delete(key);
|
|
121
|
+
const write = updateMemoryMaintenanceState(options.appHomeDir, ref, (state) => applyPendingActivityToState(state, ref.channelId, delta))
|
|
123
122
|
.then(() => undefined)
|
|
124
123
|
.catch((error) => {
|
|
125
124
|
// Put the delta back so the counters are not silently lost; the next event (or
|
|
126
125
|
// flush) retries it, folded in front of anything buffered while this write ran.
|
|
127
|
-
pending.set(
|
|
128
|
-
options.onError?.(
|
|
126
|
+
pending.set(key, mergeBack(delta, pending.get(key)));
|
|
127
|
+
options.onError?.(ref, error);
|
|
129
128
|
})
|
|
130
129
|
.finally(() => {
|
|
131
|
-
if (inFlight.get(
|
|
132
|
-
inFlight.delete(
|
|
130
|
+
if (inFlight.get(key) === write) {
|
|
131
|
+
inFlight.delete(key);
|
|
133
132
|
}
|
|
134
133
|
});
|
|
135
|
-
inFlight.set(
|
|
134
|
+
inFlight.set(key, write);
|
|
136
135
|
return write;
|
|
137
136
|
};
|
|
138
137
|
return {
|
|
139
138
|
record(event) {
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
const key = refKey(event.ref);
|
|
140
|
+
refs.set(key, event.ref);
|
|
141
|
+
pending.set(key, mergeMemoryActivity(pending.get(key), event));
|
|
142
|
+
if (timers.has(key)) {
|
|
142
143
|
return;
|
|
143
144
|
}
|
|
144
145
|
const timer = setTimeout(() => {
|
|
145
|
-
timers.delete(
|
|
146
|
-
void
|
|
146
|
+
timers.delete(key);
|
|
147
|
+
void flushConversation(key);
|
|
147
148
|
}, debounceMs);
|
|
148
149
|
// Buffered counters are never a reason to keep the process alive.
|
|
149
150
|
timer.unref?.();
|
|
150
|
-
timers.set(
|
|
151
|
+
timers.set(key, timer);
|
|
151
152
|
},
|
|
152
|
-
async flush(
|
|
153
|
-
const
|
|
154
|
-
await Promise.all([...
|
|
153
|
+
async flush(ref) {
|
|
154
|
+
const keys = ref ? [refKey(ref)] : new Set([...pending.keys(), ...inFlight.keys()]);
|
|
155
|
+
await Promise.all([...keys].map((key) => flushConversation(key)));
|
|
155
156
|
},
|
|
156
157
|
};
|
|
157
158
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
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
|
-
import {
|
|
4
|
+
import type { DeskConversation } from "../desk/types.js";
|
|
5
|
+
import { type DeskMemoryQueue } from "./desk-memory-queue.js";
|
|
5
6
|
import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
|
|
6
7
|
import { runReflect } from "./reflect.js";
|
|
7
8
|
/**
|
|
@@ -12,8 +13,8 @@ import { runReflect } from "./reflect.js";
|
|
|
12
13
|
*/
|
|
13
14
|
export interface ReflectJobInput {
|
|
14
15
|
appHomeDir: string;
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
/** The conversation to reflect on; its maintenance state is per conversation, its memory per desk. */
|
|
17
|
+
conversation: DeskConversation;
|
|
17
18
|
workspaceDir: string;
|
|
18
19
|
channelActive: boolean;
|
|
19
20
|
now?: Date;
|
|
@@ -25,7 +26,7 @@ export interface ReflectJobInput {
|
|
|
25
26
|
/** Transcript accessors: only called once the gate has decided the job may actually run. */
|
|
26
27
|
messages: () => AgentMessage[];
|
|
27
28
|
sessionEntries: () => SessionEntry[];
|
|
28
|
-
queue?:
|
|
29
|
+
queue?: DeskMemoryQueue;
|
|
29
30
|
}
|
|
30
31
|
export declare function runReflectJob(input: ReflectJobInput): Promise<void>;
|
|
31
32
|
/** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
2
2
|
import { errorMessage } from "../shared/text-utils.js";
|
|
3
|
-
import {
|
|
3
|
+
import { drainBoundaryReflectWork } from "./boundary-work.js";
|
|
4
|
+
import { getDeskMemoryQueue } from "./desk-memory-queue.js";
|
|
4
5
|
import { shouldRunReflect } from "./maintenance-gates.js";
|
|
5
6
|
import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
|
|
6
7
|
import { resolveMemoryMaintenanceSettings, } from "./maintenance-tuning.js";
|
|
@@ -12,11 +13,16 @@ function backoffUntil(now, settings) {
|
|
|
12
13
|
return formatLocalTime(new Date(now.getTime() + Math.max(0, settings.failureBackoffMinutes) * 60_000));
|
|
13
14
|
}
|
|
14
15
|
export async function runReflectJob(input) {
|
|
15
|
-
const queue = input.queue ??
|
|
16
|
-
|
|
16
|
+
const queue = input.queue ?? getDeskMemoryQueue();
|
|
17
|
+
const { conversation } = input;
|
|
18
|
+
const { channelId, deskDir } = conversation;
|
|
19
|
+
await drainBoundaryReflectWork({ ...input, queue });
|
|
20
|
+
if (!input.settings.memoryMaintenance.enabled)
|
|
21
|
+
return;
|
|
22
|
+
return queue.run(conversation, async () => {
|
|
17
23
|
const now = input.now ?? new Date();
|
|
18
24
|
const maintenance = resolveMemoryMaintenanceSettings(input.settings.memoryMaintenance);
|
|
19
|
-
const state = await readMemoryMaintenanceState(input.appHomeDir,
|
|
25
|
+
const state = await readMemoryMaintenanceState(input.appHomeDir, conversation);
|
|
20
26
|
let cachedWindow;
|
|
21
27
|
const loadSourceWindow = () => {
|
|
22
28
|
cachedWindow ??= buildIncrementalMemorySourceWindow({
|
|
@@ -41,9 +47,9 @@ export async function runReflectJob(input) {
|
|
|
41
47
|
},
|
|
42
48
|
});
|
|
43
49
|
if (!decision.allowed) {
|
|
44
|
-
await appendMemoryReviewLog(
|
|
50
|
+
await appendMemoryReviewLog(deskDir, {
|
|
45
51
|
timestamp: formatLocalTime(now),
|
|
46
|
-
channelId:
|
|
52
|
+
channelId: channelId,
|
|
47
53
|
reason: "reflect",
|
|
48
54
|
skipped: [{ target: "reflect", reason: decision.skipReason }],
|
|
49
55
|
});
|
|
@@ -52,37 +58,37 @@ export async function runReflectJob(input) {
|
|
|
52
58
|
const sourceWindow = loadSourceWindow();
|
|
53
59
|
try {
|
|
54
60
|
const result = await runReflect({
|
|
55
|
-
channelId:
|
|
56
|
-
|
|
61
|
+
channelId: channelId,
|
|
62
|
+
deskDir: deskDir,
|
|
57
63
|
workspaceDir: input.workspaceDir,
|
|
58
64
|
model: input.model,
|
|
59
65
|
resolveApiKey: input.resolveApiKey,
|
|
60
66
|
messages: sourceWindow.messages,
|
|
61
|
-
usageContext: { channelId:
|
|
67
|
+
usageContext: { channelId, desk: conversation.desk, correlationId: sourceWindow.windowId },
|
|
62
68
|
});
|
|
63
|
-
await updateMemoryMaintenanceState(input.appHomeDir,
|
|
69
|
+
await updateMemoryMaintenanceState(input.appHomeDir, conversation, (current) => ({
|
|
64
70
|
...current,
|
|
65
71
|
lastReflectAt: formatLocalTime(now),
|
|
66
72
|
lastReflectedEntryId: sourceWindow.throughEntryId ?? current.lastReflectedEntryId,
|
|
67
73
|
failureBackoffUntil: null,
|
|
68
74
|
}));
|
|
69
|
-
await appendMemoryReviewLog(
|
|
75
|
+
await appendMemoryReviewLog(deskDir, {
|
|
70
76
|
timestamp: formatLocalTime(now),
|
|
71
|
-
channelId:
|
|
77
|
+
channelId: channelId,
|
|
72
78
|
reason: "reflect",
|
|
73
79
|
correlationId: sourceWindow.windowId,
|
|
74
80
|
...reviewLogEntryFor(result),
|
|
75
81
|
});
|
|
76
82
|
}
|
|
77
83
|
catch (error) {
|
|
78
|
-
await updateMemoryMaintenanceState(input.appHomeDir,
|
|
84
|
+
await updateMemoryMaintenanceState(input.appHomeDir, conversation, (current) => ({
|
|
79
85
|
...current,
|
|
80
86
|
failureBackoffUntil: backoffUntil(now, maintenance),
|
|
81
87
|
}));
|
|
82
88
|
const message = errorMessage(error);
|
|
83
|
-
await appendMemoryReviewLog(
|
|
89
|
+
await appendMemoryReviewLog(deskDir, {
|
|
84
90
|
timestamp: formatLocalTime(now),
|
|
85
|
-
channelId:
|
|
91
|
+
channelId: channelId,
|
|
86
92
|
reason: "reflect",
|
|
87
93
|
error: message,
|
|
88
94
|
});
|