shellpuppet 0.0.1 → 0.2.0

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.
Files changed (137) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +499 -8
  4. package/dist/cli/desktopShortcut.d.ts +22 -0
  5. package/dist/cli/desktopShortcut.js +157 -0
  6. package/dist/cli/desktopShortcut.js.map +1 -0
  7. package/dist/cli/index.d.ts +13 -0
  8. package/dist/cli/index.js +846 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/client/http.d.ts +143 -0
  11. package/dist/client/http.js +581 -0
  12. package/dist/client/http.js.map +1 -0
  13. package/dist/core/dialogs.d.ts +96 -0
  14. package/dist/core/dialogs.js +226 -0
  15. package/dist/core/dialogs.js.map +1 -0
  16. package/dist/core/echo.d.ts +71 -0
  17. package/dist/core/echo.js +249 -0
  18. package/dist/core/echo.js.map +1 -0
  19. package/dist/core/find.d.ts +34 -0
  20. package/dist/core/find.js +41 -0
  21. package/dist/core/find.js.map +1 -0
  22. package/dist/core/keys.d.ts +22 -0
  23. package/dist/core/keys.js +80 -0
  24. package/dist/core/keys.js.map +1 -0
  25. package/dist/core/manager.d.ts +96 -0
  26. package/dist/core/manager.js +271 -0
  27. package/dist/core/manager.js.map +1 -0
  28. package/dist/core/nativePty.d.ts +73 -0
  29. package/dist/core/nativePty.js +161 -0
  30. package/dist/core/nativePty.js.map +1 -0
  31. package/dist/core/policy.d.ts +61 -0
  32. package/dist/core/policy.js +143 -0
  33. package/dist/core/policy.js.map +1 -0
  34. package/dist/core/promptDetector.d.ts +109 -0
  35. package/dist/core/promptDetector.js +897 -0
  36. package/dist/core/promptDetector.js.map +1 -0
  37. package/dist/core/reasoning.d.ts +265 -0
  38. package/dist/core/reasoning.js +933 -0
  39. package/dist/core/reasoning.js.map +1 -0
  40. package/dist/core/regexBudget.d.ts +64 -0
  41. package/dist/core/regexBudget.js +103 -0
  42. package/dist/core/regexBudget.js.map +1 -0
  43. package/dist/core/renderer.d.ts +127 -0
  44. package/dist/core/renderer.js +316 -0
  45. package/dist/core/renderer.js.map +1 -0
  46. package/dist/core/selection.d.ts +6 -0
  47. package/dist/core/selection.js +48 -0
  48. package/dist/core/selection.js.map +1 -0
  49. package/dist/core/session.d.ts +565 -0
  50. package/dist/core/session.js +1450 -0
  51. package/dist/core/session.js.map +1 -0
  52. package/dist/core/types.d.ts +316 -0
  53. package/dist/core/types.js +71 -0
  54. package/dist/core/types.js.map +1 -0
  55. package/dist/core/waiter.d.ts +94 -0
  56. package/dist/core/waiter.js +310 -0
  57. package/dist/core/waiter.js.map +1 -0
  58. package/dist/core/windowsConsoleHost.d.ts +147 -0
  59. package/dist/core/windowsConsoleHost.js +588 -0
  60. package/dist/core/windowsConsoleHost.js.map +1 -0
  61. package/dist/core/windowsPtyStart.d.ts +161 -0
  62. package/dist/core/windowsPtyStart.js +236 -0
  63. package/dist/core/windowsPtyStart.js.map +1 -0
  64. package/dist/daemon/audit.d.ts +23 -0
  65. package/dist/daemon/audit.js +51 -0
  66. package/dist/daemon/audit.js.map +1 -0
  67. package/dist/daemon/auth.d.ts +197 -0
  68. package/dist/daemon/auth.js +366 -0
  69. package/dist/daemon/auth.js.map +1 -0
  70. package/dist/daemon/config.d.ts +119 -0
  71. package/dist/daemon/config.js +568 -0
  72. package/dist/daemon/config.js.map +1 -0
  73. package/dist/daemon/folderPicker.d.ts +27 -0
  74. package/dist/daemon/folderPicker.js +115 -0
  75. package/dist/daemon/folderPicker.js.map +1 -0
  76. package/dist/daemon/index.d.ts +7 -0
  77. package/dist/daemon/index.js +88 -0
  78. package/dist/daemon/index.js.map +1 -0
  79. package/dist/daemon/launchProfiles.d.ts +155 -0
  80. package/dist/daemon/launchProfiles.js +554 -0
  81. package/dist/daemon/launchProfiles.js.map +1 -0
  82. package/dist/daemon/liveness.d.ts +36 -0
  83. package/dist/daemon/liveness.js +71 -0
  84. package/dist/daemon/liveness.js.map +1 -0
  85. package/dist/daemon/logger.d.ts +7 -0
  86. package/dist/daemon/logger.js +29 -0
  87. package/dist/daemon/logger.js.map +1 -0
  88. package/dist/daemon/meta.d.ts +9 -0
  89. package/dist/daemon/meta.js +24 -0
  90. package/dist/daemon/meta.js.map +1 -0
  91. package/dist/daemon/paths.d.ts +85 -0
  92. package/dist/daemon/paths.js +154 -0
  93. package/dist/daemon/paths.js.map +1 -0
  94. package/dist/daemon/screenshot.d.ts +144 -0
  95. package/dist/daemon/screenshot.js +402 -0
  96. package/dist/daemon/screenshot.js.map +1 -0
  97. package/dist/daemon/server.d.ts +453 -0
  98. package/dist/daemon/server.js +3954 -0
  99. package/dist/daemon/server.js.map +1 -0
  100. package/dist/daemon/sessionFeed.d.ts +48 -0
  101. package/dist/daemon/sessionFeed.js +101 -0
  102. package/dist/daemon/sessionFeed.js.map +1 -0
  103. package/dist/daemon/terminalReports.d.ts +38 -0
  104. package/dist/daemon/terminalReports.js +84 -0
  105. package/dist/daemon/terminalReports.js.map +1 -0
  106. package/dist/daemon/viewerLauncher.d.ts +226 -0
  107. package/dist/daemon/viewerLauncher.js +562 -0
  108. package/dist/daemon/viewerLauncher.js.map +1 -0
  109. package/dist/daemon/viewerSync.d.ts +38 -0
  110. package/dist/daemon/viewerSync.js +83 -0
  111. package/dist/daemon/viewerSync.js.map +1 -0
  112. package/dist/mcp/config.d.ts +50 -0
  113. package/dist/mcp/config.js +95 -0
  114. package/dist/mcp/config.js.map +1 -0
  115. package/dist/mcp/index.d.ts +10 -0
  116. package/dist/mcp/index.js +78 -0
  117. package/dist/mcp/index.js.map +1 -0
  118. package/dist/mcp/tools.d.ts +66 -0
  119. package/dist/mcp/tools.js +638 -0
  120. package/dist/mcp/tools.js.map +1 -0
  121. package/dist/viewer/dashboard-folders.js +20 -0
  122. package/dist/viewer/dashboard-layout.js +52 -0
  123. package/dist/viewer/dashboard.css +67 -0
  124. package/dist/viewer/dashboard.html +44 -0
  125. package/dist/viewer/dashboard.js +1518 -0
  126. package/dist/viewer/icon-16.png +0 -0
  127. package/dist/viewer/icon-180.png +0 -0
  128. package/dist/viewer/icon-32.png +0 -0
  129. package/dist/viewer/icon-512.png +0 -0
  130. package/dist/viewer/icon.ico +0 -0
  131. package/dist/viewer/icon.svg +66 -0
  132. package/dist/viewer/index.html +61 -0
  133. package/dist/viewer/pane.js +736 -0
  134. package/dist/viewer/viewer.css +95 -0
  135. package/dist/viewer/viewer.js +84 -0
  136. package/package.json +66 -7
  137. package/index.js +0 -4
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Shape validation for `~/.shellpuppet/config.json` (design §4.3 fail-closed).
3
+ *
4
+ * Why this exists: parsed JSON is not a config until its shape has been
5
+ * checked. A string where an array belongs (`"allow": "^goose"`) must not
6
+ * reach `compilePolicy`, whose `for…of` would read it one character at a
7
+ * time as single-character rules. A shape mistake must fail CLOSED, exactly
8
+ * as a malformed pattern does.
9
+ *
10
+ * The rules:
11
+ * - No config file ⇒ pure defaults (the documented behaviour).
12
+ * - A file that cannot be read or parsed, or whose root is not a JSON object
13
+ * ⇒ the intended policy is unknowable: the policy refuses every command
14
+ * (naming the problem in each refusal) and sessionEnv falls back to
15
+ * `clean`.
16
+ * - A structurally invalid `policy` section ⇒ deny-all, problem named. No
17
+ * per-field salvage: a policy that cannot be evaluated as written must not
18
+ * be guessed at. Unknown keys INSIDE `policy` invalidate it too: a
19
+ * misspelt `deny` must not silently deny nothing.
20
+ * - Invalid `sessionEnv` ⇒ `clean`, never passthrough: environment hygiene
21
+ * is a security control, and its failure mode
22
+ * must not silently hand every session the daemon's secrets.
23
+ * - Invalid `idleMinutes` / `audit` ⇒ safe defaults, problem named
24
+ * (`captureContent` records typed secrets, so anything unclear means OFF).
25
+ * - Unknown top-level keys ⇒ reported (typo detection), config otherwise
26
+ * honoured.
27
+ *
28
+ * `parseDaemonConfig` is pure; `readDaemonConfig` adds the file read. The
29
+ * daemon stays up in every case: refusing to start would strand every
30
+ * client with no error message at all, whereas a running daemon can say
31
+ * exactly what is wrong on every refused request.
32
+ */
33
+ import type { DialogSignature } from '../core/dialogs.js';
34
+ import type { AgentSignature } from '../core/reasoning.js';
35
+ import type { PolicyConfig, SessionEnvMode } from '../core/types.js';
36
+ import type { ViewerLaunchConfig, ViewerLaunchMode } from './viewerLauncher.js';
37
+ import type { LauncherConfig } from './launchProfiles.js';
38
+ export declare const DEFAULT_VIEWER_LAUNCH_MODE: ViewerLaunchMode;
39
+ export interface DaemonConfig {
40
+ /** How clients start a missing daemon. This is read before daemon startup. */
41
+ daemon?: {
42
+ startWith?: string[];
43
+ startWithOnlyIfEnvContains?: string;
44
+ };
45
+ policy?: PolicyConfig;
46
+ /** Idle self-shutdown threshold in minutes; fractions allowed (design §2.3). */
47
+ idleMinutes?: number;
48
+ /** Session environment hygiene (design §4.6). */
49
+ sessionEnv?: SessionEnvMode;
50
+ /** Audit options (design §4.5). */
51
+ audit?: {
52
+ captureContent?: boolean;
53
+ };
54
+ /** How the viewer window is opened. */
55
+ viewer?: ViewerLaunchConfig;
56
+ /** Initial dashboard text size when the browser has no saved preference. */
57
+ dashboard?: {
58
+ fontSize?: number;
59
+ };
60
+ /**
61
+ * The named programs the dashboard may start (`launcher.profiles`, design
62
+ * §4.3). Absent means a watch-only dashboard. Invalid entries are named in
63
+ * `problems` and left out; their siblings still load.
64
+ */
65
+ launcher?: LauncherConfig;
66
+ /**
67
+ * Permission dialogs to recognise beyond the built-in ones (`dialogs.ts`):
68
+ * the entries that compile. The rest are reported and left out.
69
+ */
70
+ dialogs?: DialogSignature[];
71
+ /**
72
+ * Agent signatures beyond the built-in ones, or replacing one by name
73
+ * (`reasoning.ts`): the entries that compile. The rest are reported and
74
+ * left out.
75
+ */
76
+ agentSignatures?: AgentSignature[];
77
+ /**
78
+ * The variables each agent's sessions receive from the environment of the
79
+ * client that starts them (`agents.passEnv`, design §4.6), by agent name.
80
+ * The MCP server and the CLI hold the values and apply the lists; the
81
+ * daemon only checks them, so a mistake is reported in `daemon.log` too.
82
+ */
83
+ agentPassEnv?: Record<string, string[]>;
84
+ /**
85
+ * The variables a caller may name at start for a session that runs as no
86
+ * agent (`envNames`, design §4.6): `terminal_start`'s `envNames` and the
87
+ * CLI's `--env-name`. The MCP server and the CLI hold the values and apply
88
+ * the list; the daemon only checks it, so a mistake is reported in
89
+ * `daemon.log` too.
90
+ */
91
+ envNames?: string[];
92
+ }
93
+ export interface ParsedDaemonConfig {
94
+ config: DaemonConfig;
95
+ /** Human-readable problems. The daemon logs each one loudly at startup. */
96
+ problems: string[];
97
+ }
98
+ /**
99
+ * Whether a problem bears on the `envNames` list, for the clients that apply
100
+ * it to report alongside their own refusals: a problem with the list itself,
101
+ * the unread `mcp.passEnv`, or a `config.json` that could not be read at all,
102
+ * which leaves the list empty.
103
+ */
104
+ export declare function isEnvNamesProblem(problem: string): boolean;
105
+ /**
106
+ * The daemon.log line for a signature that ran past the regular-expression
107
+ * time budget on a screen and is set aside for a minute (`SET_ASIDE_MS`), to
108
+ * be tried again. One from config is a CONFIG PROBLEM its author can act on.
109
+ * A built-in one is not anybody's to change, and a busy machine can make an
110
+ * ordinary pattern overrun, so its line says so and asks nothing.
111
+ */
112
+ export declare function signatureOverBudgetLog(kind: 'dialog' | 'agent', name: string, builtIn: boolean): {
113
+ message: string;
114
+ meta: Record<string, string>;
115
+ };
116
+ /** Validate a parsed config value. `undefined` means "no file": pure defaults. */
117
+ export declare function parseDaemonConfig(raw: unknown): ParsedDaemonConfig;
118
+ /** Read and validate the config file. ENOENT ⇒ defaults; unreadable ⇒ fail closed. */
119
+ export declare function readDaemonConfig(home: string): ParsedDaemonConfig;
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Shape validation for `~/.shellpuppet/config.json` (design §4.3 fail-closed).
3
+ *
4
+ * Why this exists: parsed JSON is not a config until its shape has been
5
+ * checked. A string where an array belongs (`"allow": "^goose"`) must not
6
+ * reach `compilePolicy`, whose `for…of` would read it one character at a
7
+ * time as single-character rules. A shape mistake must fail CLOSED, exactly
8
+ * as a malformed pattern does.
9
+ *
10
+ * The rules:
11
+ * - No config file ⇒ pure defaults (the documented behaviour).
12
+ * - A file that cannot be read or parsed, or whose root is not a JSON object
13
+ * ⇒ the intended policy is unknowable: the policy refuses every command
14
+ * (naming the problem in each refusal) and sessionEnv falls back to
15
+ * `clean`.
16
+ * - A structurally invalid `policy` section ⇒ deny-all, problem named. No
17
+ * per-field salvage: a policy that cannot be evaluated as written must not
18
+ * be guessed at. Unknown keys INSIDE `policy` invalidate it too: a
19
+ * misspelt `deny` must not silently deny nothing.
20
+ * - Invalid `sessionEnv` ⇒ `clean`, never passthrough: environment hygiene
21
+ * is a security control, and its failure mode
22
+ * must not silently hand every session the daemon's secrets.
23
+ * - Invalid `idleMinutes` / `audit` ⇒ safe defaults, problem named
24
+ * (`captureContent` records typed secrets, so anything unclear means OFF).
25
+ * - Unknown top-level keys ⇒ reported (typo detection), config otherwise
26
+ * honoured.
27
+ *
28
+ * `parseDaemonConfig` is pure; `readDaemonConfig` adds the file read. The
29
+ * daemon stays up in every case: refusing to start would strand every
30
+ * client with no error message at all, whereas a running daemon can say
31
+ * exactly what is wrong on every refused request.
32
+ */
33
+ import * as fs from 'node:fs';
34
+ import { configPath } from './paths.js';
35
+ import { compileDialogs } from '../core/dialogs.js';
36
+ import { BUILT_IN_SIGNATURES, compileSignatures } from '../core/reasoning.js';
37
+ import { ENV_NAME_PATTERN } from '../core/types.js';
38
+ import { parseLauncher } from './launchProfiles.js';
39
+ export const DEFAULT_VIEWER_LAUNCH_MODE = 'dashboard';
40
+ const POLICY_MODES = ['allow-all', 'allowlist', 'denylist'];
41
+ const POLICY_KEYS = new Set(['mode', 'allow', 'deny', 'maxSessions']);
42
+ /**
43
+ * `mcp` is the MCP adapter's section, known here so it is not flagged; the
44
+ * daemon looks inside it only for a `passEnv`, which it reports.
45
+ */
46
+ const TOP_LEVEL_KEYS = new Set([
47
+ 'policy',
48
+ 'idleMinutes',
49
+ 'sessionEnv',
50
+ 'audit',
51
+ 'mcp',
52
+ 'viewer',
53
+ 'dashboard',
54
+ 'prompts',
55
+ 'agents',
56
+ 'envNames',
57
+ 'launcher',
58
+ 'daemon',
59
+ ]);
60
+ const DAEMON_KEYS = new Set(['startWith', 'startWithOnlyIfEnvContains']);
61
+ const VIEWER_KEYS = new Set(['launchMode', 'browserPath', 'profileDir']);
62
+ const VIEWER_LAUNCH_MODES = [
63
+ 'dashboard',
64
+ 'isolated-app',
65
+ 'default-browser',
66
+ 'no-window',
67
+ ];
68
+ /**
69
+ * Viewer launch options. An invalid value falls back to "no-window", NOT to the
70
+ * launching default: config the daemon cannot read must not cause it to start
71
+ * spawning browser windows on someone's desktop, and a viewer that did not
72
+ * open is visibly wrong in a way the operator can act on.
73
+ */
74
+ function parseViewer(raw, problems) {
75
+ if (!isRecord(raw)) {
76
+ problems.push('viewer must be an object: not opening the viewer automatically');
77
+ return { launchMode: 'no-window' };
78
+ }
79
+ for (const key of Object.keys(raw)) {
80
+ if (!VIEWER_KEYS.has(key)) {
81
+ problems.push(`viewer has an unknown key "${key}": ignored (typo?)`);
82
+ }
83
+ }
84
+ const config = {};
85
+ const launchMode = raw['launchMode'];
86
+ if (launchMode !== undefined) {
87
+ if (launchMode === 'none') {
88
+ config.launchMode = 'no-window';
89
+ }
90
+ else if (typeof launchMode === 'string' &&
91
+ VIEWER_LAUNCH_MODES.includes(launchMode)) {
92
+ config.launchMode = launchMode;
93
+ }
94
+ else {
95
+ config.launchMode = 'no-window';
96
+ problems.push(`viewer.launchMode must be one of ${VIEWER_LAUNCH_MODES.join(' | ')}: not opening the viewer automatically`);
97
+ }
98
+ }
99
+ for (const key of ['browserPath', 'profileDir']) {
100
+ const value = raw[key];
101
+ if (value === undefined)
102
+ continue;
103
+ if (typeof value === 'string' && value !== '') {
104
+ config[key] = value;
105
+ }
106
+ else {
107
+ problems.push(`viewer.${key} must be a non-empty string: ignored`);
108
+ }
109
+ }
110
+ return config;
111
+ }
112
+ function isRecord(value) {
113
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
114
+ }
115
+ function isStringArray(value) {
116
+ return Array.isArray(value) && value.every((v) => typeof v === 'string');
117
+ }
118
+ /**
119
+ * `agents.passEnv`: agent name to the variables its sessions receive. An entry
120
+ * for an agent with no signature, or that is not a list, is reported and left
121
+ * out; names that are not variable names are reported and dropped from their
122
+ * list. Nothing else is affected.
123
+ */
124
+ function parseAgentPassEnv(value, known, problems) {
125
+ if (!isRecord(value)) {
126
+ problems.push('agents.passEnv must be an object of agent names to lists of variable names: passing none');
127
+ return undefined;
128
+ }
129
+ const lists = {};
130
+ for (const [agent, names] of Object.entries(value)) {
131
+ if (!known.has(agent)) {
132
+ problems.push(`agents.passEnv names ${agent}, which has no agent signature: that entry is ignored`);
133
+ continue;
134
+ }
135
+ if (!Array.isArray(names)) {
136
+ problems.push(`agents.passEnv.${agent} must be a list of variable names: that entry is ignored`);
137
+ continue;
138
+ }
139
+ const valid = names.filter((name) => typeof name === 'string' && ENV_NAME_PATTERN.test(name));
140
+ if (valid.length !== names.length) {
141
+ problems.push(`agents.passEnv.${agent}: ignoring entries that are not variable names`);
142
+ }
143
+ lists[agent] = valid;
144
+ }
145
+ return lists;
146
+ }
147
+ /**
148
+ * Whether a problem bears on the `envNames` list, for the clients that apply
149
+ * it to report alongside their own refusals: a problem with the list itself,
150
+ * the unread `mcp.passEnv`, or a `config.json` that could not be read at all,
151
+ * which leaves the list empty.
152
+ */
153
+ export function isEnvNamesProblem(problem) {
154
+ return (problem.startsWith('envNames') ||
155
+ problem.startsWith('mcp.passEnv') ||
156
+ (problem.startsWith('config.json ') && problem.includes('refusing all commands')));
157
+ }
158
+ /**
159
+ * The daemon.log line for a signature that ran past the regular-expression
160
+ * time budget on a screen and is set aside for a minute (`SET_ASIDE_MS`), to
161
+ * be tried again. One from config is a CONFIG PROBLEM its author can act on.
162
+ * A built-in one is not anybody's to change, and a busy machine can make an
163
+ * ordinary pattern overrun, so its line says so and asks nothing.
164
+ */
165
+ export function signatureOverBudgetLog(kind, name, builtIn) {
166
+ if (builtIn) {
167
+ return {
168
+ message: 'signature set aside',
169
+ meta: {
170
+ signature: name,
171
+ note: `the built-in "${name}" ${kind} signature ran past the regular-expression time budget on a ` +
172
+ 'screen, as a busy machine can make it do; it is tried again in a minute, and there is nothing to change',
173
+ },
174
+ };
175
+ }
176
+ return {
177
+ message: 'CONFIG PROBLEM',
178
+ meta: {
179
+ problem: `the "${name}" ${kind} signature ran past the regular-expression time budget on a screen ` +
180
+ 'and is set aside for a minute at a time; if it keeps happening, simplify its patterns',
181
+ },
182
+ };
183
+ }
184
+ /** A policy that refuses every command, naming the configuration problem. */
185
+ function denyAllPolicy(reason) {
186
+ // The empty allowlist is belt-and-braces: even if configError were ever
187
+ // ignored, nothing can match an empty allow list.
188
+ return { mode: 'allowlist', allow: [], configError: reason };
189
+ }
190
+ function parsePolicy(raw, problems) {
191
+ const invalid = (detail) => {
192
+ problems.push(`policy ${detail}: refusing all commands until it is fixed`);
193
+ return denyAllPolicy(`the policy section is invalid: ${detail}.`);
194
+ };
195
+ if (!isRecord(raw))
196
+ return invalid('is not an object');
197
+ for (const key of Object.keys(raw)) {
198
+ if (!POLICY_KEYS.has(key))
199
+ return invalid(`has an unknown key "${key}"`);
200
+ }
201
+ const mode = raw['mode'] ?? 'allow-all';
202
+ if (typeof mode !== 'string' || !POLICY_MODES.includes(mode)) {
203
+ return invalid(`mode must be one of ${POLICY_MODES.join(' | ')}`);
204
+ }
205
+ for (const listName of ['allow', 'deny']) {
206
+ const list = raw[listName];
207
+ if (list !== undefined && !isStringArray(list)) {
208
+ return invalid(`${listName} must be an ARRAY of regex strings (e.g. ["^goose"])`);
209
+ }
210
+ }
211
+ const maxSessions = raw['maxSessions'];
212
+ if (maxSessions !== undefined &&
213
+ (typeof maxSessions !== 'number' || !Number.isInteger(maxSessions) || maxSessions < 1)) {
214
+ return invalid('maxSessions must be a positive integer');
215
+ }
216
+ return {
217
+ mode: mode,
218
+ ...(isStringArray(raw['allow']) ? { allow: raw['allow'] } : {}),
219
+ ...(isStringArray(raw['deny']) ? { deny: raw['deny'] } : {}),
220
+ ...(typeof maxSessions === 'number' ? { maxSessions } : {}),
221
+ };
222
+ }
223
+ /** The fail-closed result for a config whose intent is unknowable. */
224
+ function unknowableConfig(reason, problem) {
225
+ return {
226
+ config: { policy: denyAllPolicy(reason), sessionEnv: 'clean' },
227
+ problems: [problem],
228
+ };
229
+ }
230
+ /** Validate a parsed config value. `undefined` means "no file": pure defaults. */
231
+ export function parseDaemonConfig(raw) {
232
+ if (raw === undefined)
233
+ return { config: {}, problems: [] };
234
+ if (!isRecord(raw)) {
235
+ return unknowableConfig('config.json is not a JSON object.', 'config.json is not a JSON object: refusing all commands and using the clean session env until it is fixed');
236
+ }
237
+ const problems = [];
238
+ const config = {};
239
+ for (const key of Object.keys(raw)) {
240
+ if (!TOP_LEVEL_KEYS.has(key)) {
241
+ problems.push(`config.json has an unknown key "${key}": ignored (typo?)`);
242
+ }
243
+ }
244
+ if (raw['policy'] !== undefined)
245
+ config.policy = parsePolicy(raw['policy'], problems);
246
+ if (raw['daemon'] !== undefined) {
247
+ const daemon = raw['daemon'];
248
+ if (!isRecord(daemon)) {
249
+ problems.push('daemon must be an object: starting directly');
250
+ }
251
+ else {
252
+ let valid = true;
253
+ for (const key of Object.keys(daemon)) {
254
+ if (!DAEMON_KEYS.has(key)) {
255
+ problems.push(`daemon has an unknown key "${key}": starting directly`);
256
+ valid = false;
257
+ }
258
+ }
259
+ const startWith = daemon['startWith'];
260
+ const condition = daemon['startWithOnlyIfEnvContains'];
261
+ if (startWith !== undefined && (!Array.isArray(startWith) || startWith.length < 1 ||
262
+ startWith.length > 16 || startWith.some((part) => typeof part !== 'string' ||
263
+ part.trim() === '' || part.length > 1024 || part.includes('\0')))) {
264
+ problems.push('daemon.startWith must have 1 to 16 non-blank strings of at most 1024 characters: starting directly');
265
+ valid = false;
266
+ }
267
+ if (condition !== undefined && (typeof condition !== 'string' || condition.trim() === '' ||
268
+ condition.length > 256)) {
269
+ problems.push('daemon.startWithOnlyIfEnvContains must be a non-blank string of at most 256 characters: starting directly');
270
+ valid = false;
271
+ }
272
+ if (valid && isStringArray(startWith)) {
273
+ config.daemon = {
274
+ startWith,
275
+ ...(typeof condition === 'string' ? { startWithOnlyIfEnvContains: condition } : {}),
276
+ };
277
+ }
278
+ }
279
+ }
280
+ const sessionEnv = raw['sessionEnv'];
281
+ if (sessionEnv !== undefined) {
282
+ if (sessionEnv === 'passthrough' || sessionEnv === 'clean' || isStringArray(sessionEnv)) {
283
+ config.sessionEnv = sessionEnv;
284
+ }
285
+ else {
286
+ config.sessionEnv = 'clean';
287
+ problems.push('sessionEnv must be "passthrough", "clean" or an array of variable names: using "clean"');
288
+ }
289
+ }
290
+ const idleMinutes = raw['idleMinutes'];
291
+ if (idleMinutes !== undefined) {
292
+ if (typeof idleMinutes === 'number' && Number.isFinite(idleMinutes) && idleMinutes > 0) {
293
+ config.idleMinutes = idleMinutes;
294
+ }
295
+ else {
296
+ problems.push('idleMinutes must be a positive number of minutes: using the default');
297
+ }
298
+ }
299
+ const audit = raw['audit'];
300
+ if (audit !== undefined) {
301
+ const captureContent = isRecord(audit) ? audit['captureContent'] : undefined;
302
+ if (isRecord(audit) && (captureContent === undefined || typeof captureContent === 'boolean')) {
303
+ config.audit = {
304
+ ...(typeof captureContent === 'boolean' ? { captureContent } : {}),
305
+ };
306
+ }
307
+ else {
308
+ problems.push('audit.captureContent must be a boolean: content capture stays off');
309
+ }
310
+ }
311
+ if (raw['viewer'] !== undefined)
312
+ config.viewer = parseViewer(raw['viewer'], problems);
313
+ if (raw['dashboard'] !== undefined) {
314
+ const dashboard = raw['dashboard'];
315
+ if (!isRecord(dashboard)) {
316
+ problems.push('dashboard must be an object: ignored');
317
+ }
318
+ else {
319
+ config.dashboard = {};
320
+ for (const key of Object.keys(dashboard)) {
321
+ if (key !== 'fontSize')
322
+ problems.push(`dashboard has an unknown key "${key}": ignored (typo?)`);
323
+ }
324
+ if (dashboard['fontSize'] !== undefined) {
325
+ const size = dashboard['fontSize'];
326
+ if (typeof size === 'number' && Number.isInteger(size) && size >= 8 && size <= 32) {
327
+ config.dashboard.fontSize = size;
328
+ }
329
+ else {
330
+ problems.push('dashboard.fontSize must be an integer from 8 to 32: ignored');
331
+ }
332
+ }
333
+ }
334
+ }
335
+ // Extra dialog signatures. A broken one is reported and left out, and the
336
+ // built-in ones are recognised regardless: detection that misses a dialog
337
+ // costs only what it cost before, so there is nothing to fail closed for.
338
+ const prompts = raw['prompts'];
339
+ if (prompts !== undefined) {
340
+ const dialogs = isRecord(prompts) ? prompts['dialogs'] : undefined;
341
+ const shapeOk = isRecord(prompts) &&
342
+ Object.keys(prompts).every((key) => key === 'dialogs') &&
343
+ (dialogs === undefined || Array.isArray(dialogs));
344
+ if (!shapeOk) {
345
+ problems.push('prompts must be an object whose only key is dialogs, an array: using the built-in dialogs only');
346
+ }
347
+ else if (Array.isArray(dialogs)) {
348
+ const compiled = compileDialogs(dialogs);
349
+ problems.push(...compiled.problems);
350
+ config.dialogs = compiled.usable.map((index) => dialogs[index]);
351
+ }
352
+ }
353
+ // Extra agent signatures. A broken one is reported and left out; a session
354
+ // that would have needed it is refused by the readers, which fail closed.
355
+ const agents = raw['agents'];
356
+ if (agents !== undefined) {
357
+ if (!isRecord(agents)) {
358
+ problems.push('agents must be an object with signatures (an array) and passEnv (an object): using the ' +
359
+ 'built-in signatures and passing no variables');
360
+ }
361
+ else {
362
+ // Each part stands alone: a mistake in one never knocks out the other.
363
+ for (const key of Object.keys(agents)) {
364
+ if (key !== 'signatures' && key !== 'passEnv')
365
+ problems.push(`agents has an unknown key ${key}: ignored`);
366
+ }
367
+ const signatures = agents['signatures'];
368
+ if (signatures !== undefined && !Array.isArray(signatures)) {
369
+ problems.push('agents.signatures must be an array: using the built-in signatures only');
370
+ }
371
+ else if (Array.isArray(signatures)) {
372
+ const compiled = compileSignatures(signatures);
373
+ problems.push(...compiled.problems);
374
+ config.agentSignatures = compiled.usable.map((index) => signatures[index]);
375
+ }
376
+ if (agents['passEnv'] !== undefined) {
377
+ const known = new Set([
378
+ ...BUILT_IN_SIGNATURES.map((signature) => signature.name),
379
+ ...(config.agentSignatures ?? []).map((signature) => signature.name),
380
+ ]);
381
+ const passEnv = parseAgentPassEnv(agents['passEnv'], known, problems);
382
+ if (passEnv !== undefined)
383
+ config.agentPassEnv = passEnv;
384
+ }
385
+ }
386
+ }
387
+ // Dashboard launch profiles. A broken entry is named and left out; its
388
+ // siblings still load, and nothing here changes policy.
389
+ if (raw['launcher'] !== undefined) {
390
+ const known = new Set([
391
+ ...BUILT_IN_SIGNATURES.map((signature) => signature.name),
392
+ ...(config.agentSignatures ?? []).map((signature) => signature.name),
393
+ ]);
394
+ const parsed = parseLauncher(raw['launcher'], known);
395
+ config.launcher = parsed.launcher;
396
+ problems.push(...parsed.problems);
397
+ }
398
+ // The variables a caller may name at start. A list under `mcp.passEnv` is
399
+ // not read: it passes nothing, and the problem says where the list goes.
400
+ const envNames = raw['envNames'];
401
+ if (envNames !== undefined) {
402
+ if (!Array.isArray(envNames)) {
403
+ problems.push('envNames in config.json must be an array of variable names: passing none');
404
+ }
405
+ else {
406
+ const valid = envNames.filter((name) => typeof name === 'string' && ENV_NAME_PATTERN.test(name));
407
+ if (valid.length !== envNames.length) {
408
+ problems.push('envNames in config.json: ignoring entries that are not variable names');
409
+ }
410
+ config.envNames = valid;
411
+ }
412
+ }
413
+ const mcp = raw['mcp'];
414
+ if (isRecord(mcp) && mcp['passEnv'] !== undefined) {
415
+ problems.push('mcp.passEnv is not read, so nothing passes from it: the variables a caller may name at start ' +
416
+ 'are read from envNames, at the top level of config.json');
417
+ }
418
+ return { config, problems };
419
+ }
420
+ /** Locate a JSON syntax error without using V8's message, which may quote config text. */
421
+ function jsonErrorLocation(raw) {
422
+ class InvalidJson extends Error {
423
+ offset;
424
+ constructor(offset) {
425
+ super('invalid JSON');
426
+ this.offset = offset;
427
+ }
428
+ }
429
+ let at = 0;
430
+ const fail = () => { throw new InvalidJson(at); };
431
+ const space = () => {
432
+ while (at < raw.length && /[ \t\r\n]/.test(raw[at] ?? ''))
433
+ at++;
434
+ };
435
+ const expectChar = (ch) => {
436
+ if (raw[at] !== ch)
437
+ fail();
438
+ at++;
439
+ };
440
+ const string = () => {
441
+ expectChar('"');
442
+ while (at < raw.length) {
443
+ const ch = raw[at] ?? '';
444
+ if (ch === '"') {
445
+ at++;
446
+ return;
447
+ }
448
+ if (ch.charCodeAt(0) < 0x20)
449
+ fail();
450
+ if (ch === '\\') {
451
+ at++;
452
+ const escaped = raw[at] ?? '';
453
+ if (escaped === 'u') {
454
+ at++;
455
+ for (let n = 0; n < 4; n++, at++) {
456
+ if (!/[0-9a-fA-F]/.test(raw[at] ?? ''))
457
+ fail();
458
+ }
459
+ continue;
460
+ }
461
+ if (!/["\\/bfnrt]/.test(escaped))
462
+ fail();
463
+ }
464
+ at++;
465
+ }
466
+ fail();
467
+ };
468
+ const value = (depth) => {
469
+ if (depth > 256)
470
+ fail();
471
+ space();
472
+ const ch = raw[at];
473
+ if (ch === '"') {
474
+ string();
475
+ return;
476
+ }
477
+ if (ch === '{') {
478
+ at++;
479
+ space();
480
+ if (raw[at] === '}') {
481
+ at++;
482
+ return;
483
+ }
484
+ for (;;) {
485
+ string();
486
+ space();
487
+ expectChar(':');
488
+ value(depth + 1);
489
+ space();
490
+ if (raw[at] === '}') {
491
+ at++;
492
+ return;
493
+ }
494
+ expectChar(',');
495
+ space();
496
+ }
497
+ }
498
+ if (ch === '[') {
499
+ at++;
500
+ space();
501
+ if (raw[at] === ']') {
502
+ at++;
503
+ return;
504
+ }
505
+ for (;;) {
506
+ value(depth + 1);
507
+ space();
508
+ if (raw[at] === ']') {
509
+ at++;
510
+ return;
511
+ }
512
+ expectChar(',');
513
+ }
514
+ }
515
+ for (const literal of ['true', 'false', 'null']) {
516
+ if (ch === literal[0]) {
517
+ for (const expected of literal)
518
+ expectChar(expected);
519
+ return;
520
+ }
521
+ }
522
+ if (ch === '-' || (ch !== undefined && /[0-9]/.test(ch))) {
523
+ const number = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(raw.slice(at));
524
+ if (number === null)
525
+ return fail();
526
+ at += number[0].length;
527
+ return;
528
+ }
529
+ fail();
530
+ };
531
+ try {
532
+ value(0);
533
+ space();
534
+ if (at < raw.length)
535
+ fail();
536
+ }
537
+ catch (error) {
538
+ if (!(error instanceof InvalidJson))
539
+ at = 0;
540
+ else
541
+ at = error.offset;
542
+ }
543
+ const lines = raw.slice(0, at).split(/\r\n|\r|\n/);
544
+ return { line: lines.length, column: (lines.at(-1) ?? '').length + 1 };
545
+ }
546
+ /** Read and validate the config file. ENOENT ⇒ defaults; unreadable ⇒ fail closed. */
547
+ export function readDaemonConfig(home) {
548
+ let rawText;
549
+ try {
550
+ rawText = fs.readFileSync(configPath(home), 'utf8');
551
+ }
552
+ catch (error) {
553
+ if (error.code === 'ENOENT') {
554
+ return { config: {}, problems: [] };
555
+ }
556
+ return unknowableConfig(`config.json exists but could not be read (${String(error)}).`, `config.json could not be read (${String(error)}): refusing all commands`);
557
+ }
558
+ let raw;
559
+ try {
560
+ raw = JSON.parse(rawText);
561
+ }
562
+ catch {
563
+ const { line, column } = jsonErrorLocation(rawText);
564
+ return unknowableConfig(`config.json is not valid JSON at line ${String(line)}, column ${String(column)}.`, `config.json is not valid JSON at line ${String(line)}, column ${String(column)}: refusing all commands`);
565
+ }
566
+ return parseDaemonConfig(raw);
567
+ }
568
+ //# sourceMappingURL=config.js.map