dsh-open-artifact 0.16.0 → 0.16.2

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.
@@ -230,7 +230,7 @@ var init_library = __esm({
230
230
  function rpcErrorCode(code) {
231
231
  return code === "parse_error" ? RPC_ERRORS.parse : code === "method_not_found" ? RPC_ERRORS.methodNotFound : code === "invalid_argument" ? RPC_ERRORS.invalidParams : RPC_ERRORS.server;
232
232
  }
233
- var HARNESS_PATH, HARNESS_SUBPROTOCOL, PROTOCOL_MIN, PROTOCOL_MAX, HARNESS_FEATURES, PROFILE_RULES_MAX, RPC_ERRORS;
233
+ var HARNESS_PATH, HARNESS_SUBPROTOCOL, PROTOCOL_MIN, PROTOCOL_MAX, HARNESS_FEATURES, PROFILE_RULES_MAX, INBOX_RETURN_MAX, RPC_ERRORS;
234
234
  var init_harness = __esm({
235
235
  "packages/protocol/src/harness.ts"() {
236
236
  "use strict";
@@ -238,8 +238,9 @@ var init_harness = __esm({
238
238
  HARNESS_SUBPROTOCOL = "open-artifact-harness";
239
239
  PROTOCOL_MIN = 1;
240
240
  PROTOCOL_MAX = 1;
241
- HARNESS_FEATURES = Object.freeze(["hello.profile", "embed.origins", "shell.command", "shell.event", "view.context", "wake.from", "wake.drafted", "wake.session", "skill.get", "commands.list", "session.may", "tools.actions", "quickstart.steps", "types.remote", "hello.runtime", "runtime.update", "types.source", "view.open"]);
241
+ HARNESS_FEATURES = Object.freeze(["hello.profile", "embed.origins", "shell.command", "shell.event", "view.context", "wake.from", "wake.drafted", "wake.session", "skill.get", "commands.list", "session.may", "tools.actions", "quickstart.steps", "types.remote", "hello.runtime", "runtime.update", "types.source", "view.open", "inbox.return"]);
242
242
  PROFILE_RULES_MAX = 4e3;
243
+ INBOX_RETURN_MAX = 500;
243
244
  RPC_ERRORS = {
244
245
  parse: -32700,
245
246
  methodNotFound: -32601,
@@ -1311,7 +1312,10 @@ beyond it (running commands, sending things, opening links).`;
1311
1312
  \`changed\`, \`read\` lists the files they touched in \`changed_files\`, and \`notes\` say so: read those files again
1312
1313
  before writing. When you write through the tools, pass the \`sha256\` you read as \`if_match\`
1313
1314
  (\`Artifact {action: "publish", url, files, if_match}\`; \`ArtifactData\` \`set\` and \`delete\` of an existing document
1314
- need it). On a \`conflict\`, merge your change into \`current\` and write again.`,
1315
+ need it). On a \`conflict\`, merge your change into \`current\` and write again; \`executionStatus: "not_executed"\` on
1316
+ it means nothing was written.`,
1317
+ `Some apps keep you to your workspace: there a folder or a file path outside it (an action's \`file\` or \`out\`,
1318
+ ArtifactData's \`file_path\` or \`out_file\`) answers \`not_granted\`. Use a path inside the workspace instead.`,
1315
1319
  `To share it, \`Artifact {action: "open", url, panel: "share"}\` opens its Share panel for the person; to export
1316
1320
  (PDF, PPTX, PNG, …), \`panel: "export"\`. Only the person changes how an artifact is shared; never make share links
1317
1321
  yourself.`,
@@ -2149,12 +2153,12 @@ var init_declaration = __esm({
2149
2153
  const value = this.value();
2150
2154
  if (key !== "__proto__") Object.defineProperty(out2, key, { value, enumerable: true, configurable: true, writable: true });
2151
2155
  this.skip();
2152
- const sep12 = s[this.i];
2153
- if (sep12 === ",") {
2156
+ const sep13 = s[this.i];
2157
+ if (sep13 === ",") {
2154
2158
  this.i++;
2155
2159
  continue;
2156
2160
  }
2157
- if (sep12 === "}") continue;
2161
+ if (sep13 === "}") continue;
2158
2162
  this.fail(`\`,\` or \`}\` is expected, not ${this.describe()}`);
2159
2163
  }
2160
2164
  }
@@ -2183,12 +2187,12 @@ var init_declaration = __esm({
2183
2187
  if (c === "." && s.startsWith("...", this.i)) this.fail("A spread is not literal data");
2184
2188
  out2.push(this.value());
2185
2189
  this.skip();
2186
- const sep12 = s[this.i];
2187
- if (sep12 === ",") {
2190
+ const sep13 = s[this.i];
2191
+ if (sep13 === ",") {
2188
2192
  this.i++;
2189
2193
  continue;
2190
2194
  }
2191
- if (sep12 === "]") continue;
2195
+ if (sep13 === "]") continue;
2192
2196
  this.fail(`\`,\` or \`]\` is expected, not ${this.describe()}`);
2193
2197
  }
2194
2198
  }
@@ -3147,7 +3151,7 @@ var init_package = __esm({
3147
3151
  "packages/daemon/package.json"() {
3148
3152
  package_default = {
3149
3153
  name: "@open-artifact/daemon",
3150
- version: "0.16.0",
3154
+ version: "0.16.2",
3151
3155
  private: true,
3152
3156
  type: "module",
3153
3157
  description: "The Open Artifact daemon (`open-artifact`): type registry, artifact library, type servers, agent tools, wake routing, the Harness API, MCP and the Shell.",
@@ -3159,9 +3163,9 @@ var init_package = __esm({
3159
3163
  "./client": "./src/client.ts"
3160
3164
  },
3161
3165
  dependencies: {
3162
- "@open-artifact/harness-kit": "0.16.0",
3163
- "@open-artifact/protocol": "0.16.0",
3164
- "@open-artifact/server-sdk": "0.16.0"
3166
+ "@open-artifact/harness-kit": "0.16.2",
3167
+ "@open-artifact/protocol": "0.16.2",
3168
+ "@open-artifact/server-sdk": "0.16.2"
3165
3169
  },
3166
3170
  license: "Apache-2.0"
3167
3171
  };
@@ -4485,21 +4489,125 @@ var init_harness_skill = __esm({
4485
4489
  }
4486
4490
  });
4487
4491
 
4492
+ // packages/protocol/src/workspace-files.ts
4493
+ import { randomBytes as randomBytes2 } from "node:crypto";
4494
+ import { lstatSync, readFileSync as readFileSync6, realpathSync as realpathSync3, renameSync as renameSync2, statSync as statSync3, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
4495
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join10, relative as relative3, resolve as resolve8, sep as sep4 } from "node:path";
4496
+ function includesPath(root, target) {
4497
+ const path = relative3(root, target);
4498
+ return path !== ".." && !path.startsWith(".." + sep4) && !isAbsolute2(path);
4499
+ }
4500
+ function artifactDirectory({ root, workspaceDirectory }) {
4501
+ const workspace = workspaceDirectory ? new WorkspaceDirectory(workspaceDirectory.root, workspaceDirectory) : void 0;
4502
+ return new WorkspaceDirectory(workspace?.resolve(root) ?? root);
4503
+ }
4504
+ function readSharingState(files2) {
4505
+ return files2.readJson(SHARING_FILE, null);
4506
+ }
4507
+ var forbidden, WorkspaceDirectory, SHARING_FILE;
4508
+ var init_workspace_files = __esm({
4509
+ "packages/protocol/src/workspace-files.ts"() {
4510
+ "use strict";
4511
+ init_errors();
4512
+ forbidden = () => new OpenArtifactError("not_granted", "File is outside the authorized workspace.", { status: 403 });
4513
+ WorkspaceDirectory = class {
4514
+ root;
4515
+ givenRoot;
4516
+ device;
4517
+ inode;
4518
+ constructor(root, identity) {
4519
+ this.givenRoot = resolve8(root);
4520
+ this.root = realpathSync3(this.givenRoot);
4521
+ const stat2 = statSync3(this.root, { bigint: true });
4522
+ if (!stat2.isDirectory()) throw forbidden();
4523
+ this.device = stat2.dev;
4524
+ this.inode = stat2.ino;
4525
+ if (identity && (identity.root !== this.root || identity.device !== this.device.toString() || identity.inode !== this.inode.toString())) throw forbidden();
4526
+ }
4527
+ get identity() {
4528
+ return { root: this.root, device: this.device.toString(), inode: this.inode.toString() };
4529
+ }
4530
+ /** Read optional metadata from a checked file. */
4531
+ readJson(input, fallback) {
4532
+ try {
4533
+ return JSON.parse(readFileSync6(this.resolve(input), "utf8"));
4534
+ } catch {
4535
+ return fallback;
4536
+ }
4537
+ }
4538
+ /** Atomically replace a metadata entry inside this directory. */
4539
+ writeJson(input, value, mode2) {
4540
+ const file = this.resolve(input, false);
4541
+ const tmp = `${file}.${randomBytes2(8).toString("hex")}.tmp`;
4542
+ writeFileSync2(tmp, `${JSON.stringify(value, null, 2)}
4543
+ `, { flag: "wx", ...mode2 === void 0 ? {} : { mode: mode2 } });
4544
+ try {
4545
+ renameSync2(tmp, file);
4546
+ } catch (error) {
4547
+ try {
4548
+ unlinkSync(tmp);
4549
+ } catch {
4550
+ }
4551
+ throw error;
4552
+ }
4553
+ }
4554
+ /**
4555
+ * Check both the directory identity and the path. New files inherit the nearest existing parent's boundary. A path
4556
+ * spelled through a link to the workspace (macOS's `/var` for `/private/var`) is judged by where it really leads.
4557
+ */
4558
+ resolve(input, followLeaf = true) {
4559
+ const directory = lstatSync(this.root, { bigint: true });
4560
+ if (!directory.isDirectory() || directory.dev !== this.device || directory.ino !== this.inode) throw forbidden();
4561
+ const path = resolve8(this.givenRoot, input);
4562
+ const target = includesPath(this.givenRoot, path) ? resolve8(this.root, relative3(this.givenRoot, path)) : path;
4563
+ const outside = !includesPath(this.root, target);
4564
+ const tail = [];
4565
+ let ancestor = target;
4566
+ if (!followLeaf && target !== this.root) {
4567
+ tail.push(basename2(target));
4568
+ ancestor = dirname6(target);
4569
+ }
4570
+ let real;
4571
+ try {
4572
+ for (; ; ) {
4573
+ try {
4574
+ lstatSync(ancestor);
4575
+ break;
4576
+ } catch (error) {
4577
+ if (error.code !== "ENOENT" || ancestor === this.root || dirname6(ancestor) === ancestor) throw error;
4578
+ tail.unshift(basename2(ancestor));
4579
+ ancestor = dirname6(ancestor);
4580
+ }
4581
+ }
4582
+ real = realpathSync3(ancestor);
4583
+ } catch (error) {
4584
+ if (outside) throw forbidden();
4585
+ throw error;
4586
+ }
4587
+ const actual = join10(real, ...tail);
4588
+ if (!includesPath(this.root, actual)) throw forbidden();
4589
+ return actual;
4590
+ }
4591
+ };
4592
+ SHARING_FILE = ".sharing.json";
4593
+ }
4594
+ });
4595
+
4488
4596
  // packages/daemon/src/store.ts
4489
- import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
4597
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
4490
4598
  import { EventEmitter as EventEmitter2 } from "node:events";
4491
- import { existsSync as existsSync6, readdirSync as readdirSync6, renameSync as renameSync2 } from "node:fs";
4492
- import { join as join10, resolve as resolve8 } from "node:path";
4599
+ import { existsSync as existsSync6, readdirSync as readdirSync6, renameSync as renameSync3 } from "node:fs";
4600
+ import { join as join11, resolve as resolve9 } from "node:path";
4493
4601
  function newArtifactId() {
4494
4602
  const time = Date.now().toString(36).padStart(9, "0");
4495
- return `art_${time}${randomBytes2(8).toString("hex")}`;
4603
+ return `art_${time}${randomBytes3(8).toString("hex")}`;
4496
4604
  }
4497
4605
  function slugify(text3) {
4498
4606
  const slug = String(text3 ?? "").normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
4499
4607
  return slug || "artifact";
4500
4608
  }
4501
4609
  function hashWorkspace(workspace) {
4502
- return createHash2("sha1").update(resolve8(workspace)).digest("hex").slice(0, 12);
4610
+ return createHash2("sha1").update(resolve9(workspace)).digest("hex").slice(0, 12);
4503
4611
  }
4504
4612
  function sessionKeyOf(ref) {
4505
4613
  return sessionKey(ref, hashWorkspace);
@@ -4522,15 +4630,18 @@ var init_store = __esm({
4522
4630
  "use strict";
4523
4631
  init_src();
4524
4632
  init_paths();
4633
+ init_workspace_files();
4525
4634
  MAX_USER_EDITS = 200;
4526
4635
  ArtifactStore = class extends EventEmitter2 {
4527
- constructor() {
4636
+ enforceWorkspaceDirectories;
4637
+ constructor(enforceWorkspaceDirectories = false) {
4528
4638
  super();
4639
+ this.enforceWorkspaceDirectories = enforceWorkspaceDirectories;
4529
4640
  ensureDir(files.artifacts());
4530
4641
  }
4531
4642
  /** The record file of an id. */
4532
4643
  fileOf(id) {
4533
- return join10(files.artifacts(), `${id}.json`);
4644
+ return join11(files.artifacts(), `${id}.json`);
4534
4645
  }
4535
4646
  /** The record of an id, or `null`. */
4536
4647
  get(id) {
@@ -4559,7 +4670,7 @@ var init_store = __esm({
4559
4670
  const out2 = [];
4560
4671
  for (const name of names) {
4561
4672
  if (!name.endsWith(".json")) continue;
4562
- const record = readJson(join10(files.artifacts(), name), null);
4673
+ const record = readJson(join11(files.artifacts(), name), null);
4563
4674
  if (record?.id) out2.push(record);
4564
4675
  }
4565
4676
  return out2.sort(
@@ -4568,8 +4679,8 @@ var init_store = __esm({
4568
4679
  }
4569
4680
  /** The record whose folder is `root`, or `null`. */
4570
4681
  byRoot(root) {
4571
- const wanted = resolve8(root);
4572
- return this.list().find((a) => resolve8(a.root) === wanted) ?? null;
4682
+ const wanted = resolve9(root);
4683
+ return this.list().find((a) => resolve9(a.root) === wanted) ?? null;
4573
4684
  }
4574
4685
  /** Writes a record and emits `changed`. */
4575
4686
  save(record) {
@@ -4581,9 +4692,13 @@ var init_store = __esm({
4581
4692
  create(fields) {
4582
4693
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
4583
4694
  const owner = fields.owner ?? null;
4695
+ const identity = fields.workspaceDirectory;
4696
+ if (this.enforceWorkspaceDirectories && !identity) throw new OpenArtifactError("not_granted", "An authorized workspace is required.");
4697
+ const workspace = identity ? new WorkspaceDirectory(identity.root, identity) : void 0;
4584
4698
  const record = {
4585
4699
  id: newArtifactId(),
4586
- root: resolve8(fields.root),
4700
+ root: workspace?.resolve(fields.root) ?? resolve9(fields.root),
4701
+ ...identity ? { workspaceDirectory: identity } : {},
4587
4702
  type: fields.type,
4588
4703
  typeSource: fields.typeSource ?? null,
4589
4704
  typeRelease: fields.typeRelease ?? null,
@@ -4608,7 +4723,8 @@ var init_store = __esm({
4608
4723
  ...fields.typeUid && fields.typeFrom ? { typeSource: fields.typeFrom } : {},
4609
4724
  ...fields.capabilities ? { capabilities: fields.capabilities } : {}
4610
4725
  };
4611
- writeJson(join10(record.root, ".artifact.json"), marker);
4726
+ if (workspace) new WorkspaceDirectory(workspace.resolve(record.root)).writeJson(".artifact.json", marker);
4727
+ else writeJson(join11(record.root, ".artifact.json"), marker);
4612
4728
  return this.save(record);
4613
4729
  }
4614
4730
  /**
@@ -4618,13 +4734,26 @@ var init_store = __esm({
4618
4734
  setCapabilities(id, capabilities) {
4619
4735
  const record = this.get(id);
4620
4736
  if (!record) throw new OpenArtifactError("not_found", `No artifact ${id}.`);
4621
- const file = join10(record.root, ".artifact.json");
4622
- const marker = readJson(file, null) ?? { type: record.type, id: record.id, release: record.typeRelease };
4737
+ const folder = new WorkspaceDirectory(this.authorizedRoot(record));
4738
+ const marker = folder.readJson(".artifact.json", null) ?? { type: record.type, id: record.id, release: record.typeRelease };
4623
4739
  const { capabilities: _old, ...rest } = marker;
4624
- writeJson(file, capabilities ? { ...rest, capabilities } : rest);
4740
+ folder.writeJson(".artifact.json", capabilities ? { ...rest, capabilities } : rest);
4625
4741
  const { capabilities: _was, ...kept } = record;
4626
4742
  return this.save({ ...kept, ...capabilities ? { capabilities } : {}, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
4627
4743
  }
4744
+ /**
4745
+ * The real folder of an artifact. One made in a workspace-confined daemon ({@link ArtifactRecord.workspaceDirectory})
4746
+ * resolves inside the workspace it was made in, and fails `not_granted` when that folder was moved, replaced or now
4747
+ * leads outside it; in a confined daemon, an artifact with no workspace fails too.
4748
+ */
4749
+ authorizedRoot(record) {
4750
+ const identity = record.workspaceDirectory;
4751
+ if (!identity) {
4752
+ if (this.enforceWorkspaceDirectories) throw new OpenArtifactError("not_granted", "This artifact needs an authorized workspace.");
4753
+ return record.root;
4754
+ }
4755
+ return new WorkspaceDirectory(identity.root, identity).resolve(record.root);
4756
+ }
4628
4757
  /** Merges `patch` into a record; `updatedAt` moves unless the patch sets it. */
4629
4758
  update(id, patch) {
4630
4759
  const record = this.get(id);
@@ -4634,9 +4763,9 @@ var init_store = __esm({
4634
4763
  /** Puts back a record {@link remove} took out of the list (Undo). */
4635
4764
  restore(id) {
4636
4765
  if (!id || !ARTIFACT_ID.test(id)) return null;
4637
- const from = join10(files.trash(), `${id}.json`);
4766
+ const from = join11(files.trash(), `${id}.json`);
4638
4767
  if (!existsSync6(from)) return null;
4639
- renameSync2(from, this.fileOf(id));
4768
+ renameSync3(from, this.fileOf(id));
4640
4769
  const record = this.get(id);
4641
4770
  if (record) this.emit("changed", record);
4642
4771
  return record;
@@ -4646,7 +4775,7 @@ var init_store = __esm({
4646
4775
  const record = this.get(id);
4647
4776
  if (!record) return false;
4648
4777
  const trash = ensureDir(files.trash());
4649
- renameSync2(this.fileOf(id), join10(trash, `${id}.json`));
4778
+ renameSync3(this.fileOf(id), join11(trash, `${id}.json`));
4650
4779
  this.emit("changed", { ...record, removed: true });
4651
4780
  return true;
4652
4781
  }
@@ -4721,8 +4850,26 @@ var init_harness_view = __esm({
4721
4850
 
4722
4851
  // packages/daemon/src/harness.ts
4723
4852
  import { spawn as spawn2 } from "node:child_process";
4724
- import { randomBytes as randomBytes3 } from "node:crypto";
4853
+ import { randomBytes as randomBytes4 } from "node:crypto";
4725
4854
  import { EventEmitter as EventEmitter3 } from "node:events";
4855
+ function returnedMessages(raw) {
4856
+ if (!Array.isArray(raw)) throw new OpenArtifactError("invalid_argument", "inbox.return needs messages (an array).");
4857
+ const kept = [];
4858
+ for (const item of raw.slice(0, INBOX_RETURN_MAX)) {
4859
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
4860
+ const message4 = item;
4861
+ if (typeof message4.text !== "string" || !message4.text) continue;
4862
+ const filled = {
4863
+ ...message4,
4864
+ kind: typeof message4.kind === "string" && message4.kind ? message4.kind : "wake",
4865
+ text: message4.text,
4866
+ at: typeof message4.at === "string" && message4.at ? message4.at : (/* @__PURE__ */ new Date()).toISOString()
4867
+ };
4868
+ if (JSON.stringify(filled).length > INBOX_RETURN_MESSAGE_MAX) continue;
4869
+ kept.push(filled);
4870
+ }
4871
+ return kept;
4872
+ }
4726
4873
  function recentSessionMaxAgeMs() {
4727
4874
  const fromEnv = Number(process.env.OPEN_ARTIFACT_RECENT_SESSION_MS);
4728
4875
  return Number.isFinite(fromEnv) && process.env.OPEN_ARTIFACT_RECENT_SESSION_MS ? fromEnv : RECENT_SESSION_MS;
@@ -4764,7 +4911,7 @@ function sessionMayOf(value) {
4764
4911
  }
4765
4912
  return may;
4766
4913
  }
4767
- var CALL_TIMEOUT_MS, POLL_GRACE_MS, POLL_MAX_MS, INBOX_WAIT_MAX_MS, RECENT_SESSION_MS, DESKTOP_HARNESS, SocketConnection, PollConnection, HarnessHub;
4914
+ var CALL_TIMEOUT_MS, POLL_GRACE_MS, POLL_MAX_MS, INBOX_WAIT_MAX_MS, INBOX_RETURN_MESSAGE_MAX, RECENT_SESSION_MS, DESKTOP_HARNESS, SocketConnection, PollConnection, HarnessHub;
4768
4915
  var init_harness2 = __esm({
4769
4916
  "packages/daemon/src/harness.ts"() {
4770
4917
  "use strict";
@@ -4781,10 +4928,11 @@ var init_harness2 = __esm({
4781
4928
  POLL_GRACE_MS = Number(process.env.OPEN_ARTIFACT_POLL_GRACE_MS ?? 2e4);
4782
4929
  POLL_MAX_MS = 6e4;
4783
4930
  INBOX_WAIT_MAX_MS = 36e5;
4931
+ INBOX_RETURN_MESSAGE_MAX = 256 * 1024;
4784
4932
  RECENT_SESSION_MS = 2 * 60 * 6e4;
4785
4933
  DESKTOP_HARNESS = "open-artifact-desktop";
4786
4934
  SocketConnection = class {
4787
- id = randomBytes3(6).toString("hex");
4935
+ id = randomBytes4(6).toString("hex");
4788
4936
  harness = null;
4789
4937
  caps = {};
4790
4938
  authed = false;
@@ -4864,7 +5012,7 @@ var init_harness2 = __esm({
4864
5012
  }
4865
5013
  };
4866
5014
  PollConnection = class {
4867
- id = `poll-${randomBytes3(6).toString("hex")}`;
5015
+ id = `poll-${randomBytes4(6).toString("hex")}`;
4868
5016
  harness;
4869
5017
  caps;
4870
5018
  authed = true;
@@ -5353,6 +5501,15 @@ var init_harness2 = __esm({
5353
5501
  const timeout = Math.min(Number(params.timeoutMs) || 6e5, INBOX_WAIT_MAX_MS);
5354
5502
  return { messages: await this.options.inbox.wait(key, timeout) };
5355
5503
  }
5504
+ case "inbox.return": {
5505
+ const params = raw;
5506
+ const key = sessionKeyOf(this.callerOf(conn, params));
5507
+ if (!key) throw new OpenArtifactError("invalid_argument", "inbox.return needs session or workspace.");
5508
+ const messages = returnedMessages(params.messages);
5509
+ this.options.inbox.giveBack(key, messages);
5510
+ if (messages.length) this.options.log(`adapter ${harness}: ${messages.length} message(s) for ${key} put back in its inbox`);
5511
+ return { ok: true, returned: messages.length };
5512
+ }
5356
5513
  case "subscribe":
5357
5514
  conn.subscribed = raw.on !== false;
5358
5515
  return { ok: true };
@@ -5686,8 +5843,8 @@ var init_settings2 = __esm({
5686
5843
 
5687
5844
  // packages/daemon/src/type-authoring.ts
5688
5845
  import { randomUUID } from "node:crypto";
5689
- import { cpSync, existsSync as existsSync7, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync6, readdirSync as readdirSync7, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "node:fs";
5690
- import { basename as basename2, extname, join as join11, relative as relative3, resolve as resolve9, sep as sep4 } from "node:path";
5846
+ import { cpSync, existsSync as existsSync7, lstatSync as lstatSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync7, readdirSync as readdirSync7, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync3 } from "node:fs";
5847
+ import { basename as basename3, extname, join as join12, relative as relative4, resolve as resolve10, sep as sep5 } from "node:path";
5691
5848
  function checkNewTypeId(id) {
5692
5849
  const value = typeof id === "string" ? id.trim() : "";
5693
5850
  if (!TYPE_ID.test(value) || value !== value.toLowerCase()) {
@@ -5700,12 +5857,12 @@ function checkNewTypeId(id) {
5700
5857
  return value;
5701
5858
  }
5702
5859
  function authoringRoot(settings2, scope, project) {
5703
- if (scope === "user") return resolve9(settings2.typeRoots.user);
5860
+ if (scope === "user") return resolve10(settings2.typeRoots.user);
5704
5861
  if (!project) throw new OpenArtifactError("invalid_argument", "A project type needs the project folder.");
5705
- return resolve9(project, settings2.typeRoots.project);
5862
+ return resolve10(project, settings2.typeRoots.project);
5706
5863
  }
5707
5864
  function makeFolder(root, id) {
5708
- const dir = join11(root, id);
5865
+ const dir = join12(root, id);
5709
5866
  if (existsSync7(dir)) throw new OpenArtifactError("conflict", `${dir} is there already: pick another id, or change that type.`);
5710
5867
  mkdirSync3(root, { recursive: true });
5711
5868
  try {
@@ -5718,9 +5875,9 @@ function makeFolder(root, id) {
5718
5875
  }
5719
5876
  function writeAll(dir, written) {
5720
5877
  for (const [rel, text3] of Object.entries(written)) {
5721
- const file = join11(dir, rel);
5722
- mkdirSync3(join11(file, ".."), { recursive: true });
5723
- writeFileSync2(file, text3);
5878
+ const file = join12(dir, rel);
5879
+ mkdirSync3(join12(file, ".."), { recursive: true });
5880
+ writeFileSync3(file, text3);
5724
5881
  }
5725
5882
  return Object.keys(written).sort();
5726
5883
  }
@@ -5737,7 +5894,7 @@ function newType(args, o) {
5737
5894
  const scope = scopeOf(args.scope);
5738
5895
  const template = templateOf(args.template);
5739
5896
  const name = nameOf(args.name, id);
5740
- const project = typeof args.project === "string" && args.project ? resolve9(args.project) : o.workspace ?? null;
5897
+ const project = typeof args.project === "string" && args.project ? resolve10(args.project) : o.workspace ?? null;
5741
5898
  const dir = makeFolder(authoringRoot(o.settings, scope, project), id);
5742
5899
  const uid = randomUUID();
5743
5900
  try {
@@ -5963,13 +6120,13 @@ function checkType(dir, o) {
5963
6120
  const add = (p, level) => {
5964
6121
  (level === "error" ? errors : warnings).push({ level, ...p });
5965
6122
  };
5966
- const id = basename2(dir);
6123
+ const id = basename3(dir);
5967
6124
  const forShare = o.forShare === true;
5968
6125
  const out2 = () => ({ ok: errors.length === 0, id, dir, forShare, errors, warnings, ...caps ? { capabilities: caps } : {} });
5969
6126
  let caps;
5970
6127
  let st;
5971
6128
  try {
5972
- st = statSync3(dir);
6129
+ st = statSync4(dir);
5973
6130
  } catch {
5974
6131
  add({ code: "not_found", message: `${dir} is not there.` }, "error");
5975
6132
  return out2();
@@ -5979,17 +6136,17 @@ function checkType(dir, o) {
5979
6136
  return out2();
5980
6137
  }
5981
6138
  const builtinRoot = o.registry.roots().find((r) => r.scope === "builtin")?.root ?? null;
5982
- const isBuiltin = builtinRoot !== null && resolve9(dir) === resolve9(builtinRoot, id);
6139
+ const isBuiltin = builtinRoot !== null && resolve10(dir) === resolve10(builtinRoot, id);
5983
6140
  if (!TYPE_ID.test(id)) add({ code: "id_invalid", message: `The folder name ${JSON.stringify(id)} is not a type id: letters, digits, ".", "_" and "-", at most 64.` }, "error");
5984
6141
  else if (!isBuiltin && BUILTIN_TYPE_IDS.includes(id)) add({ code: "id_builtin", message: `${id} is a built-in type's id: this type would hide it. Rename the folder.` }, "error");
5985
6142
  else if (RESERVED_TYPE_IDS.includes(id)) add({ code: "id_reserved", message: `${id} is reserved. Rename the folder.` }, "error");
5986
- const manifestFile = join11(dir, "artifact-type.json");
6143
+ const manifestFile = join12(dir, "artifact-type.json");
5987
6144
  let manifest = null;
5988
6145
  if (!existsSync7(manifestFile)) {
5989
6146
  add({ code: "manifest_missing", file: "artifact-type.json", message: "There is no artifact-type.json: the type has no name, version or description of its own." }, forShare ? "error" : "warning");
5990
6147
  } else {
5991
6148
  try {
5992
- const parsed = JSON.parse(readFileSync6(manifestFile, "utf8"));
6149
+ const parsed = JSON.parse(readFileSync7(manifestFile, "utf8"));
5993
6150
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) add({ code: "manifest_invalid", file: "artifact-type.json", message: "artifact-type.json is not a JSON object." }, "error");
5994
6151
  else manifest = parsed;
5995
6152
  } catch (error) {
@@ -6004,7 +6161,7 @@ function checkType(dir, o) {
6004
6161
  if (typeof manifest.version !== "string" || !manifest.version) add({ code: "version_missing", file: "artifact-type.json", message: 'There is no "version".' }, "warning");
6005
6162
  }
6006
6163
  }
6007
- const info = readTypeFolder(dir, { root: resolve9(dir, ".."), scope: "user", trusted: true });
6164
+ const info = readTypeFolder(dir, { root: resolve10(dir, ".."), scope: "user", trusted: true });
6008
6165
  if (info) {
6009
6166
  for (const problem of info.problems) {
6010
6167
  if (problem.startsWith("artifact-type.json is not valid JSON")) continue;
@@ -6014,9 +6171,9 @@ function checkType(dir, o) {
6014
6171
  } else if (TYPE_ID.test(id)) {
6015
6172
  add({ code: "not_a_type", message: "This folder has neither index.html nor artifact-type.json." }, "error");
6016
6173
  }
6017
- const indexFile = join11(dir, "index.html");
6174
+ const indexFile = join12(dir, "index.html");
6018
6175
  if (existsSync7(indexFile)) {
6019
- const html = readFileSync6(indexFile, "utf8");
6176
+ const html = readFileSync7(indexFile, "utf8");
6020
6177
  if (DECLARATION_LINE.test(html) || declarationSource(html)) {
6021
6178
  try {
6022
6179
  const decl = readStaticDeclaration(html);
@@ -6053,18 +6210,18 @@ function checkType(dir, o) {
6053
6210
  }
6054
6211
  if (manifest?.skill !== false) {
6055
6212
  const skillName = typeof manifest?.skill === "string" ? manifest.skill : "SKILL.md";
6056
- const skillFile2 = resolve9(dir, skillName);
6057
- if (!skillFile2.startsWith(resolve9(dir) + sep4) || !existsSync7(skillFile2)) {
6213
+ const skillFile2 = resolve10(dir, skillName);
6214
+ if (!skillFile2.startsWith(resolve10(dir) + sep5) || !existsSync7(skillFile2)) {
6058
6215
  add({ code: "skill_missing", file: skillName, message: `There is no ${skillName}: agents would not know how to make one.` }, "error");
6059
6216
  } else {
6060
- const fm = readFrontmatter(readFileSync6(skillFile2, "utf8"));
6217
+ const fm = readFrontmatter(readFileSync7(skillFile2, "utf8"));
6061
6218
  for (const field of ["name", "description"]) {
6062
6219
  if (!fm[field]?.trim()) add({ code: "skill_frontmatter", file: skillName, message: `${skillName} has no "${field}" in its frontmatter.` }, "error");
6063
6220
  }
6064
6221
  }
6065
6222
  }
6066
6223
  const listed3 = o.registry.list(o.workspace ?? void 0, { includeShadowed: true });
6067
- const self = listed3.find((t) => resolve9(t.dir) === resolve9(dir));
6224
+ const self = listed3.find((t) => resolve10(t.dir) === resolve10(dir));
6068
6225
  if (self) {
6069
6226
  if (self.shadowedBy) add({ code: "shadowed", message: `A ${self.shadowedBy} type of the same id wins over this one.` }, "warning");
6070
6227
  const hidden = listed3.filter((t) => t.id === id && t !== self && t.shadowedBy);
@@ -6092,9 +6249,9 @@ function packageFolderEntries(dir) {
6092
6249
  const out2 = [];
6093
6250
  const walk = (folder) => {
6094
6251
  for (const name of readdirSync7(folder).sort()) {
6095
- const full = join11(folder, name);
6096
- const rel = relative3(dir, full).split(sep4).join("/");
6097
- const st = lstatSync(full);
6252
+ const full = join12(folder, name);
6253
+ const rel = relative4(dir, full).split(sep5).join("/");
6254
+ const st = lstatSync2(full);
6098
6255
  if (st.isDirectory()) {
6099
6256
  out2.push({ path: `${rel}/`, kind: "dir", size: 0 });
6100
6257
  if (!name.startsWith(".")) walk(full);
@@ -6105,10 +6262,10 @@ function packageFolderEntries(dir) {
6105
6262
  return out2;
6106
6263
  }
6107
6264
  function typeDirOf(target, registry, workspace, cwd = process.cwd()) {
6108
- if (target === "." || target === ".." || target.includes("/") || target.includes(sep4)) return resolve9(cwd, target);
6265
+ if (target === "." || target === ".." || target.includes("/") || target.includes(sep5)) return resolve10(cwd, target);
6109
6266
  const type = registry.list(workspace ?? void 0, { includeShadowed: false }).find((t) => t.id === target);
6110
6267
  if (type) return type.dir;
6111
- if (existsSync7(resolve9(cwd, target, "artifact-type.json")) || existsSync7(resolve9(cwd, target, "index.html"))) return resolve9(cwd, target);
6268
+ if (existsSync7(resolve10(cwd, target, "artifact-type.json")) || existsSync7(resolve10(cwd, target, "index.html"))) return resolve10(cwd, target);
6112
6269
  throw new OpenArtifactError("not_found", `No type ${target}.`, { fix: "open-artifact types list shows the types; or give the folder (./my-type)." });
6113
6270
  }
6114
6271
  function typeFromPage(record, type, args, o) {
@@ -6117,7 +6274,7 @@ function typeFromPage(record, type, args, o) {
6117
6274
  }
6118
6275
  const html = (() => {
6119
6276
  try {
6120
- return readFileSync6(join11(record.root, "index.html"), "utf8");
6277
+ return readFileSync7(join12(record.root, "index.html"), "utf8");
6121
6278
  } catch {
6122
6279
  throw new OpenArtifactError("not_found", `${record.title} has no index.html yet.`);
6123
6280
  }
@@ -6125,7 +6282,7 @@ function typeFromPage(record, type, args, o) {
6125
6282
  const id = checkNewTypeId(args.id);
6126
6283
  const scope = scopeOf(args.scope);
6127
6284
  const name = nameOf(args.name ?? record.title, id);
6128
- const project = typeof args.project === "string" && args.project ? resolve9(args.project) : o.workspace ?? null;
6285
+ const project = typeof args.project === "string" && args.project ? resolve10(args.project) : o.workspace ?? null;
6129
6286
  const capabilities = record.capabilities && typeof record.capabilities === "object" ? record.capabilities : {};
6130
6287
  const dir = makeFolder(authoringRoot(o.settings, scope, project), id);
6131
6288
  const uid = randomUUID();
@@ -6163,10 +6320,10 @@ files).
6163
6320
  `
6164
6321
  };
6165
6322
  const filesOut = writeAll(dir, written);
6166
- const own = join11(record.root, "artifact-type");
6167
- if (existsSync7(own) && statSync3(own).isDirectory()) {
6168
- cpSync(own, join11(dir, "artifact-type"), { recursive: true, dereference: false, filter: (src) => !basename2(src).startsWith(".") && !lstatSync(src).isSymbolicLink() });
6169
- for (const f of listFiles(join11(dir, "artifact-type"))) filesOut.push(`artifact-type/${f}`);
6323
+ const own = join12(record.root, "artifact-type");
6324
+ if (existsSync7(own) && statSync4(own).isDirectory()) {
6325
+ cpSync(own, join12(dir, "artifact-type"), { recursive: true, dereference: false, filter: (src) => !basename3(src).startsWith(".") && !lstatSync2(src).isSymbolicLink() });
6326
+ for (const f of listFiles(join12(dir, "artifact-type"))) filesOut.push(`artifact-type/${f}`);
6170
6327
  }
6171
6328
  const skipped = skippedOf(record.root);
6172
6329
  const check = checkType(dir, { ...o, workspace: scope === "project" ? project : o.workspace });
@@ -6269,13 +6426,13 @@ function iconOf(folder, meta) {
6269
6426
  const icon = meta?.icon;
6270
6427
  const file = icon && typeof icon === "object" && !Array.isArray(icon) ? icon.file : void 0;
6271
6428
  if (file === void 0) return null;
6272
- if (typeof file !== "string" || !file || file !== basename2(file) || file.startsWith(".") || file.includes("\\") || file.includes("\0")) {
6429
+ if (typeof file !== "string" || !file || file !== basename3(file) || file.startsWith(".") || file.includes("\\") || file.includes("\0")) {
6273
6430
  return { problem: `metadata.json names the icon ${JSON.stringify(file)}: an icon is a file name in the folder; not copied.` };
6274
6431
  }
6275
6432
  if (!ICON_TYPES.has(extname(file).toLowerCase())) return { problem: `The icon ${file} is not an image Open Artifact shows (${[...ICON_TYPES].join(", ")}); not copied.` };
6276
6433
  let st;
6277
6434
  try {
6278
- st = lstatSync(join11(folder, file));
6435
+ st = lstatSync2(join12(folder, file));
6279
6436
  } catch {
6280
6437
  return { problem: `metadata.json names the icon ${file}, which is not in the folder; not copied.` };
6281
6438
  }
@@ -6284,19 +6441,19 @@ function iconOf(folder, meta) {
6284
6441
  return { file };
6285
6442
  }
6286
6443
  function typeFromSaved(path, args, o) {
6287
- const source = resolve9(path);
6444
+ const source = resolve10(path);
6288
6445
  let st;
6289
6446
  try {
6290
- st = statSync3(source);
6447
+ st = statSync4(source);
6291
6448
  } catch {
6292
6449
  throw new OpenArtifactError("not_found", `${source} is not there.`);
6293
6450
  }
6294
6451
  const folder = st.isDirectory() ? source : null;
6295
- const indexFile = folder ? join11(folder, "index.html") : source;
6452
+ const indexFile = folder ? join12(folder, "index.html") : source;
6296
6453
  if (!folder && !/\.html?$/i.test(source)) throw new OpenArtifactError("invalid_argument", `${source} is neither a folder nor an .html file.`);
6297
6454
  let indexSt;
6298
6455
  try {
6299
- indexSt = statSync3(indexFile);
6456
+ indexSt = statSync4(indexFile);
6300
6457
  } catch {
6301
6458
  throw new OpenArtifactError("not_found", `${folder} has no index.html.`);
6302
6459
  }
@@ -6304,17 +6461,17 @@ function typeFromSaved(path, args, o) {
6304
6461
  if (indexSt.size > TYPE_PACKAGE_LIMITS.fileBytes) throw new OpenArtifactError("too_large", `${indexFile} is over ${TYPE_PACKAGE_LIMITS.fileBytes / 1024 / 1024} MB.`);
6305
6462
  const id = checkNewTypeId(args.id);
6306
6463
  const scope = scopeOf(args.scope);
6307
- const project = typeof args.project === "string" && args.project ? resolve9(args.project) : o.workspace ?? null;
6308
- const original = readFileSync6(indexFile, "utf8");
6464
+ const project = typeof args.project === "string" && args.project ? resolve10(args.project) : o.workspace ?? null;
6465
+ const original = readFileSync7(indexFile, "utf8");
6309
6466
  const stripped = stripFrameRuntime(original);
6310
6467
  const used = capabilitiesUsed(stripped);
6311
6468
  const { html, declared } = withInferredCapabilities(stripped, id, used.inferred);
6312
6469
  const capabilities = declared ? { inferred: [], stubbed: [], unknown: used.unknown, declared } : used;
6313
6470
  const notes = [];
6314
6471
  let meta = null;
6315
- if (folder && existsSync7(join11(folder, "metadata.json"))) {
6472
+ if (folder && existsSync7(join12(folder, "metadata.json"))) {
6316
6473
  try {
6317
- const parsed = JSON.parse(readFileSync6(join11(folder, "metadata.json"), "utf8"));
6474
+ const parsed = JSON.parse(readFileSync7(join12(folder, "metadata.json"), "utf8"));
6318
6475
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) meta = parsed;
6319
6476
  else notes.push("metadata.json is not a JSON object: it was not read.");
6320
6477
  } catch {
@@ -6363,7 +6520,7 @@ artifact of this type is a folder, \`<root>\`, whose files and data the page rea
6363
6520
  `, "index.html": html, "SKILL.md": skill };
6364
6521
  const filesOut = writeAll(dir, written);
6365
6522
  if (icon?.file) {
6366
- cpSync(join11(folder, icon.file), join11(dir, icon.file));
6523
+ cpSync(join12(folder, icon.file), join12(dir, icon.file));
6367
6524
  filesOut.push(icon.file);
6368
6525
  }
6369
6526
  const skipped = folder ? readdirSync7(folder, { withFileTypes: true }).map((e) => e.isDirectory() ? `${e.name}/` : e.name).filter((n) => n !== "index.html" && n !== "metadata.json" && n !== icon?.file && !n.startsWith(".")).sort() : [];
@@ -6401,7 +6558,7 @@ function listFiles(dir, base = "") {
6401
6558
  const out2 = [];
6402
6559
  for (const e of readdirSync7(dir, { withFileTypes: true })) {
6403
6560
  const rel = base ? `${base}/${e.name}` : e.name;
6404
- if (e.isDirectory()) out2.push(...listFiles(join11(dir, e.name), rel));
6561
+ if (e.isDirectory()) out2.push(...listFiles(join12(dir, e.name), rel));
6405
6562
  else out2.push(rel);
6406
6563
  }
6407
6564
  return out2;
@@ -6412,7 +6569,7 @@ function skippedOf(root) {
6412
6569
  if (e.name === "index.html" || e.name === "artifact-type") continue;
6413
6570
  if (e.isDirectory()) {
6414
6571
  if (COLLAPSED.has(e.name) || e.name.startsWith(".")) out2.push(`${e.name}/`);
6415
- else out2.push(...listFiles(join11(root, e.name), e.name));
6572
+ else out2.push(...listFiles(join12(root, e.name), e.name));
6416
6573
  } else out2.push(e.name);
6417
6574
  }
6418
6575
  return out2;
@@ -6434,9 +6591,9 @@ function setTypeEnabled(id, enabled) {
6434
6591
  function setProjectTrusted(dir, trusted) {
6435
6592
  const value = typeof dir === "string" ? dir.trim() : "";
6436
6593
  if (!value || !value.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(value)) throw new OpenArtifactError("invalid_argument", "dir: the project folder, as an absolute path.");
6437
- const full = resolve9(value);
6594
+ const full = resolve10(value);
6438
6595
  const lists = savedLists();
6439
- const next = lists.trustedProjects.filter((p) => resolve9(p) !== full);
6596
+ const next = lists.trustedProjects.filter((p) => resolve10(p) !== full);
6440
6597
  if (trusted) next.push(full);
6441
6598
  saveSettings({ trustedProjects: next });
6442
6599
  return { ok: true, disabledTypes: lists.disabledTypes, trustedProjects: next };
@@ -6568,10 +6725,10 @@ description: >-
6568
6725
  });
6569
6726
 
6570
6727
  // packages/server-sdk/src/zip.ts
6571
- import { randomBytes as randomBytes4 } from "node:crypto";
6728
+ import { randomBytes as randomBytes5 } from "node:crypto";
6572
6729
  import { constants } from "node:fs";
6573
6730
  import { lstat, mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises";
6574
- import { basename as basename3, dirname as dirname6, extname as extname2, join as join12, resolve as resolve10, sep as sep5 } from "node:path";
6731
+ import { basename as basename4, dirname as dirname7, extname as extname2, join as join13, resolve as resolve11, sep as sep6 } from "node:path";
6575
6732
  import { promisify } from "node:util";
6576
6733
  import { deflateRaw as deflateRawCallback, inflateRaw as inflateRawCallback, inflateRawSync } from "node:zlib";
6577
6734
  function view(bytes) {
@@ -6637,9 +6794,9 @@ function archiveKeeps(path) {
6637
6794
  return true;
6638
6795
  }
6639
6796
  async function archiveEntries(root, skip = []) {
6640
- const top = resolve10(root);
6641
- const folder = basename3(top) || "artifact";
6642
- const skipped = new Set(skip.map((file) => resolve10(file)));
6797
+ const top = resolve11(root);
6798
+ const folder = basename4(top) || "artifact";
6799
+ const skipped = new Set(skip.map((file) => resolve11(file)));
6643
6800
  const entries = [];
6644
6801
  const walk = async (dir, rel) => {
6645
6802
  let names;
@@ -6653,7 +6810,7 @@ async function archiveEntries(root, skip = []) {
6653
6810
  const name = dirent.name;
6654
6811
  const inner = rel ? `${rel}/${name}` : name;
6655
6812
  if (!keepsStep(rel, name, inner)) continue;
6656
- const file = join12(dir, name);
6813
+ const file = join13(dir, name);
6657
6814
  if (skipped.has(file)) continue;
6658
6815
  if (dirent.isDirectory()) await walk(file, inner);
6659
6816
  else if (dirent.isFile()) {
@@ -6756,7 +6913,7 @@ async function writeZip(entries, write) {
6756
6913
  }
6757
6914
  function archiveFileName(root, now2 = /* @__PURE__ */ new Date()) {
6758
6915
  const day = `${now2.getFullYear()}-${String(now2.getMonth() + 1).padStart(2, "0")}-${String(now2.getDate()).padStart(2, "0")}`;
6759
- return `${basename3(resolve10(root)) || "artifact"}-${day}.zip`;
6916
+ return `${basename4(resolve11(root)) || "artifact"}-${day}.zip`;
6760
6917
  }
6761
6918
  function attachmentHeader(name) {
6762
6919
  const ascii = name.replace(/[^\x20-\x7e]|["\\]/g, "_");
@@ -6894,9 +7051,9 @@ async function writeNewFile(file, data, mode2 = 420) {
6894
7051
  }
6895
7052
  }
6896
7053
  async function unpackZip(bytes, files2, dest, maxBytes) {
6897
- const target = resolve10(dest);
6898
- await mkdir(dirname6(target), { recursive: true });
6899
- const temp = join12(dirname6(target), `.${basename3(target)}.${randomBytes4(6).toString("hex")}.unpack`);
7054
+ const target = resolve11(dest);
7055
+ await mkdir(dirname7(target), { recursive: true });
7056
+ const temp = join13(dirname7(target), `.${basename4(target)}.${randomBytes5(6).toString("hex")}.unpack`);
6900
7057
  await mkdir(temp);
6901
7058
  try {
6902
7059
  let total = 0;
@@ -6904,9 +7061,9 @@ async function unpackZip(bytes, files2, dest, maxBytes) {
6904
7061
  const data = await unpackZipFile(bytes, item);
6905
7062
  total += data.length;
6906
7063
  if (total > maxBytes) throw new ZipRefusal("too_large", `It unpacks to more than ${maxBytes} bytes.`);
6907
- const file = resolve10(temp, ...item.path.split("/"));
6908
- if (!file.startsWith(temp + sep5)) throw new ZipRefusal("invalid", `${item.path} would land outside its folder.`);
6909
- await mkdir(dirname6(file), { recursive: true });
7064
+ const file = resolve11(temp, ...item.path.split("/"));
7065
+ if (!file.startsWith(temp + sep6)) throw new ZipRefusal("invalid", `${item.path} would land outside its folder.`);
7066
+ await mkdir(dirname7(file), { recursive: true });
6910
7067
  await writeNewFile(file, data, item.mode);
6911
7068
  }
6912
7069
  return { temp, files: files2.length, bytes: total };
@@ -7080,8 +7237,8 @@ var init_type_package2 = __esm({
7080
7237
 
7081
7238
  // packages/daemon/src/type-packages.ts
7082
7239
  import { createHash as createHash4 } from "node:crypto";
7083
- import { existsSync as existsSync8, readFileSync as readFileSync7, readdirSync as readdirSync8, renameSync as renameSync3, rmSync as rmSync3, statSync as statSync4, writeFileSync as writeFileSync3 } from "node:fs";
7084
- import { basename as basename4, join as join13, resolve as resolve11, sep as sep6 } from "node:path";
7240
+ import { existsSync as existsSync8, readFileSync as readFileSync8, readdirSync as readdirSync8, renameSync as renameSync4, rmSync as rmSync3, statSync as statSync5, writeFileSync as writeFileSync4 } from "node:fs";
7241
+ import { basename as basename5, join as join14, resolve as resolve12, sep as sep7 } from "node:path";
7085
7242
  function installedIndex() {
7086
7243
  const read = readJson(files.typesIndex(), null);
7087
7244
  const types3 = {};
@@ -7105,12 +7262,12 @@ ${check.errors.map((e) => ` - ${e.message}`).join("\n")}`, {
7105
7262
  fix: `Fix what open-artifact types check ${dir} --for-share lists, then pack it again.`
7106
7263
  });
7107
7264
  }
7108
- const manifest = JSON.parse(readFileSync7(join13(dir, "artifact-type.json"), "utf8"));
7109
- const id = basename4(resolve11(dir));
7265
+ const manifest = JSON.parse(readFileSync8(join14(dir, "artifact-type.json"), "utf8"));
7266
+ const id = basename5(resolve12(dir));
7110
7267
  const version = String(manifest.version);
7111
7268
  const entries = packageFolderEntries(dir).filter((e) => e.kind === "file").map((e) => {
7112
- const file = join13(dir, ...e.path.split("/"));
7113
- const st = statSync4(file);
7269
+ const file = join14(dir, ...e.path.split("/"));
7270
+ const st = statSync5(file);
7114
7271
  return { name: `${id}/${e.path}`, file, size: st.size, mode: st.mode & 511, mtime: st.mtime };
7115
7272
  });
7116
7273
  const bytes = await zipBytes(entries);
@@ -7119,8 +7276,8 @@ ${check.errors.map((e) => ` - ${e.message}`).join("\n")}`, {
7119
7276
  async function packType(dir, o) {
7120
7277
  const packed = await packTypeBytes(dir, o);
7121
7278
  const cwd = o.cwd ?? process.cwd();
7122
- const where2 = o.out ? resolve11(cwd, o.out) : cwd;
7123
- const file = existsSync8(where2) && statSync4(where2).isDirectory() ? join13(where2, packageFileName(packed.id, packed.version)) : where2;
7279
+ const where2 = o.out ? resolve12(cwd, o.out) : cwd;
7280
+ const file = existsSync8(where2) && statSync5(where2).isDirectory() ? join14(where2, packageFileName(packed.id, packed.version)) : where2;
7124
7281
  writeFileAtomic(file, packed.bytes);
7125
7282
  return { id: packed.id, version: packed.version, file, sha256: packed.sha256, bytes: packed.bytes.length, files: packed.files };
7126
7283
  }
@@ -7134,7 +7291,7 @@ async function readTypePackage(bytes, source, o = {}) {
7134
7291
  fix: `Install it under another id: open-artifact types install ${source} --as <id>.`
7135
7292
  });
7136
7293
  }
7137
- const folder = join13(files.installedTypes(), id);
7294
+ const folder = join14(files.installedTypes(), id);
7138
7295
  if (!known && existsSync8(folder)) {
7139
7296
  throw new OpenArtifactError("conflict", `${folder} exists but is not in ${files.typesIndex()}: it was not installed by open-artifact types install.`, {
7140
7297
  fix: `Move that folder away, or install this one under another id with --as <id>.`
@@ -7250,16 +7407,16 @@ function allowedUrl(address) {
7250
7407
  }
7251
7408
  async function loadTypePackage(target, cwd = process.cwd()) {
7252
7409
  if (isAddress(target)) return { bytes: await fetchTypePackage(target), source: target };
7253
- const file = resolve11(cwd, target);
7410
+ const file = resolve12(cwd, target);
7254
7411
  let st;
7255
7412
  try {
7256
- st = statSync4(file);
7413
+ st = statSync5(file);
7257
7414
  } catch {
7258
7415
  throw new OpenArtifactError("not_found", `${file} is not there.`);
7259
7416
  }
7260
7417
  if (!st.isFile()) throw refuse(`${file} is not a file.`);
7261
7418
  if (st.size > PACKAGE_DOWNLOAD_MAX) throw new OpenArtifactError("too_large", `${file} is ${st.size} bytes, more than a type package may be.`);
7262
- return { bytes: readFileSync7(file), source: file };
7419
+ return { bytes: readFileSync8(file), source: file };
7263
7420
  }
7264
7421
  async function installTypePackage(pkg, o = {}) {
7265
7422
  const { preview } = pkg;
@@ -7269,7 +7426,7 @@ async function installTypePackage(pkg, o = {}) {
7269
7426
  });
7270
7427
  }
7271
7428
  const root = ensureDir(files.installedTypes());
7272
- const dest = join13(root, preview.id);
7429
+ const dest = join14(root, preview.id);
7273
7430
  let unpacked;
7274
7431
  try {
7275
7432
  unpacked = await unpackZip(
@@ -7291,13 +7448,13 @@ ${listed2(again)}`);
7291
7448
  const known = installedEntry(preview.id);
7292
7449
  if (existsSync8(dest)) {
7293
7450
  if (!known || known.uid !== preview.uid) throw new OpenArtifactError("conflict", `${dest} exists and is not an install of this type.`);
7294
- aside = join13(root, `.${preview.id}.${Date.now().toString(36)}.old`);
7295
- renameSync3(dest, aside);
7451
+ aside = join14(root, `.${preview.id}.${Date.now().toString(36)}.old`);
7452
+ renameSync4(dest, aside);
7296
7453
  }
7297
7454
  await moveIntoPlace(temp, dest);
7298
7455
  } catch (error) {
7299
7456
  rmSync3(temp, { recursive: true, force: true });
7300
- if (aside && !existsSync8(dest)) renameSync3(aside, dest);
7457
+ if (aside && !existsSync8(dest)) renameSync4(aside, dest);
7301
7458
  throw error;
7302
7459
  }
7303
7460
  if (aside) rmSync3(aside, { recursive: true, force: true });
@@ -7318,13 +7475,13 @@ ${listed2(again)}`);
7318
7475
  function uninstallType(id) {
7319
7476
  if (!TYPE_ID.test(id)) throw refuse(`${JSON.stringify(id)} is not a type id.`);
7320
7477
  const index = installedIndex();
7321
- const dir = join13(files.installedTypes(), id);
7478
+ const dir = join14(files.installedTypes(), id);
7322
7479
  if (!Object.hasOwn(index.types, id)) {
7323
7480
  throw new OpenArtifactError("not_found", `${id} is not an installed type.`, { fix: "open-artifact types list shows each type with its source; only installed ones are uninstalled." });
7324
7481
  }
7325
7482
  if (existsSync8(dir)) {
7326
- const aside = join13(files.installedTypes(), `.${id}.${Date.now().toString(36)}.removed`);
7327
- renameSync3(dir, aside);
7483
+ const aside = join14(files.installedTypes(), `.${id}.${Date.now().toString(36)}.removed`);
7484
+ renameSync4(dir, aside);
7328
7485
  rmSync3(aside, { recursive: true, force: true });
7329
7486
  }
7330
7487
  delete index.types[id];
@@ -7341,21 +7498,21 @@ function stagePackage(bytes, source) {
7341
7498
  const now2 = Date.now();
7342
7499
  for (const name of readdirSync8(dir)) {
7343
7500
  try {
7344
- if (now2 - statSync4(join13(dir, name)).mtimeMs > 36e5) rmSync3(join13(dir, name), { force: true });
7501
+ if (now2 - statSync5(join14(dir, name)).mtimeMs > 36e5) rmSync3(join14(dir, name), { force: true });
7345
7502
  } catch {
7346
7503
  }
7347
7504
  }
7348
7505
  const hash = sha256(bytes);
7349
- writeFileSync3(join13(dir, `${hash}${TYPE_PACKAGE_EXTENSION}`), bytes);
7350
- writeFileSync3(join13(dir, `${hash}.json`), JSON.stringify({ source }));
7506
+ writeFileSync4(join14(dir, `${hash}${TYPE_PACKAGE_EXTENSION}`), bytes);
7507
+ writeFileSync4(join14(dir, `${hash}.json`), JSON.stringify({ source }));
7351
7508
  return hash;
7352
7509
  }
7353
7510
  function stagedPackage(hash) {
7354
7511
  if (!/^[0-9a-f]{64}$/.test(hash)) throw refuse("sha256 is the hex digest the preview gave.");
7355
7512
  const dir = files.typesStaging();
7356
7513
  try {
7357
- const bytes = readFileSync7(join13(dir, `${hash}${TYPE_PACKAGE_EXTENSION}`));
7358
- const { source } = JSON.parse(readFileSync7(join13(dir, `${hash}.json`), "utf8"));
7514
+ const bytes = readFileSync8(join14(dir, `${hash}${TYPE_PACKAGE_EXTENSION}`));
7515
+ const { source } = JSON.parse(readFileSync8(join14(dir, `${hash}.json`), "utf8"));
7359
7516
  if (sha256(bytes) !== hash) throw new Error("changed");
7360
7517
  return { bytes, source: String(source) };
7361
7518
  } catch {
@@ -7364,11 +7521,11 @@ function stagedPackage(hash) {
7364
7521
  }
7365
7522
  function unstagePackage(hash) {
7366
7523
  if (!/^[0-9a-f]{64}$/.test(hash)) return;
7367
- for (const ext of [TYPE_PACKAGE_EXTENSION, ".json"]) rmSync3(join13(files.typesStaging(), `${hash}${ext}`), { force: true });
7524
+ for (const ext of [TYPE_PACKAGE_EXTENSION, ".json"]) rmSync3(join14(files.typesStaging(), `${hash}${ext}`), { force: true });
7368
7525
  }
7369
7526
  function typeCapabilities(dir) {
7370
7527
  try {
7371
- const decl = readStaticDeclaration(readFileSync7(join13(dir, "index.html"), "utf8"));
7528
+ const decl = readStaticDeclaration(readFileSync8(join14(dir, "index.html"), "utf8"));
7372
7529
  return decl ? Object.keys(decl.capabilities) : [];
7373
7530
  } catch {
7374
7531
  return [];
@@ -7383,7 +7540,7 @@ function typeSourceOf(type) {
7383
7540
  function markerSourceOf(type) {
7384
7541
  const { source, installedFrom } = typeSourceOf(type);
7385
7542
  if (!installedFrom) return source;
7386
- return isAddress(installedFrom) ? installedFrom : basename4(installedFrom);
7543
+ return isAddress(installedFrom) ? installedFrom : basename5(installedFrom);
7387
7544
  }
7388
7545
  function typeMismatch(record, type) {
7389
7546
  if (!record.typeUid || !type) return null;
@@ -7427,11 +7584,11 @@ var init_type_packages = __esm({
7427
7584
  });
7428
7585
 
7429
7586
  // packages/daemon/src/runtime.ts
7430
- import { createHash as createHash5, randomBytes as randomBytes5 } from "node:crypto";
7431
- import { appendFileSync, chmodSync, cpSync as cpSync2, existsSync as existsSync10, mkdirSync as mkdirSync5, readdirSync as readdirSync9, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync5, writeFileSync as writeFileSync5 } from "node:fs";
7587
+ import { createHash as createHash5, randomBytes as randomBytes6 } from "node:crypto";
7588
+ import { appendFileSync, chmodSync, cpSync as cpSync2, existsSync as existsSync10, mkdirSync as mkdirSync5, readdirSync as readdirSync9, readFileSync as readFileSync10, renameSync as renameSync5, rmSync as rmSync4, statSync as statSync6, writeFileSync as writeFileSync6 } from "node:fs";
7432
7589
  import { cp } from "node:fs/promises";
7433
7590
  import { homedir as homedir4 } from "node:os";
7434
- import { dirname as dirname7, isAbsolute as isAbsolute2, join as join15, relative as relative4, resolve as resolve13, sep as sep7 } from "node:path";
7591
+ import { dirname as dirname8, isAbsolute as isAbsolute3, join as join16, relative as relative5, resolve as resolve14, sep as sep8 } from "node:path";
7435
7592
  import { gunzipSync } from "node:zlib";
7436
7593
  function runtimeLog(line) {
7437
7594
  try {
@@ -7463,7 +7620,7 @@ function saveRuntimeSettings(patch) {
7463
7620
  function machinePolicyFile(env = process.env) {
7464
7621
  if (env.OPEN_ARTIFACT_MACHINE_POLICY) return env.OPEN_ARTIFACT_MACHINE_POLICY;
7465
7622
  if (process.platform === "darwin") return "/Library/Application Support/Open Artifact/policy.json";
7466
- if (process.platform === "win32") return join15(env.ProgramData || "C:\\ProgramData", "Open Artifact", "policy.json");
7623
+ if (process.platform === "win32") return join16(env.ProgramData || "C:\\ProgramData", "Open Artifact", "policy.json");
7467
7624
  return "/etc/open-artifact/policy.json";
7468
7625
  }
7469
7626
  function machineOff(env = process.env) {
@@ -7510,7 +7667,7 @@ function npmrc(file) {
7510
7667
  const out2 = {};
7511
7668
  let text3;
7512
7669
  try {
7513
- text3 = readFileSync9(file, "utf8");
7670
+ text3 = readFileSync10(file, "utf8");
7514
7671
  } catch {
7515
7672
  return out2;
7516
7673
  }
@@ -7523,7 +7680,7 @@ function npmrc(file) {
7523
7680
  function registryUrl(env = process.env) {
7524
7681
  const scope = "@open-artifact:registry";
7525
7682
  const lower = (name) => env[name] ?? env[name.toUpperCase()];
7526
- const rc = npmrc(env.NPM_CONFIG_USERCONFIG || env.npm_config_userconfig || join15(homedir4(), ".npmrc"));
7683
+ const rc = npmrc(env.NPM_CONFIG_USERCONFIG || env.npm_config_userconfig || join16(homedir4(), ".npmrc"));
7527
7684
  const named2 = env.OPEN_ARTIFACT_REGISTRY || runtimeSettings().registry || lower(`npm_config_${scope}`) || lower("npm_config_registry") || rc[scope] || rc.registry || DEFAULT_REGISTRY;
7528
7685
  return named2.endsWith("/") ? named2 : `${named2}/`;
7529
7686
  }
@@ -7746,25 +7903,25 @@ function readTarball(gz) {
7746
7903
  return entries;
7747
7904
  }
7748
7905
  function writeEntries(entries, dest) {
7749
- const root = resolve13(dest);
7906
+ const root = resolve14(dest);
7750
7907
  mkdirSync5(root, { recursive: true });
7751
7908
  for (const entry of entries) {
7752
- const target = resolve13(root, ...safeTarPath(entry.path));
7753
- const rel = relative4(root, target);
7754
- if (!rel || rel.startsWith("..") || isAbsolute2(rel)) throw new OpenArtifactError("bad_archive", `The package has a path outside its folder: ${entry.path}.`);
7909
+ const target = resolve14(root, ...safeTarPath(entry.path));
7910
+ const rel = relative5(root, target);
7911
+ if (!rel || rel.startsWith("..") || isAbsolute3(rel)) throw new OpenArtifactError("bad_archive", `The package has a path outside its folder: ${entry.path}.`);
7755
7912
  if (entry.type === "dir") {
7756
7913
  mkdirSync5(target, { recursive: true, mode: 493 });
7757
7914
  continue;
7758
7915
  }
7759
- mkdirSync5(dirname7(target), { recursive: true, mode: 493 });
7760
- writeFileSync5(target, entry.data, { mode: entry.mode & 73 ? 493 : 420 });
7916
+ mkdirSync5(dirname8(target), { recursive: true, mode: 493 });
7917
+ writeFileSync6(target, entry.data, { mode: entry.mode & 73 ? 493 : 420 });
7761
7918
  chmodSync(target, entry.mode & 73 ? 493 : 420);
7762
7919
  }
7763
7920
  }
7764
7921
  function publishFolder(staging, version) {
7765
- const target = join15(sharedRuntimesOf(openArtifactHome2()), version);
7922
+ const target = join16(sharedRuntimesOf(openArtifactHome2()), version);
7766
7923
  try {
7767
- renameSync4(staging, target);
7924
+ renameSync5(staging, target);
7768
7925
  } catch (error) {
7769
7926
  rmSync4(staging, { recursive: true, force: true });
7770
7927
  if (!runtimeInfo(target)) throw error;
@@ -7773,11 +7930,11 @@ function publishFolder(staging, version) {
7773
7930
  }
7774
7931
  function stagingFolder(version) {
7775
7932
  const root = ensureDir(sharedRuntimesOf(openArtifactHome2()));
7776
- return join15(root, `.staging-${version}-${process.pid}-${randomBytes5(4).toString("hex")}`);
7933
+ return join16(root, `.staging-${version}-${process.pid}-${randomBytes6(4).toString("hex")}`);
7777
7934
  }
7778
7935
  async function installFromRegistry(manifest, registry) {
7779
7936
  const version = manifest.version;
7780
- const existing = join15(sharedRuntimesOf(openArtifactHome2()), version);
7937
+ const existing = join16(sharedRuntimesOf(openArtifactHome2()), version);
7781
7938
  if (runtimeInfo(existing)) return existing;
7782
7939
  const tarball = manifest.dist.tarball;
7783
7940
  const response = await get(tarball, "application/octet-stream", 12e4);
@@ -7787,13 +7944,13 @@ async function installFromRegistry(manifest, registry) {
7787
7944
  const staging = stagingFolder(version);
7788
7945
  try {
7789
7946
  writeEntries(entries, staging);
7790
- const pkg = readJson(join15(staging, "package.json"), null);
7947
+ const pkg = readJson(join16(staging, "package.json"), null);
7791
7948
  if (pkg?.name !== RUNTIME_PACKAGE || pkg.version !== version) {
7792
7949
  throw new OpenArtifactError("bad_archive", `The tarball is not ${RUNTIME_PACKAGE}@${version} (its package.json says ${String(pkg?.name)}@${String(pkg?.version)}).`);
7793
7950
  }
7794
7951
  if (!runtimeInfo(staging)) throw new OpenArtifactError("bad_archive", "The tarball has no scripts/open-artifact.mjs.");
7795
7952
  const record = { version, integrity: String(manifest.dist.integrity), tarball, registry, installedAt: (/* @__PURE__ */ new Date()).toISOString(), attestation: attestationOf(manifest) };
7796
- writeFileSync5(join15(staging, ".install.json"), `${JSON.stringify(record, null, 2)}
7953
+ writeFileSync6(join16(staging, ".install.json"), `${JSON.stringify(record, null, 2)}
7797
7954
  `);
7798
7955
  const dir = publishFolder(staging, version);
7799
7956
  runtimeLog(`installed ${RUNTIME_PACKAGE}@${version} in ${dir} (sha512 verified; attestation ${record.attestation.present ? "present, not verified" : "absent"})`);
@@ -7821,7 +7978,7 @@ function pruneShared(keep = []) {
7821
7978
  for (const name of names) {
7822
7979
  if (!name.startsWith(".staging-")) continue;
7823
7980
  try {
7824
- if (Date.now() - statSync5(join15(root, name)).mtimeMs > 60 * 6e4) rmSync4(join15(root, name), { recursive: true, force: true });
7981
+ if (Date.now() - statSync6(join16(root, name)).mtimeMs > 60 * 6e4) rmSync4(join16(root, name), { recursive: true, force: true });
7825
7982
  } catch {
7826
7983
  }
7827
7984
  }
@@ -7911,8 +8068,8 @@ function runtimeStatusText(status) {
7911
8068
  }
7912
8069
  function runtimeOfHello(value) {
7913
8070
  const runtime2 = value;
7914
- if (!runtime2 || typeof runtime2 !== "object" || typeof runtime2.dir !== "string" || !isAbsolute2(runtime2.dir) || typeof runtime2.version !== "string" || !parseVersion(runtime2.version)) return null;
7915
- return { dir: resolve13(runtime2.dir), version: runtime2.version, ...isPolicy(runtime2.update) ? { update: runtime2.update } : {} };
8071
+ if (!runtime2 || typeof runtime2 !== "object" || typeof runtime2.dir !== "string" || !isAbsolute3(runtime2.dir) || typeof runtime2.version !== "string" || !parseVersion(runtime2.version)) return null;
8072
+ return { dir: resolve14(runtime2.dir), version: runtime2.version, ...isPolicy(runtime2.update) ? { update: runtime2.update } : {} };
7916
8073
  }
7917
8074
  var RUNTIME_PACKAGE, DEFAULT_REGISTRY, CHECK_INTERVAL_MS, MAX_TARBALL, MAX_UNPACKED, MAX_METADATA, ADAPTER_MEMORY_MS, KEEP_SHARED, runtimeCheckFile, POLICIES, isPolicy, STRICTNESS, text, sourceOf, RuntimeManager;
7918
8075
  var init_runtime = __esm({
@@ -7929,7 +8086,7 @@ var init_runtime = __esm({
7929
8086
  MAX_METADATA = 32 << 20;
7930
8087
  ADAPTER_MEMORY_MS = 90 * 24 * 60 * 6e4;
7931
8088
  KEEP_SHARED = 3;
7932
- runtimeCheckFile = () => join15(openArtifactHome2(), "runtime-update.json");
8089
+ runtimeCheckFile = () => join16(openArtifactHome2(), "runtime-update.json");
7933
8090
  POLICIES = ["auto", "prompt", "bundled"];
7934
8091
  isPolicy = (value) => POLICIES.includes(value);
7935
8092
  STRICTNESS = { auto: 0, prompt: 1, bundled: 2 };
@@ -7976,7 +8133,7 @@ var init_runtime = __esm({
7976
8133
  /** Records a runtime in `runtimes.json` (one entry per folder) and copies it into the shared folder when it is the newest. */
7977
8134
  register(record) {
7978
8135
  this.writeFile((file) => {
7979
- file.runtimes = [...file.runtimes.filter((r) => resolve13(r.dir) !== resolve13(record.dir)), { ...record, seenAt: (/* @__PURE__ */ new Date()).toISOString() }];
8136
+ file.runtimes = [...file.runtimes.filter((r) => resolve14(r.dir) !== resolve14(record.dir)), { ...record, seenAt: (/* @__PURE__ */ new Date()).toISOString() }];
7980
8137
  });
7981
8138
  this.adopt(record);
7982
8139
  }
@@ -7986,12 +8143,12 @@ var init_runtime = __esm({
7986
8143
  */
7987
8144
  adopt(record) {
7988
8145
  const home2 = openArtifactHome2();
7989
- if (this.copying || !existsSync10(join15(record.dir, "vendor", "open-artifact.mjs"))) return;
7990
- if (resolve13(record.dir).startsWith(resolve13(sharedRuntimesOf(home2)) + sep7)) return;
8146
+ if (this.copying || !existsSync10(join16(record.dir, "vendor", "open-artifact.mjs"))) return;
8147
+ if (resolve14(record.dir).startsWith(resolve14(sharedRuntimesOf(home2)) + sep8)) return;
7991
8148
  const newest = sharedRuntimes(home2)[0]?.version;
7992
8149
  if (newest && compareVersions(record.version, newest) <= 0) return;
7993
8150
  const staging = stagingFolder(record.version);
7994
- this.copying = cp(record.dir, staging, { recursive: true, verbatimSymlinks: true, filter: (from) => !from.split(sep7).includes("node_modules") }).then(() => {
8151
+ this.copying = cp(record.dir, staging, { recursive: true, verbatimSymlinks: true, filter: (from) => !from.split(sep8).includes("node_modules") }).then(() => {
7995
8152
  const dir = publishFolder(staging, record.version);
7996
8153
  this.options.log(`runtime: kept a copy of ${record.harness ?? "a host"}'s runtime ${record.version} in ${dir}`);
7997
8154
  pruneShared([record.version, this.options.version]);
@@ -8088,8 +8245,8 @@ var init_runtime = __esm({
8088
8245
  // packages/daemon/src/node-children.ts
8089
8246
  import { spawn as spawn3 } from "node:child_process";
8090
8247
  import { EventEmitter as EventEmitter4 } from "node:events";
8091
- import { realpathSync as realpathSync3 } from "node:fs";
8092
- import { isAbsolute as isAbsolute3, resolve as resolve14 } from "node:path";
8248
+ import { realpathSync as realpathSync4 } from "node:fs";
8249
+ import { isAbsolute as isAbsolute4, resolve as resolve15 } from "node:path";
8093
8250
  import { PassThrough } from "node:stream";
8094
8251
  import { Worker } from "node:worker_threads";
8095
8252
  function modeFromEnv(env = process.env) {
@@ -8124,10 +8281,10 @@ function startChild(start) {
8124
8281
  function threadEntry(args, cwd) {
8125
8282
  const at = args.findIndex((arg) => !arg.startsWith("-"));
8126
8283
  if (at < 0) throw new Error(`no script to run in ${JSON.stringify(args)}`);
8127
- const given = isAbsolute3(args[at]) ? args[at] : resolve14(cwd, args[at]);
8284
+ const given = isAbsolute4(args[at]) ? args[at] : resolve15(cwd, args[at]);
8128
8285
  let script = given;
8129
8286
  try {
8130
- script = realpathSync3(given);
8287
+ script = realpathSync4(given);
8131
8288
  } catch {
8132
8289
  }
8133
8290
  return { execArgv: args.slice(0, at), script, args: args.slice(at + 1) };
@@ -8253,9 +8410,9 @@ import(pathToFileURL(workerData.script).href).catch((error) => {
8253
8410
  });
8254
8411
 
8255
8412
  // packages/daemon/src/servers.ts
8256
- import { randomBytes as randomBytes6 } from "node:crypto";
8257
- import { createWriteStream, statSync as statSync6 } from "node:fs";
8258
- import { dirname as dirname8, join as join17 } from "node:path";
8413
+ import { randomBytes as randomBytes7 } from "node:crypto";
8414
+ import { createWriteStream, statSync as statSync7 } from "node:fs";
8415
+ import { dirname as dirname9, join as join18 } from "node:path";
8259
8416
  function parseActions(raw) {
8260
8417
  if (!Array.isArray(raw)) return [];
8261
8418
  const out2 = [];
@@ -8292,7 +8449,7 @@ function failureOf(error, timeoutMs) {
8292
8449
  }
8293
8450
  function forRemote(type, body) {
8294
8451
  if (!typeLocation(type).remote || !body || typeof body !== "object" || Array.isArray(body) || !("root" in body)) return body;
8295
- const { root: _root, ...rest } = body;
8452
+ const { root: _root, workspaceDirectory: _workspace, ...rest } = body;
8296
8453
  return rest;
8297
8454
  }
8298
8455
  function refuseRedirect(type, url, response) {
@@ -8328,7 +8485,7 @@ async function cappedText(type, url, response, max = REMOTE_ANSWER_MAX) {
8328
8485
  function stampOf(type) {
8329
8486
  let mtime = 0;
8330
8487
  try {
8331
- mtime = statSync6(join17(type.dir, "artifact-type.json")).mtimeMs;
8488
+ mtime = statSync7(join18(type.dir, "artifact-type.json")).mtimeMs;
8332
8489
  } catch {
8333
8490
  }
8334
8491
  return JSON.stringify([type.dir, type.version, mtime, type.entry, type.trusted]);
@@ -8347,12 +8504,12 @@ var init_servers = __esm({
8347
8504
  ACTION_CALL_MS = 9e4;
8348
8505
  serverFiles = {
8349
8506
  /** Last address and pid (`servers/<type>.json`), to reuse the port. */
8350
- state: (type) => join17(files.servers(), `${type}.json`),
8507
+ state: (type) => join18(files.servers(), `${type}.json`),
8351
8508
  /** The server's own state folder (`OPEN_ARTIFACT_STATE_DIR`). */
8352
- stateDir: (type) => join17(files.servers(), type),
8353
- log: (type) => join17(files.logs(), "servers", `${type}.log`),
8509
+ stateDir: (type) => join18(files.servers(), type),
8510
+ log: (type) => join18(files.logs(), "servers", `${type}.log`),
8354
8511
  /** The last action list the server gave (`servers/<type>.actions.json`). */
8355
- actions: (type) => join17(files.servers(), `${type}.actions.json`)
8512
+ actions: (type) => join18(files.servers(), `${type}.actions.json`)
8356
8513
  };
8357
8514
  ACTION_NAME = /^[a-z0-9_-][a-z0-9_.-]{0,63}$/i;
8358
8515
  where = (type, url) => typeLocation(type).remote ? `${url.origin}${url.pathname}` : url.pathname;
@@ -8412,7 +8569,15 @@ var init_servers = __esm({
8412
8569
  const url2 = fillTemplate(entry.url, { id: record.id, lang: context.lang, root: record.root });
8413
8570
  return { url: url2, page_url: url2 };
8414
8571
  }
8415
- const request = { id: record.id, root: record.root, title: record.title, lang: context.lang || "en", shell: context.shell, viewer: context.shell + shellPath(record.id) };
8572
+ const request = {
8573
+ id: record.id,
8574
+ root: record.root,
8575
+ title: record.title,
8576
+ lang: context.lang || "en",
8577
+ shell: context.shell,
8578
+ viewer: context.shell + shellPath(record.id),
8579
+ ...record.workspaceDirectory ? { workspaceDirectory: record.workspaceDirectory } : {}
8580
+ };
8416
8581
  const out2 = await this.call(type, "POST", TYPE_SERVER_ROUTES.open, request);
8417
8582
  if (!out2 || typeof out2.url !== "string") throw new OpenArtifactError("server_failed", `${type.id}: ${TYPE_SERVER_ROUTES.open} returned no url.`);
8418
8583
  const url = new URL(out2.url, base).href;
@@ -8608,8 +8773,8 @@ var init_servers = __esm({
8608
8773
  const isNode = start.command === "node";
8609
8774
  const mode2 = isNode ? this.nodeMode() : "process";
8610
8775
  const last = readJson(serverFiles.state(type.id), null);
8611
- const secret = randomBytes6(24).toString("base64url");
8612
- ensureDir(dirname8(serverFiles.log(type.id)));
8776
+ const secret = randomBytes7(24).toString("base64url");
8777
+ ensureDir(dirname9(serverFiles.log(type.id)));
8613
8778
  const stateDir = ensureDir(serverFiles.stateDir(type.id));
8614
8779
  const log = createWriteStream(serverFiles.log(type.id), { flags: "a" });
8615
8780
  log.write(`
@@ -8794,20 +8959,20 @@ __export(chatgpt_exports, {
8794
8959
  chatgptSecret: () => chatgptSecret,
8795
8960
  serveChatGpt: () => serveChatGpt
8796
8961
  });
8797
- import { randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
8798
- import { existsSync as existsSync12, readFileSync as readFileSync11 } from "node:fs";
8962
+ import { randomBytes as randomBytes8, timingSafeEqual } from "node:crypto";
8963
+ import { existsSync as existsSync12, readFileSync as readFileSync12 } from "node:fs";
8799
8964
  import { createServer } from "node:http";
8800
- import { join as join19 } from "node:path";
8965
+ import { join as join20 } from "node:path";
8801
8966
  function chatgptSecret(rotate = false) {
8802
- const file = join19(openArtifactHome2(), "chatgpt.json");
8967
+ const file = join20(openArtifactHome2(), "chatgpt.json");
8803
8968
  if (!rotate && existsSync12(file)) {
8804
8969
  try {
8805
- const secret2 = JSON.parse(readFileSync11(file, "utf8")).secret;
8970
+ const secret2 = JSON.parse(readFileSync12(file, "utf8")).secret;
8806
8971
  if (secret2 && /^[A-Za-z0-9_-]{24,}$/.test(secret2)) return secret2;
8807
8972
  } catch {
8808
8973
  }
8809
8974
  }
8810
- const secret = randomBytes7(24).toString("base64url");
8975
+ const secret = randomBytes8(24).toString("base64url");
8811
8976
  writeJson(file, { secret });
8812
8977
  return secret;
8813
8978
  }
@@ -8955,9 +9120,9 @@ ${CHATGPT_NOTE}`.trim();
8955
9120
  if (!res.headersSent) res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }));
8956
9121
  });
8957
9122
  });
8958
- await new Promise((resolve17, reject) => {
9123
+ await new Promise((resolve18, reject) => {
8959
9124
  server.once("error", reject);
8960
- server.listen(options.port, "127.0.0.1", () => resolve17());
9125
+ server.listen(options.port, "127.0.0.1", () => resolve18());
8961
9126
  });
8962
9127
  return server;
8963
9128
  }
@@ -9056,29 +9221,29 @@ button:disabled{opacity:.55;cursor:default}
9056
9221
  });
9057
9222
 
9058
9223
  // packages/daemon/src/data-refresh.ts
9059
- import { existsSync as existsSync13, readFileSync as readFileSync12, readdirSync as readdirSync10 } from "node:fs";
9060
- import { join as join20 } from "node:path";
9224
+ import { existsSync as existsSync13, readFileSync as readFileSync13, readdirSync as readdirSync10 } from "node:fs";
9225
+ import { join as join21 } from "node:path";
9061
9226
  function hasSnapshot(root) {
9062
- return existsSync13(join20(root, "db", "data", "live.json")) || existsSync13(join20(root, "db", "data", "live", "answers"));
9227
+ return existsSync13(join21(root, "db", "data", "live.json")) || existsSync13(join21(root, "db", "data", "live", "answers"));
9063
9228
  }
9064
9229
  function liveQueryIds(root) {
9065
9230
  let names;
9066
9231
  try {
9067
- names = readdirSync10(join20(root, "db", "datasets"));
9232
+ names = readdirSync10(join21(root, "db", "datasets"));
9068
9233
  } catch {
9069
9234
  return [];
9070
9235
  }
9071
9236
  const ids = [];
9072
9237
  for (const name of names.sort()) {
9073
9238
  if (!name.endsWith(".json")) continue;
9074
- const doc = readJson2(join20(root, "db", "datasets", name));
9239
+ const doc = readJson2(join21(root, "db", "datasets", name));
9075
9240
  if (!isObject4(doc) || doc.snapshot === false || !isObject4(doc.source)) continue;
9076
9241
  if (doc.source.kind === "call" || doc.source.kind === "query") ids.push(name.slice(0, -5));
9077
9242
  }
9078
9243
  return ids;
9079
9244
  }
9080
9245
  function snapshotStatusOf(root) {
9081
- const doc = readJson2(join20(root, "db", "data", "live.json"));
9246
+ const doc = readJson2(join21(root, "db", "data", "live.json"));
9082
9247
  if (!isObject4(doc)) return { at: null, failed: null };
9083
9248
  const failed = isObject4(doc.failed) && typeof doc.failed.reason === "string" ? doc.failed.reason : null;
9084
9249
  return { at: typeof doc.at === "string" && doc.at ? doc.at : null, failed };
@@ -9097,7 +9262,7 @@ var init_data_refresh = __esm({
9097
9262
  message2 = (error) => error?.message ?? String(error);
9098
9263
  readJson2 = (path) => {
9099
9264
  try {
9100
- return JSON.parse(readFileSync12(path, "utf8"));
9265
+ return JSON.parse(readFileSync13(path, "utf8"));
9101
9266
  } catch {
9102
9267
  return null;
9103
9268
  }
@@ -9253,8 +9418,8 @@ var init_data_refresh = __esm({
9253
9418
  });
9254
9419
 
9255
9420
  // packages/daemon/src/inbox.ts
9256
- import { appendFileSync as appendFileSync2, readFileSync as readFileSync13, renameSync as renameSync5, rmSync as rmSync6, writeFileSync as writeFileSync6 } from "node:fs";
9257
- import { join as join21 } from "node:path";
9421
+ import { appendFileSync as appendFileSync2, readFileSync as readFileSync14, renameSync as renameSync6, rmSync as rmSync6, writeFileSync as writeFileSync7 } from "node:fs";
9422
+ import { join as join22 } from "node:path";
9258
9423
  var safe, Inbox;
9259
9424
  var init_inbox = __esm({
9260
9425
  "packages/daemon/src/inbox.ts"() {
@@ -9268,7 +9433,7 @@ var init_inbox = __esm({
9268
9433
  }
9269
9434
  /** The file of a session key. */
9270
9435
  fileOf(key) {
9271
- return join21(files.inbox(), `${safe(key)}.jsonl`);
9436
+ return join22(files.inbox(), `${safe(key)}.jsonl`);
9272
9437
  }
9273
9438
  /** Appends a message; an open wait for this key takes it at once (`taken: true`). */
9274
9439
  append(key, item) {
@@ -9289,7 +9454,7 @@ var init_inbox = __esm({
9289
9454
  peek(key) {
9290
9455
  let text3;
9291
9456
  try {
9292
- text3 = readFileSync13(this.fileOf(key), "utf8");
9457
+ text3 = readFileSync14(this.fileOf(key), "utf8");
9293
9458
  } catch {
9294
9459
  return [];
9295
9460
  }
@@ -9333,15 +9498,31 @@ var init_inbox = __esm({
9333
9498
  this.keep(key, items);
9334
9499
  return taken;
9335
9500
  }
9501
+ /**
9502
+ * Puts back messages that were taken but not delivered: an open wait takes them at once; otherwise they wait again,
9503
+ * ahead of what came since (they are older). Synchronous, as {@link takeWhere}.
9504
+ */
9505
+ giveBack(key, messages) {
9506
+ if (!messages.length) return;
9507
+ const waiting = this.waiters.get(key);
9508
+ const first = waiting?.values().next().value;
9509
+ if (waiting && first) {
9510
+ waiting.delete(first);
9511
+ first(messages);
9512
+ return;
9513
+ }
9514
+ ensureDir(files.inbox());
9515
+ this.keep(key, [...messages, ...this.peek(key)]);
9516
+ }
9336
9517
  /** Rewrites a key's file with `kept` only (removes it when empty). */
9337
9518
  keep(key, kept) {
9338
9519
  const file = this.fileOf(key);
9339
9520
  if (!kept.length) rmSync6(file, { force: true });
9340
9521
  else {
9341
9522
  const next = `${file}.${process.pid}.tmp`;
9342
- writeFileSync6(next, kept.map((item) => `${JSON.stringify(item)}
9523
+ writeFileSync7(next, kept.map((item) => `${JSON.stringify(item)}
9343
9524
  `).join(""));
9344
- renameSync5(next, file);
9525
+ renameSync6(next, file);
9345
9526
  }
9346
9527
  }
9347
9528
  /** The messages that are there, or the next ones to come, or `[]` after `timeoutMs`. */
@@ -9374,7 +9555,7 @@ var init_inbox = __esm({
9374
9555
 
9375
9556
  // packages/daemon/src/preset.ts
9376
9557
  import { createHash as createHash6 } from "node:crypto";
9377
- import { statSync as statSync8 } from "node:fs";
9558
+ import { statSync as statSync9 } from "node:fs";
9378
9559
  function presetFrom(source, plugin = false) {
9379
9560
  const get2 = (key) => text2(source[PRESET_KEYS[key]]);
9380
9561
  const out2 = {};
@@ -9412,7 +9593,7 @@ function readPreset(env = process.env) {
9412
9593
  function readableByOthers(path) {
9413
9594
  if (process.platform === "win32") return null;
9414
9595
  try {
9415
- const mode2 = statSync8(path).mode & 511;
9596
+ const mode2 = statSync9(path).mode & 511;
9416
9597
  return mode2 & 36 ? mode2 : null;
9417
9598
  } catch {
9418
9599
  return null;
@@ -10256,9 +10437,9 @@ var init_wake2 = __esm({
10256
10437
  });
10257
10438
 
10258
10439
  // packages/daemon/src/link.ts
10259
- import { createHash as createHash7, randomBytes as randomBytes8 } from "node:crypto";
10260
- import { existsSync as existsSync14, mkdirSync as mkdirSync6, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync7, statSync as statSync9, watch as watch2 } from "node:fs";
10261
- import { dirname as dirname9, extname as extname3, join as join22, sep as sep8 } from "node:path";
10440
+ import { createHash as createHash7, randomBytes as randomBytes9 } from "node:crypto";
10441
+ import { existsSync as existsSync14, mkdirSync as mkdirSync6, readFileSync as readFileSync15, readdirSync as readdirSync11, rmSync as rmSync7, statSync as statSync10, watch as watch2 } from "node:fs";
10442
+ import { dirname as dirname10, extname as extname3, join as join23, sep as sep9 } from "node:path";
10262
10443
  function wakeSenderOf(value) {
10263
10444
  if (!value || typeof value !== "object") return void 0;
10264
10445
  const { name, role } = value;
@@ -11121,7 +11302,7 @@ var init_link2 = __esm({
11121
11302
  if (typeof write?.file_path !== "string" || !write.file_path) return write;
11122
11303
  let data;
11123
11304
  try {
11124
- data = JSON.parse(readFileSync14(write.file_path, "utf8"));
11305
+ data = JSON.parse(readFileSync15(write.file_path, "utf8"));
11125
11306
  } catch (error) {
11126
11307
  throw new OpenArtifactError("invalid_argument", `file_path ${write.file_path}: ${message3(error)}`);
11127
11308
  }
@@ -11168,7 +11349,7 @@ var init_link2 = __esm({
11168
11349
  this.syncs.set(id, state);
11169
11350
  try {
11170
11351
  state.watcher = watch2(record.root, { recursive: true, persistent: false }, (_event, name) => {
11171
- const rel = String(name ?? "").split(sep8).join("/");
11352
+ const rel = String(name ?? "").split(sep9).join("/");
11172
11353
  if (rel && !linkSynced(rel) && rel !== ".artifact.json") return;
11173
11354
  this.schedule(id, 200);
11174
11355
  });
@@ -11255,15 +11436,15 @@ var init_link2 = __esm({
11255
11436
  for (const entry of entries) {
11256
11437
  const path = rel ? `${rel}/${entry.name}` : entry.name;
11257
11438
  if (!linkSynced(path)) continue;
11258
- const file = join22(dir, entry.name);
11439
+ const file = join23(dir, entry.name);
11259
11440
  if (entry.isDirectory()) walk(file, path);
11260
11441
  else if (entry.isFile()) {
11261
11442
  try {
11262
- const stat2 = statSync9(file);
11443
+ const stat2 = statSync10(file);
11263
11444
  const known = state.hashes.get(path);
11264
11445
  if (known && known.size === stat2.size && known.mtimeMs === stat2.mtimeMs) out2.set(path, known.etag);
11265
11446
  else {
11266
- const etag = sha2562(readFileSync14(file));
11447
+ const etag = sha2562(readFileSync15(file));
11267
11448
  state.hashes.set(path, { size: stat2.size, mtimeMs: stat2.mtimeMs, etag });
11268
11449
  out2.set(path, etag);
11269
11450
  }
@@ -11279,7 +11460,7 @@ var init_link2 = __esm({
11279
11460
  /** The working copy's etag of one path now, `null` when it is not there. */
11280
11461
  hashNow(root, path) {
11281
11462
  try {
11282
- return sha2562(readFileSync14(inside(root, path)));
11463
+ return sha2562(readFileSync15(inside(root, path)));
11283
11464
  } catch {
11284
11465
  return null;
11285
11466
  }
@@ -11347,7 +11528,7 @@ var init_link2 = __esm({
11347
11528
  for (const write of pushes) {
11348
11529
  let content = null;
11349
11530
  try {
11350
- const bytes = readFileSync14(inside(root, write.path));
11531
+ const bytes = readFileSync15(inside(root, write.path));
11351
11532
  content = bytes.toString("base64");
11352
11533
  batchBytes += bytes.length;
11353
11534
  } catch {
@@ -11363,7 +11544,7 @@ var init_link2 = __esm({
11363
11544
  const file = inside(root, path);
11364
11545
  const got = host.has(path) || conflicts.includes(path) ? await client.readFile(id, path) : null;
11365
11546
  if (got) {
11366
- mkdirSync6(dirname9(file), { recursive: true });
11547
+ mkdirSync6(dirname10(file), { recursive: true });
11367
11548
  writeFileAtomic(file, got.bytes);
11368
11549
  setBase(path, sha2562(got.bytes));
11369
11550
  } else {
@@ -11377,8 +11558,8 @@ var init_link2 = __esm({
11377
11558
  const file = inside(root, path);
11378
11559
  if (!existsSync14(file)) return;
11379
11560
  const copy = conflictFile(root, path);
11380
- mkdirSync6(dirname9(copy), { recursive: true });
11381
- writeFileAtomic(copy, readFileSync14(file));
11561
+ mkdirSync6(dirname10(copy), { recursive: true });
11562
+ writeFileAtomic(copy, readFileSync15(file));
11382
11563
  kept.push(path);
11383
11564
  };
11384
11565
  for (const path of pulls) {
@@ -11537,7 +11718,7 @@ var init_link2 = __esm({
11537
11718
  };
11538
11719
  const waits = [
11539
11720
  ...threads.map((thread) => this.o.wake(record.id, { thread: by(thread) })),
11540
- ...requests.map((r) => this.o.wake(record.id, { request: by({ ...r, id: r.id ?? `req_${Date.now().toString(36)}${randomBytes8(3).toString("hex")}` }) }))
11721
+ ...requests.map((r) => this.o.wake(record.id, { request: by({ ...r, id: r.id ?? `req_${Date.now().toString(36)}${randomBytes9(3).toString("hex")}` }) }))
11541
11722
  ];
11542
11723
  await Promise.all(waits);
11543
11724
  return;
@@ -11674,12 +11855,12 @@ var init_mcp2 = __esm({
11674
11855
 
11675
11856
  // packages/daemon/src/nudge.ts
11676
11857
  import { execFile } from "node:child_process";
11677
- import { existsSync as existsSync15, readdirSync as readdirSync12, readFileSync as readFileSync15, statSync as statSync10 } from "node:fs";
11858
+ import { existsSync as existsSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, statSync as statSync11 } from "node:fs";
11678
11859
  import { homedir as homedir5 } from "node:os";
11679
- import { delimiter, isAbsolute as isAbsolute4, join as join23 } from "node:path";
11860
+ import { delimiter, isAbsolute as isAbsolute5, join as join24 } from "node:path";
11680
11861
  function expandHome2(path, home2) {
11681
11862
  if (path === "~") return home2;
11682
- return path.startsWith("~/") ? join23(home2, path.slice(2)) : path;
11863
+ return path.startsWith("~/") ? join24(home2, path.slice(2)) : path;
11683
11864
  }
11684
11865
  function fillEnv(text3) {
11685
11866
  let missing = false;
@@ -11692,7 +11873,7 @@ function fillEnv(text3) {
11692
11873
  }
11693
11874
  function onPath(name, platform = process.platform, path = process.env.PATH ?? "") {
11694
11875
  const dirs = path.split(delimiter).filter(Boolean);
11695
- const at = (dir, file) => join23(dir, file);
11876
+ const at = (dir, file) => join24(dir, file);
11696
11877
  if (platform !== "win32") {
11697
11878
  for (const dir of dirs) if (isFile(at(dir, name))) return { found: at(dir, name) };
11698
11879
  return null;
@@ -11720,7 +11901,7 @@ function nudgeProgram(command, home2, options = {}) {
11720
11901
  return { command: filled, args: before };
11721
11902
  }
11722
11903
  const path = expandHome2(filled, home2);
11723
- if (isAbsolute4(path) || path.includes("/") || path.includes("\\")) {
11904
+ if (isAbsolute5(path) || path.includes("/") || path.includes("\\")) {
11724
11905
  if (platform === "win32" && isBatch(path)) {
11725
11906
  if (existsSync15(path)) skipBatch(path);
11726
11907
  continue;
@@ -11750,7 +11931,7 @@ function liveEnvFile(spec, needs, home2, alive2 = defaultAlive) {
11750
11931
  }
11751
11932
  for (const name of names) {
11752
11933
  try {
11753
- const fields = JSON.parse(readFileSync15(join23(dir, name), "utf8"));
11934
+ const fields = JSON.parse(readFileSync16(join24(dir, name), "utf8"));
11754
11935
  if (!fields || typeof fields !== "object" || needs.some((field) => fields[field] === void 0 || fields[field] === null || fields[field] === "")) continue;
11755
11936
  const pid = spec.pid ? Number(fields[spec.pid]) : 0;
11756
11937
  if (pid && !alive2(pid)) continue;
@@ -11823,7 +12004,7 @@ var init_nudge = __esm({
11823
12004
  };
11824
12005
  isFile = (path) => {
11825
12006
  try {
11826
- return statSync10(path).isFile();
12007
+ return statSync11(path).isFile();
11827
12008
  } catch {
11828
12009
  return false;
11829
12010
  }
@@ -11834,10 +12015,18 @@ var init_nudge = __esm({
11834
12015
  });
11835
12016
 
11836
12017
  // packages/daemon/src/release-guard.ts
11837
- import { join as join24 } from "node:path";
12018
+ function releaseMarker(record) {
12019
+ try {
12020
+ const files2 = artifactDirectory(record);
12021
+ const value = files2.readJson(MARKER, null);
12022
+ return value ? { files: files2, value } : null;
12023
+ } catch {
12024
+ return null;
12025
+ }
12026
+ }
11838
12027
  function writtenRelease(record) {
11839
- const marker = readJson(join24(record.root, ".artifact.json"), null);
11840
- const candidates = [record.typeRelease, typeof marker?.release === "string" ? marker.release : null].filter((v) => !!v && !!parseVersion(v));
12028
+ const release = releaseMarker(record)?.value.release;
12029
+ const candidates = [record.typeRelease, typeof release === "string" ? release : null].filter((v) => !!v && !!parseVersion(v));
11841
12030
  return candidates.sort((a, b) => compareVersions(b, a))[0] ?? null;
11842
12031
  }
11843
12032
  function isNewerRelease(written, installed) {
@@ -11858,17 +12047,17 @@ function readOnlyNote(record, written, installed) {
11858
12047
  return `Read-only here: ${record.type} ${written} wrote this artifact and this computer has ${installed}. Do not try to change it; tell the person to update Open Artifact (open-artifact runtime update).`;
11859
12048
  }
11860
12049
  function writeMarkerRelease(record, release) {
11861
- const file = join24(record.root, ".artifact.json");
11862
- const marker = readJson(file, null);
11863
- if (marker && marker.release !== release) writeJson(file, { ...marker, release });
12050
+ const marker = releaseMarker(record);
12051
+ if (marker && marker.value.release !== release) marker.files.writeJson(MARKER, { ...marker.value, release });
11864
12052
  }
11865
- var ReleaseGuard;
12053
+ var MARKER, ReleaseGuard;
11866
12054
  var init_release_guard = __esm({
11867
12055
  "packages/daemon/src/release-guard.ts"() {
11868
12056
  "use strict";
11869
12057
  init_src();
12058
+ init_workspace_files();
11870
12059
  init_src2();
11871
- init_paths();
12060
+ MARKER = ".artifact.json";
11872
12061
  ReleaseGuard = class {
11873
12062
  options;
11874
12063
  constructor(options) {
@@ -11915,7 +12104,7 @@ var init_release_guard = __esm({
11915
12104
  });
11916
12105
 
11917
12106
  // packages/daemon/src/artifact-import.ts
11918
- import { readFileSync as readFileSync16, rmSync as rmSync8, writeFileSync as writeFileSync7 } from "node:fs";
12107
+ import { readFileSync as readFileSync17, rmSync as rmSync8, writeFileSync as writeFileSync8 } from "node:fs";
11919
12108
  import { join as join25 } from "node:path";
11920
12109
  async function readArtifactArchive(bytes, source, o) {
11921
12110
  if (bytes.byteLength > ARTIFACT_IMPORT_LIMITS.zipBytes) throw new OpenArtifactError("too_large", `${source} is larger than ${ARTIFACT_IMPORT_LIMITS.zipBytes} bytes.`, { status: 413 });
@@ -11967,9 +12156,9 @@ async function unpackArtifactArchive(bytes, read, dest) {
11967
12156
  }
11968
12157
  try {
11969
12158
  const file = join25(unpacked.temp, ".artifact.json");
11970
- const { id: _id, ...rest } = JSON.parse(readFileSync16(file, "utf8"));
12159
+ const { id: _id, ...rest } = JSON.parse(readFileSync17(file, "utf8"));
11971
12160
  rmSync8(file, { force: true });
11972
- writeFileSync7(file, `${JSON.stringify({ ...rest, type: read.type.id }, null, 2)}
12161
+ writeFileSync8(file, `${JSON.stringify({ ...rest, type: read.type.id }, null, 2)}
11973
12162
  `, { flag: "wx" });
11974
12163
  await moveIntoPlace(unpacked.temp, dest);
11975
12164
  } catch (error) {
@@ -12066,9 +12255,9 @@ var init_remote_archive = __esm({
12066
12255
 
12067
12256
  // packages/daemon/src/tools.ts
12068
12257
  import { createHash as createHash8 } from "node:crypto";
12069
- import { existsSync as existsSync16, mkdirSync as mkdirSync7, readFileSync as readFileSync17, readdirSync as readdirSync13, rmSync as rmSync9, statSync as statSync11, writeFileSync as writeFileSync8 } from "node:fs";
12258
+ import { existsSync as existsSync16, mkdirSync as mkdirSync7, readFileSync as readFileSync18, readdirSync as readdirSync13, rmSync as rmSync9, statSync as statSync12, writeFileSync as writeFileSync9 } from "node:fs";
12070
12259
  import { homedir as homedir6 } from "node:os";
12071
- import { basename as basename5, dirname as dirname10, isAbsolute as isAbsolute5, join as join26, resolve as resolve15, sep as sep9 } from "node:path";
12260
+ import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute6, join as join26, resolve as resolve16, sep as sep10 } from "node:path";
12072
12261
  import { fileURLToPath as fileURLToPath4 } from "node:url";
12073
12262
  function offlineOf(link, record) {
12074
12263
  const note = link?.offlineNote(record);
@@ -12139,6 +12328,23 @@ function argsShape(schema) {
12139
12328
  return `, args: {${shown.join(", ")}${props.length > 8 ? ", ..." : ""}}`;
12140
12329
  }
12141
12330
  function localPathIn(value, at, root, depth = 0) {
12331
+ const home2 = homedir6();
12332
+ const under = (full, dir) => !!dir && (full === resolve16(dir) || full.startsWith(resolve16(dir) + sep10));
12333
+ return pathIn(value, at, (full) => under(full, home2) || under(full, root) || existsSync16(full), depth);
12334
+ }
12335
+ function pathOutside(value, at, workspace) {
12336
+ return pathIn(value, at, (full) => {
12337
+ const top = full.split(sep10).slice(0, 2).join(sep10) || sep10;
12338
+ if (!existsSync16(top)) return false;
12339
+ try {
12340
+ workspace.resolve(full);
12341
+ return false;
12342
+ } catch {
12343
+ return true;
12344
+ }
12345
+ });
12346
+ }
12347
+ function pathIn(value, at, counts, depth = 0) {
12142
12348
  if (typeof value === "string") {
12143
12349
  if (value.length > 4096) return null;
12144
12350
  let path = value;
@@ -12149,16 +12355,13 @@ function localPathIn(value, at, root, depth = 0) {
12149
12355
  return null;
12150
12356
  }
12151
12357
  }
12152
- if (!isAbsolute5(path) || resolve15(path) === resolve15("/")) return null;
12153
- const home2 = homedir6();
12154
- const full = resolve15(path);
12155
- const under = (dir) => !!dir && (full === resolve15(dir) || full.startsWith(resolve15(dir) + sep9));
12156
- return under(home2) || under(root) || existsSync16(full) ? { at, path: value } : null;
12358
+ if (!isAbsolute6(path) || resolve16(path) === resolve16("/")) return null;
12359
+ return counts(resolve16(path)) ? { at, path: value } : null;
12157
12360
  }
12158
12361
  if (depth >= 8 || !value || typeof value !== "object") return null;
12159
12362
  const entries = Array.isArray(value) ? value.slice(0, 1e3).map((item, i) => [String(i), item]) : Object.entries(value).slice(0, 1e3);
12160
12363
  for (const [key, item] of entries) {
12161
- const found2 = localPathIn(item, Array.isArray(value) ? `${at}[${key}]` : `${at}.${key}`, root, depth + 1);
12364
+ const found2 = pathIn(item, Array.isArray(value) ? `${at}[${key}]` : `${at}.${key}`, counts, depth + 1);
12162
12365
  if (found2) return found2;
12163
12366
  }
12164
12367
  return null;
@@ -12180,18 +12383,18 @@ function capabilitiesOf(value, type) {
12180
12383
  if (problem) throw new OpenArtifactError("invalid_argument", problem);
12181
12384
  return JSON.parse(JSON.stringify(value));
12182
12385
  }
12183
- function markerTypeUid(root) {
12386
+ function markerTypeUid(files2) {
12184
12387
  try {
12185
- const marker = JSON.parse(readFileSync17(join26(root, ".artifact.json"), "utf8"));
12388
+ const marker = JSON.parse(readFileSync18(files2.resolve(".artifact.json"), "utf8"));
12186
12389
  const typeUid = typeof marker.typeUid === "string" && marker.typeUid ? marker.typeUid : null;
12187
12390
  return { typeUid, typeSource: typeUid && typeof marker.typeSource === "string" ? marker.typeSource : null };
12188
12391
  } catch {
12189
12392
  return { typeUid: null, typeSource: null };
12190
12393
  }
12191
12394
  }
12192
- function markerCapabilities(root) {
12395
+ function markerCapabilities(files2) {
12193
12396
  try {
12194
- const value = JSON.parse(readFileSync17(join26(root, ".artifact.json"), "utf8")).capabilities;
12397
+ const value = JSON.parse(readFileSync18(files2.resolve(".artifact.json"), "utf8")).capabilities;
12195
12398
  return value !== void 0 && !capabilitiesProblem(value) && Object.keys(value).length ? value : void 0;
12196
12399
  } catch {
12197
12400
  return void 0;
@@ -12206,20 +12409,26 @@ function capabilityNotes(capabilities) {
12206
12409
  ...unknown.length ? [`${unknown.join(", ")}: no such capability here; use() gives the page null for ${unknown.length === 1 ? "it" : "them"}.`] : []
12207
12410
  ];
12208
12411
  }
12209
- function contentTitle(root, titleFrom) {
12412
+ function contentTitle(files2, titleFrom) {
12210
12413
  const parsed = titleFrom ? parseTitleFrom(titleFrom) : null;
12211
12414
  if (!parsed) return void 0;
12212
12415
  try {
12213
- return titleInFile(parsed.file, readFileSync17(join26(root, parsed.file), "utf8"), parsed.pointer)?.slice(0, 200);
12416
+ return titleInFile(parsed.file, readFileSync18(files2.resolve(parsed.file), "utf8"), parsed.pointer)?.slice(0, 200);
12214
12417
  } catch {
12215
12418
  return void 0;
12216
12419
  }
12217
12420
  }
12421
+ function inFolder(root, folder) {
12422
+ const full = resolve16(root);
12423
+ const top = resolve16(folder);
12424
+ return full === top || full.startsWith(top.endsWith(sep10) ? top : top + sep10);
12425
+ }
12218
12426
  var MAX_READ, MAX_READ_TOTAL, MAX_PATHS, MAX_LIST, MAX_LIST_HASH, LIST_LIMIT, LIST_MAX2, MAX_WAIT_MS, DATA_PAGE, DATA_PAGE_MAX, REPLY_MAX_BYTES, RELATED_MAX, READ_ACTIONS, TYPE_TEXT_NOTE, NO_TYPE_FITS, SHOW_IT, AFTER_CREATE_CHECK, AFTER_CREATE, AFTER_CREATE_EARLY_CHECK, AFTER_CREATE_EARLY, AFTER_CREATE_OPENING_CHECK, AFTER_CREATE_OPENING, AFTER_CREATE_OPEN_CHECK, OPEN_NOT_AVAILABLE, OPEN_YOURSELF, OPEN_EARLY_YOURSELF, AFTER_CREATE_OPEN, changedNote, MAY_WORDS, MAY_FIX, EXISTING_MAX, STOP_WORDS, OTHER_INTENT, CJK, words, sha2563, DATA_NO_SHA_NOTE, DATA_QUERY_IGNORED_NOTE, DATA_WRITE_KEYS, NOT_SENT_NOTE, DUPLICATE_FIX, REPLY_TOO_LONG_FIX, cleanPath, now, Tools;
12219
12427
  var init_tools2 = __esm({
12220
12428
  "packages/daemon/src/tools.ts"() {
12221
12429
  "use strict";
12222
12430
  init_src();
12431
+ init_workspace_files();
12223
12432
  init_harness_profiles();
12224
12433
  init_harness_skill();
12225
12434
  init_paths();
@@ -12368,7 +12577,7 @@ var init_tools2 = __esm({
12368
12577
  case "publish":
12369
12578
  if (args.url) {
12370
12579
  this.allow(caller2, "modify", "Artifact publish with url");
12371
- return this.write(args);
12580
+ return this.write(args, caller2);
12372
12581
  }
12373
12582
  this.allow(caller2, "create", "Artifact publish with type_url");
12374
12583
  return this.create(args, caller2);
@@ -12551,17 +12760,17 @@ ${rules}` };
12551
12760
  const wanted = significant(text3);
12552
12761
  if (!wanted.size) return [];
12553
12762
  const me = sessionKeyOf(caller2);
12554
- const workspace = caller2.workspace ? resolve15(caller2.workspace) + sep9 : null;
12763
+ const workspace = caller2.workspace ? resolve16(caller2.workspace) : null;
12555
12764
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
12556
- 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) }));
12765
+ return this.o.store.list().filter((a) => a.type === type.id && this.reachable(a, workspace) && (mine(a) || reuse === "workspace" && !!workspace && inFolder(a.root, 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) }));
12557
12766
  }
12558
12767
  /** The caller's artifacts (theirs, or under their workspace) of the types `type` builds on (`openArtifact.uses`), newest first. */
12559
12768
  relatedTo(type, caller2) {
12560
12769
  if (!type.uses.length) return [];
12561
12770
  const me = sessionKeyOf(caller2);
12562
- const workspace = caller2.workspace ? resolve15(caller2.workspace) + sep9 : null;
12771
+ const workspace = caller2.workspace ? resolve16(caller2.workspace) : null;
12563
12772
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
12564
- 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 }));
12773
+ return this.o.store.list().filter((a) => type.uses.includes(a.type) && this.reachable(a, workspace) && (mine(a) || !!workspace && inFolder(a.root, 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 }));
12565
12774
  }
12566
12775
  list(args, caller2) {
12567
12776
  const scope = args.scope ?? "mine";
@@ -12576,10 +12785,10 @@ ${rules}` };
12576
12785
  const offset = args.cursor === void 0 || args.cursor === "" ? 0 : Number(args.cursor);
12577
12786
  if (!Number.isInteger(offset) || offset < 0) throw new OpenArtifactError("invalid_argument", "cursor: the next_cursor of the previous page.");
12578
12787
  const me = sessionKeyOf(caller2);
12579
- const workspace = caller2.workspace ? resolve15(caller2.workspace) + sep9 : null;
12788
+ const workspace = caller2.workspace ? resolve16(caller2.workspace) : null;
12580
12789
  const mine = (a) => !!a.owner && sessionKeyOf(a.owner) === me;
12581
12790
  const changed = (a) => !!a.lastUserEditAt && (!a.agentSeenAt || a.lastUserEditAt > a.agentSeenAt);
12582
- 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)));
12791
+ const shown = this.o.store.list().filter((a) => this.reachable(a, workspace) && (scope === "all" || mine(a) || !!workspace && inFolder(a.root, workspace))).filter((a) => (!typeId || a.type === typeId) && (!query || a.title.toLowerCase().includes(query)));
12583
12792
  const page = shown.slice(offset, offset + limit);
12584
12793
  const anyChanged = page.some(changed);
12585
12794
  return {
@@ -12607,12 +12816,17 @@ ${rules}` };
12607
12816
  * A caller with no known workspace gets the home folder, never the daemon's own folder (which may be a plugin's).
12608
12817
  */
12609
12818
  resolveFolder(folder, caller2, title) {
12610
- const base = caller2.workspace ? resolve15(caller2.workspace) : homedir6();
12611
- if (folder) return resolve15(base, folder);
12612
- const dir = join26(base, this.o.settings().artifactsDir || "artifacts");
12819
+ if (this.o.workspaceFoldersOnly && !caller2.workspace) {
12820
+ throw new OpenArtifactError("not_granted", "A local workspace is required to create or adopt a work.");
12821
+ }
12822
+ const base = caller2.workspace ? resolve16(caller2.workspace) : homedir6();
12823
+ const directory = this.o.workspaceFoldersOnly ? new WorkspaceDirectory(base) : null;
12824
+ const folderPath = (candidate) => directory?.resolve(candidate) ?? candidate;
12825
+ if (folder) return folderPath(resolve16(base, folder));
12826
+ const dir = folderPath(join26(base, this.o.settings().artifactsDir || "artifacts"));
12613
12827
  const slug = slugify(title);
12614
- let root = join26(dir, slug);
12615
- for (let i = 2; existsSync16(root) && readdirSync13(root).length; i++) root = join26(dir, `${slug}-${i}`);
12828
+ let root = folderPath(join26(dir, slug));
12829
+ for (let i = 2; existsSync16(root) && readdirSync13(root).length; i++) root = folderPath(join26(dir, `${slug}-${i}`));
12616
12830
  return root;
12617
12831
  }
12618
12832
  /** The type's actions, or `null` when they are not known; never fails. */
@@ -12693,7 +12907,19 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12693
12907
  if (known) throw new OpenArtifactError("conflict", `${root} is already the artifact ${artifactUrl(known.id)}.`, { fix: "Use that url, or give another folder." });
12694
12908
  }
12695
12909
  const owner = caller2.session || caller2.workspace ? caller2 : null;
12696
- const record = this.o.store.create({ root, type: typeId, typeSource: type.scope, typeRelease: type.version, typeUid: type.uid, typeFrom: markerSourceOf(type), owner, title, capabilities });
12910
+ const workspace = this.workspaceDirectory(caller2);
12911
+ const record = this.o.store.create({
12912
+ root,
12913
+ type: typeId,
12914
+ typeSource: type.scope,
12915
+ typeRelease: type.version,
12916
+ typeUid: type.uid,
12917
+ typeFrom: markerSourceOf(type),
12918
+ owner,
12919
+ title,
12920
+ capabilities,
12921
+ ...workspace ? { workspaceDirectory: workspace.identity } : {}
12922
+ });
12697
12923
  this.o.log(`created ${record.id} (${typeId}) at ${root} for ${sessionKeyOf(caller2) ?? "nobody"}`);
12698
12924
  const auto = this.o.link?.created?.(record) === true;
12699
12925
  const actions = await this.knownActions(type, false);
@@ -12726,13 +12952,34 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12726
12952
  /** A file's sha256, `null` when there is none. */
12727
12953
  hashOf(file) {
12728
12954
  try {
12729
- return statSync11(file).isFile() ? sha2563(readFileSync17(file)) : null;
12955
+ return statSync12(file).isFile() ? sha2563(readFileSync18(file)) : null;
12730
12956
  } catch {
12731
12957
  return null;
12732
12958
  }
12733
12959
  }
12734
- async write(args) {
12960
+ /**
12961
+ * Whether a listing may show an artifact to a caller in `workspace`: always, except in a workspace-confined daemon,
12962
+ * where only the artifacts whose folders are in that workspace are shown (`scope: "all"` included), so a sandboxed
12963
+ * agent never learns the paths of folders it cannot reach.
12964
+ */
12965
+ reachable(record, workspace) {
12966
+ return !this.o.workspaceFoldersOnly || !!workspace && inFolder(record.root, workspace);
12967
+ }
12968
+ /** In a workspace-confined daemon, the caller's workspace: every folder it makes, adopts or touches stays in it. */
12969
+ workspaceDirectory(caller2) {
12970
+ if (!this.o.workspaceFoldersOnly) return null;
12971
+ if (!caller2.workspace) throw new OpenArtifactError("not_granted", "A local workspace is required to access an artifact.");
12972
+ return new WorkspaceDirectory(caller2.workspace);
12973
+ }
12974
+ /** In a workspace-confined daemon, the artifact's real folder, checked to be in the caller's workspace. */
12975
+ artifactFiles(record, caller2) {
12976
+ const workspace = this.workspaceDirectory(caller2);
12977
+ if (!workspace) return null;
12978
+ return new WorkspaceDirectory(workspace.resolve(this.o.store.authorizedRoot(record)));
12979
+ }
12980
+ async write(args, caller2) {
12735
12981
  let record = this.o.store.require(args.url);
12982
+ const directory = this.artifactFiles(record, caller2);
12736
12983
  const type = this.o.types?.get(record.type, record.owner?.workspace ?? void 0) ?? null;
12737
12984
  const capabilities = args.capabilities === void 0 ? void 0 : capabilitiesOf(args.capabilities, type);
12738
12985
  const given = args.files === void 0 && capabilities !== void 0 ? {} : args.files;
@@ -12743,7 +12990,8 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12743
12990
  const plan = entries.map(([rel, value]) => {
12744
12991
  const clean = cleanPath(rel);
12745
12992
  if (/(^|\/)(\.artifact[^/]*|\.sharing\.json|_blobs)(\/|$)/.test(clean)) throw new OpenArtifactError("bad_path", `${rel} is the artifact's own bookkeeping.`);
12746
- const file = inside(record.root, clean);
12993
+ const requested = inside(record.root, clean);
12994
+ const file = directory?.resolve(requested, value !== null) ?? requested;
12747
12995
  if (value === null) return { clean, file, bytes: null };
12748
12996
  const content = typeof value === "string" ? value : value?.content;
12749
12997
  if (typeof content !== "string") throw new OpenArtifactError("invalid_argument", `${rel}: give text, or {content, encoding: "base64"}.`);
@@ -12761,7 +13009,8 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12761
13009
  throw new OpenArtifactError("invalid_argument", `if_match ${rel}: the sha256 read returned, null (the file must not exist) or "*".`);
12762
13010
  }
12763
13011
  const clean = cleanPath(rel);
12764
- const current = this.hashOf(inside(record.root, clean));
13012
+ const requested = inside(record.root, clean);
13013
+ const current = this.hashOf(directory?.resolve(requested) ?? requested);
12765
13014
  if (expected === null ? current !== null : current !== expected.toLowerCase()) conflicts.push(clean);
12766
13015
  }
12767
13016
  if (conflicts.length) {
@@ -12771,8 +13020,9 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12771
13020
  message: `${conflicts.length === 1 ? "A file" : `${conflicts.length} files`} changed since you read ${conflicts.length === 1 ? "it" : "them"}: nothing was written.`,
12772
13021
  fix: "Merge your change into the current version in current, then write again with its sha256 as if_match."
12773
13022
  },
13023
+ executionStatus: "not_executed",
12774
13024
  url: artifactUrl(record.id),
12775
- current: Object.fromEntries(conflicts.map((path) => [path, this.fileState(record, path)]))
13025
+ current: Object.fromEntries(conflicts.map((path) => [path, this.fileState(record, path, directory)]))
12776
13026
  };
12777
13027
  }
12778
13028
  }
@@ -12783,13 +13033,13 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12783
13033
  written.push({ path: clean, deleted: true });
12784
13034
  continue;
12785
13035
  }
12786
- mkdirSync7(dirname10(file), { recursive: true });
12787
- writeFileSync8(file, bytes);
13036
+ mkdirSync7(dirname11(file), { recursive: true });
13037
+ writeFileSync9(file, bytes);
12788
13038
  written.push({ path: clean, bytes: bytes.length, sha256: sha2563(bytes) });
12789
13039
  }
12790
13040
  if (capabilities !== void 0) record = this.o.store.setCapabilities(record.id, Object.keys(capabilities).length ? capabilities : null);
12791
13041
  const changed = changedFiles(record);
12792
- const titled = type?.titleFrom && isPageType(type) && plan.some(({ clean }) => clean === parseTitleFrom(type.titleFrom)?.file) ? contentTitle(record.root, type.titleFrom) : void 0;
13042
+ const titled = type?.titleFrom && isPageType(type) && plan.some(({ clean }) => clean === parseTitleFrom(type.titleFrom)?.file) ? contentTitle(directory ?? new WorkspaceDirectory(record.root), type.titleFrom) : void 0;
12793
13043
  this.o.store.update(record.id, { agentSeenAt: now(), ...titled && titled !== record.title ? { title: titled } : {} });
12794
13044
  if (record.remote || record.autoPublish === "pending") this.o.link?.wrote(record);
12795
13045
  const offline = this.o.link?.offlineNote(record) ?? null;
@@ -12817,20 +13067,20 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12817
13067
  }
12818
13068
  }
12819
13069
  /** What a file holds now, for a conflict: its sha256 and, for text, its content. */
12820
- fileState(record, path) {
13070
+ fileState(record, path, directory) {
12821
13071
  try {
12822
- return this.readOne(record, path, MAX_READ);
13072
+ return this.readOne(record, path, MAX_READ, directory);
12823
13073
  } catch {
12824
13074
  return { sha256: null, note: "It does not exist." };
12825
13075
  }
12826
13076
  }
12827
- listFiles(root, hashes = false) {
13077
+ listFiles(root, hashes = false, directory = null) {
12828
13078
  const out2 = [];
12829
13079
  const walk = (dir, rel) => {
12830
13080
  if (out2.length >= MAX_LIST) return;
12831
13081
  let entries;
12832
13082
  try {
12833
- entries = readdirSync13(dir, { withFileTypes: true });
13083
+ entries = readdirSync13(directory?.resolve(dir) ?? dir, { withFileTypes: true });
12834
13084
  } catch {
12835
13085
  return;
12836
13086
  }
@@ -12840,9 +13090,10 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12840
13090
  if (e.isDirectory()) walk(join26(dir, e.name), r);
12841
13091
  else if (out2.length < MAX_LIST) {
12842
13092
  try {
12843
- const file = join26(dir, e.name);
12844
- const bytes = statSync11(file).size;
12845
- out2.push({ path: r, bytes, ...hashes && bytes <= MAX_LIST_HASH ? { sha256: sha2563(readFileSync17(file)) } : {} });
13093
+ const requested = join26(dir, e.name);
13094
+ const file = directory?.resolve(requested) ?? requested;
13095
+ const bytes = statSync12(file).size;
13096
+ out2.push({ path: r, bytes, ...hashes && bytes <= MAX_LIST_HASH ? { sha256: sha2563(readFileSync18(file)) } : {} });
12846
13097
  } catch {
12847
13098
  }
12848
13099
  }
@@ -12852,12 +13103,13 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12852
13103
  return out2;
12853
13104
  }
12854
13105
  /** One file (its content and sha256) or folder (its listing) under the root; text is cut at `budget` characters. */
12855
- readOne(record, path, budget) {
12856
- const file = inside(record.root, path);
13106
+ readOne(record, path, budget, directory) {
13107
+ const requested = inside(record.root, path);
13108
+ const file = directory?.resolve(requested) ?? requested;
12857
13109
  if (!existsSync16(file)) throw new OpenArtifactError("not_found", `No file ${path} in ${record.root}.`);
12858
- const stat2 = statSync11(file);
12859
- if (stat2.isDirectory()) return { path, files: this.listFiles(file, true) };
12860
- const buffer = readFileSync17(file);
13110
+ const stat2 = statSync12(file);
13111
+ if (stat2.isDirectory()) return { path, files: this.listFiles(file, true, directory) };
13112
+ const buffer = readFileSync18(file);
12861
13113
  const hash = sha2563(buffer);
12862
13114
  if (buffer.subarray(0, 8e3).includes(0)) return { path, bytes: stat2.size, sha256: hash, binary: true, note: "A binary file: read it from disk if you need it." };
12863
13115
  if (budget <= 0) return { path, bytes: stat2.size, sha256: hash, note: "Not read: this result is full. Read it on its own." };
@@ -12877,6 +13129,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12877
13129
  throw new OpenArtifactError("invalid_argument", "read needs url (an artifact) or type_url (a type).");
12878
13130
  }
12879
13131
  const record = this.o.store.require(args.url);
13132
+ const directory = this.artifactFiles(record, caller2);
12880
13133
  const changed = changedFiles(record);
12881
13134
  this.o.store.update(record.id, { agentSeenAt: now(), updatedAt: record.updatedAt });
12882
13135
  const seen = changed.length ? { changed_files: changed, notes: [changedNote(changed.length)] } : {};
@@ -12888,7 +13141,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12888
13141
  let budget = MAX_READ_TOTAL;
12889
13142
  const files2 = args.paths.map((path) => {
12890
13143
  try {
12891
- const one = this.readOne(record, path, budget);
13144
+ const one = this.readOne(record, path, budget, directory);
12892
13145
  if (typeof one.content === "string") budget -= one.content.length;
12893
13146
  return one;
12894
13147
  } catch (error) {
@@ -12897,8 +13150,8 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12897
13150
  });
12898
13151
  return { url: artifactUrl(record.id), files: files2, ...seen, ...this.pageContentFields(record) };
12899
13152
  }
12900
- if (args.path) return { ...this.readOne(record, args.path, MAX_READ), ...seen, ...this.pageContentFields(record) };
12901
- const { owner, userEdits: _edits, remote: remote2, ...shown } = record;
13153
+ if (args.path) return { ...this.readOne(record, args.path, MAX_READ, directory), ...seen, ...this.pageContentFields(record) };
13154
+ const { owner, userEdits: _edits, remote: remote2, workspaceDirectory: _workspace, ...shown } = record;
12902
13155
  const type = this.o.types.get(record.type, owner?.workspace ?? void 0);
12903
13156
  const actions = type ? await this.knownActions(type, false) : null;
12904
13157
  return {
@@ -12912,7 +13165,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
12912
13165
  // notice: the type's, then the page content's, in the one field).
12913
13166
  ...type ? { type_title: type.title, ...typeLocationFields(type), ...this.sourceFields(type) } : {},
12914
13167
  ...type && !type.trusted ? { third_party_notice: `${restrictedTypeNotice(type)} ${PAGE_CONTENT_NOTICE}` } : {},
12915
- files: this.listFiles(record.root, true),
13168
+ files: this.listFiles(record.root, true, directory),
12916
13169
  ...actions ? { actions } : {},
12917
13170
  ...seen
12918
13171
  };
@@ -13035,6 +13288,15 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13035
13288
  );
13036
13289
  }
13037
13290
  }
13291
+ const confined = caller2 ? this.workspaceDirectory(caller2) : null;
13292
+ if (confined) {
13293
+ const outside = pathOutside(args, "args", confined);
13294
+ if (outside) {
13295
+ throw new OpenArtifactError("not_granted", `${name} cannot take ${outside.at} (${outside.path}): it is outside this session's workspace.`, {
13296
+ fix: "Use a file inside the workspace, or pass the content itself in the arguments."
13297
+ });
13298
+ }
13299
+ }
13038
13300
  const fresh = !forward && this.o.link?.renders(record, type, name) ? await this.o.link.freshen(record, type) : null;
13039
13301
  const behind = fresh?.note ?? null;
13040
13302
  if (fresh?.reload && this.o.reopenPage) await this.o.reopenPage(record);
@@ -13058,6 +13320,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13058
13320
  try {
13059
13321
  const out2 = forward ? await this.o.link.call(record, name, args, effect) : await this.o.typeAction(type, record, name, args);
13060
13322
  const result = out2 && typeof out2 === "object" && !Array.isArray(out2) ? out2 : { result: out2 };
13323
+ if (result.error && result.executionStatus === "not_executed") delete result.executionStatus;
13061
13324
  if (behind) result.notes = [...Array.isArray(result.notes) ? result.notes : [], behind];
13062
13325
  if (own && caller2 && typeof result.task === "string" && result.pending === true) {
13063
13326
  this.o.taskStarted?.({ record, type, task: result.task, action: name, effect, caller: caller2 });
@@ -13065,6 +13328,10 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13065
13328
  if (own && caller2 && effect === "write") this.o.ownership?.wrote(record.id, caller2);
13066
13329
  return result;
13067
13330
  } catch (error) {
13331
+ if (name === "open-artifact.db.write" && !forward && !location.remote && error instanceof OpenArtifactError && error.status === 409 && error.code === "conflict" && error.current !== void 0) {
13332
+ const { current, ...body } = errorBody(error);
13333
+ return { error: body, current, executionStatus: "not_executed" };
13334
+ }
13068
13335
  if (error?.code === "unknown_action") {
13069
13336
  if (missing) throw missing;
13070
13337
  if (own && !error.fix) throw unknown(actions);
@@ -13086,10 +13353,16 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13086
13353
  async adopt(args, caller2) {
13087
13354
  if (args.url) {
13088
13355
  const record2 = this.o.store.require(args.url);
13356
+ const workspace2 = this.workspaceDirectory(caller2);
13357
+ if (workspace2) workspace2.resolve(record2.workspaceDirectory ? this.o.store.authorizedRoot(record2) : record2.root);
13089
13358
  const owner = record2.owner ? sessionKeyOf(record2.owner) : null;
13090
13359
  if (owner && owner !== sessionKeyOf(caller2)) this.allow(caller2, "remove", "Artifact adopt of another session's artifact");
13091
13360
  else this.allow(caller2, "modify", "Artifact adopt");
13092
- const next = this.o.store.update(record2.id, { owner: caller2, agentSeenAt: now() });
13361
+ const next = this.o.store.update(record2.id, {
13362
+ owner: caller2,
13363
+ agentSeenAt: now(),
13364
+ ...workspace2 && !record2.workspaceDirectory ? { workspaceDirectory: workspace2.identity } : {}
13365
+ });
13093
13366
  this.o.handOff?.(next.id, caller2, "adopt");
13094
13367
  const type2 = this.o.types.get(next.type, caller2.workspace ?? void 0);
13095
13368
  const actions2 = type2 ? await this.knownActions(type2, false) : null;
@@ -13108,19 +13381,28 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13108
13381
  const known = this.o.store.byRoot(root);
13109
13382
  if (known) return this.adopt({ url: artifactUrl(known.id) }, caller2);
13110
13383
  this.allow(caller2, "create", "Artifact adopt of a folder");
13384
+ const workspace = this.workspaceDirectory(caller2);
13385
+ const files2 = new WorkspaceDirectory(workspace?.resolve(root) ?? root);
13111
13386
  let typeId = typeIdOf(args.type_url);
13112
13387
  if (!typeId) {
13113
- try {
13114
- typeId = JSON.parse(readFileSync17(join26(root, ".artifact.json"), "utf8")).type ?? null;
13115
- } catch {
13116
- typeId = this.o.types.list(caller2.workspace).find((t) => t.detect.some((rel) => existsSync16(join26(root, rel))))?.id ?? null;
13388
+ const marker = files2.readJson(".artifact.json", null);
13389
+ if (marker === null) {
13390
+ typeId = this.o.types.list(caller2.workspace).find((t) => t.detect.some((rel) => {
13391
+ try {
13392
+ return existsSync16(files2.resolve(rel));
13393
+ } catch {
13394
+ return false;
13395
+ }
13396
+ }))?.id ?? null;
13397
+ } else if (typeof marker.type === "string") {
13398
+ typeId = marker.type;
13117
13399
  }
13118
13400
  }
13119
13401
  if (!typeId) throw new OpenArtifactError("invalid_argument", `Which type is ${root}? Give type_url.`);
13120
13402
  const type = this.o.types.get(typeId, caller2.workspace);
13121
- const title = args.title || contentTitle(root, type?.titleFrom ?? null) || basename5(root);
13122
- const capabilities = isPageType(type) ? markerCapabilities(root) : void 0;
13123
- const marked = markerTypeUid(root);
13403
+ const title = args.title || contentTitle(files2, type?.titleFrom ?? null) || basename6(root);
13404
+ const capabilities = isPageType(type) ? markerCapabilities(files2) : void 0;
13405
+ const marked = markerTypeUid(files2);
13124
13406
  const record = this.o.store.create({
13125
13407
  root,
13126
13408
  type: typeId,
@@ -13130,7 +13412,8 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13130
13412
  typeFrom: marked.typeSource,
13131
13413
  owner: caller2,
13132
13414
  title,
13133
- capabilities
13415
+ capabilities,
13416
+ ...workspace ? { workspaceDirectory: workspace.identity } : {}
13134
13417
  });
13135
13418
  const auto = this.o.link?.created?.(record) === true;
13136
13419
  const actions = type ? await this.knownActions(type, false) : null;
@@ -13148,13 +13431,13 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13148
13431
  const record = this.o.store.require(args.url);
13149
13432
  if (actionKindOf("ArtifactData", typeof args.action === "string" ? args.action : void 0) !== "read") this.allow(caller2, "modify", `ArtifactData ${String(args.action)}`);
13150
13433
  const noStore = new OpenArtifactError("unsupported", `${record.type} keeps no document store: write its files with Artifact publish.`);
13151
- const db = (name, a) => this.action(record, name, a, noStore);
13434
+ const db = (name, a) => this.action(record, name, a, noStore, caller2);
13152
13435
  const docPath = args.path ?? (args.collection && args.doc_id ? `${args.collection}/${args.doc_id}` : args.collection);
13153
- const base = caller2.workspace ? resolve15(caller2.workspace) : record.root;
13436
+ const base = caller2.workspace ? resolve16(caller2.workspace) : record.root;
13154
13437
  const writeOf = (w) => {
13155
13438
  const out2 = {};
13156
13439
  for (const key of DATA_WRITE_KEYS) if (w[key] !== void 0) out2[key] = w[key];
13157
- if (typeof out2.file_path === "string" && out2.file_path) out2.file_path = resolve15(base, out2.file_path);
13440
+ if (typeof out2.file_path === "string" && out2.file_path) out2.file_path = resolve16(base, out2.file_path);
13158
13441
  return out2;
13159
13442
  };
13160
13443
  const write = async (writes) => {
@@ -13183,7 +13466,7 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13183
13466
  if (args.action === "query" && docs && out2.query !== true) notes.push(DATA_QUERY_IGNORED_NOTE);
13184
13467
  if (docs && docs.some((d) => typeof d.sha256 !== "string") || out2.exists === true && typeof out2.sha256 !== "string") notes.push(DATA_NO_SHA_NOTE);
13185
13468
  const result = { url: artifactUrl(record.id), ...out2, ...notes.length ? { notes } : {}, ...this.pageContentFields(record) };
13186
- return args.out_file ? this.dataToFile(record, result, args.out_file, base) : result;
13469
+ return args.out_file ? this.dataToFile(record, result, args.out_file, base, this.workspaceDirectory(caller2)) : result;
13187
13470
  }
13188
13471
  case "set":
13189
13472
  case "update":
@@ -13201,14 +13484,14 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13201
13484
  }
13202
13485
  }
13203
13486
  /** A read's result written to a JSON file: the agent reads it from disk instead of its context. */
13204
- dataToFile(record, result, outFile, base) {
13205
- const file = resolve15(base, outFile);
13206
- if (file === record.root || file.startsWith(record.root + sep9)) throw new OpenArtifactError("bad_path", "out_file goes outside the artifact folder: a file there would become part of the artifact.");
13207
- mkdirSync7(dirname10(file), { recursive: true });
13487
+ dataToFile(record, result, outFile, base, workspace) {
13488
+ const file = workspace ? workspace.resolve(resolve16(base, outFile)) : resolve16(base, outFile);
13489
+ if (file === record.root || file.startsWith(record.root + sep10)) throw new OpenArtifactError("bad_path", "out_file goes outside the artifact folder: a file there would become part of the artifact.");
13490
+ mkdirSync7(dirname11(file), { recursive: true });
13208
13491
  const { notes, url: _url, third_party_notice: notice, ...data } = result;
13209
13492
  const text3 = `${JSON.stringify(data, null, 2)}
13210
13493
  `;
13211
- writeFileSync8(file, text3);
13494
+ writeFileSync9(file, text3);
13212
13495
  const count = Array.isArray(data.docs) ? data.docs.length : Array.isArray(data.documents) ? data.documents.length : data.exists === true ? 1 : 0;
13213
13496
  return {
13214
13497
  url: artifactUrl(record.id),
@@ -13290,8 +13573,8 @@ ${body ?? `(The type ${type.id} has no SKILL.md: ${type.description})`}`;
13290
13573
  const touched = /* @__PURE__ */ new Set();
13291
13574
  const records = this.o.store.list();
13292
13575
  for (const p of paths) {
13293
- const abs = resolve15(caller2.workspace ?? "/", p);
13294
- const record = records.find((a) => abs === a.root || abs.startsWith(a.root + sep9));
13576
+ const abs = resolve16(caller2.workspace ?? "/", p);
13577
+ const record = records.find((a) => abs === a.root || abs.startsWith(a.root + sep10));
13295
13578
  if (record && !touched.has(record.id)) {
13296
13579
  touched.add(record.id);
13297
13580
  this.o.store.update(record.id, { agentSeenAt: now() });
@@ -13467,17 +13750,17 @@ __export(daemon_exports, {
13467
13750
  startDaemon: () => startDaemon,
13468
13751
  takeOverPrompt: () => takeOverPrompt
13469
13752
  });
13470
- import { randomBytes as randomBytes9 } from "node:crypto";
13753
+ import { randomBytes as randomBytes10 } from "node:crypto";
13471
13754
  import { EventEmitter as EventEmitter5 } from "node:events";
13472
- import { appendFileSync as appendFileSync3, cpSync as cpSync3, createReadStream, existsSync as existsSync17, openSync as openSync4, readFileSync as readFileSync18, readdirSync as readdirSync14, rmSync as rmSync10, statSync as statSync12, watch as watch3, writeFileSync as writeFileSync9, writeSync, closeSync as closeSync4 } from "node:fs";
13755
+ import { appendFileSync as appendFileSync3, cpSync as cpSync3, createReadStream, existsSync as existsSync17, mkdirSync as mkdirSync8, openSync as openSync4, readFileSync as readFileSync19, readdirSync as readdirSync14, rmSync as rmSync10, statSync as statSync13, watch as watch3, writeFileSync as writeFileSync10, writeSync, closeSync as closeSync4 } from "node:fs";
13473
13756
  import { createServer as createServer2 } from "node:http";
13474
13757
  import { userInfo } from "node:os";
13475
- import { basename as basename6, dirname as dirname11, extname as extname4, isAbsolute as isAbsolute6, join as join27, resolve as resolve16, sep as sep10 } from "node:path";
13758
+ import { basename as basename7, dirname as dirname12, extname as extname4, isAbsolute as isAbsolute7, join as join27, resolve as resolve17, sep as sep11 } from "node:path";
13476
13759
  import { Readable } from "node:stream";
13477
13760
  import { fileURLToPath as fileURLToPath5 } from "node:url";
13478
13761
  function defaultUiDir(name) {
13479
13762
  const fromEnv = name === "shell" ? process.env.OPEN_ARTIFACT_SHELL_DIR : process.env.OPEN_ARTIFACT_HOME_DIR;
13480
- return fromEnv ? resolve16(fromEnv) : resolve16(here, "..", "..", "..", "dist", "daemon", name);
13763
+ return fromEnv ? resolve17(fromEnv) : resolve17(here, "..", "..", "..", "dist", "daemon", name);
13481
13764
  }
13482
13765
  function isContentPath(rel) {
13483
13766
  const parts = rel.split("/");
@@ -13542,9 +13825,6 @@ async function readJsonBody(req) {
13542
13825
  throw new OpenArtifactError("invalid_argument", "The body is not JSON.");
13543
13826
  }
13544
13827
  }
13545
- function sharedOnLan(root) {
13546
- return readJson(join27(root, ".sharing.json"), null)?.lan === true;
13547
- }
13548
13828
  function safeUserName() {
13549
13829
  try {
13550
13830
  return userInfo().username || "You";
@@ -13605,6 +13885,7 @@ var DATA_REFRESH_MS, here, VERSION3, BOOT_PLACEHOLDER, UI_PATHS, PAGE_IDLE_MS, T
13605
13885
  var init_daemon2 = __esm({
13606
13886
  "packages/daemon/src/daemon.ts"() {
13607
13887
  "use strict";
13888
+ init_workspace_files();
13608
13889
  init_src();
13609
13890
  init_zip();
13610
13891
  init_data_refresh();
@@ -13635,7 +13916,7 @@ var init_daemon2 = __esm({
13635
13916
  init_ws();
13636
13917
  init_package();
13637
13918
  DATA_REFRESH_MS = 15 * 6e4;
13638
- here = dirname11(fileURLToPath5(import.meta.url));
13919
+ here = dirname12(fileURLToPath5(import.meta.url));
13639
13920
  VERSION3 = package_default.version ?? "0.0.0";
13640
13921
  BOOT_PLACEHOLDER = "/*__OPEN_ARTIFACT_BOOT__*/null";
13641
13922
  UI_PATHS = { shell: "/_open-artifact/shell/", home: "/_open-artifact/home/" };
@@ -13740,7 +14021,7 @@ var init_daemon2 = __esm({
13740
14021
  /** The listening port, once started. */
13741
14022
  port = 0;
13742
14023
  /** Bearer token of the Library and Harness APIs and MCP. */
13743
- token = randomBytes9(24).toString("base64url");
14024
+ token = randomBytes10(24).toString("base64url");
13744
14025
  settings;
13745
14026
  /** Install-time cloud presets (environment, `preset.json`), read once at construction. */
13746
14027
  preset;
@@ -13796,12 +14077,12 @@ var init_daemon2 = __esm({
13796
14077
  this.wantPort = options.port ?? this.settings.serverPort;
13797
14078
  this.idleMs = options.idleMs ?? Number(process.env.OPEN_ARTIFACT_IDLE_MS ?? 30 * 6e4);
13798
14079
  this.quiet = options.quiet ?? false;
13799
- this.shellDir = resolve16(options.shellDir ?? defaultUiDir("shell"));
13800
- this.homeDir = resolve16(options.homeDir ?? defaultUiDir("home"));
14080
+ this.shellDir = resolve17(options.shellDir ?? defaultUiDir("shell"));
14081
+ this.homeDir = resolve17(options.homeDir ?? defaultUiDir("home"));
13801
14082
  this.logFile = files.daemonLog();
13802
14083
  const log = (line) => this.log(line);
13803
14084
  this.types = new TypeRegistry(() => this.settings, options.builtinTypesDir !== void 0 ? { builtinDir: options.builtinTypesDir } : {});
13804
- this.store = new ArtifactStore();
14085
+ this.store = new ArtifactStore(options.workspaceFoldersOnly === true);
13805
14086
  this.inbox = new Inbox();
13806
14087
  this.wake = new WakeRouter({
13807
14088
  store: this.store,
@@ -13847,7 +14128,7 @@ var init_daemon2 = __esm({
13847
14128
  run: async (record, args) => {
13848
14129
  const type = this.typeOf(record);
13849
14130
  if (!type) throw new OpenArtifactError("not_found", `The type ${record.type} is not installed.`);
13850
- return this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}${encodeURIComponent(DATA_REFRESH_ACTION)}`, { id: record.id, root: record.root, args }, void 0, DATA_REFRESH_MS);
14131
+ return this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}${encodeURIComponent(DATA_REFRESH_ACTION)}`, { id: record.id, root: this.store.authorizedRoot(record), args }, void 0, DATA_REFRESH_MS);
13851
14132
  },
13852
14133
  sync: (id) => this.link.syncNow(id),
13853
14134
  owner: (record) => this.link.ownerName(record),
@@ -13859,11 +14140,12 @@ var init_daemon2 = __esm({
13859
14140
  inbox: this.inbox,
13860
14141
  harnesses: () => this.harnesses,
13861
14142
  settings: () => this.settings,
14143
+ workspaceFoldersOnly: options.workspaceFoldersOnly === true,
13862
14144
  viewUrl: (id) => this.viewUrl(id),
13863
14145
  openPage: (record) => this.openPage(record),
13864
14146
  reopenPage: (record) => this.reopenPage(record),
13865
14147
  reach: (type) => this.servers.reach(type),
13866
- typeAction: (type, record, name, args) => this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}${encodeURIComponent(name)}`, { id: record.id, root: record.root, args }, void 0, ACTION_CALL_MS),
14148
+ typeAction: (type, record, name, args) => this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}${encodeURIComponent(name)}`, { id: record.id, root: this.store.authorizedRoot(record), args }, void 0, ACTION_CALL_MS),
13867
14149
  typeActions: (type, options2) => this.servers.actions(type, options2),
13868
14150
  shareOf: (record) => this.shareOf(record),
13869
14151
  log,
@@ -13995,7 +14277,7 @@ var init_daemon2 = __esm({
13995
14277
  const actions = await this.servers.actions(type, { start: true });
13996
14278
  if (!actions?.some((a) => a.name === "context")) return null;
13997
14279
  await this.openPage(record);
13998
- return this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}context`, { id: record.id, root: record.root, args: {} }, void 0, ACTION_CALL_MS);
14280
+ return this.servers.call(type, "POST", `${TYPE_SERVER_ROUTES.actions}context`, { id: record.id, root: this.store.authorizedRoot(record), args: {} }, void 0, ACTION_CALL_MS);
13999
14281
  }
14000
14282
  });
14001
14283
  }
@@ -14056,7 +14338,7 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14056
14338
  writeSync(fd, String(process.pid));
14057
14339
  closeSync4(fd);
14058
14340
  } catch {
14059
- const other = Number(readFileSync18(lock, "utf8"));
14341
+ const other = Number(readFileSync19(lock, "utf8"));
14060
14342
  let alive2 = false;
14061
14343
  try {
14062
14344
  process.kill(other, 0);
@@ -14065,7 +14347,7 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14065
14347
  alive2 = false;
14066
14348
  }
14067
14349
  if (alive2) throw new OpenArtifactError("conflict", `Another open-artifact daemon (pid ${other}) runs for ${openArtifactHome2()}.`);
14068
- writeFileSync9(lock, String(process.pid), { mode: 384 });
14350
+ writeFileSync10(lock, String(process.pid), { mode: 384 });
14069
14351
  }
14070
14352
  let port = this.wantPort;
14071
14353
  for (let i = 0; ; i++) {
@@ -14098,9 +14380,17 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14098
14380
  this.data.start();
14099
14381
  return this;
14100
14382
  }
14383
+ /** The library and startup use the same checked sharing record as the editor. */
14384
+ sharedOnLan(record) {
14385
+ try {
14386
+ return readSharingState(new WorkspaceDirectory(this.store.authorizedRoot(record)))?.lan === true;
14387
+ } catch {
14388
+ return false;
14389
+ }
14390
+ }
14101
14391
  async remountShared() {
14102
14392
  for (const record of this.store.list()) {
14103
- if (!sharedOnLan(record.root)) continue;
14393
+ if (!this.sharedOnLan(record)) continue;
14104
14394
  try {
14105
14395
  await this.openPage(record);
14106
14396
  } catch (error) {
@@ -14291,7 +14581,7 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14291
14581
  const state = readJson(files.daemon(), null);
14292
14582
  if (state?.pid === process.pid) rmSync10(files.daemon(), { force: true });
14293
14583
  try {
14294
- if (Number(readFileSync18(files.lock(), "utf8")) === process.pid) rmSync10(files.lock(), { force: true });
14584
+ if (Number(readFileSync19(files.lock(), "utf8")) === process.pid) rmSync10(files.lock(), { force: true });
14295
14585
  } catch {
14296
14586
  }
14297
14587
  this.log(`daemon ${VERSION3} stopped (${reason})`);
@@ -14417,15 +14707,15 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14417
14707
  } catch {
14418
14708
  return this.notFound(req, res);
14419
14709
  }
14420
- this.sendFile(req, res, file, file.includes(`${sep10}assets${sep10}`) ? "public, max-age=31536000, immutable" : "no-cache");
14710
+ this.sendFile(req, res, file, file.includes(`${sep11}assets${sep11}`) ? "public, max-age=31536000, immutable" : "no-cache");
14421
14711
  }
14422
14712
  sendFile(req, res, file, cache) {
14423
14713
  let stat2;
14424
14714
  try {
14425
- stat2 = statSync12(file);
14715
+ stat2 = statSync13(file);
14426
14716
  if (stat2.isDirectory()) {
14427
14717
  file = join27(file, "index.html");
14428
- stat2 = statSync12(file);
14718
+ stat2 = statSync13(file);
14429
14719
  }
14430
14720
  } catch {
14431
14721
  return this.notFound(req, res);
@@ -14448,7 +14738,7 @@ data: ${JSON.stringify({ view: view2, key: claimed.key, session: claimed.session
14448
14738
  homePage(req, res) {
14449
14739
  req.resume();
14450
14740
  try {
14451
- sendHtml(res, readFileSync18(join27(this.homeDir, "index.html"), "utf8"));
14741
+ sendHtml(res, readFileSync19(join27(this.homeDir, "index.html"), "utf8"));
14452
14742
  return;
14453
14743
  } catch {
14454
14744
  }
@@ -14566,7 +14856,7 @@ ${rows}
14566
14856
  const record = this.touchOpened(found2);
14567
14857
  let template = null;
14568
14858
  try {
14569
- template = readFileSync18(join27(this.shellDir, "index.html"), "utf8");
14859
+ template = readFileSync19(join27(this.shellDir, "index.html"), "utf8");
14570
14860
  } catch {
14571
14861
  }
14572
14862
  let boot;
@@ -14613,7 +14903,7 @@ ${rows}
14613
14903
  if (depth < 5) walk(full, path, depth + 1);
14614
14904
  } else {
14615
14905
  try {
14616
- newest = Math.max(newest, statSync12(full).mtimeMs);
14906
+ newest = Math.max(newest, statSync13(full).mtimeMs);
14617
14907
  } catch {
14618
14908
  }
14619
14909
  }
@@ -14642,7 +14932,7 @@ ${rows}
14642
14932
  if (depth < 8 && entry.name !== "node_modules") walk(full, depth + 1);
14643
14933
  } else if (entry.isFile()) {
14644
14934
  try {
14645
- bytes += statSync12(full).size;
14935
+ bytes += statSync13(full).size;
14646
14936
  } catch {
14647
14937
  }
14648
14938
  }
@@ -14685,41 +14975,69 @@ ${rows}
14685
14975
  /** A folder a Library call names (absolute or `~/...`), resolved; it must exist and be a folder. */
14686
14976
  folderArg(value) {
14687
14977
  const given = typeof value === "string" ? value.trim() : "";
14688
- if (!given || !isAbsolute6(given) && !given.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
14689
- const root = resolve16(expandHome(given));
14978
+ if (!given || !isAbsolute7(given) && !given.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
14979
+ const root = resolve17(expandHome(given));
14690
14980
  let dir = false;
14691
14981
  try {
14692
- dir = statSync12(root).isDirectory();
14982
+ dir = statSync13(root).isDirectory();
14693
14983
  } catch {
14694
14984
  }
14695
14985
  if (!dir) throw new OpenArtifactError("not_found", `No folder ${root}.`);
14696
14986
  return root;
14697
14987
  }
14698
14988
  async duplicate(record, name) {
14989
+ const source = this.store.authorizedRoot(record);
14990
+ const workspace = record.workspaceDirectory;
14991
+ const inherited = {
14992
+ type: record.type,
14993
+ typeSource: record.typeSource,
14994
+ typeRelease: record.typeRelease,
14995
+ typeUid: record.typeUid ?? null,
14996
+ owner: record.owner,
14997
+ ...workspace ? { workspaceDirectory: workspace } : {}
14998
+ };
14699
14999
  if (record.type === "docs") {
14700
15000
  const type = this.typeOf(record);
14701
15001
  if (!type) throw new OpenArtifactError("unsupported", "The Docs type is unavailable.");
15002
+ if (workspace) await this.openPage(record);
14702
15003
  const copy = await this.servers.call(
14703
15004
  type,
14704
15005
  "POST",
14705
15006
  TYPE_SERVER_ROUTES.actions + "duplicate",
14706
- { root: record.root, id: record.id, args: { name: name ?? record.title.slice(0, 249) + " (copy)" } },
15007
+ { root: source, id: record.id, args: { name: name ?? record.title.slice(0, 249) + " (copy)" } },
14707
15008
  void 0,
14708
15009
  ACTION_CALL_MS
14709
15010
  );
14710
- return this.store.create({ root: copy.root, title: copy.name, type: record.type, typeSource: record.typeSource, typeRelease: record.typeRelease, typeUid: record.typeUid ?? null, owner: record.owner });
15011
+ return this.store.create({ ...inherited, root: copy.root, title: copy.name });
14711
15012
  }
14712
- const parent = dirname11(record.root);
14713
- const base = record.root.slice(parent.length + 1);
14714
- let root = join27(parent, `${base}-copy`);
14715
- for (let n = 2; existsSync17(root); n++) root = join27(parent, `${base}-copy-${n}`);
15013
+ const directory = workspace ? new WorkspaceDirectory(workspace.root, workspace) : void 0;
15014
+ const parent = directory?.root === source ? source : dirname12(source);
15015
+ const base = basename7(source) || "work";
15016
+ const target = (name2) => directory?.resolve(join27(parent, name2), false) ?? join27(parent, name2);
15017
+ let root = target(`${base}-copy`);
14716
15018
  const skip = (name2) => name2.startsWith(".") || name2 === "history" || name2 === "exports" || name2 === "node_modules" || name2 === "_agent";
14717
- ensureDir(root);
14718
- for (const name2 of readdirSync14(record.root)) {
14719
- if (skip(name2)) continue;
14720
- cpSync3(join27(record.root, name2), join27(root, name2), { recursive: true, errorOnExist: false });
15019
+ const children = readdirSync14(source).filter((name2) => !skip(name2));
15020
+ for (let n = 2; ; n++) {
15021
+ try {
15022
+ mkdirSync8(root);
15023
+ break;
15024
+ } catch (error) {
15025
+ if (error.code !== "EEXIST") throw error;
15026
+ root = target(`${base}-copy-${n}`);
15027
+ }
14721
15028
  }
14722
- return this.store.create({ root, type: record.type, typeSource: record.typeSource, typeRelease: record.typeRelease, typeUid: record.typeUid ?? null, owner: record.owner, title: `Copy of ${record.title}`.slice(0, 200) });
15029
+ const files2 = directory ? new WorkspaceDirectory(source) : void 0;
15030
+ for (const name2 of children) {
15031
+ cpSync3(join27(source, name2), join27(root, name2), {
15032
+ recursive: true,
15033
+ errorOnExist: false,
15034
+ ...files2 ? { dereference: true, filter: (path) => {
15035
+ files2.resolve(path);
15036
+ return true;
15037
+ } } : {}
15038
+ });
15039
+ }
15040
+ return this.store.create({ ...inherited, root, title: `Copy of ${record.title}`.slice(0, 200) });
14723
15041
  }
14724
15042
  thumbnailFile(id) {
14725
15043
  return join27(files.thumbnails(), `${id}.jpg`);
@@ -14751,7 +15069,7 @@ ${rows}
14751
15069
  openedAt: record.openedAt ?? null,
14752
15070
  contentAt: this.contentAt(record),
14753
15071
  thumbnail: this.thumbnailOf(record.id),
14754
- shared: sharedOnLan(record.root),
15072
+ shared: this.sharedOnLan(record),
14755
15073
  open: this.pages.has(record.id),
14756
15074
  remote: record.remote ? { name: record.remote.name, host: record.remote.host, url: record.remote.url, syncedAt: record.remote.syncedAt } : null,
14757
15075
  ...releaseView(record, type?.version ?? null)
@@ -14787,10 +15105,10 @@ ${rows}
14787
15105
  /** The project types of the folders this computer knows, but `skip` (whose types the answer lists already). */
14788
15106
  projectTypes(skip) {
14789
15107
  const known = [...this.harnesses.workspaces(), ...this.settings.trustedProjects ?? [], this.settings.homeWorkspace, ...this.typeProjects];
14790
- const folders = new Set(known.map((d) => resolve16(d)));
15108
+ const folders = new Set(known.map((d) => resolve17(d)));
14791
15109
  const out2 = [];
14792
15110
  for (const dir of folders) {
14793
- if (skip && resolve16(skip) === dir) continue;
15111
+ if (skip && resolve17(skip) === dir) continue;
14794
15112
  const root = this.types.roots(dir).find((r) => r.scope === "project");
14795
15113
  if (!root || !existsSync17(root.root)) continue;
14796
15114
  const types3 = this.types.list(dir, { includeShadowed: true }).filter((t) => t.scope === "project");
@@ -14855,9 +15173,9 @@ ${rows}
14855
15173
  }
14856
15174
  if (name === LIBRARY_ROUTES.typesPreview || name === LIBRARY_ROUTES.import) return this.packageCall(req, res, name);
14857
15175
  const body = await readJsonBody(req);
14858
- const workspace = typeof body.workspace === "string" && isAbsolute6(body.workspace) ? resolve16(body.workspace) : null;
15176
+ const workspace = typeof body.workspace === "string" && isAbsolute7(body.workspace) ? resolve17(body.workspace) : null;
14859
15177
  const project = typeof body.project === "string" && body.project ? body.project : null;
14860
- if (project !== null && !isAbsolute6(project)) throw new OpenArtifactError("invalid_argument", "project: the project folder, as an absolute path.");
15178
+ if (project !== null && !isAbsolute7(project)) throw new OpenArtifactError("invalid_argument", "project: the project folder, as an absolute path.");
14861
15179
  const o = { settings: this.settings, registry: this.types, workspace: workspace ?? (body.scope === "project" ? project : null) ?? this.settings.homeWorkspace };
14862
15180
  const changed = () => {
14863
15181
  this.settings = loadSettings(this.preset);
@@ -14868,24 +15186,24 @@ ${rows}
14868
15186
  case R.typesNew: {
14869
15187
  const made = newType({ id: body.id, scope: body.scope, template: body.template, name: body.name, project }, o);
14870
15188
  this.log(`audit: made the type ${made.id} (${made.scope}, ${String(body.template ?? "page")}) at ${made.dir}, asked by ${this.askedBy(req, name)}`);
14871
- if (made.scope === "project" && project) this.typeProjects.add(resolve16(project));
15189
+ if (made.scope === "project" && project) this.typeProjects.add(resolve17(project));
14872
15190
  changed();
14873
15191
  return sendJson(res, 200, made);
14874
15192
  }
14875
15193
  case R.typesFrom: {
14876
15194
  if (body.path !== void 0) {
14877
15195
  if (!this.hasToken(req)) throw new OpenArtifactError("not_granted", `${R.typesFrom} with a path is for the command line: open-artifact types from <path> --id <id>.`, { status: 403 });
14878
- if (typeof body.path !== "string" || !isAbsolute6(body.path)) throw new OpenArtifactError("invalid_argument", "path: the saved page (a folder or an .html file), as an absolute path.");
15196
+ if (typeof body.path !== "string" || !isAbsolute7(body.path)) throw new OpenArtifactError("invalid_argument", "path: the saved page (a folder or an .html file), as an absolute path.");
14879
15197
  const made2 = typeFromSaved(body.path, { id: body.id, scope: body.scope, name: body.name, project }, o);
14880
15198
  this.log(`audit: made the type ${made2.id} from the saved page ${made2.source} at ${made2.dir}, asked by ${this.askedBy(req, name)}`);
14881
- if (made2.scope === "project" && project) this.typeProjects.add(resolve16(project));
15199
+ if (made2.scope === "project" && project) this.typeProjects.add(resolve17(project));
14882
15200
  changed();
14883
15201
  return sendJson(res, 200, made2);
14884
15202
  }
14885
15203
  const record = this.store.require(body.artifact);
14886
15204
  const made = typeFromPage(record, this.typeOf(record), { id: body.id, scope: body.scope, name: body.name, project }, o);
14887
15205
  this.log(`audit: made the type ${made.id} from ${record.id} at ${made.dir}, asked by ${this.askedBy(req, name)}`);
14888
- if (made.scope === "project" && project) this.typeProjects.add(resolve16(project));
15206
+ if (made.scope === "project" && project) this.typeProjects.add(resolve17(project));
14889
15207
  changed();
14890
15208
  return sendJson(res, 200, made);
14891
15209
  }
@@ -15002,7 +15320,7 @@ ${rows}
15002
15320
  bytes = raw;
15003
15321
  body = { name: url.searchParams.get("name") ?? void 0, as: url.searchParams.get("as") ?? void 0, folder: url.searchParams.get("folder") ?? void 0 };
15004
15322
  }
15005
- const label = typeof body.name === "string" && body.name ? (json ? basename6(body.name) : body.name).slice(0, 1e3) : preview ? "the package" : "the archive";
15323
+ const label = typeof body.name === "string" && body.name ? (json ? basename7(body.name) : body.name).slice(0, 1e3) : preview ? "the package" : "the archive";
15006
15324
  if (preview) {
15007
15325
  const as = typeof body.as === "string" && body.as ? body.as : null;
15008
15326
  if (!bytes) {
@@ -15017,8 +15335,8 @@ ${rows}
15017
15335
  const workspace = this.settings.homeWorkspace ?? null;
15018
15336
  const read = await readArtifactArchive(bytes, label, { registry: this.types, workspace });
15019
15337
  const folder = typeof body.folder === "string" && body.folder ? body.folder : void 0;
15020
- if (folder && !isAbsolute6(folder)) throw new OpenArtifactError("invalid_argument", "folder: where to put it, as an absolute path.");
15021
- const base = folder ? resolve16(folder) : this.tools.resolveFolder(void 0, { harness: "home", session: null, workspace }, read.top);
15338
+ if (folder && !isAbsolute7(folder)) throw new OpenArtifactError("invalid_argument", "folder: where to put it, as an absolute path.");
15339
+ const base = folder ? resolve17(folder) : this.tools.resolveFolder(void 0, { harness: "home", session: null, workspace }, read.top);
15022
15340
  let dest = base;
15023
15341
  if (!folder) for (let n = 2; existsSync17(dest); n++) dest = `${base}-${n}`;
15024
15342
  const unpacked = await unpackArtifactArchive(bytes, read, dest);
@@ -15035,6 +15353,7 @@ ${rows}
15035
15353
  * absolute address on the page's own origin.
15036
15354
  */
15037
15355
  async openPage(record, context = {}) {
15356
+ record = { ...record, root: this.store.authorizedRoot(record) };
15038
15357
  const type = this.typeOf(record);
15039
15358
  if (!type) throw new OpenArtifactError("type_missing", `The type ${record.type} is not installed.`);
15040
15359
  const mismatch = typeMismatch(record, type);
@@ -15080,7 +15399,7 @@ ${rows}
15080
15399
  let timer;
15081
15400
  try {
15082
15401
  const watcher = watch3(record.root, { recursive: true, persistent: false }, (_event, name) => {
15083
- const rel = String(name ?? "").split(sep10).join("/");
15402
+ const rel = String(name ?? "").split(sep11).join("/");
15084
15403
  if (!rel || rel.split("/").some((part) => part.startsWith("."))) return;
15085
15404
  changed.add(rel);
15086
15405
  clearTimeout(timer);
@@ -15129,14 +15448,18 @@ ${rows}
15129
15448
  if (rel.includes("\0")) return this.notFound(req, res);
15130
15449
  let base = type.dir;
15131
15450
  if (rel === "/_root" || rel.startsWith("/_root/")) {
15132
- base = record.root;
15451
+ try {
15452
+ base = this.store.authorizedRoot(record);
15453
+ } catch {
15454
+ return this.notFound(req, res);
15455
+ }
15133
15456
  rel = rel.slice("/_root".length);
15134
15457
  } else if (rel === "/" || rel === "") rel = `/${type.entry.file}`;
15135
15458
  const parts = rel.split("/").filter(Boolean);
15136
15459
  if (parts.some((part) => part.startsWith("."))) return this.notFound(req, res);
15137
15460
  let file;
15138
15461
  try {
15139
- file = parts.length ? inside(resolve16(base), parts.join("/")) : resolve16(base);
15462
+ file = parts.length ? inside(resolve17(base), parts.join("/")) : resolve17(base);
15140
15463
  } catch {
15141
15464
  return this.notFound(req, res);
15142
15465
  }
@@ -15154,7 +15477,7 @@ ${rows}
15154
15477
  async sendArchive(req, res, record) {
15155
15478
  if (this.typeOf(record)?.entry?.kind === "static") {
15156
15479
  res.setHeader("X-Content-Type-Options", "nosniff");
15157
- return sendArchive(req, res, record.root);
15480
+ return sendArchive(req, res, this.store.authorizedRoot(record));
15158
15481
  }
15159
15482
  const head = req.method === "HEAD";
15160
15483
  const answer = await this.archiveAnswer(record, head ? "HEAD" : "GET");
@@ -15192,7 +15515,7 @@ ${rows}
15192
15515
  }
15193
15516
  /** The artifact's folder as a zip, made by its type server with the export's rules (what Link publishes). */
15194
15517
  async archiveBytes(record) {
15195
- if (this.typeOf(record)?.entry?.kind === "static") return zipBytes(await archiveEntries(record.root));
15518
+ if (this.typeOf(record)?.entry?.kind === "static") return zipBytes(await archiveEntries(this.store.authorizedRoot(record)));
15196
15519
  const answer = await this.archiveAnswer(record, "GET", 3e5);
15197
15520
  const type = this.typeOf(record);
15198
15521
  if (type && typeLocation(type).remote) return remoteArchiveBytes(type, answer);
@@ -15219,7 +15542,7 @@ ${rows}
15219
15542
  typeToken(typeId) {
15220
15543
  let token = this.typeTokens.get(typeId);
15221
15544
  if (!token) {
15222
- token = `oat_${randomBytes9(24).toString("base64url")}`;
15545
+ token = `oat_${randomBytes10(24).toString("base64url")}`;
15223
15546
  this.typeTokens.set(typeId, token);
15224
15547
  this.tokenTypes.set(token, typeId);
15225
15548
  }
@@ -15517,7 +15840,7 @@ data: ${JSON.stringify({ type: "presence", id, ...this.presenceOf(record) })}
15517
15840
  if (get2) {
15518
15841
  let image2;
15519
15842
  try {
15520
- image2 = readFileSync18(this.thumbnailFile(record.id));
15843
+ image2 = readFileSync19(this.thumbnailFile(record.id));
15521
15844
  } catch {
15522
15845
  throw new OpenArtifactError("not_found", "No thumbnail yet.");
15523
15846
  }
@@ -15532,7 +15855,7 @@ data: ${JSON.stringify({ type: "presence", id, ...this.presenceOf(record) })}
15532
15855
  if (image.length < 4 || image[0] !== 255 || image[1] !== 216) throw new OpenArtifactError("invalid_argument", "The body is not a JPEG.");
15533
15856
  const v = url.searchParams.get("v") || this.contentAt(record);
15534
15857
  ensureDir(files.thumbnails());
15535
- writeFileSync9(this.thumbnailFile(record.id), image);
15858
+ writeFileSync10(this.thumbnailFile(record.id), image);
15536
15859
  writeJson(join27(files.thumbnails(), `${record.id}.json`), { v, at: (/* @__PURE__ */ new Date()).toISOString() });
15537
15860
  return sendJson(res, 200, { thumbnail: v });
15538
15861
  }
@@ -15560,7 +15883,7 @@ data: ${JSON.stringify({ type: "presence", id, ...this.presenceOf(record) })}
15560
15883
  const typeId = String(body.type ?? "").replace(/^open-artifact:\/\/type\//, "");
15561
15884
  if (!typeId) throw new OpenArtifactError("invalid_argument", "type: the type id (or open-artifact://type/<id>) to create from.");
15562
15885
  const folder = typeof body.folder === "string" && body.folder.trim() ? body.folder.trim() : void 0;
15563
- if (folder && !isAbsolute6(folder) && !folder.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
15886
+ if (folder && !isAbsolute7(folder) && !folder.startsWith("~")) throw new OpenArtifactError("invalid_argument", "folder: an absolute path (or ~/...).");
15564
15887
  const caller2 = { harness: HOME_HARNESS, session: null, workspace: this.settings.homeWorkspace };
15565
15888
  const blank = body.blank === true;
15566
15889
  const made = await this.tools.call(
@@ -15637,7 +15960,7 @@ ${takeOverPrompt(record, view2.typeTitle)}` : takeOverPrompt(record, view2.typeT
15637
15960
  }
15638
15961
  const other = this.store.byRoot(root);
15639
15962
  if (other && other.id !== record.id) throw new OpenArtifactError("conflict", `${root} is already the folder of ${other.id}.`);
15640
- if (resolve16(record.root) === root) return sendJson(res, 200, this.artifactView(record));
15963
+ if (resolve17(record.root) === root) return sendJson(res, 200, this.artifactView(record));
15641
15964
  this.closePage(record);
15642
15965
  this.shellOpens.delete(record.id);
15643
15966
  this.contentStamps.delete(record.root);
@@ -15767,7 +16090,7 @@ ${takeOverPrompt(record, view2.typeTitle)}` : takeOverPrompt(record, view2.typeT
15767
16090
  }
15768
16091
  case "artifacts.publish": {
15769
16092
  const body = await readJsonBody(req);
15770
- const folder = typeof body.folder === "string" && body.folder ? resolve16(expandHome(body.folder)) : null;
16093
+ const folder = typeof body.folder === "string" && body.folder ? resolve17(expandHome(body.folder)) : null;
15771
16094
  let record = folder ? this.store.byRoot(folder) : this.store.require(body.id ?? body.url);
15772
16095
  let adopted = false;
15773
16096
  if (!record && folder && body.adopt === true) {
@@ -15923,8 +16246,8 @@ ${takeOverPrompt(record, view2.typeTitle)}` : takeOverPrompt(record, view2.typeT
15923
16246
  // packages/daemon/src/bin/open-artifact.ts
15924
16247
  init_src();
15925
16248
  import { execFileSync } from "node:child_process";
15926
- import { existsSync as existsSync18, readFileSync as readFileSync19, realpathSync as realpathSync4 } from "node:fs";
15927
- import { resolve as resolvePath, sep as sep11 } from "node:path";
16249
+ import { existsSync as existsSync18, readFileSync as readFileSync20, realpathSync as realpathSync5 } from "node:fs";
16250
+ import { resolve as resolvePath, sep as sep12 } from "node:path";
15928
16251
  import { createInterface as createInterface2 } from "node:readline";
15929
16252
 
15930
16253
  // packages/daemon/src/agent-session.ts
@@ -16246,8 +16569,8 @@ init_package();
16246
16569
  init_harness_skill();
16247
16570
  init_settings2();
16248
16571
  init_types();
16249
- import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "node:fs";
16250
- import { join as join14, resolve as resolve12 } from "node:path";
16572
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
16573
+ import { join as join15, resolve as resolve13 } from "node:path";
16251
16574
  var VERSION2 = package_default.version ?? "0.0.0";
16252
16575
  function renderSkillFor(options) {
16253
16576
  const form = options.form ?? "full";
@@ -16255,7 +16578,7 @@ function renderSkillFor(options) {
16255
16578
  const registry = new TypeRegistry(loadSettings);
16256
16579
  try {
16257
16580
  const harness = options.harness || "cli";
16258
- const workspace = resolve12(options.workspace ?? process.cwd());
16581
+ const workspace = resolve13(options.workspace ?? process.cwd());
16259
16582
  const params = { form, ...options.command ? { command: options.command } : {} };
16260
16583
  return skillFor(params, {
16261
16584
  harness,
@@ -16273,17 +16596,17 @@ function installSkillFile(options) {
16273
16596
  throw new OpenArtifactError("invalid_argument", "--command <name>: lowercase letters, digits, - and _, without the slash.");
16274
16597
  }
16275
16598
  const skill = renderSkillFor(options);
16276
- const folder = join14(resolve12(options.dir), skill.name);
16277
- const file = join14(folder, "SKILL.md");
16599
+ const folder = join15(resolve13(options.dir), skill.name);
16600
+ const file = join15(folder, "SKILL.md");
16278
16601
  if (existsSync9(file)) {
16279
- const text3 = readFileSync8(file, "utf8");
16602
+ const text3 = readFileSync9(file, "utf8");
16280
16603
  if (!options.force && !skillFileKey(text3, SKILL_GENERATED_BY)) {
16281
16604
  throw new OpenArtifactError("conflict", `${file} was not written by Open Artifact: it stays.`, { fix: "Pass --force to replace it, or choose another --dir or --command." });
16282
16605
  }
16283
16606
  if (skillFileKey(text3, "etag") === skill.etag) return { file, written: false, etag: skill.etag, reason: "unchanged" };
16284
16607
  }
16285
16608
  mkdirSync4(folder, { recursive: true });
16286
- writeFileSync4(file, renderedSkillFile(skill));
16609
+ writeFileSync5(file, renderedSkillFile(skill));
16287
16610
  return { file, written: true, etag: skill.etag };
16288
16611
  }
16289
16612
  function skillCommand(sub, flag2, has2) {
@@ -16412,8 +16735,8 @@ function doctorText(report) {
16412
16735
  // packages/daemon/src/doctor-checks.ts
16413
16736
  init_src2();
16414
16737
  init_src();
16415
- import { accessSync, constants as constants2, existsSync as existsSync11, readFileSync as readFileSync10, statSync as statSync7 } from "node:fs";
16416
- import { join as join18 } from "node:path";
16738
+ import { accessSync, constants as constants2, existsSync as existsSync11, readFileSync as readFileSync11, statSync as statSync8 } from "node:fs";
16739
+ import { join as join19 } from "node:path";
16417
16740
 
16418
16741
  // packages/daemon/src/doctor-conformance.ts
16419
16742
  init_src2();
@@ -16422,7 +16745,7 @@ init_paths();
16422
16745
  init_package();
16423
16746
  import { mkdtempSync, rmSync as rmSync5 } from "node:fs";
16424
16747
  import { tmpdir } from "node:os";
16425
- import { join as join16 } from "node:path";
16748
+ import { join as join17 } from "node:path";
16426
16749
  var CONFORMANCE_TITLE = "open-artifact doctor test";
16427
16750
  var CONFORMANCE_WAKE_TEXT = "open-artifact doctor is checking that a request from the page reaches you. Nothing to do: reply in one line that you got it.";
16428
16751
  var TOOLS2 = ["Artifact", "ArtifactData", "ArtifactComments"];
@@ -16588,8 +16911,8 @@ var toolsStep = {
16588
16911
  const create = run.quickstart.create;
16589
16912
  if (!create?.type_url) throw new Error(`quickstart answered no create call for ${type.id}`);
16590
16913
  run.typeUrl = String(create.type_url);
16591
- run.folder = mkdtempSync(join16(tmpdir(), "open-artifact-doctor-"));
16592
- const made = await call(run, context, "Artifact", { ...create, title: CONFORMANCE_TITLE, folder: join16(run.folder, "artifact"), open: "never" });
16914
+ run.folder = mkdtempSync(join17(tmpdir(), "open-artifact-doctor-"));
16915
+ const made = await call(run, context, "Artifact", { ...create, title: CONFORMANCE_TITLE, folder: join17(run.folder, "artifact"), open: "never" });
16593
16916
  const url = String(made.url ?? "");
16594
16917
  run.artifact = { url, id: url.split("/").pop() ?? "" };
16595
16918
  const detail = await api(run.state, "artifact", void 0, { query: { id: run.artifact.id } });
@@ -16702,7 +17025,7 @@ var rulesStep = {
16702
17025
  run.probe = `doctor-probe-${Math.random().toString(36).slice(2, 10)}`;
16703
17026
  try {
16704
17027
  await run.client.attach({ session: run.probe, ...run.workspace ? { workspace: run.workspace } : {}, role: refused.role });
16705
- const args = refused.need === "create" ? { action: "publish", type_url: run.typeUrl, title: `${CONFORMANCE_TITLE} (probe)`, folder: join16(run.folder, "probe"), open: "never" } : refused.need === "modify" ? { action: "publish", url: run.artifact.url, files: { "doctor-probe.txt": "probe" } } : { action: "delete", url: run.artifact.url };
17028
+ const args = refused.need === "create" ? { action: "publish", type_url: run.typeUrl, title: `${CONFORMANCE_TITLE} (probe)`, folder: join17(run.folder, "probe"), open: "never" } : refused.need === "modify" ? { action: "publish", url: run.artifact.url, files: { "doctor-probe.txt": "probe" } } : { action: "delete", url: run.artifact.url };
16706
17029
  try {
16707
17030
  const made = await call(run, context, "Artifact", args, run.probe);
16708
17031
  if (typeof made.url === "string" && refused.need === "create") run.extra.push(made.url);
@@ -16934,7 +17257,7 @@ var daemon = {
16934
17257
  const found2 = [{ status: "ok", message: `Daemon ${state.version ?? "?"} running at ${state.url} (pid ${state.pid})` }];
16935
17258
  if (process.platform !== "win32") {
16936
17259
  try {
16937
- const mode2 = statSync7(files.daemon()).mode & 511;
17260
+ const mode2 = statSync8(files.daemon()).mode & 511;
16938
17261
  if (mode2 & 63) return [...found2, { status: "fail", message: `daemon.json (which holds the token) is readable by others (mode ${mode2.toString(8)})`, fix: `chmod 600 ${files.daemon()}` }];
16939
17262
  } catch {
16940
17263
  }
@@ -17040,10 +17363,10 @@ var settings = {
17040
17363
  id: "settings",
17041
17364
  title: "Settings",
17042
17365
  run: ({ home: home2 }) => {
17043
- const file = join18(home2, "settings.json");
17366
+ const file = join19(home2, "settings.json");
17044
17367
  if (!existsSync11(file)) return { status: "ok", message: "Settings: the defaults (no settings.json)" };
17045
17368
  try {
17046
- JSON.parse(readFileSync10(file, "utf8"));
17369
+ JSON.parse(readFileSync11(file, "utf8"));
17047
17370
  return { status: "ok", message: `Settings: ${file}` };
17048
17371
  } catch (error) {
17049
17372
  return { status: "fail", message: `settings.json is not valid JSON (${error.message})`, fix: `Fix or remove ${file}; until then the defaults apply.` };
@@ -17069,9 +17392,9 @@ async function runStdioBridge(options) {
17069
17392
  };
17070
17393
  const waiting = /* @__PURE__ */ new Map();
17071
17394
  let next = 1;
17072
- const callHost = (method, params) => new Promise((resolve17, reject) => {
17395
+ const callHost = (method, params) => new Promise((resolve18, reject) => {
17073
17396
  const id = `d${next++}`;
17074
- waiting.set(id, { resolve: resolve17, reject });
17397
+ waiting.set(id, { resolve: resolve18, reject });
17075
17398
  write({ id, method, params });
17076
17399
  });
17077
17400
  let client = null;
@@ -17169,7 +17492,7 @@ async function runStdioBridge(options) {
17169
17492
  );
17170
17493
  };
17171
17494
  const lines = createInterface({ input: options.input, crlfDelay: Infinity });
17172
- await new Promise((resolve17) => {
17495
+ await new Promise((resolve18) => {
17173
17496
  lines.on("line", (line) => {
17174
17497
  if (Buffer.byteLength(line) > MAX_LINE2) {
17175
17498
  log("stdio: a line over 64 MiB; ending");
@@ -17178,7 +17501,7 @@ async function runStdioBridge(options) {
17178
17501
  }
17179
17502
  onLine(line);
17180
17503
  });
17181
- lines.on("close", resolve17);
17504
+ lines.on("close", resolve18);
17182
17505
  });
17183
17506
  for (const pending of waiting.values()) pending.reject(new OpenArtifactError("disconnected", "The host closed stdin."));
17184
17507
  waiting.clear();
@@ -17273,7 +17596,7 @@ function caller() {
17273
17596
  function ownWorkspace() {
17274
17597
  const real = (dir) => {
17275
17598
  try {
17276
- return realpathSync4(dir);
17599
+ return realpathSync5(dir);
17277
17600
  } catch {
17278
17601
  return resolvePath(dir);
17279
17602
  }
@@ -17283,7 +17606,7 @@ function ownWorkspace() {
17283
17606
  const plugins = [env.OPEN_ARTIFACT_PLUGIN_DIR, env.PLUGIN_ROOT, env.CLAUDE_PLUGIN_ROOT, env.CURSOR_PLUGIN_ROOT].filter((dir) => !!dir);
17284
17607
  return plugins.some((dir) => {
17285
17608
  const root = real(dir);
17286
- return cwd === root || cwd.startsWith(root + sep11);
17609
+ return cwd === root || cwd.startsWith(root + sep12);
17287
17610
  }) ? null : process.cwd();
17288
17611
  }
17289
17612
  function ancestors(start = process.ppid, depth = 4) {
@@ -17479,7 +17802,7 @@ async function hook(event) {
17479
17802
  if (!event) die("hook <event>");
17480
17803
  let input = {};
17481
17804
  try {
17482
- const text3 = readFileSync19(0, "utf8");
17805
+ const text3 = readFileSync20(0, "utf8");
17483
17806
  input = text3.trim() ? JSON.parse(text3) : {};
17484
17807
  } catch {
17485
17808
  input = {};
@@ -17551,7 +17874,10 @@ async function daemon2(sub) {
17551
17874
  exit();
17552
17875
  };
17553
17876
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, stop);
17554
- const started = await startDaemon2(port !== void 0 ? { port: Number(port) } : {});
17877
+ const started = await startDaemon2({
17878
+ ...port !== void 0 ? { port: Number(port) } : {},
17879
+ ...process.env.OPEN_ARTIFACT_WORKSPACE_FOLDERS_ONLY === "1" ? { workspaceFoldersOnly: true } : {}
17880
+ });
17555
17881
  running = started;
17556
17882
  started.on("exit", exit);
17557
17883
  if (asked) return stop(asked);
@@ -17629,7 +17955,7 @@ async function importCommand(file) {
17629
17955
  let bytes;
17630
17956
  const path = resolvePath(file);
17631
17957
  try {
17632
- bytes = readFileSync19(path);
17958
+ bytes = readFileSync20(path);
17633
17959
  } catch (error) {
17634
17960
  die(`import: cannot read ${path} (${error.message})`);
17635
17961
  }
@@ -17935,7 +18261,7 @@ function harnessCommand(sub) {
17935
18261
  personOnly("harness-add", `open-artifact harness add ${resolvePath(file)}`);
17936
18262
  let raw;
17937
18263
  try {
17938
- raw = JSON.parse(readFileSync19(resolvePath(file), "utf8"));
18264
+ raw = JSON.parse(readFileSync20(resolvePath(file), "utf8"));
17939
18265
  } catch (error) {
17940
18266
  die(`harness add: cannot read ${file} as JSON (${error.message})`);
17941
18267
  }