@cortex-agent/server 2026.6.22 → 2026.7.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -13
- package/defaults/.claude/settings.json +4 -0
- package/defaults/config/CORTEX.md +9 -0
- package/defaults/config/hooks/01-sensitive-file-edit.json +11 -0
- package/defaults/config/hooks/02-tasks-yaml-guard.json +11 -0
- package/defaults/config/hooks/03-ask-user-question-hook.json +19 -0
- package/defaults/config/hooks/04-exit-plan-mode-hook.json +19 -0
- package/defaults/config/hooks/05-memory-ref-tracker.json +10 -0
- package/defaults/config/hooks/06-rules-loader.json +10 -0
- package/defaults/config/hooks/07-session-activity-tracker.json +10 -0
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/09-permission-request-auto-allow.json +11 -0
- package/defaults/config/hooks/10-cortex-md-injector-session-start.json +10 -0
- package/defaults/config/hooks/11-task-status-check.json +14 -0
- package/defaults/config/hooks/12-session-new-hook.json +11 -0
- package/defaults/config/hooks/CORTEX.md +18 -0
- package/defaults/config/thread-templates/agents/coder-reviewer.json +25 -0
- package/defaults/config/thread-templates/agents/coder.json +30 -0
- package/defaults/config/thread-templates/agents/direct-review.json +17 -0
- package/defaults/config/thread-templates/agents/direct-web.json +16 -0
- package/defaults/config/thread-templates/agents/direct.json +16 -0
- package/defaults/config/thread-templates/agents/director.json +14 -0
- package/defaults/config/thread-templates/agents/doc-reviewer.json +14 -0
- package/defaults/config/thread-templates/agents/doc-writer.json +25 -0
- package/defaults/config/thread-templates/agents/executor-reviewer.json +14 -0
- package/defaults/config/thread-templates/agents/executor.json +25 -0
- package/defaults/config/thread-templates/agents/main.json +16 -0
- package/defaults/config/thread-templates/agents/manager.json +17 -0
- package/defaults/config/thread-templates/agents/scheduler-main.json +16 -0
- package/defaults/config/thread-templates/shells/worker-review.json +19 -0
- package/defaults/config/thread-templates/templates/coder-review.json +53 -0
- package/defaults/config/thread-templates/templates/default.json +10 -0
- package/defaults/config/thread-templates/templates/doc-review.json +6 -0
- package/defaults/config/thread-templates/templates/execute-review.json +6 -0
- package/defaults/config/thread-templates/templates/manager.json +11 -0
- package/defaults/config/thread-templates/templates/scheduler.json +19 -0
- package/defaults/context/decisions/DR-0012.md +1 -1
- package/defaults/context/user/CORTEX.md +2 -2
- package/defaults/gitignore +3 -0
- package/defaults/hooks/CORTEX.md +18 -0
- package/defaults/hooks/ask-user-question-hook.mjs +1 -0
- package/defaults/hooks/cortex-hook-api.mjs +84 -0
- package/defaults/hooks/cortex-md-injector.mjs +99 -49
- package/defaults/hooks/exit-plan-mode-hook.mjs +1 -0
- package/defaults/hooks/memory-ref-tracker.mjs +1 -0
- package/defaults/hooks/new-session-hook.mjs +1 -0
- package/defaults/hooks/post-task-hook.mjs +1 -0
- package/defaults/hooks/rules-loader.mjs +1 -0
- package/defaults/hooks/sensitive-file-edit.mjs +1 -0
- package/defaults/hooks/session-activity-tracker.mjs +8 -100
- package/defaults/hooks/task-status-check.mjs +10 -10
- package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
- package/defaults/mcp-config-web.json +11 -0
- package/defaults/pi/agents/explore.md +9 -0
- package/defaults/pi/agents/general-purpose.md +6 -0
- package/defaults/pi/agents/plan.md +9 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +2 -2
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +33 -0
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +16 -16
- package/defaults/plugins/cortex-common/skills/execute-method/SKILL.md +53 -0
- package/defaults/plugins/cortex-common/skills/execute-review-rubric/SKILL.md +102 -0
- package/defaults/plugins/cortex-common/skills/manager-method/SKILL.md +67 -0
- package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +3 -3
- package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +54 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +132 -112
- package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +17 -10
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/orient/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +66 -17
- package/defaults/prompts/directives/coder-reviewer.md +6 -6
- package/defaults/prompts/directives/coder.md +4 -29
- package/defaults/prompts/directives/director.md +4 -17
- package/defaults/prompts/directives/doc-reviewer.md +2 -35
- package/defaults/prompts/directives/doc-writer.md +2 -7
- package/defaults/prompts/directives/executor-reviewer.md +2 -39
- package/defaults/prompts/directives/executor.md +2 -7
- package/defaults/prompts/directives/manager.md +12 -27
- package/defaults/prompts/systemPrompts/coder.md +1 -1
- package/defaults/prompts/systemPrompts/direct.md +1 -1
- package/defaults/prompts/systemPrompts/web.md +5 -0
- package/defaults/prompts/systemPrompts/worker.md +1 -1
- package/dist/agent-adapter/bg-wait.d.ts +44 -0
- package/dist/agent-adapter/bg-wait.js +197 -0
- package/dist/agent-adapter/capabilities.d.ts +7 -1
- package/dist/agent-adapter/capabilities.js +18 -9
- package/dist/agent-adapter/claude/adapter-tui.d.ts +14 -0
- package/dist/agent-adapter/claude/adapter-tui.js +16 -0
- package/dist/agent-adapter/claude/adapter.d.ts +89 -5
- package/dist/agent-adapter/claude/adapter.js +410 -40
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +23 -8
- package/dist/agent-adapter/claude/bg-task-tracker.js +48 -19
- package/dist/agent-adapter/claude/compact-window.d.ts +9 -0
- package/dist/agent-adapter/claude/compact-window.js +46 -0
- package/dist/agent-adapter/claude/context-usage.d.ts +28 -0
- package/dist/agent-adapter/claude/context-usage.js +177 -0
- package/dist/agent-adapter/claude/defaults.d.ts +17 -3
- package/dist/agent-adapter/claude/defaults.js +25 -9
- package/dist/agent-adapter/claude/event-parser.d.ts +30 -0
- package/dist/agent-adapter/claude/event-parser.js +68 -4
- package/dist/agent-adapter/claude/hooks-builder.d.ts +23 -23
- package/dist/agent-adapter/claude/hooks-builder.js +63 -7
- package/dist/agent-adapter/claude/spawn-args.d.ts +25 -6
- package/dist/agent-adapter/claude/spawn-args.js +62 -22
- package/dist/agent-adapter/index.js +2 -4
- package/dist/agent-adapter/normalize/event-types.d.ts +8 -1
- package/dist/agent-adapter/normalize/event-types.js +1 -1
- package/dist/agent-adapter/normalize/tool-names.js +0 -9
- package/dist/agent-adapter/pi/adapter.d.ts +3 -33
- package/dist/agent-adapter/pi/adapter.js +461 -229
- package/dist/agent-adapter/pi/agent-dir.d.ts +6 -0
- package/dist/agent-adapter/pi/agent-dir.js +24 -14
- package/dist/agent-adapter/pi/defaults.d.ts +4 -0
- package/dist/agent-adapter/pi/defaults.js +11 -0
- package/dist/agent-adapter/pi/discovery.d.ts +4 -0
- package/dist/agent-adapter/pi/discovery.js +63 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +13 -2
- package/dist/agent-adapter/pi/event-parser.js +139 -69
- package/dist/agent-adapter/pi/hook-bridge.d.ts +13 -28
- package/dist/agent-adapter/pi/hook-bridge.js +272 -167
- package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +24 -0
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +39 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -35
- package/dist/agent-adapter/pi/mcp-bridge.js +147 -137
- package/dist/agent-adapter/pi/pi-ext-types.d.ts +30 -0
- package/dist/agent-adapter/pi/pi-ext-types.js +2 -2
- package/dist/agent-adapter/pi/session-support.d.ts +96 -0
- package/dist/agent-adapter/pi/session-support.js +213 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +15 -0
- package/dist/agent-adapter/pi/spawn-args.js +46 -3
- package/dist/agent-adapter/pi/subagent.d.ts +68 -0
- package/dist/agent-adapter/pi/subagent.js +521 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +1 -13
- package/dist/agent-adapter/pi/tool-shims.js +182 -198
- package/dist/agent-adapter/pi/web-fetch.d.ts +13 -0
- package/dist/agent-adapter/pi/web-fetch.js +201 -0
- package/dist/agent-adapter/pi/web-search.d.ts +9 -0
- package/dist/agent-adapter/pi/web-search.js +513 -0
- package/dist/agent-adapter/types.d.ts +61 -10
- package/dist/agent-adapter/types.js +4 -4
- package/dist/core/atomic-write.d.ts +3 -5
- package/dist/core/atomic-write.js +26 -12
- package/dist/core/bg-held-sessions.d.ts +35 -0
- package/dist/core/bg-held-sessions.js +79 -0
- package/dist/core/calver.d.ts +1 -0
- package/dist/core/calver.js +29 -0
- package/dist/core/config-generator.d.ts +13 -2
- package/dist/core/config-generator.js +55 -5
- package/dist/core/debug-mode.d.ts +14 -0
- package/dist/core/debug-mode.js +32 -0
- package/dist/core/gateway-generator.js +15 -11
- package/dist/core/hook-bus.d.ts +23 -0
- package/dist/core/hook-bus.js +111 -0
- package/dist/core/hook-exec.d.ts +15 -0
- package/dist/core/hook-exec.js +90 -0
- package/dist/core/icons.d.ts +2 -0
- package/dist/core/icons.js +2 -0
- package/dist/core/locales/en.d.ts +30 -7
- package/dist/core/locales/en.js +4 -1
- package/dist/core/locales/slices/commands.d.ts +12 -2
- package/dist/core/locales/slices/commands.js +31 -7
- package/dist/core/locales/slices/init.d.ts +1 -1
- package/dist/core/locales/slices/init.js +2 -2
- package/dist/core/locales/slices/interactions.d.ts +6 -0
- package/dist/core/locales/slices/interactions.js +14 -0
- package/dist/core/locales/slices/status.d.ts +7 -3
- package/dist/core/locales/slices/status.js +16 -8
- package/dist/core/log.js +4 -3
- package/dist/core/paths.d.ts +9 -0
- package/dist/core/paths.js +20 -1
- package/dist/core/profile-generator.d.ts +2 -2
- package/dist/core/profile-generator.js +6 -9
- package/dist/core/running-executions.d.ts +10 -1
- package/dist/core/running-executions.js +10 -0
- package/dist/core/status-format.d.ts +14 -0
- package/dist/core/status-format.js +23 -1
- package/dist/core/task-node.d.ts +7 -0
- package/dist/core/task-node.js +29 -0
- package/dist/core/types/agent-types.d.ts +23 -2
- package/dist/core/types/agent-types.js +2 -2
- package/dist/core/types/thread-types.d.ts +90 -15
- package/dist/core/types/thread-types.js +3 -3
- package/dist/core/utils.d.ts +2 -2
- package/dist/core/utils.js +3 -3
- package/dist/domain/agents/config.d.ts +6 -5
- package/dist/domain/agents/config.js +17 -5
- package/dist/domain/agents/facade.d.ts +74 -10
- package/dist/domain/agents/facade.js +333 -62
- package/dist/domain/agents/index.d.ts +1 -0
- package/dist/domain/agents/index.js +1 -0
- package/dist/domain/agents/profile-manager.d.ts +14 -7
- package/dist/domain/agents/profile-manager.js +23 -7
- package/dist/domain/agents/profile-switch.d.ts +53 -0
- package/dist/domain/agents/profile-switch.js +79 -0
- package/dist/domain/costs/cost-tracker.d.ts +21 -1
- package/dist/domain/costs/cost-tracker.js +54 -26
- package/dist/domain/costs/gateway-manager.js +5 -3
- package/dist/domain/costs/rate-limit-throttle.d.ts +44 -19
- package/dist/domain/costs/rate-limit-throttle.js +331 -103
- package/dist/domain/costs/resume-registry.d.ts +17 -9
- package/dist/domain/costs/resume-registry.js +63 -8
- package/dist/domain/executions/log-tailer.d.ts +71 -0
- package/dist/domain/executions/log-tailer.js +195 -0
- package/dist/domain/executions/registry.d.ts +10 -1
- package/dist/domain/executions/registry.js +14 -0
- package/dist/domain/hooks/hook-view.d.ts +22 -0
- package/dist/domain/hooks/hook-view.js +38 -0
- package/dist/domain/mcp/core-server.d.ts +0 -1
- package/dist/domain/mcp/core-server.js +8 -40
- package/dist/domain/mcp/feishu/file.js +1 -11
- package/dist/domain/mcp/feishu/index.d.ts +0 -2
- package/dist/domain/mcp/feishu/index.js +5 -56
- package/dist/domain/mcp/feishu-server.d.ts +0 -1
- package/dist/domain/mcp/feishu-server.js +5 -6
- package/dist/domain/mcp/manager-qa-server.d.ts +1 -0
- package/dist/domain/mcp/manager-qa-server.js +23 -0
- package/dist/domain/mcp/server.d.ts +0 -1
- package/dist/domain/mcp/server.js +5 -31
- package/dist/domain/mcp/slack-server.d.ts +0 -1
- package/dist/domain/mcp/slack-server.js +3 -5
- package/dist/domain/mcp/tasks-server.d.ts +1 -0
- package/dist/domain/mcp/tasks-server.js +23 -0
- package/dist/domain/mcp/thread-server.d.ts +1 -0
- package/dist/domain/mcp/thread-server.js +25 -0
- package/dist/domain/mcp/tools/context.d.ts +3 -10
- package/dist/domain/mcp/tools/context.js +13 -29
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -1
- package/dist/domain/mcp/tools/manager-qa.js +49 -53
- package/dist/domain/mcp/tools/schedule.d.ts +1 -2
- package/dist/domain/mcp/tools/schedule.js +7 -10
- package/dist/domain/mcp/tools/slack.d.ts +0 -1
- package/dist/domain/mcp/tools/slack.js +2 -13
- package/dist/domain/mcp/tools/task-ops.js +10 -137
- package/dist/domain/mcp/tools/thread-ops.js +6 -11
- package/dist/domain/mcp/tools/tui-ask.d.ts +2 -0
- package/dist/domain/mcp/tools/tui-ask.js +8 -0
- package/dist/domain/mcp/tools/ui-file.d.ts +2 -0
- package/dist/domain/mcp/tools/ui-file.js +49 -0
- package/dist/domain/mcp/tui-server.d.ts +0 -1
- package/dist/domain/mcp/tui-server.js +39 -24
- package/dist/domain/mcp/web-server.d.ts +1 -0
- package/dist/domain/mcp/web-server.js +25 -0
- package/dist/domain/memory/cortex-md-injector.d.ts +4 -10
- package/dist/domain/memory/cortex-md-injector.js +113 -77
- package/dist/domain/memory/cortex-md-scanner.d.ts +1 -0
- package/dist/domain/memory/cortex-md-scanner.js +5 -2
- package/dist/domain/memory/skill-scanner.d.ts +3 -1
- package/dist/domain/memory/skill-scanner.js +8 -12
- package/dist/domain/memory/user-context.d.ts +6 -5
- package/dist/domain/memory/user-context.js +12 -7
- package/dist/domain/monitor/disk-monitor.js +2 -3
- package/dist/domain/projects/index.d.ts +1 -0
- package/dist/domain/projects/project-store.d.ts +18 -0
- package/dist/domain/projects/project-store.js +39 -3
- package/dist/domain/remote/client-hot-reload.d.ts +9 -2
- package/dist/domain/remote/client-hot-reload.js +81 -9
- package/dist/domain/remote/client-manager.d.ts +15 -1
- package/dist/domain/remote/client-manager.js +75 -11
- package/dist/domain/remote/cortex-client.js +6 -48
- package/dist/domain/scheduling/job-registry.d.ts +0 -2
- package/dist/domain/scheduling/job-registry.js +2 -6
- package/dist/domain/scheduling/jobs/_shared.d.ts +5 -1
- package/dist/domain/scheduling/jobs/_shared.js +2 -1
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +1 -0
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +78 -0
- package/dist/domain/scheduling/jobs/scheduled-task.js +1 -3
- package/dist/domain/scheduling/jobs/task-dispatch.js +40 -31
- package/dist/domain/scheduling/scheduler.d.ts +0 -10
- package/dist/domain/scheduling/scheduler.js +9 -9
- package/dist/domain/sessions/session-hooks.d.ts +38 -15
- package/dist/domain/sessions/session-hooks.js +128 -122
- package/dist/domain/sessions/session-lifecycle.d.ts +38 -1
- package/dist/domain/sessions/session-lifecycle.js +41 -4
- package/dist/domain/sessions/session-registry.d.ts +3 -1
- package/dist/domain/system/doctor.d.ts +63 -0
- package/dist/domain/system/doctor.js +359 -0
- package/dist/domain/system/server-update-check.d.ts +2 -1
- package/dist/domain/system/server-update-check.js +7 -26
- package/dist/domain/system/system-notice.d.ts +18 -0
- package/dist/domain/system/system-notice.js +34 -0
- package/dist/domain/tasks/acceptance-ledger.d.ts +31 -0
- package/dist/domain/tasks/acceptance-ledger.js +83 -0
- package/dist/domain/tasks/claim-recovery.d.ts +10 -0
- package/dist/domain/tasks/claim-recovery.js +64 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +19 -0
- package/dist/domain/tasks/dispatcher.js +1 -3
- package/dist/domain/tasks/mutator.d.ts +7 -1
- package/dist/domain/tasks/mutator.js +55 -3
- package/dist/domain/tasks/recommendation/extractor.js +3 -3
- package/dist/domain/tasks/system/cortex-run.js +0 -0
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +37 -7
- package/dist/domain/tasks/system/task-completion.js +148 -42
- package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -0
- package/dist/domain/tasks/system/task-state.d.ts +10 -1
- package/dist/domain/tasks/system/task-state.js +31 -1
- package/dist/domain/threads/artifact-io.d.ts +3 -15
- package/dist/domain/threads/artifact-io.js +13 -119
- package/dist/domain/threads/hook-runner.d.ts +7 -2
- package/dist/domain/threads/hook-runner.js +68 -85
- package/dist/domain/threads/index.js +6 -1
- package/dist/domain/threads/prompt-builder.d.ts +14 -4
- package/dist/domain/threads/prompt-builder.js +38 -20
- package/dist/domain/threads/runner.d.ts +19 -5
- package/dist/domain/threads/runner.js +238 -82
- package/dist/domain/threads/shell-templates.d.ts +9 -0
- package/dist/domain/threads/shell-templates.js +117 -0
- package/dist/domain/threads/state-machine.d.ts +35 -7
- package/dist/domain/threads/state-machine.js +170 -29
- package/dist/domain/threads/template-loader.d.ts +15 -7
- package/dist/domain/threads/template-loader.js +204 -87
- package/dist/domain/threads/thread-transcript.d.ts +47 -0
- package/dist/domain/threads/thread-transcript.js +64 -0
- package/dist/domain/threads/utils.d.ts +8 -1
- package/dist/domain/threads/utils.js +17 -1
- package/dist/domain/tui-session/tui-session-service.js +9 -16
- package/dist/domain/tui-session/types.d.ts +12 -0
- package/dist/domain/ui-service/app-router.d.ts +670 -0
- package/dist/domain/ui-service/app-router.js +195 -0
- package/dist/domain/ui-service/index.d.ts +1 -1
- package/dist/domain/ui-service/input-schemas.d.ts +644 -0
- package/dist/domain/ui-service/input-schemas.js +385 -0
- package/dist/domain/ui-service/mutate/approvals.d.ts +31 -0
- package/dist/domain/ui-service/mutate/approvals.js +140 -0
- package/dist/domain/ui-service/mutate/config.d.ts +16 -0
- package/dist/domain/ui-service/mutate/config.js +72 -0
- package/dist/domain/ui-service/mutate/hooks.d.ts +16 -0
- package/dist/domain/ui-service/mutate/hooks.js +138 -0
- package/dist/domain/ui-service/mutate/issues.d.ts +18 -0
- package/dist/domain/ui-service/mutate/issues.js +111 -0
- package/dist/domain/ui-service/mutate/notes.d.ts +6 -0
- package/dist/domain/ui-service/mutate/notes.js +36 -0
- package/dist/domain/ui-service/mutate/projects.d.ts +4 -0
- package/dist/domain/ui-service/mutate/projects.js +10 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
- package/dist/domain/ui-service/mutate/schedules.js +57 -3
- package/dist/domain/ui-service/mutate/sessions.d.ts +11 -0
- package/dist/domain/ui-service/mutate/sessions.js +198 -0
- package/dist/domain/ui-service/mutate/system.d.ts +2 -0
- package/dist/domain/ui-service/mutate/system.js +97 -0
- package/dist/domain/ui-service/query/approvals.d.ts +10 -0
- package/dist/domain/ui-service/query/approvals.js +109 -0
- package/dist/domain/ui-service/query/config.d.ts +8 -0
- package/dist/domain/ui-service/query/config.js +138 -0
- package/dist/domain/ui-service/query/executions.d.ts +2 -1
- package/dist/domain/ui-service/query/executions.js +47 -3
- package/dist/domain/ui-service/query/hooks.d.ts +7 -0
- package/dist/domain/ui-service/query/hooks.js +110 -0
- package/dist/domain/ui-service/query/issues.d.ts +14 -0
- package/dist/domain/ui-service/query/issues.js +85 -0
- package/dist/domain/ui-service/query/machines.d.ts +2 -0
- package/dist/domain/ui-service/query/machines.js +39 -0
- package/dist/domain/ui-service/query/memory.d.ts +5 -0
- package/dist/domain/ui-service/query/memory.js +199 -0
- package/dist/domain/ui-service/query/notes.d.ts +3 -0
- package/dist/domain/ui-service/query/notes.js +18 -0
- package/dist/domain/ui-service/query/schedules.js +1 -0
- package/dist/domain/ui-service/query/sessions.d.ts +3 -1
- package/dist/domain/ui-service/query/sessions.js +227 -15
- package/dist/domain/ui-service/query/skills.d.ts +2 -0
- package/dist/domain/ui-service/query/skills.js +14 -0
- package/dist/domain/ui-service/query/system.d.ts +3 -0
- package/dist/domain/ui-service/query/system.js +132 -0
- package/dist/domain/ui-service/query/task-verification.d.ts +2 -0
- package/dist/domain/ui-service/query/task-verification.js +60 -0
- package/dist/domain/ui-service/query/tasks.d.ts +1 -0
- package/dist/domain/ui-service/query/tasks.js +24 -16
- package/dist/domain/ui-service/query/thread-templates.d.ts +8 -0
- package/dist/domain/ui-service/query/thread-templates.js +54 -0
- package/dist/domain/ui-service/query/threads.d.ts +2 -1
- package/dist/domain/ui-service/query/threads.js +213 -4
- package/dist/domain/ui-service/subscribe.js +27 -1
- package/dist/domain/ui-service/trpc.d.ts +13 -0
- package/dist/domain/ui-service/trpc.js +12 -0
- package/dist/domain/ui-service/types.d.ts +1266 -4
- package/dist/domain/ui-service/types.js +4 -4
- package/dist/domain/ui-service/ui-service.d.ts +2 -1
- package/dist/domain/ui-service/ui-service.js +112 -10
- package/dist/entry/app.js +307 -36
- package/dist/entry/cli.js +10 -0
- package/dist/entry/daemon-notice.d.ts +17 -0
- package/dist/entry/daemon-notice.js +26 -0
- package/dist/entry/daemon.d.ts +23 -1
- package/dist/entry/daemon.js +126 -41
- package/dist/entry/doctor-cli.d.ts +12 -0
- package/dist/entry/doctor-cli.js +76 -0
- package/dist/entry/hook-cli.d.ts +18 -0
- package/dist/entry/hook-cli.js +468 -0
- package/dist/entry/init.js +22 -18
- package/dist/entry/start-ui-http.d.ts +44 -0
- package/dist/entry/start-ui-http.js +289 -0
- package/dist/entry/startup-notify.js +5 -9
- package/dist/entry/ui-http-gate.d.ts +11 -0
- package/dist/entry/ui-http-gate.js +29 -0
- package/dist/events/event-bus.d.ts +7 -2
- package/dist/events/event-bus.js +5 -2
- package/dist/events/event-logger.js +14 -0
- package/dist/events/event-types.d.ts +110 -0
- package/dist/events/event-types.js +3 -3
- package/dist/hooks/ask-user-question-hook.mjs +1 -0
- package/dist/hooks/cortex-hook-api.mjs +84 -0
- package/dist/hooks/cortex-md-injector.mjs +99 -49
- package/dist/hooks/exit-plan-mode-hook.mjs +1 -0
- package/dist/hooks/memory-ref-tracker.mjs +1 -0
- package/dist/hooks/new-session-hook.mjs +1 -0
- package/dist/hooks/post-task-hook.mjs +1 -0
- package/dist/hooks/rules-loader.mjs +1 -0
- package/dist/hooks/sensitive-file-edit.mjs +1 -0
- package/dist/hooks/session-activity-tracker.mjs +8 -100
- package/dist/hooks/task-status-check.mjs +10 -10
- package/dist/hooks/tasks-yaml-guard.mjs +1 -0
- package/dist/orchestration/agent-file-send.d.ts +54 -0
- package/dist/orchestration/agent-file-send.js +110 -0
- package/dist/orchestration/agent-runner.d.ts +49 -0
- package/dist/orchestration/agent-runner.js +368 -55
- package/dist/orchestration/bg-continuation.d.ts +51 -9
- package/dist/orchestration/bg-continuation.js +53 -15
- package/dist/orchestration/bg-wait-guard.d.ts +28 -0
- package/dist/orchestration/bg-wait-guard.js +73 -0
- package/dist/orchestration/conduit-queue.d.ts +2 -0
- package/dist/orchestration/conduit-queue.js +14 -1
- package/dist/orchestration/conversation-runner.d.ts +37 -5
- package/dist/orchestration/conversation-runner.js +71 -13
- package/dist/orchestration/delta-coalescer.d.ts +69 -0
- package/dist/orchestration/delta-coalescer.js +128 -0
- package/dist/orchestration/interactions/ask-user-question.d.ts +11 -3
- package/dist/orchestration/interactions/ask-user-question.js +27 -3
- package/dist/orchestration/interactions/interaction-handlers.js +11 -36
- package/dist/orchestration/interactions/interaction-records.d.ts +59 -0
- package/dist/orchestration/interactions/interaction-records.js +156 -0
- package/dist/orchestration/interactions/plan-approvals.d.ts +5 -0
- package/dist/orchestration/interactions/plan-approvals.js +8 -0
- package/dist/orchestration/interactions/plan-response.d.ts +8 -0
- package/dist/orchestration/interactions/plan-response.js +37 -0
- package/dist/orchestration/lifecycle.d.ts +10 -4
- package/dist/orchestration/lifecycle.js +155 -60
- package/dist/orchestration/manager-qa.d.ts +15 -4
- package/dist/orchestration/manager-qa.js +43 -37
- package/dist/orchestration/mid-turn-inject.d.ts +105 -0
- package/dist/orchestration/mid-turn-inject.js +298 -0
- package/dist/orchestration/pending-injection-recovery.d.ts +35 -0
- package/dist/orchestration/pending-injection-recovery.js +92 -0
- package/dist/orchestration/resume-dispatcher.d.ts +26 -4
- package/dist/orchestration/resume-dispatcher.js +89 -43
- package/dist/orchestration/routing/commands/cancel.d.ts +26 -0
- package/dist/orchestration/routing/commands/cancel.js +64 -18
- package/dist/orchestration/routing/commands/compact.d.ts +10 -0
- package/dist/orchestration/routing/commands/compact.js +26 -0
- package/dist/orchestration/routing/commands/index.d.ts +2 -0
- package/dist/orchestration/routing/commands/index.js +9 -0
- package/dist/orchestration/routing/commands/mode.js +24 -11
- package/dist/orchestration/routing/commands/restart.d.ts +22 -0
- package/dist/orchestration/routing/commands/restart.js +49 -0
- package/dist/orchestration/routing/commands/session.js +4 -0
- package/dist/orchestration/routing/commands/status.js +5 -0
- package/dist/orchestration/routing/edit-handler.js +1 -1
- package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +2 -1
- package/dist/orchestration/routing/hook-bridge-subscribers.js +45 -4
- package/dist/orchestration/routing/hook-bridge.d.ts +10 -3
- package/dist/orchestration/routing/hook-bridge.js +26 -14
- package/dist/orchestration/routing/webhook.js +110 -19
- package/dist/orchestration/session-compact.d.ts +58 -0
- package/dist/orchestration/session-compact.js +82 -0
- package/dist/orchestration/session-events.d.ts +111 -0
- package/dist/orchestration/session-events.js +113 -0
- package/dist/orchestration/session-rewind.d.ts +72 -0
- package/dist/orchestration/session-rewind.js +104 -0
- package/dist/orchestration/session-send.d.ts +19 -0
- package/dist/orchestration/session-send.js +39 -0
- package/dist/orchestration/status-helpers.d.ts +4 -0
- package/dist/orchestration/status-helpers.js +18 -0
- package/dist/orchestration/thread-callback.d.ts +75 -3
- package/dist/orchestration/thread-callback.js +329 -74
- package/dist/orchestration/thread-executor.d.ts +1 -0
- package/dist/orchestration/thread-executor.js +23 -31
- package/dist/orchestration/web-bg-hold.d.ts +52 -0
- package/dist/orchestration/web-bg-hold.js +105 -0
- package/dist/platform/adapter.d.ts +3 -0
- package/dist/platform/adapter.js +2 -2
- package/dist/platform/adapters/composite-adapter.d.ts +6 -1
- package/dist/platform/adapters/composite-adapter.js +64 -4
- package/dist/platform/adapters/feishu.d.ts +6 -1
- package/dist/platform/adapters/feishu.js +52 -12
- package/dist/platform/adapters/slack.d.ts +2 -1
- package/dist/platform/adapters/slack.js +41 -9
- package/dist/platform/adapters/tui/index.d.ts +1 -1
- package/dist/platform/adapters/tui/ports.d.ts +8 -7
- package/dist/platform/adapters/tui/tui-gateway.d.ts +7 -0
- package/dist/platform/adapters/tui/tui-gateway.js +48 -5
- package/dist/platform/adapters/tui/tui-transcript.js +17 -29
- package/dist/platform/index.d.ts +1 -1
- package/dist/platform/index.js +1 -1
- package/dist/platform/interactive-builder.d.ts +7 -0
- package/dist/platform/interactive-builder.js +22 -2
- package/dist/platform/testing.d.ts +5 -0
- package/dist/platform/testing.js +7 -2
- package/dist/platform/tui/protocol.d.ts +0 -2
- package/dist/platform/tui/protocol.js +4 -53
- package/dist/platform/types.d.ts +12 -0
- package/dist/platform/types.js +5 -0
- package/dist/platform/ui-http/access-jwt.d.ts +28 -0
- package/dist/platform/ui-http/access-jwt.js +67 -0
- package/dist/platform/ui-http/app-update.d.ts +58 -0
- package/dist/platform/ui-http/app-update.js +155 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +56 -0
- package/dist/platform/ui-http/ui-http-server.js +231 -0
- package/dist/platform/ui-http/ui-ota.d.ts +20 -0
- package/dist/platform/ui-http/ui-ota.js +128 -0
- package/dist/platform/ui-http/zip-writer.d.ts +13 -0
- package/dist/platform/ui-http/zip-writer.js +102 -0
- package/dist/platform/utils/reaction-diagnostics.d.ts +4 -0
- package/dist/platform/utils/reaction-diagnostics.js +23 -0
- package/dist/store/conversation-history-repo.d.ts +243 -0
- package/dist/store/conversation-history-repo.js +399 -0
- package/dist/store/execution-repo.d.ts +19 -1
- package/dist/store/execution-repo.js +18 -1
- package/dist/store/hook-registry.d.ts +83 -0
- package/dist/store/hook-registry.js +318 -0
- package/dist/store/hook-sync.d.ts +12 -16
- package/dist/store/hook-sync.js +169 -70
- package/dist/store/hook-writer.d.ts +49 -0
- package/dist/store/hook-writer.js +132 -0
- package/dist/store/outbound-queue.d.ts +8 -0
- package/dist/store/outbound-queue.js +24 -3
- package/dist/store/pending-injection-repo.d.ts +30 -0
- package/dist/store/pending-injection-repo.js +51 -0
- package/dist/store/plugin-sync.d.ts +21 -0
- package/dist/store/plugin-sync.js +119 -0
- package/dist/store/profile-repo.d.ts +2 -1
- package/dist/store/profile-repo.js +6 -11
- package/dist/store/project-notes-repo.d.ts +27 -0
- package/dist/store/project-notes-repo.js +214 -0
- package/dist/store/provider-state-repo.d.ts +18 -0
- package/dist/store/provider-state-repo.js +107 -0
- package/dist/store/schedule-repo.d.ts +0 -21
- package/dist/store/schedule-repo.js +4 -25
- package/dist/store/session-registry-repo.d.ts +47 -1
- package/dist/store/session-registry-repo.js +71 -3
- package/dist/store/version-migrations.d.ts +11 -0
- package/dist/store/version-migrations.js +286 -9
- package/dist/tui/App.js +219 -27
- package/dist/tui/components/Dashboard.d.ts +3 -1
- package/dist/tui/components/Dashboard.js +31 -12
- package/dist/tui/components/DashboardCostTab.js +17 -2
- package/dist/tui/components/DashboardExecutionsTab.js +21 -1
- package/dist/tui/components/DashboardSchedulesTab.js +8 -3
- package/dist/tui/components/DashboardTasksTab.js +11 -6
- package/dist/tui/components/DashboardThreadsTab.js +20 -2
- package/dist/tui/components/InputBox.d.ts +17 -1
- package/dist/tui/components/InputBox.js +263 -8
- package/dist/tui/components/Notifications.js +7 -2
- package/dist/tui/components/ProjectSwitcher.js +7 -2
- package/dist/tui/components/SessionPicker.js +10 -1
- package/dist/tui/components/SidePanel.d.ts +3 -1
- package/dist/tui/components/SidePanel.js +4 -2
- package/dist/tui/components/SlashMenu.d.ts +8 -0
- package/dist/tui/components/SlashMenu.js +14 -0
- package/dist/tui/components/StatusLine.d.ts +12 -3
- package/dist/tui/components/StatusLine.js +29 -10
- package/dist/tui/components/Transcript.d.ts +9 -0
- package/dist/tui/components/Transcript.js +131 -26
- package/dist/tui/components/dashboard-constants.d.ts +1 -0
- package/dist/tui/components/dashboard-constants.js +7 -0
- package/dist/tui/hooks/useKeybindings.d.ts +1 -0
- package/dist/tui/hooks/useKeybindings.js +9 -14
- package/dist/tui/hooks/useMouseHandler.d.ts +17 -0
- package/dist/tui/hooks/useMouseHandler.js +103 -0
- package/dist/tui/hooks/useTranscript.d.ts +7 -2
- package/dist/tui/hooks/useTranscript.js +76 -57
- package/dist/tui/index.js +106 -10
- package/dist/tui/logic.d.ts +146 -2
- package/dist/tui/logic.js +411 -6
- package/dist/tui/raf-batch.d.ts +33 -0
- package/dist/tui/raf-batch.js +103 -0
- package/dist/tui/render/inline-markdown.d.ts +22 -0
- package/dist/tui/render/inline-markdown.js +99 -0
- package/dist/tui/render/rich-blocks.js +10 -8
- package/dist/tui/render-output.d.ts +46 -0
- package/dist/tui/render-output.js +86 -0
- package/dist/tui/slash-commands.d.ts +21 -0
- package/dist/tui/slash-commands.js +73 -0
- package/dist/tui/turn-status.d.ts +10 -0
- package/dist/tui/turn-status.js +53 -0
- package/package.json +17 -7
- package/web/dist/apple-touch-icon.png +0 -0
- package/web/dist/assets/index-B19jLgji.js +138 -0
- package/web/dist/assets/index-BuFyPyRW.css +1 -0
- package/web/dist/assets/index-DCgngTJG.js +1 -0
- package/web/dist/assets/pdf-worker-DIEXcFxP.js +55 -0
- package/web/dist/assets/pdf.worker.min-DqNZU1-t.js +53 -0
- package/web/dist/favicon-32.png +0 -0
- package/web/dist/favicon.svg +7 -0
- package/web/dist/index.html +37 -0
- package/defaults/config/session-hooks.json +0 -7
- package/defaults/config/thread-templates.json +0 -594
- package/defaults/prompts/directives/milestone-executor.md +0 -119
- package/defaults/prompts/directives/milestone-reviewer.md +0 -108
- package/defaults/prompts/directives/plan-executor.md +0 -121
- package/defaults/prompts/directives/plan-reviewer.md +0 -99
- package/dist/agent-adapter/codex/adapter.d.ts +0 -42
- package/dist/agent-adapter/codex/adapter.js +0 -916
- package/dist/agent-adapter/codex/event-parser.d.ts +0 -17
- package/dist/agent-adapter/codex/event-parser.js +0 -41
- package/dist/agent-adapter/codex/spawn-args.d.ts +0 -6
- package/dist/agent-adapter/codex/spawn-args.js +0 -30
- package/dist/domain/costs/codex-event-format.d.ts +0 -4
- package/dist/domain/costs/codex-event-format.js +0 -66
- package/dist/domain/costs/codex-usage-monitor.d.ts +0 -6
- package/dist/domain/costs/codex-usage-monitor.js +0 -73
- package/dist/domain/costs/rate-limit-parser.d.ts +0 -11
- package/dist/domain/costs/rate-limit-parser.js +0 -87
- package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
- package/dist/domain/mcp/feishu/bitable.js +0 -168
- package/dist/domain/mcp/feishu/block-types.d.ts +0 -44
- package/dist/domain/mcp/feishu/block-types.js +0 -127
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
- package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
- package/dist/domain/mcp/feishu/docx.d.ts +0 -3
- package/dist/domain/mcp/feishu/docx.js +0 -163
- package/dist/domain/mcp/feishu/drive.d.ts +0 -23
- package/dist/domain/mcp/feishu/drive.js +0 -66
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
- package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
- package/dist/domain/mcp/feishu/sheets.js +0 -119
- package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
- package/dist/domain/mcp/feishu/wiki.js +0 -77
- package/dist/tui/components/Header.d.ts +0 -11
- package/dist/tui/components/Header.js +0 -5
- package/dist/tui/components/MessageRow.d.ts +0 -7
- package/dist/tui/components/MessageRow.js +0 -10
|
@@ -1,104 +1,63 @@
|
|
|
1
1
|
// input: AgentSpawnConfig, session keys, injectable spawner
|
|
2
|
-
// output: PIAdapter
|
|
3
|
-
// pos: PI CLI session pool
|
|
2
|
+
// output: PIAdapter runtime sessions, context stats, manual compact, steering
|
|
3
|
+
// pos: PI CLI session pool; private spawn/codec helpers stay module-internal
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
-
import { spawn as defaultSpawn
|
|
5
|
+
import { spawn as defaultSpawn } from 'child_process';
|
|
6
6
|
import { mkdirSync } from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
|
-
import { DATA_DIR
|
|
8
|
+
import { DATA_DIR } from '../../core/utils.js';
|
|
9
9
|
import { createLogger } from '../../core/log.js';
|
|
10
10
|
import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
|
|
11
|
-
import { buildSpawnArgs } from './spawn-args.js';
|
|
11
|
+
import { buildPiEnv, buildSpawnArgs } from './spawn-args.js';
|
|
12
12
|
import { createLineSplitter, encodeCommand } from './framing.js';
|
|
13
|
-
import { piRpcLineToNormalized, createPIEventParserState } from './event-parser.js';
|
|
14
|
-
import { PI_AGENT_DIR,
|
|
15
|
-
import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
|
|
16
|
-
import { buildPrompt } from '../normalize/prompt-builder.js';
|
|
13
|
+
import { piRpcLineToNormalized, createPIEventParserState, piContextUsageFromStats } from './event-parser.js';
|
|
14
|
+
import { PI_AGENT_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible } from './agent-dir.js';
|
|
17
15
|
import { fromCanonical } from '../normalize/tool-names.js';
|
|
16
|
+
import { discoverPIProviders, piSessionFileExists } from './discovery.js';
|
|
17
|
+
import { CLOSE_EXIT_WAIT_MS, DEFAULT_PI_BINARY, EventQueue, PI_IDLE_SESSION_TIMEOUT, PI_MAX_TIMEOUT, PI_TURN_IDLE_TIMEOUT, PIContextUsageProbe, PI_CONTEXT_USAGE_TIMEOUT_MS, PISteeringQueue, SWITCH_SESSION_TIMEOUT_MS, buildPromptText, isPIContextSampleBoundary, parseRpcObject, } from './session-support.js';
|
|
18
|
+
import { DEFAULT_SESSION_DIR, HOOK_BRIDGE_PATH, MCP_BRIDGE_PATH, TOOL_SHIMS_PATH } from './defaults.js';
|
|
18
19
|
const log = createLogger('pi-adapter');
|
|
19
|
-
function
|
|
20
|
-
return
|
|
20
|
+
function record(value) {
|
|
21
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
22
|
+
? value
|
|
23
|
+
: {};
|
|
21
24
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
* so the multi-provider models.json reflects whatever the user has currently authenticated to.
|
|
25
|
-
*
|
|
26
|
-
* PI writes the table to stderr — merge via 2>&1. Returns empty array on any failure (PI not
|
|
27
|
-
* installed, timeout, parse error); the caller logs a warning and proceeds without overriding
|
|
28
|
-
* models.json, which means the PI subprocess will fall back to direct upstream calls.
|
|
29
|
-
*
|
|
30
|
-
* Uses the user's real ~/.pi/agent/ for discovery (no PI_CODING_AGENT_DIR override) — symmetric
|
|
31
|
-
* with cortex init's gateway-generator.scanPIViaListModels(). ensureAuthVisible() then mirrors
|
|
32
|
-
* the auth file into PI_AGENT_DIR so the actual spawn can see those credentials.
|
|
33
|
-
*/
|
|
34
|
-
function discoverPIProviders() {
|
|
35
|
-
try {
|
|
36
|
-
const stdout = execSync('pi --list-models 2>&1', {
|
|
37
|
-
timeout: 10_000,
|
|
38
|
-
encoding: 'utf-8',
|
|
39
|
-
// Intentionally do NOT set PI_CODING_AGENT_DIR — read user's real PI config.
|
|
40
|
-
env: { ...process.env, PI_CODING_AGENT_DIR: '' },
|
|
41
|
-
});
|
|
42
|
-
const models = parsePiListModelsOutput(stdout);
|
|
43
|
-
const uniq = new Set();
|
|
44
|
-
for (const m of models)
|
|
45
|
-
uniq.add(m.provider);
|
|
46
|
-
return Array.from(uniq);
|
|
47
|
-
}
|
|
48
|
-
catch (err) {
|
|
49
|
-
log.info(`pi --list-models failed at spawn: ${err.message ?? 'unknown'}`);
|
|
50
|
-
return [];
|
|
51
|
-
}
|
|
25
|
+
function numberOrNull(value) {
|
|
26
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
52
27
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (buffered)
|
|
87
|
-
return Promise.resolve({ value: buffered, done: false });
|
|
88
|
-
if (this.closed)
|
|
89
|
-
return Promise.resolve({ value: undefined, done: true });
|
|
90
|
-
return new Promise((resolve) => {
|
|
91
|
-
this.waiters.push(resolve);
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
close() {
|
|
95
|
-
if (this.closed)
|
|
96
|
-
return;
|
|
97
|
-
this.closed = true;
|
|
98
|
-
for (const w of this.waiters.splice(0)) {
|
|
99
|
-
w({ value: undefined, done: true });
|
|
100
|
-
}
|
|
101
|
-
}
|
|
28
|
+
function compactUsage(data) {
|
|
29
|
+
const usage = record(data['usage']);
|
|
30
|
+
if (Object.keys(usage).length === 0)
|
|
31
|
+
return null;
|
|
32
|
+
return {
|
|
33
|
+
inputTokens: numberOrNull(usage['input']) ?? 0,
|
|
34
|
+
outputTokens: numberOrNull(usage['output']) ?? 0,
|
|
35
|
+
cacheReadTokens: numberOrNull(usage['cacheRead']) ?? 0,
|
|
36
|
+
cacheWriteTokens: numberOrNull(usage['cacheWrite']) ?? 0,
|
|
37
|
+
costUsd: numberOrNull(record(usage['cost'])['total']),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function compactBase(data) {
|
|
41
|
+
const value = record(data);
|
|
42
|
+
return {
|
|
43
|
+
status: 'compacted',
|
|
44
|
+
tokensBefore: numberOrNull(value['tokensBefore']),
|
|
45
|
+
estimatedTokensAfter: numberOrNull(value['estimatedTokensAfter']),
|
|
46
|
+
usage: compactUsage(value),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function rpcErrorMessage(raw) {
|
|
50
|
+
const error = raw['error'];
|
|
51
|
+
if (typeof error === 'string')
|
|
52
|
+
return error;
|
|
53
|
+
const nested = record(error)['message'];
|
|
54
|
+
if (typeof nested === 'string')
|
|
55
|
+
return nested;
|
|
56
|
+
const dataMessage = record(raw['data'])['message'];
|
|
57
|
+
return typeof dataMessage === 'string' ? dataMessage : 'PI compact failed';
|
|
58
|
+
}
|
|
59
|
+
function isNothingToCompact(message) {
|
|
60
|
+
return /no messages to compact/i.test(message);
|
|
102
61
|
}
|
|
103
62
|
class PISession {
|
|
104
63
|
sessionKey;
|
|
@@ -125,23 +84,48 @@ class PISession {
|
|
|
125
84
|
exitPromise;
|
|
126
85
|
/** Buffer for assistant_text deltas; flushed on message_end / turn_complete / non-text events. */
|
|
127
86
|
textBuffer = '';
|
|
87
|
+
/** blockId of the text currently in textBuffer; attached to the flushed assistant_text. */
|
|
88
|
+
textBlockId = null;
|
|
89
|
+
/**
|
|
90
|
+
* Streaming preview gate, resolved once at spawn time (CORTEX_STREAM_DELTAS=0 disables it).
|
|
91
|
+
* Only assistant_delta is suppressed — the buffered whole message is unaffected.
|
|
92
|
+
*/
|
|
93
|
+
streamDeltas;
|
|
128
94
|
idleTimer = null;
|
|
129
95
|
turnIdleTimer = null;
|
|
130
96
|
maxTimer = null;
|
|
131
97
|
pendingSwitch = null;
|
|
132
98
|
pendingSwitchTimer = null;
|
|
133
|
-
/** Accumulator for the current in-flight turn. Resolved/rejected by handleRawLine. */
|
|
99
|
+
/** Accumulator for the current in-flight Cortex turn. Resolved/rejected by handleRawLine. */
|
|
134
100
|
pendingTurn = null;
|
|
101
|
+
steering = new PISteeringQueue();
|
|
102
|
+
/**
|
|
103
|
+
* Where PI's own agent loop is, tracked off its event stream because the injection RPC form
|
|
104
|
+
* depends on it. `starting` = a prompt is written but PI has not entered the loop yet; PI still
|
|
105
|
+
* reads its internal run flag as inactive there and only the dedicated steer command is safe.
|
|
106
|
+
*/
|
|
107
|
+
loopState = 'idle';
|
|
108
|
+
contextUsageProbe;
|
|
109
|
+
readyWaiters = [];
|
|
110
|
+
pendingCompact = null;
|
|
111
|
+
compactSequence = 0;
|
|
135
112
|
constructor(opts) {
|
|
136
113
|
this.sessionKey = opts.sessionKey;
|
|
137
114
|
this.registry = opts.registry;
|
|
138
115
|
this.registrySessionDir = opts.registrySessionDir;
|
|
139
116
|
this.onClose = opts.onClose;
|
|
117
|
+
this.streamDeltas = process.env['CORTEX_STREAM_DELTAS'] !== '0';
|
|
140
118
|
this.proc = opts.spawner(DEFAULT_PI_BINARY, opts.cliArgs, {
|
|
141
119
|
cwd: opts.cwd,
|
|
142
120
|
env: opts.env,
|
|
143
121
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
144
122
|
});
|
|
123
|
+
this.contextUsageProbe = new PIContextUsageProbe((command) => {
|
|
124
|
+
const stdin = this.proc.stdin;
|
|
125
|
+
if (!stdin || stdin.destroyed || stdin.writableEnded)
|
|
126
|
+
throw new Error('PI stdin unavailable');
|
|
127
|
+
stdin.write(encodeCommand(command));
|
|
128
|
+
}, (event) => this.emitNormalizedEvent(event));
|
|
145
129
|
this.proc.stdout?.on('data', (chunk) => {
|
|
146
130
|
for (const line of this.splitter.push(chunk))
|
|
147
131
|
this.handleRawLine(line);
|
|
@@ -153,6 +137,9 @@ class PISession {
|
|
|
153
137
|
this.exitPromise = new Promise((resolve) => {
|
|
154
138
|
this.proc.once('close', (code) => {
|
|
155
139
|
this.alive = false;
|
|
140
|
+
const exitError = new Error(this.stderrTail || `pi exited with code ${code ?? 0}`);
|
|
141
|
+
this.settleReadyWaiters(exitError);
|
|
142
|
+
this.rejectCompact(exitError);
|
|
156
143
|
// Reject any pending switch_session promise on unexpected subprocess exit.
|
|
157
144
|
if (this.pendingSwitch !== null) {
|
|
158
145
|
const entry = this.pendingSwitch;
|
|
@@ -163,6 +150,10 @@ class PISession {
|
|
|
163
150
|
}
|
|
164
151
|
entry.reject(new Error('pi subprocess exited while switch_session was pending'));
|
|
165
152
|
}
|
|
153
|
+
// Seal every accepted steering message before rejecting the outer turn. This releases
|
|
154
|
+
// orchestration's pending UI row and busy bracket even when PI dies before consumption.
|
|
155
|
+
this.steering.abandon();
|
|
156
|
+
this.steering.clearSink();
|
|
166
157
|
// Reject any pending turn promise if the process exits without a turn_complete.
|
|
167
158
|
if (this.pendingTurn !== null) {
|
|
168
159
|
const t = this.pendingTurn;
|
|
@@ -181,6 +172,7 @@ class PISession {
|
|
|
181
172
|
fatal: true,
|
|
182
173
|
});
|
|
183
174
|
}
|
|
175
|
+
this.contextUsageProbe.close();
|
|
184
176
|
this.events.close();
|
|
185
177
|
// Remove stream listeners and destroy streams so stub PassThrough streams
|
|
186
178
|
// (used in tests) don't keep the event loop alive after close.
|
|
@@ -207,12 +199,18 @@ class PISession {
|
|
|
207
199
|
this.onClose?.(this.sessionKey);
|
|
208
200
|
}, PI_MAX_TIMEOUT);
|
|
209
201
|
}
|
|
210
|
-
/**
|
|
202
|
+
/**
|
|
203
|
+
* Flush buffered text as a single assistant_text event, tagged with the blockId its deltas
|
|
204
|
+
* carried so the UI can replace the streamed preview with this authoritative message.
|
|
205
|
+
*/
|
|
211
206
|
flushTextBuffer() {
|
|
212
207
|
if (this.textBuffer.length > 0) {
|
|
213
|
-
this.events.push(
|
|
208
|
+
this.events.push(this.textBlockId !== null
|
|
209
|
+
? { type: 'assistant_text', text: this.textBuffer, blockId: this.textBlockId }
|
|
210
|
+
: { type: 'assistant_text', text: this.textBuffer });
|
|
214
211
|
this.textBuffer = '';
|
|
215
212
|
}
|
|
213
|
+
this.textBlockId = null;
|
|
216
214
|
}
|
|
217
215
|
clearTimers() {
|
|
218
216
|
if (this.idleTimer) {
|
|
@@ -227,6 +225,7 @@ class PISession {
|
|
|
227
225
|
clearTimeout(this.maxTimer);
|
|
228
226
|
this.maxTimer = null;
|
|
229
227
|
}
|
|
228
|
+
this.contextUsageProbe.close();
|
|
230
229
|
this.flushTextBuffer();
|
|
231
230
|
}
|
|
232
231
|
resetIdleTimer() {
|
|
@@ -251,6 +250,117 @@ class PISession {
|
|
|
251
250
|
clearTimeout(this.turnIdleTimer);
|
|
252
251
|
this.startTurnIdleTimer();
|
|
253
252
|
}
|
|
253
|
+
waitForBootstrap() {
|
|
254
|
+
if (this.sessionId !== null)
|
|
255
|
+
return Promise.resolve();
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
const waiter = {};
|
|
258
|
+
waiter.resolve = resolve;
|
|
259
|
+
waiter.reject = reject;
|
|
260
|
+
waiter.timer = setTimeout(() => {
|
|
261
|
+
const index = this.readyWaiters.indexOf(waiter);
|
|
262
|
+
if (index !== -1)
|
|
263
|
+
this.readyWaiters.splice(index, 1);
|
|
264
|
+
reject(new Error('PI compact timed out waiting for bootstrap'));
|
|
265
|
+
}, SWITCH_SESSION_TIMEOUT_MS);
|
|
266
|
+
waiter.timer.unref?.();
|
|
267
|
+
this.readyWaiters.push(waiter);
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
settleReadyWaiters(error) {
|
|
271
|
+
for (const waiter of this.readyWaiters.splice(0)) {
|
|
272
|
+
clearTimeout(waiter.timer);
|
|
273
|
+
if (error)
|
|
274
|
+
waiter.reject(error);
|
|
275
|
+
else
|
|
276
|
+
waiter.resolve();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async compact() {
|
|
280
|
+
if (this.pendingCompact)
|
|
281
|
+
throw new Error('PI compact already in progress');
|
|
282
|
+
await this.waitForBootstrap();
|
|
283
|
+
const id = `compact-${++this.compactSequence}`;
|
|
284
|
+
return new Promise((resolve, reject) => {
|
|
285
|
+
const timer = setTimeout(() => this.rejectCompact(new Error('PI compact timed out')), PI_TURN_IDLE_TIMEOUT);
|
|
286
|
+
timer.unref?.();
|
|
287
|
+
this.pendingCompact = { id, statsId: null, base: null, resolve, reject, timer };
|
|
288
|
+
try {
|
|
289
|
+
this.proc.stdin?.write(encodeCommand({ id, type: 'compact' }));
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
this.rejectCompact(error instanceof Error ? error : new Error(String(error)));
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
handleCompactResponse(raw) {
|
|
297
|
+
const pending = this.pendingCompact;
|
|
298
|
+
if (!pending || raw?.['type'] !== 'response')
|
|
299
|
+
return false;
|
|
300
|
+
if (raw['command'] === 'compact' && raw['id'] === pending.id) {
|
|
301
|
+
this.handleCompactCommandResponse(raw);
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
if (raw['command'] === 'get_session_stats' && raw['id'] === pending.statsId) {
|
|
305
|
+
this.handleCompactStatsResponse(raw);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
handleCompactCommandResponse(raw) {
|
|
311
|
+
if (raw['success'] === true) {
|
|
312
|
+
this.requestCompactStats(compactBase(raw['data']));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const message = rpcErrorMessage(raw);
|
|
316
|
+
if (isNothingToCompact(message)) {
|
|
317
|
+
this.resolveCompact({
|
|
318
|
+
status: 'not-needed', tokensBefore: null, estimatedTokensAfter: null,
|
|
319
|
+
contextUsage: null, usage: null,
|
|
320
|
+
});
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
this.rejectCompact(new Error(message));
|
|
324
|
+
}
|
|
325
|
+
requestCompactStats(base) {
|
|
326
|
+
const pending = this.pendingCompact;
|
|
327
|
+
if (!pending)
|
|
328
|
+
return;
|
|
329
|
+
pending.base = base;
|
|
330
|
+
pending.statsId = `compact-stats-${++this.compactSequence}`;
|
|
331
|
+
clearTimeout(pending.timer);
|
|
332
|
+
pending.timer = setTimeout(() => this.resolveCompact({ ...base, contextUsage: null }), PI_CONTEXT_USAGE_TIMEOUT_MS);
|
|
333
|
+
pending.timer.unref?.();
|
|
334
|
+
try {
|
|
335
|
+
this.proc.stdin?.write(encodeCommand({ id: pending.statsId, type: 'get_session_stats' }));
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
this.resolveCompact({ ...base, contextUsage: null });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
handleCompactStatsResponse(raw) {
|
|
342
|
+
const base = this.pendingCompact?.base;
|
|
343
|
+
if (!base)
|
|
344
|
+
return;
|
|
345
|
+
const contextUsage = raw['success'] === true ? piContextUsageFromStats(raw['data']) : null;
|
|
346
|
+
this.resolveCompact({ ...base, contextUsage });
|
|
347
|
+
}
|
|
348
|
+
resolveCompact(result) {
|
|
349
|
+
const pending = this.pendingCompact;
|
|
350
|
+
if (!pending)
|
|
351
|
+
return;
|
|
352
|
+
clearTimeout(pending.timer);
|
|
353
|
+
this.pendingCompact = null;
|
|
354
|
+
pending.resolve(result);
|
|
355
|
+
}
|
|
356
|
+
rejectCompact(error) {
|
|
357
|
+
const pending = this.pendingCompact;
|
|
358
|
+
if (!pending)
|
|
359
|
+
return;
|
|
360
|
+
clearTimeout(pending.timer);
|
|
361
|
+
this.pendingCompact = null;
|
|
362
|
+
pending.reject(error);
|
|
363
|
+
}
|
|
254
364
|
get eventsIterable() {
|
|
255
365
|
return {
|
|
256
366
|
[Symbol.asyncIterator]: () => ({
|
|
@@ -263,124 +373,233 @@ class PISession {
|
|
|
263
373
|
return;
|
|
264
374
|
this.resetIdleTimer();
|
|
265
375
|
this.bumpTurnIdleTimer();
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
if (this.
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
obj = JSON.parse(line);
|
|
273
|
-
}
|
|
274
|
-
catch { /* fall through to event-parser */ }
|
|
275
|
-
if (obj && typeof obj === 'object') {
|
|
276
|
-
const r = obj;
|
|
277
|
-
if (r['type'] === 'response' &&
|
|
278
|
-
r['command'] === 'switch_session' &&
|
|
279
|
-
r['id'] === this.pendingSwitch.id) {
|
|
280
|
-
const entry = this.pendingSwitch;
|
|
281
|
-
this.pendingSwitch = null;
|
|
282
|
-
if (this.pendingSwitchTimer !== null) {
|
|
283
|
-
clearTimeout(this.pendingSwitchTimer);
|
|
284
|
-
this.pendingSwitchTimer = null;
|
|
285
|
-
}
|
|
286
|
-
const data = r['data'];
|
|
287
|
-
const cancelled = data && typeof data === 'object'
|
|
288
|
-
? Boolean(data['cancelled'])
|
|
289
|
-
: false;
|
|
290
|
-
entry.resolve({ ok: r['success'] === true, cancelled });
|
|
291
|
-
return;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
}
|
|
376
|
+
const raw = parseRpcObject(line);
|
|
377
|
+
if (this.handleCompactResponse(raw))
|
|
378
|
+
return;
|
|
379
|
+
if (this.handleSwitchResponse(raw))
|
|
380
|
+
return;
|
|
381
|
+
const finishDeferred = this.handleInjectionProtocol(raw);
|
|
295
382
|
for (const evt of piRpcLineToNormalized(line, this.parserState)) {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
383
|
+
this.captureSessionStarted(evt);
|
|
384
|
+
const output = this.processPendingTurnEvent(evt);
|
|
385
|
+
if (output !== null)
|
|
386
|
+
this.emitOrProbeContext(output);
|
|
387
|
+
}
|
|
388
|
+
if (finishDeferred) {
|
|
389
|
+
const terminal = this.finishDeferredTurn();
|
|
390
|
+
if (terminal !== null)
|
|
391
|
+
this.emitOrProbeContext(terminal);
|
|
392
|
+
}
|
|
393
|
+
this.contextUsageProbe.observe(raw);
|
|
394
|
+
if (this.pendingTurn && isPIContextSampleBoundary(raw))
|
|
395
|
+
this.contextUsageProbe.requestSnapshot();
|
|
396
|
+
}
|
|
397
|
+
emitOrProbeContext(event) {
|
|
398
|
+
if (event.type === 'turn_complete')
|
|
399
|
+
this.contextUsageProbe.deferTerminal(event);
|
|
400
|
+
else
|
|
401
|
+
this.emitNormalizedEvent(event);
|
|
402
|
+
}
|
|
403
|
+
/** Correlate switch_session before the generic parser drops its response. */
|
|
404
|
+
handleSwitchResponse(raw) {
|
|
405
|
+
const pending = this.pendingSwitch;
|
|
406
|
+
if (pending === null || raw?.['type'] !== 'response' ||
|
|
407
|
+
raw['command'] !== 'switch_session' || raw['id'] !== pending.id)
|
|
408
|
+
return false;
|
|
409
|
+
this.pendingSwitch = null;
|
|
410
|
+
if (this.pendingSwitchTimer !== null) {
|
|
411
|
+
clearTimeout(this.pendingSwitchTimer);
|
|
412
|
+
this.pendingSwitchTimer = null;
|
|
413
|
+
}
|
|
414
|
+
const data = raw['data'];
|
|
415
|
+
const cancelled = data && typeof data === 'object'
|
|
416
|
+
? Boolean(data['cancelled'])
|
|
417
|
+
: false;
|
|
418
|
+
pending.resolve({ ok: raw['success'] === true, cancelled });
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
/** Observe PI-only delivery/rejection events that intentionally stay out of NormalizedEvent. */
|
|
422
|
+
handleInjectionProtocol(raw) {
|
|
423
|
+
// agent_start is emitted from inside the loop, so it is the first point at which PI's own run
|
|
424
|
+
// flag is provably set; agent_settled is the point at which it is provably clear again.
|
|
425
|
+
if (raw?.['type'] === 'agent_start')
|
|
426
|
+
this.loopState = 'running';
|
|
427
|
+
else if (raw?.['type'] === 'agent_settled')
|
|
428
|
+
this.loopState = 'idle';
|
|
429
|
+
if (raw?.['type'] === 'message_start' && this.isUserStart(raw['message'])) {
|
|
430
|
+
const turn = this.pendingTurn;
|
|
431
|
+
if (turn && !turn.openingUserSeen)
|
|
432
|
+
turn.openingUserSeen = true;
|
|
433
|
+
else if (turn)
|
|
434
|
+
this.steering.consumeNext();
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
if (!raw || !this.steering.rejectFromResponse(raw))
|
|
438
|
+
return false;
|
|
439
|
+
return !this.steering.hasPending && this.pendingTurn?.deferredCompletion === true;
|
|
440
|
+
}
|
|
441
|
+
isUserStart(message) {
|
|
442
|
+
return !!message && typeof message === 'object' &&
|
|
443
|
+
message['role'] === 'user';
|
|
444
|
+
}
|
|
445
|
+
captureSessionStarted(evt) {
|
|
446
|
+
if (evt.type !== 'session_started' || this.sessionId !== null)
|
|
447
|
+
return;
|
|
448
|
+
this.sessionId = evt.sessionId;
|
|
449
|
+
this.currentSessionId = evt.sessionId;
|
|
450
|
+
this.settleReadyWaiters();
|
|
451
|
+
if (evt.sessionFile) {
|
|
452
|
+
this.sessionFile = evt.sessionFile;
|
|
453
|
+
this.registry.set(evt.sessionId, evt.sessionFile);
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
this.registry.set(evt.sessionId, path.join(this.registrySessionDir, `${evt.sessionId}.jsonl`));
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** Update the outer send() promise and optionally replace/suppress a terminal event. */
|
|
460
|
+
processPendingTurnEvent(evt) {
|
|
461
|
+
const turn = this.pendingTurn;
|
|
462
|
+
if (!turn)
|
|
463
|
+
return evt;
|
|
464
|
+
if (evt.type === 'plan_written')
|
|
465
|
+
turn.planFilePath = evt.path;
|
|
466
|
+
// ask_user_question is handled live by the facade; accumulating it would post it twice.
|
|
467
|
+
else if (evt.type === 'ask_user_question') { /* intentionally not accumulated */ }
|
|
468
|
+
else if (evt.type === 'turn_complete')
|
|
469
|
+
return this.handleTurnComplete(evt);
|
|
470
|
+
else if (evt.type === 'error' && evt.fatal) {
|
|
471
|
+
this.flushTextBuffer();
|
|
472
|
+
this.clearTurnIdleTimer();
|
|
473
|
+
this.steering.abandon();
|
|
474
|
+
this.pendingTurn = null;
|
|
475
|
+
turn.reject(new Error(evt.message));
|
|
476
|
+
}
|
|
477
|
+
return evt;
|
|
478
|
+
}
|
|
479
|
+
handleTurnComplete(evt) {
|
|
480
|
+
const turn = this.pendingTurn;
|
|
481
|
+
this.flushTextBuffer();
|
|
482
|
+
turn.numTurns += evt.numTurns;
|
|
483
|
+
if (evt.totalCostUsd !== null)
|
|
484
|
+
turn.totalCostUsd = (turn.totalCostUsd ?? 0) + evt.totalCostUsd;
|
|
485
|
+
if (evt.error) {
|
|
486
|
+
this.steering.abandon();
|
|
487
|
+
return this.settlePendingTurn(evt.error);
|
|
488
|
+
}
|
|
489
|
+
if (this.steering.hasPending) {
|
|
490
|
+
turn.deferredCompletion = true;
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
return this.settlePendingTurn();
|
|
494
|
+
}
|
|
495
|
+
finishDeferredTurn() {
|
|
496
|
+
if (!this.pendingTurn?.deferredCompletion || this.steering.hasPending)
|
|
497
|
+
return null;
|
|
498
|
+
return this.settlePendingTurn();
|
|
499
|
+
}
|
|
500
|
+
settlePendingTurn(error) {
|
|
501
|
+
const turn = this.pendingTurn;
|
|
502
|
+
this.pendingTurn = null;
|
|
503
|
+
this.clearTurnIdleTimer();
|
|
504
|
+
const terminal = error
|
|
505
|
+
? { type: 'turn_complete', numTurns: turn.numTurns, totalCostUsd: turn.totalCostUsd, error }
|
|
506
|
+
: { type: 'turn_complete', numTurns: turn.numTurns, totalCostUsd: turn.totalCostUsd };
|
|
507
|
+
if (error)
|
|
508
|
+
turn.reject(new Error(error));
|
|
509
|
+
else
|
|
510
|
+
turn.resolve(this.buildAgentResult(turn));
|
|
511
|
+
return terminal;
|
|
512
|
+
}
|
|
513
|
+
buildAgentResult(turn) {
|
|
514
|
+
return {
|
|
515
|
+
sessionId: this.sessionId,
|
|
516
|
+
total_cost_usd: turn.totalCostUsd,
|
|
517
|
+
num_turns: turn.numTurns,
|
|
518
|
+
rateLimited: false,
|
|
519
|
+
rateLimitMessage: null,
|
|
520
|
+
planFilePath: turn.planFilePath,
|
|
521
|
+
enteredPlanMode: false,
|
|
522
|
+
exitedPlanMode: turn.planFilePath !== null,
|
|
523
|
+
askUserQuestions: turn.askUserQuestions.length > 0 ? turn.askUserQuestions : undefined,
|
|
524
|
+
finalOutput: null,
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
clearTurnIdleTimer() {
|
|
528
|
+
if (!this.turnIdleTimer)
|
|
529
|
+
return;
|
|
530
|
+
clearTimeout(this.turnIdleTimer);
|
|
531
|
+
this.turnIdleTimer = null;
|
|
532
|
+
}
|
|
533
|
+
/** Buffer deltas into whole assistant messages while preserving Web preview events. */
|
|
534
|
+
emitNormalizedEvent(evt) {
|
|
535
|
+
if (evt.type === 'context_usage') {
|
|
536
|
+
this.events.push(evt);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (evt.type !== 'assistant_text') {
|
|
540
|
+
this.flushTextBuffer();
|
|
541
|
+
this.events.push(evt);
|
|
542
|
+
return;
|
|
378
543
|
}
|
|
544
|
+
const blockId = evt.blockId ?? null;
|
|
545
|
+
if (this.textBuffer.length > 0 && blockId !== this.textBlockId)
|
|
546
|
+
this.flushTextBuffer();
|
|
547
|
+
this.textBlockId = blockId;
|
|
548
|
+
if (this.streamDeltas && blockId !== null) {
|
|
549
|
+
this.events.push({ type: 'assistant_delta', text: evt.text, blockId });
|
|
550
|
+
}
|
|
551
|
+
this.textBuffer += evt.text;
|
|
379
552
|
}
|
|
380
553
|
send(msg) {
|
|
381
554
|
if (!this.alive)
|
|
382
555
|
throw new Error('PISession.send: subprocess is not alive');
|
|
383
|
-
this.
|
|
556
|
+
this.writeOpeningPrompt(buildPromptText(msg));
|
|
557
|
+
}
|
|
558
|
+
writeOpeningPrompt(promptText) {
|
|
559
|
+
const stdin = this.proc.stdin;
|
|
560
|
+
if (!stdin)
|
|
561
|
+
throw new Error('PISession: subprocess stdin is unavailable');
|
|
562
|
+
stdin.write(encodeCommand({ type: 'prompt', message: promptText }));
|
|
563
|
+
this.loopState = 'starting';
|
|
564
|
+
if (this.pendingTurn)
|
|
565
|
+
this.pendingTurn.promptDispatched = true;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Queue a message at PI's next agent-loop boundary without opening a new Cortex run.
|
|
569
|
+
*
|
|
570
|
+
* The RPC form has to follow PI's loop state. A `prompt` with streamingBehavior=steer is only
|
|
571
|
+
* queued when PI already considers itself streaming; written during the prompt preflight window
|
|
572
|
+
* (which includes our own before_agent_start hook scripts, seconds long) PI instead takes its
|
|
573
|
+
* plain-prompt path, acks success, then throws internally and drops the message — and that failed
|
|
574
|
+
* path clears PI's run flag, so every later injection in the same turn takes the same broken
|
|
575
|
+
* branch. The dedicated `steer` command bypasses that check entirely and is drained by the
|
|
576
|
+
* opening steering poll of the loop that is about to start. Once the loop is running, or once PI
|
|
577
|
+
* has settled and the message must reopen a turn, prompt+steer is the correct form.
|
|
578
|
+
*/
|
|
579
|
+
injectUserMessage(msg) {
|
|
580
|
+
const stdin = this.proc.stdin;
|
|
581
|
+
if (!this.alive || !this.pendingTurn?.promptDispatched || !stdin ||
|
|
582
|
+
stdin.destroyed || stdin.writableEnded)
|
|
583
|
+
return false;
|
|
584
|
+
const entry = this.steering.begin(msg.text);
|
|
585
|
+
const message = buildPromptText(msg);
|
|
586
|
+
const preflight = this.loopState === 'starting';
|
|
587
|
+
try {
|
|
588
|
+
stdin.write(encodeCommand(preflight
|
|
589
|
+
? { id: entry.id, type: 'steer', message }
|
|
590
|
+
: { id: entry.id, type: 'prompt', message, streamingBehavior: 'steer' }));
|
|
591
|
+
// A prompt written to an idle PI opens a fresh run, so the next injection is a preflight one.
|
|
592
|
+
if (this.loopState === 'idle')
|
|
593
|
+
this.loopState = 'starting';
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
this.steering.rollback(entry);
|
|
598
|
+
return false;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
setInjectionAckSink(sink) {
|
|
602
|
+
this.steering.setSink(sink);
|
|
384
603
|
}
|
|
385
604
|
/**
|
|
386
605
|
* Send switch_session RPC and await ack from pi.
|
|
@@ -420,7 +639,7 @@ class PISession {
|
|
|
420
639
|
if (this.currentSessionId !== targetSessionId) {
|
|
421
640
|
if (targetPath === null) {
|
|
422
641
|
// Can't switch without a path; write prompt to current session as fallback.
|
|
423
|
-
this.
|
|
642
|
+
this.writeOpeningPrompt(promptText);
|
|
424
643
|
return { switched: false, cancelled: false };
|
|
425
644
|
}
|
|
426
645
|
const result = await this.sendSwitchSession(targetPath);
|
|
@@ -430,11 +649,11 @@ class PISession {
|
|
|
430
649
|
// BLOCKER-1 fix: write prompt in every branch regardless of result.ok.
|
|
431
650
|
// NTH-A: if result.ok===false (pi rejected switch), the prompt goes to the current
|
|
432
651
|
// (un-switched) session — intentional best-effort, caller can inspect result.ok.
|
|
433
|
-
this.
|
|
652
|
+
this.writeOpeningPrompt(promptText);
|
|
434
653
|
return { switched: result.ok, cancelled: result.cancelled };
|
|
435
654
|
}
|
|
436
655
|
// Same session: write prompt directly.
|
|
437
|
-
this.
|
|
656
|
+
this.writeOpeningPrompt(promptText);
|
|
438
657
|
return { switched: false, cancelled: false };
|
|
439
658
|
}
|
|
440
659
|
/**
|
|
@@ -462,9 +681,11 @@ class PISession {
|
|
|
462
681
|
reject,
|
|
463
682
|
planFilePath: null,
|
|
464
683
|
askUserQuestions: [],
|
|
465
|
-
|
|
466
|
-
numTurns: null,
|
|
684
|
+
numTurns: 0,
|
|
467
685
|
totalCostUsd: null,
|
|
686
|
+
promptDispatched: false,
|
|
687
|
+
openingUserSeen: false,
|
|
688
|
+
deferredCompletion: false,
|
|
468
689
|
};
|
|
469
690
|
this.startTurnIdleTimer();
|
|
470
691
|
}
|
|
@@ -473,6 +694,7 @@ class PISession {
|
|
|
473
694
|
if (this.pendingTurn !== null) {
|
|
474
695
|
const t = this.pendingTurn;
|
|
475
696
|
this.pendingTurn = null;
|
|
697
|
+
this.steering.abandon();
|
|
476
698
|
t.reject(err);
|
|
477
699
|
}
|
|
478
700
|
}
|
|
@@ -524,7 +746,21 @@ export class PIAdapter {
|
|
|
524
746
|
// The sessionPathRegistry is populated below from the bootstrap session_started
|
|
525
747
|
// event for switchSession / sendTurn path lookups — it is NOT used for the
|
|
526
748
|
// --session CLI flag here.
|
|
527
|
-
|
|
749
|
+
//
|
|
750
|
+
// Guard (mirrors Claude's resolveResumeForPrint): PI's `--session <id>` can only RESUME an
|
|
751
|
+
// existing session — unlike Claude it cannot create/force a session under an externally-supplied
|
|
752
|
+
// id. If the requested id has no matching session (a fresh session, or a stale backendSessionId
|
|
753
|
+
// whose file was pruned), passing --session makes PI exit with "No session found matching <id>".
|
|
754
|
+
// So only resume when the session is known: either bootstrapped in THIS adapter instance (path
|
|
755
|
+
// registry) or present on disk (a prior process / persisted backendSessionId). Otherwise start
|
|
756
|
+
// fresh and let PI bootstrap its own id (captured back as backendSessionId by the caller).
|
|
757
|
+
const wantResume = !!(config.resume && config.sessionId);
|
|
758
|
+
const sessionKnown = wantResume &&
|
|
759
|
+
(this.sessionPathRegistry.has(config.sessionId) || piSessionFileExists(sessionDir, config.sessionId));
|
|
760
|
+
const sessionIdForSpawn = sessionKnown ? config.sessionId : null;
|
|
761
|
+
if (wantResume && sessionIdForSpawn === null) {
|
|
762
|
+
log.info(`PI resume target '${config.sessionId}' not found (no live session or file in ${sessionDir}); starting fresh`);
|
|
763
|
+
}
|
|
528
764
|
const cliArgs = buildSpawnArgs({
|
|
529
765
|
sessionDir,
|
|
530
766
|
sessionId: sessionIdForSpawn,
|
|
@@ -535,6 +771,7 @@ export class PIAdapter {
|
|
|
535
771
|
pluginDirs: config.pluginDirs ?? null,
|
|
536
772
|
// All three extensions always injected: MCP bridge (task 5754) + tool shims (task 5b5c) + hook bridge (task d3ae).
|
|
537
773
|
extensionPaths: [MCP_BRIDGE_PATH, TOOL_SHIMS_PATH, HOOK_BRIDGE_PATH],
|
|
774
|
+
thinking: config.thinking ?? null,
|
|
538
775
|
extraOption: config.extraOption ?? null,
|
|
539
776
|
});
|
|
540
777
|
// Pre-spawn config sync (sole writers of PI_AGENT_DIR — no other code path touches these files):
|
|
@@ -568,11 +805,6 @@ export class PIAdapter {
|
|
|
568
805
|
log.warn(`Failed to write PI models.json: ${err.message}`);
|
|
569
806
|
}
|
|
570
807
|
}
|
|
571
|
-
const env = { ...process.env, ...(config.env ?? {}), PI_CODING_AGENT_DIR: PI_AGENT_DIR };
|
|
572
|
-
if (config.channel) {
|
|
573
|
-
env.SLACK_CHANNEL = config.channel;
|
|
574
|
-
env.FEISHU_CHANNEL = config.channel;
|
|
575
|
-
}
|
|
576
808
|
// Forward the agent's tool allowlist (Claude-native names) so tool-shims.ts can gate which
|
|
577
809
|
// pseudo-tools it registers — mirroring the Claude backend's `--tools` allowlist. Without this,
|
|
578
810
|
// thread-dispatched agents (whose config excludes AskUserQuestion/EnterPlanMode/ExitPlanMode)
|
|
@@ -581,8 +813,16 @@ export class PIAdapter {
|
|
|
581
813
|
?? (config.tools && config.tools.length > 0
|
|
582
814
|
? config.tools.map((t) => fromCanonical('claude', t)).filter((n) => !!n).join(',')
|
|
583
815
|
: undefined);
|
|
584
|
-
|
|
585
|
-
|
|
816
|
+
const env = buildPiEnv({
|
|
817
|
+
sessionId: config.sessionId,
|
|
818
|
+
channel: config.channel,
|
|
819
|
+
callbackSource: config.callbackSource,
|
|
820
|
+
scheduleTaskId: config.scheduleTaskId,
|
|
821
|
+
extraEnv: config.env,
|
|
822
|
+
context: config.cortexContext,
|
|
823
|
+
piAgentDir: PI_AGENT_DIR,
|
|
824
|
+
allowedTools,
|
|
825
|
+
});
|
|
586
826
|
const cwd = config.cwd ?? DATA_DIR;
|
|
587
827
|
const session = new PISession({
|
|
588
828
|
sessionKey: config.sessionKey,
|
|
@@ -628,9 +868,12 @@ export class PIAdapter {
|
|
|
628
868
|
}
|
|
629
869
|
});
|
|
630
870
|
},
|
|
871
|
+
compact: () => session.compact(),
|
|
631
872
|
sendExtensionUiResponse: (id, payload) => {
|
|
632
873
|
session.sendExtensionUiResponse(id, payload);
|
|
633
874
|
},
|
|
875
|
+
injectUserMessage: (msg) => session.injectUserMessage(msg),
|
|
876
|
+
setInjectionAckSink: (sink) => session.setInjectionAckSink(sink),
|
|
634
877
|
events: session.eventsIterable,
|
|
635
878
|
close: async () => {
|
|
636
879
|
await session.close();
|
|
@@ -689,14 +932,3 @@ export class PIAdapter {
|
|
|
689
932
|
return Array.from(this.sessions.keys());
|
|
690
933
|
}
|
|
691
934
|
}
|
|
692
|
-
export const _test = {
|
|
693
|
-
buildSpawnArgs,
|
|
694
|
-
encodeCommand,
|
|
695
|
-
createLineSplitter,
|
|
696
|
-
DEFAULT_SESSION_DIR,
|
|
697
|
-
MCP_BRIDGE_PATH,
|
|
698
|
-
TOOL_SHIMS_PATH,
|
|
699
|
-
HOOK_BRIDGE_PATH,
|
|
700
|
-
CLOSE_EXIT_WAIT_MS,
|
|
701
|
-
SWITCH_SESSION_TIMEOUT_MS,
|
|
702
|
-
};
|