@venturewild/workspace 0.1.0 → 0.1.1

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.
@@ -0,0 +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
+ }
@@ -147,6 +147,12 @@ export class DaemonBridge {
147
147
  path: msg.path,
148
148
  resolution: msg.resolution,
149
149
  conflictingUser: msg.conflictingUser,
150
+ // C12-e enrichment — present for daemon-detected conflicts only.
151
+ mineSha256: msg.mineSha256,
152
+ theirsSha256: msg.theirsSha256,
153
+ baseSha256: msg.baseSha256,
154
+ peerBackOfficePath: msg.peerBackOfficePath,
155
+ detectedAt: msg.detectedAt,
150
156
  });
151
157
  } else if (msg.kind === 'fatal') {
152
158
  this.activityBus.publish({
@@ -0,0 +1,86 @@
1
+ // Forwards meaningful errors (agent crashes, daemon exits, etc.) to the
2
+ // central bmo-sync-server so support can see what went wrong on a client's
3
+ // machine. Fire-and-forget — never blocks the user's request, never throws.
4
+ //
5
+ // Off-switch: WILD_WORKSPACE_NO_TELEMETRY=1 disables the reporter entirely.
6
+ // Privacy: only error messages + stack traces are sent — no file contents, no
7
+ // chat content, no file paths beyond their basename.
8
+
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { APP_VERSION } from './config.mjs';
12
+
13
+ // In-process burst guard so a thrashing daemon can't hammer the central
14
+ // server. Per-(workspace+category) bucket, 10 reports per 60s window.
15
+ const RL_WINDOW_MS = 60_000;
16
+ const RL_CAP = 10;
17
+ const buckets = new Map();
18
+
19
+ function bucketKey(workspaceId, category) {
20
+ return `${workspaceId}:${category}`;
21
+ }
22
+
23
+ function allow(workspaceId, category) {
24
+ const now = Date.now();
25
+ const key = bucketKey(workspaceId, category);
26
+ const ts = buckets.get(key) || [];
27
+ const recent = ts.filter((t) => now - t < RL_WINDOW_MS);
28
+ if (recent.length >= RL_CAP) {
29
+ buckets.set(key, recent);
30
+ return false;
31
+ }
32
+ recent.push(now);
33
+ buckets.set(key, recent);
34
+ return true;
35
+ }
36
+
37
+ // Redact absolute paths down to a basename so we don't leak the user's home
38
+ // directory or file layout to the central server. Picks up POSIX + Windows
39
+ // paths in free text (messages and stack traces).
40
+ const PATH_RE = /([A-Za-z]:\\[\w.\-\\\/]+|\/[\w.\-\/]+\.\w+)/g;
41
+ function redactPaths(text) {
42
+ if (typeof text !== 'string') return text;
43
+ return text.replace(PATH_RE, (full) => path.basename(full));
44
+ }
45
+
46
+ export class ErrorReporter {
47
+ constructor({ bmoSyncUrl, workspaceId, enabled }) {
48
+ this.bmoSyncUrl = bmoSyncUrl?.replace(/\/$/, '') || null;
49
+ this.workspaceId = workspaceId || 'unknown';
50
+ this.enabled = enabled !== false && !this.bmoSyncUrl?.startsWith('http://127');
51
+ }
52
+
53
+ // Fire-and-forget. Catches every failure path so calling this never breaks
54
+ // the request that triggered it.
55
+ report({ category, message, stack, agentLabel, source }) {
56
+ if (!this.enabled || !this.bmoSyncUrl) return;
57
+ const cat = (category || 'agent').slice(0, 32);
58
+ if (!message) return;
59
+ if (!allow(this.workspaceId, cat)) return;
60
+ const body = {
61
+ workspace_id: this.workspaceId,
62
+ agent_label: agentLabel || null,
63
+ category: cat,
64
+ message: redactPaths(String(message)).slice(0, 4096),
65
+ stack: stack ? redactPaths(String(stack)).slice(0, 8192) : null,
66
+ app_version: APP_VERSION,
67
+ os: `${os.platform()}-${os.arch()}`,
68
+ source: source || 'wild-workspace',
69
+ ts: Math.floor(Date.now() / 1000),
70
+ };
71
+ const url = `${this.bmoSyncUrl}/api/errors/report`;
72
+ // Detached fetch with a short timeout so a hung server can't pile up.
73
+ const ctrl = new AbortController();
74
+ const timer = setTimeout(() => ctrl.abort(), 5000);
75
+ fetch(url, {
76
+ method: 'POST',
77
+ headers: { 'content-type': 'application/json' },
78
+ body: JSON.stringify(body),
79
+ signal: ctrl.signal,
80
+ })
81
+ .catch(() => {
82
+ /* swallowed — telemetry never breaks the user's path */
83
+ })
84
+ .finally(() => clearTimeout(timer));
85
+ }
86
+ }
@@ -1,81 +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
- }
19
-
20
- start() {
21
- this.watcher = chokidar.watch(
22
- [this.inboxPath, this.installedPath, path.join(this.workspaceDir, '.wild', 'imports')],
23
- {
24
- ignoreInitial: false,
25
- persistent: true,
26
- depth: 3,
27
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
28
- },
29
- );
30
- this.watcher.on('add', () => this._refresh('add'));
31
- this.watcher.on('change', () => this._refresh('change'));
32
- this.watcher.on('unlink', () => this._refresh('unlink'));
33
- return this;
34
- }
35
-
36
- async _refresh(kind) {
37
- const snapshot = await this.snapshot();
38
- this.emit('change', { kind, snapshot });
39
- }
40
-
41
- async snapshot() {
42
- const out = {
43
- hasInbox: existsSync(this.inboxPath),
44
- inboxContent: '',
45
- installed: {},
46
- imports: [],
47
- };
48
- if (out.hasInbox) {
49
- try {
50
- out.inboxContent = await fs.readFile(this.inboxPath, 'utf8');
51
- } catch {
52
- out.inboxContent = '';
53
- }
54
- }
55
- if (existsSync(this.installedPath)) {
56
- try {
57
- const raw = await fs.readFile(this.installedPath, 'utf8');
58
- out.installed = JSON.parse(raw);
59
- } catch {
60
- out.installed = {};
61
- }
62
- }
63
- const importsDir = path.join(this.workspaceDir, '.wild', 'imports');
64
- if (existsSync(importsDir)) {
65
- try {
66
- const entries = await fs.readdir(importsDir, { withFileTypes: true });
67
- out.imports = entries
68
- .filter((e) => e.isDirectory())
69
- .map((e) => e.name);
70
- } catch {
71
- out.imports = [];
72
- }
73
- }
74
- return out;
75
- }
76
-
77
- stop() {
78
- if (this.watcher) this.watcher.close();
79
- this.watcher = null;
80
- }
81
- }
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
+ }