@cydm/pie 4.11.0 → 4.12.0

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.
Files changed (37) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/cron/index.js +1 -1
  3. package/dist/builtin/extensions/im-forward/index.js +8670 -7364
  4. package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
  5. package/dist/builtin/extensions/memory/index.js +171 -66
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +533 -50
  8. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  9. package/dist/builtin/extensions/subagent/README.md +1 -1
  10. package/dist/builtin/extensions/subagent/index.js +3 -3
  11. package/dist/builtin/extensions/todo/index.js +2 -2
  12. package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
  13. package/dist/chunks/chunk-26ILLZKQ.js +400 -0
  14. package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
  15. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  16. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
  17. package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
  18. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  19. package/dist/chunks/{chunk-B5GKDXVG.js → chunk-IZ4DYCJ7.js} +246 -80
  20. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  21. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  22. package/dist/chunks/{chunk-EWPPGYBU.js → chunk-OGGL6LUN.js} +55 -16
  23. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  24. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  25. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  26. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  27. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  28. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
  29. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
  30. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  31. package/dist/chunks/{model-registry-MGZO2RBN.js → model-registry-QNEPISBJ.js} +11 -3
  32. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  33. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  34. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  35. package/dist/cli.js +740 -512
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-L7XXKNZW.js +0 -386
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cydm/pie",
3
- "version": "4.11.0",
3
+ "version": "4.12.0",
4
4
  "description": "Pie AI Agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  "test:skill-regressions": "node --test --test-force-exit --import tsx test/axi-bridge-lifecycle.test.ts test/bash-lifecycle.test.ts test/bash-powershell-display.test.ts test/skill-creator-runner.test.ts test/tui-use-contract.test.ts test/tui-use-runtime.test.ts test/tui-use-reap.test.ts test/tui-use-kill-escalation.test.ts test/browser-runtime.test.ts test/axi-stop-semantics.test.ts test/axi-page-routing.test.ts test/computer-use-axi.test.ts test/computer-evidence.test.ts test/interactive-lifecycle.test.ts",
21
21
  "test:offline:post": "node --test --test-force-exit --import tsx test/remote-model-catalog.test.ts",
22
22
  "test:offline": "node ../../scripts/run-cli-offline.mjs",
23
- "test:offline:main": "node --test --test-concurrency=2 --test-force-exit --import tsx test/cli-attention.test.ts test/cron.test.ts test/cron-process.test.ts test/cron-poll-gate.test.ts test/memory-distill.test.ts test/memory-injection-budget.test.ts test/memory-injection-freeze.test.ts test/memory-consumption-e2e.test.ts test/memory-frozen-matching.test.ts test/memory-soul-injection.test.ts test/config-dir-fail-closed.test.ts test/cron-concurrency.test.ts test/cron-dogfood.test.ts test/cron.terminal.test.ts test/cron-journey.terminal.test.ts test/builtin-extensions.test.ts test/im-forward.test.ts test/im-forward-cli.test.ts test/im-forward-userassigned.test.ts test/im-forward-bus-health.test.ts test/im-forward-panel-fastpath.test.ts test/im-forward-worker-panel.test.ts test/im-forward-cron-panel.test.ts test/im-forward-thread-steal.test.ts test/im-forward-panel-v3.test.ts test/headless-session-commands.test.ts test/headless-compact-audit.test.ts test/builtin-command-catalog.test.ts test/im-forward-consumer.test.ts test/im-forward-settled-reaction.test.ts test/im-forward-card-compiler.test.ts test/im-forward-integration.test.ts test/user-input-scope-vision-fallback.test.ts test/im-forward-anchor-ttl.test.ts test/im-forward-anchor-ttl.dogfood.test.ts test/im-forward-group-mention.test.ts test/im-forward-onboarding.test.ts test/ownership-concurrency.test.ts test/pie-ipc-windows-security.test.ts test/im-forward-dogfood.terminal.test.ts test/thread-registry.test.ts test/im-forward-event-hub.test.ts test/im-forward-hub-routing.test.ts test/im-forward-session-anchors.test.ts test/im-forward-session-roots-ads.test.ts test/extension-user-input.test.ts test/pie-ipc-pure.test.ts test/pie-ipc-resolve.test.ts test/pie-ipc-discovery.test.ts test/pie-ipc-transport.test.ts test/pie-ipc-delivery.test.ts test/pie-ipc-extension.test.ts test/pie-ipc-e2e.test.ts test/pie-ipc-security.test.ts test/pie-ipc-dogfood.test.ts test/pie-ipc-resident-dispatch.test.ts test/pie-proc.test.ts test/pie-proc-resume.test.ts test/session-ownership.test.ts test/initial-session.test.ts test/pie-ipc-host.terminal.test.ts test/core-services.test.ts test/cli.test.ts test/cli-json-events.test.ts test/cli-auto-compaction.test.ts test/execution-state-manager.test.ts test/queued-steer-execution-state.test.ts test/todo-steering-ownership.test.ts test/architecture-boundaries.test.ts test/attachment-resolver.test.ts test/kimi-attachment-provider.test.ts test/document-attachment-extension.test.ts test/auto-compact-overflow.test.ts test/auto-compaction-ui.test.ts test/tool-compaction-dogfood.terminal.test.ts test/hierarchical-command-system.test.ts test/mcp-adapter.test.ts test/herdr-agent-state.test.ts test/extensions-enablement.test.ts test/extension-selector-shortcuts.test.ts test/skill-tool-enablement.test.ts test/message-queue-unit.test.ts test/evals-harness.test.ts test/session-trace.test.ts test/json-events-event-sink.test.ts test/json-events-lifecycle-bridge.test.ts test/json-events-self-input.test.ts test/json-events-idle-mode.test.ts test/manager-cli.test.ts test/manager-upgrade.test.ts test/json-events-sidechat-diagnostics.test.ts test/json-events-sidechat-service.test.ts test/json-events-prewarm-shutdown.test.ts test/json-envelope-composition.test.ts test/subagent-session-store.test.ts test/subagent-resolution.test.ts test/supervisor-anchor-inject.test.ts test/runtime-mode-context.test.ts test/tool-policy.test.ts test/retry-policy.test.ts test/yolo-command.test.ts test/footer-lifecycle.test.ts test/footer-waiting-for-user.test.ts test/files-utils.test.ts test/source-size-guard.test.ts test/runtime-logger.test.ts test/release-readiness.test.ts test/package-artifacts.test.ts test/init-extension-contract.test.ts test/skills-runtime.test.ts test/skills-agents-discovery.test.ts test/skills-symlink.test.ts test/model-overrides.test.ts test/auth-storage.test.ts test/extension-register-provider.test.ts test/extension-reload.test.ts test/extension-terminal-input.test.ts test/extension-session-before-events.test.ts test/extension-widgets.test.ts test/extension-render-hint.test.ts test/extension-oauth-restore.test.ts test/cross-host-parity.test.ts test/tool-name-rendering.test.ts test/session-selector.test.ts test/tree-selector-pagination.test.ts test/context-report.test.ts test/context-signals.test.ts test/plan-cache-stability.test.ts test/cache-invalidation-trace.test.ts test/cache-retention.test.ts test/trace-report.test.ts test/boot-report.test.ts test/compaction-diff.test.ts test/entry-body-and-usage.test.ts test/session-control.test.ts test/terminal-title.test.ts test/interactive-controller-title.test.ts test/todo-title.terminal.test.ts test/host-envelope-dogfood.terminal.test.ts test/host-envelope-cross-mode.test.ts test/host-envelope-registry-lifecycle.test.ts test/host-envelope-migration-roundtrip.test.ts test/host-envelope-intake-order.test.ts test/plan-mode-extension.test.ts test/extension-interaction-signals.test.ts test/rendered-page-reader.test.ts test/tools-registry.test.ts test/system-prompt-contract.test.ts test/bash-yolo.test.ts test/terminal-state-hygiene.test.ts test/terminal-mode-filter-families.test.ts test/manager-model-env.test.ts test/bash-mode-sequence-boundary.test.ts test/bash-contract.test.ts test/bash-confirm-pending.test.ts test/interaction-status-lifecycle.test.ts test/bash-process-group.test.ts test/bash-artifact-sink.test.ts test/direct-bash.test.ts test/terminal-bell.test.ts test/ctrl-d-exit.test.ts test/session-display-title.test.ts test/calm-mode.test.ts test/stream-render-throttle.test.ts test/assistant-message-performance.test.ts test/streaming-split-parity.test.ts test/message-display-resync.test.ts test/project-root.test.ts test/guard-advisory-context.test.ts test/clear-command-usage.test.ts test/daily-agent-smoke.terminal.test.ts test/slash-menu-toggles.terminal.test.ts test/cli-args.test.ts test/session-resume-cwd.test.ts test/session-resume-restart.test.ts test/session-resume-picker.test.ts test/extensions-configured-paths.test.ts test/extensions-loader-path.test.ts test/file-picker.test.ts test/interrupt-recovery.test.ts test/mention-insert-regression.test.ts test/image-paste.test.ts test/clipboard-read-image.test.ts test/clipboard-races.test.ts test/clipboard-dogfood.terminal.test.ts test/mention-picker-navigation.test.ts test/pie-unity-rpc-skill.test.ts test/skill-creator-scripts.test.ts test/interactive-compact-command.test.ts test/computer-use-broker.test.ts test/computer-use-review-regressions.test.ts test/computer-use-safety.test.ts test/axi-connection-order.test.ts test/confirm-yolo-grant.test.ts test/yolo-grant.test.ts test/yolo-shortcut.test.ts test/host-idle.test.ts test/im-forward-anchor-reclaim.test.ts test/im-forward-browser.test.ts test/im-forward-dispatch-claim.test.ts test/im-forward-dispatch-verify.test.ts test/im-forward-existing-app-terminal.test.ts test/im-forward-panel-actions.test.ts test/manager-seed.test.ts test/pending-tools-turn-boundary.test.ts test/pie-ipc-results.test.ts test/session-display-name.test.ts test/session-model-metadata.test.ts test/thinking-capabilities.test.ts ../../scripts/node-test-diagnostics.test.js ../../scripts/offline-test-runner.test.js ../../scripts/unity-consumer.test.mjs ../../scripts/owned-process-cleanup.test.mjs",
23
+ "test:offline:main": "node --test --test-concurrency=2 --test-force-exit --import tsx test/cli-attention.test.ts test/cron.test.ts test/cron-process.test.ts test/cron-poll-gate.test.ts test/memory-distill.test.ts test/memory-wiki-cli.test.ts test/memory-injection-budget.test.ts test/memory-injection-freeze.test.ts test/memory-consumption-e2e.test.ts test/memory-frozen-matching.test.ts test/memory-soul-injection.test.ts test/config-dir-fail-closed.test.ts test/cron-concurrency.test.ts test/cron-dogfood.test.ts test/cron.terminal.test.ts test/cron-journey.terminal.test.ts test/builtin-extensions.test.ts test/im-forward.test.ts test/im-forward-cli.test.ts test/im-forward-userassigned.test.ts test/im-forward-bus-health.test.ts test/im-forward-panel-fastpath.test.ts test/im-forward-worker-panel.test.ts test/im-forward-cron-panel.test.ts test/im-forward-archive-panel.test.ts test/im-forward-auto-wake.test.ts test/im-forward-provider-boundary.test.ts test/im-forward-self-heal.test.ts test/im-forward-thread-steal.test.ts test/im-forward-panel-v3.test.ts test/headless-session-commands.test.ts test/headless-compact-audit.test.ts test/builtin-command-catalog.test.ts test/im-forward-consumer.test.ts test/im-forward-settled-reaction.test.ts test/im-forward-card-compiler.test.ts test/im-forward-integration.test.ts test/user-input-scope-vision-fallback.test.ts test/im-forward-anchor-ttl.test.ts test/im-forward-anchor-ttl.dogfood.test.ts test/im-forward-group-mention.test.ts test/im-forward-onboarding.test.ts test/ownership-concurrency.test.ts test/pie-ipc-windows-security.test.ts test/im-forward-dogfood.terminal.test.ts test/thread-registry.test.ts test/im-forward-event-hub.test.ts test/im-forward-hub-routing.test.ts test/im-forward-session-anchors.test.ts test/im-forward-session-roots-ads.test.ts test/extension-user-input.test.ts test/pie-ipc-pure.test.ts test/pie-ipc-resolve.test.ts test/pie-ipc-discovery.test.ts test/pie-ipc-transport.test.ts test/pie-ipc-delivery.test.ts test/pie-ipc-extension.test.ts test/pie-ipc-e2e.test.ts test/pie-ipc-security.test.ts test/pie-ipc-dogfood.test.ts test/pie-ipc-resident-dispatch.test.ts test/pie-proc.test.ts test/pie-proc-resume.test.ts test/session-ownership.test.ts test/initial-session.test.ts test/pie-ipc-host.terminal.test.ts test/core-services.test.ts test/cli.test.ts test/cli-json-events.test.ts test/cli-auto-compaction.test.ts test/execution-state-manager.test.ts test/queued-steer-execution-state.test.ts test/todo-steering-ownership.test.ts test/architecture-boundaries.test.ts test/attachment-resolver.test.ts test/kimi-attachment-provider.test.ts test/document-attachment-extension.test.ts test/auto-compact-overflow.test.ts test/auto-compaction-ui.test.ts test/tool-compaction-dogfood.terminal.test.ts test/hierarchical-command-system.test.ts test/mcp-adapter.test.ts test/herdr-agent-state.test.ts test/extensions-enablement.test.ts test/extension-selector-shortcuts.test.ts test/skill-tool-enablement.test.ts test/message-queue-unit.test.ts test/evals-harness.test.ts test/session-trace.test.ts test/json-events-event-sink.test.ts test/json-events-lifecycle-bridge.test.ts test/json-events-self-input.test.ts test/json-events-idle-mode.test.ts test/manager-cli.test.ts test/manager-upgrade.test.ts test/json-events-sidechat-diagnostics.test.ts test/json-events-sidechat-service.test.ts test/json-events-prewarm-shutdown.test.ts test/json-envelope-composition.test.ts test/subagent-session-store.test.ts test/subagent-resolution.test.ts test/supervisor-anchor-inject.test.ts test/runtime-mode-context.test.ts test/tool-policy.test.ts test/retry-policy.test.ts test/yolo-command.test.ts test/footer-lifecycle.test.ts test/footer-waiting-for-user.test.ts test/files-utils.test.ts test/source-size-guard.test.ts test/runtime-logger.test.ts test/release-readiness.test.ts test/package-artifacts.test.ts test/init-extension-contract.test.ts test/skills-runtime.test.ts test/skills-agents-discovery.test.ts test/skills-symlink.test.ts test/model-overrides.test.ts test/auth-storage.test.ts test/extension-register-provider.test.ts test/extension-reload.test.ts test/extension-terminal-input.test.ts test/extension-session-before-events.test.ts test/extension-widgets.test.ts test/extension-render-hint.test.ts test/extension-oauth-restore.test.ts test/cross-host-parity.test.ts test/tool-name-rendering.test.ts test/session-selector.test.ts test/tree-selector-pagination.test.ts test/context-report.test.ts test/context-signals.test.ts test/plan-cache-stability.test.ts test/cache-invalidation-trace.test.ts test/cache-retention.test.ts test/trace-report.test.ts test/boot-report.test.ts test/compaction-diff.test.ts test/entry-body-and-usage.test.ts test/session-control.test.ts test/terminal-title.test.ts test/interactive-controller-title.test.ts test/todo-title.terminal.test.ts test/host-envelope-dogfood.terminal.test.ts test/host-envelope-cross-mode.test.ts test/host-envelope-registry-lifecycle.test.ts test/host-envelope-migration-roundtrip.test.ts test/host-envelope-intake-order.test.ts test/plan-mode-extension.test.ts test/extension-interaction-signals.test.ts test/rendered-page-reader.test.ts test/tools-registry.test.ts test/system-prompt-contract.test.ts test/bash-yolo.test.ts test/terminal-state-hygiene.test.ts test/terminal-mode-filter-families.test.ts test/manager-model-env.test.ts test/bash-mode-sequence-boundary.test.ts test/bash-contract.test.ts test/bash-confirm-pending.test.ts test/interaction-status-lifecycle.test.ts test/bash-process-group.test.ts test/bash-artifact-sink.test.ts test/direct-bash.test.ts test/terminal-bell.test.ts test/ctrl-d-exit.test.ts test/session-display-title.test.ts test/calm-mode.test.ts test/stream-render-throttle.test.ts test/assistant-message-performance.test.ts test/streaming-split-parity.test.ts test/message-display-resync.test.ts test/project-root.test.ts test/guard-advisory-context.test.ts test/clear-command-usage.test.ts test/daily-agent-smoke.terminal.test.ts test/slash-menu-toggles.terminal.test.ts test/cli-args.test.ts test/session-resume-cwd.test.ts test/session-resume-restart.test.ts test/session-resume-picker.test.ts test/extensions-configured-paths.test.ts test/extensions-loader-path.test.ts test/file-picker.test.ts test/interrupt-recovery.test.ts test/mention-insert-regression.test.ts test/image-paste.test.ts test/clipboard-read-image.test.ts test/clipboard-races.test.ts test/clipboard-dogfood.terminal.test.ts test/mention-picker-navigation.test.ts test/pie-unity-rpc-skill.test.ts test/skill-creator-scripts.test.ts test/interactive-compact-command.test.ts test/computer-use-broker.test.ts test/computer-use-review-regressions.test.ts test/computer-use-safety.test.ts test/axi-connection-order.test.ts test/confirm-yolo-grant.test.ts test/yolo-grant.test.ts test/yolo-shortcut.test.ts test/host-idle.test.ts test/im-forward-anchor-reclaim.test.ts test/im-forward-browser.test.ts test/im-forward-dispatch-claim.test.ts test/im-forward-dispatch-verify.test.ts test/im-forward-existing-app-terminal.test.ts test/im-forward-panel-actions.test.ts test/manager-seed.test.ts test/pending-tools-turn-boundary.test.ts test/pie-ipc-results.test.ts test/session-display-name.test.ts test/session-model-metadata.test.ts test/thinking-capabilities.test.ts ../../scripts/node-test-diagnostics.test.js ../../scripts/offline-test-runner.test.js ../../scripts/unity-consumer.test.mjs ../../scripts/owned-process-cleanup.test.mjs",
24
24
  "test:all": "npm run test:offline && npm run test:terminal:vitest",
25
25
  "test:cron:tui": "node ../../scripts/run-with-env.mjs PIE_REAL_CRON_TUI=1 -- --test --import tsx test/cron.terminal.test.ts test/cron-journey.terminal.test.ts",
26
26
  "test:ipc:tui": "node ../../scripts/run-with-env.mjs PIE_REAL_IPC_TUI=1 -- --test --import tsx test/pie-ipc-host.terminal.test.ts",
@@ -1,386 +0,0 @@
1
- import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
-
3
- // src/commands/memory-distill.ts
4
- import * as fs from "node:fs";
5
- import { createRequire } from "node:module";
6
- import * as path from "node:path";
7
- import { spawn } from "node:child_process";
8
- var require2 = createRequire(import.meta.url);
9
- function distillWorkerLogPath(memoryRoot) {
10
- return path.join(memoryRoot, "distill-worker.log");
11
- }
12
- function distillLockPath(memoryRoot) {
13
- return path.join(memoryRoot, "distill.lock");
14
- }
15
- function readDistillWorkerLog(memoryRoot, limit = 20) {
16
- try {
17
- const raw = fs.readFileSync(distillWorkerLogPath(memoryRoot), "utf8");
18
- const lines = raw.split("\n").filter((line) => line.trim().length > 0);
19
- return lines.slice(-limit);
20
- } catch {
21
- return [];
22
- }
23
- }
24
- var MEMORY_DISTILL_RETRYABLE_EXIT_CODE = 75;
25
- function distillExitCode(result) {
26
- return result.ok ? 0 : result.retryable ? MEMORY_DISTILL_RETRYABLE_EXIT_CODE : 1;
27
- }
28
- function spawnDistillWorker(memoryRoot, date, sessionsDir) {
29
- return spawnDistillCli(memoryRoot, ["--date", date, ...sessionsDir ? ["--sessions-dir", sessionsDir] : []]);
30
- }
31
- function spawnDistillAutoWorker(memoryRoot, sessionsDir) {
32
- return spawnDistillCli(memoryRoot, ["--auto", ...sessionsDir ? ["--sessions-dir", sessionsDir] : []]);
33
- }
34
- function spawnDistillCli(memoryRoot, modeArgs) {
35
- const logPath = distillWorkerLogPath(memoryRoot);
36
- const entry = process.argv[1] ? path.resolve(process.argv[1]) : null;
37
- if (!entry) return false;
38
- try {
39
- fs.mkdirSync(memoryRoot, { recursive: true });
40
- } catch {
41
- return false;
42
- }
43
- const args = [entry, "memory", "distill", ...modeArgs, "--worker", "--memory-root", memoryRoot];
44
- let out;
45
- try {
46
- out = fs.openSync(logPath, "a");
47
- const child = spawn(process.execPath, args, {
48
- detached: true,
49
- windowsHide: true,
50
- stdio: ["ignore", out, out],
51
- env: { ...process.env, PIE_MEMORY_WORKER: "1" }
52
- });
53
- child.on("error", (error) => {
54
- try {
55
- fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawn failed: ${String(error)}
56
- `);
57
- } catch {
58
- }
59
- });
60
- child.unref();
61
- try {
62
- fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawned worker (${modeArgs.join(" ")}) (pid ${child.pid})
63
- `);
64
- } catch {
65
- }
66
- return true;
67
- } catch {
68
- return false;
69
- } finally {
70
- if (out !== void 0) {
71
- try {
72
- fs.closeSync(out);
73
- } catch {
74
- }
75
- }
76
- }
77
- }
78
- var advisoryLockBackend = /* @__PURE__ */ (() => {
79
- let impl;
80
- return () => {
81
- if (impl) return impl;
82
- const koffi = require2("koffi");
83
- const { createMemoryLockBackend } = require2("@pie/shared-headless-capabilities");
84
- impl = createMemoryLockBackend(koffi);
85
- return impl;
86
- };
87
- })();
88
- function acquireAdvisoryLock(lockPath) {
89
- const backend = advisoryLockBackend();
90
- fs.mkdirSync(path.dirname(lockPath), { recursive: true });
91
- let handle;
92
- try {
93
- handle = backend.open(lockPath);
94
- } catch (error) {
95
- throw error instanceof Error ? error : new Error(String(error));
96
- }
97
- try {
98
- const result = backend.lock(handle);
99
- if (result !== "acquired") {
100
- backend.unlock(handle);
101
- return null;
102
- }
103
- } catch (error) {
104
- backend.unlock(handle);
105
- throw error;
106
- }
107
- let released = false;
108
- return {
109
- release() {
110
- if (released) return;
111
- released = true;
112
- backend.unlock(handle);
113
- }
114
- };
115
- }
116
- function acquireDistillLock(memoryRoot) {
117
- const lock = acquireAdvisoryLock(distillLockPath(memoryRoot));
118
- return lock ? () => lock.release() : null;
119
- }
120
- async function withModelTimeout(promise, timeoutMs, label) {
121
- let timer;
122
- try {
123
- return await new Promise((resolve2, reject) => {
124
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
125
- Promise.resolve(promise).then(
126
- (value) => {
127
- clearTimeout(timer);
128
- resolve2(value);
129
- },
130
- (error) => {
131
- clearTimeout(timer);
132
- reject(error);
133
- }
134
- );
135
- });
136
- } finally {
137
- if (timer !== void 0) {
138
- const t = timer;
139
- queueMicrotask(() => clearTimeout(t));
140
- }
141
- }
142
- }
143
- function normalizeCwdPath(value) {
144
- if (value.length > 1 && value.endsWith(path.sep)) return value.slice(0, -1);
145
- return value;
146
- }
147
- function pathContains(parent, child) {
148
- if (parent === child) return true;
149
- const parentWithSep = parent.endsWith(path.sep) ? parent : parent + path.sep;
150
- return child.startsWith(parentWithSep);
151
- }
152
- async function readExcludeCwds() {
153
- try {
154
- const { getSettingsPath } = await import("./config-4EOI5NOU.js");
155
- const raw = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
156
- const list = raw?.extensions?.memory?.excludeCwds;
157
- if (!Array.isArray(list)) return [];
158
- return list.filter((entry) => typeof entry === "string" && path.isAbsolute(entry)).map(normalizeCwdPath);
159
- } catch {
160
- return [];
161
- }
162
- }
163
- function isTransientDistillError(message) {
164
- const lower = message.toLowerCase();
165
- if (/^(?:(?:harvest|evidence|apply):\s*)?memory store is contended \(write\.lock\)/i.test(message.trim())) {
166
- return true;
167
- }
168
- if (/^(?:harvest|evidence|apply):/i.test(message)) {
169
- return false;
170
- }
171
- if (/^(?:distill:[^:]+:\s*)?distill (?:response contains no json array|response contains invalid json|response is not an array|candidate is not an object|candidate has invalid shape|quote is implausibly long)/i.test(
172
- message.trim()
173
- )) {
174
- return true;
175
- }
176
- if (lower.includes("no complete model/key pair") || lower.includes("invalid api key") || lower.includes("unauthorized") || lower.includes("forbidden") || lower.includes("eacces") || lower.includes("eperm") || lower.includes("erofs") || lower.includes("enospc")) {
177
- return false;
178
- }
179
- if (lower.includes("syntaxerror") || lower.includes("invalid json") || lower.includes("in json at position")) {
180
- return false;
181
- }
182
- return lower.includes("timed out") || lower.includes("timeout") || lower.includes("rate limit") || lower.includes("too many requests") || lower.includes("overloaded") || lower.includes("temporarily unavailable") || lower.includes("service unavailable") || lower.includes("bad gateway") || lower.includes("gateway timeout") || lower.includes("fetch failed") || lower.includes("connection error") || lower.includes("network error") || lower.includes("socket hang up") || lower.includes("econnreset") || lower.includes("econnrefused") || lower.includes("etimedout") || lower.includes("enotfound") || lower.includes("eai_again") || lower.includes("stopreason=length") || /(?:^|:\s*|http\s+|status(?:\s*code)?\s*[:=]?\s*)(?:429|500|502|503|504|529)\b/.test(lower);
183
- }
184
- async function runDistillWorkerMain(memoryRoot, date, noExit = false, sessionsDir) {
185
- const log = (message) => {
186
- try {
187
- fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
188
- `);
189
- } catch {
190
- }
191
- };
192
- const release = acquireDistillLock(memoryRoot);
193
- if (!release) {
194
- return { ok: false, error: "another distillation worker holds the lock", busy: true };
195
- }
196
- let result;
197
- let ledger;
198
- try {
199
- const { ModelRegistry } = await import("./model-registry-MGZO2RBN.js");
200
- const { AuthStorage } = await import("./auth-storage-C3FZMT7J.js");
201
- const { getSessionsDir } = await import("./config-4EOI5NOU.js");
202
- const { FileSessionStore } = await import("./src-3PSR2AAX.js");
203
- const { MemoryStore, runDistillation } = await import("./src-F5N6O2HR.js");
204
- const store = new MemoryStore(memoryRoot);
205
- ledger = store;
206
- const registry = new ModelRegistry(AuthStorage.create());
207
- const excludeCwds = await readExcludeCwds();
208
- const cwdFilter = excludeCwds.length > 0 ? (cwd) => {
209
- if (!cwd) return true;
210
- const normalized = normalizeCwdPath(cwd);
211
- return !excludeCwds.some((excluded) => pathContains(excluded, normalized));
212
- } : void 0;
213
- const modelCall = (modelClass) => async (prompt, options) => {
214
- const resolved = registry.resolveModelClass(modelClass);
215
- if (!resolved.model || !resolved.apiKey) {
216
- throw new Error(`no complete model/key pair for class ${modelClass}${resolved.fallbackReason ? `: ${resolved.fallbackReason}` : ""}`);
217
- }
218
- const { completeSimple } = await import("./src-TIDKYA5F.js");
219
- const message = await withModelTimeout(
220
- completeSimple(
221
- resolved.model,
222
- {
223
- systemPrompt: options?.system ?? "You are a precise extraction engine.",
224
- messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }]
225
- },
226
- // 4.3.11: reasoning models (deepseek-flash) spend part of the
227
- // budget on the thinking pass — 4096 truncated the JSON
228
- // answer mid-array (stopReason=length). 16k for light calls.
229
- { apiKey: resolved.apiKey, maxTokens: Math.min(resolved.model.maxTokens ?? 16384, 16384) }
230
- ),
231
- 12e4,
232
- `memory ${modelClass} model call`
233
- );
234
- if (message.stopReason && message.stopReason !== "stop") {
235
- const detail = typeof message.errorMessage === "string" && message.errorMessage.trim() ? `: ${message.errorMessage.trim()}` : "";
236
- throw new Error(`memory model call ended with stopReason=${message.stopReason}${detail}`);
237
- }
238
- return message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
239
- };
240
- const resolvedSessionsDir = sessionsDir ? path.resolve(sessionsDir) : getSessionsDir();
241
- const distilled = await runDistillation(
242
- {
243
- sessionStore: new FileSessionStore(resolvedSessionsDir),
244
- memoryStore: store,
245
- lightCall: modelCall("light"),
246
- balancedCall: modelCall("balanced"),
247
- callTimeoutMs: 12e4,
248
- cwdFilter,
249
- log
250
- },
251
- date
252
- );
253
- log(`done ${date}: status=${distilled.status} sessions=${distilled.sessions} ops=${distilled.patchOps}${distilled.error ? ` error=${distilled.error}` : ""}`);
254
- if (distilled.status === "failed") {
255
- ledger?.recordFailure(date, distilled.error ?? "unknown failure");
256
- } else {
257
- ledger?.clearFailures(date);
258
- }
259
- const ok = distilled.status === "applied" || distilled.status === "skipped-ran" || distilled.status === "skipped-empty";
260
- const retryable = !ok && distilled.error !== void 0 && isTransientDistillError(distilled.error);
261
- result = { ok, status: distilled.status, error: distilled.error, ...retryable ? { retryable: true } : {} };
262
- } catch (error) {
263
- const message = error instanceof Error ? error.message : String(error);
264
- log(`failed ${date}: ${message}`);
265
- try {
266
- ledger?.recordFailure(date, message);
267
- } catch {
268
- }
269
- const retryable = isTransientDistillError(message);
270
- result = { ok: false, error: message, ...retryable ? { retryable: true } : {} };
271
- } finally {
272
- release();
273
- }
274
- if (!noExit) {
275
- const exitCode = distillExitCode(result);
276
- setTimeout(() => process.exit(exitCode), 50).unref?.();
277
- }
278
- return result;
279
- }
280
- async function runDistillAuto(memoryRoot, days = 7, runner, sessionsDir) {
281
- const log = (message) => {
282
- try {
283
- fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
284
- `);
285
- } catch {
286
- }
287
- };
288
- const { MemoryStore, todayKey, harvestSessionsForDate } = await import("./src-F5N6O2HR.js");
289
- const store = new MemoryStore(memoryRoot);
290
- const today = todayKey(Date.now());
291
- const dates = [];
292
- let pinnedSessionStore;
293
- let recoveryCwdFilter;
294
- if (sessionsDir) {
295
- try {
296
- const { FileSessionStore } = await import("./src-3PSR2AAX.js");
297
- pinnedSessionStore = new FileSessionStore(path.resolve(sessionsDir));
298
- const excludeCwds = await readExcludeCwds();
299
- if (excludeCwds.length > 0) {
300
- recoveryCwdFilter = (cwd) => {
301
- if (!cwd) return true;
302
- const normalized = normalizeCwdPath(cwd);
303
- return !excludeCwds.some((excluded) => pathContains(excluded, normalized));
304
- };
305
- }
306
- } catch {
307
- }
308
- }
309
- for (let offset = days; offset >= 1; offset -= 1) {
310
- const probe = /* @__PURE__ */ new Date();
311
- probe.setDate(probe.getDate() - offset);
312
- const date = todayKey(probe.getTime());
313
- if (date === today) continue;
314
- if (!store.hasRun(date)) {
315
- dates.push(date);
316
- continue;
317
- }
318
- if (pinnedSessionStore) {
319
- const run = store.loadState().runs[date];
320
- if (run && run.ops === 0 && !run.gated && !store.readJournal(date)) {
321
- try {
322
- if (harvestSessionsForDate(pinnedSessionStore, date, { maxCharsPerSession: 256, cwdFilter: recoveryCwdFilter }).length > 0) {
323
- store.transaction(() => {
324
- const state = store.loadState();
325
- const latest = state.runs[date];
326
- if (latest && latest.ops === 0 && !latest.gated && !store.readJournal(date)) {
327
- delete state.runs[date];
328
- store.writeState(state);
329
- }
330
- });
331
- dates.push(date);
332
- }
333
- } catch {
334
- }
335
- }
336
- }
337
- }
338
- if (dates.length === 0) {
339
- log("auto: no missing checkpoints in the window");
340
- return { ok: true, lines: ["memory --auto: no missing checkpoints in the last " + days + " days."] };
341
- }
342
- log(`auto: ${dates.length} missing date(s): ${dates.join(", ")}`);
343
- const lines = [];
344
- let ok = true;
345
- let deferred = false;
346
- let failures = 0;
347
- let hasPermanentFailure = false;
348
- for (const date of dates) {
349
- const result = await (runner ?? runDistillWorkerMain)(memoryRoot, date, true, sessionsDir);
350
- if (!result.ok && result.busy) {
351
- lines.push(`${date}: busy \u2014 another distillation worker is running; next schedule retries`);
352
- deferred = true;
353
- break;
354
- }
355
- lines.push(`${date}: ${result.status ?? "failed"}${result.error ? ` \u2014 ${result.error}` : ""}`);
356
- if (!result.ok) {
357
- ok = false;
358
- failures += 1;
359
- const isRetryable = result.retryable ?? (result.error !== void 0 && isTransientDistillError(result.error));
360
- if (!isRetryable) hasPermanentFailure = true;
361
- log(`auto: ${date} failed (${isRetryable ? "transient/retryable" : "permanent"}); continuing the remaining dates`);
362
- }
363
- }
364
- if (failures > 0) {
365
- lines.push(
366
- hasPermanentFailure ? `${failures} date(s) failed (includes permanent config/storage failure; inspect log)` : `${failures} date(s) failed (transient/retryable; next run retries them)`
367
- );
368
- }
369
- const succeeded = failures === 0;
370
- const retryable = failures > 0 && !hasPermanentFailure;
371
- if (!process.env.NODE_TEST_CONTEXT) {
372
- const code = distillExitCode({ ok: succeeded, retryable });
373
- setTimeout(() => process.exit(code), 50).unref?.();
374
- }
375
- return { ok: succeeded, ...retryable ? { retryable: true } : {}, lines };
376
- }
377
-
378
- export {
379
- distillWorkerLogPath,
380
- readDistillWorkerLog,
381
- distillExitCode,
382
- spawnDistillWorker,
383
- spawnDistillAutoWorker,
384
- runDistillWorkerMain,
385
- runDistillAuto
386
- };