dsh-open-artifact 0.14.0 → 0.14.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.
@@ -1813,12 +1813,26 @@ async function ensureDaemon(options = {}) {
1813
1813
  if (running) await replaceDaemon(running, 5e3);
1814
1814
  const logFile = join3(openArtifactHome(home2), "logs", "daemon.out");
1815
1815
  const deadline = Date.now() + timeoutMs;
1816
+ const thrown = [];
1816
1817
  for (const attempt of plan.tries) {
1817
- const child = startDaemonProcess(attempt.bin, { env: attempt.env, ...home2 ? { home: home2 } : {} });
1818
1818
  let exited = false;
1819
- child.once("exit", () => {
1819
+ const onExit = () => {
1820
1820
  exited = true;
1821
- });
1821
+ };
1822
+ if (options.spawn) {
1823
+ const start = { bin: attempt.bin, args: ["daemon", "run"], env: { ...attempt.env, ...home2 ? { OPEN_ARTIFACT_HOME: home2 } : {} }, logFile };
1824
+ delete start.env.ELECTRON_RUN_AS_NODE;
1825
+ try {
1826
+ mkdirSync(join3(openArtifactHome(home2), "logs"), { recursive: true });
1827
+ const started = await options.spawn(start);
1828
+ if (started && typeof started.once === "function") started.once("exit", onExit);
1829
+ } catch (error) {
1830
+ thrown.push(`${attempt.bin}: ${error?.message ?? String(error)}`);
1831
+ continue;
1832
+ }
1833
+ } else {
1834
+ startDaemonProcess(attempt.bin, { env: attempt.env, ...home2 ? { home: home2 } : {} }).once("exit", onExit);
1835
+ }
1822
1836
  while (Date.now() < deadline) {
1823
1837
  await new Promise((done) => setTimeout(done, 150));
1824
1838
  const state2 = await readDaemon(home2);
@@ -1829,7 +1843,8 @@ async function ensureDaemon(options = {}) {
1829
1843
  }
1830
1844
  const state = await readDaemon(home2);
1831
1845
  if (state) return state;
1832
- throw new OpenArtifactError("daemon_failed", `The open-artifact daemon did not start; see ${logFile}`);
1846
+ const why = thrown.length ? ` The host's start failed: ${thrown.join("; ")}.` : "";
1847
+ throw new OpenArtifactError("daemon_failed", `The open-artifact daemon did not start; see ${logFile}.${why}`);
1833
1848
  }
1834
1849
  async function api(state, name, body, options = {}) {
1835
1850
  const url = new URL(`/api/open-artifact.${name}`, state.url);
@@ -2103,7 +2118,7 @@ var init_package = __esm({
2103
2118
  "packages/daemon/package.json"() {
2104
2119
  package_default = {
2105
2120
  name: "@open-artifact/daemon",
2106
- version: "0.14.0",
2121
+ version: "0.14.1",
2107
2122
  private: true,
2108
2123
  type: "module",
2109
2124
  description: "The Open Artifact daemon (`open-artifact`): type registry, artifact library, type servers, agent tools, wake routing, the Harness API, MCP and the Shell.",
@@ -2115,8 +2130,8 @@ var init_package = __esm({
2115
2130
  "./client": "./src/client.ts"
2116
2131
  },
2117
2132
  dependencies: {
2118
- "@open-artifact/harness-kit": "0.14.0",
2119
- "@open-artifact/protocol": "0.14.0"
2133
+ "@open-artifact/harness-kit": "0.14.1",
2134
+ "@open-artifact/protocol": "0.14.1"
2120
2135
  },
2121
2136
  license: "Apache-2.0"
2122
2137
  };
@@ -3941,8 +3956,15 @@ var init_harness2 = __esm({
3941
3956
  statusOf(ref) {
3942
3957
  const session = ref ? this.sessions.get(sessionKeyOf(ref) ?? "") : void 0;
3943
3958
  const draft = ref && this.wakeModeOf(ref.harness) === "draft" ? { wakeMode: "draft" } : {};
3944
- if (!session?.conn) return { live: false, status: "offline", ...draft };
3945
- return { live: true, status: session.status === "running" ? "running" : "idle", ...draft };
3959
+ const harnessTitle = ref ? this.titleOf(ref.harness) : void 0;
3960
+ const named2 = { ...draft, ...harnessTitle ? { harnessTitle } : {} };
3961
+ if (!session?.conn) return { live: false, status: "offline", ...named2 };
3962
+ return { live: true, status: session.status === "running" ? "running" : "idle", ...named2 };
3963
+ }
3964
+ /** A harness's display name from its profile, or `undefined` when the profile gives none (its title is its id). */
3965
+ titleOf(harness) {
3966
+ const title = harnessProfile(harness).title;
3967
+ return title && title !== harness ? title : void 0;
3946
3968
  }
3947
3969
  /** `GET /api/open-artifact.harnesses`. */
3948
3970
  info() {
@@ -5027,8 +5049,174 @@ var init_runtime = __esm({
5027
5049
  }
5028
5050
  });
5029
5051
 
5030
- // packages/daemon/src/servers.ts
5052
+ // packages/daemon/src/node-children.ts
5031
5053
  import { spawn as spawn3 } from "node:child_process";
5054
+ import { EventEmitter as EventEmitter4 } from "node:events";
5055
+ import { realpathSync as realpathSync3 } from "node:fs";
5056
+ import { isAbsolute as isAbsolute3, resolve as resolve11 } from "node:path";
5057
+ import { PassThrough } from "node:stream";
5058
+ import { Worker } from "node:worker_threads";
5059
+ function modeFromEnv(env = process.env) {
5060
+ const value = env[NODE_CHILDREN_VARIABLE]?.trim().toLowerCase();
5061
+ return value === "process" || value === "threads" ? value : null;
5062
+ }
5063
+ function badModeVariable(env = process.env) {
5064
+ const value = env[NODE_CHILDREN_VARIABLE]?.trim();
5065
+ if (!value || modeFromEnv(env)) return null;
5066
+ return `${NODE_CHILDREN_VARIABLE}=${value} is neither "process" nor "threads"; it is ignored`;
5067
+ }
5068
+ function chooseNodeChildren(facts = {}) {
5069
+ const env = facts.env ?? process.env;
5070
+ const electron = "electron" in facts ? facts.electron : process.versions.electron;
5071
+ const processType = "processType" in facts ? facts.processType : process.type;
5072
+ const forced = modeFromEnv(env);
5073
+ if (forced) return { mode: forced, reason: "env", detail: `${NODE_CHILDREN_VARIABLE}=${forced}` };
5074
+ if (!electron) return { mode: "process", reason: "node", detail: "plain Node.js runs child processes" };
5075
+ if (!processType) return { mode: "process", reason: "electron", detail: `Electron ${electron} runs the daemon as Node, so its executable runs scripts` };
5076
+ return { mode: "threads", reason: "electron", detail: `the daemon runs inside an Electron ${processType} process (Electron ${electron}), whose executable is not started as Node` };
5077
+ }
5078
+ function nodeChildren() {
5079
+ return decided ??= chooseNodeChildren();
5080
+ }
5081
+ function startChild(start) {
5082
+ const isNode = start.command === "node";
5083
+ if (isNode && start.mode === "threads") return new ThreadChild(start);
5084
+ const command = isNode ? process.execPath : start.command;
5085
+ const env = isNode ? { ...start.env, ELECTRON_RUN_AS_NODE: "1" } : start.env;
5086
+ return new ProcessChild(spawn3(command, start.args, { cwd: start.cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
5087
+ }
5088
+ function threadEntry(args, cwd) {
5089
+ const at = args.findIndex((arg) => !arg.startsWith("-"));
5090
+ if (at < 0) throw new Error(`no script to run in ${JSON.stringify(args)}`);
5091
+ const given = isAbsolute3(args[at]) ? args[at] : resolve11(cwd, args[at]);
5092
+ let script = given;
5093
+ try {
5094
+ script = realpathSync3(given);
5095
+ } catch {
5096
+ }
5097
+ return { execArgv: args.slice(0, at), script, args: args.slice(at + 1) };
5098
+ }
5099
+ var NODE_CHILDREN_VARIABLE, decided, ProcessChild, STOP_MESSAGE, BOOTSTRAP, ThreadChild;
5100
+ var init_node_children = __esm({
5101
+ "packages/daemon/src/node-children.ts"() {
5102
+ "use strict";
5103
+ NODE_CHILDREN_VARIABLE = "OPEN_ARTIFACT_NODE_CHILDREN";
5104
+ decided = null;
5105
+ ProcessChild = class extends EventEmitter4 {
5106
+ mode = "process";
5107
+ child;
5108
+ constructor(child) {
5109
+ super();
5110
+ this.child = child;
5111
+ child.on("error", (error) => this.emit("error", error));
5112
+ child.on("exit", (code, signal) => this.emit("exit", code, signal));
5113
+ }
5114
+ get pid() {
5115
+ return this.child.pid;
5116
+ }
5117
+ get label() {
5118
+ return `pid ${this.child.pid ?? "?"}`;
5119
+ }
5120
+ get instance() {
5121
+ return this.child.pid ?? null;
5122
+ }
5123
+ get stdout() {
5124
+ return this.child.stdout;
5125
+ }
5126
+ get stderr() {
5127
+ return this.child.stderr;
5128
+ }
5129
+ get ended() {
5130
+ return this.child.exitCode !== null || this.child.signalCode !== null;
5131
+ }
5132
+ stop(forceAfterMs) {
5133
+ if (this.ended) return;
5134
+ try {
5135
+ this.child.kill("SIGTERM");
5136
+ } catch {
5137
+ return;
5138
+ }
5139
+ const timer = setTimeout(() => {
5140
+ if (!this.ended) this.child.kill("SIGKILL");
5141
+ }, forceAfterMs);
5142
+ timer.unref?.();
5143
+ }
5144
+ kill() {
5145
+ if (!this.ended) this.child.kill("SIGKILL");
5146
+ }
5147
+ };
5148
+ STOP_MESSAGE = "open-artifact:stop";
5149
+ BOOTSTRAP = `
5150
+ const { parentPort, workerData } = require('node:worker_threads');
5151
+ const { pathToFileURL } = require('node:url');
5152
+ process.argv = [process.execPath, workerData.script, ...workerData.args];
5153
+ const cwd = workerData.cwd;
5154
+ process.cwd = () => cwd;
5155
+ parentPort.on('message', (message) => {
5156
+ if (message !== ${JSON.stringify(STOP_MESSAGE)}) return;
5157
+ if (process.listenerCount('SIGTERM') > 0) process.emit('SIGTERM', 'SIGTERM');
5158
+ else process.exit(143);
5159
+ });
5160
+ parentPort.unref();
5161
+ import(pathToFileURL(workerData.script).href).catch((error) => {
5162
+ process.stderr.write(String((error && error.stack) || error) + '\\n');
5163
+ process.exit(1);
5164
+ });
5165
+ `;
5166
+ ThreadChild = class extends EventEmitter4 {
5167
+ mode = "threads";
5168
+ pid = void 0;
5169
+ label;
5170
+ instance;
5171
+ stdout;
5172
+ stderr;
5173
+ exited = false;
5174
+ worker;
5175
+ constructor(start) {
5176
+ super();
5177
+ const entry = threadEntry(start.args, start.cwd);
5178
+ this.stdout = new PassThrough();
5179
+ this.stderr = new PassThrough();
5180
+ this.worker = new Worker(BOOTSTRAP, {
5181
+ eval: true,
5182
+ argv: [],
5183
+ execArgv: entry.execArgv,
5184
+ env: { ...start.env },
5185
+ stdin: false,
5186
+ stdout: true,
5187
+ stderr: true,
5188
+ workerData: { script: entry.script, args: entry.args, cwd: start.cwd },
5189
+ ...start.name ? { name: start.name } : {}
5190
+ });
5191
+ const threadId = this.worker.threadId;
5192
+ this.label = `thread ${threadId}`;
5193
+ this.instance = `${process.pid}:${threadId}`;
5194
+ this.worker.stdout.pipe(this.stdout);
5195
+ this.worker.stderr.pipe(this.stderr);
5196
+ this.worker.on("error", (error) => this.stderr.write(`${error?.stack ?? String(error)}
5197
+ `));
5198
+ this.worker.on("exit", (code) => {
5199
+ this.exited = true;
5200
+ this.emit("exit", code, null);
5201
+ });
5202
+ }
5203
+ get ended() {
5204
+ return this.exited;
5205
+ }
5206
+ stop(forceAfterMs) {
5207
+ if (this.exited) return;
5208
+ this.worker.postMessage(STOP_MESSAGE);
5209
+ const timer = setTimeout(() => this.kill(), forceAfterMs);
5210
+ timer.unref?.();
5211
+ }
5212
+ kill() {
5213
+ if (!this.exited) void this.worker.terminate();
5214
+ }
5215
+ };
5216
+ }
5217
+ });
5218
+
5219
+ // packages/daemon/src/servers.ts
5032
5220
  import { randomBytes as randomBytes5 } from "node:crypto";
5033
5221
  import { createWriteStream, statSync as statSync4 } from "node:fs";
5034
5222
  import { dirname as dirname7, join as join14 } from "node:path";
@@ -5114,6 +5302,7 @@ var init_servers = __esm({
5114
5302
  "packages/daemon/src/servers.ts"() {
5115
5303
  "use strict";
5116
5304
  init_src();
5305
+ init_node_children();
5117
5306
  init_paths();
5118
5307
  init_types();
5119
5308
  KILL_MS = 5e3;
@@ -5144,11 +5333,14 @@ var init_servers = __esm({
5144
5333
  byType = /* @__PURE__ */ new Map();
5145
5334
  timer;
5146
5335
  onExit;
5336
+ /** Servers in threads asked to stop and not ended yet ({@link drained}). */
5337
+ stopping = /* @__PURE__ */ new Set();
5338
+ saidThreads = false;
5147
5339
  constructor(options) {
5148
5340
  this.options = options;
5149
5341
  this.timer = setInterval(() => void this.checkHealth(), HEALTH_INTERVAL_MS);
5150
5342
  this.timer.unref?.();
5151
- this.onExit = () => this.killAll("SIGTERM");
5343
+ this.onExit = () => this.killAll();
5152
5344
  process.on("exit", this.onExit);
5153
5345
  }
5154
5346
  /** What the type list shows about a type's server; `null` when it never started. */
@@ -5266,7 +5458,7 @@ var init_servers = __esm({
5266
5458
  const stamp = stampOf(type);
5267
5459
  const kept = readJson(serverFiles.actions(type.id), null);
5268
5460
  const cached = kept && kept.stamp === stamp && Array.isArray(kept.actions) ? kept : null;
5269
- const pid = () => this.byType.get(type.id)?.child?.pid ?? null;
5461
+ const pid = () => this.byType.get(type.id)?.child?.instance ?? null;
5270
5462
  const ready = entry.kind === "url" || this.isReady(type.id);
5271
5463
  if (cached && (!ready || cached.pid === pid())) return cached.actions;
5272
5464
  if (!ready && options.start === false) return null;
@@ -5358,11 +5550,22 @@ var init_servers = __esm({
5358
5550
  throw new OpenArtifactError("server_failed", `${type.id}: its server did not start (${s.error}). See ${serverFiles.log(type.id)}.`);
5359
5551
  }
5360
5552
  }
5361
- spawn(s) {
5553
+ /** How a `node` server runs (`node-children.ts`); said once in the log when it is worker threads. */
5554
+ nodeMode() {
5555
+ const choice = nodeChildren();
5556
+ if (choice.mode === "threads" && !this.saidThreads) {
5557
+ this.saidThreads = true;
5558
+ this.options.log(`type servers run in worker threads of the daemon (${choice.detail})`);
5559
+ }
5560
+ return choice.mode;
5561
+ }
5562
+ async spawn(s) {
5362
5563
  const { type } = s;
5363
5564
  const entry = type.entry;
5364
- if (entry?.kind !== "server") return Promise.reject(new Error("not a server entry"));
5565
+ if (entry?.kind !== "server") throw new Error("not a server entry");
5365
5566
  const { start } = entry;
5567
+ const isNode = start.command === "node";
5568
+ const mode2 = isNode ? this.nodeMode() : "process";
5366
5569
  const last = readJson(serverFiles.state(type.id), null);
5367
5570
  const secret = randomBytes5(24).toString("base64url");
5368
5571
  ensureDir(dirname7(serverFiles.log(type.id)));
@@ -5371,8 +5574,6 @@ var init_servers = __esm({
5371
5574
  log.write(`
5372
5575
  --- ${(/* @__PURE__ */ new Date()).toISOString()} start ${start.command} ${start.args.join(" ")}
5373
5576
  `);
5374
- const isNode = start.command === "node";
5375
- const command = isNode ? process.execPath : start.command;
5376
5577
  const openArtifactEnv = {
5377
5578
  OPEN_ARTIFACT_PROTOCOL: String(OPEN_ARTIFACT_PROTOCOL),
5378
5579
  OPEN_ARTIFACT_TYPE: type.id,
@@ -5383,12 +5584,12 @@ var init_servers = __esm({
5383
5584
  OPEN_ARTIFACT_TYPE_TOKEN: this.options.tokenFor(type.id),
5384
5585
  OPEN_ARTIFACT_STATE_DIR: stateDir
5385
5586
  };
5386
- const env = { ...process.env, ...isNode ? { ELECTRON_RUN_AS_NODE: "1" } : {}, ...start.env, ...openArtifactEnv };
5587
+ const env = { ...process.env, ...start.env, ...openArtifactEnv };
5387
5588
  const readyMs = Number(process.env.OPEN_ARTIFACT_SERVER_READY_MS) || READY_TIMEOUT_MS;
5388
5589
  return new Promise((resolveReady, rejectReady) => {
5389
5590
  let child;
5390
5591
  try {
5391
- child = spawn3(command, start.args, { cwd: type.dir, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
5592
+ child = startChild({ command: start.command, args: start.args, cwd: type.dir, env, mode: mode2, name: `open-artifact type server ${type.id}` });
5392
5593
  } catch (error) {
5393
5594
  log.end();
5394
5595
  rejectReady(error);
@@ -5403,7 +5604,7 @@ var init_servers = __esm({
5403
5604
  if (settled) return;
5404
5605
  settled = true;
5405
5606
  clearTimeout(timer);
5406
- this.kill(child, "SIGTERM");
5607
+ child.stop(KILL_MS);
5407
5608
  rejectReady(new Error(message4));
5408
5609
  };
5409
5610
  const timer = setTimeout(() => fail(`no ready line within ${readyMs / 1e3} s`), readyMs);
@@ -5433,10 +5634,10 @@ var init_servers = __esm({
5433
5634
  const base = withSlash(message4.url);
5434
5635
  Object.assign(s, { base, state: "ready", error: null, misses: 0 });
5435
5636
  try {
5436
- writeJson(serverFiles.state(type.id), { port: Number(new URL(base).port) || null, url: base, pid: child.pid, at: (/* @__PURE__ */ new Date()).toISOString() });
5637
+ writeJson(serverFiles.state(type.id), { port: Number(new URL(base).port) || null, url: base, ...child.pid ? { pid: child.pid } : { thread: child.instance }, at: (/* @__PURE__ */ new Date()).toISOString() });
5437
5638
  } catch {
5438
5639
  }
5439
- this.options.log(`server ${type.id}: ready at ${base} (pid ${child.pid})`);
5640
+ this.options.log(`server ${type.id}: ready at ${base} (${child.label})`);
5440
5641
  this.options.changed?.();
5441
5642
  resolveReady(base);
5442
5643
  return;
@@ -5502,25 +5703,32 @@ var init_servers = __esm({
5502
5703
  const s = this.byType.get(typeId);
5503
5704
  if (!s) return;
5504
5705
  this.byType.delete(typeId);
5505
- if (s.child) this.kill(s.child, "SIGTERM");
5706
+ if (s.child) this.stopChild(s.child);
5506
5707
  if (s.state === "ready") this.options.changed?.();
5507
5708
  }
5508
- kill(child, signal) {
5509
- if (child.exitCode !== null || child.signalCode !== null) return;
5510
- try {
5511
- child.kill(signal);
5512
- } catch {
5513
- return;
5514
- }
5515
- if (signal === "SIGTERM") {
5516
- const timer = setTimeout(() => {
5517
- if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
5518
- }, KILL_MS);
5519
- timer.unref?.();
5520
- }
5709
+ /** Asks a server to stop (SIGTERM, or the same delivered to its thread), forced after `KILL_MS`. */
5710
+ stopChild(child) {
5711
+ if (child.ended) return;
5712
+ if (child.mode === "threads") this.stopping.add(child);
5713
+ child.once("exit", () => this.stopping.delete(child));
5714
+ child.stop(KILL_MS);
5521
5715
  }
5522
- killAll(signal) {
5523
- for (const s of this.byType.values()) if (s.child) this.kill(s.child, signal);
5716
+ /** This process is exiting: what still runs is asked to stop (a thread ends with the process anyway). */
5717
+ killAll() {
5718
+ for (const s of this.byType.values()) if (s.child && !s.child.ended) s.child.stop(KILL_MS);
5719
+ }
5720
+ /**
5721
+ * Resolves once the servers that run in this process's threads have ended (after {@link closeAll}), or after
5722
+ * `timeoutMs`: the daemon waits for them before it exits, so each finishes its own clean-up as a process would. Child
5723
+ * processes are not waited for: they finish by themselves.
5724
+ */
5725
+ async drained(timeoutMs = KILL_MS + 1e3) {
5726
+ const left = [...this.stopping].filter((child) => !child.ended);
5727
+ if (!left.length) return;
5728
+ await Promise.race([
5729
+ Promise.all(left.map((child) => new Promise((done) => child.ended ? done(null) : child.once("exit", done)))),
5730
+ new Promise((done) => setTimeout(done, timeoutMs))
5731
+ ]);
5524
5732
  }
5525
5733
  /** Stops every server. */
5526
5734
  closeAll() {
@@ -5702,9 +5910,9 @@ ${CHATGPT_NOTE}`.trim();
5702
5910
  if (!res.headersSent) res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }));
5703
5911
  });
5704
5912
  });
5705
- await new Promise((resolve13, reject) => {
5913
+ await new Promise((resolve14, reject) => {
5706
5914
  server.once("error", reject);
5707
- server.listen(options.port, "127.0.0.1", () => resolve13());
5915
+ server.listen(options.port, "127.0.0.1", () => resolve14());
5708
5916
  });
5709
5917
  return server;
5710
5918
  }
@@ -8041,7 +8249,7 @@ var init_mcp2 = __esm({
8041
8249
  import { execFile } from "node:child_process";
8042
8250
  import { existsSync as existsSync13, readdirSync as readdirSync10, readFileSync as readFileSync13, statSync as statSync8 } from "node:fs";
8043
8251
  import { homedir as homedir5 } from "node:os";
8044
- import { delimiter, isAbsolute as isAbsolute3, join as join20 } from "node:path";
8252
+ import { delimiter, isAbsolute as isAbsolute4, join as join20 } from "node:path";
8045
8253
  function expandHome2(path, home2) {
8046
8254
  if (path === "~") return home2;
8047
8255
  return path.startsWith("~/") ? join20(home2, path.slice(2)) : path;
@@ -8085,7 +8293,7 @@ function nudgeProgram(command, home2, options = {}) {
8085
8293
  return { command: filled, args: before };
8086
8294
  }
8087
8295
  const path = expandHome2(filled, home2);
8088
- if (isAbsolute3(path) || path.includes("/") || path.includes("\\")) {
8296
+ if (isAbsolute4(path) || path.includes("/") || path.includes("\\")) {
8089
8297
  if (platform === "win32" && isBatch(path)) {
8090
8298
  if (existsSync13(path)) skipBatch(path);
8091
8299
  continue;
@@ -8341,7 +8549,7 @@ var init_remote_archive = __esm({
8341
8549
  import { createHash as createHash6 } from "node:crypto";
8342
8550
  import { existsSync as existsSync14, mkdirSync as mkdirSync6, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync6, statSync as statSync9, writeFileSync as writeFileSync4 } from "node:fs";
8343
8551
  import { homedir as homedir6 } from "node:os";
8344
- import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join22, resolve as resolve11, sep as sep6 } from "node:path";
8552
+ import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute5, join as join22, resolve as resolve12, sep as sep6 } from "node:path";
8345
8553
  import { fileURLToPath as fileURLToPath4 } from "node:url";
8346
8554
  function offlineOf(link, record) {
8347
8555
  const note = link?.offlineNote(record);
@@ -8422,10 +8630,10 @@ function localPathIn(value, at, root, depth = 0) {
8422
8630
  return null;
8423
8631
  }
8424
8632
  }
8425
- if (!isAbsolute4(path) || resolve11(path) === resolve11("/")) return null;
8633
+ if (!isAbsolute5(path) || resolve12(path) === resolve12("/")) return null;
8426
8634
  const home2 = homedir6();
8427
- const full = resolve11(path);
8428
- const under = (dir) => !!dir && (full === resolve11(dir) || full.startsWith(resolve11(dir) + sep6));
8635
+ const full = resolve12(path);
8636
+ const under = (dir) => !!dir && (full === resolve12(dir) || full.startsWith(resolve12(dir) + sep6));
8429
8637
  return under(home2) || under(root) || existsSync14(full) ? { at, path: value } : null;
8430
8638
  }
8431
8639
  if (depth >= 8 || !value || typeof value !== "object") return null;
@@ -8756,7 +8964,7 @@ ${rules}` };
8756
8964
  const wanted = significant(text3);
8757
8965
  if (!wanted.size) return [];
8758
8966
  const me = sessionKeyOf(caller2);
8759
- const workspace = caller2.workspace ? resolve11(caller2.workspace) + sep6 : null;
8967
+ const workspace = caller2.workspace ? resolve12(caller2.workspace) + sep6 : null;
8760
8968
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
8761
8969
  return this.o.store.list().filter((a) => a.type === type.id && (mine(a) || reuse === "workspace" && !!workspace && a.root.startsWith(workspace))).map((a) => ({ a, score: [...significant(a.title)].filter((w) => wanted.has(w)).length })).filter(({ score }) => score > 0).sort((x, y) => y.score - x.score || String(y.a.updatedAt).localeCompare(String(x.a.updatedAt))).slice(0, EXISTING_MAX).map(({ a }) => ({ url: artifactUrl(a.id), title: a.title, type: a.type, updatedAt: a.updatedAt, root: a.root, mine: mine(a) }));
8762
8970
  }
@@ -8764,7 +8972,7 @@ ${rules}` };
8764
8972
  relatedTo(type, caller2) {
8765
8973
  if (!type.uses.length) return [];
8766
8974
  const me = sessionKeyOf(caller2);
8767
- const workspace = caller2.workspace ? resolve11(caller2.workspace) + sep6 : null;
8975
+ const workspace = caller2.workspace ? resolve12(caller2.workspace) + sep6 : null;
8768
8976
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
8769
8977
  return this.o.store.list().filter((a) => type.uses.includes(a.type) && (mine(a) || workspace && a.root.startsWith(workspace))).sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt))).slice(0, RELATED_MAX).map((a) => ({ url: artifactUrl(a.id), title: a.title, type: a.type, root: a.root, mine: mine(a), updatedAt: a.updatedAt }));
8770
8978
  }
@@ -8781,7 +8989,7 @@ ${rules}` };
8781
8989
  const offset = args.cursor === void 0 || args.cursor === "" ? 0 : Number(args.cursor);
8782
8990
  if (!Number.isInteger(offset) || offset < 0) throw new OpenArtifactError("invalid_argument", "cursor: the next_cursor of the previous page.");
8783
8991
  const me = sessionKeyOf(caller2);
8784
- const workspace = caller2.workspace ? resolve11(caller2.workspace) + sep6 : null;
8992
+ const workspace = caller2.workspace ? resolve12(caller2.workspace) + sep6 : null;
8785
8993
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
8786
8994
  const changed = (a) => !!a.lastUserEditAt && (!a.agentSeenAt || a.lastUserEditAt > a.agentSeenAt);
8787
8995
  const shown = this.o.store.list().filter((a) => scope === "all" || mine(a) || workspace && a.root.startsWith(workspace)).filter((a) => (!typeId || a.type === typeId) && (!query || a.title.toLowerCase().includes(query)));
@@ -8812,8 +9020,8 @@ ${rules}` };
8812
9020
  * A caller with no known workspace gets the home folder, never the daemon's own folder (which may be a plugin's).
8813
9021
  */
8814
9022
  resolveFolder(folder, caller2, title) {
8815
- const base = caller2.workspace ? resolve11(caller2.workspace) : homedir6();
8816
- if (folder) return resolve11(base, folder);
9023
+ const base = caller2.workspace ? resolve12(caller2.workspace) : homedir6();
9024
+ if (folder) return resolve12(base, folder);
8817
9025
  const dir = join22(base, this.o.settings().artifactsDir || "artifacts");
8818
9026
  const slug = slugify(title);
8819
9027
  let root = join22(dir, slug);
@@ -9322,11 +9530,11 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
9322
9530
  const noStore = new OpenArtifactError("unsupported", `${record.type} keeps no document store: write its files with Artifact publish.`);
9323
9531
  const db = (name, a) => this.action(record, name, a, noStore);
9324
9532
  const docPath = args.path ?? (args.collection && args.doc_id ? `${args.collection}/${args.doc_id}` : args.collection);
9325
- const base = caller2.workspace ? resolve11(caller2.workspace) : record.root;
9533
+ const base = caller2.workspace ? resolve12(caller2.workspace) : record.root;
9326
9534
  const writeOf = (w) => {
9327
9535
  const out2 = {};
9328
9536
  for (const key of DATA_WRITE_KEYS) if (w[key] !== void 0) out2[key] = w[key];
9329
- if (typeof out2.file_path === "string" && out2.file_path) out2.file_path = resolve11(base, out2.file_path);
9537
+ if (typeof out2.file_path === "string" && out2.file_path) out2.file_path = resolve12(base, out2.file_path);
9330
9538
  return out2;
9331
9539
  };
9332
9540
  const write = async (writes) => {
@@ -9374,7 +9582,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
9374
9582
  }
9375
9583
  /** A read's result written to a JSON file: the agent reads it from disk instead of its context. */
9376
9584
  dataToFile(record, result, outFile, base) {
9377
- const file = resolve11(base, outFile);
9585
+ const file = resolve12(base, outFile);
9378
9586
  if (file === record.root || file.startsWith(record.root + sep6)) throw new OpenArtifactError("bad_path", "out_file goes outside the artifact folder: a file there would become part of the artifact.");
9379
9587
  mkdirSync6(dirname9(file), { recursive: true });
9380
9588
  const { notes, url: _url, ...data } = result;
@@ -9460,7 +9668,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
9460
9668
  const touched = /* @__PURE__ */ new Set();
9461
9669
  const records = this.o.store.list();
9462
9670
  for (const p of paths) {
9463
- const abs = resolve11(caller2.workspace ?? "/", p);
9671
+ const abs = resolve12(caller2.workspace ?? "/", p);
9464
9672
  const record = records.find((a) => abs === a.root || abs.startsWith(a.root + sep6));
9465
9673
  if (record && !touched.has(record.id)) {
9466
9674
  touched.add(record.id);
@@ -9638,16 +9846,16 @@ __export(daemon_exports, {
9638
9846
  takeOverPrompt: () => takeOverPrompt
9639
9847
  });
9640
9848
  import { randomBytes as randomBytes8 } from "node:crypto";
9641
- import { EventEmitter as EventEmitter4 } from "node:events";
9849
+ import { EventEmitter as EventEmitter5 } from "node:events";
9642
9850
  import { appendFileSync as appendFileSync3, cpSync as cpSync2, createReadStream, existsSync as existsSync15, openSync as openSync4, readFileSync as readFileSync15, readdirSync as readdirSync12, rmSync as rmSync7, statSync as statSync10, watch as watch3, writeFileSync as writeFileSync5, writeSync, closeSync as closeSync4 } from "node:fs";
9643
9851
  import { createServer as createServer2 } from "node:http";
9644
9852
  import { userInfo } from "node:os";
9645
- import { dirname as dirname10, extname as extname2, isAbsolute as isAbsolute5, join as join23, resolve as resolve12, sep as sep7 } from "node:path";
9853
+ import { dirname as dirname10, extname as extname2, isAbsolute as isAbsolute6, join as join23, resolve as resolve13, sep as sep7 } from "node:path";
9646
9854
  import { Readable } from "node:stream";
9647
9855
  import { fileURLToPath as fileURLToPath5 } from "node:url";
9648
9856
  function defaultUiDir(name) {
9649
9857
  const fromEnv = name === "shell" ? process.env.OPEN_ARTIFACT_SHELL_DIR : process.env.OPEN_ARTIFACT_HOME_DIR;
9650
- return fromEnv ? resolve12(fromEnv) : resolve12(here, "..", "..", "..", "dist", "daemon", name);
9858
+ return fromEnv ? resolve13(fromEnv) : resolve13(here, "..", "..", "..", "dist", "daemon", name);
9651
9859
  }
9652
9860
  function isContentPath(rel) {
9653
9861
  const parts = rel.split("/");
@@ -9781,6 +9989,7 @@ var init_daemon2 = __esm({
9781
9989
  init_ownership();
9782
9990
  init_paths();
9783
9991
  init_servers();
9992
+ init_node_children();
9784
9993
  init_preset();
9785
9994
  init_release_guard();
9786
9995
  init_runtime();
@@ -9892,7 +10101,7 @@ var init_daemon2 = __esm({
9892
10101
  </body>
9893
10102
  </html>
9894
10103
  `;
9895
- Daemon = class extends EventEmitter4 {
10104
+ Daemon = class extends EventEmitter5 {
9896
10105
  /** The listening port, once started. */
9897
10106
  port = 0;
9898
10107
  /** Bearer token of the Library and Harness APIs and MCP. */
@@ -9952,8 +10161,8 @@ var init_daemon2 = __esm({
9952
10161
  this.wantPort = options.port ?? this.settings.serverPort;
9953
10162
  this.idleMs = options.idleMs ?? Number(process.env.OPEN_ARTIFACT_IDLE_MS ?? 30 * 6e4);
9954
10163
  this.quiet = options.quiet ?? false;
9955
- this.shellDir = resolve12(options.shellDir ?? defaultUiDir("shell"));
9956
- this.homeDir = resolve12(options.homeDir ?? defaultUiDir("home"));
10164
+ this.shellDir = resolve13(options.shellDir ?? defaultUiDir("shell"));
10165
+ this.homeDir = resolve13(options.homeDir ?? defaultUiDir("home"));
9957
10166
  this.logFile = files.daemonLog();
9958
10167
  const log = (line) => this.log(line);
9959
10168
  this.types = new TypeRegistry(() => this.settings, options.builtinTypesDir !== void 0 ? { builtinDir: options.builtinTypesDir } : {});
@@ -10036,7 +10245,9 @@ var init_daemon2 = __esm({
10036
10245
  connected: () => [...new Set([...this.harnesses.connections].filter((c) => c.authed && c.harness).map((c) => c.harness))],
10037
10246
  switchTo: (candidate, env) => {
10038
10247
  this.close();
10039
- startDaemonProcess(candidate.bin, { env });
10248
+ const choice = nodeChildren();
10249
+ if (choice.mode === "threads" && process.versions.electron) this.log(`runtime: leaving for ${candidate.version}; the app that started this daemon starts it (${choice.detail})`);
10250
+ else startDaemonProcess(candidate.bin, { env });
10040
10251
  this.emit("exit");
10041
10252
  },
10042
10253
  ...process.env.OPEN_ARTIFACT_RUNTIME_CHECK_DELAY_MS ? { checkDelayMs: Number(process.env.OPEN_ARTIFACT_RUNTIME_CHECK_DELAY_MS) } : {}
@@ -10211,6 +10422,8 @@ data: ${JSON.stringify({ view, key: claimed.key, session: claimed.session })}
10211
10422
  this.timer = setInterval(() => this.tick(), 3e4);
10212
10423
  this.timer.unref?.();
10213
10424
  this.log(`daemon ${VERSION3} listening at ${this.origin} (home ${openArtifactHome2()})`);
10425
+ const badChildren = badModeVariable();
10426
+ if (badChildren) this.log(badChildren);
10214
10427
  try {
10215
10428
  this.runtime.start();
10216
10429
  } catch (error) {
@@ -10381,6 +10594,13 @@ data: ${JSON.stringify({ view, key: claimed.key, session: claimed.session })}
10381
10594
  this.emit("exit");
10382
10595
  }
10383
10596
  }
10597
+ /**
10598
+ * After {@link close}: resolves once the type servers in this process's worker threads have ended (bounded), so the
10599
+ * process can exit without cutting their clean-up short. At once when they are child processes.
10600
+ */
10601
+ drained() {
10602
+ return this.servers.drained();
10603
+ }
10384
10604
  /** Stops everything and removes `daemon.json` and the lock. */
10385
10605
  close() {
10386
10606
  if (this.closed) return;
@@ -10484,7 +10704,7 @@ data: ${JSON.stringify({ view, key: claimed.key, session: claimed.session })}
10484
10704
  }
10485
10705
  if (!isLoopback(req.socket.remoteAddress)) return this.notFound(req, res);
10486
10706
  if (p === "/__open-artifact/health") {
10487
- const health = { openArtifact: 1, version: VERSION3 };
10707
+ const health = { openArtifact: 1, version: VERSION3, nodeChildren: nodeChildren() };
10488
10708
  return sendJson(res, 200, health);
10489
10709
  }
10490
10710
  if (p === "/favicon.ico") {
@@ -10952,7 +11172,7 @@ ${rows}
10952
11172
  if (parts.some((part) => part.startsWith("."))) return this.notFound(req, res);
10953
11173
  let file;
10954
11174
  try {
10955
- file = parts.length ? inside(resolve12(base), parts.join("/")) : resolve12(base);
11175
+ file = parts.length ? inside(resolve13(base), parts.join("/")) : resolve13(base);
10956
11176
  } catch {
10957
11177
  return this.notFound(req, res);
10958
11178
  }
@@ -11298,7 +11518,7 @@ data: ${JSON.stringify({ type: "presence", id, ...this.presenceOf(record) })}
11298
11518
  const typeId = String(body.type ?? "").replace(/^open-artifact:\/\/type\//, "");
11299
11519
  if (!typeId) throw new OpenArtifactError("invalid_argument", "type: the type id (or open-artifact://type/<id>) to create from.");
11300
11520
  const folder = typeof body.folder === "string" && body.folder.trim() ? body.folder.trim() : void 0;
11301
- if (folder && !isAbsolute5(folder) && !folder.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
11521
+ if (folder && !isAbsolute6(folder) && !folder.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
11302
11522
  const caller2 = { harness: "open-artifact-home", session: null, workspace: this.settings.homeWorkspace };
11303
11523
  const made = await this.tools.call(
11304
11524
  "Artifact",
@@ -11407,7 +11627,7 @@ ${takeOverPrompt(record, view.typeTitle)}` : takeOverPrompt(record, view.typeTit
11407
11627
  }
11408
11628
  case "artifacts.publish": {
11409
11629
  const body = await readJsonBody(req);
11410
- const folder = typeof body.folder === "string" && body.folder ? resolve12(expandHome(body.folder)) : null;
11630
+ const folder = typeof body.folder === "string" && body.folder ? resolve13(expandHome(body.folder)) : null;
11411
11631
  let record = folder ? this.store.byRoot(folder) : this.store.require(body.id ?? body.url);
11412
11632
  let adopted = false;
11413
11633
  if (!record && folder && body.adopt === true) {
@@ -11559,7 +11779,7 @@ ${takeOverPrompt(record, view.typeTitle)}` : takeOverPrompt(record, view.typeTit
11559
11779
 
11560
11780
  // packages/daemon/src/bin/open-artifact.ts
11561
11781
  import { execFileSync } from "node:child_process";
11562
- import { readFileSync as readFileSync16, realpathSync as realpathSync3 } from "node:fs";
11782
+ import { readFileSync as readFileSync16, realpathSync as realpathSync4 } from "node:fs";
11563
11783
  import { resolve as resolvePath, sep as sep8 } from "node:path";
11564
11784
  import { createInterface as createInterface2 } from "node:readline";
11565
11785
 
@@ -12562,6 +12782,27 @@ var daemon = {
12562
12782
  return found2;
12563
12783
  }
12564
12784
  };
12785
+ var nodeChildren2 = {
12786
+ id: "node-children",
12787
+ title: "Type server processes",
12788
+ run: async ({ daemon: daemon3 }) => {
12789
+ const state = await daemon3();
12790
+ if (!state) return { status: "n/a", message: "The daemon is not running" };
12791
+ let health = null;
12792
+ try {
12793
+ health = await (await fetch(`${state.url}/__open-artifact/health`, { signal: AbortSignal.timeout(3e3) })).json();
12794
+ } catch {
12795
+ return { status: "warn", message: "The daemon did not answer its health check", fix: "Run open-artifact doctor again; if it persists, restart the daemon (open-artifact daemon stop)." };
12796
+ }
12797
+ const choice = health?.nodeChildren;
12798
+ if (!choice) return { status: "n/a", message: `Daemon ${health?.version ?? "?"} does not say how it runs type servers (older than 0.14.1)` };
12799
+ const why = choice.reason === "env" ? "set by OPEN_ARTIFACT_NODE_CHILDREN" : choice.reason === "node" ? "plain Node.js" : choice.detail;
12800
+ return {
12801
+ status: "ok",
12802
+ message: choice.mode === "threads" ? `Type servers run in worker threads of the daemon (${why}); no memory isolation from the daemon` : `Type servers run as child processes (${why})`
12803
+ };
12804
+ }
12805
+ };
12565
12806
  var runtime = {
12566
12807
  id: "runtime",
12567
12808
  title: "Runtime",
@@ -12649,7 +12890,7 @@ var settings = {
12649
12890
  }
12650
12891
  }
12651
12892
  };
12652
- var DOCTOR_CHECKS = [node, home, settings, daemon, runtime, types, harnessProfileCheck, harnessAdapter, tools, ...REMOTE_CHECKS, ...CONFORMANCE_CHECKS];
12893
+ var DOCTOR_CHECKS = [node, home, settings, daemon, nodeChildren2, runtime, types, harnessProfileCheck, harnessAdapter, tools, ...REMOTE_CHECKS, ...CONFORMANCE_CHECKS];
12653
12894
 
12654
12895
  // packages/daemon/src/stdio-bridge.ts
12655
12896
  init_src();
@@ -12668,9 +12909,9 @@ async function runStdioBridge(options) {
12668
12909
  };
12669
12910
  const waiting = /* @__PURE__ */ new Map();
12670
12911
  let next = 1;
12671
- const callHost = (method, params) => new Promise((resolve13, reject) => {
12912
+ const callHost = (method, params) => new Promise((resolve14, reject) => {
12672
12913
  const id = `d${next++}`;
12673
- waiting.set(id, { resolve: resolve13, reject });
12914
+ waiting.set(id, { resolve: resolve14, reject });
12674
12915
  write({ id, method, params });
12675
12916
  });
12676
12917
  let client = null;
@@ -12768,7 +13009,7 @@ async function runStdioBridge(options) {
12768
13009
  );
12769
13010
  };
12770
13011
  const lines = createInterface({ input: options.input, crlfDelay: Infinity });
12771
- await new Promise((resolve13) => {
13012
+ await new Promise((resolve14) => {
12772
13013
  lines.on("line", (line) => {
12773
13014
  if (Buffer.byteLength(line) > MAX_LINE2) {
12774
13015
  log("stdio: a line over 64 MiB; ending");
@@ -12777,7 +13018,7 @@ async function runStdioBridge(options) {
12777
13018
  }
12778
13019
  onLine(line);
12779
13020
  });
12780
- lines.on("close", resolve13);
13021
+ lines.on("close", resolve14);
12781
13022
  });
12782
13023
  for (const pending of waiting.values()) pending.reject(new OpenArtifactError("disconnected", "The host closed stdin."));
12783
13024
  waiting.clear();
@@ -12853,7 +13094,7 @@ function caller() {
12853
13094
  function ownWorkspace() {
12854
13095
  const real = (dir) => {
12855
13096
  try {
12856
- return realpathSync3(dir);
13097
+ return realpathSync4(dir);
12857
13098
  } catch {
12858
13099
  return resolvePath(dir);
12859
13100
  }
@@ -13120,10 +13361,11 @@ async function daemon2(sub) {
13120
13361
  const { startDaemon: startDaemon2 } = await Promise.resolve().then(() => (init_daemon2(), daemon_exports));
13121
13362
  const port = flag("port");
13122
13363
  const running = await startDaemon2(port !== void 0 ? { port: Number(port) } : {});
13123
- running.on("exit", () => process.exit(0));
13364
+ const exit = () => void running.drained().finally(() => process.exit(0));
13365
+ running.on("exit", exit);
13124
13366
  const stop = () => {
13125
13367
  running.close();
13126
- process.exit(0);
13368
+ exit();
13127
13369
  };
13128
13370
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, stop);
13129
13371
  process.on("uncaughtException", (error) => running.log(`uncaught: ${error?.stack ?? error}`));