shellpuppet 0.5.1 → 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 +47 -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 +25 -4
- package/dist/core/mailbox.js +36 -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 +5 -0
- package/dist/core/renderer.js +31 -2
- package/dist/core/renderer.js.map +1 -1
- package/dist/core/session.d.ts +50 -32
- package/dist/core/session.js +333 -164
- 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 +27 -17
- package/dist/daemon/server.js +576 -453
- 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 +24 -2
- package/dist/viewer/dashboard.html +1 -1
- package/dist/viewer/dashboard.js +127 -16
- 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
|
}
|
|
@@ -1533,8 +1675,16 @@ export class Daemon {
|
|
|
1533
1675
|
this.lastActivity = Date.now();
|
|
1534
1676
|
this.writeSessionList(res, url);
|
|
1535
1677
|
}
|
|
1678
|
+
/** Build the metadata response without creating a text-bearing mailbox entry. */
|
|
1679
|
+
writeUnreadAge(res, actor) {
|
|
1680
|
+
const messages = this.mailbox.unreadAge(this.now());
|
|
1681
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
1682
|
+
this.audit.record(actor, 'unread-age-read', undefined, { count: messages.length });
|
|
1683
|
+
this.lastActivity = Date.now();
|
|
1684
|
+
json(res, 200, { messages });
|
|
1685
|
+
}
|
|
1536
1686
|
/** Owner-wide history is available only with the dashboard cookie and document proof. */
|
|
1537
|
-
serveDashboardMessages(req, res, url) {
|
|
1687
|
+
serveDashboardMessages(req, res, url, unreadAge = false) {
|
|
1538
1688
|
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1539
1689
|
if (this.dashboardCookieToken(req.headers.cookie) === null) {
|
|
1540
1690
|
if (presented)
|
|
@@ -1552,6 +1702,10 @@ export class Daemon {
|
|
|
1552
1702
|
json(res, 403, { error: 'Forbidden.' });
|
|
1553
1703
|
return;
|
|
1554
1704
|
}
|
|
1705
|
+
if (unreadAge) {
|
|
1706
|
+
this.writeUnreadAge(res, 'dashboard');
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1555
1709
|
const messages = this.mailbox.log();
|
|
1556
1710
|
const counts = {};
|
|
1557
1711
|
for (const entry of messages) {
|
|
@@ -1559,11 +1713,11 @@ export class Daemon {
|
|
|
1559
1713
|
counts[entry.to.id] = (counts[entry.to.id] ?? 0) + 1;
|
|
1560
1714
|
}
|
|
1561
1715
|
const summary = url.searchParams.get('summary') === '1';
|
|
1562
|
-
const groups = (this.
|
|
1716
|
+
const groups = (this.reload?.state.messaging.allow ?? []).filter((rule) => typeof rule !== 'string')
|
|
1563
1717
|
.map((rule) => ({ group: rule.group, members: rule.members, roles: rule.roles ?? [] }));
|
|
1564
1718
|
this.audit.record('dashboard', 'msg-log', undefined, { count: messages.length });
|
|
1565
1719
|
this.lastActivity = Date.now();
|
|
1566
|
-
json(res, 200, { enabled: this.
|
|
1720
|
+
json(res, 200, { enabled: this.reload?.state.messaging.enabled === true,
|
|
1567
1721
|
counts, ...(summary ? {} : { messages, groups }) });
|
|
1568
1722
|
}
|
|
1569
1723
|
/** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
|
|
@@ -1599,7 +1753,8 @@ export class Daemon {
|
|
|
1599
1753
|
purpose: describeProfileText(profile.purpose ?? '', profile.name),
|
|
1600
1754
|
command: profile.command,
|
|
1601
1755
|
args: [...profile.args],
|
|
1602
|
-
...(profile.resume ? { canResume: true
|
|
1756
|
+
...(profile.resume ? { canResume: true, resumeArgs: profile.resume,
|
|
1757
|
+
resumeCwd: profile.askCwd ? undefined : path.resolve(os.homedir(), profile.cwd ?? '.') } : {}),
|
|
1603
1758
|
folderRequired: profile.askCwd,
|
|
1604
1759
|
anyFolder: profile.anyFolder,
|
|
1605
1760
|
folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
|
|
@@ -1631,9 +1786,10 @@ export class Daemon {
|
|
|
1631
1786
|
return;
|
|
1632
1787
|
}
|
|
1633
1788
|
this.lastActivity = Date.now();
|
|
1789
|
+
const catalogue = this.launchProfiles;
|
|
1634
1790
|
json(res, 200, {
|
|
1635
|
-
profiles: await Promise.all(
|
|
1636
|
-
problems: [...
|
|
1791
|
+
profiles: await Promise.all(catalogue.profiles.map(profile => this.profileDescription(profile))),
|
|
1792
|
+
problems: [...catalogue.problems],
|
|
1637
1793
|
});
|
|
1638
1794
|
}
|
|
1639
1795
|
/** The desktop picker is available only to an authenticated any-folder profile. */
|
|
@@ -1686,6 +1842,7 @@ export class Daemon {
|
|
|
1686
1842
|
json(res, 409, { error: 'A folder picker is already open.' });
|
|
1687
1843
|
return;
|
|
1688
1844
|
}
|
|
1845
|
+
const pickerProfile = this.launchProfiles.profiles.find(profile => profile.name === body['profile']);
|
|
1689
1846
|
this.folderPickerBusy = true;
|
|
1690
1847
|
const controller = new AbortController();
|
|
1691
1848
|
this.folderPickerAbort = controller;
|
|
@@ -1724,6 +1881,10 @@ export class Daemon {
|
|
|
1724
1881
|
res.end();
|
|
1725
1882
|
return;
|
|
1726
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
|
+
}
|
|
1727
1888
|
json(res, 200, { path: selected });
|
|
1728
1889
|
}
|
|
1729
1890
|
catch (error) {
|
|
@@ -1847,7 +2008,8 @@ export class Daemon {
|
|
|
1847
2008
|
json(res, 409, { error: 'The launching dashboard window has closed.' });
|
|
1848
2009
|
return;
|
|
1849
2010
|
}
|
|
1850
|
-
const
|
|
2011
|
+
const profileIndex = this.launchProfiles.profiles.findIndex((entry) => entry.name === profileName);
|
|
2012
|
+
const profile = this.launchProfiles.profiles[profileIndex];
|
|
1851
2013
|
if (profile === undefined) {
|
|
1852
2014
|
json(res, 400, { error: `No such launch profile: ${profileName}` });
|
|
1853
2015
|
return;
|
|
@@ -1935,14 +2097,15 @@ export class Daemon {
|
|
|
1935
2097
|
}
|
|
1936
2098
|
// Global policy runs first, then the profile's own deny and allow lists.
|
|
1937
2099
|
// Both see the real command line, before any Windows shell wrap.
|
|
1938
|
-
const
|
|
2100
|
+
const policy = this.compiledPolicy;
|
|
2101
|
+
const globalDecision = evaluateCommand(policy, profile.command, args);
|
|
1939
2102
|
if (!globalDecision.allowed) {
|
|
1940
2103
|
this.auditDashboardRefusal(req, 'policy', launcher?.name);
|
|
1941
2104
|
json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
|
|
1942
2105
|
return;
|
|
1943
2106
|
}
|
|
1944
2107
|
if (profile.policy !== undefined) {
|
|
1945
|
-
const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, args);
|
|
2108
|
+
const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy, profile.configIndex ?? profileIndex), profile.command, args);
|
|
1946
2109
|
if (!ownDecision.allowed) {
|
|
1947
2110
|
this.auditDashboardRefusal(req, 'policy', launcher?.name);
|
|
1948
2111
|
json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
|
|
@@ -2021,6 +2184,18 @@ export class Daemon {
|
|
|
2021
2184
|
return;
|
|
2022
2185
|
}
|
|
2023
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
|
+
}
|
|
2024
2199
|
const now = this.now();
|
|
2025
2200
|
this.pruneLaunchTimes(now);
|
|
2026
2201
|
if (this.launchTimes.length + this.pendingProfileStarts.size >= this.launchesPerMinute) {
|
|
@@ -2077,14 +2252,16 @@ export class Daemon {
|
|
|
2077
2252
|
return;
|
|
2078
2253
|
}
|
|
2079
2254
|
// Reserve before yielding. Only a confirmed program starts its rolling minute.
|
|
2255
|
+
const mailboxName = this.reserveMailboxName(session, requestedName);
|
|
2080
2256
|
const reserved = session;
|
|
2081
2257
|
this.pendingProfileStarts.add(reserved);
|
|
2082
|
-
const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); };
|
|
2258
|
+
const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); mailboxName.release(); };
|
|
2083
2259
|
try {
|
|
2084
2260
|
const started = await this.programStarted(session, options, res, 'dashboard session start failed', releaseReservation);
|
|
2085
2261
|
if (started === null)
|
|
2086
2262
|
return;
|
|
2087
2263
|
session = started;
|
|
2264
|
+
this.registerMailboxSession(session, mailboxName.name);
|
|
2088
2265
|
this.launchTimes.push(this.now());
|
|
2089
2266
|
}
|
|
2090
2267
|
finally {
|
|
@@ -2093,7 +2270,6 @@ export class Daemon {
|
|
|
2093
2270
|
// A launch is an API call: the idle timer counts from it, so a session
|
|
2094
2271
|
// that has just started is not reaped sooner than `idleMinutes` allows.
|
|
2095
2272
|
this.lastActivity = Date.now();
|
|
2096
|
-
this.registerMailboxSession(session, requestedName);
|
|
2097
2273
|
if (launchingWindow && launchingWindow.socket.readyState === launchingWindow.socket.OPEN &&
|
|
2098
2274
|
this.dashboardWindowIds.has(launchingWindow.socket)) {
|
|
2099
2275
|
const { pair } = launchingWindow;
|
|
@@ -2441,6 +2617,10 @@ export class Daemon {
|
|
|
2441
2617
|
this.serveDashboardMessages(req, res, url);
|
|
2442
2618
|
return;
|
|
2443
2619
|
}
|
|
2620
|
+
if (req.method === 'GET' && url.pathname === '/dashboard/messages/unread-age') {
|
|
2621
|
+
this.serveDashboardMessages(req, res, url, true);
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2444
2624
|
if (req.method === 'POST' && url.pathname === '/dashboard/launch') {
|
|
2445
2625
|
await this.handleDashboardLaunch(req, res);
|
|
2446
2626
|
return;
|
|
@@ -2532,8 +2712,7 @@ export class Daemon {
|
|
|
2532
2712
|
return false;
|
|
2533
2713
|
}
|
|
2534
2714
|
if (state.restartCandidates) {
|
|
2535
|
-
const
|
|
2536
|
-
const resolved = retryRestartSource(home, state, snapshot, this.logger, () => this.requireHomeOwner());
|
|
2715
|
+
const resolved = retryRestartSource(this.configPermissions, state, snapshot, this.logger, () => this.requireHomeOwner());
|
|
2537
2716
|
if (resolved.restartCandidates)
|
|
2538
2717
|
return false;
|
|
2539
2718
|
// Remember a verified writer even when it rules out the rows just read.
|
|
@@ -2543,7 +2722,7 @@ export class Daemon {
|
|
|
2543
2722
|
Object.assign(state, resolved);
|
|
2544
2723
|
if (discovery.kind === 'record') {
|
|
2545
2724
|
try {
|
|
2546
|
-
writePrivateRecord(daemonStatePath(
|
|
2725
|
+
writePrivateRecord(daemonStatePath(this.configPermissions.homePath), state, () => {
|
|
2547
2726
|
if (this.requireHomeOwner().kind !== 'record')
|
|
2548
2727
|
throw new Error('Discovery changed during recovery.');
|
|
2549
2728
|
});
|
|
@@ -2569,11 +2748,11 @@ export class Daemon {
|
|
|
2569
2748
|
return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
|
|
2570
2749
|
agent: session.agent, resumeId: session.resumeId, endedAt }];
|
|
2571
2750
|
});
|
|
2572
|
-
writePrivateRecord(path.join(this.
|
|
2751
|
+
writePrivateRecord(path.join(this.configPermissions.homePath, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
|
|
2573
2752
|
}
|
|
2574
2753
|
saveLauncherClaims(excludeId, next, beforePublish) {
|
|
2575
2754
|
const grants = this.launchProfiles.sessionLaunch ?? [];
|
|
2576
|
-
const file = path.join(this.
|
|
2755
|
+
const file = path.join(this.configPermissions.homePath, 'launcher-claims.json');
|
|
2577
2756
|
if (!this.claimsRestored)
|
|
2578
2757
|
throw new Error('Saved launcher claims could not be restored.');
|
|
2579
2758
|
if (grants.length || fs.existsSync(file)) {
|
|
@@ -2603,28 +2782,25 @@ export class Daemon {
|
|
|
2603
2782
|
throw new ClaimAuditError(failure);
|
|
2604
2783
|
}
|
|
2605
2784
|
}
|
|
2606
|
-
presentedClaim(req
|
|
2785
|
+
presentedClaim(req) {
|
|
2607
2786
|
const id = req.headers['x-shellpuppet-claim'];
|
|
2608
2787
|
const secret = req.headers['x-shellpuppet-claim-secret'];
|
|
2609
2788
|
if (id === undefined && secret === undefined)
|
|
2610
2789
|
return {};
|
|
2611
2790
|
const marked = req.headers['x-shellpuppet-inside-session'] === '1';
|
|
2612
|
-
if (
|
|
2791
|
+
if (typeof id === 'string' && typeof secret === 'string' &&
|
|
2613
2792
|
this.mailbox.verifyClaim(id, secret, !marked))
|
|
2614
2793
|
return { id };
|
|
2615
2794
|
return { refused: true };
|
|
2616
2795
|
}
|
|
2617
2796
|
grantedLauncher(req, res) {
|
|
2618
2797
|
this.lapseIdleClaims();
|
|
2619
|
-
|
|
2620
|
-
if (
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
json(res, 403, { error: 'Session launch permission required.', ...invalidClaim });
|
|
2624
|
-
return undefined;
|
|
2625
|
-
}
|
|
2626
|
-
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;
|
|
2627
2802
|
}
|
|
2803
|
+
const id = this.callerContext.getStore() ?? (req.headers['x-shellpuppet-inside-session'] === '1' ? undefined : claim.id);
|
|
2628
2804
|
const caller = id === undefined ? undefined : this.mailbox.participant(id);
|
|
2629
2805
|
if (caller && this.launchProfiles.sessionLaunch?.includes(caller.name))
|
|
2630
2806
|
return caller;
|
|
@@ -2643,8 +2819,6 @@ export class Daemon {
|
|
|
2643
2819
|
if (pendingId === id)
|
|
2644
2820
|
this.pendingSchedules.delete(name);
|
|
2645
2821
|
this.nudges.remove(id);
|
|
2646
|
-
this.queuedMessageNudges.delete(id);
|
|
2647
|
-
this.inboxReadVersions.delete(id);
|
|
2648
2822
|
// Audit before end can trim old tombstones from retained history.
|
|
2649
2823
|
for (const entry of this.mailbox.log({ participantId: id })) {
|
|
2650
2824
|
if (entry.to.id === id && (entry.state === 'waiting' || entry.state === 'nudged')) {
|
|
@@ -2667,148 +2841,53 @@ export class Daemon {
|
|
|
2667
2841
|
this.audit.record('daemon', 'msg-lapse', id);
|
|
2668
2842
|
}
|
|
2669
2843
|
}
|
|
2670
|
-
async deliverNudge(id) {
|
|
2844
|
+
async deliverNudge(id, onWrite, confirmOnly = false) {
|
|
2671
2845
|
const session = this.manager.get(id);
|
|
2672
|
-
if (session
|
|
2673
|
-
this.queuedMessageNudges.delete(id);
|
|
2846
|
+
if (!session || session.exited || this.mailbox.participant(id)?.kind !== 'session')
|
|
2674
2847
|
return 'done';
|
|
2675
|
-
|
|
2676
|
-
const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
|
|
2677
|
-
// A scheduled body has no mailbox ids. It can clear on proof of consumption,
|
|
2678
|
-
// but a later inbox message can never authorise its submit key.
|
|
2679
|
-
if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
|
|
2680
|
-
!await this.clearScheduledBody(session))
|
|
2848
|
+
if (session.pendingSchedule() !== undefined && !await this.clearScheduledBody(session))
|
|
2681
2849
|
return 'wait';
|
|
2682
|
-
const
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
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);
|
|
2691
2868
|
});
|
|
2692
2869
|
}
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
const pending = session.nudgePendingLine();
|
|
2701
|
-
if (pending !== null) {
|
|
2702
|
-
if (session.nudgePendingIds().length === 0)
|
|
2703
|
-
return 'wait';
|
|
2704
|
-
const covered = session.nudgePendingIds();
|
|
2705
|
-
const auditPending = (reason) => {
|
|
2706
|
-
if (session.nudgePendingAuditOnce())
|
|
2707
|
-
this.audit.record('daemon', 'nudge-pending', id, {
|
|
2708
|
-
messageIds: [...covered], count: covered.length, reason,
|
|
2709
|
-
});
|
|
2710
|
-
};
|
|
2711
|
-
const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2712
|
-
if (ids.length === 0) {
|
|
2713
|
-
auditPending('messages-changed');
|
|
2714
|
-
return 'done';
|
|
2715
|
-
}
|
|
2716
|
-
if (!covered.every((messageId) => unread.some((entry) => entry.id === messageId))) {
|
|
2717
|
-
auditPending('messages-changed');
|
|
2718
|
-
return 'wait';
|
|
2719
|
-
}
|
|
2720
|
-
if (!session.nudgePendingSafeToSubmit()) {
|
|
2721
|
-
if (session.nudgeReadyWithLine(pending) && session.nudgePendingTouchRefusal()) {
|
|
2722
|
-
this.audit.record('daemon', 'nudge-aborted', id, {
|
|
2723
|
-
messageIds: [...covered], count: covered.length, reason: 'person-input-since',
|
|
2724
|
-
...session.nudgePendingBodyMeta(),
|
|
2725
|
-
});
|
|
2726
|
-
}
|
|
2727
|
-
auditPending('person-input-since');
|
|
2728
|
-
return 'wait';
|
|
2729
|
-
}
|
|
2730
|
-
if (!session.nudgeReadyWithLine(pending)) {
|
|
2731
|
-
auditPending('line-not-seen');
|
|
2732
|
-
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 });
|
|
2733
2877
|
}
|
|
2734
|
-
|
|
2735
|
-
const queuedInputVersion = session.nudgeQueuedInputVersion();
|
|
2736
|
-
const screenRevision = session.nudgeScreenRevision();
|
|
2737
|
-
const submitted = await session.submitPendingNudge(pending, (screen) => {
|
|
2738
|
-
const waitingIds = this.mailbox.inbox(id, { markRead: false })
|
|
2739
|
-
.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2740
|
-
return !session.exited && !session.getStalled() &&
|
|
2741
|
-
session.nudgePendingSafeToSubmit() &&
|
|
2742
|
-
session.nudgeInputVersion() === inputVersion &&
|
|
2743
|
-
session.nudgeQueuedInputVersion() === queuedInputVersion &&
|
|
2744
|
-
session.nudgeScreenRevision() === screenRevision &&
|
|
2745
|
-
session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
|
|
2746
|
-
covered.every((messageId) => this.mailbox.inbox(id, { markRead: false })
|
|
2747
|
-
.some((entry) => entry.id === messageId)) &&
|
|
2748
|
-
waitingIds.length === ids.length &&
|
|
2749
|
-
ids.every((messageId) => waitingIds.includes(messageId));
|
|
2750
|
-
});
|
|
2751
|
-
if (!submitted) {
|
|
2752
|
-
if (session.nudgePendingTouchRefusal()) {
|
|
2753
|
-
this.audit.record('daemon', 'nudge-aborted', id, {
|
|
2754
|
-
messageIds: [...covered], count: covered.length, reason: 'person-input-since',
|
|
2755
|
-
...session.nudgePendingBodyMeta(),
|
|
2756
|
-
});
|
|
2757
|
-
}
|
|
2758
|
-
auditPending('person-input-since');
|
|
2878
|
+
if (error instanceof SessionInputFailedError)
|
|
2759
2879
|
return 'wait';
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
waitingMessageIds: ids.filter((messageId) => !covered.includes(messageId)),
|
|
2764
|
-
staleMessageIds: covered.filter((messageId) => !unread.some((entry) => entry.id === messageId)) });
|
|
2765
|
-
return 'sent';
|
|
2766
|
-
}
|
|
2767
|
-
const queued = this.queuedMessageNudges?.get(id);
|
|
2768
|
-
if (queued !== undefined) {
|
|
2769
|
-
const state = session.nudgeState(this.now());
|
|
2770
|
-
if (this.now() - queued.at >= QUEUED_NUDGE_MAX_MS || (state.ready && !state.queued)) {
|
|
2771
|
-
this.queuedMessageNudges.delete(id);
|
|
2772
|
-
}
|
|
2773
|
-
else {
|
|
2774
|
-
const waitingIds = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2775
|
-
const newlyHeld = waitingIds.filter((messageId) => !queued.heldIds.has(messageId));
|
|
2776
|
-
if (newlyHeld.length > 0) {
|
|
2777
|
-
for (const messageId of newlyHeld)
|
|
2778
|
-
queued.heldIds.add(messageId);
|
|
2779
|
-
this.audit.record('daemon', 'nudge-held', id, { reason: 'queued-nudge-pending',
|
|
2780
|
-
messageIds: newlyHeld, count: newlyHeld.length, queuedMessageIds: queued.messageIds });
|
|
2781
|
-
}
|
|
2782
|
-
return waitingIds.length > 0 ? 'wait' : 'done';
|
|
2783
|
-
}
|
|
2880
|
+
if (error instanceof SessionProgramEndedError || session.exited)
|
|
2881
|
+
return 'done';
|
|
2882
|
+
throw error;
|
|
2784
2883
|
}
|
|
2785
|
-
|
|
2786
|
-
// nudged but is still unread (the agent did not read its inbox) is listed
|
|
2787
|
-
// in the line again when a later message arrives after any queued hold ends.
|
|
2788
|
-
const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
|
|
2789
|
-
if (ids.length === 0)
|
|
2884
|
+
if (!live())
|
|
2790
2885
|
return 'done';
|
|
2791
|
-
if (
|
|
2792
|
-
|
|
2793
|
-
const line = buildNudge(unread);
|
|
2794
|
-
const readVersion = this.inboxReadVersions?.get(id) ?? 0;
|
|
2795
|
-
const result = await this.deliverLine(session, line, undefined, ids, () => {
|
|
2796
|
-
const current = this.mailbox.inbox(id, { markRead: false });
|
|
2797
|
-
return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
|
|
2798
|
-
});
|
|
2799
|
-
if (result.outcome === 'aborted') {
|
|
2800
|
-
this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason,
|
|
2801
|
-
...session.nudgePendingBodyMeta() });
|
|
2802
|
-
}
|
|
2803
|
-
if (result.outcome !== 'sent' && result.outcome !== 'queued')
|
|
2886
|
+
if (result.outcome === 'unconfirmed') {
|
|
2887
|
+
record('nudge-unconfirmed', result.ids, result.queued);
|
|
2804
2888
|
return 'wait';
|
|
2805
|
-
this.mailbox.markNudged(ids);
|
|
2806
|
-
if (result.outcome === 'queued' && (this.inboxReadVersions?.get(id) ?? 0) === readVersion) {
|
|
2807
|
-
this.queuedMessageNudges.set(id, { at: this.now(), messageIds: ids, heldIds: new Set() });
|
|
2808
2889
|
}
|
|
2809
|
-
|
|
2810
|
-
...(result.outcome === 'queued' ? { queued: true } : {}) });
|
|
2811
|
-
return 'sent';
|
|
2890
|
+
return result.outcome;
|
|
2812
2891
|
}
|
|
2813
2892
|
async clearScheduledBody(session) {
|
|
2814
2893
|
const name = session.pendingSchedule();
|
|
@@ -2833,11 +2912,13 @@ export class Daemon {
|
|
|
2833
2912
|
}
|
|
2834
2913
|
this.pendingSchedules.delete(schedule.name);
|
|
2835
2914
|
}
|
|
2836
|
-
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))) {
|
|
2837
2918
|
return { sessionId: id, outcome: 'skipped', reason: 'pending' };
|
|
2838
2919
|
}
|
|
2839
2920
|
try {
|
|
2840
|
-
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);
|
|
2841
2922
|
// Ordinary input can also arrive while the scheduled write waits in the input queue.
|
|
2842
2923
|
if (result.outcome === 'skipped' && session.recentInput)
|
|
2843
2924
|
result.reason = 'recent-input';
|
|
@@ -2848,7 +2929,7 @@ export class Daemon {
|
|
|
2848
2929
|
this.pendingSchedules.set(schedule.name, session.id);
|
|
2849
2930
|
}
|
|
2850
2931
|
}
|
|
2851
|
-
async deliverLine(session, line, whenBusy,
|
|
2932
|
+
async deliverLine(session, line, whenBusy, currentDelivery, schedule) {
|
|
2852
2933
|
if (!session.hasPainted())
|
|
2853
2934
|
return { outcome: 'skipped', reason: 'unknown' };
|
|
2854
2935
|
const inputVersion = session.nudgeInputVersion();
|
|
@@ -2894,7 +2975,7 @@ export class Daemon {
|
|
|
2894
2975
|
return false;
|
|
2895
2976
|
}
|
|
2896
2977
|
if (!currentDelivery()) {
|
|
2897
|
-
failedCheck =
|
|
2978
|
+
failedCheck = 'schedule-changed';
|
|
2898
2979
|
return false;
|
|
2899
2980
|
}
|
|
2900
2981
|
if (phase === 'before' ? !current?.ready || current.queued !== queued : !session.nudgeReadyWithLine(line, queued, whenBusy)) {
|
|
@@ -2904,23 +2985,15 @@ export class Daemon {
|
|
|
2904
2985
|
return true;
|
|
2905
2986
|
};
|
|
2906
2987
|
try {
|
|
2907
|
-
const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready,
|
|
2988
|
+
const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready, () => failedCheck, schedule, queued);
|
|
2908
2989
|
if (result === 'wait')
|
|
2909
|
-
return { outcome: 'skipped', reason: session.nudgePendingLine() !== null ? 'pending' : failedCheck };
|
|
2990
|
+
return { outcome: 'skipped', reason: session.hasUnconfirmedMail || session.nudgePendingLine() !== null ? 'pending' : failedCheck };
|
|
2910
2991
|
if (result.startsWith('aborted-')) {
|
|
2911
2992
|
const reason = result.slice('aborted-'.length);
|
|
2912
2993
|
return { outcome: 'aborted', reason };
|
|
2913
2994
|
}
|
|
2914
2995
|
}
|
|
2915
2996
|
catch (error) {
|
|
2916
|
-
const pendingBody = session.nudgePendingBodyMeta();
|
|
2917
|
-
if (ids.length > 0 && pendingBody.pendingBody) {
|
|
2918
|
-
const reason = error instanceof SessionInputFailedError ? 'input-failed'
|
|
2919
|
-
: error instanceof SessionProgramEndedError ? 'session-ended' : 'write-failed';
|
|
2920
|
-
this.audit.record('daemon', 'nudge-aborted', session.id, {
|
|
2921
|
-
messageIds: ids, count: ids.length, reason, ...pendingBody,
|
|
2922
|
-
});
|
|
2923
|
-
}
|
|
2924
2997
|
if (error instanceof SessionInputFailedError)
|
|
2925
2998
|
return { outcome: 'skipped', reason: 'input-failed' };
|
|
2926
2999
|
if (error instanceof SessionProgramEndedError)
|
|
@@ -2929,10 +3002,10 @@ export class Daemon {
|
|
|
2929
3002
|
}
|
|
2930
3003
|
return { outcome: queued ? 'queued' : 'sent' };
|
|
2931
3004
|
}
|
|
2932
|
-
|
|
3005
|
+
reserveMailboxName(session, profileName) {
|
|
2933
3006
|
const label = profileName ?? session.label;
|
|
2934
|
-
const
|
|
2935
|
-
let name = !
|
|
3007
|
+
const granted = profileName === undefined && this.launchProfiles.sessionLaunch?.includes(label);
|
|
3008
|
+
let name = !granted && NAME_PATTERN.test(label) &&
|
|
2936
3009
|
(!/^s[0-9]+$/.test(label) || label === session.id) &&
|
|
2937
3010
|
!this.mailbox.nameTaken(label) ? label : session.id;
|
|
2938
3011
|
if (profileName !== undefined && name === session.id && NAME_PATTERN.test(label) &&
|
|
@@ -2945,6 +3018,9 @@ export class Daemon {
|
|
|
2945
3018
|
}
|
|
2946
3019
|
}
|
|
2947
3020
|
}
|
|
3021
|
+
return { name, release: this.mailbox.reserveSessionName(name, session.id) };
|
|
3022
|
+
}
|
|
3023
|
+
registerMailboxSession(session, name) {
|
|
2948
3024
|
this.mailbox.register({ kind: 'session', id: session.id, name, role: session.role });
|
|
2949
3025
|
if (NAME_PATTERN.test(session.label))
|
|
2950
3026
|
session.label = name;
|
|
@@ -2953,22 +3029,24 @@ export class Daemon {
|
|
|
2953
3029
|
this.endMailboxParticipant(session.id);
|
|
2954
3030
|
}
|
|
2955
3031
|
isReservedClaimName(name) {
|
|
2956
|
-
return (this.
|
|
3032
|
+
return (this.reload?.state.messaging.allow ?? []).some((rule) => rule !== 'parent-child' && rule.members.includes(name));
|
|
2957
3033
|
}
|
|
2958
3034
|
async handleMessages(req, res, url, segments, actor) {
|
|
2959
|
-
if (this.options.messaging?.enabled !== true) {
|
|
2960
|
-
json(res, 403, { error: 'Messaging is off.' });
|
|
2961
|
-
return;
|
|
2962
|
-
}
|
|
2963
3035
|
this.lapseIdleClaims();
|
|
2964
3036
|
const route = segments[1];
|
|
2965
3037
|
const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
|
|
2966
3038
|
const { id: claimId, refused } = this.presentedClaim(req);
|
|
2967
|
-
if (refused
|
|
3039
|
+
if (refused) {
|
|
2968
3040
|
json(res, 403, { error: 'Messaging claim was not recognised.', ...invalidClaim });
|
|
2969
3041
|
return;
|
|
2970
3042
|
}
|
|
2971
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
|
+
}
|
|
2972
3050
|
if (creatingClaim) {
|
|
2973
3051
|
// Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
|
|
2974
3052
|
if (this.callerContext.getStore() !== undefined) {
|
|
@@ -2992,6 +3070,10 @@ export class Daemon {
|
|
|
2992
3070
|
return;
|
|
2993
3071
|
}
|
|
2994
3072
|
const body = await readBody(req);
|
|
3073
|
+
if (!this.reload?.state.messaging.enabled) {
|
|
3074
|
+
json(res, 403, { error: 'Messaging is off.' });
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
2995
3077
|
const name = body['name'];
|
|
2996
3078
|
const replace = body['replace'] === true;
|
|
2997
3079
|
if (typeof name !== 'string') {
|
|
@@ -3045,8 +3127,7 @@ export class Daemon {
|
|
|
3045
3127
|
}
|
|
3046
3128
|
if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
|
|
3047
3129
|
if (claimId === undefined || claimId !== segments[2]) {
|
|
3048
|
-
json(res, 403, { error: 'The matching claim is required.'
|
|
3049
|
-
...(claimId === undefined ? {} : { hint: CLAIM_RECOVERY_HINT }) });
|
|
3130
|
+
json(res, 403, { error: 'The matching claim is required.' });
|
|
3050
3131
|
return;
|
|
3051
3132
|
}
|
|
3052
3133
|
const name = this.mailbox.participant(claimId)?.name;
|
|
@@ -3068,6 +3149,13 @@ export class Daemon {
|
|
|
3068
3149
|
}
|
|
3069
3150
|
if (req.method === 'POST' && route === undefined) {
|
|
3070
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
|
+
}
|
|
3071
3159
|
const result = this.mailbox.send(caller, body['to'], body['text']);
|
|
3072
3160
|
json(res, 201, result);
|
|
3073
3161
|
return;
|
|
@@ -3179,7 +3267,10 @@ export class Daemon {
|
|
|
3179
3267
|
// Behind the token, unlike /health: names of credential-shaped
|
|
3180
3268
|
// variables are not for anyone who can reach the port.
|
|
3181
3269
|
if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
|
|
3182
|
-
|
|
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);
|
|
3183
3274
|
return;
|
|
3184
3275
|
}
|
|
3185
3276
|
if (req.method === 'POST' && segments[0] === 'dashboard' && segments[1] === 'open' && segments.length === 2) {
|
|
@@ -3193,10 +3284,9 @@ export class Daemon {
|
|
|
3193
3284
|
if (url.pathname === '/launcher/previous' && req.method === 'GET') {
|
|
3194
3285
|
if (!this.grantedLauncher(req, res))
|
|
3195
3286
|
return;
|
|
3196
|
-
const file = path.join(this.options.home, 'previous-sessions.json');
|
|
3197
3287
|
try {
|
|
3198
3288
|
// Older version 1 records used the generated session id as an explicit name.
|
|
3199
|
-
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);
|
|
3200
3290
|
if (!this.verifiedRestartSnapshot(record)) {
|
|
3201
3291
|
json(res, 409, { error: 'No verified session snapshot is available for the previous restart.' });
|
|
3202
3292
|
return;
|
|
@@ -3223,6 +3313,18 @@ export class Daemon {
|
|
|
3223
3313
|
await this.launchProfile(req, res, { launcher: caller });
|
|
3224
3314
|
return;
|
|
3225
3315
|
}
|
|
3316
|
+
if (req.method === 'GET' && url.pathname === '/messages/unread-age') {
|
|
3317
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3318
|
+
if (this.callerContext.getStore() !== undefined ||
|
|
3319
|
+
req.headers['x-shellpuppet-inside-session'] !== undefined ||
|
|
3320
|
+
req.headers['x-shellpuppet-claim'] !== undefined ||
|
|
3321
|
+
req.headers['x-shellpuppet-claim-secret'] !== undefined) {
|
|
3322
|
+
json(res, 403, { error: 'Owner access is required.' });
|
|
3323
|
+
return;
|
|
3324
|
+
}
|
|
3325
|
+
this.writeUnreadAge(res, actor);
|
|
3326
|
+
return;
|
|
3327
|
+
}
|
|
3226
3328
|
if (segments[0] === 'messages') {
|
|
3227
3329
|
await this.handleMessages(req, res, url, segments, actor);
|
|
3228
3330
|
return;
|
|
@@ -3285,8 +3387,7 @@ export class Daemon {
|
|
|
3285
3387
|
return;
|
|
3286
3388
|
}
|
|
3287
3389
|
const hide = body['hideReasoning'] === true;
|
|
3288
|
-
|
|
3289
|
-
if (hide && signature === null)
|
|
3390
|
+
if (hide && this.readerFor(session, res) === null)
|
|
3290
3391
|
return;
|
|
3291
3392
|
// Absent means the default; present and not a number is a mistake to
|
|
3292
3393
|
// report, not to paper over with the default.
|
|
@@ -3318,7 +3419,7 @@ export class Daemon {
|
|
|
3318
3419
|
});
|
|
3319
3420
|
return;
|
|
3320
3421
|
}
|
|
3321
|
-
const browser = await findBrowser(this.
|
|
3422
|
+
const browser = await findBrowser(this.viewer.browserPath, this.logger);
|
|
3322
3423
|
if (browser === null) {
|
|
3323
3424
|
// No silent fallback to re-rendering the cells ourselves: that would
|
|
3324
3425
|
// return a picture of what the daemon thinks, labelled as what the
|
|
@@ -3329,10 +3430,13 @@ export class Daemon {
|
|
|
3329
3430
|
});
|
|
3330
3431
|
return;
|
|
3331
3432
|
}
|
|
3332
|
-
const capturedScreen = await session.captureViewerScreen(
|
|
3433
|
+
const capturedScreen = await session.captureViewerScreen(hide ? REASONING_CONTEXT_LINES : 0, VIEWER_SNAPSHOT_SCROLLBACK_LINES);
|
|
3333
3434
|
let redactedRows;
|
|
3334
3435
|
let expectedRows;
|
|
3335
|
-
if (
|
|
3436
|
+
if (hide) {
|
|
3437
|
+
const signature = this.readerFor(session, res);
|
|
3438
|
+
if (signature === null)
|
|
3439
|
+
return;
|
|
3336
3440
|
const view = capturedScreen.view;
|
|
3337
3441
|
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3338
3442
|
if (filtered === null) {
|
|
@@ -3368,7 +3472,7 @@ export class Daemon {
|
|
|
3368
3472
|
width,
|
|
3369
3473
|
height,
|
|
3370
3474
|
timeoutMs,
|
|
3371
|
-
profileRoot: captureProfileRoot(this.
|
|
3475
|
+
profileRoot: captureProfileRoot(this.configPermissions.homePath),
|
|
3372
3476
|
...(redactedRows === undefined ? {} : { hiddenRows: [...redactedRows.keys()] }),
|
|
3373
3477
|
logger: this.logger,
|
|
3374
3478
|
});
|
|
@@ -3430,21 +3534,19 @@ export class Daemon {
|
|
|
3430
3534
|
}
|
|
3431
3535
|
// Fails closed: without a signature to read the screen by, nothing
|
|
3432
3536
|
// is returned, never the screen unfiltered.
|
|
3433
|
-
|
|
3434
|
-
if (hide && signature === null)
|
|
3537
|
+
if (hide && this.readerFor(session, res) === null)
|
|
3435
3538
|
return;
|
|
3436
3539
|
const read = async () => {
|
|
3437
3540
|
const snapshot = await session.snapshot();
|
|
3438
|
-
if (
|
|
3541
|
+
if (!hide)
|
|
3439
3542
|
return count === undefined ? { ...snapshot } : { ...snapshot, lastLines: await session.lastLines(count) };
|
|
3440
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;
|
|
3441
3548
|
const screen = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3442
|
-
|
|
3443
|
-
let tailSource;
|
|
3444
|
-
if (count !== undefined) {
|
|
3445
|
-
tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
|
|
3446
|
-
tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
3447
|
-
}
|
|
3549
|
+
const tail = tailSource === undefined ? undefined : hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
3448
3550
|
if (screen === null || tail === null) {
|
|
3449
3551
|
json(res, 400, { error: overBudgetMessage(signature) });
|
|
3450
3552
|
return null;
|
|
@@ -3578,10 +3680,10 @@ export class Daemon {
|
|
|
3578
3680
|
return;
|
|
3579
3681
|
}
|
|
3580
3682
|
if (req.method === 'GET' && action === 'result') {
|
|
3683
|
+
const { lines } = await session.styledTail(RESULT_LINES);
|
|
3581
3684
|
const signature = this.readerFor(session, res);
|
|
3582
3685
|
if (signature === null)
|
|
3583
3686
|
return;
|
|
3584
|
-
const { lines } = await session.styledTail(RESULT_LINES);
|
|
3585
3687
|
json(res, 200, {
|
|
3586
3688
|
id: session.id,
|
|
3587
3689
|
agent: signature.name,
|
|
@@ -3655,7 +3757,7 @@ export class Daemon {
|
|
|
3655
3757
|
const bytes = submitMode === undefined ? data.length : written.inputBytes ?? 0;
|
|
3656
3758
|
if (report !== null) {
|
|
3657
3759
|
this.audit.record(actor, 'report', id, { kind: report, chars: bytes,
|
|
3658
|
-
...(this.audit
|
|
3760
|
+
...(this.reload?.state.config.audit?.captureContent ? { data } : {}) });
|
|
3659
3761
|
}
|
|
3660
3762
|
else {
|
|
3661
3763
|
this.audit.record(actor, 'input', id, { chars: bytes,
|
|
@@ -3698,8 +3800,12 @@ export class Daemon {
|
|
|
3698
3800
|
}
|
|
3699
3801
|
// Same exit race and failed input pipe as the input endpoint above:
|
|
3700
3802
|
// 409, not 500.
|
|
3803
|
+
let warning;
|
|
3701
3804
|
try {
|
|
3702
|
-
|
|
3805
|
+
if (key.trim().toLowerCase() === 'enter')
|
|
3806
|
+
warning = await session.writeEnter();
|
|
3807
|
+
else
|
|
3808
|
+
await session.write(bytes);
|
|
3703
3809
|
}
|
|
3704
3810
|
catch (error) {
|
|
3705
3811
|
json(res, 409, {
|
|
@@ -3711,7 +3817,7 @@ export class Daemon {
|
|
|
3711
3817
|
}
|
|
3712
3818
|
this.audit.record(actor, 'key', id, { key });
|
|
3713
3819
|
this.broadcastControl(id, { type: 'input-source', source: 'agent' });
|
|
3714
|
-
json(res, 200, { ok: true, key });
|
|
3820
|
+
json(res, 200, { ok: true, key, ...(warning && { warning }) });
|
|
3715
3821
|
return;
|
|
3716
3822
|
}
|
|
3717
3823
|
if (req.method === 'GET' && action === 'wait') {
|
|
@@ -3750,7 +3856,6 @@ export class Daemon {
|
|
|
3750
3856
|
if (stalled)
|
|
3751
3857
|
condition.stalled = true;
|
|
3752
3858
|
const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
|
|
3753
|
-
const pendingReader = signatureForSession(session);
|
|
3754
3859
|
let matchView;
|
|
3755
3860
|
const timeoutParam = url.searchParams.get('timeout');
|
|
3756
3861
|
const debounceParam = url.searchParams.get('debounce');
|
|
@@ -3778,12 +3883,18 @@ export class Daemon {
|
|
|
3778
3883
|
? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
|
|
3779
3884
|
: {}),
|
|
3780
3885
|
...(filteredMatch ? { screenForMatch: () => {
|
|
3781
|
-
|
|
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);
|
|
3782
3890
|
return matchView.screen;
|
|
3783
3891
|
}, stylesForMatch: () => matchView?.styled } : {}),
|
|
3784
|
-
...(
|
|
3892
|
+
...(moduleFor(session.agent)?.readingRules?.pendingComposer === true ? {
|
|
3785
3893
|
composerPending: () => {
|
|
3786
|
-
const
|
|
3894
|
+
const current = signatureForSession(session);
|
|
3895
|
+
if (!current)
|
|
3896
|
+
return false;
|
|
3897
|
+
const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, current);
|
|
3787
3898
|
return !result.found && result.reason === 'prompt-typed';
|
|
3788
3899
|
},
|
|
3789
3900
|
} : {}),
|
|
@@ -3815,7 +3926,10 @@ export class Daemon {
|
|
|
3815
3926
|
// The screen as it stands now, a moment after the wait resolved,
|
|
3816
3927
|
// with the reasoning left out.
|
|
3817
3928
|
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3818
|
-
const
|
|
3929
|
+
const current = this.readerFor(session, res);
|
|
3930
|
+
if (!current)
|
|
3931
|
+
return;
|
|
3932
|
+
const filtered = hideReasoning(view.lines, current, view.firstVisible);
|
|
3819
3933
|
if (filtered === null) {
|
|
3820
3934
|
json(res, 400, { error: overBudgetMessage(reader) });
|
|
3821
3935
|
return;
|
|
@@ -3868,10 +3982,10 @@ export class Daemon {
|
|
|
3868
3982
|
json(res, 200, { id: session.id, pattern, ...result });
|
|
3869
3983
|
return;
|
|
3870
3984
|
}
|
|
3985
|
+
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3871
3986
|
const signature = this.readerFor(session, res);
|
|
3872
3987
|
if (signature === null)
|
|
3873
3988
|
return;
|
|
3874
|
-
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
3875
3989
|
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
3876
3990
|
if (filtered === null) {
|
|
3877
3991
|
json(res, 400, { error: overBudgetMessage(signature) });
|
|
@@ -3953,7 +4067,7 @@ export class Daemon {
|
|
|
3953
4067
|
}
|
|
3954
4068
|
if (error instanceof MailboxError) {
|
|
3955
4069
|
const status = error.code === 'unknown-name' ? 404 :
|
|
3956
|
-
error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
|
|
4070
|
+
error.code === 'not-allowed' || error.code === 'unknown-sender' || error.code === 'messaging-disabled' ? 403 :
|
|
3957
4071
|
error.code === 'duplicate-name' || error.code === 'mailbox-full' ? 409 : 400;
|
|
3958
4072
|
const messages = {
|
|
3959
4073
|
'invalid-name': 'A valid participant name is required.',
|
|
@@ -4098,13 +4212,17 @@ export class Daemon {
|
|
|
4098
4212
|
// its output worker has connected, a few hundred milliseconds after the
|
|
4099
4213
|
// spawn returns, and reports pid 0 until then. The start contract is what
|
|
4100
4214
|
// it always was: a started session has a program, and its pid is real.
|
|
4101
|
-
const
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
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
|
+
}
|
|
4108
4226
|
this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
|
|
4109
4227
|
session.onExit(() => {
|
|
4110
4228
|
this.clearPromptGraceCheck(session.id);
|
|
@@ -4149,7 +4267,7 @@ export class Daemon {
|
|
|
4149
4267
|
// A connected dashboard is the human's window. Do not mint a viewer grant
|
|
4150
4268
|
// that would sit unused, and do not open a second window.
|
|
4151
4269
|
const dashboardWatching = wantsViewer && this.hasLiveDashboardSocket();
|
|
4152
|
-
const mode = this.
|
|
4270
|
+
const mode = this.viewer.launchMode ?? 'no-window';
|
|
4153
4271
|
let viewerUrl = wantsViewer && !dashboardWatching && mode !== 'dashboard'
|
|
4154
4272
|
? this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id))
|
|
4155
4273
|
: '';
|
|
@@ -4175,13 +4293,13 @@ export class Daemon {
|
|
|
4175
4293
|
}
|
|
4176
4294
|
else {
|
|
4177
4295
|
try {
|
|
4178
|
-
opened = await launch(viewerUrl, this.
|
|
4296
|
+
opened = await launch(viewerUrl, this.configPermissions.homePath, this.viewer, this.logger);
|
|
4179
4297
|
}
|
|
4180
4298
|
catch (error) {
|
|
4181
4299
|
this.logger.warn('viewer launch failed', { id: session.id, error: String(error) });
|
|
4182
4300
|
opened = {
|
|
4183
4301
|
launched: false,
|
|
4184
|
-
mode
|
|
4302
|
+
mode,
|
|
4185
4303
|
reason: String(error),
|
|
4186
4304
|
};
|
|
4187
4305
|
}
|
|
@@ -4508,7 +4626,6 @@ export class Daemon {
|
|
|
4508
4626
|
* someone happens to snapshot the session.
|
|
4509
4627
|
*/
|
|
4510
4628
|
async scanForPromptStalls() {
|
|
4511
|
-
const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
|
|
4512
4629
|
const seen = new Set();
|
|
4513
4630
|
const scheduled = new Set(this.schedules.read().filter(s => s.enabled).map(s => this.mailbox.sessionIdByName(s.session)));
|
|
4514
4631
|
for (const summary of this.manager.list()) {
|
|
@@ -4533,133 +4650,7 @@ export class Daemon {
|
|
|
4533
4650
|
});
|
|
4534
4651
|
continue;
|
|
4535
4652
|
}
|
|
4536
|
-
|
|
4537
|
-
if (detected === null) {
|
|
4538
|
-
// A snapshot may land midway through a repaint. Keep the prompt and
|
|
4539
|
-
// its clock for a short wall-clock grace period, independent of the
|
|
4540
|
-
// scan interval; a lasting disappearance still clears it.
|
|
4541
|
-
if (previous !== undefined) {
|
|
4542
|
-
if (previous.missingSince === null)
|
|
4543
|
-
previous.missingSince = this.now();
|
|
4544
|
-
const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - this.now();
|
|
4545
|
-
if (remaining > 0) {
|
|
4546
|
-
this.schedulePromptGraceCheck(session.id, remaining);
|
|
4547
|
-
continue;
|
|
4548
|
-
}
|
|
4549
|
-
}
|
|
4550
|
-
this.clearPromptGraceCheck(session.id);
|
|
4551
|
-
if (previous?.alerted === true) {
|
|
4552
|
-
this.emitEvent({
|
|
4553
|
-
type: 'prompt-clear',
|
|
4554
|
-
session: session.id,
|
|
4555
|
-
label: summary.label ?? null,
|
|
4556
|
-
});
|
|
4557
|
-
// Viewers were told the prompt was waiting; they must be told it is
|
|
4558
|
-
// over, or a badge raised by the stall alert never comes down.
|
|
4559
|
-
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4560
|
-
}
|
|
4561
|
-
if (previous !== undefined) {
|
|
4562
|
-
this.promptStates.delete(session.id);
|
|
4563
|
-
this.updateFeedSession(session.id);
|
|
4564
|
-
}
|
|
4565
|
-
continue;
|
|
4566
|
-
}
|
|
4567
|
-
// A real sighting cancels a pending repaint gap: the prompt is still there.
|
|
4568
|
-
// Refresh the stored prompt with it, too: the signature deliberately
|
|
4569
|
-
// normalises Grok's radio markers so that MOVING the selection does not
|
|
4570
|
-
// restart the stall clock, which means the same signature can describe a
|
|
4571
|
-
// visibly different set of options. Storing only on signature change
|
|
4572
|
-
// would serve a stale selection to `terminal_list` and to a viewer
|
|
4573
|
-
// joining late.
|
|
4574
|
-
const promptChanged = previous === undefined ||
|
|
4575
|
-
previous.prompt.question !== detected.question ||
|
|
4576
|
-
previous.prompt.selectedOption !== detected.selectedOption ||
|
|
4577
|
-
previous.prompt.options.length !== detected.options.length ||
|
|
4578
|
-
previous.prompt.options.some((option, index) => option !== detected.options[index]);
|
|
4579
|
-
const inputVersion = session.promptInputVersion();
|
|
4580
|
-
// Input alone does not mean this prompt was answered: a key may start
|
|
4581
|
-
// a repaint while the same decision remains on screen. A missed prompt
|
|
4582
|
-
// after input is evidence of a transition only when a prompt appears
|
|
4583
|
-
// again; the normal grace check still handles a lasting disappearance.
|
|
4584
|
-
const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
|
|
4585
|
-
previous.missingSince !== null;
|
|
4586
|
-
if (previous !== undefined) {
|
|
4587
|
-
this.clearPromptGraceCheck(session.id);
|
|
4588
|
-
previous.missingSince = null;
|
|
4589
|
-
previous.prompt = detected;
|
|
4590
|
-
}
|
|
4591
|
-
// A dialog can redraw at another width, or alongside changing sidebar
|
|
4592
|
-
// text, without changing its question or choices. Its rendered signature
|
|
4593
|
-
// then changes although the person still faces the same decision.
|
|
4594
|
-
// A stable signature also covers focus markers moving among options.
|
|
4595
|
-
const sameContent = previous !== undefined && !promptChanged;
|
|
4596
|
-
if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
|
|
4597
|
-
// A new (or changed) prompt starts its stall clock; it has not
|
|
4598
|
-
// alerted yet, so a prompt answered promptly stays silent.
|
|
4599
|
-
if (previous?.alerted === true) {
|
|
4600
|
-
// The previous prompt was announced and has now been replaced
|
|
4601
|
-
// rather than cleared. Retract it, otherwise a viewer badges the
|
|
4602
|
-
// old question while a different one is on screen.
|
|
4603
|
-
//
|
|
4604
|
-
// BOTH channels, symmetrically with the null path above. Retracting
|
|
4605
|
-
// to viewers only would leave `/events` emitting stall(Q1) then
|
|
4606
|
-
// stall(Q2) with no clear between them, which reads as two concurrent
|
|
4607
|
-
// holds or an unresolved first one. Nothing in this repository
|
|
4608
|
-
// subscribes to it, but the socket is a real API and an asymmetric
|
|
4609
|
-
// one is a trap for the first thing that consumes it.
|
|
4610
|
-
this.emitEvent({
|
|
4611
|
-
type: 'prompt-clear',
|
|
4612
|
-
session: session.id,
|
|
4613
|
-
label: summary.label ?? null,
|
|
4614
|
-
});
|
|
4615
|
-
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
4616
|
-
}
|
|
4617
|
-
this.promptStates.set(session.id, {
|
|
4618
|
-
signature: detected.signature,
|
|
4619
|
-
inputVersion,
|
|
4620
|
-
since: this.now(),
|
|
4621
|
-
alerted: false,
|
|
4622
|
-
prompt: detected,
|
|
4623
|
-
missingSince: null,
|
|
4624
|
-
});
|
|
4625
|
-
this.updateFeedSession(session.id, previous !== undefined);
|
|
4626
|
-
continue;
|
|
4627
|
-
}
|
|
4628
|
-
previous.signature = detected.signature;
|
|
4629
|
-
if (promptChanged)
|
|
4630
|
-
this.updateFeedSession(session.id);
|
|
4631
|
-
if (!previous.alerted && this.now() - previous.since >= stallMs) {
|
|
4632
|
-
previous.alerted = true;
|
|
4633
|
-
this.updateFeedSession(session.id);
|
|
4634
|
-
const waitingMs = this.now() - previous.since;
|
|
4635
|
-
this.audit.record('daemon', 'prompt-stall', session.id);
|
|
4636
|
-
this.logger.warn('session waiting on a prompt', {
|
|
4637
|
-
id: session.id,
|
|
4638
|
-
waitingMs,
|
|
4639
|
-
options: detected.options.length,
|
|
4640
|
-
});
|
|
4641
|
-
this.emitEvent({
|
|
4642
|
-
type: 'prompt-stall',
|
|
4643
|
-
session: session.id,
|
|
4644
|
-
label: summary.label ?? null,
|
|
4645
|
-
waitingMs,
|
|
4646
|
-
question: detected.question,
|
|
4647
|
-
options: detected.options,
|
|
4648
|
-
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4649
|
-
});
|
|
4650
|
-
// The session's own viewers get the same signal, so an open viewer
|
|
4651
|
-
// tab can badge itself without subscribing to the daemon stream.
|
|
4652
|
-
this.broadcastControl(session.id, {
|
|
4653
|
-
type: 'prompt-stall',
|
|
4654
|
-
waitingMs,
|
|
4655
|
-
question: detected.question,
|
|
4656
|
-
// The options travel to viewers as well as to /events, so the badge
|
|
4657
|
-
// can say what the choices are, not only THAT something is being
|
|
4658
|
-
// asked.
|
|
4659
|
-
options: detected.options,
|
|
4660
|
-
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
4661
|
-
});
|
|
4662
|
-
}
|
|
4653
|
+
this.updatePromptState(session, detected);
|
|
4663
4654
|
}
|
|
4664
4655
|
// Sessions that exited or were reaped take their prompt state with them.
|
|
4665
4656
|
for (const id of [...this.promptStates.keys()]) {
|
|
@@ -4671,6 +4662,137 @@ export class Daemon {
|
|
|
4671
4662
|
}
|
|
4672
4663
|
await this.nudges.tick();
|
|
4673
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
|
+
}
|
|
4674
4796
|
/** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
|
|
4675
4797
|
emitEvent(event) {
|
|
4676
4798
|
const message = JSON.stringify({ ...event, at: new Date().toISOString() });
|
|
@@ -4690,7 +4812,7 @@ export class Daemon {
|
|
|
4690
4812
|
}
|
|
4691
4813
|
}
|
|
4692
4814
|
/** Dashboard notifications carry metadata only; the page fetches text separately. */
|
|
4693
|
-
|
|
4815
|
+
emitDashboardEvent(event) {
|
|
4694
4816
|
const frame = JSON.stringify({ ...event, at: new Date().toISOString() });
|
|
4695
4817
|
for (const ws of this.dashboardEventSockets) {
|
|
4696
4818
|
if (ws.readyState === ws.OPEN)
|
|
@@ -5313,6 +5435,7 @@ export class Daemon {
|
|
|
5313
5435
|
if (held?.alerted === true) {
|
|
5314
5436
|
ws.send(JSON.stringify({
|
|
5315
5437
|
type: 'prompt-stall',
|
|
5438
|
+
since: held.since,
|
|
5316
5439
|
waitingMs: Date.now() - held.since,
|
|
5317
5440
|
question: held.prompt.question,
|
|
5318
5441
|
options: held.prompt.options,
|
|
@@ -5665,7 +5788,7 @@ export class Daemon {
|
|
|
5665
5788
|
this.audit.record(actor, 'report', session.id, {
|
|
5666
5789
|
kind: report,
|
|
5667
5790
|
chars: bytes?.length ?? text.length,
|
|
5668
|
-
...(this.audit
|
|
5791
|
+
...(this.reload?.state.config.audit?.captureContent ? { data: bytes === null ? text : bytes.toString('latin1') } : {}),
|
|
5669
5792
|
});
|
|
5670
5793
|
return;
|
|
5671
5794
|
}
|