shellpuppet 0.5.2 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/agents/agy/nudge.js +58 -5
- package/dist/agents/agy/nudge.js.map +1 -1
- package/dist/agents/codex/index.js +1 -1
- package/dist/agents/codex/index.js.map +1 -1
- package/dist/agents/hermes/index.js +2 -2
- package/dist/agents/hermes/index.js.map +1 -1
- package/dist/agents/hermes/nudge.d.ts +1 -0
- package/dist/agents/hermes/nudge.js +5 -0
- package/dist/agents/hermes/nudge.js.map +1 -1
- package/dist/agents/types.d.ts +4 -0
- package/dist/cli/index.js +24 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/client/http.d.ts +2 -2
- package/dist/client/http.js +1 -1
- package/dist/client/http.js.map +1 -1
- package/dist/core/dialogs.d.ts +4 -1
- package/dist/core/dialogs.js +25 -5
- package/dist/core/dialogs.js.map +1 -1
- package/dist/core/mailbox.d.ts +8 -4
- package/dist/core/mailbox.js +22 -5
- package/dist/core/mailbox.js.map +1 -1
- package/dist/core/manager.d.ts +1 -0
- package/dist/core/manager.js +5 -1
- package/dist/core/manager.js.map +1 -1
- package/dist/core/policy.d.ts +5 -3
- package/dist/core/policy.js +25 -23
- package/dist/core/policy.js.map +1 -1
- package/dist/core/readingContext.d.ts +9 -0
- package/dist/core/readingContext.js +4 -0
- package/dist/core/readingContext.js.map +1 -0
- package/dist/core/reasoning.d.ts +2 -1
- package/dist/core/reasoning.js +33 -11
- package/dist/core/reasoning.js.map +1 -1
- package/dist/core/renderer.d.ts +1 -0
- package/dist/core/renderer.js +1 -0
- package/dist/core/renderer.js.map +1 -1
- package/dist/core/session.d.ts +50 -32
- package/dist/core/session.js +332 -162
- package/dist/core/session.js.map +1 -1
- package/dist/daemon/config.d.ts +11 -1
- package/dist/daemon/config.js +42 -20
- package/dist/daemon/config.js.map +1 -1
- package/dist/daemon/configReload.d.ts +55 -0
- package/dist/daemon/configReload.js +284 -0
- package/dist/daemon/configReload.js.map +1 -0
- package/dist/daemon/configWatcher.d.ts +55 -0
- package/dist/daemon/configWatcher.js +313 -0
- package/dist/daemon/configWatcher.js.map +1 -0
- package/dist/daemon/homeOwner.d.ts +2 -1
- package/dist/daemon/homeOwner.js +33 -8
- package/dist/daemon/homeOwner.js.map +1 -1
- package/dist/daemon/index.js +3 -50
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/launchProfiles.d.ts +5 -3
- package/dist/daemon/launchProfiles.js +12 -7
- package/dist/daemon/launchProfiles.js.map +1 -1
- package/dist/daemon/nudgeScheduler.d.ts +4 -4
- package/dist/daemon/nudgeScheduler.js +16 -15
- package/dist/daemon/nudgeScheduler.js.map +1 -1
- package/dist/daemon/paths.d.ts +22 -4
- package/dist/daemon/paths.js +126 -24
- package/dist/daemon/paths.js.map +1 -1
- package/dist/daemon/restartSource.d.ts +3 -3
- package/dist/daemon/restartSource.js +5 -4
- package/dist/daemon/restartSource.js.map +1 -1
- package/dist/daemon/schedules.d.ts +6 -5
- package/dist/daemon/schedules.js +15 -51
- package/dist/daemon/schedules.js.map +1 -1
- package/dist/daemon/server.d.ts +25 -17
- package/dist/daemon/server.js +547 -452
- package/dist/daemon/server.js.map +1 -1
- package/dist/daemon/standaloneOptions.d.ts +4 -0
- package/dist/daemon/standaloneOptions.js +29 -0
- package/dist/daemon/standaloneOptions.js.map +1 -0
- package/dist/mcp/index.js +0 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/tools.d.ts +0 -6
- package/dist/mcp/tools.js +90 -85
- package/dist/mcp/tools.js.map +1 -1
- package/dist/viewer/dashboard.css +21 -2
- package/dist/viewer/dashboard.js +44 -11
- package/dist/viewer/index.html +4 -3
- package/dist/viewer/pane.js +91 -395
- package/dist/viewer/viewer.css +23 -4
- package/dist/viewer/viewer.js +2 -0
- package/package.json +1 -1
package/dist/daemon/server.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { hasAgentShellNoColor, moduleFor } from '../agents/index.js';
|
|
9
9
|
import * as fs from 'node:fs';
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
10
11
|
import { randomUUID } from 'node:crypto';
|
|
11
12
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
12
13
|
import * as http from 'node:http';
|
|
@@ -16,27 +17,32 @@ import * as path from 'node:path';
|
|
|
16
17
|
import { fileURLToPath } from 'node:url';
|
|
17
18
|
import { WebSocketServer } from 'ws';
|
|
18
19
|
import { SessionManager, PolicyViolationError, SessionStartError } from '../core/manager.js';
|
|
19
|
-
import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox.js';
|
|
20
|
-
import {
|
|
20
|
+
import { Mailbox, MailboxError, NAME_PATTERN, NUDGE_LIST_CAP, buildNudge } from '../core/mailbox.js';
|
|
21
|
+
import { readingContext } from '../core/readingContext.js';
|
|
22
|
+
import { signatureOverBudgetLog, DEFAULT_VIEWER_LAUNCH_MODE, buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
|
|
21
23
|
import { NudgeScheduler } from './nudgeScheduler.js';
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
+
import { ConfigReload, parseConfigCandidate, unavailableConfig } from './configReload.js';
|
|
25
|
+
import { ConfigPermissions, ConfigWatcher } from './configWatcher.js';
|
|
26
|
+
import { standaloneOptions } from './standaloneOptions.js';
|
|
27
|
+
import { ScheduleStore, PromptScheduler } from './schedules.js';
|
|
28
|
+
import { CommandNotFoundError, DEFAULT_SESSION_ENV, MailNudgeWriteError, SessionInputFailedError, SessionProgramEndedError, TemporaryResizeNotReadyError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
|
|
24
29
|
import { NativePtyUnavailableError } from '../core/nativePty.js';
|
|
25
30
|
import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
|
|
26
31
|
import { keyToBytes, knownKeys } from '../core/keys.js';
|
|
27
32
|
import { findOnScreen } from '../core/find.js';
|
|
28
33
|
import { screenShows } from '../core/echo.js';
|
|
29
34
|
import { RegexBudgetError } from '../core/regexBudget.js';
|
|
35
|
+
import { dialogRuleRemoved } from '../core/dialogs.js';
|
|
30
36
|
import { detectPrompt } from '../core/promptDetector.js';
|
|
31
37
|
import { markFilteredSelectedOption } from '../core/selection.js';
|
|
32
38
|
import { WaitConditionError } from '../core/waiter.js';
|
|
33
39
|
import { agentNames, hideReasoning, latestResult, programName, signatureForSession } from '../core/reasoning.js';
|
|
34
40
|
import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_BODY_BYTES, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
|
|
35
41
|
import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
|
|
36
|
-
import { NULL_AUDITOR } from './audit.js';
|
|
42
|
+
import { createAuditor, NULL_AUDITOR } from './audit.js';
|
|
37
43
|
import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
|
|
38
44
|
import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureProfileRoot, captureViewer, sweepCaptureProfiles, } from './screenshot.js';
|
|
39
|
-
import { claimDaemonState,
|
|
45
|
+
import { claimDaemonState, HomeIdentityError, readHomeRecord, daemonStatePath, writePrivateRecord, writeVerifiedRecord, inspectDaemonState, readDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
|
|
40
46
|
import { acquireHomeOwner, AlreadyRunningError } from './homeOwner.js';
|
|
41
47
|
import { daemonRunning } from './liveness.js';
|
|
42
48
|
import { restoreRestartSource, retryRestartSource, snapshotSourceId } from './restartSource.js';
|
|
@@ -45,7 +51,7 @@ import { terminalReportBatchKind } from './terminalReports.js';
|
|
|
45
51
|
import { ViewerSync } from './viewerSync.js';
|
|
46
52
|
import { SessionFeed } from './sessionFeed.js';
|
|
47
53
|
import { compileProfilePolicy, copyDaemonEnv, describeProfileText, expandProfileText, resolveLaunchCommand, resolveAnyFolder, } from './launchProfiles.js';
|
|
48
|
-
import { DEFAULT_LAUNCHES_PER_MINUTE, listRootFolders,
|
|
54
|
+
import { DEFAULT_LAUNCHES_PER_MINUTE, listRootFolders, resolveRootFolder } from './launchProfiles.js';
|
|
49
55
|
import { chooseFolder, FOLDER_PICKER_TIMEOUT_MS, FolderPickerFailureError, FolderPickerUnavailableError, FolderPickerTimeoutError } from './folderPicker.js';
|
|
50
56
|
const DEFAULT_IDLE_MS = 30 * 60_000;
|
|
51
57
|
/** Stop waits this long for an automatic dashboard launch before continuing. */
|
|
@@ -454,20 +460,41 @@ function startShapeError(body) {
|
|
|
454
460
|
}
|
|
455
461
|
return null;
|
|
456
462
|
}
|
|
457
|
-
|
|
463
|
+
async function readBootConfig(requestedHome) {
|
|
464
|
+
const permissions = new ConfigPermissions(requestedHome);
|
|
465
|
+
const home = await permissions.secureHome();
|
|
466
|
+
try {
|
|
467
|
+
const candidate = await permissions.read().then(read => parseConfigCandidate(read.text), () => unavailableConfig('Could not verify permissions or read config.json.'));
|
|
468
|
+
permissions.verifiedHome();
|
|
469
|
+
return { home, permissions, candidate };
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
permissions.close();
|
|
473
|
+
throw error;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
458
476
|
export class Daemon {
|
|
459
477
|
options;
|
|
460
478
|
logger;
|
|
479
|
+
readings = {
|
|
480
|
+
agents: () => this.reload.state.agents,
|
|
481
|
+
dialogs: () => this.reload.state.dialogs,
|
|
482
|
+
overBudget: (kind, name, builtIn) => {
|
|
483
|
+
const { message, meta } = signatureOverBudgetLog(kind, name, builtIn);
|
|
484
|
+
this.logger.warn(message, meta);
|
|
485
|
+
},
|
|
486
|
+
};
|
|
461
487
|
tokens = new TokenStore();
|
|
462
488
|
manager;
|
|
463
489
|
mailbox;
|
|
464
490
|
nudges;
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
schedules = new ScheduleStore();
|
|
491
|
+
reload;
|
|
492
|
+
get schedules() { return this.reload.state.schedules; }
|
|
468
493
|
pendingSchedules = new Map();
|
|
469
494
|
promptScheduler;
|
|
470
|
-
|
|
495
|
+
configWatcher;
|
|
496
|
+
configPermissions;
|
|
497
|
+
preparedBoot;
|
|
471
498
|
server;
|
|
472
499
|
/** Protocol accepted by dashboard authentication for this specific upgrade. */
|
|
473
500
|
dashboardUpgradeProtocols = new WeakMap();
|
|
@@ -558,14 +585,17 @@ export class Daemon {
|
|
|
558
585
|
shutdownRecords;
|
|
559
586
|
audit;
|
|
560
587
|
callerContext = new AsyncLocalStorage();
|
|
561
|
-
/**
|
|
562
|
-
* What sessions get from the daemon's environment (ADR-008), resolved once so
|
|
563
|
-
* that what the daemon reports is what its sessions get.
|
|
564
|
-
*/
|
|
588
|
+
/** Environment mode for newly admitted sessions (ADR-008). */
|
|
565
589
|
sessionEnv;
|
|
566
590
|
/** The profiles the dashboard may name, and the entries that did not load. */
|
|
567
591
|
launchProfiles;
|
|
568
|
-
launchesPerMinute
|
|
592
|
+
get launchesPerMinute() {
|
|
593
|
+
return this.reload?.state.launchesPerMinute ?? this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
|
|
594
|
+
}
|
|
595
|
+
defaultViewerMode = 'no-window';
|
|
596
|
+
get viewer() {
|
|
597
|
+
return { launchMode: this.defaultViewerMode, ...this.reload?.state.config.viewer };
|
|
598
|
+
}
|
|
569
599
|
daemonEnv;
|
|
570
600
|
omitInheritedNoColor;
|
|
571
601
|
cliPath;
|
|
@@ -586,11 +616,24 @@ export class Daemon {
|
|
|
586
616
|
* not listed and not in the feed until the start contract is met.
|
|
587
617
|
*/
|
|
588
618
|
startingIds = new Set();
|
|
619
|
+
static async standalone(home, supervised) {
|
|
620
|
+
const boot = await readBootConfig(home);
|
|
621
|
+
try {
|
|
622
|
+
const options = standaloneOptions(boot.home, boot.candidate.config, supervised);
|
|
623
|
+
const daemon = new Daemon(options);
|
|
624
|
+
daemon.preparedBoot = boot;
|
|
625
|
+
daemon.configPermissions = boot.permissions;
|
|
626
|
+
return { daemon, logger: options.logger };
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
boot.permissions.close();
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
589
633
|
constructor(options) {
|
|
590
634
|
const startedWrapped = process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] === '1';
|
|
591
635
|
delete process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'];
|
|
592
636
|
this.options = { ...options,
|
|
593
|
-
home: path.resolve(options.home),
|
|
594
637
|
startedWrapped: options.startedWrapped ?? startedWrapped };
|
|
595
638
|
this.logger = options.logger;
|
|
596
639
|
const auditor = options.audit ?? NULL_AUDITOR;
|
|
@@ -604,20 +647,14 @@ export class Daemon {
|
|
|
604
647
|
};
|
|
605
648
|
this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
|
|
606
649
|
this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
|
|
607
|
-
this.launchesPerMinute = this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
|
|
608
650
|
this.daemonEnv = { ...(options.daemonEnv ?? process.env) };
|
|
609
651
|
this.omitInheritedNoColor = hasAgentShellNoColor(this.daemonEnv);
|
|
610
652
|
this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
|
|
611
653
|
this.compiledPolicy = compilePolicy(options.policy);
|
|
612
|
-
this.manager = new SessionManager(
|
|
654
|
+
this.manager = new SessionManager(this.compiledPolicy, this.logger, {
|
|
613
655
|
sessionEnv: this.sessionEnv,
|
|
614
656
|
omitInheritedNoColor: this.omitInheritedNoColor,
|
|
615
|
-
identity: {
|
|
616
|
-
token: '',
|
|
617
|
-
instanceId: this.instanceId,
|
|
618
|
-
cliPath: this.cliPath,
|
|
619
|
-
home: this.options.home,
|
|
620
|
-
},
|
|
657
|
+
identity: { token: '', instanceId: this.instanceId, cliPath: this.cliPath, home: () => this.configPermissions.homePath },
|
|
621
658
|
}, (id) => {
|
|
622
659
|
this.endMailboxParticipant(id);
|
|
623
660
|
this.sessionFeed.remove(id);
|
|
@@ -635,9 +672,9 @@ export class Daemon {
|
|
|
635
672
|
now: () => this.now(),
|
|
636
673
|
intervalMs: options.messaging?.nudgeIntervalMs ?? DEFAULT_NUDGE_INTERVAL_MS,
|
|
637
674
|
perMinute: options.messaging?.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE,
|
|
638
|
-
deliver: (id) => this.deliverNudge(id),
|
|
675
|
+
deliver: (id, onWrite) => this.deliverNudge(id, onWrite),
|
|
639
676
|
});
|
|
640
|
-
this.promptScheduler = new PromptScheduler(this.schedules, () => this.now(), (schedule, current) => this.deliverScheduled(schedule, current), (schedule, { sessionId, outcome, reason }) => this.audit.record('daemon', 'input', sessionId, {
|
|
677
|
+
this.promptScheduler = new PromptScheduler(() => this.schedules, () => this.now(), (schedule, current) => this.deliverScheduled(schedule, current), (schedule, { sessionId, outcome, reason }) => this.audit.record('daemon', 'input', sessionId, {
|
|
641
678
|
source: 'schedule', name: schedule.name, session: schedule.session, outcome, reason,
|
|
642
679
|
}));
|
|
643
680
|
this.mailbox.on('message', (event) => {
|
|
@@ -645,23 +682,18 @@ export class Daemon {
|
|
|
645
682
|
if (entry !== undefined)
|
|
646
683
|
this.messageAudit('msg-send', entry);
|
|
647
684
|
this.emitMessageEvent({ type: 'message', ...event }, entry);
|
|
648
|
-
this.
|
|
685
|
+
this.emitDashboardEvent({ type: 'message', ...event });
|
|
649
686
|
if (this.mailbox.participant(event.to.id)?.kind === 'session')
|
|
650
687
|
this.nudges.queue(event.to.id);
|
|
651
688
|
});
|
|
652
689
|
this.mailbox.on('state', (event) => {
|
|
653
690
|
const entry = this.mailbox.log().find((item) => item.id === event.id);
|
|
654
|
-
if (event.state === 'read' && entry !== undefined) {
|
|
655
|
-
const id = entry.to.id;
|
|
656
|
-
this.inboxReadVersions.set(id, (this.inboxReadVersions.get(id) ?? 0) + 1);
|
|
657
|
-
this.queuedMessageNudges.delete(id);
|
|
658
|
-
}
|
|
659
691
|
this.emitMessageEvent({ type: 'message-state', ...event }, entry);
|
|
660
|
-
this.
|
|
692
|
+
this.emitDashboardEvent({ type: 'message-state', ...event });
|
|
661
693
|
});
|
|
662
694
|
this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
|
|
663
695
|
this.server = http.createServer((req, res) => {
|
|
664
|
-
this.handleRequest(req, res).catch((error) => {
|
|
696
|
+
readingContext.run(this.readings, () => this.handleRequest(req, res)).catch((error) => {
|
|
665
697
|
// What a person needs to find the fault: the stack, and which request
|
|
666
698
|
// met it by method and path. Never the query, the headers or the
|
|
667
699
|
// body: a query can carry a viewer grant, a header the client token.
|
|
@@ -675,7 +707,7 @@ export class Daemon {
|
|
|
675
707
|
});
|
|
676
708
|
});
|
|
677
709
|
this.server.on('upgrade', (req, socket, head) => {
|
|
678
|
-
this.handleUpgrade(req, socket, head);
|
|
710
|
+
readingContext.run(this.readings, () => this.handleUpgrade(req, socket, head));
|
|
679
711
|
});
|
|
680
712
|
}
|
|
681
713
|
get port() {
|
|
@@ -709,14 +741,115 @@ export class Daemon {
|
|
|
709
741
|
return this.sessionFeed.subscribe(listener);
|
|
710
742
|
}
|
|
711
743
|
// ------------------------------------------------------------------ start
|
|
744
|
+
applyStartSettings() {
|
|
745
|
+
const { config, policy } = this.reload.state;
|
|
746
|
+
this.compiledPolicy = policy;
|
|
747
|
+
this.manager.setPolicy(policy);
|
|
748
|
+
this.sessionEnv = config.sessionEnv ?? DEFAULT_SESSION_ENV;
|
|
749
|
+
this.manager.setSessionEnv(this.sessionEnv);
|
|
750
|
+
this.launchProfiles = config.launcher ?? { profiles: [], problems: [] };
|
|
751
|
+
}
|
|
752
|
+
applyMessaging() {
|
|
753
|
+
const config = this.reload.state.messaging;
|
|
754
|
+
const reservedNames = new Set(config.allow.flatMap(rule => rule === 'parent-child' ? [] : rule.members));
|
|
755
|
+
this.mailbox.configure(config.enabled, buildMessagingPolicy(config, {
|
|
756
|
+
parentOf: id => this.manager.get(id)?.parent,
|
|
757
|
+
}), reservedNames, config.claimIdleMinutes);
|
|
758
|
+
this.nudges.setLimits(config.nudgeIntervalMs ?? DEFAULT_NUDGE_INTERVAL_MS, config.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE);
|
|
759
|
+
}
|
|
760
|
+
async prepareConfig() {
|
|
761
|
+
const standalone = this.preparedBoot;
|
|
762
|
+
const { permissions, candidate } = standalone ?? await readBootConfig(this.options.home);
|
|
763
|
+
this.preparedBoot = undefined;
|
|
764
|
+
this.configPermissions = permissions;
|
|
765
|
+
const home = permissions.verifiedHome();
|
|
766
|
+
// Embedded callers can supply initial live settings independently of the file.
|
|
767
|
+
const boot = standalone ? candidate : { ...candidate, config: { ...candidate.config,
|
|
768
|
+
viewer: this.options.viewer ?? candidate.config.viewer,
|
|
769
|
+
policy: this.options.policy ?? candidate.config.policy,
|
|
770
|
+
sessionEnv: this.options.sessionEnv ?? candidate.config.sessionEnv,
|
|
771
|
+
idleMinutes: this.options.idleMs === undefined ? candidate.config.idleMinutes : this.options.idleMs / 60_000,
|
|
772
|
+
dashboard: this.options.dashboardFontSize === undefined ? candidate.config.dashboard : { fontSize: this.options.dashboardFontSize },
|
|
773
|
+
audit: candidate.config.audit ?? { captureContent: this.audit.captureContent },
|
|
774
|
+
messaging: this.options.messaging ?? candidate.config.messaging,
|
|
775
|
+
launcher: candidate.config.launcher ?? this.launchProfiles } };
|
|
776
|
+
this.defaultViewerMode = standalone ? DEFAULT_VIEWER_LAUNCH_MODE : 'no-window';
|
|
777
|
+
const append = this.audit.recordRequired ?? createAuditor(home).recordRequired;
|
|
778
|
+
const ownsHome = () => {
|
|
779
|
+
try {
|
|
780
|
+
return !this.stopping && this.requireHomeOwner().kind === 'record';
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
return false;
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
const reload = this.reload = new ConfigReload(boot, {
|
|
787
|
+
ownsHome,
|
|
788
|
+
log: (message, reason) => reason ? this.logger.warn(message, { reason }) : this.logger.info(message),
|
|
789
|
+
audit: (action, sections) => append('daemon', action, undefined, { sections }),
|
|
790
|
+
saveGrants: (names, read, audit) => {
|
|
791
|
+
if (!this.claimsRestored || !read.recheckDirectory)
|
|
792
|
+
throw new Error('Cannot prepare launcher claims.');
|
|
793
|
+
return writeVerifiedRecord(permissions, 'launcher-claims.json', () => this.mailbox.savedClaims(names), read.recheckDirectory, audit);
|
|
794
|
+
},
|
|
795
|
+
changed: (sections, fields, previousAgents) => {
|
|
796
|
+
this.applyStartSettings();
|
|
797
|
+
if (sections.includes('messaging'))
|
|
798
|
+
this.applyMessaging();
|
|
799
|
+
if (fields.includes('sessionEnv'))
|
|
800
|
+
this.warnPassthrough();
|
|
801
|
+
if (fields.includes('launcher.profiles'))
|
|
802
|
+
this.emitDashboardEvent({ type: 'profiles-changed' });
|
|
803
|
+
if (fields.includes('prompts.dialogs') || fields.includes('agents.signatures')) {
|
|
804
|
+
const dialogsChanged = fields.includes('prompts.dialogs');
|
|
805
|
+
for (const { id, agent } of this.manager.list()) {
|
|
806
|
+
if (!dialogsChanged && previousAgents.find(s => s.name === agent) === this.reload.state.agents.find(s => s.name === agent))
|
|
807
|
+
continue;
|
|
808
|
+
const session = this.manager.get(id);
|
|
809
|
+
if (session && !session.exited) {
|
|
810
|
+
session.refreshReadingRules();
|
|
811
|
+
const held = this.promptStates.get(id);
|
|
812
|
+
const removed = held !== undefined && dialogRuleRemoved(held.prompt, this.readings.dialogs());
|
|
813
|
+
this.updatePromptState(session, session.answerablePrompt(session.getScreen()), removed);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
},
|
|
818
|
+
}, standalone ? undefined : 'no-window');
|
|
819
|
+
this.applyStartSettings();
|
|
820
|
+
this.applyMessaging();
|
|
821
|
+
this.configWatcher = new ConfigWatcher({
|
|
822
|
+
watch: notify => fs.watch(home, { persistent: false }, (_event, name) => notify(name)),
|
|
823
|
+
read: () => permissions.read(), receive: candidate => readingContext.run(this.readings, () => reload.reconcile(candidate)), fail: reason => { if (ownsHome())
|
|
824
|
+
reload.reject(reason); },
|
|
825
|
+
health: state => {
|
|
826
|
+
if (state === 'polling' && reload.status.watcher !== state)
|
|
827
|
+
this.logger.warn('Config watcher unavailable, polling config.json.');
|
|
828
|
+
reload.status.watcher = state;
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
return boot.diagnostics;
|
|
832
|
+
}
|
|
712
833
|
async start() {
|
|
713
|
-
|
|
714
|
-
|
|
834
|
+
try {
|
|
835
|
+
return await readingContext.run(this.readings, () => this.startInHome());
|
|
836
|
+
}
|
|
837
|
+
catch (error) {
|
|
838
|
+
this.configPermissions?.close();
|
|
839
|
+
this.configWatcher?.stop();
|
|
840
|
+
throw error;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
async startInHome() {
|
|
844
|
+
const diagnostics = await this.prepareConfig();
|
|
715
845
|
// Defer to an incumbent that is running, even one too busy to answer its
|
|
716
846
|
// health check; clear a record whose daemon has gone (design §2.3).
|
|
717
|
-
const
|
|
847
|
+
const permissions = this.configPermissions;
|
|
848
|
+
const existing = readDaemonState(permissions);
|
|
718
849
|
if (existing !== null) {
|
|
719
|
-
|
|
850
|
+
const running = await this.incumbentRunning(existing);
|
|
851
|
+
permissions.verifiedHome();
|
|
852
|
+
if (running)
|
|
720
853
|
throw new AlreadyRunningError(existing);
|
|
721
854
|
if (this.stopping)
|
|
722
855
|
throw new Error('Daemon stopped during startup.');
|
|
@@ -751,8 +884,8 @@ export class Daemon {
|
|
|
751
884
|
// a session start waits for its viewer launch, so look once now and let the
|
|
752
885
|
// memoised answer serve every start. It never holds the event loop, so the
|
|
753
886
|
// daemon answers /health and everything else while it runs.
|
|
754
|
-
if (['dashboard', 'isolated-app'].includes(this.
|
|
755
|
-
void findBrowser(this.
|
|
887
|
+
if (['dashboard', 'isolated-app'].includes(this.viewer.launchMode ?? 'no-window')) {
|
|
888
|
+
void findBrowser(this.viewer.browserPath, this.logger).catch(() => undefined);
|
|
756
889
|
}
|
|
757
890
|
const state = {
|
|
758
891
|
port: this.portValue,
|
|
@@ -766,58 +899,74 @@ export class Daemon {
|
|
|
766
899
|
// Hold the home independently of discovery, including while restoring
|
|
767
900
|
// claims and publishing shutdown records. This also serialises takeovers.
|
|
768
901
|
try {
|
|
769
|
-
this.homeOwner = await acquireHomeOwner(
|
|
902
|
+
this.homeOwner = await acquireHomeOwner(permissions, state.port, this.instanceId);
|
|
770
903
|
if (this.stopping)
|
|
771
904
|
throw new Error('Daemon stopped during startup.');
|
|
772
|
-
const file = inspectDaemonState(
|
|
773
|
-
|
|
905
|
+
const file = inspectDaemonState(permissions);
|
|
906
|
+
const running = file.kind === 'record' && await this.incumbentRunning(file.state);
|
|
907
|
+
permissions.verifiedHome();
|
|
908
|
+
if (file.kind === 'record' && running) {
|
|
774
909
|
throw new AlreadyRunningError(file.state);
|
|
775
910
|
}
|
|
776
911
|
if (this.stopping)
|
|
777
912
|
throw new Error('Daemon stopped during startup.');
|
|
778
913
|
if (file.kind === 'unreadable')
|
|
779
914
|
throw new Error('Could not read daemon.json to claim the home.');
|
|
780
|
-
Object.assign(state, restoreRestartSource(
|
|
915
|
+
Object.assign(state, restoreRestartSource(permissions, file, this.logger));
|
|
916
|
+
for (const problem of diagnostics)
|
|
917
|
+
this.logger.warn('CONFIG PROBLEM', { problem });
|
|
918
|
+
permissions.verifiedHome();
|
|
781
919
|
if (file.kind === 'missing') {
|
|
782
|
-
if (!claimDaemonState(
|
|
920
|
+
if (!claimDaemonState(permissions.homePath, state))
|
|
783
921
|
throw new Error('Another daemon claimed daemon.json first.');
|
|
784
922
|
}
|
|
785
923
|
else {
|
|
786
924
|
// A failed rename leaves the entire predecessor record in place.
|
|
787
|
-
writePrivateRecord(daemonStatePath(
|
|
925
|
+
writePrivateRecord(daemonStatePath(permissions.homePath), state);
|
|
788
926
|
}
|
|
789
927
|
if (this.options.afterPublish) {
|
|
790
928
|
await this.options.afterPublish();
|
|
929
|
+
permissions.verifiedHome();
|
|
791
930
|
this.server.off('connection', refusePending);
|
|
792
931
|
}
|
|
932
|
+
this.publishedState = state;
|
|
933
|
+
try {
|
|
934
|
+
const rows = JSON.parse(readHomeRecord(permissions, 'launcher-claims.json'));
|
|
935
|
+
if (!Array.isArray(rows))
|
|
936
|
+
throw new Error('Expected saved launcher claims to be an array.');
|
|
937
|
+
const grants = this.reload.state.messaging.enabled ? this.launchProfiles.sessionLaunch ?? [] : [];
|
|
938
|
+
this.claimCount = this.mailbox.restoreClaims(rows, grants);
|
|
939
|
+
this.claimsRestored = true;
|
|
940
|
+
this.saveLauncherClaims();
|
|
941
|
+
}
|
|
942
|
+
catch (error) {
|
|
943
|
+
if (error instanceof HomeIdentityError)
|
|
944
|
+
throw error;
|
|
945
|
+
if (error.code === 'ENOENT')
|
|
946
|
+
this.claimsRestored = true;
|
|
947
|
+
else
|
|
948
|
+
this.logger.warn(this.claimsRestored ? 'Could not update saved launcher claims.' : 'Could not restore saved launcher claims.');
|
|
949
|
+
}
|
|
793
950
|
}
|
|
794
951
|
catch (error) {
|
|
795
952
|
this.releaseOwnership();
|
|
796
953
|
await this.closeServerOnly();
|
|
797
954
|
throw error;
|
|
798
955
|
}
|
|
799
|
-
this.publishedState = state;
|
|
800
|
-
const claimsFile = path.join(home, 'launcher-claims.json');
|
|
801
|
-
try {
|
|
802
|
-
const rows = JSON.parse(fs.readFileSync(claimsFile, 'utf8'));
|
|
803
|
-
if (!Array.isArray(rows))
|
|
804
|
-
throw new Error('Expected saved launcher claims to be an array.');
|
|
805
|
-
this.claimCount = this.mailbox.restoreClaims(rows, this.options.messaging?.enabled ? this.launchProfiles.sessionLaunch ?? [] : []);
|
|
806
|
-
this.claimsRestored = true;
|
|
807
|
-
this.saveLauncherClaims();
|
|
808
|
-
}
|
|
809
|
-
catch (error) {
|
|
810
|
-
if (error.code === 'ENOENT')
|
|
811
|
-
this.claimsRestored = true;
|
|
812
|
-
else
|
|
813
|
-
this.logger.warn(this.claimsRestored ? 'Could not update saved launcher claims.' : 'Could not restore saved launcher claims.');
|
|
814
|
-
}
|
|
815
956
|
// Belt and braces for the unlink/claim TOCTOU sliver: shortly after
|
|
816
957
|
// start-up, if the published record names someone else and nobody is
|
|
817
958
|
// attached to us, bow out quietly. Clients only ever discover the daemon
|
|
818
959
|
// named in the file, so nobody can be depending on us yet.
|
|
819
960
|
this.raceCheckTimer = setTimeout(() => {
|
|
820
|
-
|
|
961
|
+
let current;
|
|
962
|
+
try {
|
|
963
|
+
current = readDaemonState(permissions);
|
|
964
|
+
}
|
|
965
|
+
catch (error) {
|
|
966
|
+
if (error instanceof HomeIdentityError)
|
|
967
|
+
return;
|
|
968
|
+
throw error;
|
|
969
|
+
}
|
|
821
970
|
if (current !== null &&
|
|
822
971
|
current.instanceId !== this.instanceId &&
|
|
823
972
|
this.manager.size() === 0 &&
|
|
@@ -834,22 +983,17 @@ export class Daemon {
|
|
|
834
983
|
// Capture profiles an earlier daemon on this home could not remove, which
|
|
835
984
|
// Windows can refuse while a browser's last processes hold them. Only
|
|
836
985
|
// folders a capture names, untouched for longer than any capture runs.
|
|
837
|
-
void sweepCaptureProfiles(captureProfileRoot(
|
|
838
|
-
// Said once, at start, because passthrough leaks silently otherwise
|
|
839
|
-
// (ADR-008): the names only, never the values.
|
|
840
|
-
const { exposed } = this.environmentReport();
|
|
986
|
+
void sweepCaptureProfiles(captureProfileRoot(permissions.homePath), this.logger);
|
|
841
987
|
if (this.omitInheritedNoColor)
|
|
842
988
|
this.logger.info('omitting inherited output setting from agent tool shell', { names: ['NO_COLOR'] });
|
|
843
|
-
|
|
844
|
-
this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
|
|
845
|
-
'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
|
|
846
|
-
}
|
|
989
|
+
this.warnPassthrough();
|
|
847
990
|
this.statePublishTimer = setInterval(() => {
|
|
848
991
|
void this.keepStatePublished();
|
|
849
992
|
}, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
|
|
850
993
|
this.statePublishTimer.unref();
|
|
851
|
-
const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
|
|
852
994
|
this.idleTimer = setInterval(() => {
|
|
995
|
+
const minutes = this.reload?.state.config.idleMinutes;
|
|
996
|
+
const idleMs = minutes === undefined ? DEFAULT_IDLE_MS : minutes * 60_000;
|
|
853
997
|
this.lapseIdleClaims();
|
|
854
998
|
// Reap sessions whose grace has lapsed before judging idleness. A
|
|
855
999
|
// rejected sweep must be caught here, or it becomes an
|
|
@@ -884,14 +1028,11 @@ export class Daemon {
|
|
|
884
1028
|
});
|
|
885
1029
|
}, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
|
|
886
1030
|
this.promptScanTimer.unref();
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
if (!initial && allowance.problem !== undefined)
|
|
893
|
-
this.logger.warn('CONFIG PROBLEM', { problem: allowance.problem });
|
|
894
|
-
});
|
|
1031
|
+
if (this.reload?.status.reason)
|
|
1032
|
+
this.logger.warn('Degraded configuration at startup', { reason: this.reload.status.reason });
|
|
1033
|
+
await this.configWatcher.start();
|
|
1034
|
+
if (this.stopping)
|
|
1035
|
+
throw new Error('Daemon stopped during startup.');
|
|
895
1036
|
this.promptScheduler.start();
|
|
896
1037
|
this.logger.info('daemon started', {
|
|
897
1038
|
port: this.portValue,
|
|
@@ -939,8 +1080,7 @@ export class Daemon {
|
|
|
939
1080
|
return;
|
|
940
1081
|
this.statePublishRunning = true;
|
|
941
1082
|
try {
|
|
942
|
-
const
|
|
943
|
-
const file = inspectDaemonState(home);
|
|
1083
|
+
const file = inspectDaemonState(this.configPermissions);
|
|
944
1084
|
if (file.kind === 'unreadable')
|
|
945
1085
|
return;
|
|
946
1086
|
if (file.kind === 'record') {
|
|
@@ -962,12 +1102,12 @@ export class Daemon {
|
|
|
962
1102
|
}
|
|
963
1103
|
if (this.stopping || !this.homeOwner?.held())
|
|
964
1104
|
return;
|
|
965
|
-
removeDaemonStateIf(
|
|
1105
|
+
removeDaemonStateIf(this.configPermissions, current);
|
|
966
1106
|
}
|
|
967
1107
|
else if (file.kind === 'not-a-record') {
|
|
968
|
-
removeDaemonStateIfNotARecord(
|
|
1108
|
+
removeDaemonStateIfNotARecord(this.configPermissions, file.raw);
|
|
969
1109
|
}
|
|
970
|
-
if (this.stopPromise === null && claimDaemonState(
|
|
1110
|
+
if (this.stopPromise === null && claimDaemonState(this.configPermissions.homePath, published)) {
|
|
971
1111
|
this.foreignOwnerReported = null;
|
|
972
1112
|
this.logger.warn('daemon.json was missing, held no daemon record or named a daemon that has gone; published it again', { pid: published.pid, port: published.port });
|
|
973
1113
|
}
|
|
@@ -1010,7 +1150,8 @@ export class Daemon {
|
|
|
1010
1150
|
if (this.stopPromise === null) {
|
|
1011
1151
|
this.stopping = true;
|
|
1012
1152
|
this.promptScheduler.stop();
|
|
1013
|
-
this.
|
|
1153
|
+
this.configWatcher?.stop();
|
|
1154
|
+
this.configPermissions?.close();
|
|
1014
1155
|
this.shutdownRecords = this.saveShutdownRecords(opts);
|
|
1015
1156
|
this.stopPromise = this.doStop();
|
|
1016
1157
|
}
|
|
@@ -1025,7 +1166,7 @@ export class Daemon {
|
|
|
1025
1166
|
if (opts.restart) {
|
|
1026
1167
|
this.writeShutdownRecord('restart-source.json', () => {
|
|
1027
1168
|
this.requireHomeOwner();
|
|
1028
|
-
writePrivateRecord(path.join(this.
|
|
1169
|
+
writePrivateRecord(path.join(this.configPermissions.homePath, 'restart-source.json'), { restartFrom: this.instanceId });
|
|
1029
1170
|
});
|
|
1030
1171
|
this.writeShutdownRecord('previous-sessions.json', () => this.savePreviousSessions());
|
|
1031
1172
|
}
|
|
@@ -1044,13 +1185,13 @@ export class Daemon {
|
|
|
1044
1185
|
if (handoff.restartFrom || handoff.restartCandidates) {
|
|
1045
1186
|
// If replacement fails, the live record can still confirm a snapshot
|
|
1046
1187
|
// stamped by this instance after the storage fault clears.
|
|
1047
|
-
writePrivateRecord(daemonStatePath(this.
|
|
1188
|
+
writePrivateRecord(daemonStatePath(this.configPermissions.homePath), handoff);
|
|
1048
1189
|
}
|
|
1049
1190
|
else if (discovery.kind === 'not-a-record') {
|
|
1050
|
-
removeDaemonStateIfNotARecord(this.
|
|
1191
|
+
removeDaemonStateIfNotARecord(this.configPermissions, discovery.raw);
|
|
1051
1192
|
}
|
|
1052
1193
|
else {
|
|
1053
|
-
removeDaemonStateIf(this.
|
|
1194
|
+
removeDaemonStateIf(this.configPermissions, state);
|
|
1054
1195
|
}
|
|
1055
1196
|
}
|
|
1056
1197
|
writeShutdownRecord(file, write, verb = 'save') {
|
|
@@ -1075,7 +1216,7 @@ export class Daemon {
|
|
|
1075
1216
|
requireHomeOwner() {
|
|
1076
1217
|
const state = this.publishedState;
|
|
1077
1218
|
if (this.homeOwner?.held() && state) {
|
|
1078
|
-
const file = inspectDaemonState(this.
|
|
1219
|
+
const file = inspectDaemonState(this.configPermissions);
|
|
1079
1220
|
// The exclusive home marker still protects the durable files when
|
|
1080
1221
|
// discovery is missing, damaged or temporarily inaccessible.
|
|
1081
1222
|
if (file.kind !== 'record' && file.kind !== 'restart-handoff')
|
|
@@ -1163,10 +1304,11 @@ export class Daemon {
|
|
|
1163
1304
|
await listenerClosed;
|
|
1164
1305
|
this.logger.info('daemon stopped');
|
|
1165
1306
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1307
|
+
warnPassthrough() {
|
|
1308
|
+
const { exposed } = this.environmentReport();
|
|
1309
|
+
if (exposed.length)
|
|
1310
|
+
this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including these variables whose names look like credentials', { names: exposed });
|
|
1311
|
+
}
|
|
1170
1312
|
environmentReport() {
|
|
1171
1313
|
const mode = this.sessionEnv;
|
|
1172
1314
|
if (mode === 'passthrough')
|
|
@@ -1291,7 +1433,7 @@ export class Daemon {
|
|
|
1291
1433
|
const html = fs.readFileSync(dashboardHtmlPath, 'utf8');
|
|
1292
1434
|
const withProof = proof === null ? html.replace(DASHBOARD_PROOF_META, '')
|
|
1293
1435
|
: html.replace(DASHBOARD_PROOF_META, `<meta name="sp-csrf" content="${proof}">`);
|
|
1294
|
-
const size = proof === null ? undefined : this.
|
|
1436
|
+
const size = proof === null ? undefined : this.reload?.state.config.dashboard?.fontSize;
|
|
1295
1437
|
return withProof.replace(DASHBOARD_FONT_META, size === undefined ? '' : `<meta name="sp-dashboard-font-size" content="${String(size)}">`);
|
|
1296
1438
|
}
|
|
1297
1439
|
sendDashboardPage(res, proof, head) {
|
|
@@ -1370,7 +1512,7 @@ export class Daemon {
|
|
|
1370
1512
|
const launch = this.options.launcher ?? launchDashboard;
|
|
1371
1513
|
let opened;
|
|
1372
1514
|
try {
|
|
1373
|
-
opened = await launch(pageUrl, this.
|
|
1515
|
+
opened = await launch(pageUrl, this.configPermissions.homePath, this.viewer, this.logger, {
|
|
1374
1516
|
shouldLaunch: () => !this.stopping,
|
|
1375
1517
|
});
|
|
1376
1518
|
}
|
|
@@ -1571,11 +1713,11 @@ export class Daemon {
|
|
|
1571
1713
|
counts[entry.to.id] = (counts[entry.to.id] ?? 0) + 1;
|
|
1572
1714
|
}
|
|
1573
1715
|
const summary = url.searchParams.get('summary') === '1';
|
|
1574
|
-
const groups = (this.
|
|
1716
|
+
const groups = (this.reload?.state.messaging.allow ?? []).filter((rule) => typeof rule !== 'string')
|
|
1575
1717
|
.map((rule) => ({ group: rule.group, members: rule.members, roles: rule.roles ?? [] }));
|
|
1576
1718
|
this.audit.record('dashboard', 'msg-log', undefined, { count: messages.length });
|
|
1577
1719
|
this.lastActivity = Date.now();
|
|
1578
|
-
json(res, 200, { enabled: this.
|
|
1720
|
+
json(res, 200, { enabled: this.reload?.state.messaging.enabled === true,
|
|
1579
1721
|
counts, ...(summary ? {} : { messages, groups }) });
|
|
1580
1722
|
}
|
|
1581
1723
|
/** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
|
|
@@ -1611,7 +1753,8 @@ export class Daemon {
|
|
|
1611
1753
|
purpose: describeProfileText(profile.purpose ?? '', profile.name),
|
|
1612
1754
|
command: profile.command,
|
|
1613
1755
|
args: [...profile.args],
|
|
1614
|
-
...(profile.resume ? { canResume: true
|
|
1756
|
+
...(profile.resume ? { canResume: true, resumeArgs: profile.resume,
|
|
1757
|
+
resumeCwd: profile.askCwd ? undefined : path.resolve(os.homedir(), profile.cwd ?? '.') } : {}),
|
|
1615
1758
|
folderRequired: profile.askCwd,
|
|
1616
1759
|
anyFolder: profile.anyFolder,
|
|
1617
1760
|
folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
|
|
@@ -1643,9 +1786,10 @@ export class Daemon {
|
|
|
1643
1786
|
return;
|
|
1644
1787
|
}
|
|
1645
1788
|
this.lastActivity = Date.now();
|
|
1789
|
+
const catalogue = this.launchProfiles;
|
|
1646
1790
|
json(res, 200, {
|
|
1647
|
-
profiles: await Promise.all(
|
|
1648
|
-
problems: [...
|
|
1791
|
+
profiles: await Promise.all(catalogue.profiles.map(profile => this.profileDescription(profile))),
|
|
1792
|
+
problems: [...catalogue.problems],
|
|
1649
1793
|
});
|
|
1650
1794
|
}
|
|
1651
1795
|
/** The desktop picker is available only to an authenticated any-folder profile. */
|
|
@@ -1698,6 +1842,7 @@ export class Daemon {
|
|
|
1698
1842
|
json(res, 409, { error: 'A folder picker is already open.' });
|
|
1699
1843
|
return;
|
|
1700
1844
|
}
|
|
1845
|
+
const pickerProfile = this.launchProfiles.profiles.find(profile => profile.name === body['profile']);
|
|
1701
1846
|
this.folderPickerBusy = true;
|
|
1702
1847
|
const controller = new AbortController();
|
|
1703
1848
|
this.folderPickerAbort = controller;
|
|
@@ -1736,6 +1881,10 @@ export class Daemon {
|
|
|
1736
1881
|
res.end();
|
|
1737
1882
|
return;
|
|
1738
1883
|
}
|
|
1884
|
+
if (!isDeepStrictEqual(pickerProfile, this.launchProfiles.profiles.find(profile => profile.name === body['profile']))) {
|
|
1885
|
+
json(res, 409, { error: 'The profile changed while choosing a folder. Choose the folder again.' });
|
|
1886
|
+
return;
|
|
1887
|
+
}
|
|
1739
1888
|
json(res, 200, { path: selected });
|
|
1740
1889
|
}
|
|
1741
1890
|
catch (error) {
|
|
@@ -1859,7 +2008,8 @@ export class Daemon {
|
|
|
1859
2008
|
json(res, 409, { error: 'The launching dashboard window has closed.' });
|
|
1860
2009
|
return;
|
|
1861
2010
|
}
|
|
1862
|
-
const
|
|
2011
|
+
const profileIndex = this.launchProfiles.profiles.findIndex((entry) => entry.name === profileName);
|
|
2012
|
+
const profile = this.launchProfiles.profiles[profileIndex];
|
|
1863
2013
|
if (profile === undefined) {
|
|
1864
2014
|
json(res, 400, { error: `No such launch profile: ${profileName}` });
|
|
1865
2015
|
return;
|
|
@@ -1947,14 +2097,15 @@ export class Daemon {
|
|
|
1947
2097
|
}
|
|
1948
2098
|
// Global policy runs first, then the profile's own deny and allow lists.
|
|
1949
2099
|
// Both see the real command line, before any Windows shell wrap.
|
|
1950
|
-
const
|
|
2100
|
+
const policy = this.compiledPolicy;
|
|
2101
|
+
const globalDecision = evaluateCommand(policy, profile.command, args);
|
|
1951
2102
|
if (!globalDecision.allowed) {
|
|
1952
2103
|
this.auditDashboardRefusal(req, 'policy', launcher?.name);
|
|
1953
2104
|
json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
|
|
1954
2105
|
return;
|
|
1955
2106
|
}
|
|
1956
2107
|
if (profile.policy !== undefined) {
|
|
1957
|
-
const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, args);
|
|
2108
|
+
const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy, profile.configIndex ?? profileIndex), profile.command, args);
|
|
1958
2109
|
if (!ownDecision.allowed) {
|
|
1959
2110
|
this.auditDashboardRefusal(req, 'policy', launcher?.name);
|
|
1960
2111
|
json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
|
|
@@ -2033,6 +2184,18 @@ export class Daemon {
|
|
|
2033
2184
|
return;
|
|
2034
2185
|
}
|
|
2035
2186
|
}
|
|
2187
|
+
if (!isDeepStrictEqual(profile, this.launchProfiles.profiles.find(entry => entry.name === profileName))) {
|
|
2188
|
+
json(res, 409, { error: 'Configuration changed while preparing the launch. Try again.' });
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
if (policy !== this.compiledPolicy) {
|
|
2192
|
+
const decision = evaluateCommand(this.compiledPolicy, profile.command, args);
|
|
2193
|
+
if (!decision.allowed) {
|
|
2194
|
+
this.auditDashboardRefusal(req, 'policy', launcher?.name);
|
|
2195
|
+
json(res, 403, { error: decision.reason ?? 'Command refused by policy.' });
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2036
2199
|
const now = this.now();
|
|
2037
2200
|
this.pruneLaunchTimes(now);
|
|
2038
2201
|
if (this.launchTimes.length + this.pendingProfileStarts.size >= this.launchesPerMinute) {
|
|
@@ -2089,14 +2252,16 @@ export class Daemon {
|
|
|
2089
2252
|
return;
|
|
2090
2253
|
}
|
|
2091
2254
|
// Reserve before yielding. Only a confirmed program starts its rolling minute.
|
|
2255
|
+
const mailboxName = this.reserveMailboxName(session, requestedName);
|
|
2092
2256
|
const reserved = session;
|
|
2093
2257
|
this.pendingProfileStarts.add(reserved);
|
|
2094
|
-
const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); };
|
|
2258
|
+
const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); mailboxName.release(); };
|
|
2095
2259
|
try {
|
|
2096
2260
|
const started = await this.programStarted(session, options, res, 'dashboard session start failed', releaseReservation);
|
|
2097
2261
|
if (started === null)
|
|
2098
2262
|
return;
|
|
2099
2263
|
session = started;
|
|
2264
|
+
this.registerMailboxSession(session, mailboxName.name);
|
|
2100
2265
|
this.launchTimes.push(this.now());
|
|
2101
2266
|
}
|
|
2102
2267
|
finally {
|
|
@@ -2105,7 +2270,6 @@ export class Daemon {
|
|
|
2105
2270
|
// A launch is an API call: the idle timer counts from it, so a session
|
|
2106
2271
|
// that has just started is not reaped sooner than `idleMinutes` allows.
|
|
2107
2272
|
this.lastActivity = Date.now();
|
|
2108
|
-
this.registerMailboxSession(session, requestedName);
|
|
2109
2273
|
if (launchingWindow && launchingWindow.socket.readyState === launchingWindow.socket.OPEN &&
|
|
2110
2274
|
this.dashboardWindowIds.has(launchingWindow.socket)) {
|
|
2111
2275
|
const { pair } = launchingWindow;
|
|
@@ -2548,8 +2712,7 @@ export class Daemon {
|
|
|
2548
2712
|
return false;
|
|
2549
2713
|
}
|
|
2550
2714
|
if (state.restartCandidates) {
|
|
2551
|
-
const
|
|
2552
|
-
const resolved = retryRestartSource(home, state, snapshot, this.logger, () => this.requireHomeOwner());
|
|
2715
|
+
const resolved = retryRestartSource(this.configPermissions, state, snapshot, this.logger, () => this.requireHomeOwner());
|
|
2553
2716
|
if (resolved.restartCandidates)
|
|
2554
2717
|
return false;
|
|
2555
2718
|
// Remember a verified writer even when it rules out the rows just read.
|
|
@@ -2559,7 +2722,7 @@ export class Daemon {
|
|
|
2559
2722
|
Object.assign(state, resolved);
|
|
2560
2723
|
if (discovery.kind === 'record') {
|
|
2561
2724
|
try {
|
|
2562
|
-
writePrivateRecord(daemonStatePath(
|
|
2725
|
+
writePrivateRecord(daemonStatePath(this.configPermissions.homePath), state, () => {
|
|
2563
2726
|
if (this.requireHomeOwner().kind !== 'record')
|
|
2564
2727
|
throw new Error('Discovery changed during recovery.');
|
|
2565
2728
|
});
|
|
@@ -2585,11 +2748,11 @@ export class Daemon {
|
|
|
2585
2748
|
return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
|
|
2586
2749
|
agent: session.agent, resumeId: session.resumeId, endedAt }];
|
|
2587
2750
|
});
|
|
2588
|
-
writePrivateRecord(path.join(this.
|
|
2751
|
+
writePrivateRecord(path.join(this.configPermissions.homePath, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
|
|
2589
2752
|
}
|
|
2590
2753
|
saveLauncherClaims(excludeId, next, beforePublish) {
|
|
2591
2754
|
const grants = this.launchProfiles.sessionLaunch ?? [];
|
|
2592
|
-
const file = path.join(this.
|
|
2755
|
+
const file = path.join(this.configPermissions.homePath, 'launcher-claims.json');
|
|
2593
2756
|
if (!this.claimsRestored)
|
|
2594
2757
|
throw new Error('Saved launcher claims could not be restored.');
|
|
2595
2758
|
if (grants.length || fs.existsSync(file)) {
|
|
@@ -2619,28 +2782,25 @@ export class Daemon {
|
|
|
2619
2782
|
throw new ClaimAuditError(failure);
|
|
2620
2783
|
}
|
|
2621
2784
|
}
|
|
2622
|
-
presentedClaim(req
|
|
2785
|
+
presentedClaim(req) {
|
|
2623
2786
|
const id = req.headers['x-shellpuppet-claim'];
|
|
2624
2787
|
const secret = req.headers['x-shellpuppet-claim-secret'];
|
|
2625
2788
|
if (id === undefined && secret === undefined)
|
|
2626
2789
|
return {};
|
|
2627
2790
|
const marked = req.headers['x-shellpuppet-inside-session'] === '1';
|
|
2628
|
-
if (
|
|
2791
|
+
if (typeof id === 'string' && typeof secret === 'string' &&
|
|
2629
2792
|
this.mailbox.verifyClaim(id, secret, !marked))
|
|
2630
2793
|
return { id };
|
|
2631
2794
|
return { refused: true };
|
|
2632
2795
|
}
|
|
2633
2796
|
grantedLauncher(req, res) {
|
|
2634
2797
|
this.lapseIdleClaims();
|
|
2635
|
-
|
|
2636
|
-
if (
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
json(res, 403, { error: 'Session launch permission required.', ...invalidClaim });
|
|
2640
|
-
return undefined;
|
|
2641
|
-
}
|
|
2642
|
-
id = claim.id;
|
|
2798
|
+
const claim = this.presentedClaim(req);
|
|
2799
|
+
if (claim.refused) {
|
|
2800
|
+
json(res, 403, { error: 'Session launch permission required.', ...invalidClaim });
|
|
2801
|
+
return undefined;
|
|
2643
2802
|
}
|
|
2803
|
+
const id = this.callerContext.getStore() ?? (req.headers['x-shellpuppet-inside-session'] === '1' ? undefined : claim.id);
|
|
2644
2804
|
const caller = id === undefined ? undefined : this.mailbox.participant(id);
|
|
2645
2805
|
if (caller && this.launchProfiles.sessionLaunch?.includes(caller.name))
|
|
2646
2806
|
return caller;
|
|
@@ -2659,8 +2819,6 @@ export class Daemon {
|
|
|
2659
2819
|
if (pendingId === id)
|
|
2660
2820
|
this.pendingSchedules.delete(name);
|
|
2661
2821
|
this.nudges.remove(id);
|
|
2662
|
-
this.queuedMessageNudges.delete(id);
|
|
2663
|
-
this.inboxReadVersions.delete(id);
|
|
2664
2822
|
// Audit before end can trim old tombstones from retained history.
|
|
2665
2823
|
for (const entry of this.mailbox.log({ participantId: id })) {
|
|
2666
2824
|
if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
|
|
@@ -2683,148 +2841,53 @@ export class Daemon {
|
|
|
2683
2841
|
this.audit.record('daemon', 'msg-lapse', id);
|
|
2684
2842
|
}
|
|
2685
2843
|
}
|
|
2686
|
-
async deliverNudge(id) {
|
|
2844
|
+
async deliverNudge(id, onWrite, confirmOnly = false) {
|
|
2687
2845
|
const session = this.manager.get(id);
|
|
2688
|
-
if (session
|
|
2689
|
-
this.queuedMessageNudges.delete(id);
|
|
2846
|
+
if (!session || session.exited || this.mailbox.participant(id)?.kind !== 'session')
|
|
2690
2847
|
return 'done';
|
|
2691
|
-
|
|
2692
|
-
const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
|
|
2693
|
-
// A scheduled body has no mailbox ids. It can clear on proof of consumption,
|
|
2694
|
-
// but a later inbox message can never authorise its submit key.
|
|
2695
|
-
if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
|
|
2696
|
-
!await this.clearScheduledBody(session))
|
|
2848
|
+
if (session.pendingSchedule() !== undefined && !await this.clearScheduledBody(session))
|
|
2697
2849
|
return 'wait';
|
|
2698
|
-
const
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2850
|
+
const waiting = confirmOnly ? [] : this.mailbox.inbox(id, { markRead: false })
|
|
2851
|
+
.filter(entry => entry.state === 'waiting').slice(0, NUDGE_LIST_CAP);
|
|
2852
|
+
if (waiting.length === 0 && !session.hasUnconfirmedMail)
|
|
2853
|
+
return 'done';
|
|
2854
|
+
const ids = waiting.map(entry => entry.id);
|
|
2855
|
+
const live = () => !session.exited && !session.programEnded && !session.isKilled &&
|
|
2856
|
+
this.manager.get(id) === session && this.mailbox.participant(id)?.kind === 'session';
|
|
2857
|
+
const record = (action, messageIds, queued) => this.audit.record('daemon', action, id, { messageIds, count: messageIds.length, ...(queued ? { queued: true } : {}) });
|
|
2858
|
+
let result;
|
|
2859
|
+
try {
|
|
2860
|
+
const batch = confirmOnly ? null : { line: buildNudge(waiting), ids };
|
|
2861
|
+
result = await session.deliverMailNudge(batch, () => this.now(), onWrite, (confirmed, queued) => {
|
|
2862
|
+
if (!live())
|
|
2863
|
+
return;
|
|
2864
|
+
this.mailbox.markNudged(confirmed);
|
|
2865
|
+
record('nudge', confirmed, queued);
|
|
2866
|
+
if (this.mailbox.inbox(id, { markRead: false }).some(entry => entry.state === 'waiting'))
|
|
2867
|
+
this.nudges.queue(id);
|
|
2707
2868
|
});
|
|
2708
2869
|
}
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
const pending = session.nudgePendingLine();
|
|
2717
|
-
if (pending !== null) {
|
|
2718
|
-
if (session.nudgePendingIds().length === 0)
|
|
2719
|
-
return 'wait';
|
|
2720
|
-
const covered = session.nudgePendingIds();
|
|
2721
|
-
const auditPending = (reason) => {
|
|
2722
|
-
if (session.nudgePendingAuditOnce())
|
|
2723
|
-
this.audit.record('daemon', 'nudge-pending', id, {
|
|
2724
|
-
messageIds: [...covered], count: covered.length, reason,
|
|
2725
|
-
});
|
|
2726
|
-
};
|
|
2727
|
-
const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2728
|
-
if (ids.length === 0) {
|
|
2729
|
-
auditPending('messages-changed');
|
|
2730
|
-
return 'done';
|
|
2731
|
-
}
|
|
2732
|
-
if (!covered.every((messageId) => unread.some((entry) => entry.id === messageId))) {
|
|
2733
|
-
auditPending('messages-changed');
|
|
2734
|
-
return 'wait';
|
|
2735
|
-
}
|
|
2736
|
-
if (!session.nudgePendingSafeToSubmit()) {
|
|
2737
|
-
if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
|
|
2738
|
-
this.audit.record('daemon', 'nudge-aborted', id, {
|
|
2739
|
-
messageIds: [...covered], count: covered.length, reason: 'person-input-since',
|
|
2740
|
-
...session.nudgePendingBodyMeta(),
|
|
2741
|
-
});
|
|
2742
|
-
}
|
|
2743
|
-
auditPending('person-input-since');
|
|
2744
|
-
return 'wait';
|
|
2745
|
-
}
|
|
2746
|
-
if (!session.nudgeReadyWithLine(pending)) {
|
|
2747
|
-
auditPending('line-not-seen');
|
|
2748
|
-
return 'wait';
|
|
2870
|
+
catch (failure) {
|
|
2871
|
+
const error = failure instanceof MailNudgeWriteError ? failure.cause : failure;
|
|
2872
|
+
if (failure instanceof MailNudgeWriteError && failure.typedChars > 0) {
|
|
2873
|
+
const reason = error instanceof SessionInputFailedError ? 'input-failed'
|
|
2874
|
+
: error instanceof SessionProgramEndedError ? 'session-ended' : 'write-failed';
|
|
2875
|
+
this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason,
|
|
2876
|
+
pendingBody: true, typedChars: failure.typedChars, submitSent: false });
|
|
2749
2877
|
}
|
|
2750
|
-
|
|
2751
|
-
const queuedInputVersion = session.nudgeQueuedInputVersion();
|
|
2752
|
-
const screenRevision = session.nudgeScreenRevision();
|
|
2753
|
-
const submitted = await session.submitPendingNudge(pending, (screen) => {
|
|
2754
|
-
const waitingIds = this.mailbox.inbox(id, { markRead: false })
|
|
2755
|
-
.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2756
|
-
return !session.exited && !session.getStalled() &&
|
|
2757
|
-
session.nudgePendingSafeToSubmit() &&
|
|
2758
|
-
session.nudgeInputVersion() === inputVersion &&
|
|
2759
|
-
session.nudgeQueuedInputVersion() === queuedInputVersion &&
|
|
2760
|
-
session.nudgeScreenRevision() === screenRevision &&
|
|
2761
|
-
session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
|
|
2762
|
-
covered.every((messageId) => this.mailbox.inbox(id, { markRead: false })
|
|
2763
|
-
.some((entry) => entry.id === messageId)) &&
|
|
2764
|
-
waitingIds.length === ids.length &&
|
|
2765
|
-
ids.every((messageId) => waitingIds.includes(messageId));
|
|
2766
|
-
});
|
|
2767
|
-
if (!submitted) {
|
|
2768
|
-
if (session.nudgePendingTouchRefusal()) {
|
|
2769
|
-
this.audit.record('daemon', 'nudge-aborted', id, {
|
|
2770
|
-
messageIds: [...covered], count: covered.length, reason: 'person-input-since',
|
|
2771
|
-
...session.nudgePendingBodyMeta(),
|
|
2772
|
-
});
|
|
2773
|
-
}
|
|
2774
|
-
auditPending('person-input-since');
|
|
2878
|
+
if (error instanceof SessionInputFailedError)
|
|
2775
2879
|
return 'wait';
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
waitingMessageIds: ids.filter((messageId) => !covered.includes(messageId)),
|
|
2780
|
-
staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
|
|
2781
|
-
return 'sent';
|
|
2782
|
-
}
|
|
2783
|
-
const queued = this.queuedMessageNudges?.get(id);
|
|
2784
|
-
if (queued !== undefined) {
|
|
2785
|
-
const state = session.nudgeState(this.now());
|
|
2786
|
-
if (this.now() - queued.at >= QUEUED_NUDGE_MAX_MS || (state.ready && !state.queued)) {
|
|
2787
|
-
this.queuedMessageNudges.delete(id);
|
|
2788
|
-
}
|
|
2789
|
-
else {
|
|
2790
|
-
const waitingIds = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2791
|
-
const newlyHeld = waitingIds.filter((messageId) => !queued.heldIds.has(messageId));
|
|
2792
|
-
if (newlyHeld.length > 0) {
|
|
2793
|
-
for (const messageId of newlyHeld)
|
|
2794
|
-
queued.heldIds.add(messageId);
|
|
2795
|
-
this.audit.record('daemon', 'nudge-held', id, { reason: 'queued-nudge-pending',
|
|
2796
|
-
messageIds: newlyHeld, count: newlyHeld.length, queuedMessageIds: queued.messageIds });
|
|
2797
|
-
}
|
|
2798
|
-
return waitingIds.length > 0 ? 'wait' : 'done';
|
|
2799
|
-
}
|
|
2880
|
+
if (error instanceof SessionProgramEndedError || session.exited)
|
|
2881
|
+
return 'done';
|
|
2882
|
+
throw error;
|
|
2800
2883
|
}
|
|
2801
|
-
|
|
2802
|
-
// nudged but is still unread (the agent did not read its inbox) is listed
|
|
2803
|
-
// in the line again when a later message arrives after any queued hold ends.
|
|
2804
|
-
const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2805
|
-
if (ids.length === 0)
|
|
2884
|
+
if (!live())
|
|
2806
2885
|
return 'done';
|
|
2807
|
-
if (
|
|
2808
|
-
|
|
2809
|
-
const line = buildNudge(unread);
|
|
2810
|
-
const readVersion = this.inboxReadVersions?.get(id) ?? 0;
|
|
2811
|
-
const result = await this.deliverLine(session, line, undefined, ids, () => {
|
|
2812
|
-
const current = this.mailbox.inbox(id, { markRead: false });
|
|
2813
|
-
return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
|
|
2814
|
-
});
|
|
2815
|
-
if (result.outcome === 'aborted') {
|
|
2816
|
-
this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason,
|
|
2817
|
-
...session.nudgePendingBodyMeta() });
|
|
2818
|
-
}
|
|
2819
|
-
if (result.outcome !== 'sent' && result.outcome !== 'queued')
|
|
2886
|
+
if (result.outcome === 'unconfirmed') {
|
|
2887
|
+
record('nudge-unconfirmed', result.ids, result.queued);
|
|
2820
2888
|
return 'wait';
|
|
2821
|
-
this.mailbox.markNudged(ids);
|
|
2822
|
-
if (result.outcome === 'queued' && (this.inboxReadVersions?.get(id) ?? 0) === readVersion) {
|
|
2823
|
-
this.queuedMessageNudges.set(id, { at: this.now(), messageIds: ids, heldIds: new Set() });
|
|
2824
2889
|
}
|
|
2825
|
-
|
|
2826
|
-
...(result.outcome === 'queued' ? { queued: true } : {}) });
|
|
2827
|
-
return 'sent';
|
|
2890
|
+
return result.outcome;
|
|
2828
2891
|
}
|
|
2829
2892
|
async clearScheduledBody(session) {
|
|
2830
2893
|
const name = session.pendingSchedule();
|
|
@@ -2849,11 +2912,13 @@ export class Daemon {
|
|
|
2849
2912
|
}
|
|
2850
2913
|
this.pendingSchedules.delete(schedule.name);
|
|
2851
2914
|
}
|
|
2852
|
-
if (session.
|
|
2915
|
+
if (session.hasUnconfirmedMail)
|
|
2916
|
+
await this.deliverNudge(session.id, undefined, true);
|
|
2917
|
+
if (session.hasUnconfirmedMail || (session.nudgePendingLine() !== null && !await this.clearScheduledBody(session))) {
|
|
2853
2918
|
return { sessionId: id, outcome: 'skipped', reason: 'pending' };
|
|
2854
2919
|
}
|
|
2855
2920
|
try {
|
|
2856
|
-
const result = await this.deliverLine(session, schedule.message, schedule.whenBusy,
|
|
2921
|
+
const result = await this.deliverLine(session, schedule.message, schedule.whenBusy, () => current() && this.mailbox.sessionIdByName(schedule.session) === id, schedule.name);
|
|
2857
2922
|
// Ordinary input can also arrive while the scheduled write waits in the input queue.
|
|
2858
2923
|
if (result.outcome === 'skipped' && session.recentInput)
|
|
2859
2924
|
result.reason = 'recent-input';
|
|
@@ -2864,7 +2929,7 @@ export class Daemon {
|
|
|
2864
2929
|
this.pendingSchedules.set(schedule.name, session.id);
|
|
2865
2930
|
}
|
|
2866
2931
|
}
|
|
2867
|
-
async deliverLine(session, line, whenBusy,
|
|
2932
|
+
async deliverLine(session, line, whenBusy, currentDelivery, schedule) {
|
|
2868
2933
|
if (!session.hasPainted())
|
|
2869
2934
|
return { outcome: 'skipped', reason: 'unknown' };
|
|
2870
2935
|
const inputVersion = session.nudgeInputVersion();
|
|
@@ -2910,7 +2975,7 @@ export class Daemon {
|
|
|
2910
2975
|
return false;
|
|
2911
2976
|
}
|
|
2912
2977
|
if (!currentDelivery()) {
|
|
2913
|
-
failedCheck =
|
|
2978
|
+
failedCheck = 'schedule-changed';
|
|
2914
2979
|
return false;
|
|
2915
2980
|
}
|
|
2916
2981
|
if (phase === 'before' ? !current?.ready || current.queued !== queued : !session.nudgeReadyWithLine(line, queued, whenBusy)) {
|
|
@@ -2920,23 +2985,15 @@ export class Daemon {
|
|
|
2920
2985
|
return true;
|
|
2921
2986
|
};
|
|
2922
2987
|
try {
|
|
2923
|
-
const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready,
|
|
2988
|
+
const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready, () => failedCheck, schedule, queued);
|
|
2924
2989
|
if (result === 'wait')
|
|
2925
|
-
return { outcome: 'skipped', reason: session.nudgePendingLine() !== null ? 'pending' : failedCheck };
|
|
2990
|
+
return { outcome: 'skipped', reason: session.hasUnconfirmedMail || session.nudgePendingLine() !== null ? 'pending' : failedCheck };
|
|
2926
2991
|
if (result.startsWith('aborted-')) {
|
|
2927
2992
|
const reason = result.slice('aborted-'.length);
|
|
2928
2993
|
return { outcome: 'aborted', reason };
|
|
2929
2994
|
}
|
|
2930
2995
|
}
|
|
2931
2996
|
catch (error) {
|
|
2932
|
-
const pendingBody = session.nudgePendingBodyMeta();
|
|
2933
|
-
if (ids.length > 0 && pendingBody.pendingBody) {
|
|
2934
|
-
const reason = error instanceof SessionInputFailedError ? 'input-failed'
|
|
2935
|
-
: error instanceof SessionProgramEndedError ? 'session-ended' : 'write-failed';
|
|
2936
|
-
this.audit.record('daemon', 'nudge-aborted', session.id, {
|
|
2937
|
-
messageIds: ids, count: ids.length, reason, ...pendingBody,
|
|
2938
|
-
});
|
|
2939
|
-
}
|
|
2940
2997
|
if (error instanceof SessionInputFailedError)
|
|
2941
2998
|
return { outcome: 'skipped', reason: 'input-failed' };
|
|
2942
2999
|
if (error instanceof SessionProgramEndedError)
|
|
@@ -2945,10 +3002,10 @@ export class Daemon {
|
|
|
2945
3002
|
}
|
|
2946
3003
|
return { outcome: queued ? 'queued' : 'sent' };
|
|
2947
3004
|
}
|
|
2948
|
-
|
|
3005
|
+
reserveMailboxName(session, profileName) {
|
|
2949
3006
|
const label = profileName ?? session.label;
|
|
2950
|
-
const
|
|
2951
|
-
let name = !
|
|
3007
|
+
const granted = profileName === undefined && this.launchProfiles.sessionLaunch?.includes(label);
|
|
3008
|
+
let name = !granted && NAME_PATTERN.test(label) &&
|
|
2952
3009
|
(!/^s[0-9]+$/.test(label) || label === session.id) &&
|
|
2953
3010
|
!this.mailbox.nameTaken(label) ? label : session.id;
|
|
2954
3011
|
if (profileName !== undefined && name === session.id && NAME_PATTERN.test(label) &&
|
|
@@ -2961,6 +3018,9 @@ export class Daemon {
|
|
|
2961
3018
|
}
|
|
2962
3019
|
}
|
|
2963
3020
|
}
|
|
3021
|
+
return { name, release: this.mailbox.reserveSessionName(name, session.id) };
|
|
3022
|
+
}
|
|
3023
|
+
registerMailboxSession(session, name) {
|
|
2964
3024
|
this.mailbox.register({ kind: 'session', id: session.id, name, role: session.role });
|
|
2965
3025
|
if (NAME_PATTERN.test(session.label))
|
|
2966
3026
|
session.label = name;
|
|
@@ -2969,22 +3029,24 @@ export class Daemon {
|
|
|
2969
3029
|
this.endMailboxParticipant(session.id);
|
|
2970
3030
|
}
|
|
2971
3031
|
isReservedClaimName(name) {
|
|
2972
|
-
return (this.
|
|
3032
|
+
return (this.reload?.state.messaging.allow ?? []).some((rule) => rule !== 'parent-child' && rule.members.includes(name));
|
|
2973
3033
|
}
|
|
2974
3034
|
async handleMessages(req, res, url, segments, actor) {
|
|
2975
|
-
if (this.options.messaging?.enabled !== true) {
|
|
2976
|
-
json(res, 403, { error: 'Messaging is off.' });
|
|
2977
|
-
return;
|
|
2978
|
-
}
|
|
2979
3035
|
this.lapseIdleClaims();
|
|
2980
3036
|
const route = segments[1];
|
|
2981
3037
|
const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
|
|
2982
3038
|
const { id: claimId, refused } = this.presentedClaim(req);
|
|
2983
|
-
if (refused
|
|
3039
|
+
if (refused) {
|
|
2984
3040
|
json(res, 403, { error: 'Messaging claim was not recognised.', ...invalidClaim });
|
|
2985
3041
|
return;
|
|
2986
3042
|
}
|
|
2987
3043
|
const caller = this.callerContext.getStore() ?? claimId;
|
|
3044
|
+
const reading = req.method === 'GET' && ['inbox', 'outbox', 'wait', 'log'].includes(route ?? '');
|
|
3045
|
+
const releasing = req.method === 'DELETE' && route === 'claims';
|
|
3046
|
+
if (!this.reload?.state.messaging.enabled && !(caller !== undefined && (reading || releasing))) {
|
|
3047
|
+
json(res, 403, { error: 'Messaging is off.' });
|
|
3048
|
+
return;
|
|
3049
|
+
}
|
|
2988
3050
|
if (creatingClaim) {
|
|
2989
3051
|
// Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
|
|
2990
3052
|
if (this.callerContext.getStore() !== undefined) {
|
|
@@ -3008,6 +3070,10 @@ export class Daemon {
|
|
|
3008
3070
|
return;
|
|
3009
3071
|
}
|
|
3010
3072
|
const body = await readBody(req);
|
|
3073
|
+
if (!this.reload?.state.messaging.enabled) {
|
|
3074
|
+
json(res, 403, { error: 'Messaging is off.' });
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
3011
3077
|
const name = body['name'];
|
|
3012
3078
|
const replace = body['replace'] === true;
|
|
3013
3079
|
if (typeof name !== 'string') {
|
|
@@ -3061,8 +3127,7 @@ export class Daemon {
|
|
|
3061
3127
|
}
|
|
3062
3128
|
if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
|
|
3063
3129
|
if (claimId === undefined || claimId !== segments[2]) {
|
|
3064
|
-
json(res, 403, { error: 'The matching claim is required.'
|
|
3065
|
-
...(claimId === undefined ? {} : { hint: CLAIM_RECOVERY_HINT }) });
|
|
3130
|
+
json(res, 403, { error: 'The matching claim is required.' });
|
|
3066
3131
|
return;
|
|
3067
3132
|
}
|
|
3068
3133
|
const name = this.mailbox.participant(claimId)?.name;
|
|
@@ -3084,6 +3149,13 @@ export class Daemon {
|
|
|
3084
3149
|
}
|
|
3085
3150
|
if (req.method === 'POST' && route === undefined) {
|
|
3086
3151
|
const body = await readBody(req);
|
|
3152
|
+
if (claimId === caller) {
|
|
3153
|
+
this.lapseIdleClaims();
|
|
3154
|
+
if (this.presentedClaim(req).refused) {
|
|
3155
|
+
json(res, 403, { error: 'Messaging claim was not recognised.', ...invalidClaim });
|
|
3156
|
+
return;
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3087
3159
|
const result = this.mailbox.send(caller, body['to'], body['text']);
|
|
3088
3160
|
json(res, 201, result);
|
|
3089
3161
|
return;
|
|
@@ -3195,7 +3267,10 @@ export class Daemon {
|
|
|
3195
3267
|
// Behind the token, unlike /health: names of credential-shaped
|
|
3196
3268
|
// variables are not for anyone who can reach the port.
|
|
3197
3269
|
if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
|
|
3198
|
-
|
|
3270
|
+
const report = this.environmentReport();
|
|
3271
|
+
json(res, 200, url.searchParams.get('include') === 'config' ? {
|
|
3272
|
+
...report, configReload: this.reload?.status, messagingEnabled: this.reload?.state.messaging.enabled === true,
|
|
3273
|
+
} : report);
|
|
3199
3274
|
return;
|
|
3200
3275
|
}
|
|
3201
3276
|
if (req.method === 'POST' && segments[0] === 'dashboard' && segments[1] === 'open' && segments.length === 2) {
|
|
@@ -3209,10 +3284,9 @@ export class Daemon {
|
|
|
3209
3284
|
if (url.pathname === '/launcher/previous' && req.method === 'GET') {
|
|
3210
3285
|
if (!this.grantedLauncher(req, res))
|
|
3211
3286
|
return;
|
|
3212
|
-
const file = path.join(this.options.home, 'previous-sessions.json');
|
|
3213
3287
|
try {
|
|
3214
3288
|
// Older version 1 records used the generated session id as an explicit name.
|
|
3215
|
-
const record = JSON.parse(
|
|
3289
|
+
const record = JSON.parse(readHomeRecord(this.configPermissions, 'previous-sessions.json'), (key, value) => key === 'name' && typeof value === 'string' && /^s[0-9]+$/.test(value) ? null : value);
|
|
3216
3290
|
if (!this.verifiedRestartSnapshot(record)) {
|
|
3217
3291
|
json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
|
|
3218
3292
|
return;
|
|
@@ -3313,8 +3387,7 @@ export class Daemon {
|
|
|
3313
3387
|
return;
|
|
3314
3388
|
}
|
|
3315
3389
|
const hide = body['hideReasoning'] === true;
|
|
3316
|
-
|
|
3317
|
-
if (hide && signature === null)
|
|
3390
|
+
if (hide && this.readerFor(session, res) === null)
|
|
3318
3391
|
return;
|
|
3319
3392
|
// Absent means the default; present and not a number is a mistake to
|
|
3320
3393
|
// report, not to paper over with the default.
|
|
@@ -3346,7 +3419,7 @@ export class Daemon {
|
|
|
3346
3419
|
});
|
|
3347
3420
|
return;
|
|
3348
3421
|
}
|
|
3349
|
-
const browser = await findBrowser(this.
|
|
3422
|
+
const browser = await findBrowser(this.viewer.browserPath, this.logger);
|
|
3350
3423
|
if (browser === null) {
|
|
3351
3424
|
// No silent fallback to re-rendering the cells ourselves: that would
|
|
3352
3425
|
// return a picture of what the daemon thinks, labelled as what the
|
|
@@ -3357,10 +3430,13 @@ export class Daemon {
|
|
|
3357
3430
|
});
|
|
3358
3431
|
return;
|
|
3359
3432
|
}
|
|
3360
|
-
const capturedScreen = await session.captureViewerScreen(
|
|
3433
|
+
const capturedScreen = await session.captureViewerScreen(hide ? REASONING_CONTEXT_LINES : 0, VIEWER_SNAPSHOT_SCROLLBACK_LINES);
|
|
3361
3434
|
let redactedRows;
|
|
3362
3435
|
let expectedRows;
|
|
3363
|
-
if (
|
|
3436
|
+
if (hide) {
|
|
3437
|
+
const signature = this.readerFor(session, res);
|
|
3438
|
+
if (signature === null)
|
|
3439
|
+
return;
|
|
3364
3440
|
const view = capturedScreen.view;
|
|
3365
3441
|
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3366
3442
|
if (filtered === null) {
|
|
@@ -3396,7 +3472,7 @@ export class Daemon {
|
|
|
3396
3472
|
width,
|
|
3397
3473
|
height,
|
|
3398
3474
|
timeoutMs,
|
|
3399
|
-
profileRoot: captureProfileRoot(this.
|
|
3475
|
+
profileRoot: captureProfileRoot(this.configPermissions.homePath),
|
|
3400
3476
|
...(redactedRows === undefined ? {} : { hiddenRows: [...redactedRows.keys()] }),
|
|
3401
3477
|
logger: this.logger,
|
|
3402
3478
|
});
|
|
@@ -3458,21 +3534,19 @@ export class Daemon {
|
|
|
3458
3534
|
}
|
|
3459
3535
|
// Fails closed: without a signature to read the screen by, nothing
|
|
3460
3536
|
// is returned, never the screen unfiltered.
|
|
3461
|
-
|
|
3462
|
-
if (hide && signature === null)
|
|
3537
|
+
if (hide && this.readerFor(session, res) === null)
|
|
3463
3538
|
return;
|
|
3464
3539
|
const read = async () => {
|
|
3465
3540
|
const snapshot = await session.snapshot();
|
|
3466
|
-
if (
|
|
3541
|
+
if (!hide)
|
|
3467
3542
|
return count === undefined ? { ...snapshot } : { ...snapshot, lastLines: await session.lastLines(count) };
|
|
3468
3543
|
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3544
|
+
const tailSource = count === undefined ? undefined : await session.styledTail(count, REASONING_CONTEXT_LINES);
|
|
3545
|
+
const signature = this.readerFor(session, res);
|
|
3546
|
+
if (signature === null)
|
|
3547
|
+
return null;
|
|
3469
3548
|
const screen = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3470
|
-
|
|
3471
|
-
let tailSource;
|
|
3472
|
-
if (count !== undefined) {
|
|
3473
|
-
tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
|
|
3474
|
-
tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
3475
|
-
}
|
|
3549
|
+
const tail = tailSource === undefined ? undefined : hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
3476
3550
|
if (screen === null || tail === null) {
|
|
3477
3551
|
json(res, 400, { error: overBudgetMessage(signature) });
|
|
3478
3552
|
return null;
|
|
@@ -3606,10 +3680,10 @@ export class Daemon {
|
|
|
3606
3680
|
return;
|
|
3607
3681
|
}
|
|
3608
3682
|
if (req.method === 'GET' && action === 'result') {
|
|
3683
|
+
const { lines } = await session.styledTail(RESULT_LINES);
|
|
3609
3684
|
const signature = this.readerFor(session, res);
|
|
3610
3685
|
if (signature === null)
|
|
3611
3686
|
return;
|
|
3612
|
-
const { lines } = await session.styledTail(RESULT_LINES);
|
|
3613
3687
|
json(res, 200, {
|
|
3614
3688
|
id: session.id,
|
|
3615
3689
|
agent: signature.name,
|
|
@@ -3683,7 +3757,7 @@ export class Daemon {
|
|
|
3683
3757
|
const bytes = submitMode === undefined ? data.length : written.inputBytes ?? 0;
|
|
3684
3758
|
if (report !== null) {
|
|
3685
3759
|
this.audit.record(actor, 'report', id, { kind: report, chars: bytes,
|
|
3686
|
-
...(this.audit
|
|
3760
|
+
...(this.reload?.state.config.audit?.captureContent ? { data } : {}) });
|
|
3687
3761
|
}
|
|
3688
3762
|
else {
|
|
3689
3763
|
this.audit.record(actor, 'input', id, { chars: bytes,
|
|
@@ -3726,8 +3800,12 @@ export class Daemon {
|
|
|
3726
3800
|
}
|
|
3727
3801
|
// Same exit race and failed input pipe as the input endpoint above:
|
|
3728
3802
|
// 409, not 500.
|
|
3803
|
+
let warning;
|
|
3729
3804
|
try {
|
|
3730
|
-
|
|
3805
|
+
if (key.trim().toLowerCase() === 'enter')
|
|
3806
|
+
warning = await session.writeEnter();
|
|
3807
|
+
else
|
|
3808
|
+
await session.write(bytes);
|
|
3731
3809
|
}
|
|
3732
3810
|
catch (error) {
|
|
3733
3811
|
json(res, 409, {
|
|
@@ -3739,7 +3817,7 @@ export class Daemon {
|
|
|
3739
3817
|
}
|
|
3740
3818
|
this.audit.record(actor, 'key', id, { key });
|
|
3741
3819
|
this.broadcastControl(id, { type: 'input-source', source: 'agent' });
|
|
3742
|
-
json(res, 200, { ok: true, key });
|
|
3820
|
+
json(res, 200, { ok: true, key, ...(warning && { warning }) });
|
|
3743
3821
|
return;
|
|
3744
3822
|
}
|
|
3745
3823
|
if (req.method === 'GET' && action === 'wait') {
|
|
@@ -3778,7 +3856,6 @@ export class Daemon {
|
|
|
3778
3856
|
if (stalled)
|
|
3779
3857
|
condition.stalled = true;
|
|
3780
3858
|
const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
|
|
3781
|
-
const pendingReader = signatureForSession(session);
|
|
3782
3859
|
let matchView;
|
|
3783
3860
|
const timeoutParam = url.searchParams.get('timeout');
|
|
3784
3861
|
const debounceParam = url.searchParams.get('debounce');
|
|
@@ -3806,12 +3883,18 @@ export class Daemon {
|
|
|
3806
3883
|
? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
|
|
3807
3884
|
: {}),
|
|
3808
3885
|
...(filteredMatch ? { screenForMatch: () => {
|
|
3809
|
-
|
|
3886
|
+
const current = signatureForSession(session);
|
|
3887
|
+
if (!current)
|
|
3888
|
+
throw new WaitConditionError('The reading signature for this session is unavailable.');
|
|
3889
|
+
matchView = filteredWaitScreen(session, current, condition.prompt === true);
|
|
3810
3890
|
return matchView.screen;
|
|
3811
3891
|
}, stylesForMatch: () => matchView?.styled } : {}),
|
|
3812
|
-
...(
|
|
3892
|
+
...(moduleFor(session.agent)?.readingRules?.pendingComposer === true ? {
|
|
3813
3893
|
composerPending: () => {
|
|
3814
|
-
const
|
|
3894
|
+
const current = signatureForSession(session);
|
|
3895
|
+
if (!current)
|
|
3896
|
+
return false;
|
|
3897
|
+
const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, current);
|
|
3815
3898
|
return !result.found && result.reason === 'prompt-typed';
|
|
3816
3899
|
},
|
|
3817
3900
|
} : {}),
|
|
@@ -3843,7 +3926,10 @@ export class Daemon {
|
|
|
3843
3926
|
// The screen as it stands now, a moment after the wait resolved,
|
|
3844
3927
|
// with the reasoning left out.
|
|
3845
3928
|
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3846
|
-
const
|
|
3929
|
+
const current = this.readerFor(session, res);
|
|
3930
|
+
if (!current)
|
|
3931
|
+
return;
|
|
3932
|
+
const filtered = hideReasoning(view.lines, current, view.firstVisible);
|
|
3847
3933
|
if (filtered === null) {
|
|
3848
3934
|
json(res, 400, { error: overBudgetMessage(reader) });
|
|
3849
3935
|
return;
|
|
@@ -3896,10 +3982,10 @@ export class Daemon {
|
|
|
3896
3982
|
json(res, 200, { id: session.id, pattern, ...result });
|
|
3897
3983
|
return;
|
|
3898
3984
|
}
|
|
3985
|
+
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3899
3986
|
const signature = this.readerFor(session, res);
|
|
3900
3987
|
if (signature === null)
|
|
3901
3988
|
return;
|
|
3902
|
-
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3903
3989
|
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3904
3990
|
if (filtered === null) {
|
|
3905
3991
|
json(res, 400, { error: overBudgetMessage(signature) });
|
|
@@ -3981,7 +4067,7 @@ export class Daemon {
|
|
|
3981
4067
|
}
|
|
3982
4068
|
if (error instanceof MailboxError) {
|
|
3983
4069
|
const status = error.code === 'unknown-name' ? 404 :
|
|
3984
|
-
error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
|
|
4070
|
+
error.code === 'not-allowed' || error.code === 'unknown-sender' || error.code === 'messaging-disabled' ? 403 :
|
|
3985
4071
|
error.code === 'duplicate-name' || error.code === 'mailbox-full' ? 409 : 400;
|
|
3986
4072
|
const messages = {
|
|
3987
4073
|
'invalid-name': 'A valid participant name is required.',
|
|
@@ -4126,13 +4212,17 @@ export class Daemon {
|
|
|
4126
4212
|
// its output worker has connected, a few hundred milliseconds after the
|
|
4127
4213
|
// spawn returns, and reports pid 0 until then. The start contract is what
|
|
4128
4214
|
// it always was: a started session has a program, and its pid is real.
|
|
4129
|
-
const
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4215
|
+
const mailboxName = this.reserveMailboxName(session);
|
|
4216
|
+
try {
|
|
4217
|
+
const started = await this.programStarted(session, options, res, 'session start failed', mailboxName.release);
|
|
4218
|
+
if (!started)
|
|
4219
|
+
return;
|
|
4220
|
+
session = started;
|
|
4221
|
+
this.registerMailboxSession(session, mailboxName.name);
|
|
4222
|
+
}
|
|
4223
|
+
finally {
|
|
4224
|
+
mailboxName.release();
|
|
4225
|
+
}
|
|
4136
4226
|
this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
|
|
4137
4227
|
session.onExit(() => {
|
|
4138
4228
|
this.clearPromptGraceCheck(session.id);
|
|
@@ -4177,7 +4267,7 @@ export class Daemon {
|
|
|
4177
4267
|
// A connected dashboard is the human's window. Do not mint a viewer grant
|
|
4178
4268
|
// that would sit unused, and do not open a second window.
|
|
4179
4269
|
const dashboardWatching = wantsViewer && this.hasLiveDashboardSocket();
|
|
4180
|
-
const mode = this.
|
|
4270
|
+
const mode = this.viewer.launchMode ?? 'no-window';
|
|
4181
4271
|
let viewerUrl = wantsViewer && !dashboardWatching && mode !== 'dashboard'
|
|
4182
4272
|
? this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id))
|
|
4183
4273
|
: '';
|
|
@@ -4203,13 +4293,13 @@ export class Daemon {
|
|
|
4203
4293
|
}
|
|
4204
4294
|
else {
|
|
4205
4295
|
try {
|
|
4206
|
-
opened = await launch(viewerUrl, this.
|
|
4296
|
+
opened = await launch(viewerUrl, this.configPermissions.homePath, this.viewer, this.logger);
|
|
4207
4297
|
}
|
|
4208
4298
|
catch (error) {
|
|
4209
4299
|
this.logger.warn('viewer launch failed', { id: session.id, error: String(error) });
|
|
4210
4300
|
opened = {
|
|
4211
4301
|
launched: false,
|
|
4212
|
-
mode
|
|
4302
|
+
mode,
|
|
4213
4303
|
reason: String(error),
|
|
4214
4304
|
};
|
|
4215
4305
|
}
|
|
@@ -4536,7 +4626,6 @@ export class Daemon {
|
|
|
4536
4626
|
* someone happens to snapshot the session.
|
|
4537
4627
|
*/
|
|
4538
4628
|
async scanForPromptStalls() {
|
|
4539
|
-
const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
|
|
4540
4629
|
const seen = new Set();
|
|
4541
4630
|
const scheduled = new Set(this.schedules.read().filter(s => s.enabled).map(s => this.mailbox.sessionIdByName(s.session)));
|
|
4542
4631
|
for (const summary of this.manager.list()) {
|
|
@@ -4561,133 +4650,7 @@ export class Daemon {
|
|
|
4561
4650
|
});
|
|
4562
4651
|
continue;
|
|
4563
4652
|
}
|
|
4564
|
-
|
|
4565
|
-
if (detected === null) {
|
|
4566
|
-
// A snapshot may land midway through a repaint. Keep the prompt and
|
|
4567
|
-
// its clock for a short wall-clock grace period, independent of the
|
|
4568
|
-
// scan interval; a lasting disappearance still clears it.
|
|
4569
|
-
if (previous !== undefined) {
|
|
4570
|
-
if (previous.missingSince === null)
|
|
4571
|
-
previous.missingSince = this.now();
|
|
4572
|
-
const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - this.now();
|
|
4573
|
-
if (remaining > 0) {
|
|
4574
|
-
this.schedulePromptGraceCheck(session.id, remaining);
|
|
4575
|
-
continue;
|
|
4576
|
-
}
|
|
4577
|
-
}
|
|
4578
|
-
this.clearPromptGraceCheck(session.id);
|
|
4579
|
-
if (previous?.alerted === true) {
|
|
4580
|
-
this.emitEvent({
|
|
4581
|
-
type: 'prompt-clear',
|
|
4582
|
-
session: session.id,
|
|
4583
|
-
label: summary.label ?? null,
|
|
4584
|
-
});
|
|
4585
|
-
// Viewers were told the prompt was waiting; they must be told it is
|
|
4586
|
-
// over, or a badge raised by the stall alert never comes down.
|
|
4587
|
-
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4588
|
-
}
|
|
4589
|
-
if (previous !== undefined) {
|
|
4590
|
-
this.promptStates.delete(session.id);
|
|
4591
|
-
this.updateFeedSession(session.id);
|
|
4592
|
-
}
|
|
4593
|
-
continue;
|
|
4594
|
-
}
|
|
4595
|
-
// A real sighting cancels a pending repaint gap: the prompt is still there.
|
|
4596
|
-
// Refresh the stored prompt with it, too: the signature deliberately
|
|
4597
|
-
// normalises Grok's radio markers so that MOVING the selection does not
|
|
4598
|
-
// restart the stall clock, which means the same signature can describe a
|
|
4599
|
-
// visibly different set of options. Storing only on signature change
|
|
4600
|
-
// would serve a stale selection to `terminal_list` and to a viewer
|
|
4601
|
-
// joining late.
|
|
4602
|
-
const promptChanged = previous === undefined ||
|
|
4603
|
-
previous.prompt.question !== detected.question ||
|
|
4604
|
-
previous.prompt.selectedOption !== detected.selectedOption ||
|
|
4605
|
-
previous.prompt.options.length !== detected.options.length ||
|
|
4606
|
-
previous.prompt.options.some((option, index) => option !== detected.options[index]);
|
|
4607
|
-
const inputVersion = session.promptInputVersion();
|
|
4608
|
-
// Input alone does not mean this prompt was answered: a key may start
|
|
4609
|
-
// a repaint while the same decision remains on screen. A missed prompt
|
|
4610
|
-
// after input is evidence of a transition only when a prompt appears
|
|
4611
|
-
// again; the normal grace check still handles a lasting disappearance.
|
|
4612
|
-
const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
|
|
4613
|
-
previous.missingSince !== null;
|
|
4614
|
-
if (previous !== undefined) {
|
|
4615
|
-
this.clearPromptGraceCheck(session.id);
|
|
4616
|
-
previous.missingSince = null;
|
|
4617
|
-
previous.prompt = detected;
|
|
4618
|
-
}
|
|
4619
|
-
// A dialog can redraw at another width, or alongside changing sidebar
|
|
4620
|
-
// text, without changing its question or choices. Its rendered signature
|
|
4621
|
-
// then changes although the person still faces the same decision.
|
|
4622
|
-
// A stable signature also covers focus markers moving among options.
|
|
4623
|
-
const sameContent = previous !== undefined && !promptChanged;
|
|
4624
|
-
if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
|
|
4625
|
-
// A new (or changed) prompt starts its stall clock; it has not
|
|
4626
|
-
// alerted yet, so a prompt answered promptly stays silent.
|
|
4627
|
-
if (previous?.alerted === true) {
|
|
4628
|
-
// The previous prompt was announced and has now been replaced
|
|
4629
|
-
// rather than cleared. Retract it, otherwise a viewer badges the
|
|
4630
|
-
// old question while a different one is on screen.
|
|
4631
|
-
//
|
|
4632
|
-
// BOTH channels, symmetrically with the null path above. Retracting
|
|
4633
|
-
// to viewers only would leave `/events` emitting stall(Q1) then
|
|
4634
|
-
// stall(Q2) with no clear between them, which reads as two concurrent
|
|
4635
|
-
// holds or an unresolved first one. Nothing in this repository
|
|
4636
|
-
// subscribes to it, but the socket is a real API and an asymmetric
|
|
4637
|
-
// one is a trap for the first thing that consumes it.
|
|
4638
|
-
this.emitEvent({
|
|
4639
|
-
type: 'prompt-clear',
|
|
4640
|
-
session: session.id,
|
|
4641
|
-
label: summary.label ?? null,
|
|
4642
|
-
});
|
|
4643
|
-
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4644
|
-
}
|
|
4645
|
-
this.promptStates.set(session.id, {
|
|
4646
|
-
signature: detected.signature,
|
|
4647
|
-
inputVersion,
|
|
4648
|
-
since: this.now(),
|
|
4649
|
-
alerted: false,
|
|
4650
|
-
prompt: detected,
|
|
4651
|
-
missingSince: null,
|
|
4652
|
-
});
|
|
4653
|
-
this.updateFeedSession(session.id, previous !== undefined);
|
|
4654
|
-
continue;
|
|
4655
|
-
}
|
|
4656
|
-
previous.signature = detected.signature;
|
|
4657
|
-
if (promptChanged)
|
|
4658
|
-
this.updateFeedSession(session.id);
|
|
4659
|
-
if (!previous.alerted && this.now() - previous.since >= stallMs) {
|
|
4660
|
-
previous.alerted = true;
|
|
4661
|
-
this.updateFeedSession(session.id);
|
|
4662
|
-
const waitingMs = this.now() - previous.since;
|
|
4663
|
-
this.audit.record('daemon', 'prompt-stall', session.id);
|
|
4664
|
-
this.logger.warn('session waiting on a prompt', {
|
|
4665
|
-
id: session.id,
|
|
4666
|
-
waitingMs,
|
|
4667
|
-
options: detected.options.length,
|
|
4668
|
-
});
|
|
4669
|
-
this.emitEvent({
|
|
4670
|
-
type: 'prompt-stall',
|
|
4671
|
-
session: session.id,
|
|
4672
|
-
label: summary.label ?? null,
|
|
4673
|
-
waitingMs,
|
|
4674
|
-
question: detected.question,
|
|
4675
|
-
options: detected.options,
|
|
4676
|
-
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4677
|
-
});
|
|
4678
|
-
// The session's own viewers get the same signal, so an open viewer
|
|
4679
|
-
// tab can badge itself without subscribing to the daemon stream.
|
|
4680
|
-
this.broadcastControl(session.id, {
|
|
4681
|
-
type: 'prompt-stall',
|
|
4682
|
-
waitingMs,
|
|
4683
|
-
question: detected.question,
|
|
4684
|
-
// The options travel to viewers as well as to /events, so the badge
|
|
4685
|
-
// can say what the choices are, not only THAT something is being
|
|
4686
|
-
// asked.
|
|
4687
|
-
options: detected.options,
|
|
4688
|
-
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4689
|
-
});
|
|
4690
|
-
}
|
|
4653
|
+
this.updatePromptState(session, detected);
|
|
4691
4654
|
}
|
|
4692
4655
|
// Sessions that exited or were reaped take their prompt state with them.
|
|
4693
4656
|
for (const id of [...this.promptStates.keys()]) {
|
|
@@ -4699,6 +4662,137 @@ export class Daemon {
|
|
|
4699
4662
|
}
|
|
4700
4663
|
await this.nudges.tick();
|
|
4701
4664
|
}
|
|
4665
|
+
updatePromptState(session, detected, ruleRemoved = false) {
|
|
4666
|
+
const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
|
|
4667
|
+
const previous = this.promptStates.get(session.id);
|
|
4668
|
+
if (detected === null) {
|
|
4669
|
+
// A snapshot may land midway through a repaint. Keep the prompt and
|
|
4670
|
+
// its clock for a short wall-clock grace period, independent of the
|
|
4671
|
+
// scan interval; a lasting disappearance still clears it.
|
|
4672
|
+
if (previous !== undefined && !ruleRemoved) {
|
|
4673
|
+
if (previous.missingSince === null)
|
|
4674
|
+
previous.missingSince = this.now();
|
|
4675
|
+
const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - this.now();
|
|
4676
|
+
if (remaining > 0) {
|
|
4677
|
+
this.schedulePromptGraceCheck(session.id, remaining);
|
|
4678
|
+
return;
|
|
4679
|
+
}
|
|
4680
|
+
}
|
|
4681
|
+
this.clearPromptGraceCheck(session.id);
|
|
4682
|
+
if (previous?.alerted === true) {
|
|
4683
|
+
this.emitEvent({
|
|
4684
|
+
type: 'prompt-clear',
|
|
4685
|
+
session: session.id,
|
|
4686
|
+
label: session.label ?? null,
|
|
4687
|
+
});
|
|
4688
|
+
// Viewers were told the prompt was waiting; they must be told it is
|
|
4689
|
+
// over, or a badge raised by the stall alert never comes down.
|
|
4690
|
+
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4691
|
+
}
|
|
4692
|
+
if (previous !== undefined) {
|
|
4693
|
+
this.promptStates.delete(session.id);
|
|
4694
|
+
this.updateFeedSession(session.id);
|
|
4695
|
+
}
|
|
4696
|
+
return;
|
|
4697
|
+
}
|
|
4698
|
+
// A real sighting cancels a pending repaint gap: the prompt is still there.
|
|
4699
|
+
// Refresh the stored prompt with it, too: the signature deliberately
|
|
4700
|
+
// normalises Grok's radio markers so that MOVING the selection does not
|
|
4701
|
+
// restart the stall clock, which means the same signature can describe a
|
|
4702
|
+
// visibly different set of options. Storing only on signature change
|
|
4703
|
+
// would serve a stale selection to `terminal_list` and to a viewer
|
|
4704
|
+
// joining late.
|
|
4705
|
+
const promptChanged = previous === undefined ||
|
|
4706
|
+
previous.prompt.question !== detected.question ||
|
|
4707
|
+
previous.prompt.selectedOption !== detected.selectedOption ||
|
|
4708
|
+
previous.prompt.options.length !== detected.options.length ||
|
|
4709
|
+
previous.prompt.options.some((option, index) => option !== detected.options[index]);
|
|
4710
|
+
const inputVersion = session.promptInputVersion();
|
|
4711
|
+
// Input alone does not mean this prompt was answered: a key may start
|
|
4712
|
+
// a repaint while the same decision remains on screen. A missed prompt
|
|
4713
|
+
// after input is evidence of a transition only when a prompt appears
|
|
4714
|
+
// again; the normal grace check still handles a lasting disappearance.
|
|
4715
|
+
const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
|
|
4716
|
+
previous.missingSince !== null;
|
|
4717
|
+
if (previous !== undefined) {
|
|
4718
|
+
this.clearPromptGraceCheck(session.id);
|
|
4719
|
+
previous.missingSince = null;
|
|
4720
|
+
previous.prompt = detected;
|
|
4721
|
+
}
|
|
4722
|
+
// A dialog can redraw at another width, or alongside changing sidebar
|
|
4723
|
+
// text, without changing its question or choices. Its rendered signature
|
|
4724
|
+
// then changes although the person still faces the same decision.
|
|
4725
|
+
// A stable signature also covers focus markers moving among options.
|
|
4726
|
+
const sameContent = previous !== undefined && !promptChanged;
|
|
4727
|
+
if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
|
|
4728
|
+
// A new (or changed) prompt starts its stall clock; it has not
|
|
4729
|
+
// alerted yet, so a prompt answered promptly stays silent.
|
|
4730
|
+
if (previous?.alerted === true) {
|
|
4731
|
+
// The previous prompt was announced and has now been replaced
|
|
4732
|
+
// rather than cleared. Retract it, otherwise a viewer badges the
|
|
4733
|
+
// old question while a different one is on screen.
|
|
4734
|
+
//
|
|
4735
|
+
// BOTH channels, symmetrically with the null path above. Retracting
|
|
4736
|
+
// to viewers only would leave `/events` emitting stall(Q1) then
|
|
4737
|
+
// stall(Q2) with no clear between them, which reads as two concurrent
|
|
4738
|
+
// holds or an unresolved first one. Nothing in this repository
|
|
4739
|
+
// subscribes to it, but the socket is a real API and an asymmetric
|
|
4740
|
+
// one is a trap for the first thing that consumes it.
|
|
4741
|
+
this.emitEvent({
|
|
4742
|
+
type: 'prompt-clear',
|
|
4743
|
+
session: session.id,
|
|
4744
|
+
label: session.label ?? null,
|
|
4745
|
+
});
|
|
4746
|
+
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4747
|
+
}
|
|
4748
|
+
this.promptStates.set(session.id, {
|
|
4749
|
+
signature: detected.signature,
|
|
4750
|
+
inputVersion,
|
|
4751
|
+
since: this.now(),
|
|
4752
|
+
alerted: false,
|
|
4753
|
+
prompt: detected,
|
|
4754
|
+
missingSince: null,
|
|
4755
|
+
});
|
|
4756
|
+
this.updateFeedSession(session.id, previous !== undefined);
|
|
4757
|
+
return;
|
|
4758
|
+
}
|
|
4759
|
+
previous.signature = detected.signature;
|
|
4760
|
+
if (promptChanged)
|
|
4761
|
+
this.updateFeedSession(session.id);
|
|
4762
|
+
if (!previous.alerted && this.now() - previous.since >= stallMs) {
|
|
4763
|
+
previous.alerted = true;
|
|
4764
|
+
this.updateFeedSession(session.id);
|
|
4765
|
+
const waitingMs = this.now() - previous.since;
|
|
4766
|
+
this.audit.record('daemon', 'prompt-stall', session.id);
|
|
4767
|
+
this.logger.warn('session waiting on a prompt', {
|
|
4768
|
+
id: session.id,
|
|
4769
|
+
waitingMs,
|
|
4770
|
+
options: detected.options.length,
|
|
4771
|
+
});
|
|
4772
|
+
this.emitEvent({
|
|
4773
|
+
type: 'prompt-stall',
|
|
4774
|
+
session: session.id,
|
|
4775
|
+
label: session.label ?? null,
|
|
4776
|
+
waitingMs,
|
|
4777
|
+
question: detected.question,
|
|
4778
|
+
options: detected.options,
|
|
4779
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4780
|
+
});
|
|
4781
|
+
// The session's own viewers get the same signal, so an open viewer
|
|
4782
|
+
// tab can badge itself without subscribing to the daemon stream.
|
|
4783
|
+
this.broadcastControl(session.id, {
|
|
4784
|
+
type: 'prompt-stall',
|
|
4785
|
+
since: previous.since,
|
|
4786
|
+
waitingMs,
|
|
4787
|
+
question: detected.question,
|
|
4788
|
+
// The options travel to viewers as well as to /events, so the badge
|
|
4789
|
+
// can say what the choices are, not only THAT something is being
|
|
4790
|
+
// asked.
|
|
4791
|
+
options: detected.options,
|
|
4792
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4793
|
+
});
|
|
4794
|
+
}
|
|
4795
|
+
}
|
|
4702
4796
|
/** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
|
|
4703
4797
|
emitEvent(event) {
|
|
4704
4798
|
const message = JSON.stringify({ ...event, at: new Date().toISOString() });
|
|
@@ -4718,7 +4812,7 @@ export class Daemon {
|
|
|
4718
4812
|
}
|
|
4719
4813
|
}
|
|
4720
4814
|
/** Dashboard notifications carry metadata only; the page fetches text separately. */
|
|
4721
|
-
|
|
4815
|
+
emitDashboardEvent(event) {
|
|
4722
4816
|
const frame = JSON.stringify({ ...event, at: new Date().toISOString() });
|
|
4723
4817
|
for (const ws of this.dashboardEventSockets) {
|
|
4724
4818
|
if (ws.readyState === ws.OPEN)
|
|
@@ -5341,6 +5435,7 @@ export class Daemon {
|
|
|
5341
5435
|
if (held?.alerted === true) {
|
|
5342
5436
|
ws.send(JSON.stringify({
|
|
5343
5437
|
type: 'prompt-stall',
|
|
5438
|
+
since: held.since,
|
|
5344
5439
|
waitingMs: Date.now() - held.since,
|
|
5345
5440
|
question: held.prompt.question,
|
|
5346
5441
|
options: held.prompt.options,
|
|
@@ -5693,7 +5788,7 @@ export class Daemon {
|
|
|
5693
5788
|
this.audit.record(actor, 'report', session.id, {
|
|
5694
5789
|
kind: report,
|
|
5695
5790
|
chars: bytes?.length ?? text.length,
|
|
5696
|
-
...(this.audit
|
|
5791
|
+
...(this.reload?.state.config.audit?.captureContent ? { data: bytes === null ? text : bytes.toString('latin1') } : {}),
|
|
5697
5792
|
});
|
|
5698
5793
|
return;
|
|
5699
5794
|
}
|