@venturewild/workspace 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,216 +1,216 @@
1
- // Lifecycle owner for the bmo-sync daemon.
2
- //
3
- // The daemon is bmo-sync's sync engine running as its own process (a browser
4
- // app can't embed the Rust library the way wild-terminal's Tauri build did).
5
- // It does ALL the syncing; wild-workspace only displays its status and tells
6
- // it what to pair. This module is the one extra responsibility wild-workspace
7
- // takes on: pressing the daemon's power button.
8
- //
9
- // Why wild-workspace owns the lifecycle: on a locked-down (enterprise-managed)
10
- // machine the daemon cannot register itself as an OS service — logon-triggered
11
- // scheduled tasks are blocked without admin. So the app the user actually runs
12
- // starts it instead.
13
- //
14
- // The daemon is spawned DETACHED + window-hidden: it keeps running (and so
15
- // keeps syncing) after wild-workspace — server and browser both — has closed,
16
- // and it never flashes a console window. It is deliberately NOT stopped when
17
- // the server stops. The one gap this leaves — sync paused between a reboot and
18
- // the next `wild-workspace` launch — is covered by bmo-sync's offline-resume.
19
-
20
- import { spawn } from 'node:child_process';
21
- import {
22
- openSync,
23
- closeSync,
24
- mkdirSync,
25
- readFileSync,
26
- writeFileSync,
27
- unlinkSync,
28
- } from 'node:fs';
29
- import path from 'node:path';
30
- import os from 'node:os';
31
- import { resolveDaemonBinary } from './daemon-bin.mjs';
32
-
33
- const DEFAULT_HTTP_BASE = 'http://127.0.0.1:8320';
34
-
35
- export class DaemonSupervisor {
36
- /**
37
- * @param {object} [opts]
38
- * @param {string} [opts.httpBase] the daemon's local HTTP origin.
39
- * @param {string} [opts.globalDir] where the pid + log files live. A
40
- * machine-global dir (`~/.wild-workspace`) — the daemon is one per machine,
41
- * not one per workspace, so this is deliberately NOT the per-workspace
42
- * `.wild-workspace/` data dir.
43
- * @param {Function} [opts.resolveBinary] daemon-binary resolver (test seam).
44
- * @param {Function} [opts.spawnImpl] child_process.spawn (test seam).
45
- * @param {Function} [opts.fetchImpl] global fetch (test seam).
46
- * @param {Function} [opts.killImpl] process.kill (test seam).
47
- * @param {NodeJS.ProcessEnv} [opts.env]
48
- */
49
- constructor({
50
- httpBase = DEFAULT_HTTP_BASE,
51
- globalDir = path.join(os.homedir(), '.wild-workspace'),
52
- resolveBinary = resolveDaemonBinary,
53
- spawnImpl = spawn,
54
- fetchImpl = globalThis.fetch,
55
- killImpl = (pid, sig) => process.kill(pid, sig),
56
- env = process.env,
57
- // b-ii: when the install is logged in (account.json present), these are
58
- // injected into the daemon's spawn env so it opens the proxy link
59
- // (`BMO_DAEMON_ACCOUNT_TOKEN`) against the right relay
60
- // (`BMO_DAEMON_SERVER_URL`). Absent → daemon syncs only, no proxy link.
61
- accountToken = null,
62
- serverUrl = null,
63
- } = {}) {
64
- this.httpBase = httpBase.replace(/\/+$/, '');
65
- this.globalDir = globalDir;
66
- this.pidFile = path.join(globalDir, 'daemon.pid');
67
- this.logFile = path.join(globalDir, 'daemon.log');
68
- this.resolveBinary = resolveBinary;
69
- this.spawnImpl = spawnImpl;
70
- this.fetchImpl = fetchImpl;
71
- this.killImpl = killImpl;
72
- this.env = env;
73
- this.accountToken = accountToken;
74
- this.serverUrl = serverUrl;
75
- }
76
-
77
- /** Probe the daemon's /health endpoint. Never throws. */
78
- async health() {
79
- try {
80
- const res = await this.fetchImpl(`${this.httpBase}/health`, {
81
- signal: AbortSignal.timeout(2000),
82
- });
83
- return { running: !!res.ok };
84
- } catch {
85
- return { running: false };
86
- }
87
- }
88
-
89
- /**
90
- * Start the daemon unless it is already up. Idempotent and best-effort —
91
- * the result is reported, never thrown.
92
- * @returns {Promise<{started:boolean, alreadyRunning?:boolean, pid?:number,
93
- * error?:string}>}
94
- */
95
- async ensureRunning() {
96
- if ((await this.health()).running) {
97
- return { started: false, alreadyRunning: true };
98
- }
99
- return this.spawnDaemon();
100
- }
101
-
102
- /** Spawn the daemon detached + window-hidden, logging to `daemon.log`. */
103
- spawnDaemon() {
104
- const bin = this.resolveBinary({ env: this.env });
105
- // `null` = an explicit override path that doesn't exist; `path` = nothing
106
- // concrete found, only the bare name as a PATH last-resort. In neither case
107
- // is there a real binary to launch — refuse rather than ENOENT later.
108
- if (!bin || bin.source === 'path') {
109
- return { started: false, error: 'daemon-binary-not-found' };
110
- }
111
-
112
- try {
113
- mkdirSync(this.globalDir, { recursive: true });
114
- } catch {
115
- /* fall through — openSync below will surface a real problem */
116
- }
117
-
118
- // A real fd (not 'ignore') so the daemon's stdout/stderr land in a log the
119
- // user can read — and so its eprintln writes hit a valid handle.
120
- let logFd = 'ignore';
121
- try {
122
- logFd = openSync(this.logFile, 'a');
123
- } catch {
124
- /* can't open the log — run anyway with output discarded */
125
- }
126
-
127
- let child;
128
- try {
129
- child = this.spawnImpl(bin.path, [], {
130
- detached: true, // outlive the wild-workspace server
131
- windowsHide: true, // no console window — the whole point
132
- stdio: ['ignore', logFd, logFd],
133
- // b-ii proxy link: inject the account token + relay URL when the
134
- // install is logged in. Object-spreading a falsy value is a no-op,
135
- // so an unauthenticated install spawns with a clean inherited env.
136
- env: {
137
- ...this.env,
138
- ...(this.accountToken && { BMO_DAEMON_ACCOUNT_TOKEN: this.accountToken }),
139
- ...(this.serverUrl && { BMO_DAEMON_SERVER_URL: this.serverUrl }),
140
- },
141
- });
142
- } catch (err) {
143
- if (typeof logFd === 'number') {
144
- try { closeSync(logFd); } catch {}
145
- }
146
- return { started: false, error: String(err?.message || err) };
147
- }
148
-
149
- // The parent must drop its own copy of the log fd + its handle on the
150
- // child, or the server process can't exit cleanly.
151
- if (typeof logFd === 'number') {
152
- try { closeSync(logFd); } catch {}
153
- }
154
- child.unref();
155
-
156
- try {
157
- writeFileSync(this.pidFile, String(child.pid));
158
- } catch {
159
- /* pid file is best-effort — `stop` falls back to a health probe */
160
- }
161
- return { started: true, pid: child.pid, binary: bin.path, source: bin.source };
162
- }
163
-
164
- /** The pid recorded by the last spawn, or null. */
165
- readPid() {
166
- try {
167
- const pid = Number(readFileSync(this.pidFile, 'utf8').trim());
168
- return Number.isInteger(pid) && pid > 0 ? pid : null;
169
- } catch {
170
- return null;
171
- }
172
- }
173
-
174
- /** Stop the daemon (best-effort) by signalling the recorded pid. */
175
- async stop() {
176
- const pid = this.readPid();
177
- if (!pid) {
178
- const running = (await this.health()).running;
179
- return { stopped: false, reason: running ? 'no-pid-file' : 'not-running' };
180
- }
181
- try {
182
- this.killImpl(pid, 'SIGTERM');
183
- } catch (err) {
184
- if (err?.code === 'ESRCH') {
185
- // already gone — tidy the stale pid file
186
- try { unlinkSync(this.pidFile); } catch {}
187
- return { stopped: false, reason: 'not-running' };
188
- }
189
- return { stopped: false, reason: String(err?.message || err) };
190
- }
191
- try { unlinkSync(this.pidFile); } catch {}
192
- return { stopped: true, pid };
193
- }
194
-
195
- /** Combined status for `wild-workspace daemon status`. */
196
- async status() {
197
- const { running } = await this.health();
198
- return {
199
- running,
200
- pid: this.readPid(),
201
- httpBase: this.httpBase,
202
- pidFile: this.pidFile,
203
- logFile: this.logFile,
204
- };
205
- }
206
-
207
- /** Poll /health until the daemon answers or the deadline passes. */
208
- async waitForHealthy(timeoutMs = 4000) {
209
- const deadline = Date.now() + timeoutMs;
210
- while (Date.now() < deadline) {
211
- if ((await this.health()).running) return true;
212
- await new Promise((r) => setTimeout(r, 250));
213
- }
214
- return false;
215
- }
216
- }
1
+ // Lifecycle owner for the bmo-sync daemon.
2
+ //
3
+ // The daemon is bmo-sync's sync engine running as its own process (a browser
4
+ // app can't embed the Rust library the way wild-terminal's Tauri build did).
5
+ // It does ALL the syncing; wild-workspace only displays its status and tells
6
+ // it what to pair. This module is the one extra responsibility wild-workspace
7
+ // takes on: pressing the daemon's power button.
8
+ //
9
+ // Why wild-workspace owns the lifecycle: on a locked-down (enterprise-managed)
10
+ // machine the daemon cannot register itself as an OS service — logon-triggered
11
+ // scheduled tasks are blocked without admin. So the app the user actually runs
12
+ // starts it instead.
13
+ //
14
+ // The daemon is spawned DETACHED + window-hidden: it keeps running (and so
15
+ // keeps syncing) after wild-workspace — server and browser both — has closed,
16
+ // and it never flashes a console window. It is deliberately NOT stopped when
17
+ // the server stops. The one gap this leaves — sync paused between a reboot and
18
+ // the next `wild-workspace` launch — is covered by bmo-sync's offline-resume.
19
+
20
+ import { spawn } from 'node:child_process';
21
+ import {
22
+ openSync,
23
+ closeSync,
24
+ mkdirSync,
25
+ readFileSync,
26
+ writeFileSync,
27
+ unlinkSync,
28
+ } from 'node:fs';
29
+ import path from 'node:path';
30
+ import os from 'node:os';
31
+ import { resolveDaemonBinary } from './daemon-bin.mjs';
32
+
33
+ const DEFAULT_HTTP_BASE = 'http://127.0.0.1:8320';
34
+
35
+ export class DaemonSupervisor {
36
+ /**
37
+ * @param {object} [opts]
38
+ * @param {string} [opts.httpBase] the daemon's local HTTP origin.
39
+ * @param {string} [opts.globalDir] where the pid + log files live. A
40
+ * machine-global dir (`~/.wild-workspace`) — the daemon is one per machine,
41
+ * not one per workspace, so this is deliberately NOT the per-workspace
42
+ * `.wild-workspace/` data dir.
43
+ * @param {Function} [opts.resolveBinary] daemon-binary resolver (test seam).
44
+ * @param {Function} [opts.spawnImpl] child_process.spawn (test seam).
45
+ * @param {Function} [opts.fetchImpl] global fetch (test seam).
46
+ * @param {Function} [opts.killImpl] process.kill (test seam).
47
+ * @param {NodeJS.ProcessEnv} [opts.env]
48
+ */
49
+ constructor({
50
+ httpBase = DEFAULT_HTTP_BASE,
51
+ globalDir = path.join(os.homedir(), '.wild-workspace'),
52
+ resolveBinary = resolveDaemonBinary,
53
+ spawnImpl = spawn,
54
+ fetchImpl = globalThis.fetch,
55
+ killImpl = (pid, sig) => process.kill(pid, sig),
56
+ env = process.env,
57
+ // b-ii: when the install is logged in (account.json present), these are
58
+ // injected into the daemon's spawn env so it opens the proxy link
59
+ // (`BMO_DAEMON_ACCOUNT_TOKEN`) against the right relay
60
+ // (`BMO_DAEMON_SERVER_URL`). Absent → daemon syncs only, no proxy link.
61
+ accountToken = null,
62
+ serverUrl = null,
63
+ } = {}) {
64
+ this.httpBase = httpBase.replace(/\/+$/, '');
65
+ this.globalDir = globalDir;
66
+ this.pidFile = path.join(globalDir, 'daemon.pid');
67
+ this.logFile = path.join(globalDir, 'daemon.log');
68
+ this.resolveBinary = resolveBinary;
69
+ this.spawnImpl = spawnImpl;
70
+ this.fetchImpl = fetchImpl;
71
+ this.killImpl = killImpl;
72
+ this.env = env;
73
+ this.accountToken = accountToken;
74
+ this.serverUrl = serverUrl;
75
+ }
76
+
77
+ /** Probe the daemon's /health endpoint. Never throws. */
78
+ async health() {
79
+ try {
80
+ const res = await this.fetchImpl(`${this.httpBase}/health`, {
81
+ signal: AbortSignal.timeout(2000),
82
+ });
83
+ return { running: !!res.ok };
84
+ } catch {
85
+ return { running: false };
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Start the daemon unless it is already up. Idempotent and best-effort —
91
+ * the result is reported, never thrown.
92
+ * @returns {Promise<{started:boolean, alreadyRunning?:boolean, pid?:number,
93
+ * error?:string}>}
94
+ */
95
+ async ensureRunning() {
96
+ if ((await this.health()).running) {
97
+ return { started: false, alreadyRunning: true };
98
+ }
99
+ return this.spawnDaemon();
100
+ }
101
+
102
+ /** Spawn the daemon detached + window-hidden, logging to `daemon.log`. */
103
+ spawnDaemon() {
104
+ const bin = this.resolveBinary({ env: this.env });
105
+ // `null` = an explicit override path that doesn't exist; `path` = nothing
106
+ // concrete found, only the bare name as a PATH last-resort. In neither case
107
+ // is there a real binary to launch — refuse rather than ENOENT later.
108
+ if (!bin || bin.source === 'path') {
109
+ return { started: false, error: 'daemon-binary-not-found' };
110
+ }
111
+
112
+ try {
113
+ mkdirSync(this.globalDir, { recursive: true });
114
+ } catch {
115
+ /* fall through — openSync below will surface a real problem */
116
+ }
117
+
118
+ // A real fd (not 'ignore') so the daemon's stdout/stderr land in a log the
119
+ // user can read — and so its eprintln writes hit a valid handle.
120
+ let logFd = 'ignore';
121
+ try {
122
+ logFd = openSync(this.logFile, 'a');
123
+ } catch {
124
+ /* can't open the log — run anyway with output discarded */
125
+ }
126
+
127
+ let child;
128
+ try {
129
+ child = this.spawnImpl(bin.path, [], {
130
+ detached: true, // outlive the wild-workspace server
131
+ windowsHide: true, // no console window — the whole point
132
+ stdio: ['ignore', logFd, logFd],
133
+ // b-ii proxy link: inject the account token + relay URL when the
134
+ // install is logged in. Object-spreading a falsy value is a no-op,
135
+ // so an unauthenticated install spawns with a clean inherited env.
136
+ env: {
137
+ ...this.env,
138
+ ...(this.accountToken && { BMO_DAEMON_ACCOUNT_TOKEN: this.accountToken }),
139
+ ...(this.serverUrl && { BMO_DAEMON_SERVER_URL: this.serverUrl }),
140
+ },
141
+ });
142
+ } catch (err) {
143
+ if (typeof logFd === 'number') {
144
+ try { closeSync(logFd); } catch {}
145
+ }
146
+ return { started: false, error: String(err?.message || err) };
147
+ }
148
+
149
+ // The parent must drop its own copy of the log fd + its handle on the
150
+ // child, or the server process can't exit cleanly.
151
+ if (typeof logFd === 'number') {
152
+ try { closeSync(logFd); } catch {}
153
+ }
154
+ child.unref();
155
+
156
+ try {
157
+ writeFileSync(this.pidFile, String(child.pid));
158
+ } catch {
159
+ /* pid file is best-effort — `stop` falls back to a health probe */
160
+ }
161
+ return { started: true, pid: child.pid, binary: bin.path, source: bin.source };
162
+ }
163
+
164
+ /** The pid recorded by the last spawn, or null. */
165
+ readPid() {
166
+ try {
167
+ const pid = Number(readFileSync(this.pidFile, 'utf8').trim());
168
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /** Stop the daemon (best-effort) by signalling the recorded pid. */
175
+ async stop() {
176
+ const pid = this.readPid();
177
+ if (!pid) {
178
+ const running = (await this.health()).running;
179
+ return { stopped: false, reason: running ? 'no-pid-file' : 'not-running' };
180
+ }
181
+ try {
182
+ this.killImpl(pid, 'SIGTERM');
183
+ } catch (err) {
184
+ if (err?.code === 'ESRCH') {
185
+ // already gone — tidy the stale pid file
186
+ try { unlinkSync(this.pidFile); } catch {}
187
+ return { stopped: false, reason: 'not-running' };
188
+ }
189
+ return { stopped: false, reason: String(err?.message || err) };
190
+ }
191
+ try { unlinkSync(this.pidFile); } catch {}
192
+ return { stopped: true, pid };
193
+ }
194
+
195
+ /** Combined status for `wild-workspace daemon status`. */
196
+ async status() {
197
+ const { running } = await this.health();
198
+ return {
199
+ running,
200
+ pid: this.readPid(),
201
+ httpBase: this.httpBase,
202
+ pidFile: this.pidFile,
203
+ logFile: this.logFile,
204
+ };
205
+ }
206
+
207
+ /** Poll /health until the daemon answers or the deadline passes. */
208
+ async waitForHealthy(timeoutMs = 4000) {
209
+ const deadline = Date.now() + timeoutMs;
210
+ while (Date.now() < deadline) {
211
+ if ((await this.health()).running) return true;
212
+ await new Promise((r) => setTimeout(r, 250));
213
+ }
214
+ return false;
215
+ }
216
+ }
@@ -1,86 +1,86 @@
1
- // Component System inbox surfacing.
2
- // When `.wild/inbox.md` exists or changes, emit notifications.
3
- // Drives the "I noticed you imported X — want me to walk integration?" cue in chat.
4
-
5
- import fs from 'node:fs/promises';
6
- import { existsSync } from 'node:fs';
7
- import path from 'node:path';
8
- import chokidar from 'chokidar';
9
- import { EventEmitter } from 'node:events';
10
-
11
- export class InboxWatcher extends EventEmitter {
12
- constructor(workspaceDir) {
13
- super();
14
- this.workspaceDir = workspaceDir;
15
- this.inboxPath = path.join(workspaceDir, '.wild', 'inbox.md');
16
- this.installedPath = path.join(workspaceDir, '.wild', 'installed.json');
17
- this.watcher = null;
18
- // Resolves once the watcher's initial scan is done — see start().
19
- this.ready = Promise.resolve();
20
- }
21
-
22
- start() {
23
- this.watcher = chokidar.watch(
24
- [this.inboxPath, this.installedPath, path.join(this.workspaceDir, '.wild', 'imports')],
25
- {
26
- ignoreInitial: false,
27
- persistent: true,
28
- depth: 3,
29
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
30
- },
31
- );
32
- this.watcher.on('add', () => this._refresh('add'));
33
- this.watcher.on('change', () => this._refresh('change'));
34
- this.watcher.on('unlink', () => this._refresh('unlink'));
35
- // Resolves once chokidar's initial scan completes and it is actively
36
- // watching — anything created after this point is reliably detected.
37
- this.ready = new Promise((resolve) => this.watcher.once('ready', resolve));
38
- return this;
39
- }
40
-
41
- async _refresh(kind) {
42
- const snapshot = await this.snapshot();
43
- this.emit('change', { kind, snapshot });
44
- }
45
-
46
- async snapshot() {
47
- const out = {
48
- hasInbox: existsSync(this.inboxPath),
49
- inboxContent: '',
50
- installed: {},
51
- imports: [],
52
- };
53
- if (out.hasInbox) {
54
- try {
55
- out.inboxContent = await fs.readFile(this.inboxPath, 'utf8');
56
- } catch {
57
- out.inboxContent = '';
58
- }
59
- }
60
- if (existsSync(this.installedPath)) {
61
- try {
62
- const raw = await fs.readFile(this.installedPath, 'utf8');
63
- out.installed = JSON.parse(raw);
64
- } catch {
65
- out.installed = {};
66
- }
67
- }
68
- const importsDir = path.join(this.workspaceDir, '.wild', 'imports');
69
- if (existsSync(importsDir)) {
70
- try {
71
- const entries = await fs.readdir(importsDir, { withFileTypes: true });
72
- out.imports = entries
73
- .filter((e) => e.isDirectory())
74
- .map((e) => e.name);
75
- } catch {
76
- out.imports = [];
77
- }
78
- }
79
- return out;
80
- }
81
-
82
- stop() {
83
- if (this.watcher) this.watcher.close();
84
- this.watcher = null;
85
- }
86
- }
1
+ // Component System inbox surfacing.
2
+ // When `.wild/inbox.md` exists or changes, emit notifications.
3
+ // Drives the "I noticed you imported X — want me to walk integration?" cue in chat.
4
+
5
+ import fs from 'node:fs/promises';
6
+ import { existsSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import chokidar from 'chokidar';
9
+ import { EventEmitter } from 'node:events';
10
+
11
+ export class InboxWatcher extends EventEmitter {
12
+ constructor(workspaceDir) {
13
+ super();
14
+ this.workspaceDir = workspaceDir;
15
+ this.inboxPath = path.join(workspaceDir, '.wild', 'inbox.md');
16
+ this.installedPath = path.join(workspaceDir, '.wild', 'installed.json');
17
+ this.watcher = null;
18
+ // Resolves once the watcher's initial scan is done — see start().
19
+ this.ready = Promise.resolve();
20
+ }
21
+
22
+ start() {
23
+ this.watcher = chokidar.watch(
24
+ [this.inboxPath, this.installedPath, path.join(this.workspaceDir, '.wild', 'imports')],
25
+ {
26
+ ignoreInitial: false,
27
+ persistent: true,
28
+ depth: 3,
29
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
30
+ },
31
+ );
32
+ this.watcher.on('add', () => this._refresh('add'));
33
+ this.watcher.on('change', () => this._refresh('change'));
34
+ this.watcher.on('unlink', () => this._refresh('unlink'));
35
+ // Resolves once chokidar's initial scan completes and it is actively
36
+ // watching — anything created after this point is reliably detected.
37
+ this.ready = new Promise((resolve) => this.watcher.once('ready', resolve));
38
+ return this;
39
+ }
40
+
41
+ async _refresh(kind) {
42
+ const snapshot = await this.snapshot();
43
+ this.emit('change', { kind, snapshot });
44
+ }
45
+
46
+ async snapshot() {
47
+ const out = {
48
+ hasInbox: existsSync(this.inboxPath),
49
+ inboxContent: '',
50
+ installed: {},
51
+ imports: [],
52
+ };
53
+ if (out.hasInbox) {
54
+ try {
55
+ out.inboxContent = await fs.readFile(this.inboxPath, 'utf8');
56
+ } catch {
57
+ out.inboxContent = '';
58
+ }
59
+ }
60
+ if (existsSync(this.installedPath)) {
61
+ try {
62
+ const raw = await fs.readFile(this.installedPath, 'utf8');
63
+ out.installed = JSON.parse(raw);
64
+ } catch {
65
+ out.installed = {};
66
+ }
67
+ }
68
+ const importsDir = path.join(this.workspaceDir, '.wild', 'imports');
69
+ if (existsSync(importsDir)) {
70
+ try {
71
+ const entries = await fs.readdir(importsDir, { withFileTypes: true });
72
+ out.imports = entries
73
+ .filter((e) => e.isDirectory())
74
+ .map((e) => e.name);
75
+ } catch {
76
+ out.imports = [];
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+
82
+ stop() {
83
+ if (this.watcher) this.watcher.close();
84
+ this.watcher = null;
85
+ }
86
+ }