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,71 @@
1
+ /**
2
+ * Whether a recorded daemon is still running, as opposed to whether it
3
+ * answers (design §2.3). Under load a daemon can take seconds to answer
4
+ * `/health`, and its state file must never be cleared, nor a second daemon
5
+ * started, on that account: the first daemon would keep running with every
6
+ * session in it, and no new client could reach it again.
7
+ *
8
+ * Running means both:
9
+ * - its process exists, which a signal-0 probe tells; and
10
+ * - its port accepts a TCP connection. The operating system completes the
11
+ * handshake from the listening socket's accept queue even while the
12
+ * daemon's event loop is busy, and refuses it at once when nothing listens.
13
+ *
14
+ * Together they guard against a reused pid after a crash or a reboot: an
15
+ * unrelated process may then own the recorded pid, but not also listen on the
16
+ * recorded port. They also read a stopping daemon as gone, since it stops
17
+ * listening before it ends its sessions.
18
+ *
19
+ * The limit is the accept queue, which is finite. A daemon stuck for so long
20
+ * that its queue fills (232 waiting connections on Windows with Node 22, as
21
+ * measured) refuses further connections, as if it had gone, and is then taken
22
+ * for gone.
23
+ */
24
+ import * as net from 'node:net';
25
+ /** A refusal arrives within milliseconds; this only bounds a probe that hangs. */
26
+ const PORT_PROBE_TIMEOUT_MS = 5_000;
27
+ /** Whether a process with this pid exists. */
28
+ export function processExists(pid) {
29
+ // Signal 0 to pid 0 or a negative pid addresses a process group, not one
30
+ // process.
31
+ if (!Number.isInteger(pid) || pid <= 0)
32
+ return false;
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ }
37
+ catch (error) {
38
+ // EPERM: the process exists but belongs to another user.
39
+ return error.code === 'EPERM';
40
+ }
41
+ }
42
+ /**
43
+ * Whether something accepts a TCP connection on this loopback port. A probe
44
+ * that is neither accepted nor refused within the bound counts as accepted:
45
+ * something is there, and taking a daemon for gone is the mistake to avoid.
46
+ */
47
+ export function portAccepts(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
48
+ if (!Number.isInteger(port) || port <= 0 || port > 65_535)
49
+ return Promise.resolve(false);
50
+ return new Promise((resolve) => {
51
+ const socket = net.connect({ host: '127.0.0.1', port });
52
+ const settle = (accepted) => {
53
+ socket.destroy();
54
+ resolve(accepted);
55
+ };
56
+ socket.once('connect', () => {
57
+ settle(true);
58
+ });
59
+ socket.once('error', () => {
60
+ settle(false);
61
+ });
62
+ socket.setTimeout(timeoutMs, () => {
63
+ settle(true);
64
+ });
65
+ });
66
+ }
67
+ /** Whether the daemon a state record names is still running. */
68
+ export async function daemonRunning(record) {
69
+ return processExists(record.pid) && (await portAccepts(record.port));
70
+ }
71
+ //# sourceMappingURL=liveness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"liveness.js","sourceRoot":"","sources":["../../src/daemon/liveness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAEhC,kFAAkF;AAClF,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAEpC,8CAA8C;AAC9C,MAAM,UAAU,aAAa,CAAC,GAAW;IACvC,yEAAyE;IACzE,WAAW;IACX,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,yDAAyD;QACzD,OAAQ,KAA+B,CAAC,IAAI,KAAK,OAAO,CAAC;IAC3D,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,SAAS,GAAG,qBAAqB;IACzE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,GAAG,MAAM;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACzF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;QACxD,MAAM,MAAM,GAAG,CAAC,QAAiB,EAAQ,EAAE;YACzC,MAAM,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO,CAAC,QAAQ,CAAC,CAAC;QACpB,CAAC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YAC1B,MAAM,CAAC,IAAI,CAAC,CAAC;QACf,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE;YACxB,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,EAAE;YAChC,MAAM,CAAC,IAAI,CAAC,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,gEAAgE;AAChE,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,MAAqC;IACvE,OAAO,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACvE,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * File-backed logger for the daemon. The daemon runs fully detached with
3
+ * `stdio: 'ignore'`, so a log file is the only place its story can go.
4
+ * Logging must never crash the daemon, so failures are swallowed.
5
+ */
6
+ import type { Logger } from '../core/types.js';
7
+ export declare function createFileLogger(filePath: string): Logger;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * File-backed logger for the daemon. The daemon runs fully detached with
3
+ * `stdio: 'ignore'`, so a log file is the only place its story can go.
4
+ * Logging must never crash the daemon, so failures are swallowed.
5
+ */
6
+ import * as fs from 'node:fs';
7
+ export function createFileLogger(filePath) {
8
+ const write = (level, message, meta) => {
9
+ try {
10
+ const line = JSON.stringify({
11
+ time: new Date().toISOString(),
12
+ level,
13
+ message,
14
+ ...(meta !== undefined ? { meta } : {}),
15
+ }) + '\n';
16
+ fs.appendFileSync(filePath, line);
17
+ }
18
+ catch {
19
+ // Never let logging take the daemon down.
20
+ }
21
+ };
22
+ return {
23
+ debug: (m, meta) => write('debug', m, meta),
24
+ info: (m, meta) => write('info', m, meta),
25
+ warn: (m, meta) => write('warn', m, meta),
26
+ error: (m, meta) => write('error', m, meta),
27
+ };
28
+ }
29
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/daemon/logger.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAG9B,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAC/C,MAAM,KAAK,GAAG,CAAC,KAAa,EAAE,OAAe,EAAE,IAA8B,EAAQ,EAAE;QACrF,IAAI,CAAC;YACH,MAAM,IAAI,GACR,IAAI,CAAC,SAAS,CAAC;gBACb,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBAC9B,KAAK;gBACL,OAAO;gBACP,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACxC,CAAC,GAAG,IAAI,CAAC;YACZ,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;QAAC,MAAM,CAAC;YACP,0CAA0C;QAC5C,CAAC;IACH,CAAC,CAAC;IACF,OAAO;QACL,KAAK,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC;QAC3C,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC;QACzC,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC;QACzC,KAAK,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC;KAC5C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Package metadata at runtime. Works from `dist/daemon/` and from `src/daemon/`
3
+ * under the test runner, because both sit two levels below the package root.
4
+ */
5
+ export declare function packageVersion(): string;
6
+ /** The oldest Node major line supported: `engines` in package.json says the same. */
7
+ export declare const MIN_NODE_MAJOR = 22;
8
+ /** Enforce the Node floor with a clear error (design §9): no installer does it. */
9
+ export declare function assertNodeVersion(minMajor?: number): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Package metadata at runtime. Works from `dist/daemon/` and from `src/daemon/`
3
+ * under the test runner, because both sit two levels below the package root.
4
+ */
5
+ import { createRequire } from 'node:module';
6
+ let cached = null;
7
+ export function packageVersion() {
8
+ if (cached === null) {
9
+ const require = createRequire(import.meta.url);
10
+ cached = require('../../package.json').version;
11
+ }
12
+ return cached;
13
+ }
14
+ /** The oldest Node major line supported: `engines` in package.json says the same. */
15
+ export const MIN_NODE_MAJOR = 22;
16
+ /** Enforce the Node floor with a clear error (design §9): no installer does it. */
17
+ export function assertNodeVersion(minMajor = MIN_NODE_MAJOR) {
18
+ const major = Number(process.versions.node.split('.')[0]);
19
+ if (major < minMajor) {
20
+ throw new Error(`ShellPuppet requires Node ${String(minMajor)}+, but you are running ` +
21
+ `${process.versions.node}. Upgrade Node and try again.`);
22
+ }
23
+ }
24
+ //# sourceMappingURL=meta.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meta.js","sourceRoot":"","sources":["../../src/daemon/meta.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAM5C,IAAI,MAAM,GAAkB,IAAI,CAAC;AAEjC,MAAM,UAAU,cAAc;IAC5B,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/C,MAAM,GAAI,OAAO,CAAC,oBAAoB,CAAiB,CAAC,OAAO,CAAC;IAClE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,qFAAqF;AACrF,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;AAEjC,mFAAmF;AACnF,MAAM,UAAU,iBAAiB,CAAC,QAAQ,GAAG,cAAc;IACzD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,6BAA6B,MAAM,CAAC,QAAQ,CAAC,yBAAyB;YACpE,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,+BAA+B,CAC1D,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `~/.shellpuppet/` layout, permission hardening and the daemon state file
3
+ * (design §2.2, §2.3, §4.1).
4
+ *
5
+ * Everything honours `SHELLPUPPET_HOME` so tests (and unusual setups) can
6
+ * isolate themselves completely from the real per-user directory.
7
+ */
8
+ /** Daemon discovery record: written atomically, read by every client. */
9
+ export interface DaemonState {
10
+ port: number;
11
+ token: string;
12
+ pid: number;
13
+ version: string;
14
+ startedAt: string;
15
+ /** Set by the daemon entry from the client's internal start marker. */
16
+ startedWrapped?: boolean;
17
+ }
18
+ export declare function shellpuppetHome(env?: NodeJS.ProcessEnv): string;
19
+ export declare function daemonStatePath(home: string): string;
20
+ export declare function daemonLogPath(home: string): string;
21
+ export declare function configPath(home: string): string;
22
+ /**
23
+ * Create the home directory if absent and harden its permissions on first
24
+ * creation (design §4.1). `fs.chmod` is a near-no-op on Windows, so there we
25
+ * strip ACL inheritance and grant only the current user, with `(OI)(CI)` so
26
+ * files created inside inherit the restriction. POSIX gets a real 0700.
27
+ *
28
+ * Hardening failures are reported, not fatal: a working daemon with a warning
29
+ * beats a dead one, and the token file being unreadable to others is
30
+ * defence-in-depth on top of loopback binding + bearer auth.
31
+ */
32
+ export declare function ensureHome(home: string): Promise<{
33
+ created: boolean;
34
+ warning?: string;
35
+ }>;
36
+ /**
37
+ * What the state file holds: a daemon record; content that is not one (an
38
+ * emptied, truncated or hand-edited file), kept so that only that same content
39
+ * is ever removed; nothing; or a read that failed, which says nothing about
40
+ * the content and so is left alone.
41
+ */
42
+ export type DaemonStateFile = {
43
+ kind: 'record';
44
+ state: DaemonState;
45
+ } | {
46
+ kind: 'not-a-record';
47
+ raw: string;
48
+ } | {
49
+ kind: 'missing';
50
+ } | {
51
+ kind: 'unreadable';
52
+ };
53
+ export declare function inspectDaemonState(home: string): DaemonStateFile;
54
+ export declare function readDaemonState(home: string): DaemonState | null;
55
+ export declare function removeDaemonState(home: string): void;
56
+ /**
57
+ * Remove the state file only while it still names `record`'s daemon, so that
58
+ * clearing a stale record cannot delete one that another daemon has just
59
+ * claimed in its place.
60
+ */
61
+ export declare function removeDaemonStateIf(home: string, record: {
62
+ pid: number;
63
+ port: number;
64
+ }): void;
65
+ /**
66
+ * Remove a state file that holds no daemon record, only while it still holds
67
+ * exactly the content `raw` that was judged. A claim links a complete file
68
+ * into place, so a record claimed in the meantime stays; a writer outside
69
+ * ShellPuppet that rewrites the file in place can still lose its write.
70
+ */
71
+ export declare function removeDaemonStateIfNotARecord(home: string, raw: string): void;
72
+ /**
73
+ * Atomically CLAIM the state file (design §2.2's crash-safe startup, extended
74
+ * for the auto-start race). Two daemons racing must not both believe they won:
75
+ *
76
+ * 1. content is written to a temp file in the same directory (never partial);
77
+ * 2. `fs.link(temp, daemon.json)` publishes it: link() fails with EEXIST if
78
+ * the file exists, so exactly one racer succeeds. (A plain rename() would
79
+ * overwrite and let the LAST writer win while both think they did.)
80
+ *
81
+ * Returns false when a file is already there. The caller then judges what it
82
+ * holds: it defers to a running daemon, or clears a record whose daemon has
83
+ * gone, or a file that holds no record, and retries.
84
+ */
85
+ export declare function claimDaemonState(home: string, state: DaemonState): boolean;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * `~/.shellpuppet/` layout, permission hardening and the daemon state file
3
+ * (design §2.2, §2.3, §4.1).
4
+ *
5
+ * Everything honours `SHELLPUPPET_HOME` so tests (and unusual setups) can
6
+ * isolate themselves completely from the real per-user directory.
7
+ */
8
+ import { execFile } from 'node:child_process';
9
+ import * as fs from 'node:fs';
10
+ import * as os from 'node:os';
11
+ import * as path from 'node:path';
12
+ import { promisify } from 'node:util';
13
+ const execFileAsync = promisify(execFile);
14
+ export function shellpuppetHome(env = process.env) {
15
+ return env['SHELLPUPPET_HOME'] ?? path.join(os.homedir(), '.shellpuppet');
16
+ }
17
+ export function daemonStatePath(home) {
18
+ return path.join(home, 'daemon.json');
19
+ }
20
+ export function daemonLogPath(home) {
21
+ return path.join(home, 'daemon.log');
22
+ }
23
+ export function configPath(home) {
24
+ return path.join(home, 'config.json');
25
+ }
26
+ /**
27
+ * Create the home directory if absent and harden its permissions on first
28
+ * creation (design §4.1). `fs.chmod` is a near-no-op on Windows, so there we
29
+ * strip ACL inheritance and grant only the current user, with `(OI)(CI)` so
30
+ * files created inside inherit the restriction. POSIX gets a real 0700.
31
+ *
32
+ * Hardening failures are reported, not fatal: a working daemon with a warning
33
+ * beats a dead one, and the token file being unreadable to others is
34
+ * defence-in-depth on top of loopback binding + bearer auth.
35
+ */
36
+ export async function ensureHome(home) {
37
+ if (fs.existsSync(home))
38
+ return { created: false };
39
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
40
+ if (process.platform === 'win32') {
41
+ const user = process.env['USERNAME'];
42
+ if (user === undefined || user === '') {
43
+ return { created: true, warning: 'USERNAME not set: directory ACL not hardened' };
44
+ }
45
+ try {
46
+ await execFileAsync('icacls', [home, '/inheritance:r', '/grant:r', `${user}:(OI)(CI)F`], { windowsHide: true });
47
+ }
48
+ catch (error) {
49
+ return { created: true, warning: `icacls hardening failed: ${String(error)}` };
50
+ }
51
+ }
52
+ else {
53
+ fs.chmodSync(home, 0o700);
54
+ }
55
+ return { created: true };
56
+ }
57
+ export function inspectDaemonState(home) {
58
+ let raw;
59
+ try {
60
+ raw = fs.readFileSync(daemonStatePath(home), 'utf8');
61
+ }
62
+ catch (error) {
63
+ return error.code === 'ENOENT'
64
+ ? { kind: 'missing' }
65
+ : { kind: 'unreadable' };
66
+ }
67
+ const state = parseDaemonState(raw);
68
+ return state !== null ? { kind: 'record', state } : { kind: 'not-a-record', raw };
69
+ }
70
+ function parseDaemonState(raw) {
71
+ try {
72
+ const parsed = JSON.parse(raw);
73
+ if (typeof parsed === 'object' &&
74
+ parsed !== null &&
75
+ typeof parsed.port === 'number' &&
76
+ typeof parsed.token === 'string' &&
77
+ typeof parsed.pid === 'number') {
78
+ return parsed;
79
+ }
80
+ return null;
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ export function readDaemonState(home) {
87
+ const file = inspectDaemonState(home);
88
+ return file.kind === 'record' ? file.state : null;
89
+ }
90
+ export function removeDaemonState(home) {
91
+ try {
92
+ fs.unlinkSync(daemonStatePath(home));
93
+ }
94
+ catch {
95
+ // Already gone, which is fine.
96
+ }
97
+ }
98
+ /**
99
+ * Remove the state file only while it still names `record`'s daemon, so that
100
+ * clearing a stale record cannot delete one that another daemon has just
101
+ * claimed in its place.
102
+ */
103
+ export function removeDaemonStateIf(home, record) {
104
+ const current = readDaemonState(home);
105
+ if (current !== null && current.pid === record.pid && current.port === record.port) {
106
+ removeDaemonState(home);
107
+ }
108
+ }
109
+ /**
110
+ * Remove a state file that holds no daemon record, only while it still holds
111
+ * exactly the content `raw` that was judged. A claim links a complete file
112
+ * into place, so a record claimed in the meantime stays; a writer outside
113
+ * ShellPuppet that rewrites the file in place can still lose its write.
114
+ */
115
+ export function removeDaemonStateIfNotARecord(home, raw) {
116
+ const current = inspectDaemonState(home);
117
+ if (current.kind === 'not-a-record' && current.raw === raw) {
118
+ removeDaemonState(home);
119
+ }
120
+ }
121
+ /**
122
+ * Atomically CLAIM the state file (design §2.2's crash-safe startup, extended
123
+ * for the auto-start race). Two daemons racing must not both believe they won:
124
+ *
125
+ * 1. content is written to a temp file in the same directory (never partial);
126
+ * 2. `fs.link(temp, daemon.json)` publishes it: link() fails with EEXIST if
127
+ * the file exists, so exactly one racer succeeds. (A plain rename() would
128
+ * overwrite and let the LAST writer win while both think they did.)
129
+ *
130
+ * Returns false when a file is already there. The caller then judges what it
131
+ * holds: it defers to a running daemon, or clears a record whose daemon has
132
+ * gone, or a file that holds no record, and retries.
133
+ */
134
+ export function claimDaemonState(home, state) {
135
+ const target = daemonStatePath(home);
136
+ const temp = path.join(home, `daemon.json.${String(state.pid)}.tmp`);
137
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2), { mode: 0o600 });
138
+ try {
139
+ fs.linkSync(temp, target);
140
+ return true;
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ finally {
146
+ try {
147
+ fs.unlinkSync(temp);
148
+ }
149
+ catch {
150
+ // Best effort.
151
+ }
152
+ }
153
+ }
154
+ //# sourceMappingURL=paths.js.map
@@ -0,0 +1 @@
1
+ {"version":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;AAED;;;;;GAKG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAAY,EAAE,GAAW;IACrE,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,OAAO,CAAC,IAAI,KAAK,cAAc,IAAI,OAAO,CAAC,GAAG,KAAK,GAAG,EAAE,CAAC;QAC3D,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,KAAkB;IAC/D,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrE,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACxE,IAAI,CAAC;QACH,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC1B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;YAAS,CAAC;QACT,IAAI,CAAC;YACH,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;QAAC,MAAM,CAAC;YACP,eAAe;QACjB,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * A picture of the viewer, as a browser draws it (design §5).
3
+ *
4
+ * The daemon's text snapshot is what the agent reads; the viewer is what the
5
+ * human sees, and the two can disagree: when the renderer is right and only
6
+ * the page is wrong, no text tool can tell. This module opens the real viewer
7
+ * page in the same Chromium the isolated viewer window uses, headless, drives
8
+ * it over the DevTools protocol and returns the pixels plus the text of each
9
+ * row xterm drew. It uses the WebSocket client the daemon already depends on,
10
+ * and no bundled browser (viewerLauncher.ts says why).
11
+ *
12
+ * The page is opened in capture mode (`capture=1`): chrome hidden, the grid
13
+ * held at the daemon's geometry, never a resize sent and a flag raised once
14
+ * the first snapshot has been drawn, which is what this waits on. A
15
+ * screenshot must not change what the program sees.
16
+ *
17
+ * Daemon-side only; logging through the injected logger.
18
+ */
19
+ import WebSocket from 'ws';
20
+ import type { Logger } from '../core/types.js';
21
+ export interface CaptureOptions {
22
+ /** A Chromium-family binary, as `findBrowser()` reports it. */
23
+ browser: string;
24
+ /** The viewer URL, viewer grant included. Capture mode is added here. */
25
+ viewerUrl: string;
26
+ /** Browser window size in CSS pixels; the grid scales its font to fill it. */
27
+ width: number;
28
+ height: number;
29
+ /** Viewport rows the reasoning filter hid; covered before the picture is taken. */
30
+ hiddenRows?: readonly number[];
31
+ /** Budget for the whole capture, browser start to screenshot. */
32
+ timeoutMs?: number;
33
+ /**
34
+ * Open the page as a viewer that may drive the grid, as a human's window
35
+ * does, rather than in capture mode. Readiness is then the probe below,
36
+ * which such a call should always give.
37
+ */
38
+ drive?: boolean;
39
+ /**
40
+ * An expression evaluated in the page, whose value comes back as `probe`.
41
+ * The picture waits for it to be truthy: after the first paint in capture
42
+ * mode, as the whole of readiness when driving.
43
+ */
44
+ probe?: string;
45
+ /** Script installed before navigation, for browser integration probes. */
46
+ beforeNavigateScript?: string;
47
+ /** Browser integration tests may slow the renderer to match CI runners. */
48
+ cpuThrottlingRate?: number;
49
+ /** A test-only expression read after a capture times out. */
50
+ timeoutProbe?: string;
51
+ /** Browser integration tests can finish at the probe after closing their page. */
52
+ probeOnly?: boolean;
53
+ /** Test-only DevTools interaction after the readiness probe succeeds. */
54
+ interact?: (page: {
55
+ evaluate: (expression: string) => Promise<unknown>;
56
+ send: (method: string, params?: Record<string, unknown>, browserWideOrSession?: boolean | string) => Promise<unknown>;
57
+ }) => Promise<unknown>;
58
+ /**
59
+ * The folder the capture's own browser profile is made in, created when
60
+ * absent. The daemon passes `captureProfileRoot(home)`, which it sweeps of
61
+ * leftovers; a direct caller that gives none gets the system's temporary
62
+ * folder.
63
+ */
64
+ profileRoot?: string;
65
+ logger?: Logger;
66
+ }
67
+ /** Where the daemon makes capture profiles: a folder of its own in its home. */
68
+ export declare function captureProfileRoot(home: string): string;
69
+ /**
70
+ * When a profile folder that could not be removed as its capture ended is
71
+ * tried again. On Windows a browser's last child processes can hold files in
72
+ * it for a while after the browser itself has exited, longer under load.
73
+ */
74
+ export declare const PROFILE_RETRY_DELAYS_MS: number[];
75
+ /**
76
+ * How old a leftover profile folder must be before a sweep removes it: far
77
+ * longer than a capture can run (`MAX_CAPTURE_TIMEOUT_MS`, plus the wait for
78
+ * the browser to exit), so a capture still running is never swept.
79
+ */
80
+ export declare const STALE_PROFILE_AGE_MS: number;
81
+ /**
82
+ * Remove a capture's profile folder. One that cannot be removed yet is tried
83
+ * again after each of `retryDelaysMs`, on timers that never keep the process
84
+ * alive, and one still there after the last is left for the sweep at the next
85
+ * daemon start. Resolves with whether the first attempt removed it.
86
+ */
87
+ export declare function removeCaptureProfile(profileDir: string, logger: Logger, retryDelaysMs?: readonly number[], remove?: (dir: string) => Promise<void>): Promise<boolean>;
88
+ /**
89
+ * Remove the capture profiles left in `root`: only folders named as a capture
90
+ * names them, and only those untouched for `minAgeMs`. Resolves with how many
91
+ * were removed. Nothing here throws: a folder that cannot be removed now is
92
+ * left for the next sweep.
93
+ */
94
+ export declare function sweepCaptureProfiles(root: string, logger: Logger, minAgeMs?: number, now?: number): Promise<number>;
95
+ export interface Capture {
96
+ png: Buffer;
97
+ /** The picture's dimensions, read from the PNG itself. */
98
+ width: number;
99
+ height: number;
100
+ /** What `probe` evaluated to, when one was given. */
101
+ probe?: unknown;
102
+ /**
103
+ * The text of each viewport row as xterm drew it: right-trimmed, trailing
104
+ * blank rows dropped. That is the same shape as the daemon snapshot's lines,
105
+ * so the two can be compared directly.
106
+ */
107
+ rows: string[];
108
+ }
109
+ /**
110
+ * Budget for a whole capture: starting the browser, connecting to DevTools,
111
+ * loading the page, waiting for its first snapshot and the screenshot
112
+ * itself. Cold starts dominate the figure and vary widely: a capture that
113
+ * worked took 20.8 s on a cold Windows CI runner. So the default is 45 s,
114
+ * about twice that.
115
+ */
116
+ export declare const DEFAULT_CAPTURE_TIMEOUT_MS = 45000;
117
+ /** The range a caller may ask for instead. */
118
+ export declare const MIN_CAPTURE_TIMEOUT_MS = 1000;
119
+ export declare const MAX_CAPTURE_TIMEOUT_MS = 120000;
120
+ /**
121
+ * The smallest DevTools client this needs: request ids in, results out.
122
+ * Exported for its unit test only.
123
+ */
124
+ export declare class DevTools {
125
+ private readonly ws;
126
+ private deadline;
127
+ private nextId;
128
+ private readonly pending;
129
+ constructor(ws: WebSocket, deadline: number);
130
+ extendDeadline(ms: number): void;
131
+ send<T>(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<T>;
132
+ }
133
+ /**
134
+ * How the capture browser is started: headless, DevTools on a port the OS
135
+ * picks, its own profile, and the switches that keep the browser's own
136
+ * background requests off (`QUIET_BROWSER_SWITCHES`).
137
+ */
138
+ export declare function captureBrowserArgs(profileDir: string, width: number, height: number): string[];
139
+ /**
140
+ * Open the viewer page headless, wait for its first snapshot to be drawn,
141
+ * and return the pixels and the rows. Throws when the browser will not start,
142
+ * DevTools will not answer or the page does not paint within the budget.
143
+ */
144
+ export declare function captureViewer(options: CaptureOptions): Promise<Capture>;