@agentproto/runtime 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { promises } from 'fs';
1
+ import { promises, readFileSync } from 'fs';
2
2
  import { homedir } from 'os';
3
3
  import { resolve, dirname, isAbsolute } from 'path';
4
4
 
@@ -35,6 +35,26 @@ async function loadWorkspacesConfig(path = DEFAULT_CONFIG_PATH()) {
35
35
  }
36
36
  return normalizeConfig(parsed);
37
37
  }
38
+ function loadWorkspacesConfigSync(path = DEFAULT_CONFIG_PATH()) {
39
+ let raw;
40
+ try {
41
+ raw = readFileSync(path, "utf8");
42
+ } catch (err) {
43
+ if (err.code === "ENOENT") {
44
+ return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] };
45
+ }
46
+ throw err;
47
+ }
48
+ let parsed;
49
+ try {
50
+ parsed = JSON.parse(raw);
51
+ } catch (err) {
52
+ throw new Error(
53
+ `agentproto: ${path} is not valid JSON (${err instanceof Error ? err.message : String(err)}). Delete the file or fix it manually.`
54
+ );
55
+ }
56
+ return normalizeConfig(parsed);
57
+ }
38
58
  async function saveWorkspacesConfig(config, path = DEFAULT_CONFIG_PATH()) {
39
59
  const normalized = normalizeConfig(config);
40
60
  await promises.mkdir(dirname(path), { recursive: true });
@@ -93,6 +113,11 @@ function setActiveWorkspace(config, slug) {
93
113
  function findWorkspace(config, slug) {
94
114
  return config.workspaces.find((w) => w.slug === sanitizeSlug(slug));
95
115
  }
116
+ function findWorkspaceByPath(config, dir) {
117
+ const resolved = resolve(dir);
118
+ const candidates = config.workspaces.filter((w) => resolved.startsWith(resolve(w.path) + "/") || resolved === resolve(w.path)).sort((a, b) => b.path.length - a.path.length);
119
+ return candidates[0];
120
+ }
96
121
  function getActiveWorkspace(config) {
97
122
  if (!config.active) return config.workspaces[0];
98
123
  return findWorkspace(config, config.active) ?? config.workspaces[0];
@@ -131,6 +156,6 @@ function normalizeConfig(parsed) {
131
156
  return out;
132
157
  }
133
158
 
134
- export { DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH, WORKSPACES_CONFIG_VERSION, addWorkspace, findWorkspace, getActiveWorkspace, loadWorkspacesConfig, removeWorkspace, sanitizeSlug, saveWorkspacesConfig, setActiveWorkspace };
159
+ export { DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH, WORKSPACES_CONFIG_VERSION, addWorkspace, findWorkspace, findWorkspaceByPath, getActiveWorkspace, loadWorkspacesConfig, loadWorkspacesConfigSync, removeWorkspace, sanitizeSlug, saveWorkspacesConfig, setActiveWorkspace };
135
160
  //# sourceMappingURL=workspaces-config.mjs.map
136
161
  //# sourceMappingURL=workspaces-config.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workspaces-config.ts"],"names":["fs"],"mappings":";;;;;;;;;AA0BO,IAAM,yBAAA,GAA4B;AA8BlC,IAAM,kBAAA,GAAqB,MAChC,OAAA,CAAQ,OAAA,IAAW,aAAa;AAC3B,IAAM,mBAAA,GAAsB,MACjC,OAAA,CAAQ,kBAAA,IAAsB,iBAAiB;AAK1C,SAAS,aAAa,KAAA,EAAuB;AAClD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AACzC,EAAA,MAAM,OAAA,GAAU,OAAA,CACb,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA,CAC5B,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAGd,EAAA,OAAO,OAAA,IAAW,WAAA;AACpB;AAKA,eAAsB,oBAAA,CACpB,IAAA,GAAe,mBAAA,EAAoB,EACR;AAC3B,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAMA,QAAA,CAAG,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACtC,SAAS,GAAA,EAAK;AACZ,IAAA,IA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AA4B;AAC9C,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY,KAAA,CAAM,GAAA,CAAI,CAAA,CAAE,MAAM,CAAC,CAAA;AAC/C,EAAA,MAAM,SAAA,GAAY,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA;AAC3C,EAAA,MAAM,SACJ,OAAO,GAAA,CAAI,MAAA,KAAW,QAAA,IAAY,UAAU,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,IAAA,KAAS,IAAI,MAAM,CAAA,GACtE,IAAI,MAAA,GACL,SAAA,CAAU,CAAC,CAAA,EAAG,IAAA;AACpB,EAAA,MAAM,GAAA,GAAwB;AAAA,IAC5B,OAAA,EAAS,yBAAA;AAAA,IACT,UAAA,EAAY;AAAA,GACd;AACA,EAAA,IAAI,MAAA,KAAW,MAAA,EAAW,GAAA,CAAI,MAAA,GAAS,MAAA;AACvC,EAAA,OAAO,GAAA;AACT","file":"workspaces-config.mjs","sourcesContent":["/**\n * `~/.agentproto/workspaces.json` — single source of truth for the\n * local agentproto control plane. Tracks which directories the user\n * has opted into as agentproto workspaces, plus which one is \"active\"\n * (the daemon's default working set when no workspace is named in\n * a tool call).\n *\n * Why a config file instead of recreating an MCP entry per workspace:\n * - One daemon = one MCP entry in the user's IDE (clean to read in\n * `claude mcp list`, no `dapper_willow` / `noble_lantern` spam).\n * - The daemon walks `workspaces[]` at boot and exposes them all;\n * tools that need a target take an optional `workspace` arg and\n * fall back to `active` when omitted.\n * - The CLI (`agentproto workspace add/list/remove/use`), the daemon,\n * and the guilde-web onboarding dialog all read+write the same\n * file, so changes from one surface are immediately visible to\n * the others.\n *\n * File layout is intentionally boring (small, hand-editable JSON) —\n * future fields go on top, never break v1 readers.\n */\n\nimport { promises as fs } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, isAbsolute, resolve } from \"node:path\"\n\nexport const WORKSPACES_CONFIG_VERSION = 1 as const\n\nexport interface WorkspaceEntry {\n /** Stable handle — what tools accept as `workspace`. Lowercase\n * ASCII, hyphen-only. The CLI sanitises arbitrary names down to\n * this shape so paste-from-finder Just Works. */\n slug: string\n /** Absolute filesystem path. Required absolute so the daemon can\n * serve the workspace regardless of its own cwd. */\n path: string\n /** ISO-8601 — first time the entry was added. Pure metadata, no\n * behavioural impact. */\n addedAt: string\n /** Last time the entry was touched (renamed, path edited, used as\n * active). Lets the CLI sort by recency without an N+1 stat. */\n updatedAt: string\n /** Free-text label the user can attach so workspaces with similar\n * slugs stay distinguishable in `agentproto workspace list`. */\n label?: string\n}\n\nexport interface WorkspacesConfig {\n version: typeof WORKSPACES_CONFIG_VERSION\n /** Active workspace slug — daemon defaults to this when no\n * `workspace` arg is passed. May be undefined when no workspaces\n * are registered yet. */\n active?: string\n workspaces: WorkspaceEntry[]\n}\n\nexport const DEFAULT_CONFIG_DIR = (): string =>\n resolve(homedir(), \".agentproto\")\nexport const DEFAULT_CONFIG_PATH = (): string =>\n resolve(DEFAULT_CONFIG_DIR(), \"workspaces.json\")\n\n/** Reduce arbitrary user input to a safe slug. Aligns with what most\n * tooling validates against (`/^[a-z0-9][a-z0-9-]{0,63}$/`) so the\n * daemon never has to encode it for URLs or filesystem paths. */\nexport function sanitizeSlug(input: string): string {\n const trimmed = input.trim().toLowerCase()\n const cleaned = trimmed\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64)\n // Edge case: input was entirely non-conforming — fall back to a\n // generic so we never return an empty string.\n return cleaned || \"workspace\"\n}\n\n/** Read the config from disk. Returns an empty config (no workspaces,\n * no active) when the file is missing — this is the legitimate\n * first-boot state, not an error. */\nexport async function loadWorkspacesConfig(\n path: string = DEFAULT_CONFIG_PATH()\n): Promise<WorkspacesConfig> {\n let raw: string\n try {\n raw = await fs.readFile(path, \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] }\n }\n throw err\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n throw new Error(\n `agentproto: ${path} is not valid JSON (${\n err instanceof Error ? err.message : String(err)\n }). Delete the file or fix it manually.`\n )\n }\n return normalizeConfig(parsed)\n}\n\n/** Write the config back. Creates the parent directory if missing.\n * Atomic-ish: writes to a temp file first, then renames over the\n * target — avoids the partial-write window where a concurrent reader\n * sees half a JSON object. */\nexport async function saveWorkspacesConfig(\n config: WorkspacesConfig,\n path: string = DEFAULT_CONFIG_PATH()\n): Promise<void> {\n const normalized = normalizeConfig(config)\n await fs.mkdir(dirname(path), { recursive: true })\n const tmp = `${path}.tmp.${process.pid}`\n await fs.writeFile(tmp, JSON.stringify(normalized, null, 2) + \"\\n\", \"utf8\")\n await fs.rename(tmp, path)\n}\n\n/**\n * Pure helpers — caller manages persistence. Returns a NEW config\n * (never mutates) so callers can compose multiple updates before\n * a single save.\n */\nexport function addWorkspace(\n config: WorkspacesConfig,\n input: { slug: string; path: string; label?: string }\n): WorkspacesConfig {\n if (!isAbsolute(input.path)) {\n throw new Error(\n `addWorkspace: path must be absolute, got \"${input.path}\".`\n )\n }\n const slug = sanitizeSlug(input.slug)\n const now = new Date().toISOString()\n const existingIdx = config.workspaces.findIndex(w => w.slug === slug)\n const next: WorkspaceEntry = existingIdx >= 0\n ? {\n ...config.workspaces[existingIdx]!,\n path: input.path,\n ...(input.label !== undefined ? { label: input.label } : {}),\n updatedAt: now,\n }\n : {\n slug,\n path: input.path,\n ...(input.label ? { label: input.label } : {}),\n addedAt: now,\n updatedAt: now,\n }\n const workspaces = [...config.workspaces]\n if (existingIdx >= 0) workspaces[existingIdx] = next\n else workspaces.push(next)\n // First-add becomes active automatically — saves the user a\n // separate `workspace use` call right after a fresh `add`.\n const active = config.active ?? slug\n return { ...config, workspaces, active }\n}\n\nexport function removeWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspacesConfig {\n const sanitised = sanitizeSlug(slug)\n const workspaces = config.workspaces.filter(w => w.slug !== sanitised)\n // If the removed workspace was active, hand off to whatever's\n // first — predictable and avoids leaving the daemon in an\n // unreachable state when the user removes the only one.\n let active = config.active\n if (active === sanitised) {\n active = workspaces[0]?.slug\n }\n const next: WorkspacesConfig = { ...config, workspaces }\n if (active !== undefined) next.active = active\n else delete next.active\n return next\n}\n\nexport function setActiveWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspacesConfig {\n const sanitised = sanitizeSlug(slug)\n if (!config.workspaces.some(w => w.slug === sanitised)) {\n throw new Error(\n `setActiveWorkspace: no workspace registered with slug \"${sanitised}\". ` +\n `Run \\`agentproto workspace add <path> --slug ${sanitised}\\` first.`\n )\n }\n return { ...config, active: sanitised }\n}\n\nexport function findWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspaceEntry | undefined {\n return config.workspaces.find(w => w.slug === sanitizeSlug(slug))\n}\n\n/** The active workspace, or undefined when none is registered. Pure\n * convenience to avoid re-implementing the lookup at every caller. */\nexport function getActiveWorkspace(\n config: WorkspacesConfig\n): WorkspaceEntry | undefined {\n if (!config.active) return config.workspaces[0]\n return findWorkspace(config, config.active) ?? config.workspaces[0]\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid config. Skips entries\n * with missing required fields rather than throwing — partial recovery\n * is friendlier than \"your config file is corrupted, here's a stack\n * trace\". Logs nothing here; the CLI shells that consume this should\n * decide whether to surface a warning.\n */\nfunction normalizeConfig(parsed: unknown): WorkspacesConfig {\n if (!parsed || typeof parsed !== \"object\") {\n return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] }\n }\n const obj = parsed as Record<string, unknown>\n const workspaces: WorkspaceEntry[] = []\n if (Array.isArray(obj.workspaces)) {\n for (const entry of obj.workspaces) {\n if (!entry || typeof entry !== \"object\") continue\n const e = entry as Record<string, unknown>\n const slug = typeof e.slug === \"string\" ? sanitizeSlug(e.slug) : \"\"\n const path = typeof e.path === \"string\" ? e.path : \"\"\n if (!slug || !path) continue\n const addedAt =\n typeof e.addedAt === \"string\" ? e.addedAt : new Date().toISOString()\n const updatedAt = typeof e.updatedAt === \"string\" ? e.updatedAt : addedAt\n const we: WorkspaceEntry = { slug, path, addedAt, updatedAt }\n if (typeof e.label === \"string\" && e.label.trim()) {\n we.label = e.label.trim()\n }\n workspaces.push(we)\n }\n }\n // De-dupe by slug (last wins) — the file is hand-editable so a\n // typo could have produced two entries with the same slug.\n const dedup = new Map<string, WorkspaceEntry>()\n for (const w of workspaces) dedup.set(w.slug, w)\n const finalList = Array.from(dedup.values())\n const active =\n typeof obj.active === \"string\" && finalList.some(w => w.slug === obj.active)\n ? (obj.active as string)\n : finalList[0]?.slug\n const out: WorkspacesConfig = {\n version: WORKSPACES_CONFIG_VERSION,\n workspaces: finalList,\n }\n if (active !== undefined) out.active = active\n return out\n}\n"]}
1
+ {"version":3,"sources":["../src/workspaces-config.ts"],"names":["fs"],"mappings":";;;;;;;;;AA0BO,IAAM,yBAAA,GAA4B;AA8BlC,IAAM,kBAAA,GAAqB,MAChC,OAAA,CAAQ,OAAA,IAAW,aAAa;AAC3B,IAAM,mBAAA,GAAsB,MACjC,OAAA,CAAQ,kBAAA,IAAsB,iBAAiB;AAK1C,SAAS,aAAa,KAAA,EAAuB;AAClD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AACzC,EAAA,MAAM,OAAA,GAAU,OAAA,CACb,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA,CAC5B,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAGd,EAAA,OAAO,OAAA,IAAW,WAAA;AACpB;AAKA,eAAsB,oBAAA,CACpB,IAAA,GAAe,mBAAA,EAAoB,EACR;AAC3B,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAMA,QAAA,CAAG,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACtC,SAAS,G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A,KAAA,MAAW,KAAK,UAAA,EAAY,KAAA,CAAM,GAAA,CAAI,CAAA,CAAE,MAAM,CAAC,CAAA;AAC/C,EAAA,MAAM,SAAA,GAAY,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA;AAC3C,EAAA,MAAM,SACJ,OAAO,GAAA,CAAI,MAAA,KAAW,QAAA,IAAY,UAAU,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,IAAA,KAAS,IAAI,MAAM,CAAA,GACtE,IAAI,MAAA,GACL,SAAA,CAAU,CAAC,CAAA,EAAG,IAAA;AACpB,EAAA,MAAM,GAAA,GAAwB;AAAA,IAC5B,OAAA,EAAS,yBAAA;AAAA,IACT,UAAA,EAAY;AAAA,GACd;AACA,EAAA,IAAI,MAAA,KAAW,MAAA,EAAW,GAAA,CAAI,MAAA,GAAS,MAAA;AACvC,EAAA,OAAO,GAAA;AACT","file":"workspaces-config.mjs","sourcesContent":["/**\n * `~/.agentproto/workspaces.json` — single source of truth for the\n * local agentproto control plane. Tracks which directories the user\n * has opted into as agentproto workspaces, plus which one is \"active\"\n * (the daemon's default working set when no workspace is named in\n * a tool call).\n *\n * Why a config file instead of recreating an MCP entry per workspace:\n * - One daemon = one MCP entry in the user's IDE (clean to read in\n * `claude mcp list`, no `dapper_willow` / `noble_lantern` spam).\n * - The daemon walks `workspaces[]` at boot and exposes them all;\n * tools that need a target take an optional `workspace` arg and\n * fall back to `active` when omitted.\n * - The CLI (`agentproto workspace add/list/remove/use`), the daemon,\n * and the guilde-web onboarding dialog all read+write the same\n * file, so changes from one surface are immediately visible to\n * the others.\n *\n * File layout is intentionally boring (small, hand-editable JSON) —\n * future fields go on top, never break v1 readers.\n */\n\nimport { promises as fs, readFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, isAbsolute, resolve } from \"node:path\"\n\nexport const WORKSPACES_CONFIG_VERSION = 1 as const\n\nexport interface WorkspaceEntry {\n /** Stable handle — what tools accept as `workspace`. Lowercase\n * ASCII, hyphen-only. The CLI sanitises arbitrary names down to\n * this shape so paste-from-finder Just Works. */\n slug: string\n /** Absolute filesystem path. Required absolute so the daemon can\n * serve the workspace regardless of its own cwd. */\n path: string\n /** ISO-8601 — first time the entry was added. Pure metadata, no\n * behavioural impact. */\n addedAt: string\n /** Last time the entry was touched (renamed, path edited, used as\n * active). Lets the CLI sort by recency without an N+1 stat. */\n updatedAt: string\n /** Free-text label the user can attach so workspaces with similar\n * slugs stay distinguishable in `agentproto workspace list`. */\n label?: string\n}\n\nexport interface WorkspacesConfig {\n version: typeof WORKSPACES_CONFIG_VERSION\n /** Active workspace slug — daemon defaults to this when no\n * `workspace` arg is passed. May be undefined when no workspaces\n * are registered yet. */\n active?: string\n workspaces: WorkspaceEntry[]\n}\n\nexport const DEFAULT_CONFIG_DIR = (): string =>\n resolve(homedir(), \".agentproto\")\nexport const DEFAULT_CONFIG_PATH = (): string =>\n resolve(DEFAULT_CONFIG_DIR(), \"workspaces.json\")\n\n/** Reduce arbitrary user input to a safe slug. Aligns with what most\n * tooling validates against (`/^[a-z0-9][a-z0-9-]{0,63}$/`) so the\n * daemon never has to encode it for URLs or filesystem paths. */\nexport function sanitizeSlug(input: string): string {\n const trimmed = input.trim().toLowerCase()\n const cleaned = trimmed\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64)\n // Edge case: input was entirely non-conforming — fall back to a\n // generic so we never return an empty string.\n return cleaned || \"workspace\"\n}\n\n/** Read the config from disk. Returns an empty config (no workspaces,\n * no active) when the file is missing — this is the legitimate\n * first-boot state, not an error. */\nexport async function loadWorkspacesConfig(\n path: string = DEFAULT_CONFIG_PATH()\n): Promise<WorkspacesConfig> {\n let raw: string\n try {\n raw = await fs.readFile(path, \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] }\n }\n throw err\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n throw new Error(\n `agentproto: ${path} is not valid JSON (${\n err instanceof Error ? err.message : String(err)\n }). Delete the file or fix it manually.`\n )\n }\n return normalizeConfig(parsed)\n}\n\n/** Sync twin of `loadWorkspacesConfig`, sharing its normalisation (and\n * therefore its slug sanitisation) exactly.\n *\n * Exists because bucket resolution runs on paths that cannot await: the\n * sessions registry loads its history synchronously at construction so\n * the dashboard has rows immediately, and flushes synchronously on\n * `process.on(\"exit\")` where Node won't await. Both need to know which\n * slugs are registered. The file is <1KB, so the sync read is cheaper\n * than the machinery to avoid it. */\nexport function loadWorkspacesConfigSync(\n path: string = DEFAULT_CONFIG_PATH()\n): WorkspacesConfig {\n let raw: string\n try {\n raw = readFileSync(path, \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] }\n }\n throw err\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n throw new Error(\n `agentproto: ${path} is not valid JSON (${\n err instanceof Error ? err.message : String(err)\n }). Delete the file or fix it manually.`\n )\n }\n return normalizeConfig(parsed)\n}\n\n/** Write the config back. Creates the parent directory if missing.\n * Atomic-ish: writes to a temp file first, then renames over the\n * target — avoids the partial-write window where a concurrent reader\n * sees half a JSON object. */\nexport async function saveWorkspacesConfig(\n config: WorkspacesConfig,\n path: string = DEFAULT_CONFIG_PATH()\n): Promise<void> {\n const normalized = normalizeConfig(config)\n await fs.mkdir(dirname(path), { recursive: true })\n const tmp = `${path}.tmp.${process.pid}`\n await fs.writeFile(tmp, JSON.stringify(normalized, null, 2) + \"\\n\", \"utf8\")\n await fs.rename(tmp, path)\n}\n\n/**\n * Pure helpers — caller manages persistence. Returns a NEW config\n * (never mutates) so callers can compose multiple updates before\n * a single save.\n */\nexport function addWorkspace(\n config: WorkspacesConfig,\n input: { slug: string; path: string; label?: string }\n): WorkspacesConfig {\n if (!isAbsolute(input.path)) {\n throw new Error(\n `addWorkspace: path must be absolute, got \"${input.path}\".`\n )\n }\n const slug = sanitizeSlug(input.slug)\n const now = new Date().toISOString()\n const existingIdx = config.workspaces.findIndex(w => w.slug === slug)\n const next: WorkspaceEntry = existingIdx >= 0\n ? {\n ...config.workspaces[existingIdx]!,\n path: input.path,\n ...(input.label !== undefined ? { label: input.label } : {}),\n updatedAt: now,\n }\n : {\n slug,\n path: input.path,\n ...(input.label ? { label: input.label } : {}),\n addedAt: now,\n updatedAt: now,\n }\n const workspaces = [...config.workspaces]\n if (existingIdx >= 0) workspaces[existingIdx] = next\n else workspaces.push(next)\n // First-add becomes active automatically — saves the user a\n // separate `workspace use` call right after a fresh `add`.\n const active = config.active ?? slug\n return { ...config, workspaces, active }\n}\n\nexport function removeWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspacesConfig {\n const sanitised = sanitizeSlug(slug)\n const workspaces = config.workspaces.filter(w => w.slug !== sanitised)\n // If the removed workspace was active, hand off to whatever's\n // first — predictable and avoids leaving the daemon in an\n // unreachable state when the user removes the only one.\n let active = config.active\n if (active === sanitised) {\n active = workspaces[0]?.slug\n }\n const next: WorkspacesConfig = { ...config, workspaces }\n if (active !== undefined) next.active = active\n else delete next.active\n return next\n}\n\nexport function setActiveWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspacesConfig {\n const sanitised = sanitizeSlug(slug)\n if (!config.workspaces.some(w => w.slug === sanitised)) {\n throw new Error(\n `setActiveWorkspace: no workspace registered with slug \"${sanitised}\". ` +\n `Run \\`agentproto workspace add <path> --slug ${sanitised}\\` first.`\n )\n }\n return { ...config, active: sanitised }\n}\n\nexport function findWorkspace(\n config: WorkspacesConfig,\n slug: string\n): WorkspaceEntry | undefined {\n return config.workspaces.find(w => w.slug === sanitizeSlug(slug))\n}\n\n/** Find a workspace whose path is an ancestor of (or equal to) the\n * given directory. Returns the most specific match (longest path)\n * when multiple workspaces nest under the same root. */\nexport function findWorkspaceByPath(\n config: WorkspacesConfig,\n dir: string\n): WorkspaceEntry | undefined {\n const resolved = resolve(dir)\n const candidates = config.workspaces\n .filter(w => resolved.startsWith(resolve(w.path) + \"/\") || resolved === resolve(w.path))\n .sort((a, b) => b.path.length - a.path.length)\n return candidates[0]\n}\n\n/** The active workspace, or undefined when none is registered. Pure\n * convenience to avoid re-implementing the lookup at every caller. */\nexport function getActiveWorkspace(\n config: WorkspacesConfig\n): WorkspaceEntry | undefined {\n if (!config.active) return config.workspaces[0]\n return findWorkspace(config, config.active) ?? config.workspaces[0]\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid config. Skips entries\n * with missing required fields rather than throwing — partial recovery\n * is friendlier than \"your config file is corrupted, here's a stack\n * trace\". Logs nothing here; the CLI shells that consume this should\n * decide whether to surface a warning.\n */\nfunction normalizeConfig(parsed: unknown): WorkspacesConfig {\n if (!parsed || typeof parsed !== \"object\") {\n return { version: WORKSPACES_CONFIG_VERSION, workspaces: [] }\n }\n const obj = parsed as Record<string, unknown>\n const workspaces: WorkspaceEntry[] = []\n if (Array.isArray(obj.workspaces)) {\n for (const entry of obj.workspaces) {\n if (!entry || typeof entry !== \"object\") continue\n const e = entry as Record<string, unknown>\n const slug = typeof e.slug === \"string\" ? sanitizeSlug(e.slug) : \"\"\n const path = typeof e.path === \"string\" ? e.path : \"\"\n if (!slug || !path) continue\n const addedAt =\n typeof e.addedAt === \"string\" ? e.addedAt : new Date().toISOString()\n const updatedAt = typeof e.updatedAt === \"string\" ? e.updatedAt : addedAt\n const we: WorkspaceEntry = { slug, path, addedAt, updatedAt }\n if (typeof e.label === \"string\" && e.label.trim()) {\n we.label = e.label.trim()\n }\n workspaces.push(we)\n }\n }\n // De-dupe by slug (last wins) — the file is hand-editable so a\n // typo could have produced two entries with the same slug.\n const dedup = new Map<string, WorkspaceEntry>()\n for (const w of workspaces) dedup.set(w.slug, w)\n const finalList = Array.from(dedup.values())\n const active =\n typeof obj.active === \"string\" && finalList.some(w => w.slug === obj.active)\n ? (obj.active as string)\n : finalList[0]?.slug\n const out: WorkspacesConfig = {\n version: WORKSPACES_CONFIG_VERSION,\n workspaces: finalList,\n }\n if (active !== undefined) out.active = active\n return out\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/runtime",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "@agentproto/runtime — long-running gateway that turns an agentproto workspace into a live runtime. Composes @agentproto/mcp-server (CRUD verbs) with HTTP transport, HEARTBEAT.md autonomy loop, and append-only conversation persistence. Drop a workspace dir, point your MCP client at it, and the agent ticks on its own.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -19,7 +19,7 @@
19
19
  "bugs": {
20
20
  "url": "https://github.com/agentproto/ts/issues"
21
21
  },
22
- "license": "MIT",
22
+ "license": "Apache-2.0",
23
23
  "type": "module",
24
24
  "main": "dist/index.mjs",
25
25
  "module": "dist/index.mjs",
@@ -70,6 +70,11 @@
70
70
  "types": "./dist/resume-strategies.d.ts",
71
71
  "import": "./dist/resume-strategies.mjs",
72
72
  "default": "./dist/resume-strategies.mjs"
73
+ },
74
+ "./session-story": {
75
+ "types": "./dist/session-story.d.ts",
76
+ "import": "./dist/session-story.mjs",
77
+ "default": "./dist/session-story.mjs"
73
78
  }
74
79
  },
75
80
  "files": [
@@ -86,23 +91,25 @@
86
91
  "gray-matter": "^4.0.3",
87
92
  "ws": "^8.18.0",
88
93
  "zod": "^4.4.3",
89
- "@agentproto/acp": "0.4.0",
90
- "@agentproto/workflow": "0.1.0-alpha.1",
91
- "@agentproto/workflow-loader": "0.1.0-alpha.0",
92
- "@agentproto/workflow-runtime": "0.3.0",
93
- "@agentproto/provider-kit": "0.2.0",
94
- "@agentproto/provider-presets": "0.2.0",
95
- "@agentproto/eval-reporters": "0.2.0",
96
- "@agentproto/agent": "0.2.0",
97
- "@agentproto/manifest": "0.2.0",
98
- "@agentproto/mcp-server": "0.2.1",
99
- "@agentproto/model-catalog": "0.2.0",
100
- "@agentproto/redaction": "0.2.0",
101
- "@agentproto/sandbox": "0.1.0",
102
- "@agentproto/telemetry-langfuse": "0.2.0"
94
+ "@agentproto/acp": "0.5.0",
95
+ "@agentproto/workflow": "0.1.0",
96
+ "@agentproto/workflow-loader": "0.1.0",
97
+ "@agentproto/workflow-runtime": "0.4.0",
98
+ "@agentproto/provider-kit": "0.2.1",
99
+ "@agentproto/provider-presets": "0.3.0",
100
+ "@agentproto/eval-reporters": "0.2.1",
101
+ "@agentproto/agent": "0.2.1",
102
+ "@agentproto/manifest": "0.2.1",
103
+ "@agentproto/mcp-server": "0.2.2",
104
+ "@agentproto/model-catalog": "0.4.0",
105
+ "@agentproto/providers-store": "0.2.1",
106
+ "@agentproto/redaction": "0.2.1",
107
+ "@agentproto/sandbox": "0.1.2",
108
+ "@agentproto/secrets": "0.2.0",
109
+ "@agentproto/telemetry-langfuse": "0.2.1"
103
110
  },
104
111
  "optionalDependencies": {
105
- "@agentproto/sandbox-e2b": "0.1.0"
112
+ "@agentproto/sandbox-e2b": "0.1.2"
106
113
  },
107
114
  "devDependencies": {
108
115
  "@types/node": "^25.6.2",
@@ -110,8 +117,9 @@
110
117
  "tsup": "^8.5.1",
111
118
  "typescript": "^5.9.3",
112
119
  "vitest": "^3.2.4",
113
- "@agentproto/driver": "0.1.2",
114
- "@agentproto/tool": "0.2.0",
120
+ "@agentproto/driver": "0.1.3",
121
+ "@agentproto/rendezvous": "0.2.0",
122
+ "@agentproto/tool": "0.2.1",
115
123
  "@agentproto/tooling": "0.1.0-alpha.0"
116
124
  },
117
125
  "scripts": {
@@ -1,61 +0,0 @@
1
- /**
2
- * Pure resolver for `~/.agentproto/config.json`'s `defaults` block —
3
- * computes the effective `skills` + `options` for an `agent_start` spawn
4
- * before adapter-specific normalization. No fs, no adapter I/O, so it's
5
- * unit-testable in isolation from `session-spawn.ts` (which owns the fs
6
- * read + the adapter-manifest lookup).
7
- *
8
- * Precedence (lowest → highest): global `defaults` < `defaults.adapters.
9
- * <slug>` < the explicit `agent_start` call.
10
- * - `options`: shallow-merged maps, later (higher-precedence) keys win.
11
- * - `skills`: global ∪ per-adapter when the caller didn't pass `skills`
12
- * at all; an explicit `skills` (even `[]`) REPLACES the union rather
13
- * than merging into it — a deliberate exact set, mirroring how an
14
- * explicit `mcpServers: []` opts out of the hermes default in
15
- * `session-spawn.ts`.
16
- */
17
- interface DefaultsAdapterConfig {
18
- skills?: string[];
19
- options?: Record<string, boolean | number | string>;
20
- }
21
- /** Shape of `config.json`'s top-level `defaults` block. */
22
- interface SpawnDefaultsConfig {
23
- skills?: string[];
24
- options?: Record<string, boolean | number | string>;
25
- adapters?: Record<string, DefaultsAdapterConfig>;
26
- /** Depth cutoff for the role-derived default (see `resolveRole` in
27
- * `role.ts`) applied when an `agent_start` call omits `role`:
28
- * `depth < cutoff` → supervisor, `depth >= cutoff` → executor.
29
- * Default 1 (root spawns keep today's unrestricted behaviour; any
30
- * spawn made THROUGH an orchestrator defaults to executor). Tune
31
- * this up (e.g. to a large number) to restore the old permissive
32
- * behaviour for existing deep spawns wholesale. */
33
- defaultRoleDepthCutoff?: number;
34
- /** Trust-boundary cap on pack-carried roles (see `role-registry.ts`'s
35
- * `loadRoleRegistry`): a role pack whose `toolPolicy.delegation` is
36
- * `"allow"` at a level ABOVE this cap has it forced to `"deny"` —
37
- * the pack can still declare the intent, the daemon just refuses to
38
- * grant it. Lets an operator install third-party role packs without
39
- * trusting every one of them to self-grant delegation. Undefined
40
- * (default) ⇒ no cap, any pack-declared level may carry
41
- * `delegation: "allow"` (back-compat: #214 had no such knob). */
42
- maxGrantableDelegation?: number;
43
- /** Default per-session Langfuse tracing opt-in when an `agent_start` call
44
- * omits `trace`. Default false — sessions trace only when they opt in or
45
- * this is on. See `filterSessionObserver` / `SpawnAgentInput.trace`. */
46
- langfuseTracing?: boolean;
47
- /** Redactor slug applied to traced session content before it's sent to
48
- * Langfuse (see `@agentproto/redaction`'s registry). Default "secrets"
49
- * (deny-list by key + value-scan for secret shapes). */
50
- traceRedactor?: string;
51
- }
52
- /** Manifest-declared AIP-45 option id + type, the minimum an adapter
53
- * resolver needs to expose for `normalizeSkillsOption` below. Mirrors
54
- * `AgentCliOption`'s `id`/`type` fields without importing
55
- * `@agentproto/driver-agent-cli` into the runtime package. */
56
- interface DeclaredAdapterOption {
57
- id: string;
58
- type: "boolean" | "integer" | "string" | "enum";
59
- }
60
-
61
- export type { DeclaredAdapterOption as D, SpawnDefaultsConfig as S };