@cortex-agent/server 2026.10.15 → 2026.10.21
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 +76 -50
- package/defaults/board/board.css +140 -62
- package/defaults/board/scaffold.html +36 -13
- package/defaults/config/environments/creative.json +0 -1
- package/defaults/config/environments/main.json +1 -2
- package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
- package/defaults/plugins/cortex-system/plugin.json +2 -2
- package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
- package/dist/agent-adapter/claude/adapter.d.ts +2 -5
- package/dist/agent-adapter/claude/adapter.js +6 -5
- package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
- package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
- package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
- package/dist/agent-adapter/claude/cache-refresh.js +145 -0
- package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
- package/dist/agent-adapter/claude/cache-touch.js +75 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
- package/dist/agent-adapter/claude/event-parser.js +33 -17
- package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
- package/dist/agent-adapter/claude/event-translator.js +2 -0
- package/dist/agent-adapter/claude/session-options.d.ts +6 -13
- package/dist/agent-adapter/claude/session-options.js +2 -13
- package/dist/agent-adapter/claude/spawn-args.d.ts +4 -21
- package/dist/agent-adapter/claude/spawn-args.js +17 -24
- package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
- package/dist/agent-adapter/claude/transcript-clear.js +217 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
- package/dist/agent-adapter/claude/turn-machine.js +21 -68
- package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
- package/dist/agent-adapter/claude/window-warmup.js +38 -0
- package/dist/agent-adapter/continuation-phase.js +3 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
- package/dist/agent-adapter/pi/adapter.d.ts +0 -1
- package/dist/agent-adapter/pi/adapter.js +5 -13
- package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
- package/dist/agent-adapter/pi/event-parser.js +43 -27
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
- package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
- package/dist/agent-adapter/pi/pi-session.js +15 -0
- package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
- package/dist/agent-adapter/pi/providers-config.js +1 -1
- package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
- package/dist/agent-adapter/pi/quota-sink.js +3 -3
- package/dist/agent-adapter/pi/runtime.js +6 -1
- package/dist/agent-adapter/pi/session-options.d.ts +9 -13
- package/dist/agent-adapter/pi/session-options.js +12 -25
- package/dist/agent-adapter/run-events.d.ts +11 -10
- package/dist/agent-adapter/run-events.js +2 -0
- package/dist/agent-adapter/types.d.ts +5 -4
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/codex-quota.d.ts +1 -1
- package/dist/core/codex-quota.js +1 -1
- package/dist/core/gateway-generator.d.ts +9 -11
- package/dist/core/gateway-generator.js +31 -58
- package/dist/core/locales/en.d.ts +51 -77
- package/dist/core/locales/slices/commands.d.ts +26 -31
- package/dist/core/locales/slices/commands.js +54 -64
- package/dist/core/locales/slices/init.d.ts +8 -19
- package/dist/core/locales/slices/init.js +17 -53
- package/dist/core/locales/slices/interactions.d.ts +3 -3
- package/dist/core/locales/slices/interactions.js +6 -6
- package/dist/core/locales/slices/notices.d.ts +1 -3
- package/dist/core/locales/slices/notices.js +2 -6
- package/dist/core/locales/slices/scheduling.d.ts +9 -9
- package/dist/core/locales/slices/scheduling.js +18 -18
- package/dist/core/locales/slices/status.d.ts +0 -4
- package/dist/core/locales/slices/status.js +0 -8
- package/dist/core/locales/slices/tui.d.ts +0 -1
- package/dist/core/locales/slices/tui.js +0 -2
- package/dist/core/locales/slices/uimsg.d.ts +4 -7
- package/dist/core/locales/slices/uimsg.js +9 -15
- package/dist/core/models-generator.d.ts +29 -0
- package/dist/core/models-generator.js +82 -0
- package/dist/core/paths.d.ts +1 -1
- package/dist/core/paths.js +1 -1
- package/dist/core/settings-spec.d.ts +25 -0
- package/dist/core/settings-spec.js +34 -0
- package/dist/core/status-format.d.ts +3 -2
- package/dist/core/status-format.js +2 -2
- package/dist/core/types/environment-types.d.ts +0 -2
- package/dist/domain/agents/agent-state.d.ts +11 -56
- package/dist/domain/agents/agent-state.js +48 -115
- package/dist/domain/agents/agent-switch.d.ts +2 -24
- package/dist/domain/agents/agent-switch.js +9 -72
- package/dist/domain/agents/config.d.ts +11 -61
- package/dist/domain/agents/config.js +47 -154
- package/dist/domain/agents/engine-selection.d.ts +21 -0
- package/dist/domain/agents/engine-selection.js +37 -0
- package/dist/domain/agents/environments/registry.js +2 -1
- package/dist/domain/agents/environments/resolve.js +0 -1
- package/dist/domain/agents/environments/schema.d.ts +0 -1
- package/dist/domain/agents/environments/schema.js +0 -1
- package/dist/domain/agents/index.d.ts +2 -1
- package/dist/domain/agents/index.js +3 -7
- package/dist/domain/agents/model-selection.d.ts +18 -70
- package/dist/domain/agents/model-selection.js +100 -150
- package/dist/domain/agents/models.d.ts +12 -0
- package/dist/domain/agents/models.js +94 -0
- package/dist/domain/agents/subagent/registry.d.ts +2 -0
- package/dist/domain/agents/subagent/registry.js +8 -0
- package/dist/domain/agents/subagent/runner.d.ts +5 -5
- package/dist/domain/agents/subagent/runner.js +12 -35
- package/dist/domain/auth/auth-status.d.ts +4 -4
- package/dist/domain/auth/auth-status.js +17 -28
- package/dist/domain/auth/gateway-sync.d.ts +6 -26
- package/dist/domain/auth/gateway-sync.js +31 -75
- package/dist/domain/benchmark/identity.d.ts +3 -5
- package/dist/domain/benchmark/identity.js +0 -1
- package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
- package/dist/domain/benchmark/production-attempt-identity.js +32 -35
- package/dist/domain/benchmark/session-evidence.d.ts +2 -1
- package/dist/domain/benchmark/session-evidence.js +8 -1
- package/dist/domain/browser/broker.d.ts +99 -0
- package/dist/domain/browser/broker.js +487 -0
- package/dist/domain/costs/claude-account.js +21 -0
- package/dist/domain/costs/rate-limit-throttle.js +3 -1
- package/dist/domain/costs/reset-account.d.ts +2 -0
- package/dist/domain/costs/usage-service.d.ts +1 -1
- package/dist/domain/costs/usage-service.js +20 -7
- package/dist/domain/mcp/tools/context.d.ts +5 -6
- package/dist/domain/mcp/tools/context.js +17 -3
- package/dist/domain/mcp/tools/subagent.js +1 -1
- package/dist/domain/mcp/tools/ui-file.js +1 -1
- package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
- package/dist/domain/pi-providers/custom-provider-model.js +1 -1
- package/dist/domain/remote/device-browser.js +1 -1
- package/dist/domain/remote/device-chrome-commands.js +2 -0
- package/dist/domain/remote/device-port.js +2 -2
- package/dist/domain/runs/attempt.d.ts +3 -3
- package/dist/domain/runs/attempt.js +2 -3
- package/dist/domain/runs/builders.d.ts +4 -4
- package/dist/domain/runs/builders.js +4 -5
- package/dist/domain/runs/compact.d.ts +4 -17
- package/dist/domain/runs/compact.js +14 -56
- package/dist/domain/runs/config-resolver.d.ts +15 -83
- package/dist/domain/runs/config-resolver.js +24 -150
- package/dist/domain/runs/engine-spec.d.ts +8 -8
- package/dist/domain/runs/engine-spec.js +15 -31
- package/dist/domain/runs/events.d.ts +1 -1
- package/dist/domain/runs/fallback.d.ts +6 -38
- package/dist/domain/runs/fallback.js +10 -72
- package/dist/domain/runs/notices.d.ts +1 -11
- package/dist/domain/runs/notices.js +3 -30
- package/dist/domain/runs/request.d.ts +4 -3
- package/dist/domain/runs/retryable-errors.d.ts +0 -13
- package/dist/domain/runs/retryable-errors.js +0 -17
- package/dist/domain/runs/run.d.ts +12 -42
- package/dist/domain/runs/run.js +40 -147
- package/dist/domain/runs/service.d.ts +1 -1
- package/dist/domain/runs/service.js +8 -3
- package/dist/domain/runs/spec-loader.d.ts +1 -1
- package/dist/domain/runs/spend.d.ts +1 -1
- package/dist/domain/runs/spend.js +1 -1
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +25 -19
- package/dist/domain/scheduling/schedule-ops.d.ts +0 -1
- package/dist/domain/scheduling/schedule-ops.js +2 -5
- package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
- package/dist/domain/scheduling/schedule-selection.js +16 -0
- package/dist/domain/scheduling/schedule-spec.d.ts +6 -5
- package/dist/domain/scheduling/schedule-spec.js +6 -6
- package/dist/domain/scheduling/scheduler.d.ts +3 -1
- package/dist/domain/scheduling/scheduler.js +22 -21
- package/dist/domain/sessions/session-hooks.d.ts +5 -4
- package/dist/domain/sessions/session-hooks.js +15 -33
- package/dist/domain/sessions/session-lifecycle.d.ts +19 -51
- package/dist/domain/sessions/session-lifecycle.js +34 -96
- package/dist/domain/system/doctor.d.ts +3 -3
- package/dist/domain/system/doctor.js +22 -26
- package/dist/domain/system/own-bin-path.d.ts +13 -0
- package/dist/domain/system/own-bin-path.js +36 -0
- package/dist/domain/system/terminal-cli/index.d.ts +58 -0
- package/dist/domain/system/terminal-cli/index.js +100 -0
- package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
- package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
- package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
- package/dist/domain/system/terminal-cli/registrar.js +1 -0
- package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
- package/dist/domain/system/terminal-cli/shims.js +108 -0
- package/dist/domain/system/terminal-cli/state.d.ts +7 -0
- package/dist/domain/system/terminal-cli/state.js +36 -0
- package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
- package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
- package/dist/domain/tui-session/tui-session-service.js +1 -1
- package/dist/domain/tui-session/types.d.ts +2 -2
- package/dist/domain/ui-service/app-router.d.ts +49 -71
- package/dist/domain/ui-service/app-router.js +9 -13
- package/dist/domain/ui-service/assistant-snapshots.js +2 -0
- package/dist/domain/ui-service/contract.parity.d.ts +19 -0
- package/dist/domain/ui-service/contract.parity.js +1 -0
- package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
- package/dist/domain/ui-service/inline-media-types.js +1 -0
- package/dist/domain/ui-service/input-schemas.d.ts +52 -115
- package/dist/domain/ui-service/input-schemas.js +38 -84
- package/dist/domain/ui-service/mutate/auth.d.ts +1 -1
- package/dist/domain/ui-service/mutate/auth.js +3 -2
- package/dist/domain/ui-service/mutate/config.d.ts +0 -8
- package/dist/domain/ui-service/mutate/config.js +0 -22
- package/dist/domain/ui-service/mutate/models.d.ts +13 -0
- package/dist/domain/ui-service/mutate/models.js +137 -0
- package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
- package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
- package/dist/domain/ui-service/mutate/sessions.d.ts +2 -2
- package/dist/domain/ui-service/mutate/sessions.js +29 -126
- package/dist/domain/ui-service/query/config.js +22 -42
- package/dist/domain/ui-service/query/models.js +2 -2
- package/dist/domain/ui-service/query/schedules.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -13
- package/dist/domain/ui-service/types.d.ts +51 -177
- package/dist/domain/ui-service/ui-service.d.ts +23 -49
- package/dist/domain/ui-service/ui-service.js +8 -6
- package/dist/entry/app.js +42 -19
- package/dist/entry/browser-cli.d.ts +39 -0
- package/dist/entry/browser-cli.js +317 -0
- package/dist/entry/cli-help.d.ts +1 -0
- package/dist/entry/cli-help.js +37 -6
- package/dist/entry/cli.js +16 -14
- package/dist/entry/daemon.js +2 -0
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.d.ts +7 -8
- package/dist/entry/init.js +89 -249
- package/dist/entry/path-cli.d.ts +4 -0
- package/dist/entry/path-cli.js +65 -0
- package/dist/entry/schedule-cli.js +13 -6
- package/dist/entry/shutdown.d.ts +1 -1
- package/dist/entry/shutdown.js +8 -1
- package/dist/entry/start-ui-http.js +8 -0
- package/dist/entry/ui-service-wiring.js +8 -10
- package/dist/events/event-types.d.ts +3 -2
- package/dist/orchestration/agent-runner.d.ts +2 -2
- package/dist/orchestration/agent-runner.js +10 -9
- package/dist/orchestration/benchmark-session-webhook.js +13 -1
- package/dist/orchestration/browser-webhook.d.ts +11 -0
- package/dist/orchestration/browser-webhook.js +28 -0
- package/dist/orchestration/cache-keep-warm.d.ts +77 -0
- package/dist/orchestration/cache-keep-warm.js +213 -0
- package/dist/orchestration/claude-window-warmup.d.ts +40 -0
- package/dist/orchestration/claude-window-warmup.js +126 -0
- package/dist/orchestration/conversation-request.d.ts +6 -10
- package/dist/orchestration/conversation-request.js +5 -23
- package/dist/orchestration/delta-coalescer.d.ts +4 -2
- package/dist/orchestration/delta-coalescer.js +5 -5
- package/dist/orchestration/edit-retry.js +9 -11
- package/dist/orchestration/inline-media-eager.d.ts +13 -0
- package/dist/orchestration/inline-media-eager.js +58 -0
- package/dist/orchestration/inline-media.d.ts +22 -0
- package/dist/orchestration/inline-media.js +151 -0
- package/dist/orchestration/interactions/ask-user-resume.js +3 -7
- package/dist/orchestration/interactions/interaction-handlers.js +6 -6
- package/dist/orchestration/mid-turn-inject.d.ts +2 -1
- package/dist/orchestration/mid-turn-inject.js +1 -1
- package/dist/orchestration/pending-injection-recovery.d.ts +2 -1
- package/dist/orchestration/pending-injection-recovery.js +1 -1
- package/dist/orchestration/routing/commands/index.js +4 -4
- package/dist/orchestration/routing/commands/mode.d.ts +5 -44
- package/dist/orchestration/routing/commands/mode.js +98 -272
- package/dist/orchestration/routing/commands/schedule.js +29 -18
- package/dist/orchestration/routing/commands/session.js +9 -9
- package/dist/orchestration/routing/commands/status.js +1 -1
- package/dist/orchestration/routing/commands/usage-format.js +3 -0
- package/dist/orchestration/routing/webhook.js +4 -0
- package/dist/orchestration/session-compact.d.ts +0 -1
- package/dist/orchestration/session-compact.js +5 -7
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/status-helpers.d.ts +0 -4
- package/dist/orchestration/status-helpers.js +0 -18
- package/dist/orchestration/subagent-webhook.js +9 -34
- package/dist/orchestration/team-webhook.d.ts +8 -9
- package/dist/orchestration/team-webhook.js +16 -42
- package/dist/orchestration/transcript-sink.d.ts +6 -0
- package/dist/orchestration/transcript-sink.js +21 -2
- package/dist/orchestration/turn/terminal.js +7 -7
- package/dist/orchestration/turn/turn-prep.d.ts +0 -8
- package/dist/orchestration/turn/turn-prep.js +0 -51
- package/dist/orchestration/turn/turn-tracking.d.ts +2 -2
- package/dist/orchestration/turn/turn-tracking.js +8 -5
- package/dist/orchestration/turn/turn.d.ts +0 -2
- package/dist/orchestration/turn/turn.js +13 -15
- package/dist/platform/adapters/tui/ports.d.ts +1 -1
- package/dist/platform/adapters/tui/tui-transcript.js +2 -0
- package/dist/platform/browser/agent-browser.d.ts +50 -0
- package/dist/platform/browser/agent-browser.js +165 -0
- package/dist/platform/browser/managed-browser.d.ts +1 -11
- package/dist/platform/browser/managed-browser.js +4 -12
- package/dist/platform/ui-http/browser-stream.d.ts +110 -0
- package/dist/platform/ui-http/browser-stream.js +447 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
- package/dist/platform/ui-http/ui-http-server.js +23 -6
- package/dist/store/conversation-history-reader.js +8 -0
- package/dist/store/conversation-history-repo.d.ts +8 -1
- package/dist/store/conversation-history-repo.js +5 -0
- package/dist/store/conversation-ledger-repo.d.ts +6 -6
- package/dist/store/conversation-ledger-repo.js +4 -4
- package/dist/store/models-repo.d.ts +18 -0
- package/dist/store/models-repo.js +74 -0
- package/dist/store/pending-injection-repo.d.ts +2 -1
- package/dist/store/pending-injection-repo.js +3 -1
- package/dist/store/retire-profiles-migration.d.ts +28 -0
- package/dist/store/retire-profiles-migration.js +335 -0
- package/dist/store/schedule-repo.d.ts +2 -1
- package/dist/store/session-registry-import.js +3 -2
- package/dist/store/session-registry-journal.d.ts +10 -13
- package/dist/store/session-registry-journal.js +48 -25
- package/dist/store/session-registry-repo.d.ts +4 -4
- package/dist/store/session-registry-repo.js +4 -5
- package/dist/store/version-migrations.d.ts +2 -3
- package/dist/store/version-migrations.js +19 -3
- package/dist/tui/slash-commands.js +2 -2
- package/dist/tui/turn-status.js +1 -1
- package/package.json +6 -4
- package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
- package/web/dist/assets/index-CaSZPg_H.css +1 -0
- package/web/dist/assets/index-CzOR7Edh.js +522 -0
- package/web/dist/assets/{index-CndZZ1IQ.js → index-cIGFv27z.js} +1 -1
- package/web/dist/index.html +3 -2
- package/web/dist/theme.css +6 -0
- package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
- package/dist/agent-adapter/browser-mcp-server.js +0 -28
- package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
- package/dist/agent-adapter/claude/browser-mcp.js +0 -10
- package/dist/core/profile-generator.d.ts +0 -79
- package/dist/core/profile-generator.js +0 -215
- package/dist/domain/agents/profile-manager.d.ts +0 -103
- package/dist/domain/agents/profile-manager.js +0 -286
- package/dist/domain/agents/profile-switch.d.ts +0 -49
- package/dist/domain/agents/profile-switch.js +0 -62
- package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
- package/dist/domain/ui-service/mutate/profiles.js +0 -151
- package/dist/store/profile-repo.d.ts +0 -20
- package/dist/store/profile-repo.js +0 -97
- package/web/dist/assets/index-B76ueW3q.js +0 -494
- package/web/dist/assets/index-C8O0yxg8.css +0 -1
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Keep-warm for Claude prompt caches.
|
|
2
|
+
//
|
|
3
|
+
// A Claude subscription session's prompt cache lives one hour past its last read. A session that
|
|
4
|
+
// still expects a wake (an open waitpoint, a busy worker, a background `agent` run) is often woken
|
|
5
|
+
// later than that, and the wake then rewrites its whole context at the cache-write price. Every few
|
|
6
|
+
// minutes this sweep finds such sessions whose cache is nearing the hour and reads it once through
|
|
7
|
+
// a fork that leaves the session's transcript alone (agent-adapter/claude/cache-refresh.ts). A read
|
|
8
|
+
// restarts the hour, so the cache survives until the wake, up to `cacheKeepWarmHours` after the
|
|
9
|
+
// session last called the model. A cache presumed expired is left alone: refreshing it would write
|
|
10
|
+
// the whole uncleared context, while the wake's cold resume clears old tool output first.
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import { createLogger } from '../core/log.js';
|
|
13
|
+
import { resolveSpawnCwd } from '../core/paths.js';
|
|
14
|
+
import { runRegistry } from '../core/run-registry.js';
|
|
15
|
+
import { getSettings } from '../core/settings.js';
|
|
16
|
+
import { shortSessionId } from '../core/short-session-id.js';
|
|
17
|
+
import { effectiveBackendSessionId, sessionStore } from '../store/session-registry-repo.js';
|
|
18
|
+
import { hasRunningBackgroundRuns } from '../domain/agents/subagent/registry.js';
|
|
19
|
+
import { recordCost } from '../domain/costs/cost-tracker.js';
|
|
20
|
+
import { requestRoute, resolveRunSelection } from '../domain/runs/config-resolver.js';
|
|
21
|
+
import { buildEngineSpec } from '../domain/runs/engine-spec.js';
|
|
22
|
+
import { isTeamLead } from '../domain/sessions/team.js';
|
|
23
|
+
import { cacheRefreshLaunch, runCacheRefresh, } from '../agent-adapter/claude/cache-refresh.js';
|
|
24
|
+
import { lastCacheTouch, lastModelActivity, noteCacheRefresh } from '../agent-adapter/claude/cache-touch.js';
|
|
25
|
+
import { computeTranscriptPath } from '../agent-adapter/claude/transcript-path.js';
|
|
26
|
+
import { conduitQueues, enqueueAndWait } from './conduit-queue.js';
|
|
27
|
+
import { conversationEngineRequest } from './conversation-request.js';
|
|
28
|
+
import { countOpenWaitpoints, describeTeam, isWorkerBusy } from './team-state.js';
|
|
29
|
+
const log = createLogger('cache-keep-warm');
|
|
30
|
+
export const KEEP_WARM_SWEEP_MS = 5 * 60_000;
|
|
31
|
+
/** Refresh once the cache is this old: ten minutes short of its one-hour lifetime. */
|
|
32
|
+
export const KEEP_WARM_REFRESH_AGE_MS = 50 * 60_000;
|
|
33
|
+
/** Past this the cache is presumed expired (a restart lost the refresh record, or a sweep missed
|
|
34
|
+
* the window). The window is wider than the sweep interval, so every pass-through is caught once. */
|
|
35
|
+
export const KEEP_WARM_MAX_AGE_MS = 58 * 60_000;
|
|
36
|
+
/** Below this a cold rewrite is cheap enough that keeping the cache is not worth a request. */
|
|
37
|
+
export const KEEP_WARM_MIN_CONTEXT_TOKENS = 100_000;
|
|
38
|
+
const HOUR_MS = 60 * 60_000;
|
|
39
|
+
function largeClaudeSession(session) {
|
|
40
|
+
const used = session.contextUsage?.usedTokens ?? 0;
|
|
41
|
+
if (session.backend !== 'claude' || used < KEEP_WARM_MIN_CONTEXT_TOKENS)
|
|
42
|
+
return null;
|
|
43
|
+
return effectiveBackendSessionId(session);
|
|
44
|
+
}
|
|
45
|
+
/** Only a subscription mode caches for an hour; elsewhere the cache is gone long before a refresh. */
|
|
46
|
+
function subscriptionSelection(session, deps, modes) {
|
|
47
|
+
let selection;
|
|
48
|
+
try {
|
|
49
|
+
selection = deps.selection(session);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return selection.backend === 'claude' && modes.includes(selection.mode) ? selection : null;
|
|
55
|
+
}
|
|
56
|
+
/** Due when the cache nears the hour but has not yet passed it, while the last model activity is
|
|
57
|
+
* within the cap. */
|
|
58
|
+
function refreshDue(target, deps, hours) {
|
|
59
|
+
const transcript = deps.transcriptPath(target.backendSessionId);
|
|
60
|
+
const active = deps.lastActivity(transcript);
|
|
61
|
+
if (active === null)
|
|
62
|
+
return false;
|
|
63
|
+
const now = deps.now();
|
|
64
|
+
const age = now - (deps.lastTouch(transcript, target.backendSessionId) ?? active);
|
|
65
|
+
const nearingExpiry = age >= KEEP_WARM_REFRESH_AGE_MS && age < KEEP_WARM_MAX_AGE_MS;
|
|
66
|
+
return now - active <= hours * HOUR_MS && nearingExpiry;
|
|
67
|
+
}
|
|
68
|
+
/** The session's refresh target when it is due one now, else null. Cheapest checks first. */
|
|
69
|
+
export async function dueTarget(session, deps, settings) {
|
|
70
|
+
const backendSessionId = largeClaudeSession(session);
|
|
71
|
+
if (!backendSessionId || !(await deps.hasWakeSource(session)))
|
|
72
|
+
return null;
|
|
73
|
+
const selection = subscriptionSelection(session, deps, settings.subscriptionModes);
|
|
74
|
+
if (!selection)
|
|
75
|
+
return null;
|
|
76
|
+
const target = { session, backendSessionId, selection };
|
|
77
|
+
return refreshDue(target, deps, settings.hours) && !deps.busy(session.channel) ? target : null;
|
|
78
|
+
}
|
|
79
|
+
function costEntry(target, result) {
|
|
80
|
+
const { usage } = result;
|
|
81
|
+
return {
|
|
82
|
+
project: target.session.projectId ?? 'general',
|
|
83
|
+
trigger: 'cache-refresh',
|
|
84
|
+
cost_usd: result.costUsd,
|
|
85
|
+
backend: 'claude',
|
|
86
|
+
mode: target.selection.mode,
|
|
87
|
+
source: 'estimate',
|
|
88
|
+
input_tokens: usage.inputTokens,
|
|
89
|
+
output_tokens: usage.outputTokens,
|
|
90
|
+
prompt_tokens: usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens,
|
|
91
|
+
cache_read_tokens: usage.cacheReadTokens,
|
|
92
|
+
cache_creation_tokens: usage.cacheWriteTokens,
|
|
93
|
+
provider: 'anthropic',
|
|
94
|
+
model: target.selection.model,
|
|
95
|
+
session_id: target.session.sessionId,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/** One refresh, queued on the session's channel so a wake that arrives meanwhile waits for it. A
|
|
99
|
+
* turn that got into the queue first has already warmed the cache, so the refresh then skips. */
|
|
100
|
+
async function refreshTarget(target, deps, settings) {
|
|
101
|
+
const id = shortSessionId(target.session.sessionId);
|
|
102
|
+
let result;
|
|
103
|
+
try {
|
|
104
|
+
result = await deps.runQueued(target.session.channel, async () => refreshDue(target, deps, settings.hours) ? deps.refresh(target) : null);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
log.warn(`cache refresh ${id} failed: ${error.message}`);
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
if (!result)
|
|
111
|
+
return false;
|
|
112
|
+
deps.noteRefresh(target.backendSessionId, deps.now());
|
|
113
|
+
await deps.recordCost(costEntry(target, result))
|
|
114
|
+
.catch((error) => log.warn(`cache refresh ${id} cost not recorded: ${error.message}`));
|
|
115
|
+
const { cacheReadTokens, cacheWriteTokens } = result.usage;
|
|
116
|
+
log.info(`cache refresh ${id}: read ${cacheReadTokens}, write ${cacheWriteTokens}, `
|
|
117
|
+
+ `$${result.costUsd.toFixed(3)}, ${(result.durationMs / 1000).toFixed(1)}s`);
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
/** One pass, one session at a time. Returns how many sessions were refreshed. */
|
|
121
|
+
export async function sweepCacheKeepWarm(deps = productionKeepWarmDeps) {
|
|
122
|
+
const settings = deps.settings();
|
|
123
|
+
if (settings.hours <= 0)
|
|
124
|
+
return 0;
|
|
125
|
+
let refreshed = 0;
|
|
126
|
+
for (const session of await deps.listSessions()) {
|
|
127
|
+
const target = await dueTarget(session, deps, settings);
|
|
128
|
+
if (target && await refreshTarget(target, deps, settings))
|
|
129
|
+
refreshed++;
|
|
130
|
+
}
|
|
131
|
+
return refreshed;
|
|
132
|
+
}
|
|
133
|
+
const productionWakeSourceDeps = {
|
|
134
|
+
backgroundRuns: hasRunningBackgroundRuns,
|
|
135
|
+
openWaitpoints: countOpenWaitpoints,
|
|
136
|
+
isLead: (session) => isTeamLead(session),
|
|
137
|
+
team: (leadSessionId) => describeTeam(leadSessionId),
|
|
138
|
+
};
|
|
139
|
+
/** A lead's workers that still owe it a report: running, waiting on a question, or on a waitpoint. */
|
|
140
|
+
async function hasPendingWorker(session, deps) {
|
|
141
|
+
if (!deps.isLead(session))
|
|
142
|
+
return false;
|
|
143
|
+
const team = await deps.team(session.sessionId);
|
|
144
|
+
return team.some((view) => isWorkerBusy(view) || view.status === 'external');
|
|
145
|
+
}
|
|
146
|
+
/** Whether something will still wake the session: a background `agent` run of its own, an open
|
|
147
|
+
* waitpoint it owns, or (as a lead) a worker that has not reported back. */
|
|
148
|
+
export async function hasWakeSource(session, deps = productionWakeSourceDeps) {
|
|
149
|
+
if (deps.backgroundRuns(session.sessionId))
|
|
150
|
+
return true;
|
|
151
|
+
if (await deps.openWaitpoints(session.sessionId, session.channel) > 0)
|
|
152
|
+
return true;
|
|
153
|
+
return hasPendingWorker(session, deps);
|
|
154
|
+
}
|
|
155
|
+
/** The fork's launch, built from the request the session's next turn would run under: same agent,
|
|
156
|
+
* selection, policy and route, so its argv and env match that turn's. Its execution id is its own. */
|
|
157
|
+
export function keepWarmLaunch(target) {
|
|
158
|
+
const { session, backendSessionId } = target;
|
|
159
|
+
const request = conversationEngineRequest({
|
|
160
|
+
ids: { sessionId: session.sessionId, backendSessionId, projectId: session.projectId ?? 'general' },
|
|
161
|
+
channel: session.channel, session, trigger: 'cache-refresh',
|
|
162
|
+
});
|
|
163
|
+
const spec = buildEngineSpec(request, request.selection, {
|
|
164
|
+
route: requestRoute(request, request.selection),
|
|
165
|
+
executionId: `cache-refresh-${randomUUID()}`,
|
|
166
|
+
});
|
|
167
|
+
return cacheRefreshLaunch(spec);
|
|
168
|
+
}
|
|
169
|
+
export const productionKeepWarmDeps = {
|
|
170
|
+
listSessions: () => sessionStore.listRecentSessions(Number.MAX_SAFE_INTEGER),
|
|
171
|
+
settings: () => {
|
|
172
|
+
const settings = getSettings();
|
|
173
|
+
return { hours: settings.cacheKeepWarmHours, subscriptionModes: settings.anthropicSubscriptionModes };
|
|
174
|
+
},
|
|
175
|
+
selection: (session) => resolveRunSelection({ channel: session.channel, session }),
|
|
176
|
+
// A conversation turn spawns in the default cwd, which is where its transcript lives.
|
|
177
|
+
transcriptPath: (backendSessionId) => computeTranscriptPath(resolveSpawnCwd(), backendSessionId),
|
|
178
|
+
lastActivity: lastModelActivity,
|
|
179
|
+
lastTouch: lastCacheTouch,
|
|
180
|
+
hasWakeSource: (session) => hasWakeSource(session),
|
|
181
|
+
busy: (channel) => runRegistry.hasChannel(channel) || conduitQueues.has(channel),
|
|
182
|
+
runQueued: enqueueAndWait,
|
|
183
|
+
refresh: (target) => runCacheRefresh(keepWarmLaunch(target)),
|
|
184
|
+
noteRefresh: noteCacheRefresh,
|
|
185
|
+
recordCost,
|
|
186
|
+
now: () => Date.now(),
|
|
187
|
+
};
|
|
188
|
+
let timer = null;
|
|
189
|
+
let running = false;
|
|
190
|
+
function arm() {
|
|
191
|
+
timer = setTimeout(async () => {
|
|
192
|
+
timer = null;
|
|
193
|
+
await sweepCacheKeepWarm().catch((error) => log.error(`sweep: ${error.message}`));
|
|
194
|
+
if (running)
|
|
195
|
+
arm();
|
|
196
|
+
}, KEEP_WARM_SWEEP_MS);
|
|
197
|
+
timer.unref?.();
|
|
198
|
+
}
|
|
199
|
+
/** Start the periodic keep-warm sweep. `cacheKeepWarmHours` is read on every pass, so turning it
|
|
200
|
+
* off or on takes effect without a restart. */
|
|
201
|
+
export function startCacheKeepWarm() {
|
|
202
|
+
if (running)
|
|
203
|
+
return;
|
|
204
|
+
running = true;
|
|
205
|
+
arm();
|
|
206
|
+
}
|
|
207
|
+
/** Stop the loop before the stores flush: a pass records costs. */
|
|
208
|
+
export function stopCacheKeepWarm() {
|
|
209
|
+
running = false;
|
|
210
|
+
if (timer)
|
|
211
|
+
clearTimeout(timer);
|
|
212
|
+
timer = null;
|
|
213
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type ProviderUsage } from '../domain/costs/usage-store.js';
|
|
2
|
+
import { type WindowWarmupLaunch } from '../agent-adapter/claude/window-warmup.js';
|
|
3
|
+
export declare const WARMUP_TICK_MS = 60000;
|
|
4
|
+
/** How long the window must have been closed, with no Claude run since, before a warm-up. */
|
|
5
|
+
export declare const WARMUP_QUIET_MS: number;
|
|
6
|
+
/** A failed warm-up is retried no sooner than this. */
|
|
7
|
+
export declare const WARMUP_RETRY_MS: number;
|
|
8
|
+
/** The five-hour window's close in epoch ms; null when no window is open; undefined when the
|
|
9
|
+
* account has reported no five-hour window at all. */
|
|
10
|
+
export type WindowEnd = number | null | undefined;
|
|
11
|
+
export interface WarmupState {
|
|
12
|
+
/** When this loop began watching (null while disabled): runs before it are unknown. */
|
|
13
|
+
watchingSince: number | null;
|
|
14
|
+
/** When the current window was seen closed; null while one is open. */
|
|
15
|
+
idleSince: number | null;
|
|
16
|
+
/** Last time a Claude run, or a warm-up, was seen. */
|
|
17
|
+
lastActivity: number | null;
|
|
18
|
+
lastAttempt: number | null;
|
|
19
|
+
}
|
|
20
|
+
export interface WarmupDeps {
|
|
21
|
+
enabled(): boolean;
|
|
22
|
+
/** The Claude subscription mode a warm-up runs under; null when there is none. */
|
|
23
|
+
mode(): string | null;
|
|
24
|
+
windowEnd(): Promise<WindowEnd>;
|
|
25
|
+
claudeRunning(): boolean;
|
|
26
|
+
warm(mode: string): Promise<void>;
|
|
27
|
+
collectUsage(): Promise<unknown>;
|
|
28
|
+
now(): number;
|
|
29
|
+
}
|
|
30
|
+
export declare function newWarmupState(): WarmupState;
|
|
31
|
+
export declare function fiveHourEnd(record: ProviderUsage | null): WindowEnd;
|
|
32
|
+
/** One pass. Returns true when it sent a warm-up that succeeded. */
|
|
33
|
+
export declare function tickWindowWarmup(state: WarmupState, deps?: WarmupDeps): Promise<boolean>;
|
|
34
|
+
/** The launch a subscription-mode turn would get: same config dir, route and credentials. It runs
|
|
35
|
+
* in a scratch directory so no project instructions ride along. */
|
|
36
|
+
export declare function warmupLaunch(mode: string): WindowWarmupLaunch;
|
|
37
|
+
export declare const productionWarmupDeps: WarmupDeps;
|
|
38
|
+
/** Start the loop. `claudeWindowWarmupEnabled` is read on every pass, so toggling it needs no restart. */
|
|
39
|
+
export declare function startClaudeWindowWarmup(): void;
|
|
40
|
+
export declare function stopClaudeWindowWarmup(): void;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Warm-up for Claude's five-hour subscription window.
|
|
2
|
+
//
|
|
3
|
+
// The five-hour window opens with the first request after the previous one closed. Once it has
|
|
4
|
+
// closed and no Claude run has started for ten minutes, one tiny request through Claude Code opens
|
|
5
|
+
// the next window, so it closes five hours from now instead of five hours from whenever work
|
|
6
|
+
// resumes. Claude Code refreshes its login on the way, which keeps the account usage readable.
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { createLogger } from '../core/log.js';
|
|
10
|
+
import { runRegistry } from '../core/run-registry.js';
|
|
11
|
+
import { getSettings } from '../core/settings.js';
|
|
12
|
+
import { usageService } from '../domain/costs/usage-service.js';
|
|
13
|
+
import { usageStore } from '../domain/costs/usage-store.js';
|
|
14
|
+
import { resolveRunRoute } from '../domain/runs/config-resolver.js';
|
|
15
|
+
import { routeEnvFields } from '../domain/runs/engine-spec.js';
|
|
16
|
+
import { buildClaudeEnv } from '../agent-adapter/claude/spawn-args.js';
|
|
17
|
+
import { runWindowWarmup } from '../agent-adapter/claude/window-warmup.js';
|
|
18
|
+
const log = createLogger('claude-window-warmup');
|
|
19
|
+
export const WARMUP_TICK_MS = 60_000;
|
|
20
|
+
/** How long the window must have been closed, with no Claude run since, before a warm-up. */
|
|
21
|
+
export const WARMUP_QUIET_MS = 10 * 60_000;
|
|
22
|
+
/** A failed warm-up is retried no sooner than this. */
|
|
23
|
+
export const WARMUP_RETRY_MS = 30 * 60_000;
|
|
24
|
+
const WARMUP_CHANNEL = 'claude-window-warmup';
|
|
25
|
+
export function newWarmupState() {
|
|
26
|
+
return { watchingSince: null, idleSince: null, lastActivity: null, lastAttempt: null };
|
|
27
|
+
}
|
|
28
|
+
export function fiveHourEnd(record) {
|
|
29
|
+
const window = record?.windows.find((candidate) => candidate.type === 'five_hour');
|
|
30
|
+
if (!window)
|
|
31
|
+
return undefined;
|
|
32
|
+
return window.resetsAt === null ? null : window.resetsAt * 1000;
|
|
33
|
+
}
|
|
34
|
+
/** A Claude run seen since the window closed has already opened the next one. */
|
|
35
|
+
function quietSinceClose(state, now) {
|
|
36
|
+
const idleSince = state.idleSince;
|
|
37
|
+
if (state.lastActivity !== null && state.lastActivity >= idleSince)
|
|
38
|
+
return false;
|
|
39
|
+
return now - Math.max(idleSince, state.watchingSince ?? now) >= WARMUP_QUIET_MS;
|
|
40
|
+
}
|
|
41
|
+
/** Fold one observation into the state; true when a warm-up is due now. */
|
|
42
|
+
function observe(state, end, running, now) {
|
|
43
|
+
if (running) {
|
|
44
|
+
state.lastActivity = now;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (end === undefined)
|
|
48
|
+
return false;
|
|
49
|
+
if (end !== null && end > now) {
|
|
50
|
+
state.idleSince = null;
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
state.idleSince = end ?? state.idleSince ?? now;
|
|
54
|
+
return quietSinceClose(state, now)
|
|
55
|
+
&& (state.lastAttempt === null || now - state.lastAttempt >= WARMUP_RETRY_MS);
|
|
56
|
+
}
|
|
57
|
+
async function warmUp(state, deps, mode) {
|
|
58
|
+
state.lastAttempt = deps.now();
|
|
59
|
+
try {
|
|
60
|
+
await deps.warm(mode);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
log.warn(`warm-up failed: ${error.message}`);
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
state.lastActivity = deps.now();
|
|
67
|
+
log.info('Claude five-hour window warmed up');
|
|
68
|
+
await deps.collectUsage().catch((error) => log.warn(`usage refresh failed: ${error.message}`));
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
/** One pass. Returns true when it sent a warm-up that succeeded. */
|
|
72
|
+
export async function tickWindowWarmup(state, deps = productionWarmupDeps) {
|
|
73
|
+
if (!deps.enabled()) {
|
|
74
|
+
state.watchingSince = null;
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
const now = deps.now();
|
|
78
|
+
state.watchingSince ??= now;
|
|
79
|
+
const mode = deps.mode();
|
|
80
|
+
if (!mode || !observe(state, await deps.windowEnd(), deps.claudeRunning(), now))
|
|
81
|
+
return false;
|
|
82
|
+
return warmUp(state, deps, mode);
|
|
83
|
+
}
|
|
84
|
+
// --- Production wiring ---
|
|
85
|
+
/** The launch a subscription-mode turn would get: same config dir, route and credentials. It runs
|
|
86
|
+
* in a scratch directory so no project instructions ride along. */
|
|
87
|
+
export function warmupLaunch(mode) {
|
|
88
|
+
const route = resolveRunRoute({ mode }, { trigger: WARMUP_CHANNEL });
|
|
89
|
+
const { sets, unsets } = routeEnvFields(route);
|
|
90
|
+
const env = buildClaudeEnv(WARMUP_CHANNEL, randomUUID(), null, null, route.ANTHROPIC_BASE_URL, sets, undefined, undefined, unsets);
|
|
91
|
+
return { command: 'claude', env, cwd: tmpdir() };
|
|
92
|
+
}
|
|
93
|
+
export const productionWarmupDeps = {
|
|
94
|
+
enabled: () => getSettings().claudeWindowWarmupEnabled,
|
|
95
|
+
mode: () => getSettings().anthropicSubscriptionModes.map((mode) => mode.trim()).find(Boolean) ?? null,
|
|
96
|
+
windowEnd: async () => fiveHourEnd(await usageStore.get('anthropic', 'subscription')),
|
|
97
|
+
claudeRunning: () => runRegistry.getAll().some((run) => run.backend === 'claude'),
|
|
98
|
+
warm: (mode) => runWindowWarmup(warmupLaunch(mode)),
|
|
99
|
+
collectUsage: () => usageService.collect(),
|
|
100
|
+
now: () => Date.now(),
|
|
101
|
+
};
|
|
102
|
+
const loopState = newWarmupState();
|
|
103
|
+
let timer = null;
|
|
104
|
+
let running = false;
|
|
105
|
+
function arm() {
|
|
106
|
+
timer = setTimeout(async () => {
|
|
107
|
+
timer = null;
|
|
108
|
+
await tickWindowWarmup(loopState).catch((error) => log.error(`tick: ${error.message}`));
|
|
109
|
+
if (running)
|
|
110
|
+
arm();
|
|
111
|
+
}, WARMUP_TICK_MS);
|
|
112
|
+
timer.unref?.();
|
|
113
|
+
}
|
|
114
|
+
/** Start the loop. `claudeWindowWarmupEnabled` is read on every pass, so toggling it needs no restart. */
|
|
115
|
+
export function startClaudeWindowWarmup() {
|
|
116
|
+
if (running)
|
|
117
|
+
return;
|
|
118
|
+
running = true;
|
|
119
|
+
arm();
|
|
120
|
+
}
|
|
121
|
+
export function stopClaudeWindowWarmup() {
|
|
122
|
+
running = false;
|
|
123
|
+
if (timer)
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
timer = null;
|
|
126
|
+
}
|
|
@@ -21,7 +21,7 @@ export interface ConversationSessionIds {
|
|
|
21
21
|
* One turn on a session's live engine. Every surface that opens such a turn — a user message, an
|
|
22
22
|
* edit retry, an ask-user answer — builds its request here, because the pool respawns the engine
|
|
23
23
|
* when two requests disagree on anything that decides it (agent tools and plugins, worker tools,
|
|
24
|
-
* the
|
|
24
|
+
* the interaction bridge).
|
|
25
25
|
*/
|
|
26
26
|
export interface PrepareConversationRequestOptions {
|
|
27
27
|
ids: ConversationSessionIds;
|
|
@@ -34,8 +34,6 @@ export interface PrepareConversationRequestOptions {
|
|
|
34
34
|
/** Attachments the platform refused to hand over; named in the prompt so the agent cannot
|
|
35
35
|
* answer as though the user had sent nothing. */
|
|
36
36
|
failedFiles?: AttachmentFailure[];
|
|
37
|
-
/** CDP endpoint of the browser this session opted into, or null for the usual no-browser session. */
|
|
38
|
-
browserCdpEndpoint?: string | null;
|
|
39
37
|
/** Execution trigger of a surface other than a plain message (`edit-retry`, `ask-user-question`).
|
|
40
38
|
* Absent ⇒ the session's own (see {@link conversationTrigger}). */
|
|
41
39
|
trigger?: string;
|
|
@@ -80,18 +78,16 @@ export declare function resolveConversationProject(args: {
|
|
|
80
78
|
*/
|
|
81
79
|
export declare function conversationRunPolicy(agentConfig: ResolvedEnvironment, opts: {
|
|
82
80
|
channel: string;
|
|
83
|
-
browserCdpEndpoint?: string | null;
|
|
84
81
|
}): RunRequest['policy'];
|
|
85
82
|
/**
|
|
86
83
|
* Which agent — which execution environment — a conversation turn opens under.
|
|
87
84
|
*
|
|
88
|
-
* The chain
|
|
85
|
+
* The chain follows the session's own choice (what the composer set, or what
|
|
89
86
|
* `!agent` recorded on the session), then the channel's selection, then the global default, then
|
|
90
87
|
* `main`. `getDefaultAgent(channel)` already folds the middle two together.
|
|
91
88
|
*
|
|
92
89
|
* A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
|
|
93
|
-
* since it was persisted must not kill every turn of the session that named it
|
|
94
|
-
* unknown channel profile falls back instead of throwing (see the run-config resolution below).
|
|
90
|
+
* since it was persisted must not kill every turn of the session that named it.
|
|
95
91
|
*/
|
|
96
92
|
export declare function resolveConversationAgent(candidates: ReadonlyArray<string | null | undefined>, resolve?: (name: string) => ResolvedEnvironment | null): {
|
|
97
93
|
agentName: string;
|
|
@@ -152,9 +148,9 @@ export declare function resolveConversationTeam(session: TeamSessionFields | nul
|
|
|
152
148
|
lead: string;
|
|
153
149
|
} | null;
|
|
154
150
|
}>;
|
|
155
|
-
/** The options that decide a turn's engine: whose session, on which channel,
|
|
156
|
-
*
|
|
157
|
-
export type ConversationEngineOptions = Pick<PrepareConversationRequestOptions, 'ids' | 'channel' | 'session' | '
|
|
151
|
+
/** The options that decide a turn's engine: whose session, on which channel, opened by which
|
|
152
|
+
* surface. A command on the live engine (compaction) has exactly these. */
|
|
153
|
+
export type ConversationEngineOptions = Pick<PrepareConversationRequestOptions, 'ids' | 'channel' | 'session' | 'trigger'>;
|
|
158
154
|
/** Assemble the `RunRequest` for one turn on a session's live engine (see the options' doc). */
|
|
159
155
|
export declare function prepareConversationRequest(opts: PrepareConversationRequestOptions): Promise<PreparedRequest>;
|
|
160
156
|
/**
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { getDefaultAgent } from '../domain/agents/index.js';
|
|
3
|
-
import {
|
|
4
|
-
import { effectiveProfile, resolveRunConfig } from '../domain/runs/config-resolver.js';
|
|
3
|
+
import { resolveRunSelection } from '../domain/runs/config-resolver.js';
|
|
5
4
|
import { FALLBACK_ENVIRONMENT, resolveEnvironmentByName } from '../domain/agents/environments/index.js';
|
|
6
5
|
import { composeUserPrompt, userProfileBlock } from '../domain/runs/prompt.js';
|
|
7
6
|
import { resolveSystemVars } from '../core/prompt-template.js';
|
|
@@ -75,19 +74,17 @@ export function conversationRunPolicy(agentConfig, opts) {
|
|
|
75
74
|
settingSources: agentConfig.settingSources,
|
|
76
75
|
mcpComposition: agentConfig.mcpComposition ?? 'direct',
|
|
77
76
|
mcpToolAllowlist: agentConfig.mcpToolAllowlist,
|
|
78
|
-
browserCdpEndpoint: opts.browserCdpEndpoint ?? null,
|
|
79
77
|
};
|
|
80
78
|
}
|
|
81
79
|
/**
|
|
82
80
|
* Which agent — which execution environment — a conversation turn opens under.
|
|
83
81
|
*
|
|
84
|
-
* The chain
|
|
82
|
+
* The chain follows the session's own choice (what the composer set, or what
|
|
85
83
|
* `!agent` recorded on the session), then the channel's selection, then the global default, then
|
|
86
84
|
* `main`. `getDefaultAgent(channel)` already folds the middle two together.
|
|
87
85
|
*
|
|
88
86
|
* A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
|
|
89
|
-
* since it was persisted must not kill every turn of the session that named it
|
|
90
|
-
* unknown channel profile falls back instead of throwing (see the run-config resolution below).
|
|
87
|
+
* since it was persisted must not kill every turn of the session that named it.
|
|
91
88
|
*/
|
|
92
89
|
export function resolveConversationAgent(candidates, resolve = resolveEnvironmentByName) {
|
|
93
90
|
for (const name of [...candidates, FALLBACK_ENVIRONMENT]) {
|
|
@@ -180,21 +177,6 @@ export async function resolveConversationTeam(session, args, deps = {}) {
|
|
|
180
177
|
return none;
|
|
181
178
|
}
|
|
182
179
|
}
|
|
183
|
-
/** The profile a turn runs on: the agent's own, or the channel's when it says `__active__`. */
|
|
184
|
-
function conversationProfile(channel, agentConfig) {
|
|
185
|
-
// D5: one resolution for name, profile and the channel's `!model` override. A hardcoded agent
|
|
186
|
-
// profile is an explicit override; `__active__` means "whatever this channel resolves to".
|
|
187
|
-
const runConfig = resolveRunConfig({
|
|
188
|
-
channel,
|
|
189
|
-
override: agentConfig.profile === '__active__' ? null : agentConfig.profile,
|
|
190
|
-
});
|
|
191
|
-
if (runConfig.resolved)
|
|
192
|
-
return effectiveProfile(runConfig);
|
|
193
|
-
// An unknown name here is not the user naming a bad profile — it is a channel profile that was
|
|
194
|
-
// renamed or deleted since it was persisted, so the turn falls back to the default rather than
|
|
195
|
-
// dying. (Named-profile errors surface through `!profile`, which validates before it writes.)
|
|
196
|
-
return effectiveProfile(resolveRunConfig({ channel, override: getDefaultProfileName() }));
|
|
197
|
-
}
|
|
198
180
|
/** The user prompt with the ambient blocks this turn owes the session. */
|
|
199
181
|
async function composeConversationPrompt(opts, agent, state) {
|
|
200
182
|
const { backendSessionId, projectId } = opts.ids;
|
|
@@ -238,7 +220,7 @@ function conversationContext(opts, state) {
|
|
|
238
220
|
function conversationShape(opts) {
|
|
239
221
|
const { session, channel } = opts;
|
|
240
222
|
const { agentConfig } = resolveConversationAgent([session?.agentName ?? null, getDefaultAgent(channel)]);
|
|
241
|
-
const policy = conversationRunPolicy(agentConfig, { channel
|
|
223
|
+
const policy = conversationRunPolicy(agentConfig, { channel });
|
|
242
224
|
// Team mode: a lead's engine loads the worker tools, a worker's loads `mark_routine`.
|
|
243
225
|
const teamLead = isTeamLead(session);
|
|
244
226
|
const teamWorker = isTeamWorker(session);
|
|
@@ -251,7 +233,7 @@ function conversationShape(opts) {
|
|
|
251
233
|
// turn has opened its engine under — changing it would silently re-pool every live session.
|
|
252
234
|
engineKey: channel,
|
|
253
235
|
},
|
|
254
|
-
|
|
236
|
+
selection: resolveRunSelection({ channel, session }),
|
|
255
237
|
spec: fromAgentSlot(agentConfig, { mcpComposition: policy.mcpComposition }),
|
|
256
238
|
prompt: { text: '' },
|
|
257
239
|
context: conversationContext(opts, { teamLead, teamWorker }),
|
|
@@ -8,6 +8,7 @@ export interface DeltaFlush {
|
|
|
8
8
|
text: string;
|
|
9
9
|
/** 0 for a block's first published event, +1 per event after that. Lets a consumer detect gaps. */
|
|
10
10
|
seq: number;
|
|
11
|
+
kind?: 'thinking';
|
|
11
12
|
}
|
|
12
13
|
export interface DeltaCoalescerOptions {
|
|
13
14
|
onFlush: (flush: DeltaFlush) => void;
|
|
@@ -16,7 +17,7 @@ export interface DeltaCoalescerOptions {
|
|
|
16
17
|
}
|
|
17
18
|
export interface DeltaCoalescer {
|
|
18
19
|
/** Accumulate one incremental chunk. Empty chunks are ignored. */
|
|
19
|
-
push(blockId: string, text: string): void;
|
|
20
|
+
push(blockId: string, text: string, kind?: 'thinking'): void;
|
|
20
21
|
/** Publish what is pending for `blockId` (or for every block when omitted) right now. Callers
|
|
21
22
|
* MUST do this before the block's complete message goes out, so the preview never trails the
|
|
22
23
|
* authoritative text. */
|
|
@@ -32,7 +33,7 @@ export declare function resolveFlushMs(env: Record<string, string | undefined>):
|
|
|
32
33
|
export declare function createDeltaCoalescer(opts: DeltaCoalescerOptions): DeltaCoalescer;
|
|
33
34
|
export interface SessionDeltaStream {
|
|
34
35
|
/** Feed one incremental chunk from the adapter. */
|
|
35
|
-
onDelta(text: string, blockId: string): void;
|
|
36
|
+
onDelta(text: string, blockId: string, kind?: 'thinking'): void;
|
|
36
37
|
/** Publish what is pending — call this immediately before the block's complete message. */
|
|
37
38
|
flush(blockId?: string): void;
|
|
38
39
|
/** End of turn: cancel timers, drop anything unpublished. */
|
|
@@ -62,6 +63,7 @@ export declare function createSessionDeltaStream(args: {
|
|
|
62
63
|
blockId: string;
|
|
63
64
|
text: string;
|
|
64
65
|
seq: number;
|
|
66
|
+
kind?: 'thinking';
|
|
65
67
|
}) => void;
|
|
66
68
|
flushMs?: number;
|
|
67
69
|
}): SessionDeltaStream | null;
|
|
@@ -29,7 +29,7 @@ export function createDeltaCoalescer(opts) {
|
|
|
29
29
|
}
|
|
30
30
|
if (state.pending.length === 0)
|
|
31
31
|
return;
|
|
32
|
-
const flush = { blockId, text: state.pending, seq: state.seq };
|
|
32
|
+
const flush = { blockId, text: state.pending, seq: state.seq, ...(state.kind ? { kind: state.kind } : {}) };
|
|
33
33
|
state.pending = '';
|
|
34
34
|
state.seq += 1;
|
|
35
35
|
// A failing sink is not the streaming path's problem: the block keeps accumulating and the
|
|
@@ -40,12 +40,12 @@ export function createDeltaCoalescer(opts) {
|
|
|
40
40
|
catch { /* contained on purpose */ }
|
|
41
41
|
}
|
|
42
42
|
return {
|
|
43
|
-
push(blockId, text) {
|
|
43
|
+
push(blockId, text, kind) {
|
|
44
44
|
if (disposed || !text)
|
|
45
45
|
return;
|
|
46
46
|
let state = blocks.get(blockId);
|
|
47
47
|
if (!state) {
|
|
48
|
-
state = { pending: '', seq: 0, timer: null };
|
|
48
|
+
state = { pending: '', seq: 0, timer: null, kind };
|
|
49
49
|
blocks.set(blockId, state);
|
|
50
50
|
}
|
|
51
51
|
state.pending += text;
|
|
@@ -110,10 +110,10 @@ export function createSessionDeltaStream(args) {
|
|
|
110
110
|
const publish = args.publish ?? publishSessionMessageDelta;
|
|
111
111
|
const coalescer = createDeltaCoalescer({
|
|
112
112
|
flushMs: args.flushMs,
|
|
113
|
-
onFlush: (
|
|
113
|
+
onFlush: (flush) => publish({ sessionId, channel, ...flush }),
|
|
114
114
|
});
|
|
115
115
|
return {
|
|
116
|
-
onDelta: (text, blockId) => coalescer.push(blockId, text),
|
|
116
|
+
onDelta: (text, blockId, kind) => coalescer.push(blockId, text, kind),
|
|
117
117
|
flush: (blockId) => coalescer.flush(blockId),
|
|
118
118
|
dispose: () => coalescer.dispose(),
|
|
119
119
|
};
|
|
@@ -5,12 +5,11 @@ import { enqueue } from './conduit-queue.js';
|
|
|
5
5
|
import { getSessionAsync } from '../domain/sessions/session.js';
|
|
6
6
|
import { acquireSessionUse } from '../domain/sessions/session-use.js';
|
|
7
7
|
import { sessionStore, effectiveBackendSessionId } from '../store/session-registry-repo.js';
|
|
8
|
-
import {
|
|
8
|
+
import { resolveRunSelection } from '../domain/runs/config-resolver.js';
|
|
9
9
|
import { buildUserProcessingMessage, writeStatus, buildStatusActionBlocks, initStatusBlocks, } from './status-helpers.js';
|
|
10
10
|
import { initTurnTracking, finishTurnTracking, consumePendingTurnSupersession, } from './turn/turn-tracking.js';
|
|
11
11
|
import { handleAgentError } from './turn/terminal.js';
|
|
12
12
|
import { openTurn } from './turn/turn.js';
|
|
13
|
-
import { withTurnBrowser } from './turn/turn-prep.js';
|
|
14
13
|
import { prepareConversationRequest } from './conversation-request.js';
|
|
15
14
|
export function reprocessMessage(channel, text, adapter, opts) {
|
|
16
15
|
trackPendingTask(+1);
|
|
@@ -32,14 +31,15 @@ async function executeRetry(channel, text, adapter, opts) {
|
|
|
32
31
|
const userMessageTs = opts.originalTs;
|
|
33
32
|
const retryDest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
|
|
34
33
|
const retryPrefix = `${Icons.refresh} ${t('status.retry')} (${t('status.retryEdited')}) | `;
|
|
35
|
-
const
|
|
34
|
+
const selection = resolveRunSelection({ channel, session });
|
|
35
|
+
const retryStatusText = retryPrefix + buildUserProcessingMessage({ startTime, selection, sessionId });
|
|
36
36
|
const retryBlocksTemplate = { channel, sessionId, isDm: true };
|
|
37
37
|
const statusMsg = await adapter.postMessage(retryDest, {
|
|
38
38
|
text: retryStatusText,
|
|
39
39
|
richBlocks: buildStatusActionBlocks(retryStatusText, retryBlocksTemplate),
|
|
40
40
|
});
|
|
41
41
|
initStatusBlocks(statusMsg, retryBlocksTemplate);
|
|
42
|
-
updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, opts.supersededStatusTimestamps, retryPrefix, startTime, sessionId);
|
|
42
|
+
updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, opts.supersededStatusTimestamps, retryPrefix, startTime, sessionId, selection);
|
|
43
43
|
const turnTrackingToken = await initTurnTracking(channel, sessionId, backendSessionId, userMessageTs, text, statusMsg.messageId);
|
|
44
44
|
if (consumePendingTurnSupersession(channel, turnTrackingToken)) {
|
|
45
45
|
finishTurnTracking(channel, turnTrackingToken);
|
|
@@ -69,8 +69,7 @@ export async function runRetryAgent(args) {
|
|
|
69
69
|
return;
|
|
70
70
|
const backendSessionId = session ? effectiveBackendSessionId(session) : null;
|
|
71
71
|
const projectId = session?.projectId ?? 'general';
|
|
72
|
-
|
|
73
|
-
await withTurnBrowser({ backend, browser: session?.browser ?? null }, (cdpEndpoint) => openTurn({
|
|
72
|
+
await openTurn({
|
|
74
73
|
channel, adapter, threadAnchorId: null,
|
|
75
74
|
session: { sessionId, backendSessionId, projectId, lease: leased.lease },
|
|
76
75
|
// RAW text: what the ledger recorded and what an auto-resume would replay.
|
|
@@ -82,10 +81,9 @@ export async function runRetryAgent(args) {
|
|
|
82
81
|
startTime,
|
|
83
82
|
// The retry replays a message a human wrote, on the session's live engine: a user turn.
|
|
84
83
|
prepareRequest: (ids) => prepareConversationRequest({
|
|
85
|
-
ids, channel, session, userMessage: text || '',
|
|
86
|
-
browserCdpEndpoint: cdpEndpoint, trigger: 'edit-retry',
|
|
84
|
+
ids, channel, session, userMessage: text || '', trigger: 'edit-retry',
|
|
87
85
|
}),
|
|
88
|
-
})
|
|
86
|
+
});
|
|
89
87
|
}
|
|
90
88
|
/** The retry's session lease (none for a channel without a session), or null when it could not be
|
|
91
89
|
* taken — in which case the failure is already rendered and the ledger turn closed. */
|
|
@@ -111,14 +109,14 @@ async function leaseRetrySession(args) {
|
|
|
111
109
|
return null;
|
|
112
110
|
}
|
|
113
111
|
}
|
|
114
|
-
function updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, supersededTimestamps, retryPrefix, startTime, sessionId) {
|
|
112
|
+
function updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, supersededTimestamps, retryPrefix, startTime, sessionId, selection) {
|
|
115
113
|
const userPermalinkP = adapter.getPermalink({ conduit: channel, messageId: userMessageTs }).catch(() => null);
|
|
116
114
|
const statusPermalinkP = supersededTimestamps?.length
|
|
117
115
|
? adapter.getPermalink(statusMsg).catch(() => null)
|
|
118
116
|
: Promise.resolve(null);
|
|
119
117
|
Promise.all([userPermalinkP, statusPermalinkP]).then(([userPermalink, statusPermalink]) => {
|
|
120
118
|
if (userPermalink) {
|
|
121
|
-
writeStatus(adapter, statusMsg, `${Icons.refresh} ${t('status.retry')} (<${userPermalink}|${t('status.retryEdited')}>) | ` + buildUserProcessingMessage({ startTime,
|
|
119
|
+
writeStatus(adapter, statusMsg, `${Icons.refresh} ${t('status.retry')} (<${userPermalink}|${t('status.retryEdited')}>) | ` + buildUserProcessingMessage({ startTime, selection, sessionId }));
|
|
122
120
|
}
|
|
123
121
|
if (statusPermalink && supersededTimestamps?.length) {
|
|
124
122
|
for (const oldTs of supersededTimestamps) {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { snapshotInlineMedia } from './inline-media.js';
|
|
2
|
+
import type { ResolveMediaInput } from '../domain/ui-service/inline-media-types.js';
|
|
3
|
+
type MessageMedia = Omit<ResolveMediaInput, 'src'> & {
|
|
4
|
+
text: string;
|
|
5
|
+
};
|
|
6
|
+
interface EagerDeps {
|
|
7
|
+
snapshot: typeof snapshotInlineMedia;
|
|
8
|
+
warn: (message: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export declare function extractMediaSources(markdown: string): string[];
|
|
11
|
+
/** Called after the row is durable; an unavailable image must never fail the assistant turn. */
|
|
12
|
+
export declare function eagerSnapshotInlineMedia(message: MessageMedia, deps?: EagerDeps): Promise<void>;
|
|
13
|
+
export {};
|