@chroxy/server 0.11.10 → 0.11.11
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/CONFIG.md +4 -2
- package/package.json +3 -3
- package/src/acp-session.js +5 -1
- package/src/agent-connections.js +12 -1
- package/src/agent-control/client.js +29 -0
- package/src/agent-control/events.js +8 -4
- package/src/agent-control/local-connection.js +34 -16
- package/src/agent-control/mcp-server.js +2 -0
- package/src/anthropic-compatible-config.js +1 -0
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/base-session.js +319 -2
- package/src/bound-client-policy.js +12 -0
- package/src/byok-mcp-config.js +9 -5
- package/src/byok-mcp-trust.js +34 -20
- package/src/byok-session.js +62 -9
- package/src/byok-tool-executor.js +81 -1
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-tui/pty-driver.js +5 -1
- package/src/claude-tui/usage-limit.js +2 -2
- package/src/claude-tui-session.js +57 -4
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/schedule-cmd.js +25 -3
- package/src/cli/server-cmd.js +6 -0
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli-session.js +190 -11
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +78 -17
- package/src/codex-error-text.js +114 -0
- package/src/config-dir-migration.js +11 -6
- package/src/config.js +23 -3
- package/src/connection-info.js +73 -14
- package/src/continuations.js +153 -40
- package/src/conversation-scanner.js +2 -21
- package/src/conversation-search.js +4 -17
- package/src/dev-preview.js +2 -1
- package/src/docker-session.js +10 -1
- package/src/doctor.js +14 -3
- package/src/durable-write.js +35 -0
- package/src/environments/authority.js +7 -1
- package/src/event-normalizer.js +35 -2
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/handler-utils.js +6 -13
- package/src/handlers/checkpoint-handlers.js +8 -0
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +40 -11
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +4 -4
- package/src/handlers/session-handlers.js +10 -1
- package/src/handlers/settings-handlers.js +42 -8
- package/src/handlers/skills-handlers.js +7 -0
- package/src/history-page.js +8 -0
- package/src/jsonl-reader.js +90 -10
- package/src/jsonl-subprocess-session.js +4 -1
- package/src/logger.js +105 -15
- package/src/mailbox-route.js +102 -0
- package/src/notification-prefs.js +15 -0
- package/src/orchestration/orchestration-manager.js +38 -9
- package/src/orchestration/permission-gate.js +4 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +151 -33
- package/src/orphan-reaper.js +77 -20
- package/src/outgoing-policy.js +10 -4
- package/src/permission-floor.js +54 -2
- package/src/permission-manager.js +32 -13
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +7 -3
- package/src/platform.js +156 -4
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/providers.js +2 -0
- package/src/redaction.js +181 -22
- package/src/scheduled-task-store.js +12 -0
- package/src/scheduler.js +304 -17
- package/src/sdk-session.js +60 -7
- package/src/server-cli/push-notification-handler.js +6 -1
- package/src/server-cli.js +30 -1
- package/src/session-ci-watcher.js +210 -37
- package/src/session-manager.js +590 -19
- package/src/session-message-history.js +121 -2
- package/src/session-name-allocator.js +685 -0
- package/src/statusline.js +78 -19
- package/src/summarize-session.js +2 -0
- package/src/turn-outcome.js +5 -2
- package/src/utils/argv-safety.js +29 -0
- package/src/utils/binary-package-manifest.js +57 -15
- package/src/utils/bounded-regex-worker.js +4 -0
- package/src/utils/bounded-regex.js +16 -7
- package/src/utils/pid-liveness.js +47 -0
- package/src/web-task-manager.js +45 -4
- package/src/worktree-gc.js +195 -4
- package/src/ws-auth.js +103 -19
- package/src/ws-broadcaster.js +39 -7
- package/src/ws-client-manager.js +8 -0
- package/src/ws-file-ops/browser.js +35 -3
- package/src/ws-forwarding.js +23 -3
- package/src/ws-handler-context.js +18 -0
- package/src/ws-history.js +79 -12
- package/src/ws-message-handlers.js +10 -2
- package/src/ws-server.js +253 -13
package/src/session-manager.js
CHANGED
|
@@ -6,7 +6,7 @@ import { randomBytes } from 'crypto'
|
|
|
6
6
|
import { statSync, mkdirSync, rmSync, realpathSync } from 'fs'
|
|
7
7
|
import { join, resolve, dirname, basename, isAbsolute } from 'path'
|
|
8
8
|
import { execFileSync } from 'child_process'
|
|
9
|
-
import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
|
|
9
|
+
import { USER_SHELL_PROVIDER, permissionOutcomeForReason } from '@chroxy/protocol'
|
|
10
10
|
import { getProvider, getProviderAuthInfo, DEFAULT_PROVIDER } from './providers.js'
|
|
11
11
|
import { isClaudeProvider, CLAUDE_NEW_SESSION_DEFAULT_MODEL } from './models.js'
|
|
12
12
|
import { classifyClaudeModelRequest } from './claude-model-request.js'
|
|
@@ -15,7 +15,7 @@ import { MonthlyProgrammaticBudgetManager } from './billing-budget.js'
|
|
|
15
15
|
import { runProviderPreflight, buildBinaryProvenanceOptions, ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderBinaryUnsupportedError, ProviderBinaryVersionError, ProviderCredentialMissingError } from './utils/preflight.js'
|
|
16
16
|
import { GIT } from './git.js'
|
|
17
17
|
import { isGitRepoSync } from './utils/git-repo.js'
|
|
18
|
-
import { sweepOrphanChroxyWorktrees } from './worktree-gc.js'
|
|
18
|
+
import { sweepOrphanChroxyWorktrees, worktreeUnsavedWorkReport, describeUnsavedWork, sanitizeNoticeText } from './worktree-gc.js'
|
|
19
19
|
import { hasPersistedTranscript, readConversationHistoryWithMetaAsync } from './jsonl-reader.js'
|
|
20
20
|
import { resolveTranscriptSource } from './transcript-sources.js'
|
|
21
21
|
import { NATIVE_RESUME_DRIVER, nativeRestoreError } from './codex-native-resume.js'
|
|
@@ -40,7 +40,7 @@ import { SessionPresetTrustStore } from './session-preset-trust.js'
|
|
|
40
40
|
import { BinaryProvenanceLedger } from './binary-provenance-trust.js'
|
|
41
41
|
import { PermissionRuleStore } from './permission-rule-store.js'
|
|
42
42
|
import { permissionDecisionToken } from './permission-scope.js'
|
|
43
|
-
import { ScheduledTaskStore, defaultScheduledTasksPath } from './scheduled-task-store.js'
|
|
43
|
+
import { ScheduledTaskStore, defaultScheduledTasksPath, isScheduledTaskIdShape } from './scheduled-task-store.js'
|
|
44
44
|
import { createLogger } from './logger.js'
|
|
45
45
|
import { ExternalSessionRegistry } from './external-session-registry.js'
|
|
46
46
|
import { metrics } from './metrics.js'
|
|
@@ -52,6 +52,8 @@ import { assertProviderPermissionModeSupported, UnsupportedPermissionModeError }
|
|
|
52
52
|
import { toWireCount } from './utils/wire-counters.js'
|
|
53
53
|
import { assertSafeArgvValue } from './utils/argv-safety.js'
|
|
54
54
|
import { configPath } from './config-dir.js'
|
|
55
|
+
import { createSessionNameAllocator, isAllocatorNameForCwd } from './session-name-allocator.js'
|
|
56
|
+
import { canonicalProjectForCwd } from '@chroxy/protocol/project'
|
|
55
57
|
import {
|
|
56
58
|
forwardPerSessionSettingsToProviderOpts,
|
|
57
59
|
serializePerSessionSettings,
|
|
@@ -376,8 +378,9 @@ function providerStartDeadlineMs(session) {
|
|
|
376
378
|
function permissionOutcomeForEvent(event, data) {
|
|
377
379
|
if (!data || typeof data.requestId !== 'string' || !data.requestId) return null
|
|
378
380
|
if (event === 'permission_expired') return 'expired'
|
|
379
|
-
|
|
380
|
-
|
|
381
|
+
// #8952: one table (`PERMISSION_NO_DECISION_REASON_OUTCOMES`) shared with the clients.
|
|
382
|
+
const noDecision = permissionOutcomeForReason(data.reason)
|
|
383
|
+
if (noDecision) return noDecision
|
|
381
384
|
return data.decision === 'deny' ? 'denied' : 'allowed'
|
|
382
385
|
}
|
|
383
386
|
|
|
@@ -447,10 +450,17 @@ export function withRetainedPermissionOutcomes(transcript, ring, truncated) {
|
|
|
447
450
|
let outcomes = []
|
|
448
451
|
for (const entry of ring) {
|
|
449
452
|
// #8259: an interrupted turn's marker is daemon-written too (the provider's own
|
|
450
|
-
// transcript never saw the turn end), so it is retained the same way.
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
453
|
+
// transcript never saw the turn end), so it is retained the same way. #9241: so
|
|
454
|
+
// is the marker for a turn the user stopped before any reply.
|
|
455
|
+
const markerOutcome = !!entry && entry.type === 'result'
|
|
456
|
+
&& (entry.turnOutcome === 'interrupted' || entry.turnOutcome === 'stopped_before_output')
|
|
457
|
+
? entry.turnOutcome
|
|
458
|
+
: null
|
|
459
|
+
if (!entry || (entry.type !== 'permission_outcome' && !markerOutcome)) continue
|
|
460
|
+
// A marker's identity is (outcome, timestamp), the same pair the clients dedupe on. Two
|
|
461
|
+
// markers of one outcome stamped in the SAME millisecond collapse to one; a session runs
|
|
462
|
+
// one turn at a time, so that needs two turns to end inside a millisecond.
|
|
463
|
+
const key = markerOutcome ? `${markerOutcome}:${entry.timestamp}` : entry.requestId
|
|
454
464
|
if (seen.has(key)) continue
|
|
455
465
|
seen.add(key)
|
|
456
466
|
const { _seq: _ringSeq, ...copy } = entry
|
|
@@ -582,6 +592,14 @@ export class SessionManager extends EventEmitter {
|
|
|
582
592
|
// MCP config — see byok-mcp-fleet.MCPFleet.start() for the trade-off.
|
|
583
593
|
mcpStartCapMs,
|
|
584
594
|
|
|
595
|
+
// Naming of sessions created without a name: 'project' ("<project> <n>", kept in a
|
|
596
|
+
// durable store beside the state file) or 'legacy' ("Session <n>"). The manager's own
|
|
597
|
+
// default is 'legacy' so every direct caller and test keeps today's names; the daemon
|
|
598
|
+
// passes resolveSessionNaming(config) (default 'project'). `sessionNameAllocator` is an
|
|
599
|
+
// injection point for tests.
|
|
600
|
+
sessionNaming = 'legacy',
|
|
601
|
+
sessionNameAllocator,
|
|
602
|
+
|
|
585
603
|
// State persistence
|
|
586
604
|
stateFilePath,
|
|
587
605
|
stateTtlMs,
|
|
@@ -918,6 +936,17 @@ export class SessionManager extends EventEmitter {
|
|
|
918
936
|
})
|
|
919
937
|
// Backward-compatible accessors for tests that reference internal state
|
|
920
938
|
this._stateFilePath = this._persistence._stateFilePath
|
|
939
|
+
// Project-scoped session names. The store lives beside session-state.json (the same
|
|
940
|
+
// dirname rule as every sidecar below), so a test's temp stateFilePath keeps it out of
|
|
941
|
+
// the real ~/.chroxy. Nothing touches the disk until the first allocation.
|
|
942
|
+
this._sessionNaming = sessionNaming === 'project' ? 'project' : 'legacy'
|
|
943
|
+
this._namingWarnedAt = new Map()
|
|
944
|
+
this._namingClock = () => performance.now()
|
|
945
|
+
this._sessionNameAllocator = sessionNameAllocator || createSessionNameAllocator({
|
|
946
|
+
dir: dirname(this._stateFilePath),
|
|
947
|
+
liveNames: () => this._liveSessionNames(),
|
|
948
|
+
log: { warn: (m) => log.warn(m), error: (m) => log.error(m) },
|
|
949
|
+
})
|
|
921
950
|
// #6276: orphan-shell reaper sidecar, colocated with the state file so a
|
|
922
951
|
// test's temp stateFilePath keeps it out of the real ~/.chroxy.
|
|
923
952
|
this._userShellSidecarPath = join(dirname(this._stateFilePath), 'user-shells.json')
|
|
@@ -1071,6 +1100,15 @@ export class SessionManager extends EventEmitter {
|
|
|
1071
1100
|
this._sessionLastActivityAt = new Map() // sessionId -> last meaningful user/agent activity timestamp
|
|
1072
1101
|
// #8301: sessions whose user pressed Stop and has not typed since — daemon turns are refused (see daemonTurnRefusal).
|
|
1073
1102
|
this._userStopped = new Set()
|
|
1103
|
+
// #8326: sessionId -> daemon turns dispatched since a person last typed into it. In-memory
|
|
1104
|
+
// on purpose (a restart is a fresh start; see daemonTurnRefusal). Reset by recordUserIntent only.
|
|
1105
|
+
this._daemonWakeCount = new Map()
|
|
1106
|
+
// #8327: sessionId -> Set of owners (TurnDriver instances) currently occupying it. THE one
|
|
1107
|
+
// registry every driver reports to (see markTurnDriven); daemonTurnRefusal answers `orchestrated`.
|
|
1108
|
+
this._turnDriven = new Map()
|
|
1109
|
+
// #9301: sessions with a release announcement already scheduled (coalesces a
|
|
1110
|
+
// release / re-drive / release inside one tick into a single emit).
|
|
1111
|
+
this._releaseAnnouncing = new Set()
|
|
1074
1112
|
// #8866: sessionId -> { seed, claimed } — the archived-transcript seed of a session
|
|
1075
1113
|
// continued as a NEW thread, held until the first accepted user input carries it.
|
|
1076
1114
|
this._continuationSeeds = new Map()
|
|
@@ -1183,6 +1221,8 @@ export class SessionManager extends EventEmitter {
|
|
|
1183
1221
|
this._history.cleanupSession(sessionId)
|
|
1184
1222
|
this._costBudget.removeSession(sessionId)
|
|
1185
1223
|
this._userStopped.delete(sessionId)
|
|
1224
|
+
this._daemonWakeCount.delete(sessionId)
|
|
1225
|
+
this._turnDriven.delete(sessionId)
|
|
1186
1226
|
this._continuationSeeds.delete(sessionId)
|
|
1187
1227
|
for (const [requestId, pending] of this._permissionRequests) {
|
|
1188
1228
|
if (pending.sessionId === sessionId) this._permissionRequests.delete(requestId)
|
|
@@ -1199,6 +1239,10 @@ export class SessionManager extends EventEmitter {
|
|
|
1199
1239
|
// a particular event — the general lesson this repo already learned once
|
|
1200
1240
|
// for the environment tag.
|
|
1201
1241
|
forgetSurveyKey(this, sessionId)
|
|
1242
|
+
// #9118: the session is gone for good. `destroyAll()` (a daemon shutdown, which keeps
|
|
1243
|
+
// every session for the next start) bypasses this method, so this event is exactly "removed,
|
|
1244
|
+
// not shut down": the principal journal and its subscriptions are torn down on it.
|
|
1245
|
+
this.emit('session_removed', { sessionId })
|
|
1202
1246
|
}
|
|
1203
1247
|
|
|
1204
1248
|
/**
|
|
@@ -1266,6 +1310,22 @@ export class SessionManager extends EventEmitter {
|
|
|
1266
1310
|
return entry ? entry.session : null
|
|
1267
1311
|
}
|
|
1268
1312
|
|
|
1313
|
+
/** #9301: the session id a mailbox id is registered to, or null. */
|
|
1314
|
+
agentCommIdSessionId(agentCommId) {
|
|
1315
|
+
return (typeof agentCommId === 'string' && this._agentCommIds.get(agentCommId)) || null
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* #9184: is the session behind this mailbox id occupied by a TurnDriver? The
|
|
1320
|
+
* mailbox wake is a typed line into a live PTY; into a driven session it would
|
|
1321
|
+
* interleave with the driven turn exactly as a CI wake would (#8327). False for
|
|
1322
|
+
* an unknown id (the caller already reports `no-session` for that).
|
|
1323
|
+
*/
|
|
1324
|
+
isAgentCommIdTurnDriven(agentCommId) {
|
|
1325
|
+
const sessionId = typeof agentCommId === 'string' ? this._agentCommIds.get(agentCommId) : undefined
|
|
1326
|
+
return sessionId ? this.isTurnDriven(sessionId) : false
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1269
1329
|
/** Max recent mailbox delivery events retained for the Control Room snapshot. */
|
|
1270
1330
|
static MAILBOX_EVENT_LIMIT = 50
|
|
1271
1331
|
|
|
@@ -1571,7 +1631,7 @@ export class SessionManager extends EventEmitter {
|
|
|
1571
1631
|
* effectiveSessionPreamble: (string|undefined),
|
|
1572
1632
|
* }} the validated create plan.
|
|
1573
1633
|
*/
|
|
1574
|
-
_resolveCreateSessionPlan({ name, cwd, model, permissionMode, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sessionPreamble, preserveId, resumeSessionId, isRestore = false, modelSource = 'explicit' } = {}) {
|
|
1634
|
+
_resolveCreateSessionPlan({ name, cwd, model, permissionMode, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sessionPreamble, preserveId, resumeSessionId, isRestore = false, modelSource = 'explicit', nameIdempotencyKey, successorOf } = {}) {
|
|
1575
1635
|
if (this._sessions.size >= this.maxSessions) {
|
|
1576
1636
|
log.error(`Cannot create session: limit reached (${this._sessions.size}/${this.maxSessions})`)
|
|
1577
1637
|
throw new SessionLimitError(this.maxSessions)
|
|
@@ -1640,7 +1700,21 @@ export class SessionManager extends EventEmitter {
|
|
|
1640
1700
|
? preserveId
|
|
1641
1701
|
: null
|
|
1642
1702
|
const sessionId = preserve ?? randomBytes(16).toString('hex')
|
|
1643
|
-
|
|
1703
|
+
// An explicit name always wins and consumes no number. An unnamed NEW session in
|
|
1704
|
+
// 'project' mode is named after its project, but only once everything that can still
|
|
1705
|
+
// refuse the create has run (see the end of this method); every other unnamed create
|
|
1706
|
+
// takes the legacy counter here, exactly as before.
|
|
1707
|
+
// A name of only whitespace is no name for this purpose (project mode only; the legacy
|
|
1708
|
+
// path keeps using whatever it was given). A restore-shaped call (isRestore, a preserved id,
|
|
1709
|
+
// or a restored worktree) never allocates, whatever else it says.
|
|
1710
|
+
const unnamed = !name || String(name).trim() === ''
|
|
1711
|
+
const restoreShaped = isRestore || !!preserveId || !!restoreWorktreePath
|
|
1712
|
+
const wantProjectName = unnamed && !successorOf && !restoreShaped && this._sessionNaming === 'project'
|
|
1713
|
+
// A successor of an archived session ("continue as a new thread") is named at the same last
|
|
1714
|
+
// step: a fresh number when its predecessor carried an allocator-style name, else
|
|
1715
|
+
// "<name> (continued)". Neither consumes the legacy counter.
|
|
1716
|
+
const wantSuccessorName = unnamed && !!successorOf && !restoreShaped
|
|
1717
|
+
let sessionName = (wantProjectName || wantSuccessorName) ? null : (name || `Session ${++this._sessionCounter}`)
|
|
1644
1718
|
|
|
1645
1719
|
// Pre-flight: verify the provider's binary exists and required credential
|
|
1646
1720
|
// env vars are set BEFORE constructing/spawning. Without this, a missing
|
|
@@ -1873,9 +1947,27 @@ export class SessionManager extends EventEmitter {
|
|
|
1873
1947
|
}
|
|
1874
1948
|
}
|
|
1875
1949
|
|
|
1950
|
+
// Project naming happens LAST: the preflight, model, worktree and preset steps above can
|
|
1951
|
+
// all throw, and a create that never happens must not spend a number. (A failure after
|
|
1952
|
+
// this point, in provider construction, still leaves a gap: numbers are never reissued.)
|
|
1953
|
+
let nameAllocation = null
|
|
1954
|
+
if (wantSuccessorName) {
|
|
1955
|
+
const base = typeof successorOf.name === 'string' && successorOf.name ? successorOf.name : 'Archived session'
|
|
1956
|
+
if (this._sessionNaming === 'project' && isAllocatorNameForCwd(base, successorOf.cwd)) {
|
|
1957
|
+
nameAllocation = this._allocateProjectName(resolvedCwd)
|
|
1958
|
+
}
|
|
1959
|
+
sessionName = nameAllocation ? nameAllocation.name : `${base} (continued)`
|
|
1960
|
+
} else if (wantProjectName) {
|
|
1961
|
+
// Synchronous disk work (about 15 ms; 27-57 ms with an idempotency key once the bind runs):
|
|
1962
|
+
// see the cost note in session-name-allocator.js.
|
|
1963
|
+
nameAllocation = this._allocateProjectName(resolvedCwd, nameIdempotencyKey)
|
|
1964
|
+
sessionName = nameAllocation ? nameAllocation.name : `Session ${++this._sessionCounter}`
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1876
1967
|
return {
|
|
1877
1968
|
sessionId,
|
|
1878
1969
|
sessionName,
|
|
1970
|
+
nameAllocation,
|
|
1879
1971
|
resolvedCwd,
|
|
1880
1972
|
resolvedModel,
|
|
1881
1973
|
resolvedPermissionMode,
|
|
@@ -1975,10 +2067,13 @@ export class SessionManager extends EventEmitter {
|
|
|
1975
2067
|
* `{ orchestrationRunId, orchestrationRole }`, surfaced as optional session-list badge
|
|
1976
2068
|
* fields). NOT settable over the wire (the create_session handler whitelists its
|
|
1977
2069
|
* fields), and NOT persisted — in-memory only in v1; restart-reconcile re-establishes
|
|
1978
|
-
* it (#6743).
|
|
2070
|
+
* it (#6743). The ONE exception is `scheduledTaskId` (#8571), which is persisted as
|
|
2071
|
+
* a restore HINT (see `_serializeSessionEntry`): after a restart it is held inert on
|
|
2072
|
+
* the entry, never in `metadata`, until the scheduler adopts the session
|
|
2073
|
+
* (`adoptScheduledTask`). Every other key is dropped across a restart.
|
|
1979
2074
|
* @returns {string} sessionId
|
|
1980
2075
|
*/
|
|
1981
|
-
createSession({ name, cwd, model, permissionMode, resumeSessionId, nativeResume, conversationPersisted, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, codexSandbox, environmentId, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, disabledMcpServers, bootedModel, messageCounter, skipPermissions, agentCommId, metadata = null, skipPersist = false, preserveId, isRestore = false, modelSource } = {}) {
|
|
2076
|
+
createSession({ name, cwd, model, permissionMode, resumeSessionId, nativeResume, conversationPersisted, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, codexSandbox, environmentId, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, disabledMcpServers, bootedModel, messageCounter, skipPermissions, agentCommId, metadata = null, skipPersist = false, preserveId, isRestore = false, modelSource, nameIdempotencyKey, successorOf } = {}) {
|
|
1982
2077
|
// #6036 — front-half SRP extraction: preflight + isolation + provider/preset
|
|
1983
2078
|
// resolution (incl. the limit guard, cwd check, id/name, #2962 preflight,
|
|
1984
2079
|
// #5985 user-shell gate, #3403 model fallback, worktree create/restore, and
|
|
@@ -2003,10 +2098,13 @@ export class SessionManager extends EventEmitter {
|
|
|
2003
2098
|
resumeSessionId,
|
|
2004
2099
|
isRestore,
|
|
2005
2100
|
modelSource,
|
|
2101
|
+
nameIdempotencyKey,
|
|
2102
|
+
successorOf,
|
|
2006
2103
|
})
|
|
2007
2104
|
const {
|
|
2008
2105
|
sessionId,
|
|
2009
2106
|
sessionName,
|
|
2107
|
+
nameAllocation,
|
|
2010
2108
|
resolvedCwd,
|
|
2011
2109
|
resolvedModel,
|
|
2012
2110
|
resolvedPermissionMode,
|
|
@@ -2312,6 +2410,9 @@ export class SessionManager extends EventEmitter {
|
|
|
2312
2410
|
}
|
|
2313
2411
|
|
|
2314
2412
|
this._sessions.set(sessionId, entry)
|
|
2413
|
+
// The session exists: tie its reserved project number to it. Best effort — a failure
|
|
2414
|
+
// never fails the create (the number is simply left unbound).
|
|
2415
|
+
if (nameAllocation?.key && nameIdempotencyKey !== undefined) this._bindProjectName(nameAllocation, nameIdempotencyKey, sessionId)
|
|
2315
2416
|
// #7552: TAG the environment as soon as the entry is live — paired with the
|
|
2316
2417
|
// untag in `_cleanupSessionMaps`, the single funnel every session takes out
|
|
2317
2418
|
// of `_sessions`. Attaching here rather than after `start()` keeps the pair
|
|
@@ -2909,6 +3010,209 @@ export class SessionManager extends EventEmitter {
|
|
|
2909
3010
|
return this.resolveSessionPresetForCwd(cwd)
|
|
2910
3011
|
}
|
|
2911
3012
|
|
|
3013
|
+
/**
|
|
3014
|
+
* The ids of the live sessions, and nothing else: no provider getter runs, so a session whose
|
|
3015
|
+
* state is broken cannot affect a caller that only needs to know which ids exist (#9119).
|
|
3016
|
+
* @returns {string[]}
|
|
3017
|
+
*/
|
|
3018
|
+
listSessionIds() {
|
|
3019
|
+
const ids = []
|
|
3020
|
+
for (const [sessionId, entry] of this._sessions) if (!entry._destroying) ids.push(sessionId)
|
|
3021
|
+
return ids
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3024
|
+
/**
|
|
3025
|
+
* When this session last saw meaningful activity (what `listSessions()` reports as
|
|
3026
|
+
* `lastActivityAt`), read for one session without touching any other session or any provider
|
|
3027
|
+
* getter. `null` when the session is not there (#9120).
|
|
3028
|
+
* @param {string} sessionId
|
|
3029
|
+
* @returns {number|null}
|
|
3030
|
+
*/
|
|
3031
|
+
getLastActivityAt(sessionId) {
|
|
3032
|
+
const entry = this._sessions.get(sessionId)
|
|
3033
|
+
if (!entry) return null
|
|
3034
|
+
return this._sessionLastActivityAt.get(sessionId) || entry.createdAt || null
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
/**
|
|
3038
|
+
* #8571: live, non-destroying sessions linked to a scheduled task, for the
|
|
3039
|
+
* scheduler's adoption pass. `owned` is true when `metadata.scheduledTaskId` is set
|
|
3040
|
+
* (the scheduler adopted it, or created it); false when the link is only a restore
|
|
3041
|
+
* HINT carried over from the state file, which is inert until adopted.
|
|
3042
|
+
* @returns {Array<{ sessionId: string, taskId: string, owned: boolean, lastActivityAt: number }>}
|
|
3043
|
+
*/
|
|
3044
|
+
listScheduledTaskSessions() {
|
|
3045
|
+
const out = []
|
|
3046
|
+
for (const [sessionId, entry] of this._sessions) {
|
|
3047
|
+
if (entry._destroying) continue
|
|
3048
|
+
const owned = isScheduledTaskIdShape(entry.metadata?.scheduledTaskId)
|
|
3049
|
+
const taskId = owned ? entry.metadata.scheduledTaskId : entry.restoredScheduledTaskId
|
|
3050
|
+
if (!isScheduledTaskIdShape(taskId)) continue
|
|
3051
|
+
out.push({ sessionId, taskId, owned, lastActivityAt: this.getLastActivityAt(sessionId) || 0 })
|
|
3052
|
+
}
|
|
3053
|
+
return out
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
/**
|
|
3057
|
+
* #8571: the scheduler takes ownership of a session linked to `taskId` (owned, or a
|
|
3058
|
+
* restore hint). Sets `metadata.scheduledTaskId` (merged into any other metadata)
|
|
3059
|
+
* and clears the hint, which is what makes `getHandoffBlockers` report
|
|
3060
|
+
* `automation_owned`. The persisted value is the same before and after, so nothing
|
|
3061
|
+
* needs flushing. Refuses a session linked to a different task or none. Idempotent:
|
|
3062
|
+
* for an already-owned session it just confirms ownership. An adopted session
|
|
3063
|
+
* belongs to its task: deleting the task closes it and its worktree. An archive
|
|
3064
|
+
* restore of a scheduled session comes back through restore, so it is re-adopted
|
|
3065
|
+
* the same way.
|
|
3066
|
+
* @param {string} sessionId
|
|
3067
|
+
* @param {string} taskId
|
|
3068
|
+
* @returns {boolean} whether the session is now owned by `taskId`
|
|
3069
|
+
*/
|
|
3070
|
+
adoptScheduledTask(sessionId, taskId) {
|
|
3071
|
+
const entry = this._sessions.get(sessionId)
|
|
3072
|
+
if (!entry || entry._destroying || !isScheduledTaskIdShape(taskId)) return false
|
|
3073
|
+
const current = entry.metadata?.scheduledTaskId
|
|
3074
|
+
if (current !== undefined && current !== null) return current === taskId
|
|
3075
|
+
if (entry.restoredScheduledTaskId !== taskId) return false
|
|
3076
|
+
entry.metadata = { ...(entry.metadata || {}), scheduledTaskId: taskId }
|
|
3077
|
+
delete entry.restoredScheduledTaskId
|
|
3078
|
+
return true
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
/**
|
|
3082
|
+
* #8571: a restore hint is valid only until a human uses the session. Without
|
|
3083
|
+
* this, a duplicate the scheduler did not pick would keep its hint, be adopted
|
|
3084
|
+
* later (when the chosen session is closed) and have scheduled prompts driven
|
|
3085
|
+
* into the user's own conversation, and be destroyed with the task. Drops the
|
|
3086
|
+
* unadopted hint and persists, so the next restart agrees. A no-op for an OWNED
|
|
3087
|
+
* (adopted) session, which belongs to its task exactly as it does within one
|
|
3088
|
+
* daemon run, and for a session with no hint.
|
|
3089
|
+
* @param {string} sessionId
|
|
3090
|
+
* @returns {boolean} whether a hint was released
|
|
3091
|
+
*/
|
|
3092
|
+
releaseRestoreHint(sessionId) {
|
|
3093
|
+
const entry = this._sessions.get(sessionId)
|
|
3094
|
+
if (!entry || entry.restoredScheduledTaskId === undefined) return false
|
|
3095
|
+
if (isScheduledTaskIdShape(entry.metadata?.scheduledTaskId)) return false
|
|
3096
|
+
delete entry.restoredScheduledTaskId
|
|
3097
|
+
// #9242: NOW, not on the debounce: a crash in the window would resurrect the hint.
|
|
3098
|
+
this._flushPersistOrWarn(sessionId)
|
|
3099
|
+
return true
|
|
3100
|
+
}
|
|
3101
|
+
|
|
3102
|
+
/**
|
|
3103
|
+
* #9242: a person is using this session — end its scheduled-task link in BOTH forms
|
|
3104
|
+
* (an adopted ownership and an unadopted restore hint), each persisted at once.
|
|
3105
|
+
* The one entry point for every person-driven release (`recordUserIntent`, a
|
|
3106
|
+
* checkpoint Files restore).
|
|
3107
|
+
* @param {string} sessionId
|
|
3108
|
+
* @returns {boolean} whether any link was released
|
|
3109
|
+
*/
|
|
3110
|
+
releaseScheduledTaskLink(sessionId) {
|
|
3111
|
+
const hint = this.releaseRestoreHint(sessionId)
|
|
3112
|
+
const owned = this.releaseScheduledOwnership(sessionId)
|
|
3113
|
+
return hint || owned
|
|
3114
|
+
}
|
|
3115
|
+
|
|
3116
|
+
/**
|
|
3117
|
+
* #9242: is this live session OWNED by scheduled task `taskId`? Ownership is
|
|
3118
|
+
* `metadata.scheduledTaskId`; a restore hint or a session a person has taken over
|
|
3119
|
+
* does not count. The scheduler asks before it drives or destroys a session.
|
|
3120
|
+
* @param {string} sessionId
|
|
3121
|
+
* @param {string} taskId
|
|
3122
|
+
* @returns {boolean}
|
|
3123
|
+
*/
|
|
3124
|
+
ownsScheduledTask(sessionId, taskId) {
|
|
3125
|
+
const entry = this._sessions.get(sessionId)
|
|
3126
|
+
if (!entry || entry._destroying || !isScheduledTaskIdShape(taskId)) return false
|
|
3127
|
+
return entry.metadata?.scheduledTaskId === taskId
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
/**
|
|
3131
|
+
* #9242: end a scheduled task's ownership of a session, leaving an ordinary one
|
|
3132
|
+
* (no `automation_owned` blocker, never driven or closed by the scheduler again).
|
|
3133
|
+
* Called when a person uses the session (`recordUserIntent`) and when the task is
|
|
3134
|
+
* deleted while its session still holds work. Drops the key from `metadata`
|
|
3135
|
+
* (keeping any other), clears a stale hint, and persists so a restart agrees.
|
|
3136
|
+
* With `taskId`, only releases a session owned by that task.
|
|
3137
|
+
* @param {string} sessionId
|
|
3138
|
+
* @param {string} [taskId]
|
|
3139
|
+
* @returns {boolean} whether ownership was released
|
|
3140
|
+
*/
|
|
3141
|
+
releaseScheduledOwnership(sessionId, taskId) {
|
|
3142
|
+
const entry = this._sessions.get(sessionId)
|
|
3143
|
+
if (!entry || entry._destroying) return false
|
|
3144
|
+
const current = entry.metadata?.scheduledTaskId
|
|
3145
|
+
if (!isScheduledTaskIdShape(current)) return false
|
|
3146
|
+
if (taskId !== undefined && current !== taskId) return false
|
|
3147
|
+
const { scheduledTaskId: _released, ...rest } = entry.metadata
|
|
3148
|
+
entry.metadata = Object.keys(rest).length > 0 ? rest : null
|
|
3149
|
+
delete entry.restoredScheduledTaskId
|
|
3150
|
+
// Written NOW, not on the debounce: a crash inside the debounce window would
|
|
3151
|
+
// resurrect the old link as a restore hint and re-adopt a session a person is
|
|
3152
|
+
// using. (A failed write is logged and emitted by _flushPersistOrWarn; the
|
|
3153
|
+
// in-memory release stands either way.)
|
|
3154
|
+
this._flushPersistOrWarn(sessionId)
|
|
3155
|
+
return true
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
/**
|
|
3159
|
+
* #9242: would destroying this session lose work? True when it has a worktree
|
|
3160
|
+
* with uncommitted/untracked/ignored content or commits no ref reaches, or when
|
|
3161
|
+
* that cannot be determined (fail safe). A session with no worktree is `false`:
|
|
3162
|
+
* destroying it removes no files.
|
|
3163
|
+
* @param {string} sessionId
|
|
3164
|
+
* @returns {boolean}
|
|
3165
|
+
*/
|
|
3166
|
+
hasUnsavedWorktreeWork(sessionId) {
|
|
3167
|
+
return this.unsavedWorktreeWork(sessionId)?.has === true
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
/**
|
|
3171
|
+
* #9286: the same question as hasUnsavedWorktreeWork, answered with WHAT was found
|
|
3172
|
+
* (`{ has, kinds, samples }`, see worktreeUnsavedWorkReport). `null` for a session
|
|
3173
|
+
* with no worktree.
|
|
3174
|
+
* @param {string} sessionId
|
|
3175
|
+
*/
|
|
3176
|
+
unsavedWorktreeWork(sessionId) {
|
|
3177
|
+
const entry = this._sessions.get(sessionId)
|
|
3178
|
+
if (!entry?.worktreePath) return null
|
|
3179
|
+
return worktreeUnsavedWorkReport(entry.worktreePath)
|
|
3180
|
+
}
|
|
3181
|
+
|
|
3182
|
+
/**
|
|
3183
|
+
* #9286: tell the person why a deleted scheduled task's session was kept. A `system`
|
|
3184
|
+
* message in the session's own history, so it renders in the chat, replays on
|
|
3185
|
+
* reconnect and survives a restart (flushed now); it is also broadcast live. It
|
|
3186
|
+
* only informs: nothing is removed, and closing the session stays the person's call.
|
|
3187
|
+
* Never throws: a failed notice must not undo the keep.
|
|
3188
|
+
* @param {string} sessionId
|
|
3189
|
+
* @param {string} taskId
|
|
3190
|
+
* @param {{ kinds: string[], samples: Record<string, string[]> }} report
|
|
3191
|
+
* @param {string} [taskName] - the deleted task's own name (not the session's, which may be renamed)
|
|
3192
|
+
* @returns {boolean} whether the notice was recorded
|
|
3193
|
+
*/
|
|
3194
|
+
noteScheduledSessionKept(sessionId, taskId, report, taskName) {
|
|
3195
|
+
try {
|
|
3196
|
+
const entry = this._sessions.get(sessionId)
|
|
3197
|
+
if (!entry || entry._destroying) return false
|
|
3198
|
+
const what = describeUnsavedWork(report) || 'unsaved work'
|
|
3199
|
+
const label = typeof taskName === 'string' && taskName ? `Scheduled task "${sanitizeNoticeText(taskName, 120)}"` : 'A scheduled task'
|
|
3200
|
+
const data = {
|
|
3201
|
+
type: 'system',
|
|
3202
|
+
content: `${label} was deleted, but this session was kept open instead of being closed, because its worktree holds unsaved work: ${what}. ` +
|
|
3203
|
+
'It is an ordinary session now and nothing has been removed. Review the worktree, then close the session yourself to remove it.',
|
|
3204
|
+
timestamp: Date.now(),
|
|
3205
|
+
}
|
|
3206
|
+
this._recordHistory(sessionId, 'message', data)
|
|
3207
|
+
this.emit('session_event', { sessionId, event: 'message', data })
|
|
3208
|
+
this._flushPersistOrWarn(sessionId)
|
|
3209
|
+
return true
|
|
3210
|
+
} catch (err) {
|
|
3211
|
+
log.warn(`Could not record the kept-session notice for ${sessionId}: ${err?.message || err}`)
|
|
3212
|
+
return false
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
|
|
2912
3216
|
/**
|
|
2913
3217
|
* List all sessions with summary info.
|
|
2914
3218
|
* @returns {Array<{ sessionId, name, cwd, model, permissionMode, isBusy, busyReason, backgroundShellCount, createdAt, lastActivityAt, stdinForwardingDisabled, stdinDroppedBytes, stdinDroppedCount }>}
|
|
@@ -3524,6 +3828,7 @@ export class SessionManager extends EventEmitter {
|
|
|
3524
3828
|
this._history.clear()
|
|
3525
3829
|
this._costBudget.clear()
|
|
3526
3830
|
this._userStopped.clear()
|
|
3831
|
+
this._turnDriven.clear()
|
|
3527
3832
|
// #5554: persist any pending usage records on shutdown (best-effort).
|
|
3528
3833
|
try { this.skillsUsageRecorder?.flush() } catch { /* non-fatal */ }
|
|
3529
3834
|
}
|
|
@@ -3652,6 +3957,19 @@ export class SessionManager extends EventEmitter {
|
|
|
3652
3957
|
...(typeof entry.session.conversationPersisted === 'boolean'
|
|
3653
3958
|
? { conversationPersisted: entry.session.conversationPersisted }
|
|
3654
3959
|
: {}),
|
|
3960
|
+
// #8571: the scheduler's task->session link is the ONE metadata key that
|
|
3961
|
+
// survives a restart, written as a RESTORE HINT so the engine can re-adopt
|
|
3962
|
+
// its session instead of minting another. Ownership (`metadata`) wins; else
|
|
3963
|
+
// a hint carried from the state file is written back unchanged, so a link
|
|
3964
|
+
// nobody adopted (scheduler disabled, store failed to load, task gone,
|
|
3965
|
+
// duplicate) is never lost. Orchestration keys stay in-memory (#6743).
|
|
3966
|
+
// Omitted unless valid; an older build reading it ignores the unknown key.
|
|
3967
|
+
...(() => {
|
|
3968
|
+
const taskId = isScheduledTaskIdShape(entry.metadata?.scheduledTaskId)
|
|
3969
|
+
? entry.metadata.scheduledTaskId
|
|
3970
|
+
: entry.restoredScheduledTaskId
|
|
3971
|
+
return isScheduledTaskIdShape(taskId) ? { scheduledTaskId: taskId } : {}
|
|
3972
|
+
})(),
|
|
3655
3973
|
cwd: entry.cwd,
|
|
3656
3974
|
model: entry.session.model,
|
|
3657
3975
|
// Persist the model the underlying CLI actually booted with (#3700b).
|
|
@@ -4065,6 +4383,15 @@ export class SessionManager extends EventEmitter {
|
|
|
4065
4383
|
// restored history + worktree instead of destroying them.
|
|
4066
4384
|
isRestore: true,
|
|
4067
4385
|
})
|
|
4386
|
+
// #8571: a persisted scheduled-task link comes back as an inert HINT on the
|
|
4387
|
+
// entry, NOT as `metadata`: ownership (and the `automation_owned` handoff
|
|
4388
|
+
// blocker) begins only when the scheduler adopts the session
|
|
4389
|
+
// (`adoptScheduledTask`). Only a well-formed task id is trusted; the hint is
|
|
4390
|
+
// written back by `_serializeSessionEntry`, so an unadopted link survives.
|
|
4391
|
+
if (isScheduledTaskIdShape(saved.scheduledTaskId)) {
|
|
4392
|
+
const restored = this._sessions.get(sessionId)
|
|
4393
|
+
if (restored) restored.restoredScheduledTaskId = saved.scheduledTaskId
|
|
4394
|
+
}
|
|
4068
4395
|
try {
|
|
4069
4396
|
// #4089 / #4124: restore the per-session running totals + the
|
|
4070
4397
|
// threshold-notified latch onto the freshly-created entry. We do
|
|
@@ -4501,6 +4828,70 @@ export class SessionManager extends EventEmitter {
|
|
|
4501
4828
|
return sessionId
|
|
4502
4829
|
}
|
|
4503
4830
|
|
|
4831
|
+
/** 'project' or 'legacy': how this manager names a session created without a name. */
|
|
4832
|
+
get sessionNaming() { return this._sessionNaming }
|
|
4833
|
+
|
|
4834
|
+
/** Names that currently occupy the namespace: live sessions plus parked failed restores. */
|
|
4835
|
+
_liveSessionNames() {
|
|
4836
|
+
const names = []
|
|
4837
|
+
for (const entry of this._sessions.values()) if (typeof entry?.name === 'string') names.push(entry.name)
|
|
4838
|
+
for (const { saved } of this._failedRestores.values()) if (typeof saved?.name === 'string') names.push(saved.name)
|
|
4839
|
+
return names
|
|
4840
|
+
}
|
|
4841
|
+
|
|
4842
|
+
/**
|
|
4843
|
+
* Reserve "<project> <n>" for a session about to be created in `cwd`. Returns
|
|
4844
|
+
* `{ name, key, number, idempotencyKey }` or null when the caller must use the legacy name
|
|
4845
|
+
* (not a project, store closed or busy, any allocator problem). Never throws.
|
|
4846
|
+
* @private
|
|
4847
|
+
*/
|
|
4848
|
+
_allocateProjectName(cwd, idempotencyKey) {
|
|
4849
|
+
try {
|
|
4850
|
+
const key = typeof idempotencyKey === 'string' && idempotencyKey.length > 0 && idempotencyKey.length <= 256 ? idempotencyKey : undefined
|
|
4851
|
+
const res = this._sessionNameAllocator.allocate({ cwd, ...(key !== undefined ? { idempotencyKey: key } : {}) })
|
|
4852
|
+
if (!res?.ok) {
|
|
4853
|
+
if (res?.reason && res.reason !== 'non_project') this._warnNamingUnavailable(res.reason, cwd)
|
|
4854
|
+
return null
|
|
4855
|
+
}
|
|
4856
|
+
return { name: res.name, key: res.key, number: res.number, idempotencyKey: key }
|
|
4857
|
+
} catch (err) {
|
|
4858
|
+
log.warn(`Project session naming failed (${err?.message || err}); using the legacy name`)
|
|
4859
|
+
return null
|
|
4860
|
+
}
|
|
4861
|
+
}
|
|
4862
|
+
|
|
4863
|
+
/**
|
|
4864
|
+
* One WARN per (reason, project): a closed store would otherwise repeat the same line on
|
|
4865
|
+
* every create. States that stay until an operator acts (evidence_lost, inconsistent,
|
|
4866
|
+
* store_full, unsupported_fs) are logged once per manager and project; transient ones at
|
|
4867
|
+
* most once a minute (on a monotonic clock; a negative step counts as elapsed).
|
|
4868
|
+
* @private
|
|
4869
|
+
*/
|
|
4870
|
+
_warnNamingUnavailable(reason, cwd) {
|
|
4871
|
+
const STICKY = new Set(['evidence_lost', 'inconsistent', 'store_full', 'unsupported_fs'])
|
|
4872
|
+
let scope = cwd
|
|
4873
|
+
try {
|
|
4874
|
+
scope = canonicalProjectForCwd(cwd)?.root ?? cwd
|
|
4875
|
+
} catch { /* fall back to the cwd */ }
|
|
4876
|
+
const k = `${reason}\u0000${scope}`
|
|
4877
|
+
const last = this._namingWarnedAt.get(k)
|
|
4878
|
+
const now = this._namingClock()
|
|
4879
|
+
if (last !== undefined && (STICKY.has(reason) || (now - last >= 0 && now - last < 60_000))) return
|
|
4880
|
+
this._namingWarnedAt.set(k, now)
|
|
4881
|
+
log.warn(`Project session naming unavailable (${reason}) for ${scope}; using the legacy name`)
|
|
4882
|
+
}
|
|
4883
|
+
|
|
4884
|
+
/** Best-effort bind of a reserved number to the session that took it. @private */
|
|
4885
|
+
_bindProjectName(allocation, requestKey, sessionId) {
|
|
4886
|
+
try {
|
|
4887
|
+
if (allocation.idempotencyKey === undefined || allocation.idempotencyKey !== requestKey) return
|
|
4888
|
+
const res = this._sessionNameAllocator.bind(allocation.idempotencyKey, sessionId, { number: allocation.number })
|
|
4889
|
+
if (!res?.ok) log.warn(`Could not bind session name "${allocation.name}" to session ${sessionId} (${res?.reason || 'unknown'})`)
|
|
4890
|
+
} catch (err) {
|
|
4891
|
+
log.warn(`Could not bind session name "${allocation.name}" to session ${sessionId}: ${err?.message || err}`)
|
|
4892
|
+
}
|
|
4893
|
+
}
|
|
4894
|
+
|
|
4504
4895
|
/**
|
|
4505
4896
|
* Keep `_sessionCounter` ahead of any "Session N" name still occupying disk
|
|
4506
4897
|
* state, so the first new auto-named session after a restore cannot collide
|
|
@@ -4884,7 +5275,8 @@ export class SessionManager extends EventEmitter {
|
|
|
4884
5275
|
let newId
|
|
4885
5276
|
try {
|
|
4886
5277
|
newId = this.createSession({
|
|
4887
|
-
|
|
5278
|
+
// Named by the create plan, at its last step (a refused create spends no number).
|
|
5279
|
+
successorOf: { name: baseName, cwd: saved.cwd },
|
|
4888
5280
|
cwd: saved.cwd,
|
|
4889
5281
|
model: saved.model || undefined,
|
|
4890
5282
|
// #7855: a model read back from a saved record is a replay, not a request
|
|
@@ -5331,6 +5723,20 @@ export class SessionManager extends EventEmitter {
|
|
|
5331
5723
|
return Promise.race([handle, timeout]).finally(() => clearTimeout(timer))
|
|
5332
5724
|
}
|
|
5333
5725
|
|
|
5726
|
+
/**
|
|
5727
|
+
* #9245: public wrapper over `_awaitStartSettled` for callers outside the
|
|
5728
|
+
* manager (the scheduler) that must not send into a session whose provider
|
|
5729
|
+
* `start()` is still in flight. Same contract: never rejects; call it
|
|
5730
|
+
* synchronously after the session was created or looked up.
|
|
5731
|
+
*
|
|
5732
|
+
* @param {string} sessionId
|
|
5733
|
+
* @param {number} timeoutMs
|
|
5734
|
+
* @returns {Promise<{ok: true} | {ok: false, error: any} | {ok: true, pending: true}>}
|
|
5735
|
+
*/
|
|
5736
|
+
awaitSessionStart(sessionId, timeoutMs) {
|
|
5737
|
+
return this._awaitStartSettled(sessionId, timeoutMs)
|
|
5738
|
+
}
|
|
5739
|
+
|
|
5334
5740
|
/**
|
|
5335
5741
|
* Check if all sessions are idle (not busy).
|
|
5336
5742
|
* Used by drain protocol to wait for in-flight work.
|
|
@@ -5397,6 +5803,16 @@ export class SessionManager extends EventEmitter {
|
|
|
5397
5803
|
return this._history.getLatestSeq(sessionId)
|
|
5398
5804
|
}
|
|
5399
5805
|
|
|
5806
|
+
/**
|
|
5807
|
+
* #8415 -- tool inputs a client at `cursor` holds a card for without the input.
|
|
5808
|
+
* @param {string} sessionId
|
|
5809
|
+
* @param {number} cursor
|
|
5810
|
+
* @returns {Array<{messageId: string, toolUseId?: string, input: object}>}
|
|
5811
|
+
*/
|
|
5812
|
+
getToolInputBackfills(sessionId, cursor) {
|
|
5813
|
+
return this._history.getToolInputBackfills(sessionId, cursor)
|
|
5814
|
+
}
|
|
5815
|
+
|
|
5400
5816
|
/**
|
|
5401
5817
|
* Get the conversation ID (SDK session ID) for a session.
|
|
5402
5818
|
* @returns {string|null}
|
|
@@ -5563,7 +5979,17 @@ export class SessionManager extends EventEmitter {
|
|
|
5563
5979
|
* @param {string} sessionId
|
|
5564
5980
|
*/
|
|
5565
5981
|
recordUserIntent(sessionId) {
|
|
5982
|
+
// #8571: a person using a session ends any unadopted scheduled-task restore
|
|
5983
|
+
// hint on it. Only the CLIENT input handlers call this (the scheduler's turn
|
|
5984
|
+
// driver goes through `session.sendMessage` directly, never here).
|
|
5985
|
+
// #9242: and ends an ADOPTED task's ownership too. The scheduler drives its
|
|
5986
|
+
// session by `session.sendMessage` and never reaches here, so this is a person
|
|
5987
|
+
// by construction. Their session is no longer the task's: the next fire gets a
|
|
5988
|
+
// fresh one, and deleting the task leaves it alone.
|
|
5989
|
+
this.releaseScheduledTaskLink(sessionId)
|
|
5566
5990
|
this._userStopped.delete(sessionId)
|
|
5991
|
+
// #8326: a person typing is also what ends a run of consecutive daemon wakes.
|
|
5992
|
+
this._daemonWakeCount.delete(sessionId)
|
|
5567
5993
|
}
|
|
5568
5994
|
|
|
5569
5995
|
/**
|
|
@@ -5579,6 +6005,64 @@ export class SessionManager extends EventEmitter {
|
|
|
5579
6005
|
if (this._sessions.has(sessionId)) this._userStopped.add(sessionId)
|
|
5580
6006
|
}
|
|
5581
6007
|
|
|
6008
|
+
/**
|
|
6009
|
+
* #8281: why a handoff must not start from this session right now. The
|
|
6010
|
+
* session's own blockers (`BaseSession.getHandoffBlockers`) plus the reasons
|
|
6011
|
+
* only the manager can see. Not consumed anywhere yet; `isRunning`,
|
|
6012
|
+
* `listSessions().isBusy` and the idle timeout are untouched.
|
|
6013
|
+
*
|
|
6014
|
+
* Manager-level codes:
|
|
6015
|
+
* - `not_found` no such session (the only entry returned)
|
|
6016
|
+
* - `destroying` the entry is being torn down
|
|
6017
|
+
* - `automation_owned` the session is bound to a scheduled task or owned
|
|
6018
|
+
* by an orchestration run, read from the in-memory
|
|
6019
|
+
* `entry.metadata` those engines already stamp at
|
|
6020
|
+
* createSession (`scheduledTaskId` /
|
|
6021
|
+
* `orchestrationRunId`). Metadata is not persisted, so
|
|
6022
|
+
* it is absent for a session restored after a restart,
|
|
6023
|
+
* exactly as the engines' own session maps are. The
|
|
6024
|
+
* persisted `scheduledTaskId` is only a restore hint
|
|
6025
|
+
* (#8571): it adds this blocker once the scheduler has
|
|
6026
|
+
* adopted the session (`adoptScheduledTask`), not before.
|
|
6027
|
+
* - `evaluator_pending` the caller says the prompt evaluator holds a draft
|
|
6028
|
+
*
|
|
6029
|
+
* One input lives outside the SessionManager and must be passed in by the
|
|
6030
|
+
* caller, which today is the WS layer: `evaluatorPending`, because the
|
|
6031
|
+
* evaluator's draft state is on the WS handler context, not on the session.
|
|
6032
|
+
* Hook-routed permission prompts need no input: ws-permissions registers each
|
|
6033
|
+
* one on its owning session (`notifyPermissionPending`), and the session's
|
|
6034
|
+
* `getPendingPermissionIds()` reports it.
|
|
6035
|
+
*
|
|
6036
|
+
* @param {string} sessionId
|
|
6037
|
+
* @param {{ evaluatorPending?: boolean }} [options]
|
|
6038
|
+
* @returns {{ code: string, detail?: object }[]}
|
|
6039
|
+
*/
|
|
6040
|
+
getHandoffBlockers(sessionId, { evaluatorPending = false } = {}) {
|
|
6041
|
+
const entry = this._sessions.get(sessionId)
|
|
6042
|
+
if (!entry) return [{ code: 'not_found' }]
|
|
6043
|
+
const blockers = []
|
|
6044
|
+
const sessionBlockers = typeof entry.session?.getHandoffBlockers === 'function'
|
|
6045
|
+
? entry.session.getHandoffBlockers()
|
|
6046
|
+
: []
|
|
6047
|
+
for (const blocker of sessionBlockers) blockers.push(blocker)
|
|
6048
|
+
if (entry._destroying && !blockers.some((b) => b.code === 'destroying')) {
|
|
6049
|
+
blockers.push({ code: 'destroying' })
|
|
6050
|
+
}
|
|
6051
|
+
const scheduledTaskId = entry.metadata?.scheduledTaskId
|
|
6052
|
+
const orchestrationRunId = entry.metadata?.orchestrationRunId
|
|
6053
|
+
if (scheduledTaskId || orchestrationRunId) {
|
|
6054
|
+
blockers.push({
|
|
6055
|
+
code: 'automation_owned',
|
|
6056
|
+
detail: {
|
|
6057
|
+
...(scheduledTaskId ? { scheduledTaskId } : {}),
|
|
6058
|
+
...(orchestrationRunId ? { orchestrationRunId } : {}),
|
|
6059
|
+
},
|
|
6060
|
+
})
|
|
6061
|
+
}
|
|
6062
|
+
if (evaluatorPending) blockers.push({ code: 'evaluator_pending' })
|
|
6063
|
+
return blockers
|
|
6064
|
+
}
|
|
6065
|
+
|
|
5582
6066
|
/**
|
|
5583
6067
|
* #8301: THE refusal seam for a daemon-authored turn — one answer, asked both
|
|
5584
6068
|
* before dispatch and again when a queued wake is about to flush. Returns why
|
|
@@ -5587,6 +6071,20 @@ export class SessionManager extends EventEmitter {
|
|
|
5587
6071
|
* - `'no-session'` the session is gone or being torn down
|
|
5588
6072
|
* - `'budget-paused'` the cost budget pause (typed input is refused for this)
|
|
5589
6073
|
* - `'user-stopped'` the user pressed Stop and has not typed since
|
|
6074
|
+
* - `'wake-cap'` (#8326) `options.maxConsecutiveWakes` daemon turns have
|
|
6075
|
+
* already been dispatched with no user-typed input between
|
|
6076
|
+
* (`recordUserIntent` resets; `recordDaemonUserInput`
|
|
6077
|
+
* counts). Opt-in per call: absent = no cap. The count is
|
|
6078
|
+
* in-memory and per daemon run — a restart starts at 0,
|
|
6079
|
+
* which is acceptable because the loop it bounds needs a
|
|
6080
|
+
* live agent pushing in this process.
|
|
6081
|
+
* - `'orchestrated'` (#8327) a TurnDriver (scheduler, build-manager /
|
|
6082
|
+
* orchestration run) occupies the session: a wake turn
|
|
6083
|
+
* would interleave with the driven turn and its `result`
|
|
6084
|
+
* could settle the driver's waiter with the wake's text.
|
|
6085
|
+
* Checked after the user-facing reasons (they need a
|
|
6086
|
+
* person to act; this one clears by itself when the
|
|
6087
|
+
* driver releases) and after the cap, before the provider.
|
|
5590
6088
|
* - otherwise the provider's own reason (`session.daemonTurnRefusal()`): a
|
|
5591
6089
|
* state in which its `sendMessage` would respawn, error, or discard the
|
|
5592
6090
|
* user's queued follow-ups
|
|
@@ -5594,18 +6092,22 @@ export class SessionManager extends EventEmitter {
|
|
|
5594
6092
|
* A provider hook that throws refuses (fail safe): not being able to tell is
|
|
5595
6093
|
* not a reason to wake.
|
|
5596
6094
|
*
|
|
5597
|
-
*
|
|
5598
|
-
*
|
|
5599
|
-
* is nothing cheap to ask here; building a registry for it is its own change.
|
|
6095
|
+
* Order is part of the contract: no-session, budget-paused, user-stopped,
|
|
6096
|
+
* wake-cap, orchestrated, provider.
|
|
5600
6097
|
*
|
|
5601
6098
|
* @param {string} sessionId
|
|
6099
|
+
* @param {{ maxConsecutiveWakes?: number }} [options]
|
|
5602
6100
|
* @returns {string|null}
|
|
5603
6101
|
*/
|
|
5604
|
-
daemonTurnRefusal(sessionId) {
|
|
6102
|
+
daemonTurnRefusal(sessionId, { maxConsecutiveWakes } = {}) {
|
|
5605
6103
|
const entry = this._sessions.get(sessionId)
|
|
5606
6104
|
if (!entry || entry._destroying) return 'no-session'
|
|
5607
6105
|
if (this._costBudget.isPaused(sessionId)) return 'budget-paused'
|
|
5608
6106
|
if (this._userStopped.has(sessionId)) return 'user-stopped'
|
|
6107
|
+
if (Number.isFinite(maxConsecutiveWakes) && (this._daemonWakeCount.get(sessionId) ?? 0) >= maxConsecutiveWakes) {
|
|
6108
|
+
return 'wake-cap'
|
|
6109
|
+
}
|
|
6110
|
+
if (this.isTurnDriven(sessionId)) return 'orchestrated'
|
|
5609
6111
|
try {
|
|
5610
6112
|
const reason = entry.session?.daemonTurnRefusal?.()
|
|
5611
6113
|
return typeof reason === 'string' && reason.length > 0 ? reason : null
|
|
@@ -5615,6 +6117,74 @@ export class SessionManager extends EventEmitter {
|
|
|
5615
6117
|
}
|
|
5616
6118
|
}
|
|
5617
6119
|
|
|
6120
|
+
/**
|
|
6121
|
+
* #8327: a TurnDriver took (or queued for) the session. `owner` is the driver
|
|
6122
|
+
* instance; several may hold one session at once, and it counts as driven until
|
|
6123
|
+
* every owner has released. Idempotent per owner. No-op for an unknown session.
|
|
6124
|
+
*
|
|
6125
|
+
* @param {string} sessionId
|
|
6126
|
+
* @param {object} owner
|
|
6127
|
+
*/
|
|
6128
|
+
markTurnDriven(sessionId, owner) {
|
|
6129
|
+
if (!this._sessions.has(sessionId) || !owner) return
|
|
6130
|
+
let owners = this._turnDriven.get(sessionId)
|
|
6131
|
+
if (!owners) { owners = new Set(); this._turnDriven.set(sessionId, owners) }
|
|
6132
|
+
owners.add(owner)
|
|
6133
|
+
}
|
|
6134
|
+
|
|
6135
|
+
/** #8327: the owner let go of the session (turn ended, errored, timed out, or driver disposed). */
|
|
6136
|
+
releaseTurnDriven(sessionId, owner) {
|
|
6137
|
+
const owners = this._turnDriven.get(sessionId)
|
|
6138
|
+
if (!owners) return
|
|
6139
|
+
owners.delete(owner)
|
|
6140
|
+
if (owners.size === 0) {
|
|
6141
|
+
this._turnDriven.delete(sessionId)
|
|
6142
|
+
this._announceReleased(sessionId)
|
|
6143
|
+
}
|
|
6144
|
+
}
|
|
6145
|
+
|
|
6146
|
+
/**
|
|
6147
|
+
* #9301: tell the daemon-wake paths a session is free again, so a wake refused
|
|
6148
|
+
* as `orchestrated` can be delivered once. Fires only when the LAST owner has
|
|
6149
|
+
* released (the caller checks), and one tick LATER, re-checking occupancy: the
|
|
6150
|
+
* scheduler / orchestration may hand the session to its next turn synchronously
|
|
6151
|
+
* after a release, and a wake delivered into THAT turn is the interleaving the
|
|
6152
|
+
* refusal exists to prevent. If it is driven again by then nothing is emitted —
|
|
6153
|
+
* the next release announces it. Not emitted for a session destroyed meanwhile.
|
|
6154
|
+
* Emits `turn_driven_released { sessionId }`.
|
|
6155
|
+
*/
|
|
6156
|
+
_announceReleased(sessionId) {
|
|
6157
|
+
if (this._releaseAnnouncing.has(sessionId)) return
|
|
6158
|
+
this._releaseAnnouncing.add(sessionId)
|
|
6159
|
+
setImmediate(() => {
|
|
6160
|
+
this._releaseAnnouncing.delete(sessionId)
|
|
6161
|
+
if (!this._sessions.has(sessionId) || this.isTurnDriven(sessionId)) return
|
|
6162
|
+
try {
|
|
6163
|
+
this.emit('turn_driven_released', { sessionId })
|
|
6164
|
+
} catch (err) {
|
|
6165
|
+
log.warn(`turn_driven_released listener threw for session ${sessionId}: ${err?.message || err}`)
|
|
6166
|
+
}
|
|
6167
|
+
})
|
|
6168
|
+
}
|
|
6169
|
+
|
|
6170
|
+
/** #8327: is any TurnDriver occupying this session right now? */
|
|
6171
|
+
isTurnDriven(sessionId) {
|
|
6172
|
+
return (this._turnDriven.get(sessionId)?.size ?? 0) > 0
|
|
6173
|
+
}
|
|
6174
|
+
|
|
6175
|
+
/**
|
|
6176
|
+
* #8326: a daemon turn was DISPATCHED to the model — counts toward the wake
|
|
6177
|
+
* cap (see `daemonTurnRefusal`). Separate from `recordDaemonUserInput`
|
|
6178
|
+
* (history/broadcast) because the claude-tui PTY route dispatches without ever
|
|
6179
|
+
* being recorded. The watcher calls this exactly once per dispatched wake.
|
|
6180
|
+
*
|
|
6181
|
+
* @param {string} sessionId
|
|
6182
|
+
*/
|
|
6183
|
+
noteDaemonWake(sessionId) {
|
|
6184
|
+
if (!this._sessions.has(sessionId)) return
|
|
6185
|
+
this._daemonWakeCount.set(sessionId, (this._daemonWakeCount.get(sessionId) ?? 0) + 1)
|
|
6186
|
+
}
|
|
6187
|
+
|
|
5618
6188
|
/**
|
|
5619
6189
|
* #8301: make a DAEMON-authored turn visible the way a typed one is. The CI
|
|
5620
6190
|
* wake travels the provider's `sendMessage` seam as an ordinary user turn, but
|
|
@@ -5629,7 +6199,8 @@ export class SessionManager extends EventEmitter {
|
|
|
5629
6199
|
* what a session is called. No `clientId` goes out — there is no sender, so
|
|
5630
6200
|
* every viewer renders it (a client skips only the `user_input` it sent).
|
|
5631
6201
|
*
|
|
5632
|
-
* Call it only once the provider has
|
|
6202
|
+
* Call it only once the provider has DISPATCHED the line (a wake that queued
|
|
6203
|
+
* behind a running turn is recorded when it flushes, never at enqueue).
|
|
5633
6204
|
* Nothing is recorded for a session that no longer exists.
|
|
5634
6205
|
*
|
|
5635
6206
|
* @param {string} sessionId
|