@cortex-agent/server 2026.7.30 → 2026.8.3-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.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/core/utils.d.ts +21 -1
- package/dist/core/utils.js +37 -1
- 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-hot-reload.d.ts +9 -1
- package/dist/domain/remote/client-hot-reload.js +60 -12
- 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/install-cli.js +8 -3
- 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-XqBCYtkw.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,17 +1,21 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output: attributed runs
|
|
3
|
-
// pos: Backend-neutral agent
|
|
1
|
+
// input: run config, adapters, profiles, task/cost events
|
|
2
|
+
// output: attributed runs with exact continuation accounting
|
|
3
|
+
// pos: Backend-neutral agent run facade
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
-
import { getAdapter } from '../../agent-adapter/index.js';
|
|
6
|
-
import { shouldAwaitBgInline, waitForBgContinuation } from '../../agent-adapter/bg-wait.js';
|
|
5
|
+
import { getAdapter, resolveMcpComposition } from '../../agent-adapter/index.js';
|
|
6
|
+
import { canAwaitBgContinuation, shouldAwaitBgInline, waitForBgContinuation, } from '../../agent-adapter/bg-wait.js';
|
|
7
|
+
import { consumeEventStream, createProcessCloser, createRunEventTee, settleEventfulRun, } from '../../agent-adapter/event-tee.js';
|
|
7
8
|
import { resolveProfileConfig } from './profile-manager.js';
|
|
8
9
|
import { recordCost } from '../costs/cost-tracker.js';
|
|
9
10
|
import { configureEnvForMode, isApiRateLimitError, isRetryableResult, isRetryableError } from './config.js';
|
|
10
|
-
import {
|
|
11
|
+
import { isProviderRateLimited, isThrottled } from '../costs/rate-limit-throttle.js';
|
|
11
12
|
import { GATEWAY_URL } from '../costs/gateway-manager.js';
|
|
12
13
|
import { createLogger } from '../../core/log.js';
|
|
14
|
+
import { getSettings } from '../../core/settings.js';
|
|
13
15
|
import { loadCortexRules } from '../memory/rules-loader.js';
|
|
16
|
+
import { configIsRateLimited, rateLimitedResult, resolveRateLimitProvider, withAuthLifecycle, withRateLimitProvider, } from './provider-run-lifecycle.js';
|
|
14
17
|
import { t } from '../../core/i18n.js';
|
|
18
|
+
export { resolveRateLimitProvider };
|
|
15
19
|
const log = createLogger('facade');
|
|
16
20
|
function assistantNoticeLevel(text) {
|
|
17
21
|
return text.startsWith('API Error:') ? 'error' : undefined;
|
|
@@ -92,35 +96,6 @@ class AttemptNoticeTracker {
|
|
|
92
96
|
this.emitTerminal(t('status.rateLimitedExhausted'), t('status.rateLimitedExhausted'));
|
|
93
97
|
}
|
|
94
98
|
}
|
|
95
|
-
const DEFAULT_PROVIDER_BY_BACKEND = {
|
|
96
|
-
claude: 'anthropic',
|
|
97
|
-
};
|
|
98
|
-
export function resolveRateLimitProvider(config) {
|
|
99
|
-
return config.provider || DEFAULT_PROVIDER_BY_BACKEND[config.backend] || config.backend;
|
|
100
|
-
}
|
|
101
|
-
function withRateLimitProvider(handle, provider) {
|
|
102
|
-
return {
|
|
103
|
-
promise: handle.promise.then((result) => ({ ...result, rateLimitProvider: result.rateLimitProvider || provider }), (error) => {
|
|
104
|
-
if (isRetryableError(error)) {
|
|
105
|
-
error.rateLimitProvider ??= provider;
|
|
106
|
-
}
|
|
107
|
-
throw error;
|
|
108
|
-
}),
|
|
109
|
-
kill: () => handle.kill(),
|
|
110
|
-
get sessionId() { return handle.sessionId ?? null; },
|
|
111
|
-
get agentProcess() { return handle.agentProcess; },
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
function configIsRateLimited(config) {
|
|
115
|
-
return isProviderModeRateLimited(resolveRateLimitProvider(config), config.mode || 'api');
|
|
116
|
-
}
|
|
117
|
-
function rateLimitedResult(mode, provider) {
|
|
118
|
-
return {
|
|
119
|
-
sessionId: null, total_cost_usd: null, num_turns: null,
|
|
120
|
-
rateLimited: true, rateLimitMessage: `Mode ${mode} is rate-limited`, rateLimitProvider: provider,
|
|
121
|
-
planFilePath: null, enteredPlanMode: false, exitedPlanMode: false, finalOutput: null,
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
99
|
function withTerminalNotices(handle, notices) {
|
|
125
100
|
let killed = false;
|
|
126
101
|
return {
|
|
@@ -182,7 +157,7 @@ export function filterChannelScopedPlugins(dirs, channel) {
|
|
|
182
157
|
});
|
|
183
158
|
}
|
|
184
159
|
// --- Adapter execution ---
|
|
185
|
-
function
|
|
160
|
+
export function buildAgentSpawnConfig(options, config, anthropicBaseUrl) {
|
|
186
161
|
// Pack the Cortex execution context only if at least one field is set, so adapters can
|
|
187
162
|
// skip writing CORTEX_* env vars / route-context fields when there's nothing to report.
|
|
188
163
|
const ctx = {
|
|
@@ -197,13 +172,16 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
|
197
172
|
threadDepth: options.threadDepth ?? null,
|
|
198
173
|
taskId: options.taskId ?? null,
|
|
199
174
|
taskProject: options.taskProject ?? null,
|
|
175
|
+
taskGeneration: options.taskGeneration ?? null,
|
|
200
176
|
};
|
|
201
|
-
const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.trackSessionId ||
|
|
177
|
+
const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.trackSessionId ||
|
|
178
|
+
ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null || ctx.taskId ||
|
|
179
|
+
ctx.taskProject || ctx.taskGeneration);
|
|
202
180
|
// Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
|
|
203
181
|
// Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
|
|
204
|
-
const rules = loadCortexRules();
|
|
205
|
-
const appendSystemPrompt = rules.
|
|
206
|
-
? rules.
|
|
182
|
+
const rules = options.loadCortexRules === false ? [] : loadCortexRules().global;
|
|
183
|
+
const appendSystemPrompt = rules.length > 0
|
|
184
|
+
? rules.map(rule => rule.body).join('\n\n---\n\n')
|
|
207
185
|
: undefined;
|
|
208
186
|
return {
|
|
209
187
|
sessionId: options.sessionId ?? null,
|
|
@@ -212,6 +190,14 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
|
212
190
|
model: config.model,
|
|
213
191
|
systemPrompt: typeof options.systemPrompt === 'string' ? options.systemPrompt : undefined,
|
|
214
192
|
outputStyle: typeof options.outputStyle === 'string' ? options.outputStyle : undefined,
|
|
193
|
+
cwd: options.cwd,
|
|
194
|
+
mcpComposition: resolveMcpComposition(options.mcpComposition, options.useCoreMcp),
|
|
195
|
+
mcpConfigPaths: options.mcpConfigPaths,
|
|
196
|
+
disableHooks: options.disableHooks,
|
|
197
|
+
streamDeltas: options.streamDeltas,
|
|
198
|
+
captureTranscriptLogs: options.captureTranscriptLogs,
|
|
199
|
+
preserveUnreportedAccounting: options.preserveUnreportedAccounting,
|
|
200
|
+
processSpawner: options.processSpawner,
|
|
215
201
|
pluginDirs: filterChannelScopedPlugins(Array.isArray(options.pluginDirs) ? options.pluginDirs : undefined, options.channel),
|
|
216
202
|
env: config.extraEnv && Object.keys(config.extraEnv).length > 0 ? config.extraEnv : undefined,
|
|
217
203
|
extraOption: config.extraOption && Object.keys(config.extraOption).length > 0 ? config.extraOption : undefined,
|
|
@@ -237,138 +223,155 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
|
237
223
|
appendSystemPrompt,
|
|
238
224
|
};
|
|
239
225
|
}
|
|
226
|
+
class LegacyEventDispatcher {
|
|
227
|
+
adapter;
|
|
228
|
+
options;
|
|
229
|
+
config;
|
|
230
|
+
spawnConfig;
|
|
231
|
+
active = true;
|
|
232
|
+
handlers;
|
|
233
|
+
constructor(adapter, options, config, spawnConfig) {
|
|
234
|
+
this.adapter = adapter;
|
|
235
|
+
this.options = options;
|
|
236
|
+
this.config = config;
|
|
237
|
+
this.spawnConfig = spawnConfig;
|
|
238
|
+
this.handlers = {
|
|
239
|
+
session_started: (event) => this.sessionStarted(event),
|
|
240
|
+
assistant_text: (event) => this.assistantText(event),
|
|
241
|
+
assistant_delta: (event) => this.assistantDelta(event),
|
|
242
|
+
tool_use: (event) => this.toolUse(event),
|
|
243
|
+
tool_result: (event) => this.toolResult(event),
|
|
244
|
+
turn_progress: (event) => this.turnProgress(event),
|
|
245
|
+
context_usage: (event) => this.contextUsage(event),
|
|
246
|
+
turn_complete: (event) => this.turnComplete(event),
|
|
247
|
+
cost_record: (event) => this.costRecord(event),
|
|
248
|
+
context_compacted: () => this.contextCompacted(),
|
|
249
|
+
plan_written: (event) => this.planWritten(event),
|
|
250
|
+
ask_user_question: (event) => this.askUserQuestion(event),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
async dispatch(event) {
|
|
254
|
+
if (!this.active)
|
|
255
|
+
return;
|
|
256
|
+
await this.handlers[event.type]?.(event);
|
|
257
|
+
}
|
|
258
|
+
sessionStarted(event) {
|
|
259
|
+
if (!this.options.channel?.startsWith('web:'))
|
|
260
|
+
return;
|
|
261
|
+
if (!this.spawnConfig.resume || !this.spawnConfig.sessionId)
|
|
262
|
+
return;
|
|
263
|
+
if (event.sessionId === this.spawnConfig.sessionId)
|
|
264
|
+
return;
|
|
265
|
+
this.options.onAssistantMessage?.(t('notify.backendSessionReset'), undefined, 'warning');
|
|
266
|
+
}
|
|
267
|
+
assistantText(event) {
|
|
268
|
+
this.options.onAssistantMessage?.(event.text, event.blockId, assistantNoticeLevel(event.text));
|
|
269
|
+
}
|
|
270
|
+
assistantDelta(event) {
|
|
271
|
+
this.options.onAssistantDelta?.(event.text, event.blockId);
|
|
272
|
+
}
|
|
273
|
+
toolUse(event) {
|
|
274
|
+
this.options.onToolUse?.(event.name, event.input, event.toolUseId);
|
|
275
|
+
}
|
|
276
|
+
toolResult(event) {
|
|
277
|
+
this.options.onToolResult?.(event.toolUseId, event.content, !event.ok);
|
|
278
|
+
}
|
|
279
|
+
progress(numTurns, totalCostUsd) {
|
|
280
|
+
this.options.onProgress?.({ num_turns: numTurns, total_cost_usd: totalCostUsd, duration_ms: null });
|
|
281
|
+
}
|
|
282
|
+
turnProgress(event) {
|
|
283
|
+
this.progress(event.numTurns, null);
|
|
284
|
+
}
|
|
285
|
+
async contextUsage(event) {
|
|
286
|
+
await this.options.onContextUsage?.({
|
|
287
|
+
usedTokens: event.usedTokens,
|
|
288
|
+
contextWindow: event.contextWindow,
|
|
289
|
+
percent: event.percent,
|
|
290
|
+
accuracy: event.accuracy,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
turnComplete(event) {
|
|
294
|
+
this.progress(event.numTurns, event.totalCostUsd);
|
|
295
|
+
this.active = false;
|
|
296
|
+
}
|
|
297
|
+
costRecord(event) {
|
|
298
|
+
if (this.options.recordCost === false)
|
|
299
|
+
return;
|
|
300
|
+
void recordCost({
|
|
301
|
+
project: this.options.project || 'general',
|
|
302
|
+
trigger: this.options.trigger || 'unknown',
|
|
303
|
+
cost_usd: event.cost_usd,
|
|
304
|
+
backend: this.adapter.backend,
|
|
305
|
+
mode: this.config.mode || 'api',
|
|
306
|
+
source: 'estimate',
|
|
307
|
+
input_tokens: event.tokens_in ?? 0,
|
|
308
|
+
output_tokens: event.tokens_out ?? 0,
|
|
309
|
+
provider: event.provider || undefined,
|
|
310
|
+
model: event.model || undefined,
|
|
311
|
+
}).catch(err => log.warn('recordCost failed:', err?.message ?? err));
|
|
312
|
+
}
|
|
313
|
+
contextCompacted() {
|
|
314
|
+
if (!this.options.onAssistantMessage)
|
|
315
|
+
return;
|
|
316
|
+
if (!getSettings().notifyCompaction)
|
|
317
|
+
return;
|
|
318
|
+
this.options.onAssistantMessage(t('notify.contextCompacted'), undefined, 'info');
|
|
319
|
+
}
|
|
320
|
+
planWritten(event) {
|
|
321
|
+
this.options.onPlanWritten?.({ path: event.path, content: event.content, toolUseId: event.toolUseId });
|
|
322
|
+
}
|
|
323
|
+
askUserQuestion(event) {
|
|
324
|
+
this.options.onAskUserQuestion?.({ toolUseId: event.toolUseId, questions: event.questions });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function shouldAwaitRunBackground(adapter, options, result, proc) {
|
|
328
|
+
const canRegisterSink = typeof proc.setContinuationSink === 'function';
|
|
329
|
+
if (options.awaitBackground === false)
|
|
330
|
+
return false;
|
|
331
|
+
if (options.awaitBackground === true) {
|
|
332
|
+
return canAwaitBgContinuation(adapter.backend, result, canRegisterSink);
|
|
333
|
+
}
|
|
334
|
+
return shouldAwaitBgInline(adapter.backend, options.threadId, result, canRegisterSink);
|
|
335
|
+
}
|
|
336
|
+
async function resolveRunResult(turnPromise, foregroundEventsDrained, adapter, options, proc, onContinuationEvent) {
|
|
337
|
+
const result = await turnPromise;
|
|
338
|
+
if (!shouldAwaitRunBackground(adapter, options, result, proc))
|
|
339
|
+
return result;
|
|
340
|
+
await foregroundEventsDrained;
|
|
341
|
+
log.info(`agent turn ${options.threadId ?? proc.sessionId ?? 'direct'} has background work remaining — waiting inline`);
|
|
342
|
+
const completionOnly = options.backgroundWaitPolicy === 'completion-only';
|
|
343
|
+
return waitForBgContinuation({
|
|
344
|
+
proc,
|
|
345
|
+
baseResult: result,
|
|
346
|
+
onAssistantText: options.onAssistantMessage ?? null,
|
|
347
|
+
onToolUse: options.onToolUse ?? null,
|
|
348
|
+
onToolResult: options.onToolResult ?? null,
|
|
349
|
+
onContextUsage: options.onContextUsage ?? null,
|
|
350
|
+
onEvent: onContinuationEvent,
|
|
351
|
+
completionOnly,
|
|
352
|
+
stopPromise: completionOnly ? proc.supervision?.closed : undefined,
|
|
353
|
+
});
|
|
354
|
+
}
|
|
240
355
|
export function runWithAdapter(adapter, message, options, config, anthropicBaseUrl) {
|
|
241
|
-
const spawnConfig =
|
|
356
|
+
const spawnConfig = options.preparedSpawnConfig
|
|
357
|
+
?? buildAgentSpawnConfig(options, config, anthropicBaseUrl);
|
|
242
358
|
const proc = adapter.spawn(spawnConfig);
|
|
243
|
-
const attachments = (options.files || []).map((
|
|
244
|
-
mimeType:
|
|
245
|
-
path:
|
|
359
|
+
const attachments = (options.files || []).map((file) => ({
|
|
360
|
+
mimeType: file.mimetype ?? file.mimeType,
|
|
361
|
+
path: file.localPath ?? file.path,
|
|
246
362
|
}));
|
|
247
363
|
const turnPromise = proc.send({ text: message, attachments });
|
|
248
|
-
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
const changedWebResume = options.channel?.startsWith('web:')
|
|
258
|
-
&& spawnConfig.resume
|
|
259
|
-
&& spawnConfig.sessionId
|
|
260
|
-
&& event.sessionId !== spawnConfig.sessionId;
|
|
261
|
-
if (changedWebResume) {
|
|
262
|
-
options.onAssistantMessage?.(t('notify.backendSessionReset'), undefined, 'warning');
|
|
263
|
-
}
|
|
264
|
-
break;
|
|
265
|
-
}
|
|
266
|
-
case 'assistant_text':
|
|
267
|
-
options.onAssistantMessage?.(event.text, event.blockId, assistantNoticeLevel(event.text));
|
|
268
|
-
break;
|
|
269
|
-
case 'assistant_delta':
|
|
270
|
-
// Token-level preview. Only surfaces where a caller opted in by passing the callback —
|
|
271
|
-
// Slack / Feishu / Ink-TUI pass none, so no partial text can reach OutputStream.
|
|
272
|
-
options.onAssistantDelta?.(event.text, event.blockId);
|
|
273
|
-
break;
|
|
274
|
-
case 'tool_use':
|
|
275
|
-
options.onToolUse?.(event.name, event.input, event.toolUseId);
|
|
276
|
-
break;
|
|
277
|
-
case 'tool_result':
|
|
278
|
-
options.onToolResult?.(event.toolUseId, event.content, !event.ok);
|
|
279
|
-
break;
|
|
280
|
-
case 'turn_progress':
|
|
281
|
-
options.onProgress?.({
|
|
282
|
-
num_turns: event.numTurns,
|
|
283
|
-
total_cost_usd: null,
|
|
284
|
-
duration_ms: null,
|
|
285
|
-
});
|
|
286
|
-
break;
|
|
287
|
-
case 'context_usage':
|
|
288
|
-
await options.onContextUsage?.({
|
|
289
|
-
usedTokens: event.usedTokens,
|
|
290
|
-
contextWindow: event.contextWindow,
|
|
291
|
-
percent: event.percent,
|
|
292
|
-
accuracy: event.accuracy,
|
|
293
|
-
});
|
|
294
|
-
break;
|
|
295
|
-
case 'turn_complete':
|
|
296
|
-
options.onProgress?.({
|
|
297
|
-
num_turns: event.numTurns,
|
|
298
|
-
total_cost_usd: event.totalCostUsd,
|
|
299
|
-
duration_ms: null,
|
|
300
|
-
});
|
|
301
|
-
return;
|
|
302
|
-
case 'cost_record':
|
|
303
|
-
// All three backends emit cost_record via their event parser/adapter.
|
|
304
|
-
// This is the single recording point for all LLM costs.
|
|
305
|
-
recordCost({
|
|
306
|
-
project: options.project || 'general',
|
|
307
|
-
trigger: options.trigger || 'unknown',
|
|
308
|
-
cost_usd: event.cost_usd,
|
|
309
|
-
backend: adapter.backend,
|
|
310
|
-
mode: config.mode || 'api',
|
|
311
|
-
source: 'estimate',
|
|
312
|
-
input_tokens: event.tokens_in,
|
|
313
|
-
output_tokens: event.tokens_out,
|
|
314
|
-
provider: event.provider || undefined,
|
|
315
|
-
model: event.model || undefined,
|
|
316
|
-
}).catch(err => log.warn('recordCost failed:', err?.message ?? err));
|
|
317
|
-
break;
|
|
318
|
-
case 'context_compacted':
|
|
319
|
-
// Off by default; when enabled, preserve the text path used by every platform while
|
|
320
|
-
// giving chat clients explicit presentation semantics instead of an emoji convention.
|
|
321
|
-
if (process.env.CORTEX_NOTIFY_COMPACTION === '1') {
|
|
322
|
-
options.onAssistantMessage?.(t('notify.contextCompacted'), undefined, 'info');
|
|
323
|
-
}
|
|
324
|
-
break;
|
|
325
|
-
case 'plan_written':
|
|
326
|
-
options.onPlanWritten?.({ path: event.path, content: event.content, toolUseId: event.toolUseId });
|
|
327
|
-
break;
|
|
328
|
-
case 'ask_user_question':
|
|
329
|
-
options.onAskUserQuestion?.({ toolUseId: event.toolUseId, questions: event.questions });
|
|
330
|
-
break;
|
|
331
|
-
default:
|
|
332
|
-
break;
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
catch (e) {
|
|
337
|
-
log.warn('runWithAdapter event loop error:', e?.message ?? e);
|
|
338
|
-
}
|
|
339
|
-
})();
|
|
340
|
-
const promise = (async () => {
|
|
341
|
-
try {
|
|
342
|
-
const [result] = await Promise.all([turnPromise, eventLoop]);
|
|
343
|
-
// Thread/dispatch turns (threadId set) wait INLINE for background-task continuations:
|
|
344
|
-
// a thread step's deliverable is its result, so the step must not complete while a
|
|
345
|
-
// run_in_background task is still running — the continuation output belongs to it.
|
|
346
|
-
// (Interactive turns return immediately; orchestration/lifecycle holds their status
|
|
347
|
-
// asynchronously.) Registration is race-free here: the sink lands within the same
|
|
348
|
-
// microtask drain as the result line, before the CLI's next stdout line is processed.
|
|
349
|
-
if (shouldAwaitBgInline(adapter.backend, options.threadId, result, typeof proc.setContinuationSink === 'function')) {
|
|
350
|
-
log.info(`thread turn ${options.threadId} has background work remaining — waiting inline for the continuation`);
|
|
351
|
-
return await waitForBgContinuation({
|
|
352
|
-
proc,
|
|
353
|
-
baseResult: result,
|
|
354
|
-
onAssistantText: options.onAssistantMessage ?? null,
|
|
355
|
-
onToolUse: options.onToolUse ?? null,
|
|
356
|
-
onToolResult: options.onToolResult ?? null,
|
|
357
|
-
onContextUsage: options.onContextUsage ?? null,
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
return result;
|
|
361
|
-
}
|
|
362
|
-
catch (err) {
|
|
363
|
-
await eventLoop.catch(() => { });
|
|
364
|
-
throw err;
|
|
365
|
-
}
|
|
366
|
-
finally {
|
|
367
|
-
await proc.close().catch(() => { });
|
|
368
|
-
}
|
|
369
|
-
})();
|
|
364
|
+
const closeProcess = createProcessCloser(proc);
|
|
365
|
+
const legacy = new LegacyEventDispatcher(adapter, options, config, spawnConfig);
|
|
366
|
+
const tee = createRunEventTee(proc, options.observers ?? [], options.requiredSinks ?? []);
|
|
367
|
+
const eventLoop = consumeEventStream({
|
|
368
|
+
proc, tee, onEvent: (event) => legacy.dispatch(event),
|
|
369
|
+
});
|
|
370
|
+
const resultPromise = resolveRunResult(turnPromise, eventLoop, adapter, options, proc, (event) => {
|
|
371
|
+
tee.dispatch(event);
|
|
372
|
+
});
|
|
370
373
|
return {
|
|
371
|
-
promise,
|
|
374
|
+
promise: settleEventfulRun(resultPromise, eventLoop, () => tee.close(), closeProcess),
|
|
372
375
|
kill: () => proc.kill(),
|
|
373
376
|
get sessionId() { return proc.sessionId; },
|
|
374
377
|
agentProcess: proc,
|
|
@@ -433,7 +436,7 @@ export async function compactAgentContext(request, deps = compactAgentDeps) {
|
|
|
433
436
|
project: request.projectId,
|
|
434
437
|
trigger: 'manual-compact',
|
|
435
438
|
});
|
|
436
|
-
const proc = deps.getAdapter(request.backend).spawn(
|
|
439
|
+
const proc = deps.getAdapter(request.backend).spawn(buildAgentSpawnConfig({
|
|
437
440
|
sessionId: request.backendSessionId,
|
|
438
441
|
trackSessionId: request.sessionId,
|
|
439
442
|
sessionKey: request.channel,
|
|
@@ -467,7 +470,8 @@ export function runAgentOnce(message, options, config) {
|
|
|
467
470
|
const anthropicBaseUrl = configureEnvForMode(effectiveMode, Object.keys(metadata).length > 0 ? metadata : undefined);
|
|
468
471
|
const adapter = getAdapter(config.backend);
|
|
469
472
|
const handle = runWithAdapter(adapter, message, options, config, anthropicBaseUrl);
|
|
470
|
-
|
|
473
|
+
const attributed = withRateLimitProvider(handle, resolveRateLimitProvider(config));
|
|
474
|
+
return withAuthLifecycle(attributed, options, config);
|
|
471
475
|
}
|
|
472
476
|
export function runAgent(message, options = {}) {
|
|
473
477
|
const profileConfig = resolveProfileConfig(options.profileName);
|
|
@@ -570,7 +574,7 @@ export const _test = {
|
|
|
570
574
|
runWithAdapter,
|
|
571
575
|
resolveRateLimitProvider,
|
|
572
576
|
withRateLimitProvider,
|
|
573
|
-
buildSpawnConfig,
|
|
577
|
+
buildSpawnConfig: buildAgentSpawnConfig,
|
|
574
578
|
filterChannelScopedPlugins,
|
|
575
579
|
};
|
|
576
580
|
// --- Claude bridge helper re-exports ---
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Backend } from '../../agent-adapter/index.js';
|
|
2
|
+
import type { AgentHandle, AgentResult } from '../../core/types/agent-types.js';
|
|
3
|
+
interface ProviderConfig {
|
|
4
|
+
backend: Backend;
|
|
5
|
+
provider?: string | null;
|
|
6
|
+
mode: string | null;
|
|
7
|
+
}
|
|
8
|
+
interface AuthRunOptions {
|
|
9
|
+
channel?: string;
|
|
10
|
+
trackSessionId?: string | null;
|
|
11
|
+
sessionId?: string | null;
|
|
12
|
+
}
|
|
13
|
+
export declare function resolveRateLimitProvider(config: Pick<ProviderConfig, 'backend' | 'provider'>): string;
|
|
14
|
+
export declare function withRateLimitProvider(handle: AgentHandle, provider: string): AgentHandle;
|
|
15
|
+
export declare function withAuthLifecycle(handle: AgentHandle, options: AuthRunOptions, config: ProviderConfig): AgentHandle;
|
|
16
|
+
export declare function configIsRateLimited(config: ProviderConfig): boolean;
|
|
17
|
+
export declare function rateLimitedResult(mode: string, provider: string): AgentResult;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// input: agent handles, provider config, auth events
|
|
2
|
+
// output: provider identity, gating, and lifecycle wrappers
|
|
3
|
+
// pos: Provider-attributed run lifecycle helpers
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
import { classifyAuthError, publishAuthRecovered, publishAuthRequired } from '../auth/auth-events.js';
|
|
6
|
+
import { isProviderModeRateLimited } from '../costs/rate-limit-throttle.js';
|
|
7
|
+
import { isRetryableError } from './config.js';
|
|
8
|
+
const DEFAULT_PROVIDER_BY_BACKEND = {
|
|
9
|
+
claude: 'anthropic',
|
|
10
|
+
};
|
|
11
|
+
export function resolveRateLimitProvider(config) {
|
|
12
|
+
return config.provider || DEFAULT_PROVIDER_BY_BACKEND[config.backend] || config.backend;
|
|
13
|
+
}
|
|
14
|
+
export function withRateLimitProvider(handle, provider) {
|
|
15
|
+
return {
|
|
16
|
+
promise: handle.promise.then((result) => ({ ...result, rateLimitProvider: result.rateLimitProvider || provider }), (error) => {
|
|
17
|
+
if (isRetryableError(error)) {
|
|
18
|
+
error.rateLimitProvider ??= provider;
|
|
19
|
+
}
|
|
20
|
+
throw error;
|
|
21
|
+
}),
|
|
22
|
+
kill: () => handle.kill(),
|
|
23
|
+
get sessionId() { return handle.sessionId ?? null; },
|
|
24
|
+
get agentProcess() { return handle.agentProcess; },
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function withAuthLifecycle(handle, options, config) {
|
|
28
|
+
const identity = { backend: config.backend, provider: resolveRateLimitProvider(config) };
|
|
29
|
+
return {
|
|
30
|
+
promise: handle.promise.then((result) => {
|
|
31
|
+
if (!result.rateLimited)
|
|
32
|
+
publishAuthRecovered(identity);
|
|
33
|
+
return result;
|
|
34
|
+
}, (error) => {
|
|
35
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
36
|
+
const kind = classifyAuthError(message);
|
|
37
|
+
if (kind) {
|
|
38
|
+
publishAuthRequired({
|
|
39
|
+
...identity, authType: null, kind,
|
|
40
|
+
channel: options.channel ?? null,
|
|
41
|
+
sessionId: options.trackSessionId ?? options.sessionId ?? handle.sessionId ?? null,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
throw error;
|
|
45
|
+
}),
|
|
46
|
+
kill: () => handle.kill(),
|
|
47
|
+
get sessionId() { return handle.sessionId ?? null; },
|
|
48
|
+
get agentProcess() { return handle.agentProcess; },
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function configIsRateLimited(config) {
|
|
52
|
+
return isProviderModeRateLimited(resolveRateLimitProvider(config), config.mode || 'api');
|
|
53
|
+
}
|
|
54
|
+
export function rateLimitedResult(mode, provider) {
|
|
55
|
+
return {
|
|
56
|
+
sessionId: null, total_cost_usd: null, num_turns: null,
|
|
57
|
+
rateLimited: true, rateLimitMessage: `Mode ${mode} is rate-limited`, rateLimitProvider: provider,
|
|
58
|
+
planFilePath: null, enteredPlanMode: false, exitedPlanMode: false, finalOutput: null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AuthErrorKind, EventBus } from '../../events/index.js';
|
|
2
|
+
type AuthBackend = 'claude' | 'pi';
|
|
3
|
+
type AuthType = 'oauth' | 'api_key' | null;
|
|
4
|
+
export declare function classifyAuthError(message: string): AuthErrorKind | null;
|
|
5
|
+
export declare function initAuthEvents(bus: EventBus | null): void;
|
|
6
|
+
export declare function publishAuthRequired(input: {
|
|
7
|
+
backend: AuthBackend;
|
|
8
|
+
provider: string;
|
|
9
|
+
authType: AuthType;
|
|
10
|
+
kind: AuthErrorKind;
|
|
11
|
+
channel: string | null;
|
|
12
|
+
sessionId: string | null;
|
|
13
|
+
}): void;
|
|
14
|
+
export declare function publishAuthRecovered(input: {
|
|
15
|
+
backend: AuthBackend;
|
|
16
|
+
provider: string;
|
|
17
|
+
}): void;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// input: provider error messages, run identity, shared EventBus
|
|
2
|
+
// output: auth classification and required/recovered lifecycle events
|
|
3
|
+
// pos: Authentication failure event publisher
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
const AUTH_ERROR_PATTERNS = [
|
|
6
|
+
[/(?:\blogin_required\b|please\s+run\s+\/login\b)/i, 'login_required'],
|
|
7
|
+
[/(?:\boauth_expired\b|oauth\s+token\s+has\s+expired\b)/i, 'oauth_expired'],
|
|
8
|
+
[/(?:\bauthentication_error\b|\bauthentication\b|\binvalid[_ -]api[_ -]key\b|\binvalid\s+x-api-key\b)/i, 'invalid_api_key'],
|
|
9
|
+
[/(?:\bunauthorized\b|\b401\b)/i, 'unauthorized'],
|
|
10
|
+
[/\binvalid_grant\b/i, 'invalid_grant'],
|
|
11
|
+
];
|
|
12
|
+
let eventBus = null;
|
|
13
|
+
const pendingRecovery = new Set();
|
|
14
|
+
function pairKey(backend, provider) {
|
|
15
|
+
return `${backend}:${provider}`;
|
|
16
|
+
}
|
|
17
|
+
export function classifyAuthError(message) {
|
|
18
|
+
for (const [pattern, kind] of AUTH_ERROR_PATTERNS) {
|
|
19
|
+
if (pattern.test(message))
|
|
20
|
+
return kind;
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
export function initAuthEvents(bus) {
|
|
25
|
+
eventBus = bus;
|
|
26
|
+
pendingRecovery.clear();
|
|
27
|
+
}
|
|
28
|
+
export function publishAuthRequired(input) {
|
|
29
|
+
if (!eventBus)
|
|
30
|
+
return;
|
|
31
|
+
pendingRecovery.add(pairKey(input.backend, input.provider));
|
|
32
|
+
eventBus.publish({ type: 'auth.required', ...input });
|
|
33
|
+
}
|
|
34
|
+
export function publishAuthRecovered(input) {
|
|
35
|
+
if (!eventBus || !pendingRecovery.delete(pairKey(input.backend, input.provider)))
|
|
36
|
+
return;
|
|
37
|
+
eventBus.publish({ type: 'auth.recovered', ...input });
|
|
38
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// input: AuthStatusSnapshot types and localized copy
|
|
2
|
+
// output: formatAuthStatusSummary
|
|
3
|
+
// pos: Human-readable backend auth status formatter
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
import { t } from '../../core/i18n.js';
|
|
6
|
+
function authStateLabel(state) {
|
|
7
|
+
return t(`cmd.auth.state.${state}`);
|
|
8
|
+
}
|
|
9
|
+
function authTypeLabel(authType) {
|
|
10
|
+
return t(`cmd.auth.type.${authType ?? 'none'}`);
|
|
11
|
+
}
|
|
12
|
+
function expirySuffix(key, value) {
|
|
13
|
+
return value ? t(`cmd.auth.${key}`, { time: value }) : '';
|
|
14
|
+
}
|
|
15
|
+
function formatCredential(credential) {
|
|
16
|
+
return t('cmd.auth.credentialLine', {
|
|
17
|
+
authType: authTypeLabel(credential.authType),
|
|
18
|
+
state: authStateLabel(credential.state),
|
|
19
|
+
source: credential.source ?? '—',
|
|
20
|
+
expires: expirySuffix('expires', credential.expiresAt),
|
|
21
|
+
refreshExpires: expirySuffix('refreshExpires', credential.refreshExpiresAt),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function formatAccount(account) {
|
|
25
|
+
const backend = t(`cmd.auth.backend.${account.backend}`);
|
|
26
|
+
const line = t('cmd.auth.accountLine', {
|
|
27
|
+
backend, label: account.label, authType: authTypeLabel(account.authType),
|
|
28
|
+
state: authStateLabel(account.state), inUse: account.inUse ? t('cmd.auth.inUse') : '',
|
|
29
|
+
});
|
|
30
|
+
if (account.credentials.length === 0)
|
|
31
|
+
return [line];
|
|
32
|
+
return [line, t('cmd.auth.credentials'), ...account.credentials.map(formatCredential)];
|
|
33
|
+
}
|
|
34
|
+
function visibleInSummary(account) {
|
|
35
|
+
return account.backend === 'claude'
|
|
36
|
+
|| account.inUse
|
|
37
|
+
|| account.state !== 'logged-out'
|
|
38
|
+
|| account.credentials.length > 0;
|
|
39
|
+
}
|
|
40
|
+
export function formatAuthStatusSummary(snapshot) {
|
|
41
|
+
const runtimeStatus = snapshot.piRuntime.available
|
|
42
|
+
? t('cmd.auth.runtimeAvailable')
|
|
43
|
+
: t('cmd.auth.runtimeUnavailable');
|
|
44
|
+
const version = snapshot.piRuntime.version
|
|
45
|
+
? t('cmd.auth.runtimeVersion', { version: snapshot.piRuntime.version })
|
|
46
|
+
: '';
|
|
47
|
+
const visible = snapshot.accounts.filter(visibleInSummary);
|
|
48
|
+
const hidden = snapshot.accounts.length - visible.length;
|
|
49
|
+
const lines = [
|
|
50
|
+
t('cmd.auth.heading'),
|
|
51
|
+
t('cmd.auth.generatedAt', { time: snapshot.generatedAt }),
|
|
52
|
+
t('cmd.auth.runtimeLine', { status: runtimeStatus, version }),
|
|
53
|
+
...visible.flatMap(formatAccount),
|
|
54
|
+
];
|
|
55
|
+
if (hidden > 0)
|
|
56
|
+
lines.push(t('cmd.auth.hiddenLoggedOut', { n: hidden }));
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|