@0perator/operator 0.1.359 → 0.1.360-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dashboard/index.html +2 -2
  2. package/dist/autonomy/cloud-agent.js +2 -2
  3. package/dist/autonomy/headless.js +15 -6
  4. package/dist/autonomy/session-factory.js +2 -1
  5. package/dist/background/notices.js +1 -1
  6. package/dist/browser/session.js +7 -0
  7. package/dist/cli.js +94 -52
  8. package/dist/config/features.js +6 -5
  9. package/dist/config/persona.js +57 -40
  10. package/dist/config/settings.js +39 -55
  11. package/dist/config/toolchain.js +14 -1
  12. package/dist/engine/agent.js +72 -33
  13. package/dist/engine/aurora.js +24 -2
  14. package/dist/engine/compaction.js +27 -7
  15. package/dist/engine/decision-points.js +16 -4
  16. package/dist/engine/kv-slot.js +87 -0
  17. package/dist/engine/loop-guard.js +49 -18
  18. package/dist/engine/messages.js +8 -1
  19. package/dist/engine/progress-deadline.js +37 -0
  20. package/dist/engine/verify-gate.js +134 -9
  21. package/dist/enterprise/cli.js +13 -1
  22. package/dist/mcp/craft-server.js +5 -3
  23. package/dist/memory/live-progress.js +35 -6
  24. package/dist/permissions/policy.js +8 -0
  25. package/dist/permissions/signature.js +9 -0
  26. package/dist/products/artifact-library.js +47 -0
  27. package/dist/products/craft.js +58 -94
  28. package/dist/products/temple.js +230 -0
  29. package/dist/remote/host.js +28 -1
  30. package/dist/router/discovery.js +23 -6
  31. package/dist/router/models.js +29 -70
  32. package/dist/services/preflight.js +3 -41
  33. package/dist/session.js +121 -38
  34. package/dist/skills/catalogue.js +2 -0
  35. package/dist/skills/finder.js +1 -1
  36. package/dist/toolchain/toolchain.py +20 -3
  37. package/dist/tools/background-result.js +26 -0
  38. package/dist/tools/chauffeur-native.js +6 -0
  39. package/dist/tools/craft.js +17 -6
  40. package/dist/tools/deferred.js +64 -30
  41. package/dist/tools/executor.js +4 -2
  42. package/dist/tools/paths.js +3 -3
  43. package/dist/tools/read-ledger.js +44 -0
  44. package/dist/tools/registry.js +218 -264
  45. package/dist/tools/sandbox.js +52 -39
  46. package/dist/tools/shell-context.js +5 -0
  47. package/dist/tools/shell-session.js +61 -29
  48. package/dist/tools/vision-gateway.js +79 -34
  49. package/dist/tools/wave-tools.js +2 -2
  50. package/dist/tools/wave2-tools.js +6 -6
  51. package/dist/ui/ArtifactPicker.js +2 -2
  52. package/dist/ui/Composer.js +9 -2
  53. package/dist/ui/StatusRule.js +1 -1
  54. package/dist/ui/modelPicker.js +1 -1
  55. package/dist/ui/nextStep.js +1 -0
  56. package/dist/ui/pending.js +10 -0
  57. package/dist/update.js +87 -9
  58. package/dist/util/retry.js +34 -0
  59. package/dist/util/slash.js +2 -1
  60. package/dist/vault/tool.js +3 -1
  61. package/mcp/powertools-toolbox.mjs +166 -1
  62. package/package.json +9 -13
  63. package/dashboard/README.md +0 -62
  64. package/dist/compose/client.js +0 -56
  65. package/mcp/README.md +0 -88
  66. package/mcp/powertools.md +0 -210
@@ -0,0 +1,47 @@
1
+ // The owner's artifact library on Temple — the data source for the /artifacts browser (search · attach · copy url ·
2
+ // delete). Same identity and transport as artifact_create (products/temple.ts): the signed-in Operator token, Temple's
3
+ // owner-scoped temple_list / temple_read / temple_delete. Never a fleet key, never another account's artifacts.
4
+ import * as temple from "./temple.js";
5
+ import { getOperatorToken } from "../engine/aurora.js";
6
+ export class ArtifactLibraryError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "ArtifactLibraryError";
10
+ }
11
+ }
12
+ /** The share link people open — a pure string, no network call (the "copy url" action). */
13
+ export const viewUrl = (id) => temple.shareUrl(id);
14
+ const summary = (a) => ({ id: a.id, title: a.title, url: temple.shareUrl(a.id), created_at: a.created_at, content_type: a.kind });
15
+ const unwrap = (r) => {
16
+ if (!r.ok)
17
+ throw new ArtifactLibraryError(r.error);
18
+ return r.value;
19
+ };
20
+ /** The owner's library, newest first. */
21
+ export async function listMine(limit = 100) {
22
+ return unwrap(await temple.list(limit)).map(summary);
23
+ }
24
+ /** The owner's artifacts whose title, kind or id contains every word of `q` (case-insensitive). */
25
+ export async function search(q) {
26
+ const words = q.toLowerCase().split(/\s+/).filter(Boolean);
27
+ return (await listMine()).filter((a) => words.every((w) => `${a.title} ${a.content_type} ${a.id}`.toLowerCase().includes(w)));
28
+ }
29
+ /** One artifact's metadata plus its entry page (index.html), for attaching to a turn. */
30
+ export async function get(id, fetchImpl = fetch) {
31
+ const a = unwrap(await temple.read(id));
32
+ let content = "";
33
+ if (a.view_url) {
34
+ const token = getOperatorToken() || process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN;
35
+ try {
36
+ const res = await fetchImpl(`${a.view_url.replace(/\/?$/, "/")}index.html`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
37
+ if (res.ok)
38
+ content = await res.text();
39
+ }
40
+ catch { /* metadata alone still attaches */ }
41
+ }
42
+ return { ...summary(a), content };
43
+ }
44
+ /** Delete one artifact (owner-checked server-side). */
45
+ export async function del(id) {
46
+ unwrap(await temple.remove(id));
47
+ }
@@ -1,27 +1,16 @@
1
- // Craft product handlers — the hosted, account-owned, shareable surface (page / deck / doc / board / dashboard /
2
- // app) on the shared product rails (SPEC products-craft-mdoc §craft). The promotion of artifact_create into a
3
- // first-class, owned, versioned, addressable product.
4
- //
5
- // Same broker shape as artifactCreate: an env-configurable base, the op_ bearer (the ONLY credential sent, never
6
- // logged), graceful when the surface is down. Account-ownership, ACL, versioning and the change-feed/revoke
7
- // guarantee live SERVER-SIDE on the hosted surface (the shared-contract backend); this client brokers and never
8
- // owns the ACL. Scope + types come from the canonical rails (store.ts / scope.ts) — not redefined here.
1
+ // Craft product handlers — the account-owned, versioned, shareable artifacts (page / deck / doc / board / dashboard /
2
+ // app / image / video) behind the craft_* tools and the craft MCP server. Storage, ownership, ACL and versions live on
3
+ // Temple, the one artifact surface (products/temple.ts); this layer adds the product's scope check (`domain:craft`)
4
+ // and the tool-facing wording. Same rails as before: the caller's own bearer + scopes when the MCP server hands them
5
+ // in, else the signed-in process identity.
9
6
  import { readFileSync } from "node:fs";
10
7
  import { domainInScope, DOMAIN_DENIED } from "./scope.js";
11
8
  import { operatorPath } from "../config/home.js";
9
+ import * as temple from "./temple.js";
12
10
  const CRAFT_DOMAIN = "craft";
13
11
  const str = (v, fallback = "") => (v === undefined || v === null ? fallback : String(v));
14
- /** Hosted-surface base — env-configurable, no host surfaced in any user-read string. */
15
- function craftBase() {
16
- return (process.env.KODE_CRAFT_URL || process.env.KODE_CRAFTBOARD_URL || "https://craftboard.axe.onl").replace(/\/$/, "");
17
- }
18
- /** The signed-in operator bearer — the ONLY credential sent; never logged. */
19
- function operatorToken() {
20
- return process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN || process.env.KODE_CRAFT_TOKEN || undefined;
21
- }
22
- /** This key's scope atoms (AuthGate authz, e.g. "domain:craft") — same source + shape mdoc's resolveActor uses:
23
- * the cached identity's claims.scopes, with an env override. Empty ⇒ unrestricted (legacy key); domainInScope
24
- * applies the `domain:` rule. */
12
+ /** This key's scope atoms (AuthGate authz, e.g. "domain:craft") — the cached identity's claims.scopes, with an env
13
+ * override. Empty ⇒ unrestricted (legacy key); domainInScope applies the `domain:` rule. */
25
14
  function resolveScopes() {
26
15
  const env = process.env.KODE_OPERATOR_SCOPES;
27
16
  if (env !== undefined)
@@ -34,104 +23,79 @@ function resolveScopes() {
34
23
  return [];
35
24
  }
36
25
  }
37
- const CRAFT_TYPES = /^(page|deck|doc|board|dashboard|app|svg|markdown|canvas|html)$/;
38
- /** One brokered call to the hosted Craft object API. Carries the op_ bearer; graceful on any failure; never throws. */
39
- async function craftCall({ method, path, body, timeoutMs = 30_000, auth }) {
26
+ function gate(auth) {
40
27
  if (!domainInScope(auth?.scopes ?? resolveScopes(), CRAFT_DOMAIN))
41
- return { ok: false, error: `${DOMAIN_DENIED}: this key is not scoped for the Craft product` };
42
- const token = auth?.bearer ?? operatorToken();
43
- if (!token)
44
- return { ok: false, error: "not signed in — Craft needs an Operator account (run `operator auth login`)" };
45
- const base = craftBase();
46
- const ctrl = new AbortController();
47
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
48
- try {
49
- const res = await fetch(`${base}${path}`, {
50
- method, signal: ctrl.signal,
51
- headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", Authorization: `Bearer ${token}` },
52
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
53
- });
54
- if (res.status === 401 || res.status === 403)
55
- return { ok: false, error: `the Craft surface refused this request (${res.status}) — your key may not be scoped for Craft, or you lack access to this object.` };
56
- if (!res.ok)
57
- return { ok: false, error: `the Craft surface returned ${res.status} — it may be down or moved.` };
58
- const json = (await res.json().catch(() => ({})));
59
- return { ok: true, json };
60
- }
61
- catch (e) {
62
- const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
63
- return { ok: false, error: `could not reach the Craft surface (${msg})` };
64
- }
65
- finally {
66
- clearTimeout(timer);
67
- }
68
- }
69
- function viewUrlOf(json) {
70
- const direct = str(json.viewUrl || json.url);
71
- if (direct)
72
- return direct;
73
- const rel = str(json.path).match(/\/v\/[A-Za-z0-9_-]+/); // the surface returns a relative "/v/<id>"
74
- return rel ? `${craftBase()}${rel[0]}` : undefined;
28
+ return `${DOMAIN_DENIED}: this key is not scoped for the Craft product`;
29
+ return undefined;
75
30
  }
31
+ const visibilityOf = (v) => (/^(private|link|public)$/.test(str(v)) ? str(v) : undefined);
76
32
  export async function craftCreate(args, auth) {
77
33
  const content = str(args.content);
78
- if (!content)
79
- return "error: craft_create needs `content` (the page/deck/doc body — HTML, SVG, or markdown)";
80
- const typeIn = str(args.type).toLowerCase();
81
- const type = CRAFT_TYPES.test(typeIn) ? typeIn : "page";
82
- const title = str(args.title) || "Operator craft";
83
- const r = await craftCall({ method: "POST", path: "/api/v1/craft", body: { type, title, content }, auth });
34
+ const paths = Array.isArray(args.paths) ? args.paths.map(String).filter(Boolean) : [];
35
+ if (!content && !paths.length)
36
+ return "error: craft_create needs `content` (HTML, markdown, SVG or text) or `paths` (images, video, files)";
37
+ const denied = gate(auth);
38
+ if (denied)
39
+ return `error: ${denied}`;
40
+ const r = await temple.publish({ title: str(args.title) || "Operator craft", content: content || undefined, content_type: str(args.content_type) || undefined, kind: str(args.type) || undefined, paths, visibility: visibilityOf(args.visibility) ?? "link" }, auth);
84
41
  if (!r.ok)
85
42
  return `error: ${r.error}`;
86
- const id = str(r.json.id);
87
- const url = viewUrlOf(r.json);
88
- return url ? `created craft ${id} → ${url}` : (id ? `created craft ${id} (no URL returned)` : "craft created (no id returned)");
43
+ return `created craft ${r.value.id} (${r.value.kind}, v${r.value.version}) → ${r.value.share}`;
89
44
  }
90
45
  export async function craftUpdate(args, auth) {
91
46
  const id = str(args.id);
92
47
  if (!id)
93
48
  return "error: craft_update needs `id` (from craft_create / craft_list)";
94
- const patch = {};
95
- if (str(args.content))
96
- patch.content = str(args.content);
97
- if (str(args.title))
98
- patch.title = str(args.title);
99
- if (str(args.visibility))
100
- patch.visibility = str(args.visibility); // server validates against the shared Visibility set
101
- if (Object.keys(patch).length === 0)
49
+ const visibility = visibilityOf(args.visibility);
50
+ if (!str(args.content) && !str(args.title) && !visibility)
102
51
  return "error: craft_update needs at least one of `content`, `title`, `visibility`";
103
- if (str(args.expected_version))
104
- patch.expectedVersion = str(args.expected_version); // optimistic concurrency
105
- const r = await craftCall({ method: "PATCH", path: `/api/v1/craft/${encodeURIComponent(id)}`, body: patch, auth });
52
+ const denied = gate(auth);
53
+ if (denied)
54
+ return `error: ${denied}`;
55
+ let base = Number(args.expected_version);
56
+ if (!Number.isInteger(base) || base < 1) {
57
+ const cur = await temple.read(id, auth);
58
+ if (!cur.ok)
59
+ return `error: ${cur.error}`;
60
+ base = cur.value.version;
61
+ }
62
+ const r = await temple.update(id, { base_version: base, title: str(args.title) || undefined, content: str(args.content) || undefined, content_type: str(args.content_type) || undefined, visibility }, auth);
106
63
  if (!r.ok)
107
- return `error: ${r.error}`;
108
- if (str(r.json.conflict))
109
- return `error: craft ${id} changed since you read it (expected ${str(args.expected_version)}, live ${str(r.json.version)}) — craft_get it again, reapply, retry.`;
110
- const url = viewUrlOf(r.json);
111
- return `updated craft ${id}${str(r.json.version) ? ` → version ${str(r.json.version)}` : ""}${url ? ` · ${url}` : ""}`;
64
+ return /version|conflict/i.test(r.error) ? `error: craft ${id} changed since you read it (${r.error}) — craft_get it again, reapply, retry.` : `error: ${r.error}`;
65
+ return `updated craft ${id} → version ${r.value.version} · ${r.value.share}`;
112
66
  }
113
67
  export async function craftList(args, auth) {
114
- const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100);
115
- const r = await craftCall({ method: "GET", path: `/api/v1/craft?limit=${limit}`, timeoutMs: 15_000, auth });
68
+ const denied = gate(auth);
69
+ if (denied)
70
+ return `error: ${denied}`;
71
+ const r = await temple.list(Number(args.limit) || 20, auth);
116
72
  if (!r.ok)
117
73
  return `error: ${r.error}`;
118
- const items = Array.isArray(r.json.items) ? r.json.items : [];
119
- if (!items.length)
120
- return "no craft yet — make one with craft_create";
121
- return items.map((it) => `${str(it.id)} · ${str(it.type) || "page"} · ${str(it.title) || "(untitled)"} · ${str(it.visibility) || "private"}${viewUrlOf(it) ? ` · ${viewUrlOf(it)}` : ""}`).join("\n");
74
+ return r.value.length ? r.value.map(temple.format.line).join("\n") : "no craft yet — make one with craft_create";
122
75
  }
123
76
  export async function craftGet(args, auth) {
124
77
  const id = str(args.id);
125
78
  if (!id)
126
79
  return "error: craft_get needs `id`";
127
- const r = await craftCall({ method: "GET", path: `/api/v1/craft/${encodeURIComponent(id)}`, timeoutMs: 15_000, auth });
80
+ const denied = gate(auth);
81
+ if (denied)
82
+ return `error: ${denied}`;
83
+ const r = await temple.read(id, auth);
128
84
  if (!r.ok)
129
85
  return `error: ${r.error}`;
130
- const j = r.json;
131
- const url = viewUrlOf(j);
132
- const head = `craft ${str(j.id)} · ${str(j.type) || "page"} · ${str(j.title) || "(untitled)"} · ${str(j.visibility) || "private"} · owner ${str(j.owner)} · v${str(j.version)}`;
133
- const body = str(j.content);
134
- return `${head}${url ? `\n${url}` : ""}${body ? `\n\n${body.length > 4000 ? body.slice(0, 4000) + "\n… (truncated; craft_get returns the current version)" : body}` : ""}`;
86
+ const a = r.value;
87
+ const files = Array.isArray(a.files) ? ` · files: ${a.files.map((f) => (typeof f === "string" ? f : str(f.path))).join(", ")}` : "";
88
+ return `${temple.format.line(a)}${files}${a.view_url ? `\nrender: ${a.view_url}` : ""}`;
89
+ }
90
+ export async function craftDelete(args, auth) {
91
+ const id = str(args.id);
92
+ if (!id)
93
+ return "error: craft_delete needs `id`";
94
+ const denied = gate(auth);
95
+ if (denied)
96
+ return `error: ${denied}`;
97
+ const r = await temple.remove(id, auth);
98
+ return r.ok ? `deleted craft ${id}` : `error: ${r.error}`;
135
99
  }
136
100
  // Exposed for tests (pure helpers that don't touch the network).
137
- export const _internal = { craftBase, viewUrlOf, resolveScopes };
101
+ export const _internal = { resolveScopes };
@@ -0,0 +1,230 @@
1
+ // Temple — the ONE artifact surface every Operator surface publishes to (CLI, headless, ACP/IDE, the craft MCP server,
2
+ // web/mobile through the shared engine). Hosted on the fleet behind the one door: `${TEMPLE_BASE}/mcp` (JSON-RPC
3
+ // tools/call on temple_publish | temple_update | temple_read | temple_list | temple_delete). Contract:
4
+ // _ai-docs/architecture/2026-11-23-artifacts-on-temple.md.
5
+ //
6
+ // Auth is the signed-in Operator identity (an `op_` token Temple verifies at AuthGate), never a fleet key: an artifact
7
+ // belongs to the person who made it. Resolution, first wins: a per-request bearer (the craft MCP server hands the
8
+ // caller's own), the engine's process identity (setOperatorToken at boot; browser/JSCore hosts inject it), the env.
9
+ // Loaded lazily by its callers (nodeImport) — the neutral engine bundle never pulls node:fs through this file.
10
+ import { getOperatorToken } from "../engine/aurora.js";
11
+ const nodeImport = (m) => import(m);
12
+ const str = (v, fallback = "") => (v === undefined || v === null ? fallback : String(v));
13
+ /** The artifact kinds Temple stores. Everything an Operator surface makes maps onto one of these. */
14
+ export const TEMPLE_KINDS = ["page", "deck", "doc", "board", "dashboard", "app", "image", "video"];
15
+ // A web page cannot call api.0perator.co cross-origin, so the web host points this at its same-origin proxy.
16
+ let _base;
17
+ export function setTempleBase(url) { _base = url || undefined; }
18
+ export function templeBase() {
19
+ return (_base || process.env.KODE_TEMPLE_URL || "https://api.0perator.co/v1/temple").replace(/\/+$/, "");
20
+ }
21
+ /** Where a person opens an artifact: the product's own share link, never the API host. */
22
+ export function shareUrl(id) {
23
+ return `${(process.env.KODE_TEMPLE_SHARE_BASE || "https://0perator.co").replace(/\/+$/, "")}/c/${encodeURIComponent(id)}`;
24
+ }
25
+ function bearerOf(auth) {
26
+ return auth?.bearer || getOperatorToken() || process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN || undefined;
27
+ }
28
+ /** One MCP tools/call against Temple. Never throws; the bearer is never logged or echoed. */
29
+ export async function templeCall(tool, args, opts = {}) {
30
+ const token = bearerOf(opts.auth);
31
+ if (!token)
32
+ return { ok: false, error: "not signed in — artifacts need an Operator account (run `operator auth login`)" };
33
+ const ctrl = new AbortController();
34
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 60_000);
35
+ try {
36
+ const res = await (opts.fetchImpl ?? fetch)(`${templeBase()}/mcp`, {
37
+ method: "POST", signal: ctrl.signal,
38
+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", "User-Agent": "operator/kode-tsi", Authorization: `Bearer ${token}` },
39
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } }),
40
+ });
41
+ if (!res.ok)
42
+ return { ok: false, error: `the artifact surface returned ${res.status}${res.status === 401 || res.status === 403 ? " — sign in again (`operator auth login`)" : ""}` };
43
+ const raw = await res.text();
44
+ const body = raw.startsWith("event:") || raw.startsWith("data:") ? raw.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5)).join("") : raw;
45
+ const rpc = JSON.parse(body);
46
+ if (rpc.error)
47
+ return { ok: false, error: rpc.error.message ?? "the artifact surface refused the call" };
48
+ const text = (rpc.result?.content ?? []).map((c) => c.text ?? "").join("");
49
+ let value;
50
+ try {
51
+ value = JSON.parse(text);
52
+ }
53
+ catch {
54
+ value = text;
55
+ }
56
+ const err = value?.error;
57
+ if (rpc.result?.isError || err) {
58
+ const msg = err?.message ?? (typeof value === "string" ? value : "the artifact surface refused the call");
59
+ return { ok: false, error: err?.code === "unauthorized" ? `${msg} — sign in again (\`operator auth login\`)` : msg };
60
+ }
61
+ return { ok: true, value: value };
62
+ }
63
+ catch (e) {
64
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
65
+ return { ok: false, error: `could not reach the artifact surface (${msg})` };
66
+ }
67
+ finally {
68
+ clearTimeout(timer);
69
+ }
70
+ }
71
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
72
+ const shell = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title>` +
73
+ `<style>body{font:16px/1.6 system-ui,-apple-system,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;color:#1d1d1f}` +
74
+ `pre{background:#f5f5f7;padding:.8rem;overflow:auto;border-radius:6px}code{font-family:ui-monospace,Menlo,monospace}` +
75
+ `img,video{max-width:100%}@media(prefers-color-scheme:dark){body{background:#111;color:#eee}pre{background:#222}}</style></head><body>${body}</body></html>`;
76
+ /** A small, dependency-free markdown → HTML for doc artifacts: headings, paragraphs, lists, fenced code, inline code,
77
+ * bold/italic, links, images, blockquotes, rules. Every text run is escaped first. */
78
+ export function markdownToHtml(md) {
79
+ const inline = (s) => esc(s)
80
+ .replace(/`([^`]+)`/g, "<code>$1</code>")
81
+ .replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, '<img alt="$1" src="$2">')
82
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2">$1</a>')
83
+ .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
84
+ .replace(/(^|[^*])\*([^*]+)\*/g, "$1<em>$2</em>");
85
+ const out = [];
86
+ const lines = md.replace(/\r\n?/g, "\n").split("\n");
87
+ let i = 0;
88
+ while (i < lines.length) {
89
+ const line = lines[i];
90
+ if (/^```/.test(line)) {
91
+ const code = [];
92
+ for (i++; i < lines.length && !/^```/.test(lines[i]); i++)
93
+ code.push(lines[i]);
94
+ i++;
95
+ out.push(`<pre><code>${esc(code.join("\n"))}</code></pre>`);
96
+ }
97
+ else if (/^#{1,6}\s/.test(line)) {
98
+ const n = line.match(/^#+/)[0].length;
99
+ out.push(`<h${n}>${inline(line.slice(n).trim())}</h${n}>`);
100
+ i++;
101
+ }
102
+ else if (/^(\s*[-*+]\s|\s*\d+\.\s)/.test(line)) {
103
+ const ordered = /^\s*\d+\.\s/.test(line);
104
+ const items = [];
105
+ while (i < lines.length && /^(\s*[-*+]\s|\s*\d+\.\s)/.test(lines[i]))
106
+ items.push(`<li>${inline(lines[i++].replace(/^\s*([-*+]|\d+\.)\s/, ""))}</li>`);
107
+ out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`);
108
+ }
109
+ else if (/^>\s?/.test(line)) {
110
+ const q = [];
111
+ while (i < lines.length && /^>\s?/.test(lines[i]))
112
+ q.push(lines[i++].replace(/^>\s?/, ""));
113
+ out.push(`<blockquote>${inline(q.join(" "))}</blockquote>`);
114
+ }
115
+ else if (/^(-{3,}|\*{3,})\s*$/.test(line)) {
116
+ out.push("<hr>");
117
+ i++;
118
+ }
119
+ else if (line.trim() === "") {
120
+ i++;
121
+ }
122
+ else {
123
+ const p = [];
124
+ while (i < lines.length && lines[i].trim() !== "" && !/^(```|#{1,6}\s|\s*[-*+]\s|\s*\d+\.\s|>)/.test(lines[i]))
125
+ p.push(lines[i++]);
126
+ out.push(`<p>${inline(p.join(" "))}</p>`);
127
+ }
128
+ }
129
+ return out.join("\n");
130
+ }
131
+ const MEDIA = {
132
+ png: { kind: "image", mime: "image/png" }, jpg: { kind: "image", mime: "image/jpeg" }, jpeg: { kind: "image", mime: "image/jpeg" },
133
+ gif: { kind: "image", mime: "image/gif" }, webp: { kind: "image", mime: "image/webp" }, svg: { kind: "image", mime: "image/svg+xml" },
134
+ mp4: { kind: "video", mime: "video/mp4" }, webm: { kind: "video", mime: "video/webm" }, mov: { kind: "video", mime: "video/quicktime" },
135
+ };
136
+ /** The kind an artifact is stored as. Accepts Temple's kinds and the words surfaces already use. */
137
+ export function kindOf(type, fallback = "page") {
138
+ const t = type.toLowerCase();
139
+ if (TEMPLE_KINDS.includes(t))
140
+ return t;
141
+ if (t === "markdown" || t === "text" || t === "document")
142
+ return "doc";
143
+ if (t === "slides" || t === "presentation")
144
+ return "deck";
145
+ if (t === "canvas" || t === "html" || t === "svg" || t === "css")
146
+ return t === "canvas" ? "app" : "page";
147
+ return fallback;
148
+ }
149
+ /** Build Temple's `files` map (index.html always present) and the kind from what a surface has. */
150
+ export async function filesFor(input) {
151
+ const files = {};
152
+ const ct = str(input.content_type).toLowerCase();
153
+ let kind = kindOf(str(input.kind) || ct || "page");
154
+ const media = [];
155
+ if (input.paths?.length) {
156
+ const { readFile } = (await nodeImport("node:fs/promises"));
157
+ const { basename } = (await nodeImport("node:path"));
158
+ for (const p of input.paths) {
159
+ let data;
160
+ try {
161
+ data = await readFile(p);
162
+ }
163
+ catch (e) {
164
+ return { error: `cannot read ${p}: ${e.message}` };
165
+ }
166
+ const name = basename(p).replace(/[^\w.-]+/g, "_");
167
+ if (name === "index.html")
168
+ return { error: "a path named index.html collides with the generated entry page — pass its HTML as `content` instead" };
169
+ files[name] = { content_base64: data.toString("base64") };
170
+ const m = MEDIA[name.split(".").pop()?.toLowerCase() ?? ""];
171
+ if (m)
172
+ media.push({ name, ...m });
173
+ }
174
+ }
175
+ const content = str(input.content);
176
+ if (content) {
177
+ if (ct === "markdown" || ct === "text" || (kind === "doc" && !/^\s*</.test(content))) {
178
+ files["index.html"] = { content: shell(input.title, ct === "text" ? `<pre>${esc(content)}</pre>` : markdownToHtml(content)) };
179
+ if (!input.kind)
180
+ kind = "doc";
181
+ }
182
+ else if (ct === "svg" || /^\s*<svg[\s>]/i.test(content)) {
183
+ files["image.svg"] = { content };
184
+ files["index.html"] = { content: shell(input.title, `<img src="image.svg" alt="${esc(input.title)}">`) };
185
+ if (!input.kind)
186
+ kind = "image";
187
+ }
188
+ else {
189
+ files["index.html"] = { content: /<html[\s>]/i.test(content) ? content : shell(input.title, content) };
190
+ }
191
+ }
192
+ else if (media.length) {
193
+ const body = media.map((m) => m.kind === "video" ? `<video src="${m.name}" controls playsinline></video>` : `<img src="${m.name}" alt="${esc(input.title)}">`).join("\n");
194
+ files["index.html"] = { content: shell(input.title, `<h1>${esc(input.title)}</h1>\n${body}`) };
195
+ if (!input.kind)
196
+ kind = media[0].kind;
197
+ }
198
+ else {
199
+ return { error: "an artifact needs `content` (HTML, markdown, SVG or text) or `paths` (images, video, files)" };
200
+ }
201
+ return { files, kind };
202
+ }
203
+ // ── the operations every surface uses ───────────────────────────────────────────────────────────────────────────────
204
+ const line = (a) => `${a.id} · ${a.kind} · ${a.title || "(untitled)"} · ${a.visibility} · v${a.version} · ${shareUrl(a.id)}`;
205
+ export async function publish(input, auth) {
206
+ const built = await filesFor(input);
207
+ if ("error" in built)
208
+ return { ok: false, error: built.error };
209
+ const r = await templeCall("temple_publish", { title: input.title, kind: built.kind, files: built.files, visibility: input.visibility ?? "link" }, { auth });
210
+ return r.ok ? { ok: true, value: { ...r.value, share: shareUrl(r.value.id) } } : r;
211
+ }
212
+ export async function update(id, input, auth) {
213
+ const args = { id, base_version: input.base_version };
214
+ if (input.title)
215
+ args.title = input.title;
216
+ if (input.visibility)
217
+ args.visibility = input.visibility;
218
+ if (input.content || input.paths?.length) {
219
+ const built = await filesFor({ title: input.title ?? "", ...input });
220
+ if ("error" in built)
221
+ return { ok: false, error: built.error };
222
+ args.files = built.files;
223
+ }
224
+ const r = await templeCall("temple_update", args, { auth });
225
+ return r.ok ? { ok: true, value: { ...r.value, share: shareUrl(r.value.id) } } : r;
226
+ }
227
+ export const read = (id, auth) => templeCall("temple_read", { id }, { auth });
228
+ export const list = (limit = 20, auth) => templeCall("temple_list", { limit: Math.min(Math.max(limit, 1), 100) }, { auth });
229
+ export const remove = (id, auth) => templeCall("temple_delete", { id }, { auth });
230
+ export const format = { line };
@@ -1,5 +1,12 @@
1
1
  import { frameKey as deriveFrameKey, pairingId as derivePairingId, encryptFrame, decryptFrame } from "./pairing.js";
2
2
  import { redactSecrets } from "../engine/redact.js";
3
+ let socketCtor = globalThis.WebSocket;
4
+ /** The WebSocket constructor for this runtime: the global one, else `ws`'s (same addEventListener / send / close shape). */
5
+ async function loadSocketCtor() {
6
+ const pkg = "ws"; // a variable, so type-checking and the node-free bundle never resolve it
7
+ socketCtor ??= (await import(pkg)).WebSocket;
8
+ return socketCtor;
9
+ }
3
10
  /** Redact known secret shapes in tool-approval args before they hit the relay / followers. */
4
11
  export function redactApprovalArgs(args) {
5
12
  try {
@@ -114,9 +121,15 @@ export class RemoteHost {
114
121
  openSocket() {
115
122
  this.cb.onState?.("connecting");
116
123
  this.welcomedThisAttempt = false;
124
+ if (!socketCtor) {
125
+ // No global WebSocket (Node 20/21): load `ws` once, then dial. A failed load is reported like a failed dial.
126
+ loadSocketCtor().then(() => { if (!this.closedByUs)
127
+ this.openSocket(); }, (e) => { this.cb.onState?.("error", String(e)); this.rotateUrl(); this.scheduleReconnect(); });
128
+ return;
129
+ }
117
130
  let ws;
118
131
  try {
119
- ws = new WebSocket(this.relayUrl);
132
+ ws = new socketCtor(this.relayUrl);
120
133
  }
121
134
  catch (e) {
122
135
  this.cb.onState?.("error", String(e));
@@ -392,6 +405,20 @@ export class RemoteHost {
392
405
  this.entries.push(e);
393
406
  return e;
394
407
  }
408
+ /** Prime the mirror with what the shell already shows, before connect(): a host started late, or while a turn runs,
409
+ * then snapshots the conversation so far and the turn in flight instead of an empty, idle session (SPEC §5). */
410
+ seed(entries, activity) {
411
+ for (const e of entries) {
412
+ if (e.kind === "message")
413
+ this.upsertMessage(e.message.id, e.message.role, e.message.content, e.message.reasoning);
414
+ else if (e.kind === "tool")
415
+ this.pickTool(e.step);
416
+ else if (e.kind === "toolBatch")
417
+ for (const step of e.steps)
418
+ this.pickTool(step);
419
+ }
420
+ this.activity = activity;
421
+ }
395
422
  // ── public turn-aware emitters (called from cli.tsx sendTurn) ──────────────
396
423
  userPrompt(text) {
397
424
  const e = this.upsertMessage("u" + (++this.turnN) + "_" + Date.now().toString(36), "user", text);
@@ -24,7 +24,7 @@ export function usableCtx(nCtx, marginPct = SERVED_CTX_MARGIN) {
24
24
  function v1(base) {
25
25
  return base.replace(/\/+$/, "") + "/v1";
26
26
  }
27
- /** A stable, human-ish host tag ("192.168.1.103:8097") for ids/labels when a server advertises no alias. */
27
+ /** A stable, human-ish host tag ("192.0.2.10:8097") for ids/labels when a server advertises no alias. */
28
28
  function hostTag(base) {
29
29
  try {
30
30
  const u = new URL(base);
@@ -67,12 +67,29 @@ function nCtxOf(props) {
67
67
  const nCtx = Number(props?.default_generation_settings?.n_ctx ?? props?.n_ctx);
68
68
  return Number.isFinite(nCtx) && nCtx > 0 ? nCtx : null;
69
69
  }
70
- /** The RAW served context window of one base (`GET /props` → n_ctx), or null when it does not answer in time or is
71
- * not a llama.cpp server (a gateway or vendor leg never serves /props). The read probeHost and the session's
72
- * boot-time probe of the primary share; callers apply usableCtx for the engine's number. */
70
+ /** The RAW served context window of one base, or null when nothing answers in time. A llama.cpp server names it on
71
+ * `GET /props` (n_ctx); the fleet router (portal) has no /props but publishes each route's served window as
72
+ * `context_length` on `GET /v1/models/<model>`, so a gateway base is sized by the model it is asked for. The read
73
+ * probeHost and the session's probe of the active endpoint share; callers apply usableCtx for the engine's number. */
73
74
  export async function probeServedCtx(base, opts = {}) {
74
- const props = await getJson(`${base.replace(/\/+$/, "")}/props`, opts.timeoutMs ?? DEFAULTS.timeoutMs, opts.fetchImpl ?? fetch);
75
- return props ? nCtxOf(props) : null;
75
+ return (await probeServed(base, opts)).ctx;
76
+ }
77
+ /** probeServedCtx plus the server's slot count: llama.cpp `/props` `total_slots`, or the router's `total_slots` on
78
+ * `GET /v1/models/<model>`. Null where the endpoint does not say (a router that predates the field, a vendor).
79
+ * `direct` is true only when the base answered `/props` with `total_slots` itself: it IS a llama-server, not a
80
+ * router or gateway in front of one (those serve no `/props`). */
81
+ export async function probeServed(base, opts = {}) {
82
+ const timeoutMs = opts.timeoutMs ?? DEFAULTS.timeoutMs;
83
+ const f = opts.fetchImpl ?? fetch;
84
+ const bare = base.replace(/\/+$/, "");
85
+ const positive = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : null; };
86
+ const props = await getJson(`${bare.replace(/\/v1$/, "")}/props`, timeoutMs, f);
87
+ const nCtx = props ? nCtxOf(props) : null;
88
+ const own = positive(props?.total_slots);
89
+ if (nCtx || !opts.model)
90
+ return { ctx: nCtx, slots: own, direct: own !== null };
91
+ const row = await getJson(`${bare.endsWith("/v1") ? bare : v1(bare)}/models/${encodeURIComponent(opts.model)}`, timeoutMs, f);
92
+ return { ctx: positive(row?.context_length), slots: positive(row?.total_slots), direct: false };
76
93
  }
77
94
  /** Probe one fleet base and build a ModelProfile from what the SERVER reports, or null if it doesn't
78
95
  * answer `/props` in time (→ absent from the picker). `/props` is the source of truth for the context