@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
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentProcess } from './types.js';
|
|
2
|
+
import type { NormalizedEvent } from './normalize/event-types.js';
|
|
3
|
+
export interface EventObserver {
|
|
4
|
+
onEvent(event: NormalizedEvent): void;
|
|
5
|
+
onClose?(): void | Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export interface RunEventTee {
|
|
8
|
+
dispatch(event: NormalizedEvent): void;
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export declare function createRunEventTee(proc: AgentProcess, observers: EventObserver[], requiredSinks: EventObserver[]): RunEventTee;
|
|
12
|
+
export declare function createProcessCloser(proc: AgentProcess): () => Promise<void>;
|
|
13
|
+
export declare function settleEventfulRun<T>(resultPromise: Promise<T>, eventLoop: Promise<void>, closeTee: () => Promise<void>, closeProcess: () => Promise<void>): Promise<T>;
|
|
14
|
+
export interface ConsumeEventStreamOptions {
|
|
15
|
+
proc: AgentProcess;
|
|
16
|
+
tee: RunEventTee;
|
|
17
|
+
onEvent(event: NormalizedEvent): void | Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export declare function consumeEventStream(options: ConsumeEventStreamOptions): Promise<void>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// input: normalized events, agent process, observers
|
|
2
|
+
// output: synchronous tee with required-sink failure propagation
|
|
3
|
+
// pos: Backend-neutral run event fan-out
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
import { createLogger } from '../core/log.js';
|
|
6
|
+
const log = createLogger('event-tee');
|
|
7
|
+
class TrajectoryWriteFailedError extends Error {
|
|
8
|
+
reason = 'trajectory_write_failed';
|
|
9
|
+
cause;
|
|
10
|
+
constructor(cause) {
|
|
11
|
+
super(`Required trajectory sink failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
12
|
+
this.name = 'TrajectoryWriteFailedError';
|
|
13
|
+
this.cause = cause;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function isRequiredFailure(error) {
|
|
17
|
+
return !!error && typeof error === 'object'
|
|
18
|
+
&& error.reason === 'trajectory_write_failed';
|
|
19
|
+
}
|
|
20
|
+
function dispatchObservers(observers, event) {
|
|
21
|
+
for (const observer of observers) {
|
|
22
|
+
try {
|
|
23
|
+
observer.onEvent(event);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
log.warn('run observer onEvent failed:', error?.message ?? error);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function dispatchRequiredSinks(sinks, event, proc) {
|
|
31
|
+
for (const sink of sinks) {
|
|
32
|
+
try {
|
|
33
|
+
sink.onEvent(event);
|
|
34
|
+
}
|
|
35
|
+
catch (cause) {
|
|
36
|
+
proc.kill();
|
|
37
|
+
throw new TrajectoryWriteFailedError(cause);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function closeObservers(observers) {
|
|
42
|
+
for (const observer of observers) {
|
|
43
|
+
try {
|
|
44
|
+
await observer.onClose?.();
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
log.warn('run observer onClose failed:', error?.message ?? error);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function closeRequiredSinks(sinks, proc) {
|
|
52
|
+
let failed = false;
|
|
53
|
+
let firstCause;
|
|
54
|
+
for (const sink of sinks) {
|
|
55
|
+
try {
|
|
56
|
+
await sink.onClose?.();
|
|
57
|
+
}
|
|
58
|
+
catch (cause) {
|
|
59
|
+
if (!failed)
|
|
60
|
+
firstCause = cause;
|
|
61
|
+
failed = true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (!failed)
|
|
65
|
+
return;
|
|
66
|
+
proc.kill();
|
|
67
|
+
throw new TrajectoryWriteFailedError(firstCause);
|
|
68
|
+
}
|
|
69
|
+
export function createRunEventTee(proc, observers, requiredSinks) {
|
|
70
|
+
let closed = false;
|
|
71
|
+
return {
|
|
72
|
+
dispatch(event) {
|
|
73
|
+
dispatchObservers(observers, event);
|
|
74
|
+
dispatchRequiredSinks(requiredSinks, event, proc);
|
|
75
|
+
},
|
|
76
|
+
async close() {
|
|
77
|
+
if (closed)
|
|
78
|
+
return;
|
|
79
|
+
closed = true;
|
|
80
|
+
await closeObservers(observers);
|
|
81
|
+
await closeRequiredSinks(requiredSinks, proc);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export function createProcessCloser(proc) {
|
|
86
|
+
let closed = false;
|
|
87
|
+
return async () => {
|
|
88
|
+
if (closed)
|
|
89
|
+
return;
|
|
90
|
+
closed = true;
|
|
91
|
+
await proc.close().catch(() => { });
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export async function settleEventfulRun(resultPromise, eventLoop, closeTee, closeProcess) {
|
|
95
|
+
let result;
|
|
96
|
+
let failed = false;
|
|
97
|
+
let failure;
|
|
98
|
+
try {
|
|
99
|
+
[result] = await Promise.all([resultPromise, eventLoop]);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
failed = true;
|
|
103
|
+
failure = error;
|
|
104
|
+
await closeProcess();
|
|
105
|
+
try {
|
|
106
|
+
await eventLoop;
|
|
107
|
+
}
|
|
108
|
+
catch (eventError) {
|
|
109
|
+
failure = eventError;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
await closeTee();
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
failed = true;
|
|
117
|
+
failure = error;
|
|
118
|
+
}
|
|
119
|
+
await closeProcess();
|
|
120
|
+
if (failed)
|
|
121
|
+
throw failure;
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
export async function consumeEventStream(options) {
|
|
125
|
+
let legacyFailed = false;
|
|
126
|
+
try {
|
|
127
|
+
for await (const event of options.proc.events) {
|
|
128
|
+
options.tee.dispatch(event);
|
|
129
|
+
if (legacyFailed)
|
|
130
|
+
continue;
|
|
131
|
+
try {
|
|
132
|
+
await options.onEvent(event);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
legacyFailed = true;
|
|
136
|
+
log.warn('legacy event callback failed:', error?.message ?? error);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (isRequiredFailure(error))
|
|
142
|
+
throw error;
|
|
143
|
+
log.warn('event stream consumer failed:', error?.message ?? error);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -5,4 +5,5 @@ export * from './normalize/event-types.js';
|
|
|
5
5
|
export * from './normalize/hooks.js';
|
|
6
6
|
export * from './normalize/tool-names.js';
|
|
7
7
|
export declare function getAdapter(backend: Backend): AgentAdapter;
|
|
8
|
+
export declare function registerPISessionPath(sessionId: string, sessionPath: string): void;
|
|
8
9
|
export declare function closeAllAdapters(): Promise<void>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// input: backend
|
|
2
|
-
// output:
|
|
1
|
+
// input: backend labels and restored PI transcript paths
|
|
2
|
+
// output: adapter lookup, PI path registration, public re-exports
|
|
3
3
|
// pos: Unified entry point for the Agent adapter system
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { ClaudeAdapter } from './claude/adapter.js';
|
|
@@ -9,9 +9,10 @@ export * from './capabilities.js';
|
|
|
9
9
|
export * from './normalize/event-types.js';
|
|
10
10
|
export * from './normalize/hooks.js';
|
|
11
11
|
export * from './normalize/tool-names.js';
|
|
12
|
+
const PI_ADAPTER = new PIAdapter();
|
|
12
13
|
const ADAPTERS = {
|
|
13
14
|
claude: new ClaudeAdapter(),
|
|
14
|
-
pi:
|
|
15
|
+
pi: PI_ADAPTER,
|
|
15
16
|
};
|
|
16
17
|
export function getAdapter(backend) {
|
|
17
18
|
const adapter = ADAPTERS[backend];
|
|
@@ -19,6 +20,9 @@ export function getAdapter(backend) {
|
|
|
19
20
|
throw new Error(`Unknown backend: ${backend}`);
|
|
20
21
|
return adapter;
|
|
21
22
|
}
|
|
23
|
+
export function registerPISessionPath(sessionId, sessionPath) {
|
|
24
|
+
PI_ADAPTER.registerSessionPath(sessionId, sessionPath);
|
|
25
|
+
}
|
|
22
26
|
export async function closeAllAdapters() {
|
|
23
27
|
for (const adapter of Object.values(ADAPTERS)) {
|
|
24
28
|
for (const key of adapter.listSessions()) {
|
|
@@ -4,6 +4,19 @@ export interface QuestionSpec {
|
|
|
4
4
|
multi?: boolean;
|
|
5
5
|
options?: string[];
|
|
6
6
|
}
|
|
7
|
+
interface CostRecordEvent {
|
|
8
|
+
type: 'cost_record';
|
|
9
|
+
provider: string;
|
|
10
|
+
model: string;
|
|
11
|
+
/** Claude input_tokens + cache_creation_input_tokens + cache_read_input_tokens; null if underivable. */
|
|
12
|
+
tokens_in: number | null;
|
|
13
|
+
tokens_out: number | null;
|
|
14
|
+
/** The same Claude prompt total, retained for aggregate metrics. */
|
|
15
|
+
prompt_tokens?: number | null;
|
|
16
|
+
/** Claude cache-read tokens; cache creation remains prompt-only. */
|
|
17
|
+
cached_tokens?: number | null;
|
|
18
|
+
cost_usd: number | null;
|
|
19
|
+
}
|
|
7
20
|
export type NormalizedEvent = {
|
|
8
21
|
type: 'session_started';
|
|
9
22
|
sessionId: string;
|
|
@@ -12,6 +25,7 @@ export type NormalizedEvent = {
|
|
|
12
25
|
type: 'assistant_text';
|
|
13
26
|
text: string;
|
|
14
27
|
blockId?: string;
|
|
28
|
+
model?: string | null;
|
|
15
29
|
} | {
|
|
16
30
|
type: 'assistant_delta';
|
|
17
31
|
text: string;
|
|
@@ -48,19 +62,12 @@ export type NormalizedEvent = {
|
|
|
48
62
|
} & ContextUsage) | {
|
|
49
63
|
type: 'rate_limit';
|
|
50
64
|
raw: unknown;
|
|
51
|
-
} | {
|
|
52
|
-
type: 'cost_record';
|
|
53
|
-
provider: string;
|
|
54
|
-
model: string;
|
|
55
|
-
tokens_in: number;
|
|
56
|
-
tokens_out: number;
|
|
57
|
-
cost_usd: number | null;
|
|
58
|
-
} | {
|
|
65
|
+
} | CostRecordEvent | {
|
|
59
66
|
type: 'turn_progress';
|
|
60
67
|
numTurns: number;
|
|
61
68
|
} | {
|
|
62
69
|
type: 'turn_complete';
|
|
63
|
-
numTurns: number;
|
|
70
|
+
numTurns: number | null;
|
|
64
71
|
totalCostUsd: number | null;
|
|
65
72
|
error?: string | null;
|
|
66
73
|
} | {
|
|
@@ -68,3 +75,4 @@ export type NormalizedEvent = {
|
|
|
68
75
|
message: string;
|
|
69
76
|
fatal: boolean;
|
|
70
77
|
};
|
|
78
|
+
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output: NormalizedEvent
|
|
3
|
-
// pos:
|
|
4
|
-
// >>>
|
|
1
|
+
// input: core agent types
|
|
2
|
+
// output: NormalizedEvent with documented accounting fields
|
|
3
|
+
// pos: Backend-neutral event schema
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
export {};
|
|
@@ -1,20 +1,32 @@
|
|
|
1
1
|
import { Capability } from '../capabilities.js';
|
|
2
|
-
import type { AgentAdapter, AgentSpawnConfig, Backend } from '../types.js';
|
|
2
|
+
import type { AgentAdapter, AgentSpawnConfig, Backend, McpComposition } from '../types.js';
|
|
3
|
+
import { type PIProviderDiscovery } from './discovery.js';
|
|
3
4
|
import { type PIAgentProcess, type SpawnFn, type SwitchResult } from './session-support.js';
|
|
4
5
|
export type { PIAgentProcess } from './session-support.js';
|
|
6
|
+
type UnsupportedPiMcpComposition = Extract<McpComposition, 'none' | 'benchmark-thread-run'>;
|
|
7
|
+
export declare class UnsupportedMcpCompositionError extends Error {
|
|
8
|
+
readonly composition: UnsupportedPiMcpComposition;
|
|
9
|
+
readonly name = "UnsupportedMcpCompositionError";
|
|
10
|
+
constructor(composition: UnsupportedPiMcpComposition);
|
|
11
|
+
}
|
|
5
12
|
export declare class PIAdapter implements AgentAdapter {
|
|
6
13
|
readonly backend: Backend;
|
|
7
14
|
readonly capabilities: Set<Capability>;
|
|
8
15
|
private readonly sessions;
|
|
9
16
|
private readonly spawner;
|
|
17
|
+
private readonly providerDiscovery;
|
|
18
|
+
private readonly configuredProviderOverrides;
|
|
10
19
|
private readonly sessionPathRegistry;
|
|
11
20
|
/** sessionDir for the <sessionId>.jsonl path convention. Exposed for tests. */
|
|
12
21
|
readonly sessionDir: string;
|
|
13
|
-
constructor(spawner?: SpawnFn, sessionDir?: string);
|
|
22
|
+
constructor(spawner?: SpawnFn, sessionDir?: string, providerDiscovery?: PIProviderDiscovery);
|
|
23
|
+
private gatewayOverrides;
|
|
14
24
|
spawn(config: AgentSpawnConfig): PIAgentProcess;
|
|
25
|
+
/** Record the exact transcript path restored by rewind before the next resume spawn. */
|
|
26
|
+
registerSessionPath(sessionId: string, sessionPath: string): void;
|
|
15
27
|
/**
|
|
16
|
-
* Resolve
|
|
17
|
-
*
|
|
28
|
+
* Resolve an existing JSONL path from the live registry or filename-only disk discovery.
|
|
29
|
+
* Stale and synthesized registry entries are evicted before discovery.
|
|
18
30
|
*/
|
|
19
31
|
resolveSessionPath(sessionId: string): string | null;
|
|
20
32
|
/**
|
|
@@ -1,22 +1,38 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output:
|
|
3
|
-
// pos: PI
|
|
4
|
-
// >>>
|
|
1
|
+
// input: spawn config, provider cache, spawner, settings
|
|
2
|
+
// output: PI sessions, resume path registry, events and compact
|
|
3
|
+
// pos: PI backend adapter
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { spawn as defaultSpawn } from 'child_process';
|
|
6
|
-
import { mkdirSync } from 'fs';
|
|
6
|
+
import { existsSync, mkdirSync } from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import { DATA_DIR } from '../../core/utils.js';
|
|
9
9
|
import { createLogger } from '../../core/log.js';
|
|
10
|
+
import { getSettings } from '../../core/settings.js';
|
|
10
11
|
import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
|
|
12
|
+
import { resolveMcpComposition } from '../types.js';
|
|
11
13
|
import { buildPiEnv, buildSpawnArgs } from './spawn-args.js';
|
|
12
14
|
import { createLineSplitter, encodeCommand } from './framing.js';
|
|
13
15
|
import { piRpcLineToNormalized, createPIEventParserState, piContextUsageFromStats } from './event-parser.js';
|
|
14
|
-
import { PI_AGENT_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible } from './agent-dir.js';
|
|
16
|
+
import { PI_AGENT_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible, } from './agent-dir.js';
|
|
15
17
|
import { fromCanonical } from '../normalize/tool-names.js';
|
|
16
|
-
import {
|
|
18
|
+
import { piProviderDiscovery, findPISessionFilePath, } from './discovery.js';
|
|
17
19
|
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
20
|
import { DEFAULT_SESSION_DIR, HOOK_BRIDGE_PATH, MCP_BRIDGE_PATH, TOOL_SHIMS_PATH } from './defaults.js';
|
|
19
21
|
const log = createLogger('pi-adapter');
|
|
22
|
+
export class UnsupportedMcpCompositionError extends Error {
|
|
23
|
+
composition;
|
|
24
|
+
name = 'UnsupportedMcpCompositionError';
|
|
25
|
+
constructor(composition) {
|
|
26
|
+
super(`PI backend does not support MCP composition: ${composition}`);
|
|
27
|
+
this.composition = composition;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function assertSupportedMcpComposition(config) {
|
|
31
|
+
const composition = resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp);
|
|
32
|
+
if (composition === 'none' || composition === 'benchmark-thread-run') {
|
|
33
|
+
throw new UnsupportedMcpCompositionError(composition);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
20
36
|
function record(value) {
|
|
21
37
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
22
38
|
? value
|
|
@@ -114,7 +130,7 @@ class PISession {
|
|
|
114
130
|
this.registry = opts.registry;
|
|
115
131
|
this.registrySessionDir = opts.registrySessionDir;
|
|
116
132
|
this.onClose = opts.onClose;
|
|
117
|
-
this.streamDeltas =
|
|
133
|
+
this.streamDeltas = getSettings().streamDeltas;
|
|
118
134
|
this.proc = opts.spawner(DEFAULT_PI_BINARY, opts.cliArgs, {
|
|
119
135
|
cwd: opts.cwd,
|
|
120
136
|
env: opts.env,
|
|
@@ -539,6 +555,8 @@ class PISession {
|
|
|
539
555
|
if (evt.type !== 'assistant_text') {
|
|
540
556
|
this.flushTextBuffer();
|
|
541
557
|
this.events.push(evt);
|
|
558
|
+
if (evt.type === 'turn_complete')
|
|
559
|
+
this.events.close();
|
|
542
560
|
return;
|
|
543
561
|
}
|
|
544
562
|
const blockId = evt.blockId ?? null;
|
|
@@ -728,42 +746,45 @@ export class PIAdapter {
|
|
|
728
746
|
capabilities = CAPABILITIES_BY_BACKEND.pi;
|
|
729
747
|
sessions = new Map();
|
|
730
748
|
spawner;
|
|
749
|
+
providerDiscovery;
|
|
750
|
+
configuredProviderOverrides = new Map();
|
|
731
751
|
sessionPathRegistry = new Map();
|
|
732
752
|
/** sessionDir for the <sessionId>.jsonl path convention. Exposed for tests. */
|
|
733
753
|
sessionDir;
|
|
734
|
-
constructor(spawner = defaultSpawn, sessionDir = DEFAULT_SESSION_DIR) {
|
|
754
|
+
constructor(spawner = defaultSpawn, sessionDir = DEFAULT_SESSION_DIR, providerDiscovery = piProviderDiscovery) {
|
|
735
755
|
this.spawner = spawner;
|
|
736
756
|
this.sessionDir = sessionDir;
|
|
757
|
+
this.providerDiscovery = providerDiscovery;
|
|
758
|
+
}
|
|
759
|
+
gatewayOverrides(discovered, currentProvider, gatewayPath) {
|
|
760
|
+
if (currentProvider) {
|
|
761
|
+
const [current] = buildProviderOverrides([], currentProvider, gatewayPath);
|
|
762
|
+
this.configuredProviderOverrides.set(currentProvider, current);
|
|
763
|
+
}
|
|
764
|
+
const byName = new Map(buildProviderOverrides(discovered, null, null).map((override) => [override.name, override]));
|
|
765
|
+
for (const override of this.configuredProviderOverrides.values())
|
|
766
|
+
byName.set(override.name, override);
|
|
767
|
+
return Array.from(byName.values());
|
|
737
768
|
}
|
|
738
769
|
spawn(config) {
|
|
770
|
+
assertSupportedMcpComposition(config);
|
|
739
771
|
const sessionDir = this.sessionDir;
|
|
740
772
|
mkdirSync(sessionDir, { recursive: true });
|
|
741
|
-
//
|
|
742
|
-
//
|
|
743
|
-
//
|
|
744
|
-
//
|
|
745
|
-
//
|
|
746
|
-
// The sessionPathRegistry is populated below from the bootstrap session_started
|
|
747
|
-
// event for switchSession / sendTurn path lookups — it is NOT used for the
|
|
748
|
-
// --session CLI flag here.
|
|
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).
|
|
773
|
+
// Resolve the backend id to one exact path before spawn and pass that path to --session.
|
|
774
|
+
// PI therefore opens the selected transcript directly instead of scanning session bodies.
|
|
775
|
+
// The live registry carries PI's authoritative sessionFile; after restart, deterministic
|
|
776
|
+
// filename lookup prefers the canonical id form, then the newest timestamp-prefixed form.
|
|
777
|
+
// A missing target starts fresh because PI cannot create an externally assigned session id.
|
|
757
778
|
const wantResume = !!(config.resume && config.sessionId);
|
|
758
|
-
const
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
if (wantResume &&
|
|
779
|
+
const sessionPathForSpawn = wantResume
|
|
780
|
+
? this.resolveSessionPath(config.sessionId)
|
|
781
|
+
: null;
|
|
782
|
+
if (wantResume && sessionPathForSpawn === null) {
|
|
762
783
|
log.info(`PI resume target '${config.sessionId}' not found (no live session or file in ${sessionDir}); starting fresh`);
|
|
763
784
|
}
|
|
764
785
|
const cliArgs = buildSpawnArgs({
|
|
765
786
|
sessionDir,
|
|
766
|
-
|
|
787
|
+
sessionPath: sessionPathForSpawn,
|
|
767
788
|
model: config.model ?? null,
|
|
768
789
|
provider: config.piProvider ?? null,
|
|
769
790
|
systemPrompt: config.systemPrompt ?? null,
|
|
@@ -792,8 +813,8 @@ export class PIAdapter {
|
|
|
792
813
|
// uses (config.piProvider). The current provider is always routed through the gateway even
|
|
793
814
|
// when discovery doesn't list it (e.g. an anthropic-protocol relay whose key the gateway
|
|
794
815
|
// injects). config.piGatewayPath, when set, decouples the gateway route from the provider name.
|
|
795
|
-
const discovered =
|
|
796
|
-
const overrides =
|
|
816
|
+
const discovered = this.providerDiscovery.getProviders();
|
|
817
|
+
const overrides = this.gatewayOverrides(discovered, config.piProvider ?? null, config.piGatewayPath ?? null);
|
|
797
818
|
if (overrides.length > 0) {
|
|
798
819
|
writeProvidersConfig(overrides, config.piGatewayBaseUrl);
|
|
799
820
|
}
|
|
@@ -852,7 +873,7 @@ export class PIAdapter {
|
|
|
852
873
|
session.beginTurn(resolve, reject);
|
|
853
874
|
const targetId = session.sessionId;
|
|
854
875
|
if (targetId !== null) {
|
|
855
|
-
const targetPath = this.
|
|
876
|
+
const targetPath = this.resolveSessionPath(targetId);
|
|
856
877
|
// sendTurn errors (e.g. switch_session timeout) surface via the events stream
|
|
857
878
|
// as a fatal error event, which will reject pendingTurn. The catch here is a
|
|
858
879
|
// belt-and-suspenders guard for programming errors in sendTurn itself.
|
|
@@ -887,12 +908,24 @@ export class PIAdapter {
|
|
|
887
908
|
},
|
|
888
909
|
};
|
|
889
910
|
}
|
|
911
|
+
/** Record the exact transcript path restored by rewind before the next resume spawn. */
|
|
912
|
+
registerSessionPath(sessionId, sessionPath) {
|
|
913
|
+
this.sessionPathRegistry.set(sessionId, sessionPath);
|
|
914
|
+
}
|
|
890
915
|
/**
|
|
891
|
-
* Resolve
|
|
892
|
-
*
|
|
916
|
+
* Resolve an existing JSONL path from the live registry or filename-only disk discovery.
|
|
917
|
+
* Stale and synthesized registry entries are evicted before discovery.
|
|
893
918
|
*/
|
|
894
919
|
resolveSessionPath(sessionId) {
|
|
895
|
-
|
|
920
|
+
const registered = this.sessionPathRegistry.get(sessionId);
|
|
921
|
+
if (registered && existsSync(registered))
|
|
922
|
+
return registered;
|
|
923
|
+
if (registered)
|
|
924
|
+
this.sessionPathRegistry.delete(sessionId);
|
|
925
|
+
const discovered = findPISessionFilePath(this.sessionDir, sessionId);
|
|
926
|
+
if (discovered)
|
|
927
|
+
this.sessionPathRegistry.set(sessionId, discovered);
|
|
928
|
+
return discovered;
|
|
896
929
|
}
|
|
897
930
|
/**
|
|
898
931
|
* Switch an existing subprocess (identified by onSessionKey) to serve a different PI session.
|
|
@@ -1,4 +1,20 @@
|
|
|
1
|
+
export declare const PI_PROVIDER_CACHE_TTL_MS: number;
|
|
2
|
+
export declare const PI_PROVIDER_RETRY_MS = 30000;
|
|
3
|
+
type ProviderScan = () => Promise<string[]>;
|
|
4
|
+
export interface PIProviderDiscovery {
|
|
5
|
+
getProviders(): string[];
|
|
6
|
+
refresh(): void;
|
|
7
|
+
}
|
|
8
|
+
export interface PIProviderDiscoveryOptions {
|
|
9
|
+
scan?: ProviderScan;
|
|
10
|
+
now?: () => number;
|
|
11
|
+
cacheTtlMs?: number;
|
|
12
|
+
retryMs?: number;
|
|
13
|
+
}
|
|
1
14
|
/** Discover authenticated PI providers without inheriting Cortex's private agent directory. */
|
|
2
|
-
export declare function discoverPIProviders(): string[]
|
|
3
|
-
|
|
4
|
-
export declare
|
|
15
|
+
export declare function discoverPIProviders(): Promise<string[]>;
|
|
16
|
+
export declare function createPIProviderDiscovery(options?: PIProviderDiscoveryOptions): PIProviderDiscovery;
|
|
17
|
+
export declare const piProviderDiscovery: PIProviderDiscovery;
|
|
18
|
+
/** Resolve PI's exact id-bearing filename without opening transcript bodies. */
|
|
19
|
+
export declare function findPISessionFilePath(sessionDir: string, sessionId: string): string | null;
|
|
20
|
+
export {};
|
|
@@ -1,63 +1,101 @@
|
|
|
1
|
-
// input: PI
|
|
2
|
-
// output:
|
|
3
|
-
// pos: PI
|
|
4
|
-
// >>>
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
// input: PI model table, refresh requests, session filenames
|
|
2
|
+
// output: refreshable provider cache and filename session lookup
|
|
3
|
+
// pos: PI provider and resume-target discovery
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
import { execFile } from 'child_process';
|
|
6
|
+
import { readdirSync } from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
|
|
9
|
+
import { selectPISessionFilename } from '../../core/pi-session-filename.js';
|
|
9
10
|
import { createLogger } from '../../core/log.js';
|
|
10
11
|
const log = createLogger('pi-adapter');
|
|
12
|
+
export const PI_PROVIDER_CACHE_TTL_MS = 5 * 60_000;
|
|
13
|
+
export const PI_PROVIDER_RETRY_MS = 30_000;
|
|
11
14
|
/** Discover authenticated PI providers without inheriting Cortex's private agent directory. */
|
|
12
15
|
export function discoverPIProviders() {
|
|
13
|
-
|
|
14
|
-
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
execFile('pi', ['--list-models'], {
|
|
15
18
|
timeout: 10_000,
|
|
16
19
|
encoding: 'utf-8',
|
|
17
20
|
env: { ...process.env, PI_CODING_AGENT_DIR: '' },
|
|
21
|
+
}, (error, stdout, stderr) => {
|
|
22
|
+
if (error) {
|
|
23
|
+
reject(error);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const models = parsePiListModelsOutput(`${stdout}\n${stderr}`);
|
|
27
|
+
resolve(Array.from(new Set(models.map((model) => model.provider))));
|
|
18
28
|
});
|
|
19
|
-
|
|
20
|
-
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
class CachedPIProviderDiscovery {
|
|
32
|
+
scan;
|
|
33
|
+
now;
|
|
34
|
+
cacheTtlMs;
|
|
35
|
+
retryMs;
|
|
36
|
+
providers = [];
|
|
37
|
+
nextRefreshAt = 0;
|
|
38
|
+
inFlight = null;
|
|
39
|
+
refreshQueued = false;
|
|
40
|
+
constructor(scan, now, cacheTtlMs, retryMs) {
|
|
41
|
+
this.scan = scan;
|
|
42
|
+
this.now = now;
|
|
43
|
+
this.cacheTtlMs = cacheTtlMs;
|
|
44
|
+
this.retryMs = retryMs;
|
|
21
45
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
46
|
+
getProviders() {
|
|
47
|
+
const snapshot = [...this.providers];
|
|
48
|
+
if (this.now() >= this.nextRefreshAt && !this.inFlight)
|
|
49
|
+
this.startRefresh();
|
|
50
|
+
return snapshot;
|
|
25
51
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
try {
|
|
33
|
-
files = readdirSync(sessionDir).filter((file) => file.endsWith('.jsonl'));
|
|
52
|
+
refresh() {
|
|
53
|
+
if (!this.inFlight) {
|
|
54
|
+
this.startRefresh();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
this.refreshQueued = true;
|
|
34
58
|
}
|
|
35
|
-
|
|
36
|
-
|
|
59
|
+
startRefresh() {
|
|
60
|
+
const refresh = Promise.resolve()
|
|
61
|
+
.then(this.scan)
|
|
62
|
+
.then((providers) => this.accept(providers))
|
|
63
|
+
.catch((error) => this.reject(error))
|
|
64
|
+
.finally(() => this.finishRefresh(refresh));
|
|
65
|
+
this.inFlight = refresh;
|
|
37
66
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
67
|
+
finishRefresh(refresh) {
|
|
68
|
+
if (this.inFlight !== refresh)
|
|
69
|
+
return;
|
|
70
|
+
this.inFlight = null;
|
|
71
|
+
if (!this.refreshQueued)
|
|
72
|
+
return;
|
|
73
|
+
this.refreshQueued = false;
|
|
74
|
+
this.startRefresh();
|
|
75
|
+
}
|
|
76
|
+
accept(providers) {
|
|
77
|
+
this.providers = Array.from(new Set(providers));
|
|
78
|
+
this.nextRefreshAt = this.now() + this.cacheTtlMs;
|
|
79
|
+
}
|
|
80
|
+
reject(error) {
|
|
81
|
+
this.nextRefreshAt = this.now() + this.retryMs;
|
|
82
|
+
const message = error instanceof Error ? error.message : 'unknown';
|
|
83
|
+
log.info(`pi --list-models refresh failed: ${message}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function createPIProviderDiscovery(options = {}) {
|
|
87
|
+
return new CachedPIProviderDiscovery(options.scan ?? discoverPIProviders, options.now ?? Date.now, options.cacheTtlMs ?? PI_PROVIDER_CACHE_TTL_MS, options.retryMs ?? PI_PROVIDER_RETRY_MS);
|
|
41
88
|
}
|
|
42
|
-
|
|
43
|
-
|
|
89
|
+
export const piProviderDiscovery = createPIProviderDiscovery();
|
|
90
|
+
/** Resolve PI's exact id-bearing filename without opening transcript bodies. */
|
|
91
|
+
export function findPISessionFilePath(sessionDir, sessionId) {
|
|
92
|
+
if (!sessionId)
|
|
93
|
+
return null;
|
|
44
94
|
try {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const bytes = readSync(fd, buffer, 0, buffer.length, 0);
|
|
48
|
-
const firstLine = buffer.toString('utf8', 0, bytes).split('\n', 1)[0];
|
|
49
|
-
const header = JSON.parse(firstLine);
|
|
50
|
-
return header.id === sessionId || header.sessionId === sessionId;
|
|
95
|
+
const filename = selectPISessionFilename(readdirSync(sessionDir), sessionId);
|
|
96
|
+
return filename ? path.join(sessionDir, filename) : null;
|
|
51
97
|
}
|
|
52
98
|
catch {
|
|
53
|
-
return
|
|
54
|
-
}
|
|
55
|
-
finally {
|
|
56
|
-
if (fd !== null) {
|
|
57
|
-
try {
|
|
58
|
-
closeSync(fd);
|
|
59
|
-
}
|
|
60
|
-
catch { /* ignore close failure after a read attempt */ }
|
|
61
|
-
}
|
|
99
|
+
return null;
|
|
62
100
|
}
|
|
63
101
|
}
|