@hearsay-tools/squawk 0.19.0-dev.9086 → 0.19.0-dev.9088

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 (48) hide show
  1. package/dist/built-in-cli-commands.js +6 -1
  2. package/dist/built-in-cli-commands.js.map +1 -1
  3. package/dist/ci-wait/controller.d.ts +7 -7
  4. package/dist/cli-dispatch.d.ts +2 -1
  5. package/dist/cli-dispatch.js +20 -7
  6. package/dist/cli-dispatch.js.map +1 -1
  7. package/dist/contract/hosts.d.ts +161 -0
  8. package/dist/contract/index.js +116 -0
  9. package/dist/core/cli-registry.d.ts +1 -0
  10. package/dist/core/cli-registry.js.map +1 -1
  11. package/dist/features/automations/tools.d.ts +8 -8
  12. package/dist/features/hosts/cli.d.ts +59 -0
  13. package/dist/features/hosts/cli.js +28 -17
  14. package/dist/features/hosts/cli.js.map +1 -1
  15. package/dist/features/hosts/host-server-cli.d.ts +13 -0
  16. package/dist/features/hosts/host-server-cli.js +246 -0
  17. package/dist/features/hosts/host-server-cli.js.map +1 -0
  18. package/dist/features/hosts/host-server.d.ts +51 -0
  19. package/dist/features/hosts/host-server.js +407 -0
  20. package/dist/features/hosts/host-server.js.map +1 -0
  21. package/dist/features/hosts/index.d.ts +2 -0
  22. package/dist/features/hosts/index.js +12 -0
  23. package/dist/features/hosts/index.js.map +1 -1
  24. package/dist/features/hosts/runtime-archive.d.ts +103 -0
  25. package/dist/features/hosts/runtime-archive.js +619 -0
  26. package/dist/features/hosts/runtime-archive.js.map +1 -0
  27. package/dist/features/hosts/start-methods.d.ts +76 -0
  28. package/dist/features/hosts/start-methods.js +234 -0
  29. package/dist/features/hosts/start-methods.js.map +1 -0
  30. package/dist/features/hosts/tar-gz.d.ts +30 -0
  31. package/dist/features/hosts/tar-gz.js +143 -0
  32. package/dist/features/hosts/tar-gz.js.map +1 -0
  33. package/dist/host-server-store.d.ts +103 -0
  34. package/dist/host-server-store.js +348 -0
  35. package/dist/host-server-store.js.map +1 -0
  36. package/dist/index.js +2 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/serve-command.d.ts +10 -1
  39. package/dist/serve-command.js +63 -9
  40. package/dist/serve-command.js.map +1 -1
  41. package/dist/server/live-routes.d.ts +6 -6
  42. package/dist/server/providers-routes.d.ts +58 -58
  43. package/dist/server/runner-install-routes.d.ts +10 -10
  44. package/dist/server/runs-routes.d.ts +995 -995
  45. package/dist/server/server.d.ts +699 -699
  46. package/dist/server/workspace-identity-routes.d.ts +5 -5
  47. package/dist/server/workspace-routes.d.ts +85 -85
  48. package/package.json +4 -4
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Persistence-checked start methods for remote `hsq serve` (spec § Architecture 2 step 3,
3
+ * hearsay-tools/squawk#4539).
4
+ *
5
+ * A remote server must outlive every SSH session (including the tunnel's). `detectStartMethod`
6
+ * checks the machine before spawning anything:
7
+ * 1. User systemd with linger on (`systemd-run --user`); tries `loginctl enable-linger` for the
8
+ * current user first when linger is off.
9
+ * 2. A new session with no terminal via `detached-process.ts` (`spawnDetached`), only where there
10
+ * is no logind or logind reports `KillUserProcesses=no`.
11
+ * 3. Neither holds: start nothing and report `cannot-persist` with the one command the operator
12
+ * runs (`loginctl enable-linger <user>`).
13
+ */
14
+ import { type ChildProcess } from 'node:child_process';
15
+ import type { HostServerStartMethod } from '../../contract/index.js';
16
+ import { spawnDetached } from '../../detached-process.ts';
17
+ import type { Home } from '../../home/home.ts';
18
+ export interface StartMethodCommandResult {
19
+ code: number | null;
20
+ stdout: string;
21
+ stderr: string;
22
+ error?: string | undefined;
23
+ }
24
+ export interface StartMethodCommandOptions {
25
+ timeoutMs?: number | undefined;
26
+ env?: NodeJS.ProcessEnv | undefined;
27
+ }
28
+ export type StartMethodDetection = {
29
+ ok: true;
30
+ method: HostServerStartMethod;
31
+ } | {
32
+ ok: false;
33
+ method: 'cannot-persist';
34
+ operatorCommand: string;
35
+ reason: string;
36
+ };
37
+ export interface StartMethodsDeps {
38
+ platform?: NodeJS.Platform | undefined;
39
+ username?: string | undefined;
40
+ runCommand?: ((file: string, args: readonly string[], options?: StartMethodCommandOptions) => Promise<StartMethodCommandResult>) | undefined;
41
+ pathExists?: ((path: string) => boolean) | undefined;
42
+ spawnDetachedProcess?: typeof spawnDetached | undefined;
43
+ }
44
+ export declare function defaultRunCommand(file: string, args: readonly string[], options?: StartMethodCommandOptions): Promise<StartMethodCommandResult>;
45
+ /** This Squawk runtime's own CLI entry argv (mirrors `features/jobs/command.ts`). */
46
+ export declare function ownServeEntryArgv(): string[];
47
+ /**
48
+ * Determine which persistence-checked start method is safe on this machine.
49
+ * Never starts any process; only probes systemd/logind state (and attempts `loginctl enable-linger`
50
+ * for the own user when user systemd is reachable and linger is off).
51
+ */
52
+ export declare function detectStartMethod(deps?: StartMethodsDeps): Promise<StartMethodDetection>;
53
+ export interface SpawnHostServerInput {
54
+ method: HostServerStartMethod;
55
+ home: Home;
56
+ starterInstallId: string;
57
+ entryArgv?: readonly string[] | undefined;
58
+ env?: NodeJS.ProcessEnv | undefined;
59
+ }
60
+ export interface SpawnedHostServer {
61
+ method: HostServerStartMethod;
62
+ unitName?: string | undefined;
63
+ child?: ChildProcess | undefined;
64
+ }
65
+ /**
66
+ * Environment for a managed remote server, shared identically by both `systemd-user` and
67
+ * `detached` starts: inherits the remote machine's own environment from `hsq host-server ensure`,
68
+ * drops only SSH-session-bound variables (`SSH_*`, `XDG_SESSION_*`, `DISPLAY`; keeps
69
+ * `XDG_RUNTIME_DIR`) and names `systemd-run` cannot accept, and sets `HSQ_REMOTE=1`.
70
+ */
71
+ export declare function buildHostedServerEnv(baseEnv: NodeJS.ProcessEnv): Record<string, string>;
72
+ /**
73
+ * Spawn `hsq serve --no-project --no-open --port 0 --bind-host 127.0.0.1 --start-claim <id>` in
74
+ * hosted mode using the previously checked persistence method.
75
+ */
76
+ export declare function spawnHostServerProcess(input: SpawnHostServerInput, deps?: StartMethodsDeps): Promise<SpawnedHostServer>;
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Persistence-checked start methods for remote `hsq serve` (spec § Architecture 2 step 3,
3
+ * hearsay-tools/squawk#4539).
4
+ *
5
+ * A remote server must outlive every SSH session (including the tunnel's). `detectStartMethod`
6
+ * checks the machine before spawning anything:
7
+ * 1. User systemd with linger on (`systemd-run --user`); tries `loginctl enable-linger` for the
8
+ * current user first when linger is off.
9
+ * 2. A new session with no terminal via `detached-process.ts` (`spawnDetached`), only where there
10
+ * is no logind or logind reports `KillUserProcesses=no`.
11
+ * 3. Neither holds: start nothing and report `cannot-persist` with the one command the operator
12
+ * runs (`loginctl enable-linger <user>`).
13
+ */
14
+ import { execFile as execFileCallback } from 'node:child_process';
15
+ import { randomBytes } from 'node:crypto';
16
+ import { existsSync } from 'node:fs';
17
+ import { userInfo } from 'node:os';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { promisify } from 'node:util';
20
+ import { shellQuote } from '../../core/shell-env.js';
21
+ import { spawnDetached } from '../../detached-process.js';
22
+ import { privateDirectory } from '../../home/private-files.js';
23
+ const execFile = promisify(execFileCallback);
24
+ const PROBE_TIMEOUT_MS = 10_000;
25
+ const SYSTEMD_RUN_TIMEOUT_MS = 15_000;
26
+ const SIMPLE_USERNAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
27
+ /**
28
+ * Valid POSIX/systemd environment variable name (`env_name_is_valid` in systemd): ASCII letter or
29
+ * underscore followed by ASCII letters, digits, or underscores. Non-conforming names (such as
30
+ * bash-exported functions `BASH_FUNC_*%%`, empty names, leading digits, or names containing
31
+ * punctuation like `-` or `.`) are rejected by `systemd-run --setenv=NAME` and skipped for both
32
+ * start methods so `systemd-user` and `detached` receive the exact same environment set.
33
+ */
34
+ const VALID_ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
35
+ export async function defaultRunCommand(file, args, options = {}) {
36
+ try {
37
+ const result = await execFile(file, [...args], {
38
+ encoding: 'utf8',
39
+ timeout: options.timeoutMs ?? PROBE_TIMEOUT_MS,
40
+ maxBuffer: 1024 * 1024,
41
+ ...(options.env !== undefined ? { env: options.env } : {}),
42
+ });
43
+ return { code: 0, stdout: result.stdout, stderr: result.stderr };
44
+ }
45
+ catch (error) {
46
+ const err = error;
47
+ return {
48
+ code: typeof err.code === 'number' ? err.code : null,
49
+ stdout: err.stdout ?? '',
50
+ stderr: err.stderr ?? '',
51
+ error: err.message ?? String(error),
52
+ };
53
+ }
54
+ }
55
+ /** This Squawk runtime's own CLI entry argv (mirrors `features/jobs/command.ts`). */
56
+ export function ownServeEntryArgv() {
57
+ const source = import.meta.url.endsWith('.ts');
58
+ const entry = fileURLToPath(new URL(source ? '../../index.ts' : '../../hsq.js', import.meta.url));
59
+ return [process.execPath, ...(source ? ['--import', import.meta.resolve('tsx')] : []), entry];
60
+ }
61
+ function formatLingerOperatorCommand(username) {
62
+ const renderedUser = SIMPLE_USERNAME_PATTERN.test(username) ? username : shellQuote(username);
63
+ return `loginctl enable-linger ${renderedUser}`;
64
+ }
65
+ function hasLingerYes(stdout) {
66
+ return /(?:^|\n)Linger=yes(?:\s|$)/.test(stdout) || stdout.trim() === 'yes';
67
+ }
68
+ async function checkUserSystemdWithLinger(username, runCommand) {
69
+ const userBus = await runCommand('systemctl', ['--user', 'show-environment']);
70
+ if (userBus.code !== 0)
71
+ return false;
72
+ const initial = await runCommand('loginctl', ['show-user', username, '-p', 'Linger']);
73
+ if (initial.code === 0 && hasLingerYes(initial.stdout))
74
+ return true;
75
+ // Try enabling linger for our own user (succeeds without sudo where policy allows it).
76
+ await runCommand('loginctl', ['enable-linger', username]);
77
+ const rechecked = await runCommand('loginctl', ['show-user', username, '-p', 'Linger']);
78
+ return rechecked.code === 0 && hasLingerYes(rechecked.stdout);
79
+ }
80
+ async function readKillUserProcesses(runCommand) {
81
+ const busctl = await runCommand('busctl', [
82
+ 'get-property',
83
+ 'org.freedesktop.login1',
84
+ '/org/freedesktop/login1',
85
+ 'org.freedesktop.login1.Manager',
86
+ 'KillUserProcesses',
87
+ ]);
88
+ if (busctl.code === 0) {
89
+ const trimmed = busctl.stdout.trim();
90
+ if (trimmed === 'b false')
91
+ return 'no';
92
+ if (trimmed === 'b true')
93
+ return 'yes';
94
+ }
95
+ const loginctl = await runCommand('loginctl', ['show-session', '-p', 'KillUserProcesses']);
96
+ if (loginctl.code === 0) {
97
+ if (/(?:^|\n)KillUserProcesses=no(?:\s|$)/.test(loginctl.stdout))
98
+ return 'no';
99
+ if (/(?:^|\n)KillUserProcesses=yes(?:\s|$)/.test(loginctl.stdout))
100
+ return 'yes';
101
+ }
102
+ return 'unknown';
103
+ }
104
+ /**
105
+ * Determine which persistence-checked start method is safe on this machine.
106
+ * Never starts any process; only probes systemd/logind state (and attempts `loginctl enable-linger`
107
+ * for the own user when user systemd is reachable and linger is off).
108
+ */
109
+ export async function detectStartMethod(deps = {}) {
110
+ const platform = deps.platform ?? process.platform;
111
+ if (platform !== 'linux') {
112
+ return { ok: true, method: 'detached' };
113
+ }
114
+ const runCommand = deps.runCommand ?? defaultRunCommand;
115
+ const pathExists = deps.pathExists ?? existsSync;
116
+ const username = deps.username ?? userInfo().username;
117
+ const operatorCommand = formatLingerOperatorCommand(username);
118
+ if (await checkUserSystemdWithLinger(username, runCommand)) {
119
+ return { ok: true, method: 'systemd-user' };
120
+ }
121
+ const killUserProcesses = await readKillUserProcesses(runCommand);
122
+ if (killUserProcesses === 'no') {
123
+ return { ok: true, method: 'detached' };
124
+ }
125
+ if (killUserProcesses === 'yes') {
126
+ return {
127
+ ok: false,
128
+ method: 'cannot-persist',
129
+ operatorCommand,
130
+ reason: 'logind ends user processes when SSH sessions close (KillUserProcesses=yes) and linger is not enabled.',
131
+ };
132
+ }
133
+ const hasSystemdLogind = pathExists('/run/systemd/system') || pathExists('/run/systemd/seats');
134
+ if (!hasSystemdLogind) {
135
+ return { ok: true, method: 'detached' };
136
+ }
137
+ return {
138
+ ok: false,
139
+ method: 'cannot-persist',
140
+ operatorCommand,
141
+ reason: 'systemd/logind is active without linger and KillUserProcesses=no could not be confirmed.',
142
+ };
143
+ }
144
+ function buildHostedServeArgs(entryArgv, starterInstallId) {
145
+ return [
146
+ ...entryArgv,
147
+ 'serve',
148
+ '--no-project',
149
+ '--no-open',
150
+ '--port',
151
+ '0',
152
+ '--bind-host',
153
+ '127.0.0.1',
154
+ '--start-claim',
155
+ starterInstallId,
156
+ ];
157
+ }
158
+ function isSessionBoundEnvVar(name) {
159
+ return name.startsWith('SSH_') || name.startsWith('XDG_SESSION_') || name === 'DISPLAY';
160
+ }
161
+ /**
162
+ * Environment for a managed remote server, shared identically by both `systemd-user` and
163
+ * `detached` starts: inherits the remote machine's own environment from `hsq host-server ensure`,
164
+ * drops only SSH-session-bound variables (`SSH_*`, `XDG_SESSION_*`, `DISPLAY`; keeps
165
+ * `XDG_RUNTIME_DIR`) and names `systemd-run` cannot accept, and sets `HSQ_REMOTE=1`.
166
+ */
167
+ export function buildHostedServerEnv(baseEnv) {
168
+ const entries = [];
169
+ for (const [name, value] of Object.entries(baseEnv)) {
170
+ if (value === undefined)
171
+ continue;
172
+ if (isSessionBoundEnvVar(name))
173
+ continue;
174
+ if (!VALID_ENV_NAME_PATTERN.test(name))
175
+ continue;
176
+ entries.push([name, value]);
177
+ }
178
+ entries.push(['HSQ_REMOTE', '1']);
179
+ return Object.fromEntries(entries);
180
+ }
181
+ /** Escape literal `$` as `$$` for systemd `ExecStart` arguments (never the executable at index 0). */
182
+ function escapeSystemdArg(arg) {
183
+ return arg.replaceAll('$', () => '$$');
184
+ }
185
+ /**
186
+ * Spawn `hsq serve --no-project --no-open --port 0 --bind-host 127.0.0.1 --start-claim <id>` in
187
+ * hosted mode using the previously checked persistence method.
188
+ */
189
+ export async function spawnHostServerProcess(input, deps = {}) {
190
+ privateDirectory(input.home.state);
191
+ const entryArgv = input.entryArgv ?? ownServeEntryArgv();
192
+ const hostedEnv = buildHostedServerEnv(input.env ?? process.env);
193
+ const serveArgv = buildHostedServeArgs(entryArgv, input.starterInstallId);
194
+ if (input.method === 'systemd-user') {
195
+ const runCommand = deps.runCommand ?? defaultRunCommand;
196
+ const unitName = `hsq-host-server-${Date.now().toString(36)}-${randomBytes(4).toString('hex')}`;
197
+ // Pass variable names only (`--setenv=NAME`) so systemd-run reads values from its own `env`
198
+ // (`hostedEnv`) and no inherited value appears in argv or `/proc/<pid>/cmdline`.
199
+ const envArgs = Object.keys(hostedEnv).map((name) => `--setenv=${name}`);
200
+ const args = [
201
+ '--user',
202
+ `--unit=${unitName}`,
203
+ '--collect',
204
+ '--no-block',
205
+ `--working-directory=${input.home.state}`,
206
+ ...envArgs,
207
+ '--',
208
+ serveArgv[0],
209
+ ...serveArgv.slice(1).map(escapeSystemdArg),
210
+ ];
211
+ const result = await runCommand('systemd-run', args, {
212
+ timeoutMs: SYSTEMD_RUN_TIMEOUT_MS,
213
+ env: hostedEnv,
214
+ });
215
+ if (result.code !== 0) {
216
+ const detail = result.stderr.trim() || result.error || `exit code ${String(result.code)}`;
217
+ throw new Error(`systemd-run --user failed to start host server: ${detail}`);
218
+ }
219
+ return { method: 'systemd-user', unitName };
220
+ }
221
+ const spawnDetachedFn = deps.spawnDetachedProcess ?? spawnDetached;
222
+ const child = spawnDetachedFn(serveArgv[0], serveArgv.slice(1), {
223
+ cwd: input.home.state,
224
+ env: hostedEnv,
225
+ stdio: 'ignore',
226
+ });
227
+ await new Promise((resolveSpawn, rejectSpawn) => {
228
+ child.once('spawn', resolveSpawn);
229
+ child.once('error', rejectSpawn);
230
+ });
231
+ child.unref();
232
+ return { method: 'detached', child };
233
+ }
234
+ //# sourceMappingURL=start-methods.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-methods.js","sourceRoot":"","sources":["../../../src/features/hosts/start-methods.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAqB,MAAM,oBAAoB,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA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AK,CAAC,KAAK,EAAE,CAAC;IACd,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AACvC,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Minimal streaming POSIX ustar + PAX `.tar.gz` writer (`node:zlib`).
3
+ *
4
+ * Unlike `home/migration-files.ts` (which synchronously tars a single directory tree with a
5
+ * 255-byte ustar limit), runtime archives assemble files from multiple resolved package roots
6
+ * into virtual `node_modules/...` paths that may exceed 255 bytes and stream asynchronously
7
+ * into an SSH child's stdin. Standard GNU and BSD `tar -xzf -` extract the output directly.
8
+ */
9
+ import { type Writable } from 'node:stream';
10
+ export type TarEntryInput = {
11
+ name: string;
12
+ kind: 'dir';
13
+ mode?: number;
14
+ mtimeSeconds?: number;
15
+ } | {
16
+ name: string;
17
+ kind: 'file';
18
+ mode: number;
19
+ content: Buffer;
20
+ mtimeSeconds?: number;
21
+ };
22
+ export declare class TarArchiveError extends Error {
23
+ constructor(message: string);
24
+ }
25
+ /** Encode one entry (with an optional PAX extended header for paths that overflow ustar). */
26
+ export declare function encodeTarEntry(entry: TarEntryInput): Buffer[];
27
+ /** Stream tar entries as gzipped bytes into `destination`. */
28
+ export declare function streamTarGz(destination: Writable, entries: Iterable<TarEntryInput>): Promise<void>;
29
+ /** Build a `.tar.gz` buffer from entries. */
30
+ export declare function buildTarGzBuffer(entries: Iterable<TarEntryInput>): Promise<Buffer>;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Minimal streaming POSIX ustar + PAX `.tar.gz` writer (`node:zlib`).
3
+ *
4
+ * Unlike `home/migration-files.ts` (which synchronously tars a single directory tree with a
5
+ * 255-byte ustar limit), runtime archives assemble files from multiple resolved package roots
6
+ * into virtual `node_modules/...` paths that may exceed 255 bytes and stream asynchronously
7
+ * into an SSH child's stdin. Standard GNU and BSD `tar -xzf -` extract the output directly.
8
+ */
9
+ import { Readable } from 'node:stream';
10
+ import { pipeline } from 'node:stream/promises';
11
+ import { createGzip } from 'node:zlib';
12
+ export class TarArchiveError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = 'TarArchiveError';
16
+ }
17
+ }
18
+ const BLOCK_SIZE = 512;
19
+ function normalizeArchiveName(raw) {
20
+ const cleaned = raw.replace(/\/+$/, '');
21
+ if (!cleaned || cleaned.includes('\0') || cleaned.includes('\\') || cleaned.startsWith('/')) {
22
+ throw new TarArchiveError(`Refusing unsafe archive entry path: ${JSON.stringify(raw)}`);
23
+ }
24
+ const parts = cleaned.split('/');
25
+ if (parts.some((part) => part === '' || part === '.' || part === '..')) {
26
+ throw new TarArchiveError(`Refusing traversal archive entry path: ${JSON.stringify(raw)}`);
27
+ }
28
+ return cleaned;
29
+ }
30
+ function writeOctal(header, value, offset, width) {
31
+ const octal = Math.max(0, Math.floor(value)).toString(8);
32
+ if (octal.length >= width) {
33
+ throw new TarArchiveError(`Tar header value ${value} overflows width ${width}`);
34
+ }
35
+ header.write(`${octal.padStart(width - 1, '0')}\0`, offset, width, 'ascii');
36
+ }
37
+ function finalizeHeader(header) {
38
+ header.fill(32, 148, 156);
39
+ let checksum = 0;
40
+ for (let i = 0; i < BLOCK_SIZE; i++)
41
+ checksum += header[i];
42
+ header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii');
43
+ return header;
44
+ }
45
+ function splitUstarName(name) {
46
+ if (Buffer.byteLength(name) <= 100)
47
+ return { prefix: '', shortName: name };
48
+ const slashIndices = [];
49
+ for (let i = name.indexOf('/'); i !== -1; i = name.indexOf('/', i + 1))
50
+ slashIndices.push(i);
51
+ for (let i = slashIndices.length - 1; i >= 0; i--) {
52
+ const idx = slashIndices[i];
53
+ const prefix = name.slice(0, idx);
54
+ const shortName = name.slice(idx + 1);
55
+ if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(shortName) <= 100) {
56
+ return { prefix, shortName };
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+ function formatPaxRecord(key, value) {
62
+ const suffix = ` ${key}=${value}\n`;
63
+ let len = Buffer.byteLength(suffix) + 1;
64
+ while (true) {
65
+ const total = Buffer.byteLength(String(len)) + Buffer.byteLength(suffix);
66
+ if (total === len)
67
+ return Buffer.from(`${len}${suffix}`, 'utf8');
68
+ len = total;
69
+ }
70
+ }
71
+ function buildHeaderBlock(shortName, prefix, size, mode, typeFlag, mtimeSeconds) {
72
+ const header = Buffer.alloc(BLOCK_SIZE);
73
+ header.write(shortName, 0, 100, 'utf8');
74
+ writeOctal(header, mode & 0o777, 100, 8);
75
+ writeOctal(header, 0, 108, 8);
76
+ writeOctal(header, 0, 116, 8);
77
+ writeOctal(header, size, 124, 12);
78
+ writeOctal(header, mtimeSeconds, 136, 12);
79
+ header.write(typeFlag, 156, 1, 'ascii');
80
+ header.write('ustar\0', 257, 6, 'ascii');
81
+ header.write('00', 263, 2, 'ascii');
82
+ if (prefix)
83
+ header.write(prefix, 345, 155, 'utf8');
84
+ return finalizeHeader(header);
85
+ }
86
+ function padBlock(size) {
87
+ const rem = size % BLOCK_SIZE;
88
+ return rem === 0 ? Buffer.alloc(0) : Buffer.alloc(BLOCK_SIZE - rem);
89
+ }
90
+ /** Encode one entry (with an optional PAX extended header for paths that overflow ustar). */
91
+ export function encodeTarEntry(entry) {
92
+ const normalized = normalizeArchiveName(entry.name);
93
+ const tarName = entry.kind === 'dir' ? `${normalized}/` : normalized;
94
+ const mtime = entry.mtimeSeconds ?? 0;
95
+ const content = entry.kind === 'file' ? entry.content : Buffer.alloc(0);
96
+ const mode = entry.kind === 'dir' ? (entry.mode ?? 0o755) : entry.mode;
97
+ const typeFlag = entry.kind === 'dir' ? '5' : '0';
98
+ const parts = [];
99
+ const ustar = splitUstarName(tarName);
100
+ if (ustar) {
101
+ parts.push(buildHeaderBlock(ustar.shortName, ustar.prefix, content.length, mode, typeFlag, mtime));
102
+ }
103
+ else {
104
+ const paxData = formatPaxRecord('path', tarName);
105
+ parts.push(buildHeaderBlock('PaxHeaders/entry', '', paxData.length, 0o644, 'x', mtime));
106
+ parts.push(paxData, padBlock(paxData.length));
107
+ const fallbackName = Buffer.from(tarName, 'utf8').subarray(0, 100).toString('utf8');
108
+ parts.push(buildHeaderBlock(fallbackName, '', content.length, mode, typeFlag, mtime));
109
+ }
110
+ if (content.length > 0) {
111
+ parts.push(content, padBlock(content.length));
112
+ }
113
+ return parts;
114
+ }
115
+ function* generateTarChunks(entries) {
116
+ for (const entry of entries) {
117
+ for (const part of encodeTarEntry(entry)) {
118
+ if (part.length > 0)
119
+ yield part;
120
+ }
121
+ }
122
+ yield Buffer.alloc(BLOCK_SIZE * 2);
123
+ }
124
+ /** Stream tar entries as gzipped bytes into `destination`. */
125
+ export async function streamTarGz(destination, entries) {
126
+ await pipeline(Readable.from(generateTarChunks(entries)), createGzip({ level: 6 }), destination);
127
+ }
128
+ /** Build a `.tar.gz` buffer from entries. */
129
+ export async function buildTarGzBuffer(entries) {
130
+ const chunks = [];
131
+ const gzip = createGzip({ level: 6 });
132
+ const done = new Promise((resolveDone, rejectDone) => {
133
+ gzip.on('data', (chunk) => chunks.push(chunk));
134
+ gzip.once('error', rejectDone);
135
+ gzip.once('end', () => resolveDone(Buffer.concat(chunks)));
136
+ });
137
+ for (const chunk of generateTarChunks(entries)) {
138
+ gzip.write(chunk);
139
+ }
140
+ gzip.end();
141
+ return done;
142
+ }
143
+ //# sourceMappingURL=tar-gz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tar-gz.js","sourceRoot":"","sources":["../../../src/features/hosts/tar-gz.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,QAAQ,EAAiB,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAMvC,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IA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CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QAC/B,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;IACH,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;QAC/C,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IACD,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,103 @@
1
+ import { type HostServerClaimPhase } from './contract/index.js';
2
+ import { type RecordedProcess } from './core/process-stat.ts';
3
+ import type { Home } from './home/home.ts';
4
+ export declare const HOST_SERVER_DB_FILE = "host-server.db";
5
+ export declare function hostServerDbPath(home: Pick<Home, 'state'>): string;
6
+ export interface HostServerClaim {
7
+ pid: number;
8
+ startToken?: string | undefined;
9
+ phase: HostServerClaimPhase;
10
+ port: number | null;
11
+ version: string;
12
+ starterInstallId: string;
13
+ updatedAt: string;
14
+ }
15
+ export interface HostServerStoreDeps {
16
+ isProcessLive?: ((entry: RecordedProcess) => boolean) | undefined;
17
+ now?: (() => Date) | undefined;
18
+ }
19
+ export type HostServerStoreErrorCode = 'unreadable' | 'invalid_input';
20
+ export declare class HostServerStoreError extends Error {
21
+ readonly code: HostServerStoreErrorCode;
22
+ readonly dbPath: string;
23
+ constructor(code: HostServerStoreErrorCode, dbPath: string, message: string);
24
+ }
25
+ export interface ClaimStartInput {
26
+ pid: number;
27
+ startToken?: string | undefined;
28
+ version: string;
29
+ starterInstallId: string;
30
+ }
31
+ export type ClaimStartResult = {
32
+ outcome: 'claimed';
33
+ claim: HostServerClaim;
34
+ replaced: boolean;
35
+ } | {
36
+ outcome: 'already-claimed';
37
+ claim: HostServerClaim;
38
+ } | {
39
+ outcome: 'paused';
40
+ starterInstallId: string;
41
+ };
42
+ export interface MarkRunningInput {
43
+ pid: number;
44
+ startToken?: string | undefined;
45
+ port: number;
46
+ starterInstallId: string;
47
+ }
48
+ export type MarkRunningResult = {
49
+ outcome: 'running';
50
+ claim: HostServerClaim;
51
+ } | {
52
+ outcome: 'paused';
53
+ starterInstallId: string;
54
+ } | {
55
+ outcome: 'lost-claim';
56
+ liveOwner?: HostServerClaim | undefined;
57
+ };
58
+ export interface HostServerStateSnapshot {
59
+ dbPath: string;
60
+ claim?: HostServerClaim | undefined;
61
+ claimLive: boolean;
62
+ paused: boolean;
63
+ pausedStarters: string[];
64
+ }
65
+ export interface PauseAndReadResult {
66
+ dbPath: string;
67
+ paused: true;
68
+ claim?: HostServerClaim | undefined;
69
+ claimLive: boolean;
70
+ ownedLiveClaim?: HostServerClaim | undefined;
71
+ }
72
+ export interface ResumeHostServerResult {
73
+ dbPath: string;
74
+ resumed: true;
75
+ wasPaused: boolean;
76
+ }
77
+ /**
78
+ * First action of `hsq serve --start-claim <starterInstallId>`: atomically check for a pause
79
+ * record or live claim, and if clear, write this process's `starting` claim row.
80
+ */
81
+ export declare function claimHostServerStart(home: Pick<Home, 'state'>, input: ClaimStartInput, deps?: HostServerStoreDeps): ClaimStartResult;
82
+ /**
83
+ * Promote this process's `starting` claim to `running` with its bound port after the server
84
+ * listens and holds its cockpit lease. Never recreates a deleted claim; reports `paused` if a
85
+ * stop recorded a pause while starting.
86
+ */
87
+ export declare function markHostServerRunning(home: Pick<Home, 'state'>, input: MarkRunningInput, deps?: HostServerStoreDeps): MarkRunningResult;
88
+ /**
89
+ * Read-only snapshot of `<state>/host-server.db`. Never creates the database file when absent;
90
+ * throws `HostServerStoreError('unreadable', dbPath)` when an existing file cannot be read.
91
+ */
92
+ export declare function readHostServerState(home: Pick<Home, 'state'>, starterInstallId?: string, deps?: HostServerStoreDeps): HostServerStateSnapshot;
93
+ /**
94
+ * Atomic `stop` decision: write the pause record for `starterInstallId` and read the start claim
95
+ * in one `BEGIN IMMEDIATE` transaction. Only a live claim whose `starterInstallId` matches is
96
+ * returned as `ownedLiveClaim` to be signalled.
97
+ */
98
+ export declare function pauseAndReadHostServerClaim(home: Pick<Home, 'state'>, starterInstallId: string, deps?: HostServerStoreDeps): PauseAndReadResult;
99
+ /**
100
+ * Atomic `resume` decision: remove the pause record for `starterInstallId` in one
101
+ * `BEGIN IMMEDIATE` transaction.
102
+ */
103
+ export declare function resumeHostServer(home: Pick<Home, 'state'>, starterInstallId: string): ResumeHostServerResult;