@cortex-agent/server 2026.7.30 → 2026.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/defaults/CORTEX.md +1 -0
- package/defaults/config/CORTEX.md +2 -1
- package/defaults/config/hooks/13-status-md-guard.json +11 -0
- package/defaults/config/hooks/CORTEX.md +1 -0
- package/defaults/config/mcp-config-empty.json +3 -0
- package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
- package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
- package/defaults/config/thread-templates/agents/coder.json +4 -14
- package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
- package/defaults/config/thread-templates/templates/coder-review.json +3 -27
- package/defaults/context/projects/CORTEX.md +1 -1
- package/defaults/data/schedules.json +12 -0
- package/defaults/hooks/CORTEX.md +1 -0
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +193 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
- package/defaults/prompts/directives/coder-reviewer.md +24 -20
- package/defaults/prompts/directives/coder.md +4 -5
- package/defaults/prompts/directives/director.md +4 -10
- package/defaults/prompts/directives/manager.md +9 -10
- package/defaults/prompts/systemPrompts/worker.md +2 -2
- package/defaults/rules/cortex-md.md +31 -0
- package/defaults/rules/experiment-format.md +8 -1
- package/defaults/rules/issues-md.md +10 -9
- package/defaults/rules/meta-conventions.md +5 -4
- package/defaults/rules/mission-md.md +2 -1
- package/defaults/rules/status-md.md +39 -21
- package/dist/agent-adapter/bg-wait.d.ts +10 -12
- package/dist/agent-adapter/bg-wait.js +209 -129
- package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
- package/dist/agent-adapter/claude/adapter-tui.js +8 -5
- package/dist/agent-adapter/claude/adapter.d.ts +43 -14
- package/dist/agent-adapter/claude/adapter.js +276 -161
- package/dist/agent-adapter/claude/defaults.d.ts +2 -0
- package/dist/agent-adapter/claude/defaults.js +5 -5
- package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
- package/dist/agent-adapter/claude/event-parser.js +28 -31
- package/dist/agent-adapter/claude/hooks-builder.js +4 -3
- package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
- package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
- package/dist/agent-adapter/claude/spawn-args.js +44 -38
- package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
- package/dist/agent-adapter/claude/tmux-control.js +39 -32
- package/dist/agent-adapter/event-tee.d.ts +19 -0
- package/dist/agent-adapter/event-tee.js +145 -0
- package/dist/agent-adapter/index.d.ts +1 -0
- package/dist/agent-adapter/index.js +7 -3
- package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
- package/dist/agent-adapter/normalize/event-types.js +4 -4
- package/dist/agent-adapter/pi/adapter.d.ts +16 -4
- package/dist/agent-adapter/pi/adapter.js +69 -36
- package/dist/agent-adapter/pi/discovery.d.ts +19 -3
- package/dist/agent-adapter/pi/discovery.js +81 -43
- package/dist/agent-adapter/pi/event-parser.js +4 -2
- package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
- package/dist/agent-adapter/pi/spawn-args.js +6 -5
- package/dist/agent-adapter/types.d.ts +43 -2
- package/dist/agent-adapter/types.js +8 -4
- package/dist/core/atomic-write.d.ts +6 -1
- package/dist/core/atomic-write.js +183 -7
- package/dist/core/cli-utils.d.ts +15 -2
- package/dist/core/cli-utils.js +46 -41
- package/dist/core/config-generator.d.ts +4 -0
- package/dist/core/config-generator.js +34 -21
- package/dist/core/json-repository.d.ts +4 -0
- package/dist/core/json-repository.js +6 -3
- package/dist/core/locales/en.d.ts +94 -0
- package/dist/core/locales/slices/commands.d.ts +76 -0
- package/dist/core/locales/slices/commands.js +155 -1
- package/dist/core/locales/slices/status.d.ts +18 -0
- package/dist/core/locales/slices/status.js +43 -2
- package/dist/core/log.d.ts +5 -0
- package/dist/core/log.js +25 -23
- package/dist/core/pi-session-filename.d.ts +2 -0
- package/dist/core/pi-session-filename.js +18 -0
- package/dist/core/resume-reminder.d.ts +5 -0
- package/dist/core/resume-reminder.js +18 -0
- package/dist/core/runtime-env.d.ts +1 -0
- package/dist/core/runtime-env.js +15 -0
- package/dist/core/settings-migration.d.ts +5 -0
- package/dist/core/settings-migration.js +128 -0
- package/dist/core/settings-spec.d.ts +174 -0
- package/dist/core/settings-spec.js +150 -0
- package/dist/core/settings.d.ts +10 -0
- package/dist/core/settings.js +235 -0
- package/dist/core/task-parser.d.ts +11 -1
- package/dist/core/task-parser.js +34 -3
- package/dist/core/types/agent-types.d.ts +19 -0
- package/dist/core/types/agent-types.js +1 -1
- package/dist/core/types/thread-types.d.ts +48 -3
- package/dist/core/types/thread-types.js +2 -2
- package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
- package/dist/domain/agent-run/access-probe-cli.js +139 -0
- package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
- package/dist/domain/agent-run/access-probe-policy.js +614 -0
- package/dist/domain/agent-run/access-probe.d.ts +21 -0
- package/dist/domain/agent-run/access-probe.js +194 -0
- package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
- package/dist/domain/agent-run/agent-run-cli.js +171 -0
- package/dist/domain/agent-run/atif.d.ts +54 -0
- package/dist/domain/agent-run/atif.js +211 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
- package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
- package/dist/domain/agent-run/identity.d.ts +62 -0
- package/dist/domain/agent-run/identity.js +118 -0
- package/dist/domain/agent-run/journal.d.ts +51 -0
- package/dist/domain/agent-run/journal.js +259 -0
- package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
- package/dist/domain/agent-run/manifest-contract.js +134 -0
- package/dist/domain/agent-run/manifest.d.ts +51 -0
- package/dist/domain/agent-run/manifest.js +801 -0
- package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
- package/dist/domain/agent-run/pinned-node-process.js +206 -0
- package/dist/domain/agent-run/role-surface.d.ts +4 -0
- package/dist/domain/agent-run/role-surface.js +99 -0
- package/dist/domain/agent-run/run-config.d.ts +22 -0
- package/dist/domain/agent-run/run-config.js +135 -0
- package/dist/domain/agent-run/runner.d.ts +7 -0
- package/dist/domain/agent-run/runner.js +518 -0
- package/dist/domain/agent-run/supervisor.d.ts +78 -0
- package/dist/domain/agent-run/supervisor.js +425 -0
- package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
- package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
- package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
- package/dist/domain/agent-run/trajectory-merge.js +505 -0
- package/dist/domain/agents/config.d.ts +10 -0
- package/dist/domain/agents/config.js +149 -44
- package/dist/domain/agents/facade.d.ts +42 -7
- package/dist/domain/agents/facade.js +174 -170
- package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
- package/dist/domain/agents/provider-run-lifecycle.js +60 -0
- package/dist/domain/auth/auth-events.d.ts +18 -0
- package/dist/domain/auth/auth-events.js +38 -0
- package/dist/domain/auth/auth-format.d.ts +2 -0
- package/dist/domain/auth/auth-format.js +58 -0
- package/dist/domain/auth/auth-status.d.ts +61 -0
- package/dist/domain/auth/auth-status.js +304 -0
- package/dist/domain/auth/auth-watch.d.ts +16 -0
- package/dist/domain/auth/auth-watch.js +125 -0
- package/dist/domain/auth/cc-login.d.ts +7 -0
- package/dist/domain/auth/cc-login.js +16 -0
- package/dist/domain/auth/cc-subscription.d.ts +38 -0
- package/dist/domain/auth/cc-subscription.js +204 -0
- package/dist/domain/auth/index.d.ts +12 -0
- package/dist/domain/auth/index.js +16 -0
- package/dist/domain/auth/login-flow.d.ts +120 -0
- package/dist/domain/auth/login-flow.js +253 -0
- package/dist/domain/auth/login-service.d.ts +32 -0
- package/dist/domain/auth/login-service.js +97 -0
- package/dist/domain/auth/logout.d.ts +32 -0
- package/dist/domain/auth/logout.js +123 -0
- package/dist/domain/auth/pi-login.d.ts +36 -0
- package/dist/domain/auth/pi-login.js +72 -0
- package/dist/domain/auth/pi-oauth.d.ts +36 -0
- package/dist/domain/auth/pi-oauth.js +84 -0
- package/dist/domain/auth/pi-runtime.d.ts +72 -0
- package/dist/domain/auth/pi-runtime.js +86 -0
- package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
- package/dist/domain/mcp/benchmark-thread-server.js +26 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
- package/dist/domain/memory/user-context.js +6 -8
- package/dist/domain/monitor/disk-monitor.js +47 -16
- package/dist/domain/projects/project-store.js +23 -6
- package/dist/domain/remote/client-manager.js +12 -6
- package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
- package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
- package/dist/domain/scheduling/runner.d.ts +2 -0
- package/dist/domain/scheduling/runner.js +7 -4
- package/dist/domain/sessions/session-backup.d.ts +14 -20
- package/dist/domain/sessions/session-backup.js +57 -68
- package/dist/domain/system/doctor.d.ts +4 -0
- package/dist/domain/system/doctor.js +113 -28
- package/dist/domain/system/server-update-check.js +7 -5
- package/dist/domain/system/system-notice.d.ts +3 -1
- package/dist/domain/system/system-notice.js +6 -11
- package/dist/domain/tasks/archiver.d.ts +1 -0
- package/dist/domain/tasks/archiver.js +13 -7
- package/dist/domain/tasks/claim-recovery.d.ts +3 -3
- package/dist/domain/tasks/claim-recovery.js +12 -8
- package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
- package/dist/domain/tasks/dispatch-utils.js +22 -18
- package/dist/domain/tasks/dispatcher.d.ts +1 -0
- package/dist/domain/tasks/dispatcher.js +9 -5
- package/dist/domain/tasks/mutator.d.ts +21 -11
- package/dist/domain/tasks/mutator.js +30 -24
- package/dist/domain/tasks/pending-tracker.d.ts +5 -2
- package/dist/domain/tasks/pending-tracker.js +11 -5
- package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
- package/dist/domain/tasks/system/cortex-run.js +24 -4
- package/dist/domain/tasks/system/task-cli.d.ts +1 -0
- package/dist/domain/tasks/system/task-cli.js +72 -22
- package/dist/domain/tasks/system/task-completion.d.ts +19 -2
- package/dist/domain/tasks/system/task-completion.js +31 -17
- package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
- package/dist/domain/tasks/system/task-file-input.js +57 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
- package/dist/domain/tasks/system/task-id-utils.js +13 -4
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
- package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
- package/dist/domain/tasks/system/task-lock.js +19 -5
- package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
- package/dist/domain/tasks/system/task-mutations.js +28 -4
- package/dist/domain/tasks/system/task-process.js +10 -8
- package/dist/domain/tasks/system/task-state.d.ts +65 -11
- package/dist/domain/tasks/system/task-state.js +86 -13
- package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
- package/dist/domain/threads/local-runtime-deps.js +91 -0
- package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
- package/dist/domain/threads/local-runtime-scope.js +12 -0
- package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
- package/dist/domain/threads/pending-user-inputs.js +37 -0
- package/dist/domain/threads/prompt-builder.d.ts +12 -1
- package/dist/domain/threads/prompt-builder.js +73 -26
- package/dist/domain/threads/runner.d.ts +15 -3
- package/dist/domain/threads/runner.js +261 -105
- package/dist/domain/threads/state-machine.d.ts +1 -1
- package/dist/domain/threads/state-machine.js +17 -8
- package/dist/domain/ui-service/app-router.d.ts +86 -6
- package/dist/domain/ui-service/app-router.js +171 -133
- package/dist/domain/ui-service/input-schemas.d.ts +132 -10
- package/dist/domain/ui-service/input-schemas.js +59 -5
- package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
- package/dist/domain/ui-service/mutate/approvals.js +2 -1
- package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
- package/dist/domain/ui-service/mutate/auth.js +83 -0
- package/dist/domain/ui-service/mutate/config.js +11 -10
- package/dist/domain/ui-service/query/approvals.js +3 -0
- package/dist/domain/ui-service/query/auth.d.ts +6 -0
- package/dist/domain/ui-service/query/auth.js +12 -0
- package/dist/domain/ui-service/query/config.d.ts +5 -5
- package/dist/domain/ui-service/query/config.js +27 -17
- package/dist/domain/ui-service/query/tasks.d.ts +1 -1
- package/dist/domain/ui-service/query/tasks.js +69 -30
- package/dist/domain/ui-service/query/threads.js +3 -3
- package/dist/domain/ui-service/types.d.ts +67 -8
- package/dist/domain/ui-service/types.js +2 -2
- package/dist/domain/ui-service/ui-service.js +16 -2
- package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
- package/dist/entry/admin-channel-hot-reload.js +22 -0
- package/dist/entry/app.js +38 -38
- package/dist/entry/auth-cli.d.ts +10 -0
- package/dist/entry/auth-cli.js +52 -0
- package/dist/entry/cli-help.d.ts +5 -0
- package/dist/entry/cli-help.js +130 -0
- package/dist/entry/cli.d.ts +5 -5
- package/dist/entry/cli.js +174 -248
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +204 -103
- package/dist/entry/draft-attachments.d.ts +8 -0
- package/dist/entry/draft-attachments.js +83 -0
- package/dist/entry/feishu-login.d.ts +2 -6
- package/dist/entry/feishu-login.js +16 -21
- package/dist/entry/init.js +6 -4
- package/dist/entry/start-ui-http.d.ts +2 -8
- package/dist/entry/start-ui-http.js +7 -34
- package/dist/events/event-logger.js +11 -13
- package/dist/events/event-types.d.ts +19 -1
- package/dist/events/event-types.js +3 -3
- package/dist/events/index.d.ts +1 -1
- package/dist/events/index.js +3 -3
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +193 -0
- package/dist/orchestration/agent-file-send.js +44 -14
- package/dist/orchestration/agent-runner.d.ts +7 -3
- package/dist/orchestration/agent-runner.js +65 -41
- package/dist/orchestration/conversation-runner.d.ts +5 -1
- package/dist/orchestration/conversation-runner.js +16 -7
- package/dist/orchestration/lifecycle.d.ts +23 -1
- package/dist/orchestration/lifecycle.js +103 -40
- package/dist/orchestration/mid-turn-inject.d.ts +2 -0
- package/dist/orchestration/mid-turn-inject.js +29 -13
- package/dist/orchestration/resume-dispatcher.d.ts +3 -5
- package/dist/orchestration/resume-dispatcher.js +9 -17
- package/dist/orchestration/routing/commands/index.d.ts +4 -1
- package/dist/orchestration/routing/commands/index.js +83 -61
- package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
- package/dist/orchestration/routing/commands/login-notice.js +97 -0
- package/dist/orchestration/routing/commands/login.d.ts +12 -0
- package/dist/orchestration/routing/commands/login.js +555 -0
- package/dist/orchestration/routing/commands/status.js +45 -59
- package/dist/orchestration/routing/edit-handler.d.ts +5 -0
- package/dist/orchestration/routing/edit-handler.js +127 -73
- package/dist/orchestration/routing/webhook.js +5 -4
- package/dist/orchestration/session-rewind.d.ts +5 -1
- package/dist/orchestration/session-rewind.js +106 -62
- package/dist/orchestration/session-send.d.ts +2 -0
- package/dist/orchestration/session-send.js +5 -6
- package/dist/orchestration/status-helpers.d.ts +1 -2
- package/dist/orchestration/status-helpers.js +7 -10
- package/dist/orchestration/thread-callback.d.ts +19 -11
- package/dist/orchestration/thread-callback.js +132 -61
- package/dist/orchestration/thread-executor.js +37 -27
- package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
- package/dist/orchestration/turn-mutation-lock.js +36 -0
- package/dist/orchestration/turn-notify.d.ts +2 -5
- package/dist/orchestration/turn-notify.js +9 -21
- package/dist/platform/adapter.d.ts +1 -0
- package/dist/platform/adapter.js +2 -2
- package/dist/platform/adapters/composite-adapter.d.ts +2 -0
- package/dist/platform/adapters/composite-adapter.js +13 -3
- package/dist/platform/adapters/feishu.d.ts +2 -4
- package/dist/platform/adapters/feishu.js +38 -59
- package/dist/platform/adapters/index.d.ts +1 -1
- package/dist/platform/adapters/index.js +13 -12
- package/dist/platform/adapters/slack.d.ts +1 -1
- package/dist/platform/adapters/slack.js +12 -35
- package/dist/platform/index.d.ts +2 -1
- package/dist/platform/index.js +3 -3
- package/dist/platform/testing.d.ts +1 -0
- package/dist/platform/testing.js +13 -4
- package/dist/platform/tool-trace.js +6 -11
- package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
- package/dist/platform/ui-http/ui-http-server.js +6 -18
- package/dist/store/execution-repo.d.ts +17 -1
- package/dist/store/execution-repo.js +55 -4
- package/dist/store/prompt-migration-replacements.d.ts +4 -0
- package/dist/store/prompt-migration-replacements.js +149 -0
- package/dist/store/thread-repo.d.ts +15 -4
- package/dist/store/thread-repo.js +61 -24
- package/dist/store/version-migrations.js +36 -1
- package/native/cortex-supervisor/dist/build-manifest.json +22 -0
- package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
- package/package.json +5 -2
- package/web/dist/assets/index-DrNx9R6c.js +139 -0
- package/web/dist/assets/index-zpf3OSKC.css +1 -0
- package/web/dist/index.html +2 -2
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
- package/web/dist/assets/index-B19jLgji.js +0 -138
- package/web/dist/assets/index-BuFyPyRW.css +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output:
|
|
3
|
-
// pos:
|
|
4
|
-
// >>>
|
|
1
|
+
// input: user turns, platform files, mutation leases, callbacks
|
|
2
|
+
// output: provider runs with reusable attachment downloads
|
|
3
|
+
// pos: Plain user-message and injection path
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { resolveDestinationConduit, SYNTHETIC_CALLBACK_SENDER } from '../platform/types.js';
|
|
6
6
|
import { conduitQueues, enqueue } from './conduit-queue.js';
|
|
7
7
|
import { trackPendingTask } from './busy-tracker.js';
|
|
@@ -13,7 +13,7 @@ import { conversationHistory, summarizeToolInputForHistory } from '../store/conv
|
|
|
13
13
|
import { pendingInjectionRepo } from '../store/pending-injection-repo.js';
|
|
14
14
|
import { getActiveProfile, getDefaultAgent, resolveBackendForChannel } from '../domain/agents/index.js';
|
|
15
15
|
import { registerNamedSession } from '../domain/sessions/session-lifecycle.js';
|
|
16
|
-
import { handleAgentSuccess, handleAgentError, initTurnTracking } from './lifecycle.js';
|
|
16
|
+
import { consumePendingTurnSupersession, finishTurnTracking, handleAgentSuccess, handleAgentError, initTurnTracking } from './lifecycle.js';
|
|
17
17
|
import { buildSessionTag, buildUserProcessingMessage, makeFallbackNotifier, makeStreamingMessageCallback, computeElapsed, writeStatus, sealStatus, buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from './status-helpers.js';
|
|
18
18
|
import { readFileSync } from 'fs';
|
|
19
19
|
import { createLogger } from '../core/log.js';
|
|
@@ -41,7 +41,19 @@ import { shouldHoldForBg, shouldHoldWebForBg } from './bg-continuation.js';
|
|
|
41
41
|
import { holdWebForBg } from './web-bg-hold.js';
|
|
42
42
|
import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
|
|
43
43
|
import { WORKSPACE_DIR, resolveWorkspaceRelPath } from '../core/utils.js';
|
|
44
|
+
import { acquireTurnMutationLock } from './turn-mutation-lock.js';
|
|
44
45
|
const TEMP_DIR = WORKSPACE_DIR;
|
|
46
|
+
function acceptUserMessage(opts) {
|
|
47
|
+
const ts = new Date().toISOString();
|
|
48
|
+
recordHistory(conversationHistory.appendUser(opts.sessionId, {
|
|
49
|
+
text: opts.text, ts, attachments: opts.attachments,
|
|
50
|
+
}));
|
|
51
|
+
publishSessionMessage({
|
|
52
|
+
sessionId: opts.sessionId, channel: opts.channel, role: 'user',
|
|
53
|
+
text: opts.text, ts, attachments: opts.attachments,
|
|
54
|
+
});
|
|
55
|
+
void ensureSessionLabel(opts.sessionName, opts.text);
|
|
56
|
+
}
|
|
45
57
|
export class AgentRunner {
|
|
46
58
|
_enqueue;
|
|
47
59
|
_track;
|
|
@@ -51,10 +63,22 @@ export class AgentRunner {
|
|
|
51
63
|
constructor(opts = {}) {
|
|
52
64
|
this._enqueue = opts.enqueue ?? enqueue;
|
|
53
65
|
this._track = opts.track ?? trackPendingTask;
|
|
54
|
-
this._execute = opts.execute ?? ((ctx) => this._executeReal(ctx));
|
|
55
|
-
this._tryInject = opts.tryInject ?? ((ctx) => this._tryInjectReal(ctx));
|
|
66
|
+
this._execute = opts.execute ?? ((ctx, release, load) => this._executeReal(ctx, release, load));
|
|
67
|
+
this._tryInject = opts.tryInject ?? ((ctx, load) => this._tryInjectReal(ctx, load));
|
|
56
68
|
}
|
|
57
69
|
async route(ctx) {
|
|
70
|
+
const mutationRelease = ctx.mutationRelease ?? await acquireTurnMutationLock(ctx.channel);
|
|
71
|
+
const loadPlatformFiles = createPlatformFileLoader(ctx);
|
|
72
|
+
let queued = false;
|
|
73
|
+
try {
|
|
74
|
+
queued = await this._routeWithAdmission(ctx, mutationRelease, loadPlatformFiles);
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
if (!queued)
|
|
78
|
+
mutationRelease();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async _routeWithAdmission(ctx, mutationRelease, loadPlatformFiles) {
|
|
58
82
|
const { message, channel, adapter } = ctx;
|
|
59
83
|
// DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
|
|
60
84
|
// consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
|
|
@@ -65,7 +89,7 @@ export class AgentRunner {
|
|
|
65
89
|
if (message.senderId !== SYNTHETIC_CALLBACK_SENDER && tryAnswerFromHuman(channel, ctx.userMessage || '')) {
|
|
66
90
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
67
91
|
await adapter.postMessage(dest, { text: `${Icons.ok} ${t('subtask.replyDelivered')}` }).catch(() => { });
|
|
68
|
-
return;
|
|
92
|
+
return false;
|
|
69
93
|
}
|
|
70
94
|
// A plain user message arriving while this channel already has a live turn is delivered INTO
|
|
71
95
|
// that turn (backend stdin) rather than waiting behind it, when the backend can take it. The
|
|
@@ -73,21 +97,23 @@ export class AgentRunner {
|
|
|
73
97
|
// bracket — so we return before the queue machinery. Everything it declines (no live turn,
|
|
74
98
|
// incapable backend, !command, synthetic wake, backend refusal) falls through to today's
|
|
75
99
|
// queue behaviour unchanged.
|
|
76
|
-
if (await this._tryInject(ctx))
|
|
77
|
-
return;
|
|
100
|
+
if (await this._tryInject(ctx, loadPlatformFiles))
|
|
101
|
+
return false;
|
|
78
102
|
const markerRef = conduitQueues.has(channel)
|
|
79
103
|
? { conduit: channel, messageId: message.ref.messageId }
|
|
80
104
|
: null;
|
|
81
105
|
if (markerRef)
|
|
82
106
|
await adapter.markQueued(markerRef).catch(() => { });
|
|
83
107
|
this._track(+1);
|
|
84
|
-
this._enqueue(channel, () => this._runQueued(ctx, markerRef));
|
|
108
|
+
this._enqueue(channel, () => this._runQueued(ctx, markerRef, mutationRelease, loadPlatformFiles));
|
|
109
|
+
return true;
|
|
85
110
|
}
|
|
86
|
-
async _runQueued(ctx, markerRef) {
|
|
111
|
+
async _runQueued(ctx, markerRef, mutationRelease, loadPlatformFiles) {
|
|
87
112
|
try {
|
|
88
|
-
await this._execute(ctx);
|
|
113
|
+
await this._execute(ctx, mutationRelease, loadPlatformFiles);
|
|
89
114
|
}
|
|
90
115
|
finally {
|
|
116
|
+
mutationRelease();
|
|
91
117
|
if (markerRef)
|
|
92
118
|
await ctx.adapter.unmarkQueued(markerRef).catch(() => { });
|
|
93
119
|
this._track(-1);
|
|
@@ -98,7 +124,7 @@ export class AgentRunner {
|
|
|
98
124
|
* message to `mid-turn-inject`. Ordered cheapest-gate-first because route() is the hot path for
|
|
99
125
|
* every inbound message — the store lookups only run once a live turn is actually present.
|
|
100
126
|
*/
|
|
101
|
-
async _tryInjectReal(ctx) {
|
|
127
|
+
async _tryInjectReal(ctx, loadPlatformFiles) {
|
|
102
128
|
try {
|
|
103
129
|
if (!isInjectableMessage({ text: ctx.userMessage || '', senderId: ctx.message.senderId }))
|
|
104
130
|
return false;
|
|
@@ -117,6 +143,10 @@ export class AgentRunner {
|
|
|
117
143
|
senderId: ctx.message.senderId,
|
|
118
144
|
messageId: ctx.message.ref.messageId,
|
|
119
145
|
attachments: ctx.message.webAttachments,
|
|
146
|
+
prepareBackendAttachments: async () => (await loadPlatformFiles()).map((file) => ({
|
|
147
|
+
mimeType: file.mimetype,
|
|
148
|
+
path: file.localPath,
|
|
149
|
+
})),
|
|
120
150
|
});
|
|
121
151
|
}
|
|
122
152
|
catch (e) {
|
|
@@ -125,9 +155,9 @@ export class AgentRunner {
|
|
|
125
155
|
return false;
|
|
126
156
|
}
|
|
127
157
|
}
|
|
128
|
-
async _executeReal(ctx) {
|
|
129
|
-
const { message, channel, adapter, threadAnchorId,
|
|
130
|
-
const downloadedFiles = await
|
|
158
|
+
async _executeReal(ctx, mutationRelease, loadPlatformFiles) {
|
|
159
|
+
const { message, channel, adapter, threadAnchorId, userMessage, agentMessage } = ctx;
|
|
160
|
+
const downloadedFiles = await loadPlatformFiles();
|
|
131
161
|
// Web-uploaded attachments are already on disk — map to DownloadedFile shape.
|
|
132
162
|
// The `path` field from upload is the UI-relative `workspace/attachments/...` alias for
|
|
133
163
|
// WORKSPACE_DIR's contents; resolveWorkspaceRelPath maps it to the real absolute path under
|
|
@@ -179,31 +209,16 @@ export class AgentRunner {
|
|
|
179
209
|
richBlocks: buildSealedStatusActionBlocks(statusText, blocksTemplate),
|
|
180
210
|
}, threadAnchorId ? { threadId: threadAnchorId } : undefined);
|
|
181
211
|
const messageTs = message.ref.messageId;
|
|
182
|
-
await initTurnTracking(channel, sessionId, backendSessionId, sessionName, messageTs, userMessage || '', statusMsg.messageId
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (sessionId) {
|
|
187
|
-
// Share a single timestamp between the conversation-history entry and the EventBus
|
|
188
|
-
// event so the web UI's content-based de-dup (transcript query vs SSE live-tail)
|
|
189
|
-
// produces identical msgKeys for the same message.
|
|
190
|
-
const userTs = new Date().toISOString();
|
|
191
|
-
recordHistory(conversationHistory.appendUser(sessionId, {
|
|
192
|
-
text: userMessage || '',
|
|
193
|
-
ts: userTs,
|
|
194
|
-
attachments: message.webAttachments,
|
|
195
|
-
}));
|
|
196
|
-
publishSessionMessage({
|
|
197
|
-
sessionId,
|
|
198
|
-
channel,
|
|
199
|
-
role: 'user',
|
|
200
|
-
text: userMessage || '',
|
|
201
|
-
ts: userTs,
|
|
212
|
+
const turnTrackingToken = await initTurnTracking(channel, sessionId, backendSessionId, sessionName, messageTs, userMessage || '', statusMsg.messageId, {
|
|
213
|
+
mutationRelease,
|
|
214
|
+
onAccepted: () => acceptUserMessage({
|
|
215
|
+
sessionId, channel, sessionName, text: userMessage || '',
|
|
202
216
|
attachments: message.webAttachments,
|
|
203
|
-
})
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
217
|
+
}),
|
|
218
|
+
});
|
|
219
|
+
if (consumePendingTurnSupersession(channel, turnTrackingToken)) {
|
|
220
|
+
finishTurnTracking(channel, turnTrackingToken);
|
|
221
|
+
return;
|
|
207
222
|
}
|
|
208
223
|
const onMessagePosted = (ref) => void conversationLedger.addResponseTs(channel, messageTs, ref.messageId).catch((e) => log.error(e));
|
|
209
224
|
// 2. Build agent callbacks (streaming, fallback, progress)
|
|
@@ -270,6 +285,7 @@ export class AgentRunner {
|
|
|
270
285
|
}).catch(() => { });
|
|
271
286
|
initStatusBlocks(statusMsg, blocksTemplateWithExec);
|
|
272
287
|
},
|
|
288
|
+
onExecutionRegistered: () => finishTurnTracking(channel, turnTrackingToken),
|
|
273
289
|
onAssistantDelta: deltaStream ? (text, blockId) => deltaStream.onDelta(text, blockId) : null,
|
|
274
290
|
onAssistantMessage: (text, blockId, noticeLevel) => {
|
|
275
291
|
// Drain this block's preview FIRST: the authoritative message must never be overtaken by
|
|
@@ -365,6 +381,7 @@ export class AgentRunner {
|
|
|
365
381
|
});
|
|
366
382
|
}
|
|
367
383
|
finally {
|
|
384
|
+
finishTurnTracking(channel, turnTrackingToken);
|
|
368
385
|
// The turn is over (successfully, in error, or cancelled): no preview may outlive it.
|
|
369
386
|
deltaStream?.dispose();
|
|
370
387
|
// Skip the idle seal when a web bg-hold is active — it owns the terminal running:false
|
|
@@ -528,6 +545,13 @@ function buildAgentCallbacks(adapter, destination, statusMsg, threadAnchorId, st
|
|
|
528
545
|
};
|
|
529
546
|
return { onFallback, onAssistantMsg, onProgress, onToolUse };
|
|
530
547
|
}
|
|
548
|
+
function createPlatformFileLoader(ctx) {
|
|
549
|
+
let pending = null;
|
|
550
|
+
return () => {
|
|
551
|
+
pending ??= downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
|
|
552
|
+
return pending;
|
|
553
|
+
};
|
|
554
|
+
}
|
|
531
555
|
async function downloadFiles(files, hasFiles, adapter) {
|
|
532
556
|
if (!hasFiles || !files)
|
|
533
557
|
return [];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { PlatformAdapter, DownloadedFile } from '../platform/index.js';
|
|
2
2
|
import type { AgentResult, ChatNoticeLevel, ContextUsage } from '../core/types/agent-types.js';
|
|
3
3
|
import { projectStore } from '../domain/projects/index.js';
|
|
4
|
+
import { runningExecutions } from '../core/running-executions.js';
|
|
4
5
|
export interface RunConversationOptions {
|
|
5
6
|
adapter: PlatformAdapter;
|
|
6
7
|
channel: string;
|
|
@@ -26,6 +27,8 @@ export interface RunConversationOptions {
|
|
|
26
27
|
/** Fired once the execution record is created, before the agent starts — lets the caller
|
|
27
28
|
* attach an execution-scoped Cancel button to the status message. */
|
|
28
29
|
onExecutionStarted?: (executionId: string) => void | Promise<void>;
|
|
30
|
+
/** Fired synchronously after the backend handle is registered for cancellation. */
|
|
31
|
+
onExecutionRegistered?: () => void;
|
|
29
32
|
/** `blockId` identifies prior deltas; `noticeLevel` marks system-authored chat notices. */
|
|
30
33
|
onAssistantMessage?: ((text: string, blockId?: string, noticeLevel?: ChatNoticeLevel) => void) | null;
|
|
31
34
|
/** Incremental chunk of a block still being generated. Web chat only — see delta-coalescer. */
|
|
@@ -33,7 +36,7 @@ export interface RunConversationOptions {
|
|
|
33
36
|
onProgress?: ((progress: any) => void) | null;
|
|
34
37
|
onContextUsage?: ((usage: ContextUsage) => void | Promise<void>) | null;
|
|
35
38
|
onFallback?: ((...args: any[]) => Promise<void>) | null;
|
|
36
|
-
/** Receives the
|
|
39
|
+
/** Receives the backend-ready prompt after context and attachment paths are assembled. */
|
|
37
40
|
onPromptBuilt?: ((prompt: string) => void) | null;
|
|
38
41
|
onToolUse?: ((name: string, input: any, toolUseId: string) => void) | null;
|
|
39
42
|
onToolResult?: ((toolUseId: string, content: string, isError: boolean) => void) | null;
|
|
@@ -51,6 +54,7 @@ export interface ConversationResult {
|
|
|
51
54
|
* register a ContinuationSink on the (Claude) session. Opaque to other consumers. */
|
|
52
55
|
agentProcess?: unknown;
|
|
53
56
|
}
|
|
57
|
+
export declare function registerConversationHandle(registry: Pick<typeof runningExecutions, 'register'>, registration: Parameters<typeof runningExecutions.register>[0], onRegistered?: () => void): void;
|
|
54
58
|
/**
|
|
55
59
|
* Decide whether (and which) project context to inject into the conversation prompt.
|
|
56
60
|
* Returns the {id, contextDir} pair for buildConversationPrompt, or null to inject nothing.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// input: agent facade, prompt
|
|
2
|
-
// output:
|
|
3
|
-
// pos:
|
|
4
|
-
// >>>
|
|
1
|
+
// input: agent facade, prompt serializers, execution registry
|
|
2
|
+
// output: plain turns and backend-ready prompt callbacks
|
|
3
|
+
// pos: Thread-free user-turn execution
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
//
|
|
6
6
|
// Why this exists: plain user chat messages used to be wrapped in a `templateName:'default'`
|
|
7
7
|
// ThreadRecord and run through runThread() with ~12 `isDefault` short-circuits. That coupled
|
|
@@ -16,6 +16,15 @@ import { projectStore } from '../domain/projects/index.js';
|
|
|
16
16
|
import * as executionRegistry from '../domain/executions/registry.js';
|
|
17
17
|
import { sessionStore } from '../store/session-registry-repo.js';
|
|
18
18
|
import { runningExecutions } from '../core/running-executions.js';
|
|
19
|
+
import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
|
|
20
|
+
export function registerConversationHandle(registry, registration, onRegistered) {
|
|
21
|
+
registry.register(registration);
|
|
22
|
+
onRegistered?.();
|
|
23
|
+
}
|
|
24
|
+
function buildBackendPrompt(prompt, files) {
|
|
25
|
+
const attachments = files.map((file) => ({ mimeType: file.mimetype, path: file.localPath }));
|
|
26
|
+
return buildAgentPrompt(prompt, attachments);
|
|
27
|
+
}
|
|
19
28
|
/**
|
|
20
29
|
* Decide whether (and which) project context to inject into the conversation prompt.
|
|
21
30
|
* Returns the {id, contextDir} pair for buildConversationPrompt, or null to inject nothing.
|
|
@@ -61,7 +70,7 @@ export async function runConversation(opts) {
|
|
|
61
70
|
// on the session's first turn (see resolveConversationProject for the exact gating).
|
|
62
71
|
project: resolveConversationProject({ channel: opts.channel, projectId: opts.projectId, isFreshSession }),
|
|
63
72
|
});
|
|
64
|
-
opts.onPromptBuilt?.(prompt);
|
|
73
|
+
opts.onPromptBuilt?.(buildBackendPrompt(prompt, opts.files));
|
|
65
74
|
// Attribute cost/execution to the session's bound project (from the registry record), NOT a
|
|
66
75
|
// re-derivation from the message text. A session created under project X stays project X even if
|
|
67
76
|
// no message ever mentions X literally (that mismatch previously dumped everything into 'general').
|
|
@@ -121,7 +130,7 @@ export async function runConversation(opts) {
|
|
|
121
130
|
});
|
|
122
131
|
// Track the handle for cancellation under the channel key (preserves !cancel / supersede /
|
|
123
132
|
// killByKey paths); executionId is indexed too so the Cancel button can resolve it.
|
|
124
|
-
runningExecutions
|
|
133
|
+
registerConversationHandle(runningExecutions, {
|
|
125
134
|
threadId: null,
|
|
126
135
|
channel: opts.channel,
|
|
127
136
|
agentSlotId: null,
|
|
@@ -131,7 +140,7 @@ export async function runConversation(opts) {
|
|
|
131
140
|
backend: channelBackend,
|
|
132
141
|
agentProcess: handle.agentProcess,
|
|
133
142
|
sessionId: handle.sessionId,
|
|
134
|
-
});
|
|
143
|
+
}, opts.onExecutionRegistered);
|
|
135
144
|
let result;
|
|
136
145
|
try {
|
|
137
146
|
result = await handle.promise;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { PlatformAdapter, MessageRef } from '../platform/index.js';
|
|
2
2
|
import type { AgentResult, ContextUsage } from '../core/types/agent-types.js';
|
|
3
|
+
import { type TurnMutationRelease } from './turn-mutation-lock.js';
|
|
4
|
+
import { conversationLedger } from '../store/conversation-ledger-repo.js';
|
|
5
|
+
import * as sessionBackup from '../domain/sessions/session-backup.js';
|
|
3
6
|
import type { ContinuationSink } from '../agent-adapter/types.js';
|
|
4
7
|
export declare function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger, sessionName, threadAnchorId, userMessageTs, projectId, onAssistantMessage, onToolUse, onToolResult, onContextUsage, registerContinuationSink }: {
|
|
5
8
|
result: AgentResult;
|
|
@@ -55,4 +58,23 @@ export declare function reprocessMessage(channel: string, text: string, adapter:
|
|
|
55
58
|
sessionName: string | null;
|
|
56
59
|
supersededStatusTimestamps?: string[];
|
|
57
60
|
}): void;
|
|
58
|
-
|
|
61
|
+
interface TurnTrackingDeps {
|
|
62
|
+
resolveBackend(channel: string): string;
|
|
63
|
+
getProfile(channel: string): string | null;
|
|
64
|
+
ledger: Pick<typeof conversationLedger, 'initAndBeginTurn' | 'setBackupPath'>;
|
|
65
|
+
backup: Pick<typeof sessionBackup, 'findPISessionFile' | 'backupSessionFile' | 'createBackup'>;
|
|
66
|
+
}
|
|
67
|
+
export interface TurnTrackingOptions {
|
|
68
|
+
onAccepted?: () => void;
|
|
69
|
+
mutationRelease?: TurnMutationRelease;
|
|
70
|
+
deps?: TurnTrackingDeps;
|
|
71
|
+
}
|
|
72
|
+
export type TurnTrackingToken = symbol;
|
|
73
|
+
export declare function markPendingTurnSuperseded(channel: string): void;
|
|
74
|
+
export declare function isPendingTurnSuperseded(channel: string): boolean;
|
|
75
|
+
export declare function consumePendingTurnSupersession(channel: string, token: TurnTrackingToken): boolean;
|
|
76
|
+
export declare function finishTurnTracking(channel: string, token: TurnTrackingToken): void;
|
|
77
|
+
export declare function isTurnTrackingPending(channel: string): boolean;
|
|
78
|
+
export declare function waitForTurnTracking(channel: string): Promise<void>;
|
|
79
|
+
export declare function initTurnTracking(channel: string, trackSessionId: string | null, backendSessionId: string | null, sessionName: string | null, userMessageTs: string, userMessageText: string, statusMessageTs: string, options?: TurnTrackingOptions): Promise<TurnTrackingToken>;
|
|
80
|
+
export {};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output:
|
|
3
|
-
// pos: Agent
|
|
4
|
-
// >>>
|
|
1
|
+
// input: turns, mutation leases, results and callbacks
|
|
2
|
+
// output: snapshot barriers and provider finalization
|
|
3
|
+
// pos: Agent turn initialization and completion
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { createLogger } from '../core/log.js';
|
|
6
6
|
import { Icons } from '../core/icons.js';
|
|
7
7
|
import { t } from '../core/i18n.js';
|
|
8
8
|
import { trackPendingTask } from './busy-tracker.js';
|
|
9
9
|
import { enqueue } from './conduit-queue.js';
|
|
10
10
|
import { supersededEdits } from './superseded-edits.js';
|
|
11
|
+
import { acquireTurnMutationLock } from './turn-mutation-lock.js';
|
|
11
12
|
import { runningExecutions } from '../core/running-executions.js';
|
|
12
13
|
import { finalizeLocalExecution, buildSessionTag, buildUserProcessingMessage, makeFallbackNotifier, makeStreamingMessageCallback, computeElapsed, formatMetricsSuffix, writeStatus, sealStatus, buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from './status-helpers.js';
|
|
13
14
|
import { getSessionAsync, setSessionAsync } from '../domain/sessions/session.js';
|
|
@@ -367,11 +368,19 @@ async function executeRetry(channel, text, adapter, opts) {
|
|
|
367
368
|
});
|
|
368
369
|
initStatusBlocks(statusMsg, retryBlocksTemplate);
|
|
369
370
|
updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, opts.supersededStatusTimestamps, retryPrefix, startTime, sessionName, sessionId);
|
|
370
|
-
await initTurnTracking(channel, sessionId, backendSessionId, sessionName, userMessageTs, text, statusMsg.messageId);
|
|
371
|
+
const turnTrackingToken = await initTurnTracking(channel, sessionId, backendSessionId, sessionName, userMessageTs, text, statusMsg.messageId);
|
|
372
|
+
if (consumePendingTurnSupersession(channel, turnTrackingToken)) {
|
|
373
|
+
finishTurnTracking(channel, turnTrackingToken);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
371
376
|
const onMessagePosted = (ref) => void conversationLedger.addResponseTs(channel, userMessageTs, ref.messageId).catch((e) => log.error(e));
|
|
372
|
-
await runRetryAgent({
|
|
377
|
+
await runRetryAgent({
|
|
378
|
+
channel, text, adapter, statusMsg, startTime, sessionId, backendSessionId,
|
|
379
|
+
sessionName, projectId, userMessageTs, retryPrefix, onMessagePosted,
|
|
380
|
+
retryDest, turnTrackingToken,
|
|
381
|
+
});
|
|
373
382
|
}
|
|
374
|
-
async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, sessionId, backendSessionId, sessionName, projectId, userMessageTs, retryPrefix, onMessagePosted, retryDest }) {
|
|
383
|
+
async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, sessionId, backendSessionId, sessionName, projectId, userMessageTs, retryPrefix, onMessagePosted, retryDest, turnTrackingToken }) {
|
|
375
384
|
const agentMessage = normalizeSkillCommandPrefix(text || '');
|
|
376
385
|
let executionId = null;
|
|
377
386
|
let handle;
|
|
@@ -393,6 +402,7 @@ async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, ses
|
|
|
393
402
|
onProgress: buildRetryProgressUpdater(adapter, channel, statusMsg, retryPrefix, startTime, sessionName, sessionId),
|
|
394
403
|
});
|
|
395
404
|
runningExecutions.register({ threadId: null /* A5: edit-retry — threadId not yet wired; Cancel button will warn */, channel, agentSlotId: null, executionId, kill: () => handle.kill(), backend: retryBackend });
|
|
405
|
+
finishTurnTracking(channel, turnTrackingToken);
|
|
396
406
|
const result = await handle.promise;
|
|
397
407
|
runningExecutions.complete(executionId, result?.total_cost_usd ?? 0);
|
|
398
408
|
clearStreamingCallback(channel);
|
|
@@ -416,6 +426,9 @@ async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, ses
|
|
|
416
426
|
clearStreamingCallback(channel);
|
|
417
427
|
await handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId: handle?.sessionId, userMessageTs });
|
|
418
428
|
}
|
|
429
|
+
finally {
|
|
430
|
+
finishTurnTracking(channel, turnTrackingToken);
|
|
431
|
+
}
|
|
419
432
|
}
|
|
420
433
|
function buildRetryProgressUpdater(adapter, channel, statusMsg, retryPrefix, startTime, sessionName, sessionId) {
|
|
421
434
|
return (progress) => {
|
|
@@ -443,38 +456,88 @@ function updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, super
|
|
|
443
456
|
}
|
|
444
457
|
}).catch(() => { });
|
|
445
458
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
if (
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
459
|
+
const defaultTurnTrackingDeps = {
|
|
460
|
+
resolveBackend: resolveBackendForChannel,
|
|
461
|
+
getProfile: getActiveProfile,
|
|
462
|
+
ledger: conversationLedger,
|
|
463
|
+
backup: sessionBackup,
|
|
464
|
+
};
|
|
465
|
+
async function snapshotTurn(deps, backend, backendSessionId, turnIndex) {
|
|
466
|
+
if (!backendSessionId)
|
|
467
|
+
return null;
|
|
468
|
+
if (backend !== 'pi')
|
|
469
|
+
return deps.backup.createBackup(backendSessionId, turnIndex);
|
|
470
|
+
const piFile = await deps.backup.findPISessionFile(backendSessionId);
|
|
471
|
+
return piFile ? deps.backup.backupSessionFile(piFile, turnIndex) : null;
|
|
472
|
+
}
|
|
473
|
+
const currentTurnTracking = new Map();
|
|
474
|
+
const turnTrackingByToken = new Map();
|
|
475
|
+
const supersededPendingTurns = new Map();
|
|
476
|
+
export function markPendingTurnSuperseded(channel) {
|
|
477
|
+
const token = currentTurnTracking.get(channel);
|
|
478
|
+
if (token)
|
|
479
|
+
supersededPendingTurns.set(channel, token);
|
|
480
|
+
}
|
|
481
|
+
export function isPendingTurnSuperseded(channel) {
|
|
482
|
+
return supersededPendingTurns.has(channel);
|
|
483
|
+
}
|
|
484
|
+
export function consumePendingTurnSupersession(channel, token) {
|
|
485
|
+
if (supersededPendingTurns.get(channel) !== token)
|
|
486
|
+
return false;
|
|
487
|
+
supersededPendingTurns.delete(channel);
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
export function finishTurnTracking(channel, token) {
|
|
491
|
+
const state = turnTrackingByToken.get(token);
|
|
492
|
+
if (!state || state.channel !== channel)
|
|
493
|
+
return;
|
|
494
|
+
turnTrackingByToken.delete(token);
|
|
495
|
+
if (currentTurnTracking.get(channel) === token)
|
|
496
|
+
currentTurnTracking.delete(channel);
|
|
497
|
+
if (supersededPendingTurns.get(channel) === token)
|
|
498
|
+
supersededPendingTurns.delete(channel);
|
|
499
|
+
state.release?.();
|
|
500
|
+
}
|
|
501
|
+
export function isTurnTrackingPending(channel) {
|
|
502
|
+
return currentTurnTracking.has(channel);
|
|
503
|
+
}
|
|
504
|
+
export function waitForTurnTracking(channel) {
|
|
505
|
+
const token = currentTurnTracking.get(channel);
|
|
506
|
+
const operation = token ? turnTrackingByToken.get(token)?.operation : null;
|
|
507
|
+
return operation ? operation.then(() => undefined) : Promise.resolve();
|
|
508
|
+
}
|
|
509
|
+
async function runTurnTracking(args, options, token) {
|
|
510
|
+
const release = options.mutationRelease ?? await acquireTurnMutationLock(args.channel);
|
|
511
|
+
try {
|
|
512
|
+
const deps = options.deps ?? defaultTurnTrackingDeps;
|
|
513
|
+
const backend = deps.resolveBackend(args.channel);
|
|
514
|
+
const { turnIndex } = await deps.ledger.initAndBeginTurn(args.channel, {
|
|
515
|
+
sessionId: args.trackSessionId || null, sessionName: args.sessionName, backend,
|
|
516
|
+
profileName: deps.getProfile(args.channel), userMessageTs: args.userMessageTs,
|
|
517
|
+
userMessageText: args.userMessageText || '', statusMessageTs: args.statusMessageTs,
|
|
518
|
+
});
|
|
519
|
+
const backupPath = await snapshotTurn(deps, backend, args.backendSessionId, turnIndex);
|
|
520
|
+
if (backupPath)
|
|
521
|
+
await deps.ledger.setBackupPath(args.channel, args.userMessageTs, backupPath);
|
|
522
|
+
options.onAccepted?.();
|
|
523
|
+
const state = turnTrackingByToken.get(token);
|
|
524
|
+
if (state)
|
|
525
|
+
state.release = release;
|
|
526
|
+
return token;
|
|
479
527
|
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
release();
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
export function initTurnTracking(channel, trackSessionId, backendSessionId, sessionName, userMessageTs, userMessageText, statusMessageTs, options = {}) {
|
|
534
|
+
const token = Symbol(channel);
|
|
535
|
+
const operation = runTurnTracking({
|
|
536
|
+
channel, trackSessionId, backendSessionId, sessionName,
|
|
537
|
+
userMessageTs, userMessageText, statusMessageTs,
|
|
538
|
+
}, options, token);
|
|
539
|
+
currentTurnTracking.set(channel, token);
|
|
540
|
+
turnTrackingByToken.set(token, { channel, operation, release: null });
|
|
541
|
+
void operation.catch(() => finishTurnTracking(channel, token));
|
|
542
|
+
return operation;
|
|
480
543
|
}
|
|
@@ -82,6 +82,8 @@ export interface MidTurnInjectCtx {
|
|
|
82
82
|
/** The inbound platform message id — the ledger turn's key. */
|
|
83
83
|
messageId: string;
|
|
84
84
|
attachments?: AttachmentMeta[];
|
|
85
|
+
/** Lazily download platform-native files only after an injectable target is selected. */
|
|
86
|
+
prepareBackendAttachments?: () => Promise<UserMessage['attachments']>;
|
|
85
87
|
}
|
|
86
88
|
/** Only plain human messages may fold into an in-flight turn. Commands and synthetic session
|
|
87
89
|
* re-entry messages own separate dispatch semantics; edits kill the live execution before routing. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// input: live execution,
|
|
2
|
-
// output:
|
|
1
|
+
// input: live execution, lazy platform files, path/pending seams
|
|
2
|
+
// output: injected turns, resolved files, DEBUG prompts
|
|
3
3
|
// pos: Busy-channel injection branch of AgentRunner.route
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
/**
|
|
@@ -13,11 +13,16 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { randomUUID } from 'node:crypto';
|
|
15
15
|
import { Capability, CAPABILITIES_BY_BACKEND } from '../agent-adapter/capabilities.js';
|
|
16
|
+
import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
|
|
16
17
|
import { SYNTHETIC_CALLBACK_SENDER } from '../platform/types.js';
|
|
17
18
|
import { createLogger } from '../core/log.js';
|
|
19
|
+
import { resolveWorkspaceRelPath } from '../core/paths.js';
|
|
20
|
+
import { getSettings } from '../core/settings.js';
|
|
18
21
|
const log = createLogger('mid-turn-inject');
|
|
19
22
|
/** Leak guard: a wedged process must not hold the daemon restart gate forever. */
|
|
20
|
-
|
|
23
|
+
function defaultMaxWaitMs() {
|
|
24
|
+
return getSettings().injectWaitMaxS * 1000;
|
|
25
|
+
}
|
|
21
26
|
/** Only plain human messages may fold into an in-flight turn. Commands and synthetic session
|
|
22
27
|
* re-entry messages own separate dispatch semantics; edits kill the live execution before routing. */
|
|
23
28
|
export function isInjectableMessage(opts) {
|
|
@@ -144,7 +149,7 @@ class PendingLifecycle {
|
|
|
144
149
|
disposeIfIdle(this.record.channel);
|
|
145
150
|
}
|
|
146
151
|
}
|
|
147
|
-
function buildPendingRecord(deps, ctx, sessionId, backend, ts) {
|
|
152
|
+
function buildPendingRecord(deps, ctx, message, sessionId, backend, ts) {
|
|
148
153
|
return {
|
|
149
154
|
id: deps.createPendingId?.() ?? randomUUID(),
|
|
150
155
|
sessionId,
|
|
@@ -155,12 +160,12 @@ function buildPendingRecord(deps, ctx, sessionId, backend, ts) {
|
|
|
155
160
|
profileName: ctx.profileName ?? null,
|
|
156
161
|
text: ctx.text,
|
|
157
162
|
attachments: ctx.attachments,
|
|
158
|
-
...(deps.captureDebug ? { agentMessage:
|
|
163
|
+
...(deps.captureDebug ? { agentMessage: buildAgentPrompt(message.text, message.attachments ?? []) } : {}),
|
|
159
164
|
createdAt: ts,
|
|
160
165
|
};
|
|
161
166
|
}
|
|
162
167
|
function armReleaseCap(deps, entry) {
|
|
163
|
-
const capMs = deps.maxWaitMs ??
|
|
168
|
+
const capMs = deps.maxWaitMs ?? defaultMaxWaitMs();
|
|
164
169
|
if (capMs <= 0)
|
|
165
170
|
return;
|
|
166
171
|
const timer = setTimeout(() => {
|
|
@@ -205,13 +210,14 @@ export async function tryInjectIntoLiveTurn(deps, ctx) {
|
|
|
205
210
|
const target = selectInjectTarget(deps.getLiveExecutions(ctx.channel));
|
|
206
211
|
if (!target)
|
|
207
212
|
return false;
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
213
|
+
const platformAttachments = ctx.prepareBackendAttachments
|
|
214
|
+
? await ctx.prepareBackendAttachments()
|
|
215
|
+
: undefined;
|
|
216
|
+
const message = prepareBackendMessage(ctx, platformAttachments);
|
|
217
|
+
if (!target.proc.injectUserMessage(message))
|
|
212
218
|
return false;
|
|
213
219
|
const state = stateFor(ctx.channel);
|
|
214
|
-
const record = buildPendingRecord(deps, ctx, ctx.sessionId, target.backend, deps.now());
|
|
220
|
+
const record = buildPendingRecord(deps, ctx, message, ctx.sessionId, target.backend, deps.now());
|
|
215
221
|
const entry = new PendingLifecycle(record, deps, state);
|
|
216
222
|
deps.track(+1);
|
|
217
223
|
state.pending.push(entry);
|
|
@@ -286,11 +292,21 @@ function registerSinks(deps, channel, sessionId, proc, state) {
|
|
|
286
292
|
onResult: () => handleContinuationResult(deps, state, sessionId, channel),
|
|
287
293
|
});
|
|
288
294
|
}
|
|
289
|
-
|
|
295
|
+
function prepareBackendMessage(ctx, platformAttachments) {
|
|
296
|
+
const platform = platformAttachments ?? [];
|
|
297
|
+
const web = attachmentsForBackend(ctx.attachments) ?? [];
|
|
298
|
+
const attachments = [...platform, ...web];
|
|
299
|
+
return { text: ctx.text, attachments: attachments.length > 0 ? attachments : undefined };
|
|
300
|
+
}
|
|
301
|
+
/** Resolve UI attachment aliases before handing files to the backend. */
|
|
290
302
|
function attachmentsForBackend(attachments) {
|
|
291
303
|
if (!attachments?.length)
|
|
292
304
|
return undefined;
|
|
293
|
-
|
|
305
|
+
const resolved = attachments.flatMap((attachment) => {
|
|
306
|
+
const localPath = resolveWorkspaceRelPath(attachment.path);
|
|
307
|
+
return localPath ? [{ mimeType: attachment.mimeType, path: localPath }] : [];
|
|
308
|
+
});
|
|
309
|
+
return resolved.length > 0 ? resolved : undefined;
|
|
294
310
|
}
|
|
295
311
|
/** Test hook: drop all per-channel injection state. */
|
|
296
312
|
export const _test = {
|
|
@@ -3,11 +3,10 @@ import type { EventBus } from '../events/index.js';
|
|
|
3
3
|
import type { ThreadRecord, RunThreadOptions } from '../core/types/thread-types.js';
|
|
4
4
|
import { type ResumeEntry } from '../domain/costs/resume-registry.js';
|
|
5
5
|
import { agentRunner } from './agent-runner.js';
|
|
6
|
-
/** Auto-resume
|
|
6
|
+
/** Auto-resume feature gate. */
|
|
7
7
|
export declare function isAutoResumeEnabled(): boolean;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export declare function buildResumeReminder(): string;
|
|
8
|
+
import { buildResumeReminder } from '../core/resume-reminder.js';
|
|
9
|
+
export { buildResumeReminder };
|
|
11
10
|
export interface ResumeDeps {
|
|
12
11
|
takeReady: (activeProviders: string[]) => ResumeEntry[];
|
|
13
12
|
activeProviders: () => string[];
|
|
@@ -41,4 +40,3 @@ export declare function registerResumeWakeOnAgentSettle(bus: EventBus, adapter:
|
|
|
41
40
|
/** Drain entries whose provider is no longer active and re-enter each target.
|
|
42
41
|
* Called after provider clears and during startup reconciliation. Never throws. */
|
|
43
42
|
export declare function dispatchPendingResumes(adapter: PlatformAdapter, overrides?: Partial<ResumeDeps>): Promise<void>;
|
|
44
|
-
export {};
|