@cortex-agent/server 2026.7.30 → 2026.8.3
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 +1 -1
- package/defaults/CORTEX.md +1 -0
- package/defaults/config/CORTEX.md +2 -1
- package/defaults/config/hooks/13-status-md-guard.json +11 -0
- package/defaults/config/hooks/CORTEX.md +1 -0
- package/defaults/config/mcp-config-empty.json +3 -0
- package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
- package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
- package/defaults/config/thread-templates/agents/coder.json +4 -14
- package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
- package/defaults/config/thread-templates/templates/coder-review.json +3 -27
- package/defaults/context/projects/CORTEX.md +1 -1
- package/defaults/data/schedules.json +12 -0
- package/defaults/hooks/CORTEX.md +1 -0
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +193 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
- package/defaults/prompts/directives/coder-reviewer.md +24 -20
- package/defaults/prompts/directives/coder.md +4 -5
- package/defaults/prompts/directives/director.md +4 -10
- package/defaults/prompts/directives/manager.md +9 -10
- package/defaults/prompts/systemPrompts/worker.md +2 -2
- package/defaults/rules/cortex-md.md +31 -0
- package/defaults/rules/experiment-format.md +8 -1
- package/defaults/rules/issues-md.md +10 -9
- package/defaults/rules/meta-conventions.md +5 -4
- package/defaults/rules/mission-md.md +2 -1
- package/defaults/rules/status-md.md +39 -21
- package/dist/agent-adapter/bg-wait.d.ts +10 -12
- package/dist/agent-adapter/bg-wait.js +209 -129
- package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
- package/dist/agent-adapter/claude/adapter-tui.js +8 -5
- package/dist/agent-adapter/claude/adapter.d.ts +43 -14
- package/dist/agent-adapter/claude/adapter.js +276 -161
- package/dist/agent-adapter/claude/defaults.d.ts +2 -0
- package/dist/agent-adapter/claude/defaults.js +5 -5
- package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
- package/dist/agent-adapter/claude/event-parser.js +28 -31
- package/dist/agent-adapter/claude/hooks-builder.js +4 -3
- package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
- package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
- package/dist/agent-adapter/claude/spawn-args.js +44 -38
- package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
- package/dist/agent-adapter/claude/tmux-control.js +39 -32
- package/dist/agent-adapter/event-tee.d.ts +19 -0
- package/dist/agent-adapter/event-tee.js +145 -0
- package/dist/agent-adapter/index.d.ts +1 -0
- package/dist/agent-adapter/index.js +7 -3
- package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
- package/dist/agent-adapter/normalize/event-types.js +4 -4
- package/dist/agent-adapter/pi/adapter.d.ts +16 -4
- package/dist/agent-adapter/pi/adapter.js +69 -36
- package/dist/agent-adapter/pi/discovery.d.ts +19 -3
- package/dist/agent-adapter/pi/discovery.js +81 -43
- package/dist/agent-adapter/pi/event-parser.js +4 -2
- package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
- package/dist/agent-adapter/pi/spawn-args.js +6 -5
- package/dist/agent-adapter/types.d.ts +43 -2
- package/dist/agent-adapter/types.js +8 -4
- package/dist/core/atomic-write.d.ts +6 -1
- package/dist/core/atomic-write.js +183 -7
- package/dist/core/cli-utils.d.ts +15 -2
- package/dist/core/cli-utils.js +46 -41
- package/dist/core/config-generator.d.ts +4 -0
- package/dist/core/config-generator.js +34 -21
- package/dist/core/json-repository.d.ts +4 -0
- package/dist/core/json-repository.js +6 -3
- package/dist/core/locales/en.d.ts +94 -0
- package/dist/core/locales/slices/commands.d.ts +76 -0
- package/dist/core/locales/slices/commands.js +155 -1
- package/dist/core/locales/slices/status.d.ts +18 -0
- package/dist/core/locales/slices/status.js +43 -2
- package/dist/core/log.d.ts +5 -0
- package/dist/core/log.js +25 -23
- package/dist/core/pi-session-filename.d.ts +2 -0
- package/dist/core/pi-session-filename.js +18 -0
- package/dist/core/resume-reminder.d.ts +5 -0
- package/dist/core/resume-reminder.js +18 -0
- package/dist/core/runtime-env.d.ts +1 -0
- package/dist/core/runtime-env.js +15 -0
- package/dist/core/settings-migration.d.ts +5 -0
- package/dist/core/settings-migration.js +128 -0
- package/dist/core/settings-spec.d.ts +174 -0
- package/dist/core/settings-spec.js +150 -0
- package/dist/core/settings.d.ts +10 -0
- package/dist/core/settings.js +235 -0
- package/dist/core/task-parser.d.ts +11 -1
- package/dist/core/task-parser.js +34 -3
- package/dist/core/types/agent-types.d.ts +19 -0
- package/dist/core/types/agent-types.js +1 -1
- package/dist/core/types/thread-types.d.ts +48 -3
- package/dist/core/types/thread-types.js +2 -2
- package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
- package/dist/domain/agent-run/access-probe-cli.js +139 -0
- package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
- package/dist/domain/agent-run/access-probe-policy.js +614 -0
- package/dist/domain/agent-run/access-probe.d.ts +21 -0
- package/dist/domain/agent-run/access-probe.js +194 -0
- package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
- package/dist/domain/agent-run/agent-run-cli.js +171 -0
- package/dist/domain/agent-run/atif.d.ts +54 -0
- package/dist/domain/agent-run/atif.js +211 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
- package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
- package/dist/domain/agent-run/identity.d.ts +62 -0
- package/dist/domain/agent-run/identity.js +118 -0
- package/dist/domain/agent-run/journal.d.ts +51 -0
- package/dist/domain/agent-run/journal.js +259 -0
- package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
- package/dist/domain/agent-run/manifest-contract.js +134 -0
- package/dist/domain/agent-run/manifest.d.ts +51 -0
- package/dist/domain/agent-run/manifest.js +801 -0
- package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
- package/dist/domain/agent-run/pinned-node-process.js +206 -0
- package/dist/domain/agent-run/role-surface.d.ts +4 -0
- package/dist/domain/agent-run/role-surface.js +99 -0
- package/dist/domain/agent-run/run-config.d.ts +22 -0
- package/dist/domain/agent-run/run-config.js +135 -0
- package/dist/domain/agent-run/runner.d.ts +7 -0
- package/dist/domain/agent-run/runner.js +518 -0
- package/dist/domain/agent-run/supervisor.d.ts +78 -0
- package/dist/domain/agent-run/supervisor.js +425 -0
- package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
- package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
- package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
- package/dist/domain/agent-run/trajectory-merge.js +505 -0
- package/dist/domain/agents/config.d.ts +10 -0
- package/dist/domain/agents/config.js +149 -44
- package/dist/domain/agents/facade.d.ts +42 -7
- package/dist/domain/agents/facade.js +174 -170
- package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
- package/dist/domain/agents/provider-run-lifecycle.js +60 -0
- package/dist/domain/auth/auth-events.d.ts +18 -0
- package/dist/domain/auth/auth-events.js +38 -0
- package/dist/domain/auth/auth-format.d.ts +2 -0
- package/dist/domain/auth/auth-format.js +58 -0
- package/dist/domain/auth/auth-status.d.ts +61 -0
- package/dist/domain/auth/auth-status.js +304 -0
- package/dist/domain/auth/auth-watch.d.ts +16 -0
- package/dist/domain/auth/auth-watch.js +125 -0
- package/dist/domain/auth/cc-login.d.ts +7 -0
- package/dist/domain/auth/cc-login.js +16 -0
- package/dist/domain/auth/cc-subscription.d.ts +38 -0
- package/dist/domain/auth/cc-subscription.js +204 -0
- package/dist/domain/auth/index.d.ts +12 -0
- package/dist/domain/auth/index.js +16 -0
- package/dist/domain/auth/login-flow.d.ts +120 -0
- package/dist/domain/auth/login-flow.js +253 -0
- package/dist/domain/auth/login-service.d.ts +32 -0
- package/dist/domain/auth/login-service.js +97 -0
- package/dist/domain/auth/logout.d.ts +32 -0
- package/dist/domain/auth/logout.js +123 -0
- package/dist/domain/auth/pi-login.d.ts +36 -0
- package/dist/domain/auth/pi-login.js +72 -0
- package/dist/domain/auth/pi-oauth.d.ts +36 -0
- package/dist/domain/auth/pi-oauth.js +84 -0
- package/dist/domain/auth/pi-runtime.d.ts +72 -0
- package/dist/domain/auth/pi-runtime.js +86 -0
- package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
- package/dist/domain/mcp/benchmark-thread-server.js +26 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
- package/dist/domain/memory/user-context.js +6 -8
- package/dist/domain/monitor/disk-monitor.js +47 -16
- package/dist/domain/projects/project-store.js +23 -6
- package/dist/domain/remote/client-manager.js +12 -6
- package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
- package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
- package/dist/domain/scheduling/runner.d.ts +2 -0
- package/dist/domain/scheduling/runner.js +7 -4
- package/dist/domain/sessions/session-backup.d.ts +14 -20
- package/dist/domain/sessions/session-backup.js +57 -68
- package/dist/domain/system/doctor.d.ts +4 -0
- package/dist/domain/system/doctor.js +113 -28
- package/dist/domain/system/server-update-check.js +7 -5
- package/dist/domain/system/system-notice.d.ts +3 -1
- package/dist/domain/system/system-notice.js +6 -11
- package/dist/domain/tasks/archiver.d.ts +1 -0
- package/dist/domain/tasks/archiver.js +13 -7
- package/dist/domain/tasks/claim-recovery.d.ts +3 -3
- package/dist/domain/tasks/claim-recovery.js +12 -8
- package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
- package/dist/domain/tasks/dispatch-utils.js +22 -18
- package/dist/domain/tasks/dispatcher.d.ts +1 -0
- package/dist/domain/tasks/dispatcher.js +9 -5
- package/dist/domain/tasks/mutator.d.ts +21 -11
- package/dist/domain/tasks/mutator.js +30 -24
- package/dist/domain/tasks/pending-tracker.d.ts +5 -2
- package/dist/domain/tasks/pending-tracker.js +11 -5
- package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
- package/dist/domain/tasks/system/cortex-run.js +24 -4
- package/dist/domain/tasks/system/task-cli.d.ts +1 -0
- package/dist/domain/tasks/system/task-cli.js +72 -22
- package/dist/domain/tasks/system/task-completion.d.ts +19 -2
- package/dist/domain/tasks/system/task-completion.js +31 -17
- package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
- package/dist/domain/tasks/system/task-file-input.js +57 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
- package/dist/domain/tasks/system/task-id-utils.js +13 -4
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
- package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
- package/dist/domain/tasks/system/task-lock.js +19 -5
- package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
- package/dist/domain/tasks/system/task-mutations.js +28 -4
- package/dist/domain/tasks/system/task-process.js +10 -8
- package/dist/domain/tasks/system/task-state.d.ts +65 -11
- package/dist/domain/tasks/system/task-state.js +86 -13
- package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
- package/dist/domain/threads/local-runtime-deps.js +91 -0
- package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
- package/dist/domain/threads/local-runtime-scope.js +12 -0
- package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
- package/dist/domain/threads/pending-user-inputs.js +37 -0
- package/dist/domain/threads/prompt-builder.d.ts +12 -1
- package/dist/domain/threads/prompt-builder.js +73 -26
- package/dist/domain/threads/runner.d.ts +15 -3
- package/dist/domain/threads/runner.js +261 -105
- package/dist/domain/threads/state-machine.d.ts +1 -1
- package/dist/domain/threads/state-machine.js +17 -8
- package/dist/domain/ui-service/app-router.d.ts +86 -6
- package/dist/domain/ui-service/app-router.js +171 -133
- package/dist/domain/ui-service/input-schemas.d.ts +132 -10
- package/dist/domain/ui-service/input-schemas.js +59 -5
- package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
- package/dist/domain/ui-service/mutate/approvals.js +2 -1
- package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
- package/dist/domain/ui-service/mutate/auth.js +83 -0
- package/dist/domain/ui-service/mutate/config.js +11 -10
- package/dist/domain/ui-service/query/approvals.js +3 -0
- package/dist/domain/ui-service/query/auth.d.ts +6 -0
- package/dist/domain/ui-service/query/auth.js +12 -0
- package/dist/domain/ui-service/query/config.d.ts +5 -5
- package/dist/domain/ui-service/query/config.js +27 -17
- package/dist/domain/ui-service/query/tasks.d.ts +1 -1
- package/dist/domain/ui-service/query/tasks.js +69 -30
- package/dist/domain/ui-service/query/threads.js +3 -3
- package/dist/domain/ui-service/types.d.ts +67 -8
- package/dist/domain/ui-service/types.js +2 -2
- package/dist/domain/ui-service/ui-service.js +16 -2
- package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
- package/dist/entry/admin-channel-hot-reload.js +22 -0
- package/dist/entry/app.js +38 -38
- package/dist/entry/auth-cli.d.ts +10 -0
- package/dist/entry/auth-cli.js +52 -0
- package/dist/entry/cli-help.d.ts +5 -0
- package/dist/entry/cli-help.js +130 -0
- package/dist/entry/cli.d.ts +5 -5
- package/dist/entry/cli.js +174 -248
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +204 -103
- package/dist/entry/draft-attachments.d.ts +8 -0
- package/dist/entry/draft-attachments.js +83 -0
- package/dist/entry/feishu-login.d.ts +2 -6
- package/dist/entry/feishu-login.js +16 -21
- package/dist/entry/init.js +6 -4
- package/dist/entry/start-ui-http.d.ts +2 -8
- package/dist/entry/start-ui-http.js +7 -34
- package/dist/events/event-logger.js +11 -13
- package/dist/events/event-types.d.ts +19 -1
- package/dist/events/event-types.js +3 -3
- package/dist/events/index.d.ts +1 -1
- package/dist/events/index.js +3 -3
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +193 -0
- package/dist/orchestration/agent-file-send.js +44 -14
- package/dist/orchestration/agent-runner.d.ts +7 -3
- package/dist/orchestration/agent-runner.js +65 -41
- package/dist/orchestration/conversation-runner.d.ts +5 -1
- package/dist/orchestration/conversation-runner.js +16 -7
- package/dist/orchestration/lifecycle.d.ts +23 -1
- package/dist/orchestration/lifecycle.js +103 -40
- package/dist/orchestration/mid-turn-inject.d.ts +2 -0
- package/dist/orchestration/mid-turn-inject.js +29 -13
- package/dist/orchestration/resume-dispatcher.d.ts +3 -5
- package/dist/orchestration/resume-dispatcher.js +9 -17
- package/dist/orchestration/routing/commands/index.d.ts +4 -1
- package/dist/orchestration/routing/commands/index.js +83 -61
- package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
- package/dist/orchestration/routing/commands/login-notice.js +97 -0
- package/dist/orchestration/routing/commands/login.d.ts +12 -0
- package/dist/orchestration/routing/commands/login.js +555 -0
- package/dist/orchestration/routing/commands/status.js +45 -59
- package/dist/orchestration/routing/edit-handler.d.ts +5 -0
- package/dist/orchestration/routing/edit-handler.js +127 -73
- package/dist/orchestration/routing/webhook.js +5 -4
- package/dist/orchestration/session-rewind.d.ts +5 -1
- package/dist/orchestration/session-rewind.js +106 -62
- package/dist/orchestration/session-send.d.ts +2 -0
- package/dist/orchestration/session-send.js +5 -6
- package/dist/orchestration/status-helpers.d.ts +1 -2
- package/dist/orchestration/status-helpers.js +7 -10
- package/dist/orchestration/thread-callback.d.ts +19 -11
- package/dist/orchestration/thread-callback.js +132 -61
- package/dist/orchestration/thread-executor.js +37 -27
- package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
- package/dist/orchestration/turn-mutation-lock.js +36 -0
- package/dist/orchestration/turn-notify.d.ts +2 -5
- package/dist/orchestration/turn-notify.js +9 -21
- package/dist/platform/adapter.d.ts +1 -0
- package/dist/platform/adapter.js +2 -2
- package/dist/platform/adapters/composite-adapter.d.ts +2 -0
- package/dist/platform/adapters/composite-adapter.js +13 -3
- package/dist/platform/adapters/feishu.d.ts +2 -4
- package/dist/platform/adapters/feishu.js +38 -59
- package/dist/platform/adapters/index.d.ts +1 -1
- package/dist/platform/adapters/index.js +13 -12
- package/dist/platform/adapters/slack.d.ts +1 -1
- package/dist/platform/adapters/slack.js +12 -35
- package/dist/platform/index.d.ts +2 -1
- package/dist/platform/index.js +3 -3
- package/dist/platform/testing.d.ts +1 -0
- package/dist/platform/testing.js +13 -4
- package/dist/platform/tool-trace.js +6 -11
- package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
- package/dist/platform/ui-http/ui-http-server.js +6 -18
- package/dist/store/execution-repo.d.ts +17 -1
- package/dist/store/execution-repo.js +55 -4
- package/dist/store/prompt-migration-replacements.d.ts +4 -0
- package/dist/store/prompt-migration-replacements.js +149 -0
- package/dist/store/thread-repo.d.ts +15 -4
- package/dist/store/thread-repo.js +61 -24
- package/dist/store/version-migrations.js +36 -1
- package/native/cortex-supervisor/dist/build-manifest.json +22 -0
- package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
- package/package.json +5 -2
- package/web/dist/assets/index-DrNx9R6c.js +139 -0
- package/web/dist/assets/index-zpf3OSKC.css +1 -0
- package/web/dist/index.html +2 -2
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
- package/web/dist/assets/index-B19jLgji.js +0 -138
- package/web/dist/assets/index-BuFyPyRW.css +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
// input: session
|
|
2
|
-
// output:
|
|
3
|
-
// pos: Claude
|
|
1
|
+
// input: session streams, spawn config, reported accounting
|
|
2
|
+
// output: Claude turns with cache-inclusive input accounting
|
|
3
|
+
// pos: Claude backend adapter
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { spawn } from 'child_process';
|
|
6
|
-
import { createWriteStream } from 'fs';
|
|
6
|
+
import { createWriteStream, mkdirSync } from 'fs';
|
|
7
7
|
import { createInterface } from 'readline';
|
|
8
|
+
import { Writable } from 'stream';
|
|
8
9
|
import * as path from 'path';
|
|
9
10
|
import * as crypto from 'crypto';
|
|
10
11
|
import { DATA_DIR, readableTimestamp } from '../../core/utils.js';
|
|
@@ -12,8 +13,9 @@ import { createLogger } from '../../core/log.js';
|
|
|
12
13
|
import { handleRateLimitEvent } from '../../domain/costs/rate-limit-throttle.js';
|
|
13
14
|
import { fromCanonical } from '../normalize/tool-names.js';
|
|
14
15
|
import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
|
|
16
|
+
import { resolveMcpComposition } from '../types.js';
|
|
15
17
|
import { createEventStream } from '../normalize/event-stream.js';
|
|
16
|
-
import { CancelledError,
|
|
18
|
+
import { CancelledError, IDLE_SESSION_TIMEOUT, LOGS_DIR, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
|
|
17
19
|
import { buildClaudeEnv, buildSpawnArgs } from './spawn-args.js';
|
|
18
20
|
import { ClaudeTuiSession, defaultTailFactory, computeJsonlPath, resolveTuiResume } from './adapter-tui.js';
|
|
19
21
|
import { TmuxControl } from './tmux-control.js';
|
|
@@ -23,6 +25,29 @@ import { BgTaskTracker, routeLine } from './bg-task-tracker.js';
|
|
|
23
25
|
import { ClaudeContextUsageTracker } from './context-usage.js';
|
|
24
26
|
import { resolveAutoCompactWindow } from './compact-window.js';
|
|
25
27
|
const log = createLogger('claude-bridge');
|
|
28
|
+
function spawnClaudeProcess(spawner, args, options) {
|
|
29
|
+
if (spawner)
|
|
30
|
+
return spawner('claude', args, options);
|
|
31
|
+
return { process: spawn('claude', args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] }) };
|
|
32
|
+
}
|
|
33
|
+
function tokenValue(value) {
|
|
34
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
35
|
+
}
|
|
36
|
+
function sumKnownTokens(values) {
|
|
37
|
+
const tokens = values.map(tokenValue);
|
|
38
|
+
if (tokens.some(value => value === null))
|
|
39
|
+
return null;
|
|
40
|
+
const total = tokens.reduce((sum, value) => sum + value, 0);
|
|
41
|
+
return Number.isSafeInteger(total) ? total : null;
|
|
42
|
+
}
|
|
43
|
+
function promptAccounting(usage) {
|
|
44
|
+
return {
|
|
45
|
+
promptTokens: sumKnownTokens([
|
|
46
|
+
usage?.input, usage?.cacheCreation, usage?.cacheRead,
|
|
47
|
+
]),
|
|
48
|
+
cachedTokens: sumKnownTokens([usage?.cacheRead]),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
26
51
|
/** Single source of truth for ClaudeSession fields → ClaudeSpawnOptions CLI args translation.
|
|
27
52
|
* Used by both ClaudeSession.toSpawnOptions() (production) and _test.computeSpawnArgs (lock-in test). */
|
|
28
53
|
function deriveClaudeSpawnOptions(fields) {
|
|
@@ -38,6 +63,10 @@ function deriveClaudeSpawnOptions(fields) {
|
|
|
38
63
|
thinking: fields.thinking,
|
|
39
64
|
needsResume: fields.needsResume,
|
|
40
65
|
sessionId: fields.sessionId,
|
|
66
|
+
mcpComposition: fields.mcpComposition,
|
|
67
|
+
mcpConfigPaths: fields.mcpConfigPaths,
|
|
68
|
+
disableHooks: fields.disableHooks,
|
|
69
|
+
streamDeltas: fields.streamDeltas,
|
|
41
70
|
};
|
|
42
71
|
}
|
|
43
72
|
/**
|
|
@@ -75,6 +104,15 @@ class ClaudeSession {
|
|
|
75
104
|
pluginDirs;
|
|
76
105
|
anthropicBaseUrl;
|
|
77
106
|
extraEnv;
|
|
107
|
+
cwd;
|
|
108
|
+
mcpComposition;
|
|
109
|
+
mcpConfigPaths;
|
|
110
|
+
disableHooks;
|
|
111
|
+
streamDeltas;
|
|
112
|
+
captureTranscriptLogs;
|
|
113
|
+
preserveUnreportedAccounting;
|
|
114
|
+
processSpawner;
|
|
115
|
+
supervision;
|
|
78
116
|
extraOption;
|
|
79
117
|
thinking;
|
|
80
118
|
context;
|
|
@@ -89,6 +127,8 @@ class ClaudeSession {
|
|
|
89
127
|
bgTracker = new BgTaskTracker();
|
|
90
128
|
/** Set by orchestration to receive spontaneous background-task continuation turns. */
|
|
91
129
|
continuationSink = null;
|
|
130
|
+
/** One-shot events that arrived before completion-only waiting installed its sink. */
|
|
131
|
+
pendingContinuationDeliveries = [];
|
|
92
132
|
/** Messages injected into an in-flight turn that the CLI has not echoed back yet, in write
|
|
93
133
|
* order. Each is popped by its `--replay-user-messages` echo (the delivery ack). */
|
|
94
134
|
pendingInjections = [];
|
|
@@ -107,7 +147,7 @@ class ClaudeSession {
|
|
|
107
147
|
cumulativeCostUsd = 0;
|
|
108
148
|
/** Captured from result event's modelUsage key for cost_record. */
|
|
109
149
|
lastModelName = null;
|
|
110
|
-
/** Captured from result event's usage for cost_record
|
|
150
|
+
/** Captured from result event's usage for legacy cost_record and compact accounting. */
|
|
111
151
|
lastTokenUsage = null;
|
|
112
152
|
constructor(channel, sessionId, options) {
|
|
113
153
|
this.channel = channel;
|
|
@@ -115,9 +155,9 @@ class ClaudeSession {
|
|
|
115
155
|
this.sessionKey = options.sessionKey || channel;
|
|
116
156
|
this.needsResume = options.needsResume;
|
|
117
157
|
this.modelName = options.model || null;
|
|
118
|
-
|
|
119
|
-
//
|
|
120
|
-
this.contextUsageTracker = new ClaudeContextUsageTracker(this.modelName, resolveAutoCompactWindow(
|
|
158
|
+
this.cwd = options.cwd ?? DATA_DIR;
|
|
159
|
+
// Settings are read per session because the CLI reads project settings from its spawn cwd.
|
|
160
|
+
this.contextUsageTracker = new ClaudeContextUsageTracker(this.modelName, resolveAutoCompactWindow(this.cwd));
|
|
121
161
|
this.isUserInitiated = options.isUserInitiated || false;
|
|
122
162
|
this.callbackSource = options.callbackSource || null;
|
|
123
163
|
this.scheduleTaskId = options.scheduleTaskId || null;
|
|
@@ -129,6 +169,13 @@ class ClaudeSession {
|
|
|
129
169
|
this.pluginDirs = options.pluginDirs || null;
|
|
130
170
|
this.anthropicBaseUrl = options.anthropicBaseUrl;
|
|
131
171
|
this.extraEnv = options.extraEnv;
|
|
172
|
+
this.mcpComposition = resolveMcpComposition(options.mcpComposition, options.context?.useCoreMcp);
|
|
173
|
+
this.mcpConfigPaths = options.mcpConfigPaths;
|
|
174
|
+
this.disableHooks = options.disableHooks === true;
|
|
175
|
+
this.streamDeltas = options.streamDeltas;
|
|
176
|
+
this.captureTranscriptLogs = options.captureTranscriptLogs !== false;
|
|
177
|
+
this.preserveUnreportedAccounting = options.preserveUnreportedAccounting === true;
|
|
178
|
+
this.processSpawner = options.processSpawner;
|
|
132
179
|
this.extraOption = options.extraOption;
|
|
133
180
|
this.thinking = options.thinking ?? null;
|
|
134
181
|
this.context = options.context;
|
|
@@ -147,10 +194,26 @@ class ClaudeSession {
|
|
|
147
194
|
thinking: this.thinking,
|
|
148
195
|
needsResume: this.needsResume,
|
|
149
196
|
sessionId: this.sessionId,
|
|
197
|
+
mcpComposition: this.mcpComposition,
|
|
198
|
+
mcpConfigPaths: this.mcpConfigPaths,
|
|
199
|
+
disableHooks: this.disableHooks,
|
|
200
|
+
streamDeltas: this.streamDeltas,
|
|
150
201
|
});
|
|
151
202
|
}
|
|
203
|
+
matchesSpawn(cwd, composition) {
|
|
204
|
+
return this.cwd === cwd && this.mcpComposition === composition;
|
|
205
|
+
}
|
|
152
206
|
handleProcessClose(code) {
|
|
153
207
|
log.info(`Process closed: ${this.sessionId.substring(0, 8)} code=${code}`);
|
|
208
|
+
if (this.idleTimer)
|
|
209
|
+
clearTimeout(this.idleTimer);
|
|
210
|
+
if (this.maxTimer)
|
|
211
|
+
clearTimeout(this.maxTimer);
|
|
212
|
+
if (this.turnIdleTimer)
|
|
213
|
+
clearTimeout(this.turnIdleTimer);
|
|
214
|
+
this.idleTimer = null;
|
|
215
|
+
this.maxTimer = null;
|
|
216
|
+
this.turnIdleTimer = null;
|
|
154
217
|
this.alive = false;
|
|
155
218
|
clearActivePlanFile(this.sessionId);
|
|
156
219
|
if (this.currentTurn) {
|
|
@@ -180,7 +243,8 @@ class ClaudeSession {
|
|
|
180
243
|
// otherwise wait forever — any process death (restart / crash / kill / timeout) must
|
|
181
244
|
// seal it. No-op when nothing is pending; always releases the sink (session is gone).
|
|
182
245
|
this.notifyBgInterrupted();
|
|
183
|
-
sessions.
|
|
246
|
+
if (sessions.get(this.sessionKey) === this)
|
|
247
|
+
sessions.delete(this.sessionKey);
|
|
184
248
|
}
|
|
185
249
|
/** Deliver a synthetic interrupted result to the continuation sink (single-fire: the sink
|
|
186
250
|
* reference is cleared before invoking). Fires only when background work may still produce
|
|
@@ -215,29 +279,23 @@ class ClaudeSession {
|
|
|
215
279
|
spawnProcess() {
|
|
216
280
|
const env = buildClaudeEnv(this.channel, this.sessionId, this.callbackSource, this.scheduleTaskId, this.anthropicBaseUrl, this.extraEnv, this.context);
|
|
217
281
|
const spawnOptions = this.toSpawnOptions();
|
|
218
|
-
// CORE_MCP_CONFIG marks template threads; spawn args add task, answer, and control layers.
|
|
219
|
-
// Default/direct sessions use the full core + tasks + manager-answer + ext config.
|
|
220
|
-
if (this.context?.useCoreMcp) {
|
|
221
|
-
spawnOptions.mcpConfigPath = CORE_MCP_CONFIG;
|
|
222
|
-
}
|
|
223
282
|
// Sessions that originate from Slack (channel carries the SlackAdapter `slack:` prefix) load the
|
|
224
|
-
// cortex-slack MCP server so the agent can send files to Slack.
|
|
225
|
-
// it for thread/core sessions (CORE_MCP_CONFIG) regardless of this flag.
|
|
283
|
+
// cortex-slack MCP server so the agent can send files to Slack. Non-direct compositions suppress it.
|
|
226
284
|
spawnOptions.loadSlackMcp = this.channel.startsWith('slack:');
|
|
227
285
|
// Sessions that originate from Feishu (channel carries the FeishuAdapter `feishu:` prefix) load the
|
|
228
|
-
// cortex-feishu MCP server so the agent can read/write Feishu documents.
|
|
229
|
-
// it for thread/core sessions (CORE_MCP_CONFIG) regardless of this flag.
|
|
286
|
+
// cortex-feishu MCP server so the agent can read/write Feishu documents. Non-direct compositions suppress it.
|
|
230
287
|
spawnOptions.loadFeishuMcp = this.channel.startsWith('feishu:');
|
|
231
288
|
// Sessions that originate from the Web UI (channel carries the `web:` prefix) load the cortex-web
|
|
232
|
-
// MCP server so the agent can send files into the chat via send_file.
|
|
233
|
-
// it for thread/core sessions (CORE_MCP_CONFIG) regardless of this flag.
|
|
289
|
+
// MCP server so the agent can send files into the chat via send_file. Non-direct compositions suppress it.
|
|
234
290
|
spawnOptions.loadWebMcp = this.channel.startsWith('web:');
|
|
235
|
-
// User-message-initiated
|
|
236
|
-
//
|
|
291
|
+
// User-message-initiated direct print sessions get the cortex-tui-bridge interaction tools;
|
|
292
|
+
// non-direct compositions suppress them.
|
|
237
293
|
spawnOptions.isUserInitiated = this.isUserInitiated;
|
|
238
294
|
const args = buildSpawnArgs(spawnOptions);
|
|
239
295
|
log.info(`Spawning persistent process: ${this.sessionId.substring(0, 8)} ${this.needsResume ? '(resume)' : '(new)'}`);
|
|
240
|
-
|
|
296
|
+
const spawned = spawnClaudeProcess(this.processSpawner, args, { cwd: this.cwd, env });
|
|
297
|
+
this.proc = spawned.process;
|
|
298
|
+
this.supervision = spawned.supervision;
|
|
241
299
|
this.stderr = '';
|
|
242
300
|
this.rl = createInterface({ input: this.proc.stdout, crlfDelay: Infinity });
|
|
243
301
|
this.rl.on('line', (line) => this.handleLine(line));
|
|
@@ -251,6 +309,11 @@ class ClaudeSession {
|
|
|
251
309
|
}, MAX_TIMEOUT);
|
|
252
310
|
}
|
|
253
311
|
createTurnStreams(userMessage) {
|
|
312
|
+
if (!this.captureTranscriptLogs) {
|
|
313
|
+
const sink = () => new Writable({ write(_chunk, _encoding, done) { done(); } });
|
|
314
|
+
return { rawStream: sink(), txtStream: sink() };
|
|
315
|
+
}
|
|
316
|
+
mkdirSync(LOGS_DIR, { recursive: true });
|
|
254
317
|
const ts = readableTimestamp();
|
|
255
318
|
const rawStream = createWriteStream(path.join(LOGS_DIR, `claude-output-${ts}.jsonl`), { flags: 'a' });
|
|
256
319
|
const txtStream = createWriteStream(path.join(LOGS_DIR, `claude-output-${ts}.txt`), { flags: 'a' });
|
|
@@ -282,13 +345,31 @@ class ClaudeSession {
|
|
|
282
345
|
killed: false,
|
|
283
346
|
};
|
|
284
347
|
}
|
|
348
|
+
deliverContinuation(delivery) {
|
|
349
|
+
const sink = this.continuationSink;
|
|
350
|
+
if (!sink) {
|
|
351
|
+
if (this.preserveUnreportedAccounting)
|
|
352
|
+
this.pendingContinuationDeliveries.push(delivery);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
delivery(sink);
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
log.warn('continuation sink threw:', error.message);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
285
362
|
/** Register/replace the continuation sink. Persists across normal turns; lives as long
|
|
286
363
|
* as the pooled session, until close()/kill(). */
|
|
287
364
|
setContinuationSink(sink) {
|
|
288
365
|
this.continuationSink = sink;
|
|
366
|
+
const pending = this.pendingContinuationDeliveries.splice(0);
|
|
367
|
+
for (const delivery of pending)
|
|
368
|
+
this.deliverContinuation(delivery);
|
|
289
369
|
}
|
|
290
370
|
clearContinuationSink() {
|
|
291
371
|
this.continuationSink = null;
|
|
372
|
+
this.pendingContinuationDeliveries.length = 0;
|
|
292
373
|
}
|
|
293
374
|
/** Register/replace the injection delivery-ack sink. Lifetime mirrors continuationSink. */
|
|
294
375
|
setInjectionAckSink(sink) {
|
|
@@ -367,60 +448,29 @@ class ClaudeSession {
|
|
|
367
448
|
log.warn('injection onDelivered threw:', e.message);
|
|
368
449
|
}
|
|
369
450
|
}
|
|
451
|
+
continuationCallbacks() {
|
|
452
|
+
return {
|
|
453
|
+
resolve: (value) => this.deliverContinuation(sink => sink.onResult(value)),
|
|
454
|
+
reject: (error) => log.warn('continuation turn rejected:', error?.message ?? String(error)),
|
|
455
|
+
onAssistantMessage: (text, _blockId, model) => this.deliverContinuation(sink => sink.onAssistantText(text, model)),
|
|
456
|
+
onToolUse: (name, input, id) => this.deliverContinuation(sink => sink.onToolUse?.(name, input, id)),
|
|
457
|
+
onToolResult: (id, content, isError) => this.deliverContinuation(sink => sink.onToolResult?.(id, content, isError)),
|
|
458
|
+
onContextUsage: (usage) => this.deliverContinuation(sink => sink.onContextUsage?.(usage)),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
370
461
|
/** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
|
|
371
|
-
* background task finishes. Its
|
|
372
|
-
* (not to a send() promise — there is no caller awaiting it). */
|
|
462
|
+
* background task finishes. Its output is delivered or buffered for continuationSink. */
|
|
373
463
|
openContinuationTurn(label = '[background-task continuation]') {
|
|
374
464
|
this.bgTracker.disarmContinuation();
|
|
375
465
|
const streams = this.createTurnStreams(label);
|
|
376
|
-
const sink = this.continuationSink;
|
|
377
466
|
this.currentTurn = {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
resultData: null,
|
|
386
|
-
planFilePath: null,
|
|
387
|
-
enteredPlanMode: false,
|
|
388
|
-
exitedPlanMode: false,
|
|
389
|
-
askUserQuestions: [],
|
|
390
|
-
finalOutput: null,
|
|
391
|
-
longestOutput: null,
|
|
392
|
-
turnCount: 0,
|
|
393
|
-
onProgress: null,
|
|
394
|
-
onAssistantMessage: sink ? (text) => { try {
|
|
395
|
-
sink.onAssistantText(text);
|
|
396
|
-
}
|
|
397
|
-
catch (e) {
|
|
398
|
-
log.warn('continuation onAssistantText threw:', e.message);
|
|
399
|
-
} } : null,
|
|
400
|
-
// A spontaneous background-task continuation has no caller awaiting it and reaches the UI
|
|
401
|
-
// through the sink's complete messages only — nothing streams a preview for it.
|
|
402
|
-
onAssistantDelta: null,
|
|
403
|
-
onToolUse: sink?.onToolUse ? (name, input, toolUseId) => { try {
|
|
404
|
-
sink.onToolUse(name, input, toolUseId);
|
|
405
|
-
}
|
|
406
|
-
catch { } } : null,
|
|
407
|
-
onToolResult: sink?.onToolResult ? (toolUseId, content, isError) => { try {
|
|
408
|
-
sink.onToolResult(toolUseId, content, isError);
|
|
409
|
-
}
|
|
410
|
-
catch { } } : null,
|
|
411
|
-
onCompact: null,
|
|
412
|
-
onContextUsage: sink?.onContextUsage ? (usage) => {
|
|
413
|
-
try {
|
|
414
|
-
sink.onContextUsage(usage);
|
|
415
|
-
}
|
|
416
|
-
catch (e) {
|
|
417
|
-
log.warn('continuation onContextUsage threw:', e.message);
|
|
418
|
-
}
|
|
419
|
-
} : null,
|
|
420
|
-
rawStream: streams.rawStream,
|
|
421
|
-
txtStream: streams.txtStream,
|
|
422
|
-
killed: false,
|
|
423
|
-
spontaneous: true,
|
|
467
|
+
...this.continuationCallbacks(),
|
|
468
|
+
resultData: null, planFilePath: null,
|
|
469
|
+
enteredPlanMode: false, exitedPlanMode: false,
|
|
470
|
+
askUserQuestions: [], finalOutput: null, longestOutput: null, turnCount: 0,
|
|
471
|
+
onProgress: null, onAssistantDelta: null, onCompact: null,
|
|
472
|
+
rawStream: streams.rawStream, txtStream: streams.txtStream,
|
|
473
|
+
killed: false, spontaneous: true,
|
|
424
474
|
};
|
|
425
475
|
}
|
|
426
476
|
writeTurnStdin(prompt) {
|
|
@@ -511,38 +561,51 @@ class ClaudeSession {
|
|
|
511
561
|
clearTimeout(this.turnIdleTimer);
|
|
512
562
|
this.startTurnIdleTimer();
|
|
513
563
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
const cumulativeCost = data.total_cost_usd ?? 0;
|
|
564
|
+
turnCost(data) {
|
|
565
|
+
if (data.total_cost_usd == null)
|
|
566
|
+
return 0;
|
|
567
|
+
const cumulativeCost = data.total_cost_usd;
|
|
519
568
|
const turnCost = cumulativeCost - this.cumulativeCostUsd;
|
|
520
569
|
this.cumulativeCostUsd = cumulativeCost;
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
const
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
570
|
+
return turnCost > 0 ? turnCost : 0;
|
|
571
|
+
}
|
|
572
|
+
captureTurnAccounting(data) {
|
|
573
|
+
const missingToken = this.preserveUnreportedAccounting ? null : 0;
|
|
574
|
+
this.lastTokenUsage = data.usage ? {
|
|
575
|
+
input: data.usage.input_tokens ?? missingToken,
|
|
576
|
+
output: data.usage.output_tokens ?? missingToken,
|
|
577
|
+
cacheCreation: data.usage.cache_creation_input_tokens ?? missingToken,
|
|
578
|
+
cacheRead: data.usage.cache_read_input_tokens ?? missingToken,
|
|
579
|
+
} : null;
|
|
580
|
+
const models = data.modelUsage ? Object.keys(data.modelUsage) : [];
|
|
581
|
+
this.lastModelName = models[0] ?? null;
|
|
582
|
+
return this.turnCost(data);
|
|
583
|
+
}
|
|
584
|
+
reportedAccounting(data) {
|
|
585
|
+
const usage = data.usage;
|
|
586
|
+
const turnUsage = usage ? {
|
|
587
|
+
input: tokenValue(usage.input_tokens),
|
|
588
|
+
output: tokenValue(usage.output_tokens),
|
|
589
|
+
cacheCreation: tokenValue(usage.cache_creation_input_tokens),
|
|
590
|
+
cacheRead: tokenValue(usage.cache_read_input_tokens),
|
|
591
|
+
} : null;
|
|
592
|
+
return {
|
|
593
|
+
usageReported: usage != null,
|
|
594
|
+
inputTokens: turnUsage?.input ?? null,
|
|
595
|
+
outputTokens: turnUsage?.output ?? null,
|
|
596
|
+
...promptAccounting(turnUsage),
|
|
597
|
+
model: data.modelUsage ? Object.keys(data.modelUsage)[0] ?? null : null,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
settleResultTurn(turn, data, result) {
|
|
543
601
|
if (result.resolved) {
|
|
544
|
-
|
|
545
|
-
|
|
602
|
+
const value = result.value;
|
|
603
|
+
if (this.preserveUnreportedAccounting) {
|
|
604
|
+
value.costReported = data.total_cost_usd != null;
|
|
605
|
+
value.reportedAccounting = this.reportedAccounting(data);
|
|
606
|
+
}
|
|
607
|
+
value.pendingBackgroundTasks = this.bgTracker.pendingCount;
|
|
608
|
+
value.undeliveredBackgroundTasks = this.bgTracker.undeliveredCount;
|
|
546
609
|
}
|
|
547
610
|
this.currentTurn = null;
|
|
548
611
|
if (this.turnIdleTimer)
|
|
@@ -559,6 +622,11 @@ class ClaudeSession {
|
|
|
559
622
|
else
|
|
560
623
|
turn.reject(result.error);
|
|
561
624
|
}
|
|
625
|
+
handleResultEvent(turn, data) {
|
|
626
|
+
turn.resultData = { ...data, total_cost_usd: this.captureTurnAccounting(data) };
|
|
627
|
+
const result = extractResult(turn.resultData, this.sessionId, false, 0, '', turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
|
|
628
|
+
this.settleResultTurn(turn, data, result);
|
|
629
|
+
}
|
|
562
630
|
/** Preserve the complete result carrier that print mode emits as a `user` content block. */
|
|
563
631
|
handleToolResultEvent(turn, data) {
|
|
564
632
|
if (typeof turn.onToolResult !== 'function')
|
|
@@ -591,45 +659,46 @@ class ClaudeSession {
|
|
|
591
659
|
}
|
|
592
660
|
}
|
|
593
661
|
}
|
|
662
|
+
handleAssistantToolBlock(turn, block) {
|
|
663
|
+
if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
|
|
664
|
+
turn.planFilePath = block.input.file_path;
|
|
665
|
+
setActivePlanFile(this.sessionId, block.input.file_path);
|
|
666
|
+
}
|
|
667
|
+
if (block.name === 'EnterPlanMode')
|
|
668
|
+
turn.enteredPlanMode = true;
|
|
669
|
+
if (block.name === 'ExitPlanMode')
|
|
670
|
+
turn.exitedPlanMode = true;
|
|
671
|
+
if (typeof turn.onToolUse !== 'function')
|
|
672
|
+
return;
|
|
673
|
+
try {
|
|
674
|
+
turn.onToolUse(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '');
|
|
675
|
+
}
|
|
676
|
+
catch (error) {
|
|
677
|
+
log.warn('onToolUse threw:', error.message);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
handleAssistantTextBlock(turn, data, block) {
|
|
681
|
+
if (!block.text)
|
|
682
|
+
return;
|
|
683
|
+
turn.finalOutput = block.text;
|
|
684
|
+
if (block.text.length > (turn.longestOutput?.length || 0))
|
|
685
|
+
turn.longestOutput = block.text;
|
|
686
|
+
const blockId = takeTextBlockId(this.streamDeltaState) ?? undefined;
|
|
687
|
+
const streamedModel = this.streamDeltaState.messageId === data.message?.id
|
|
688
|
+
? this.streamDeltaState.model
|
|
689
|
+
: null;
|
|
690
|
+
const model = typeof data.message?.model === 'string' ? data.message.model : streamedModel;
|
|
691
|
+
turn.onAssistantMessage?.(block.text, blockId, model);
|
|
692
|
+
}
|
|
594
693
|
handleAssistantEvent(turn, data) {
|
|
595
694
|
turn.turnCount += 1;
|
|
596
695
|
for (const block of (data.message?.content || [])) {
|
|
597
|
-
if (block.type === 'tool_use')
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
}
|
|
602
|
-
if (block.name === 'EnterPlanMode') {
|
|
603
|
-
turn.enteredPlanMode = true;
|
|
604
|
-
}
|
|
605
|
-
if (block.name === 'ExitPlanMode') {
|
|
606
|
-
turn.exitedPlanMode = true;
|
|
607
|
-
}
|
|
608
|
-
if (typeof turn.onToolUse === 'function') {
|
|
609
|
-
try {
|
|
610
|
-
turn.onToolUse(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '');
|
|
611
|
-
}
|
|
612
|
-
catch (e) {
|
|
613
|
-
log.warn('onToolUse threw:', e.message);
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
if (block.type === 'text' && block.text) {
|
|
618
|
-
turn.finalOutput = block.text;
|
|
619
|
-
if (block.text.length > (turn.longestOutput?.length || 0))
|
|
620
|
-
turn.longestOutput = block.text;
|
|
621
|
-
// Adopt the id of the text block that just streamed, so the UI can replace its accumulated
|
|
622
|
-
// preview with this authoritative text instead of appending a second row. The block's own
|
|
623
|
-
// position in `message.content` cannot serve: the CLI sends one assistant event per block,
|
|
624
|
-
// so that position is always 0 while the streamed index may be any number.
|
|
625
|
-
const blockId = takeTextBlockId(this.streamDeltaState) ?? undefined;
|
|
626
|
-
if (typeof turn.onAssistantMessage === 'function')
|
|
627
|
-
turn.onAssistantMessage(block.text, blockId);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
if (typeof turn.onProgress === 'function') {
|
|
631
|
-
turn.onProgress({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
|
|
696
|
+
if (block.type === 'tool_use')
|
|
697
|
+
this.handleAssistantToolBlock(turn, block);
|
|
698
|
+
if (block.type === 'text')
|
|
699
|
+
this.handleAssistantTextBlock(turn, data, block);
|
|
632
700
|
}
|
|
701
|
+
turn.onProgress?.({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
|
|
633
702
|
}
|
|
634
703
|
emitContextUsage(data) {
|
|
635
704
|
const usage = this.contextUsageTracker.observe(data);
|
|
@@ -716,7 +785,8 @@ class ClaudeSession {
|
|
|
716
785
|
// finished (bgTracker armed) or an injected message was consumed after this turn's result
|
|
717
786
|
// Both make the CLI open a turn of its own — open a synthetic turn for it so its
|
|
718
787
|
// output is routed (to continuationSink) instead of being dropped.
|
|
719
|
-
|
|
788
|
+
const canCaptureContinuation = this.continuationSink || this.preserveUnreportedAccounting;
|
|
789
|
+
if (!this.currentTurn && canCaptureContinuation && data.type === 'assistant'
|
|
720
790
|
&& (this.injectionContinuationArmed || routeLine(this.bgTracker, data, false) === 'open-continuation')) {
|
|
721
791
|
const fromInjection = this.injectionContinuationArmed;
|
|
722
792
|
this.injectionContinuationArmed = false;
|
|
@@ -815,9 +885,13 @@ class ClaudeSession {
|
|
|
815
885
|
if (!this.proc || this.proc.exitCode !== null)
|
|
816
886
|
return false;
|
|
817
887
|
this.alive = false;
|
|
818
|
-
sessions.
|
|
819
|
-
|
|
888
|
+
if (sessions.get(this.sessionKey) === this)
|
|
889
|
+
sessions.delete(this.sessionKey);
|
|
890
|
+
if (this.currentTurn)
|
|
820
891
|
this.currentTurn.killed = true;
|
|
892
|
+
if (this.supervision) {
|
|
893
|
+
this.supervision.cancel('cancel');
|
|
894
|
+
return true;
|
|
821
895
|
}
|
|
822
896
|
try {
|
|
823
897
|
this.proc.kill('SIGTERM');
|
|
@@ -827,6 +901,9 @@ class ClaudeSession {
|
|
|
827
901
|
return false;
|
|
828
902
|
}
|
|
829
903
|
}
|
|
904
|
+
getSupervision() {
|
|
905
|
+
return this.supervision;
|
|
906
|
+
}
|
|
830
907
|
isAlive() {
|
|
831
908
|
return this.alive;
|
|
832
909
|
}
|
|
@@ -835,8 +912,11 @@ class ClaudeSession {
|
|
|
835
912
|
const sessions = new Map();
|
|
836
913
|
function getOrCreateSession(channel, sessionId, options) {
|
|
837
914
|
const key = options.sessionKey || channel;
|
|
915
|
+
const cwd = options.cwd ?? DATA_DIR;
|
|
916
|
+
const composition = resolveMcpComposition(options.mcpComposition, options.context?.useCoreMcp);
|
|
838
917
|
let session = sessions.get(key);
|
|
839
|
-
|
|
918
|
+
const incompatible = session && !session.matchesSpawn(cwd, composition);
|
|
919
|
+
if (!session || !session.isAlive() || incompatible || (options.needsResume && session.sessionId !== sessionId)) {
|
|
840
920
|
if (session)
|
|
841
921
|
session.close();
|
|
842
922
|
session = new ClaudeSession(channel, sessionId, { ...options, sessionKey: key });
|
|
@@ -873,8 +953,8 @@ export function closeAllSessions() {
|
|
|
873
953
|
/**
|
|
874
954
|
* Decide whether a print-mode ClaudeSession should spawn with `--resume <id>`.
|
|
875
955
|
*
|
|
876
|
-
* Print sessions
|
|
877
|
-
*
|
|
956
|
+
* Print sessions default to `DATA_DIR` and may receive an explicit cwd, so transcript lookup uses
|
|
957
|
+
* the same resolved cwd as the process spawn. A *fresh* session (notably the `cortex tui`
|
|
878
958
|
* frontend) pre-registers its sessionId BEFORE the first Claude turn, so callers ask to
|
|
879
959
|
* resume an id that has no transcript yet — Claude then exits with
|
|
880
960
|
* "No conversation found with session ID: <id>". Gating the resume request on the
|
|
@@ -882,8 +962,8 @@ export function closeAllSessions() {
|
|
|
882
962
|
* only later turns / reconnects use `--resume`. Self-healing: a deleted transcript also
|
|
883
963
|
* correctly falls back to create. Mirrors {@link resolveTuiResume} for the tmux path.
|
|
884
964
|
*/
|
|
885
|
-
export function resolveResumeForPrint(requestedResume, sessionId, exists) {
|
|
886
|
-
return resolveTuiResume(requestedResume, computeJsonlPath(
|
|
965
|
+
export function resolveResumeForPrint(requestedResume, sessionId, exists, cwd = DATA_DIR) {
|
|
966
|
+
return resolveTuiResume(requestedResume, computeJsonlPath(cwd, sessionId), exists);
|
|
887
967
|
}
|
|
888
968
|
export function runClaude(userMessage, opts) {
|
|
889
969
|
const effectiveSessionId = opts.sessionId || crypto.randomUUID();
|
|
@@ -914,15 +994,17 @@ export function selectClaudeMode(config) {
|
|
|
914
994
|
}
|
|
915
995
|
function getOrCreateTuiSession(config, sessionIdEffective) {
|
|
916
996
|
const key = config.sessionKey;
|
|
997
|
+
const cwd = config.cwd || DATA_DIR;
|
|
998
|
+
const composition = resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp);
|
|
917
999
|
let session = tuiSessions.get(key);
|
|
918
|
-
|
|
919
|
-
|
|
1000
|
+
if (session && (session.sessionId !== sessionIdEffective
|
|
1001
|
+
|| session.cwd !== cwd
|
|
1002
|
+
|| session.mcpComposition !== composition)) {
|
|
920
1003
|
session.kill();
|
|
921
1004
|
session = undefined;
|
|
922
1005
|
}
|
|
923
1006
|
if (!session) {
|
|
924
1007
|
const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
|
|
925
|
-
const cwd = config.cwd || DATA_DIR;
|
|
926
1008
|
const opts = sessionOptionsFromSpawnConfig({ ...config, sessionId: sessionIdEffective });
|
|
927
1009
|
// `--resume` only works once a transcript exists. A fresh TUI session pre-registers its
|
|
928
1010
|
// sessionId before the first turn, so config.resume can be true with no transcript yet —
|
|
@@ -943,9 +1025,7 @@ function getOrCreateTuiSession(config, sessionIdEffective) {
|
|
|
943
1025
|
outputStyle: opts.outputStyle,
|
|
944
1026
|
extraOption: opts.extraOption ?? null,
|
|
945
1027
|
thinking: opts.thinking ?? null,
|
|
946
|
-
|
|
947
|
-
// control-plane layers while suppressing the direct-session TUI bridge.
|
|
948
|
-
mcpConfigPath: opts.context?.useCoreMcp ? CORE_MCP_CONFIG : undefined,
|
|
1028
|
+
mcpComposition: composition,
|
|
949
1029
|
callbackSource: opts.callbackSource,
|
|
950
1030
|
scheduleTaskId: opts.scheduleTaskId,
|
|
951
1031
|
anthropicBaseUrl: opts.anthropicBaseUrl,
|
|
@@ -1001,6 +1081,14 @@ function sessionOptionsFromSpawnConfig(config) {
|
|
|
1001
1081
|
claudeAgent: config.claudeAgent ?? null,
|
|
1002
1082
|
anthropicBaseUrl: config.anthropicBaseUrl,
|
|
1003
1083
|
extraEnv: config.env,
|
|
1084
|
+
cwd: config.cwd ?? DATA_DIR,
|
|
1085
|
+
mcpComposition: resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp),
|
|
1086
|
+
mcpConfigPaths: config.mcpConfigPaths,
|
|
1087
|
+
disableHooks: config.disableHooks,
|
|
1088
|
+
streamDeltas: config.streamDeltas,
|
|
1089
|
+
captureTranscriptLogs: config.captureTranscriptLogs,
|
|
1090
|
+
preserveUnreportedAccounting: config.preserveUnreportedAccounting,
|
|
1091
|
+
processSpawner: config.processSpawner,
|
|
1004
1092
|
extraOption: config.extraOption,
|
|
1005
1093
|
thinking: config.thinking ?? null,
|
|
1006
1094
|
context: config.cortexContext,
|
|
@@ -1024,6 +1112,10 @@ function computeSpawnArgsForConfig(config) {
|
|
|
1024
1112
|
thinking: opts.thinking ?? null,
|
|
1025
1113
|
needsResume: opts.needsResume,
|
|
1026
1114
|
sessionId: opts.sessionIdEffective,
|
|
1115
|
+
mcpComposition: opts.mcpComposition ?? 'direct',
|
|
1116
|
+
mcpConfigPaths: opts.mcpConfigPaths,
|
|
1117
|
+
disableHooks: opts.disableHooks,
|
|
1118
|
+
streamDeltas: opts.streamDeltas,
|
|
1027
1119
|
});
|
|
1028
1120
|
spawnOptions.isUserInitiated = config.isUserInitiated;
|
|
1029
1121
|
return buildSpawnArgs(spawnOptions);
|
|
@@ -1039,7 +1131,7 @@ export class ClaudeAdapter {
|
|
|
1039
1131
|
// Gate resume on the transcript actually existing — a pre-registered sessionId
|
|
1040
1132
|
// (e.g. cortex tui handshake) must spawn `--session-id` on its first turn, not
|
|
1041
1133
|
// `--resume` (which fails "No conversation found"). See resolveResumeForPrint.
|
|
1042
|
-
sessionOptions.needsResume = resolveResumeForPrint(sessionOptions.needsResume, sessionIdEffective);
|
|
1134
|
+
sessionOptions.needsResume = resolveResumeForPrint(sessionOptions.needsResume, sessionIdEffective, undefined, sessionOptions.cwd);
|
|
1043
1135
|
const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
|
|
1044
1136
|
const session = getOrCreateSession(channel, sessionIdEffective, sessionOptions);
|
|
1045
1137
|
const stream = createEventStream();
|
|
@@ -1047,6 +1139,7 @@ export class ClaudeAdapter {
|
|
|
1047
1139
|
return {
|
|
1048
1140
|
sessionKey: config.sessionKey,
|
|
1049
1141
|
get sessionId() { return session.sessionId; },
|
|
1142
|
+
get supervision() { return session.getSupervision(); },
|
|
1050
1143
|
async send(message) {
|
|
1051
1144
|
if (!started) {
|
|
1052
1145
|
stream.push({ type: 'session_started', sessionId: session.sessionId });
|
|
@@ -1058,7 +1151,11 @@ export class ClaudeAdapter {
|
|
|
1058
1151
|
try {
|
|
1059
1152
|
const result = await session.sendMessage(message.text, {
|
|
1060
1153
|
files,
|
|
1061
|
-
onAssistantMessage: (text, blockId) => stream.push({
|
|
1154
|
+
onAssistantMessage: (text, blockId, model) => stream.push({
|
|
1155
|
+
type: 'assistant_text', text,
|
|
1156
|
+
...(blockId ? { blockId } : {}),
|
|
1157
|
+
...(model != null ? { model } : {}),
|
|
1158
|
+
}),
|
|
1062
1159
|
// Token-level preview of the block above. Same FIFO stream, so every delta is delivered
|
|
1063
1160
|
// before the complete message that supersedes it.
|
|
1064
1161
|
onAssistantDelta: (text, blockId) => stream.push({ type: 'assistant_delta', text, blockId }),
|
|
@@ -1089,23 +1186,38 @@ export class ClaudeAdapter {
|
|
|
1089
1186
|
if (result.rateLimited) {
|
|
1090
1187
|
stream.push({ type: 'rate_limit', raw: { message: result.rateLimitMessage } });
|
|
1091
1188
|
}
|
|
1092
|
-
// Emit cost_record from
|
|
1093
|
-
|
|
1094
|
-
|
|
1189
|
+
// Emit cost_record from the resolved turn, not mutable session accounting.
|
|
1190
|
+
const preserveReportedness = config.preserveUnreportedAccounting === true;
|
|
1191
|
+
const accounting = result.reportedAccounting;
|
|
1192
|
+
const hasReportableAccounting = preserveReportedness
|
|
1193
|
+
? result.costReported === true || accounting?.usageReported === true
|
|
1194
|
+
: result.total_cost_usd != null || session.lastTokenUsage !== null;
|
|
1195
|
+
if (hasReportableAccounting) {
|
|
1196
|
+
const legacyUsage = session.lastTokenUsage;
|
|
1197
|
+
const exactPrompt = promptAccounting(legacyUsage);
|
|
1095
1198
|
stream.push({
|
|
1096
1199
|
type: 'cost_record',
|
|
1097
1200
|
provider: 'anthropic',
|
|
1098
|
-
model:
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1201
|
+
model: (preserveReportedness ? accounting?.model : session.lastModelName)
|
|
1202
|
+
|| session.modelName || 'unknown',
|
|
1203
|
+
tokens_in: preserveReportedness
|
|
1204
|
+
? accounting?.promptTokens ?? null : exactPrompt.promptTokens,
|
|
1205
|
+
tokens_out: preserveReportedness ? accounting?.outputTokens ?? null : legacyUsage?.output ?? 0,
|
|
1206
|
+
prompt_tokens: preserveReportedness
|
|
1207
|
+
? accounting?.promptTokens ?? null : exactPrompt.promptTokens,
|
|
1208
|
+
cached_tokens: preserveReportedness
|
|
1209
|
+
? accounting?.cachedTokens ?? null : exactPrompt.cachedTokens,
|
|
1210
|
+
cost_usd: preserveReportedness && result.costReported !== true
|
|
1211
|
+
? null
|
|
1212
|
+
: result.total_cost_usd ?? null,
|
|
1102
1213
|
});
|
|
1103
1214
|
}
|
|
1104
1215
|
stream.push({
|
|
1105
1216
|
type: 'turn_complete',
|
|
1106
|
-
numTurns: result.num_turns ?? 0,
|
|
1217
|
+
numTurns: preserveReportedness ? result.num_turns : result.num_turns ?? 0,
|
|
1107
1218
|
totalCostUsd: result.total_cost_usd ?? null,
|
|
1108
1219
|
});
|
|
1220
|
+
stream.close();
|
|
1109
1221
|
return result;
|
|
1110
1222
|
}
|
|
1111
1223
|
catch (err) {
|
|
@@ -1157,6 +1269,7 @@ export class ClaudeAdapter {
|
|
|
1157
1269
|
files,
|
|
1158
1270
|
onEvent: (ev) => stream.push(ev),
|
|
1159
1271
|
});
|
|
1272
|
+
stream.close();
|
|
1160
1273
|
// TuiAgentResult shape lines up with AgentResult — only structural cast needed.
|
|
1161
1274
|
return tuiResult;
|
|
1162
1275
|
}
|
|
@@ -1244,6 +1357,7 @@ function makeSessionForTest(modelName = null, autoCompactWindow = null) {
|
|
|
1244
1357
|
s.streamDeltaState = createStreamDeltaState();
|
|
1245
1358
|
s.contextUsageTracker = new ClaudeContextUsageTracker(modelName, autoCompactWindow);
|
|
1246
1359
|
s.continuationSink = null;
|
|
1360
|
+
s.pendingContinuationDeliveries = [];
|
|
1247
1361
|
s.pendingInjections = [];
|
|
1248
1362
|
s.injectionAck = null;
|
|
1249
1363
|
s.injectionContinuationArmed = false;
|
|
@@ -1252,6 +1366,7 @@ function makeSessionForTest(modelName = null, autoCompactWindow = null) {
|
|
|
1252
1366
|
s.turnIdleTimer = null;
|
|
1253
1367
|
s.maxTimer = null;
|
|
1254
1368
|
s.cumulativeCostUsd = 0;
|
|
1369
|
+
s.preserveUnreportedAccounting = false;
|
|
1255
1370
|
s.lastTokenUsage = null;
|
|
1256
1371
|
s.lastModelName = null;
|
|
1257
1372
|
s.alive = true;
|