@0perator/operator 0.1.354 → 0.1.355-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.
@@ -0,0 +1,36 @@
1
+ /** The AuthGate per-key scope rule (item 2): a `domain:` atom restricts the key to named products; a key
2
+ * with NO `domain:` atom is unrestricted (every legacy token keeps full access). `domain:*` = all. */
3
+ export function domainInScope(scopes, product) {
4
+ const domains = (scopes ?? []).filter((s) => s.startsWith("domain:")).map((s) => s.slice(7));
5
+ if (domains.length === 0)
6
+ return true; // no domain atom => all domains (backward compatible)
7
+ return domains.includes("*") || domains.includes(product);
8
+ }
9
+ /** Object-level authorization. `actor` is an ACCOUNT id (never a key). The owner can do anything; an editor
10
+ * grant can read+write; a reader grant / an open visibility can read+list. Ownership is the account, so a
11
+ * different key for the SAME account has the same rights, and a key for a different account does not. */
12
+ export function can(actor, action, obj) {
13
+ if (!actor)
14
+ return action === "read" || action === "list" ? obj.visibility === "public" || obj.visibility === "link" : false;
15
+ if (actor === obj.owner)
16
+ return true;
17
+ const role = obj.grants[actor];
18
+ switch (action) {
19
+ case "read":
20
+ case "list":
21
+ if (role === "reader" || role === "editor")
22
+ return true;
23
+ return obj.visibility === "public" || obj.visibility === "link"
24
+ || (obj.visibility === "people" && role !== undefined);
25
+ case "write":
26
+ return role === "editor";
27
+ case "delete":
28
+ case "share":
29
+ return false; // owner-only (handled above)
30
+ default:
31
+ return false;
32
+ }
33
+ }
34
+ /** The one reason string a surface returns when the domain gate denies — mirrors the model_not_in_scope
35
+ * shape so clients can branch on it. */
36
+ export const DOMAIN_DENIED = "domain_not_in_scope";
@@ -0,0 +1,165 @@
1
+ // Shared product rails — the account-scoped, versioned object store every Operator-API product rides
2
+ // (artifacts / craft / mdoc). SPEC: _ai-docs/specs/2026-11-06-operator-api-products-craft-mdoc.md.
3
+ //
4
+ // NODE-SIDE ONLY. This module uses node builtins and is loaded LAZILY from the tool run() bodies
5
+ // (tools/mdoc.ts), never statically from tools/registry.ts — so the platform:neutral engine bundle
6
+ // (test/neutral-graph.test.mts) stays node-free. Tool SCHEMAS live in tools/mdoc.ts; the store runs here.
7
+ //
8
+ // The one contract (spec §): a product is a namespace of OBJECTS under an OWNER ACCOUNT. Each object has
9
+ // immutable, content-addressed VERSIONS + a current pointer, an explicit ACL, and drives a per-account
10
+ // CHANGE FEED. Ownership is an ACCOUNT, never a key (the inverse of the 10/14 compose bug). One guard —
11
+ // can() in scope.ts — backs every surface.
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, readdirSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import { operatorPath } from "../config/home.js";
16
+ // older than this => a lagging client must full-resync (spec §5). Env override exists for tests only.
17
+ const MAX_FEED = Number(process.env.KODE_PRODUCT_FEED_MAX) > 0 ? Number(process.env.KODE_PRODUCT_FEED_MAX) : 5000;
18
+ // A stable, non-reversible per-account directory key. The account id (AuthGate `sub`) is NEVER a path
19
+ // segment — it is hashed, exactly like artifacts' localStore, so a hostile account id cannot traverse.
20
+ function accountKey(account) {
21
+ return createHash("sha256").update("axe-products:" + account).digest("hex").slice(0, 16);
22
+ }
23
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; // object ids: validated, and still never used as a path segment
24
+ function assertId(id) {
25
+ if (!ID_RE.test(id))
26
+ throw new Error(`invalid object id: ${JSON.stringify(id).slice(0, 64)}`);
27
+ }
28
+ function contentHash(s) {
29
+ return createHash("sha256").update(s).digest("hex").slice(0, 16);
30
+ }
31
+ function atomicWrite(path, data) {
32
+ mkdirSync(dirname(path), { recursive: true });
33
+ const tmp = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
34
+ writeFileSync(tmp, data, { mode: 0o600 });
35
+ renameSync(tmp, path);
36
+ }
37
+ function readJson(path) {
38
+ try {
39
+ return JSON.parse(readFileSync(path, "utf8"));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** One product's on-disk store, rooted per account. All object/version/blob files live UNDER the account's
46
+ * hashed dir, so a path is always `<home>/products/<product>/<accountKey>/...` and the account can never
47
+ * reach another account's bytes through this class. */
48
+ export class ProductStore {
49
+ product;
50
+ constructor(product) {
51
+ this.product = product;
52
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(product))
53
+ throw new Error(`invalid product domain: ${product}`);
54
+ }
55
+ accountDir(account) {
56
+ return operatorPath("products", this.product, accountKey(account));
57
+ }
58
+ objPath(account, id) {
59
+ return join(this.accountDir(account), "objects", contentHash(id) + ".json");
60
+ }
61
+ versionPath(account, version) {
62
+ return join(this.accountDir(account), "versions", version + ".txt");
63
+ }
64
+ feedPath(account) {
65
+ return join(this.accountDir(account), "feed.json");
66
+ }
67
+ /** Load an object, with the account-match guard: a record whose owner != the account that owns the dir is
68
+ * refused (a defense-in-depth check on top of the per-account path). Returns null when absent. */
69
+ load(ownerAccount, id) {
70
+ assertId(id);
71
+ const o = readJson(this.objPath(ownerAccount, id));
72
+ if (!o)
73
+ return null;
74
+ if (o.owner !== ownerAccount)
75
+ throw new Error("account mismatch: object owner does not match store account");
76
+ return o;
77
+ }
78
+ /** Read a version's content from the OWNER's version store. */
79
+ content(ownerAccount, version) {
80
+ if (!/^[0-9a-f]{16}$/.test(version))
81
+ throw new Error("invalid version hash");
82
+ try {
83
+ return readFileSync(this.versionPath(ownerAccount, version), "utf8");
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ /** Create-or-update. Optimistic concurrency: `expect` (the version the writer last saw) must match the
90
+ * current version, else the stale write is REFUSED and the live object handed back — never clobbered. */
91
+ put(args) {
92
+ assertId(args.id);
93
+ const now = Date.now();
94
+ const prev = this.load(args.owner, args.id);
95
+ if (prev && args.expect !== undefined && args.expect !== prev.current) {
96
+ const e = new Error("stale write: object changed since you read it");
97
+ e.live = prev;
98
+ throw e;
99
+ }
100
+ const version = contentHash(args.content);
101
+ atomicWrite(this.versionPath(args.owner, version), args.content);
102
+ // Audience of THIS change before we mutate the ACL — so an ACL-narrowing put still notifies the dropped
103
+ // grantees (the #68 revoke-notify fix, done once here for every product).
104
+ const prevGrantees = prev ? Object.keys(prev.grants) : [];
105
+ const nextVis = args.visibility ?? prev?.visibility ?? "private";
106
+ const nextGrants = args.grants ?? prev?.grants ?? {};
107
+ const nextGrantees = Object.keys(nextGrants);
108
+ const dropped = prevGrantees.filter((a) => !nextGrantees.includes(a));
109
+ const obj = {
110
+ id: args.id,
111
+ product: this.product,
112
+ owner: args.owner,
113
+ type: args.type ?? prev?.type,
114
+ visibility: nextVis,
115
+ grants: nextGrants,
116
+ current: version,
117
+ versions: [...(prev?.versions ?? []), { version, ts: now, author: args.author, note: args.note }],
118
+ meta: { ...(prev?.meta ?? {}), ...(args.meta ?? {}) },
119
+ createdAt: prev?.createdAt ?? now,
120
+ updatedAt: now,
121
+ };
122
+ atomicWrite(this.objPath(args.owner, args.id), JSON.stringify(obj, null, 1));
123
+ // Feed: the owner + the CURRENT grantees see the put; the DROPPED grantees see a revoke — so a client
124
+ // that cached this object learns it lost access instead of silently keeping stale content.
125
+ this.appendFeed(args.owner, { kind: "put", id: args.id, version });
126
+ for (const a of nextGrantees)
127
+ this.appendFeed(a, { kind: "put", id: args.id, version });
128
+ for (const a of dropped)
129
+ this.appendFeed(a, { kind: "revoke", id: args.id });
130
+ return { object: obj };
131
+ }
132
+ list(owner) {
133
+ const dir = join(this.accountDir(owner), "objects");
134
+ if (!existsSync(dir))
135
+ return [];
136
+ const out = [];
137
+ for (const f of readdirSync(dir)) {
138
+ const o = readJson(join(dir, f));
139
+ if (o && o.owner === owner)
140
+ out.push(o);
141
+ }
142
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
143
+ }
144
+ appendFeed(account, e) {
145
+ const path = this.feedPath(account);
146
+ const feed = readJson(path) ?? [];
147
+ const seq = (feed.length ? feed[feed.length - 1].seq : 0) + 1;
148
+ feed.push({ seq, ts: Date.now(), product: this.product, ...e });
149
+ while (feed.length > MAX_FEED)
150
+ feed.shift();
151
+ atomicWrite(path, JSON.stringify(feed));
152
+ }
153
+ /** Changes after `cursor` for an account. If the cursor is older than the oldest retained event the client
154
+ * is too far behind to trust an incremental feed (it could have missed a delete/revoke) — it is told to
155
+ * RESYNC rather than silently handed a gap (spec §5). */
156
+ changes(account, cursor = 0) {
157
+ const feed = readJson(this.feedPath(account)) ?? [];
158
+ const oldest = feed.length ? feed[0].seq : 0;
159
+ // A gap exists when the oldest event we still hold is newer than cursor+1 — the client missed everything
160
+ // between its cursor and `oldest` (a trimmed feed), including any delete/revoke, so it must full-resync.
161
+ const resync = oldest > cursor + 1;
162
+ const changes = feed.filter((e) => e.seq > cursor);
163
+ return { changes, resync, cursor: feed.length ? feed[feed.length - 1].seq : cursor };
164
+ }
165
+ }
@@ -139,6 +139,13 @@ export const BUILTIN_MODELS = [
139
139
  // the V1 vendor keys ship, reintroduce a byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
140
140
  { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
141
141
  { id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
142
+ // ── capabilities (0.1.355) ──────────────────────────────────────────────────────────────────────────────
143
+ // A capability is a name the gateway resolves (the portal's aliases and routes), so the owner asks for a KIND of worker and
144
+ // the fleet answers with its best healthy model: the strongest resident one first, parallel delegations spilling down the
145
+ // chain instead of queueing. Swapping or promoting a model moves a pointer on the server and no client changes. Hidden: never
146
+ // a picker row and never offered by tier (profilesByTier skips hidden rows), reached by id (delegate_task, spawn_agent). `ctx`
147
+ // is the smallest window any model in the chain serves, so compaction is safe wherever the request lands.
148
+ { id: "subagent", tier: "power", label: "Sub-agent", box: "fleet", kind: "single", desc: "capability: the default sub-agent — the gateway picks the best healthy model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["subagent", "subagent"], model: "subagent", ctx: 262144, hidden: true },
142
149
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
143
150
  { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — Cortana plans each request into steps and hands them to gpt-oss-20b specialists, checks their work, writes the answer and reads any images (settings.moa overrides)" },
144
151
  ];
package/dist/session.js CHANGED
@@ -26,7 +26,7 @@ import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start
26
26
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
27
27
  import { getByoToken, hasByoToken } from "./auth/byo.js";
28
28
  import { Executor } from "./tools/executor.js";
29
- import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
29
+ import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
30
30
  import { isFeatureEnabled } from "./config/features.js";
31
31
  import { MemoryStore } from "./memory/index.js";
32
32
  import { McpHub, withMcp } from "./mcp/index.js";
@@ -448,6 +448,8 @@ export class Session {
448
448
  // Flag-gated cloud-agent tools (config/features.ts `cloudAgents`): absent from the base registry, merged in
449
449
  // here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
450
450
  const cloudTools = cloudAgentToolsFor({ features: cfg.features });
451
+ const mdocTools = mdocToolsFor({ features: cfg.features }); // flag-gated product tools (feature `mdoc`, default OFF)
452
+ const craftTools = craftToolsFor({ features: cfg.features }); // flag-gated product tools (feature `craft`, default OFF)
451
453
  if (cfg.spawnAgent)
452
454
  reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
453
455
  if (cfg.messageAgent)
@@ -473,6 +475,10 @@ export class Session {
473
475
  })));
474
476
  for (const t of cloudTools)
475
477
  reg.set(t.name, t);
478
+ for (const t of mdocTools)
479
+ reg.set(t.name, t);
480
+ for (const t of craftTools)
481
+ reg.set(t.name, t);
476
482
  if (cfg.toolAllow) {
477
483
  const allow = new Set([...cfg.toolAllow, "self_status"]);
478
484
  for (const name of [...reg.keys()])
@@ -12,6 +12,7 @@ import { listLocalSkills } from "../config/skills-index.js";
12
12
  import { listCatalogue, catalogueDir } from "./catalogue.js";
13
13
  import { OPERATOR_URLS, operatorToken, registry } from "../tools/registry.js";
14
14
  import { operatorTrustedUrl } from "../engine/aurora.js";
15
+ import { PRODUCT_API_HOST } from "../config/product-hosts.js";
15
16
  const words = (q) => q.toLowerCase().split(/\s+/).filter(Boolean);
16
17
  /** Every query word appears in the haystack — the same AND rule session search uses. */
17
18
  const matches = (q, ...hay) => {
@@ -63,7 +64,9 @@ export function toolSource() {
63
64
  },
64
65
  };
65
66
  }
66
- /** The hub bases, in the order they are tried. */
67
+ /** The hub bases, in the order they are tried.
68
+ * An explicit override (env, then the home's skills.json) wins; otherwise the marketplace gateway (api.0perator.co) is
69
+ * tried first, for signed-in subscribers. An unauthenticated caller or a 401/403/404 falls through to the next base. */
67
70
  export function hubBases(env = process.env) {
68
71
  const fromEnv = (env.KODE_SKILLS_HUB ?? "").split(",").map((s) => s.trim()).filter(Boolean);
69
72
  let fromHome = [];
@@ -73,7 +76,8 @@ export function hubBases(env = process.env) {
73
76
  fromHome = cfg.hub.endpoints.filter((x) => typeof x === "string");
74
77
  }
75
78
  catch { /* no hub config in this home */ }
76
- return [...new Set([...fromEnv, ...fromHome, ...OPERATOR_URLS].map((b) => b.replace(/\/+$/, "")))];
79
+ const gateway = `https://${PRODUCT_API_HOST}`;
80
+ return [...new Set([...fromEnv, ...fromHome, gateway, ...OPERATOR_URLS].map((b) => b.replace(/\/+$/, "")))];
77
81
  }
78
82
  const hubOrigin = (src) => {
79
83
  if (!src)
@@ -0,0 +1,44 @@
1
+ const nodeImport = (m) => import(m);
2
+ async function craft() {
3
+ return (await nodeImport("../products/craft.js"));
4
+ }
5
+ export const CRAFT_TOOLS = [
6
+ {
7
+ name: "craft_create",
8
+ description: "Make a first-class CRAFT — a hosted, shareable, ACCOUNT-OWNED page / deck / doc / board / dashboard / app — and get a stable id + a public URL. Unlike artifact_create (ephemeral), a craft is owned by your account, versioned, and can be updated / listed / fetched later by id. Use for work you'll keep, revise, or share for review.",
9
+ parameters: { type: "object", additionalProperties: false, required: ["content"], properties: {
10
+ content: { type: "string", description: "the page/deck/doc body — HTML, SVG, or markdown" },
11
+ title: { type: "string", description: "short title" },
12
+ type: { type: "string", description: "page (default) | deck | doc | board | dashboard | app | svg | markdown | canvas" },
13
+ } },
14
+ async run(args) { return (await craft()).craftCreate(args); },
15
+ },
16
+ {
17
+ name: "craft_update",
18
+ description: "Update a craft you own by id — new content, title, or visibility (private | link | people | workspace | public). Optimistic concurrency: pass expected_version (from craft_get) to avoid clobbering a change made since you read it.",
19
+ parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
20
+ id: { type: "string", description: "the craft id (from craft_create / craft_list)" },
21
+ content: { type: "string", description: "replacement body" },
22
+ title: { type: "string", description: "new title" },
23
+ visibility: { type: "string", description: "private | link | people | workspace | public" },
24
+ expected_version: { type: "string", description: "the version you last read (optimistic concurrency)" },
25
+ } },
26
+ async run(args) { return (await craft()).craftUpdate(args); },
27
+ },
28
+ {
29
+ name: "craft_list", safe: true,
30
+ description: "List the crafts your account owns (id · type · title · visibility · URL). Read-only.",
31
+ parameters: { type: "object", additionalProperties: false, properties: {
32
+ limit: { type: "number", description: "max rows (default 20, max 100)" },
33
+ } },
34
+ async run(args) { return (await craft()).craftList(args); },
35
+ },
36
+ {
37
+ name: "craft_get", safe: true,
38
+ description: "Fetch one craft by id — its metadata (owner, version, visibility), URL, and current content. Read-only.",
39
+ parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
40
+ id: { type: "string", description: "the craft id" },
41
+ } },
42
+ async run(args) { return (await craft()).craftGet(args); },
43
+ },
44
+ ];
@@ -0,0 +1,132 @@
1
+ const nodeImport = (m) => import(m);
2
+ const str = (v, d = "") => (v === undefined || v === null ? d : String(v));
3
+ async function mdoc() {
4
+ return (await nodeImport("../products/mdoc.js"));
5
+ }
6
+ export const MDOC_TOOLS = [
7
+ {
8
+ name: "mdoc_put",
9
+ description: "Store or update a model-doc (mdoc): versioned, retrievable knowledge — a decision log, spec, handoff, " +
10
+ "convention, or a roledrobe chip. Every put is a new immutable version; mdoc_history lists them. Pass the " +
11
+ "same id to update. Use this for durable knowledge other turns/agents should find — not for a one-off note.",
12
+ parameters: {
13
+ type: "object",
14
+ additionalProperties: false,
15
+ required: ["id", "content"],
16
+ properties: {
17
+ id: { type: "string", description: "stable id for this doc (e.g. 'decision-2026-11-06-product-rails')" },
18
+ content: { type: "string", description: "the doc body (markdown or text)" },
19
+ type: { type: "string", enum: ["decision", "spec", "handoff", "convention", "chip"], description: "doc type (default: decision)" },
20
+ title: { type: "string" },
21
+ tags: { type: "array", items: { type: "string" } },
22
+ note: { type: "string", description: "a short note for this version (shows in history)" },
23
+ },
24
+ },
25
+ async run(args) {
26
+ try {
27
+ const m = await mdoc();
28
+ const tags = Array.isArray(args.tags) ? args.tags.map((t) => String(t)) : undefined;
29
+ const obj = m.mdocPut(m.resolveActor(), {
30
+ id: str(args.id), content: str(args.content), type: args.type,
31
+ title: args.title ? str(args.title) : undefined, tags, note: args.note ? str(args.note) : undefined,
32
+ });
33
+ return `stored mdoc ${obj.id} (type ${obj.type}, version ${obj.current}, ${obj.versions.length} version(s))`;
34
+ }
35
+ catch (e) {
36
+ return `mdoc_put failed: ${e.message}`;
37
+ }
38
+ },
39
+ },
40
+ {
41
+ name: "mdoc_get",
42
+ description: "Read a model-doc by id (optionally a specific version hash). Returns its content and metadata.",
43
+ safe: true,
44
+ parameters: {
45
+ type: "object", additionalProperties: false, required: ["id"],
46
+ properties: { id: { type: "string" }, version: { type: "string", description: "a version hash from mdoc_history (default: current)" } },
47
+ },
48
+ async run(args) {
49
+ try {
50
+ const m = await mdoc();
51
+ const r = m.mdocGet(m.resolveActor(), str(args.id), args.version ? str(args.version) : undefined);
52
+ if (!r)
53
+ return `mdoc ${str(args.id)} not found (or not accessible)`;
54
+ const meta = r.object.meta;
55
+ return `# ${meta.title ?? r.object.id} [${r.object.type}] v${r.object.current}\n` +
56
+ `tags: ${(meta.tags ?? []).join(", ") || "—"}\n\n${r.content}`;
57
+ }
58
+ catch (e) {
59
+ return `mdoc_get failed: ${e.message}`;
60
+ }
61
+ },
62
+ },
63
+ {
64
+ name: "mdoc_list",
65
+ description: "List your model-docs (optionally filtered by type), newest first.",
66
+ safe: true,
67
+ parameters: {
68
+ type: "object", additionalProperties: false,
69
+ properties: { type: { type: "string", enum: ["decision", "spec", "handoff", "convention", "chip"] } },
70
+ },
71
+ async run(args) {
72
+ try {
73
+ const m = await mdoc();
74
+ const items = m.mdocList(m.resolveActor(), { type: args.type });
75
+ if (!items.length)
76
+ return "no mdocs yet";
77
+ return items.map((o) => {
78
+ const meta = o.meta;
79
+ return `- ${o.id} [${o.type}] ${meta.title ?? ""} · ${o.versions.length}v · ${new Date(o.updatedAt).toISOString().slice(0, 10)}`;
80
+ }).join("\n");
81
+ }
82
+ catch (e) {
83
+ return `mdoc_list failed: ${e.message}`;
84
+ }
85
+ },
86
+ },
87
+ {
88
+ name: "mdoc_search",
89
+ description: "Search your model-docs by keyword (title, tags, content), newest/most-relevant first. The way to find prior decisions, specs or chips at runtime.",
90
+ safe: true,
91
+ parameters: {
92
+ type: "object", additionalProperties: false, required: ["query"],
93
+ properties: {
94
+ query: { type: "string" },
95
+ type: { type: "string", enum: ["decision", "spec", "handoff", "convention", "chip"] },
96
+ limit: { type: "number" },
97
+ },
98
+ },
99
+ async run(args) {
100
+ try {
101
+ const m = await mdoc();
102
+ const hits = m.mdocSearch(m.resolveActor(), str(args.query), {
103
+ type: args.type, limit: typeof args.limit === "number" ? args.limit : undefined,
104
+ });
105
+ if (!hits.length)
106
+ return "no matching mdocs";
107
+ return hits.map((h) => `- ${h.object.id} [${h.object.type}] — ${h.snippet.replace(/\s+/g, " ").trim()}`).join("\n");
108
+ }
109
+ catch (e) {
110
+ return `mdoc_search failed: ${e.message}`;
111
+ }
112
+ },
113
+ },
114
+ {
115
+ name: "mdoc_history",
116
+ description: "List the version history of a model-doc (each version's hash, time, author, note) for diffing or rollback.",
117
+ safe: true,
118
+ parameters: { type: "object", additionalProperties: false, required: ["id"], properties: { id: { type: "string" } } },
119
+ async run(args) {
120
+ try {
121
+ const m = await mdoc();
122
+ const h = m.mdocHistory(m.resolveActor(), str(args.id));
123
+ if (!h)
124
+ return `mdoc ${str(args.id)} not found (or not accessible)`;
125
+ return h.slice().reverse().map((v) => `- v${v.version} · ${new Date(v.ts).toISOString()} · ${v.author}${v.note ? ` · ${v.note}` : ""}`).join("\n");
126
+ }
127
+ catch (e) {
128
+ return `mdoc_history failed: ${e.message}`;
129
+ }
130
+ },
131
+ },
132
+ ];
@@ -10,12 +10,14 @@ import { indexSessions, readSession, searchSessions } from "../memory/session-in
10
10
  import { formatHits, indexCatalog, readCatalogSession, searchCatalog, sessionSearchConfig, SESSION_SCOPES } from "../memory/session-catalog.js";
11
11
  import { listLocalSkills, localSkillsDir as profileSkillsDir, resolveSkillFile } from "../config/skills-index.js";
12
12
  import { operatorPath } from "../config/home.js";
13
+ import { PRODUCT_API_HOST } from "../config/product-hosts.js";
13
14
  import { ownChild } from "../util/owned-children.js";
14
15
  import { BG_MAX_RUNNING, createJob, finishJob, newJobId, pruneShellJobs, runningJobCount, shellJobs, stopShellJob, trackJobOutput } from "./shell-jobs.js";
15
16
  import { pexecFile } from "./exec.js";
16
17
  import { WAVE_TOOLS } from "./wave-tools.js";
17
18
  import { WAVE2_TOOLS } from "./wave2-tools.js";
18
19
  import { GIT_PR_TOOLS } from "./git-pr.js";
20
+ import { MDOC_TOOLS } from "./mdoc.js";
19
21
  import { INCIDENT_TOOLS } from "./incident-tools.js";
20
22
  import { MONITORING_TOOLS } from "./monitoring-tools.js";
21
23
  import { desktopScreenshot, desktopClick, desktopRead, appInteract, capturePermalink, liveDrive } from "./chauffeur-native.js";
@@ -25,6 +27,7 @@ import { DOC_TEXT_EXTS, describeDocText, docExt, extractDocText } from "./doc-te
25
27
  import { gatewayModelAllowed, resolveVisionGateway } from "./vision-gateway.js";
26
28
  import { expandPath, assertContentSearchScope, assertShellHomeWideSearch, assertShellBlindDownload } from "./paths.js";
27
29
  import { resolveReadPath } from "./read-path.js";
30
+ import { CRAFT_TOOLS } from "./craft.js";
28
31
  import { runMemoryTool } from "./memory.js";
29
32
  import { documentGenerate } from "./document.js";
30
33
  import { runCronTool } from "../autonomy/cron.js";
@@ -2791,6 +2794,16 @@ const TOOLS = [
2791
2794
  }, required: ["name", "content"] },
2792
2795
  run: (a) => skillSave(str(a.name), str(a.content)),
2793
2796
  },
2797
+ {
2798
+ name: "skill_publish", safe: false,
2799
+ contract: { v: 1, effects: ["read", "egress"], audit: ["name", "version"] },
2800
+ description: "Publish one of your profile skills to the AXE marketplace under your account. Needs sign-in and an active subscription; it lands quarantined and unverified, visible only to you until it is reviewed.",
2801
+ parameters: { type: "object", properties: {
2802
+ name: { type: "string", description: "the profile skill to publish (as saved by skill_save)" },
2803
+ version: { type: "string", description: "semantic version, default 1.0.0; a published version cannot be replaced" },
2804
+ }, required: ["name"] },
2805
+ run: (a) => skillPublish(str(a.name), str(a.version).trim() || "1.0.0"),
2806
+ },
2794
2807
  {
2795
2808
  name: "memory", safe: false,
2796
2809
  description: "Batch-edit memories/MEMORY.md or memories/USER.md: each operation adds, replaces or removes text; budget-checked, one atomic write.",
@@ -2858,7 +2871,7 @@ const TOOLS = [
2858
2871
  },
2859
2872
  {
2860
2873
  name: "delegate_task", safe: false,
2861
- description: `Run ONE self-contained subtask on a sub-agent (a headless Operator session with its own tools) and get its final answer; blocks. It has NO memory of this conversation and cannot ask — \`task\` must carry every path, constraint and the exact output wanted. \`model\`: any /model id; OMIT IT to use the owner's configured default sub-agent (almost always right). Never name a model you have not seen answer in this fleet (an unloaded one fails); tool-heavy work (repo review, exploration, web research, debugging) needs a strong tool-driver such as "cortana". Connected cloud providers work too ("claude-sonnet", BYO: ${BYO_DELEGATE_PROVIDERS}); one without a stored key is refused with the command to store it. Don't delegate a single tool call; sub-agents cannot delegate further and can mutate the workspace.`,
2874
+ description: `Run ONE self-contained subtask on a sub-agent (a headless Operator session with its own tools) and get its final answer; blocks. It has NO memory of this conversation and cannot ask — \`task\` must carry every path, constraint and the exact output wanted. \`model\`: any /model id; OMIT IT to use the owner's configured default sub-agent (almost always right). Never name a model you have not seen answer in this fleet (an unloaded one fails); tool-heavy work (repo review, exploration, web research, debugging) belongs on the default, which the gateway fills with a strong tool-driver and spills parallel delegations across the fleet. Connected cloud providers work too ("claude-sonnet", BYO: ${BYO_DELEGATE_PROVIDERS}); one without a stored key is refused with the command to store it. Don't delegate a single tool call; sub-agents cannot delegate further and can mutate the workspace.`,
2862
2875
  parameters: { type: "object", properties: {
2863
2876
  task: { type: "string", description: "the complete, self-contained subtask — the sub-agent sees only this" },
2864
2877
  model: { type: "string", description: "registry model id; omit for the owner's configured default sub-agent" },
@@ -3159,6 +3172,40 @@ async function skillSave(name, content) {
3159
3172
  return `error saving skill: ${e.message}`;
3160
3173
  }
3161
3174
  }
3175
+ const MARKETPLACE_URL = (process.env.KODE_MARKETPLACE_URL ?? `https://${PRODUCT_API_HOST}`).replace(/\/+$/, "");
3176
+ const publishFailures = {
3177
+ 401: "sign in first (operator login)",
3178
+ 403: "the marketplace needs an active subscription on your account",
3179
+ 409: "that version is already published; bump the version",
3180
+ 413: "the skill is too large for the marketplace",
3181
+ 429: "too many publishes this hour; try again later",
3182
+ };
3183
+ async function skillPublish(name, version) {
3184
+ if (!name)
3185
+ return "error: skill_publish needs a name";
3186
+ const local = (await localSkills()).find((ls) => ls.name === name || slugify(ls.name) === slugify(name));
3187
+ if (!local)
3188
+ return `error: no profile skill '${name}'; save it with skill_save first`;
3189
+ const token = await operatorToken();
3190
+ if (!token)
3191
+ return publishFailures[401];
3192
+ try {
3193
+ const { readFile } = await nodeImport("node:fs/promises");
3194
+ const content = await readFile(local.file, "utf8");
3195
+ const res = await fetch(`${MARKETPLACE_URL}/v1/skills`, {
3196
+ method: "POST",
3197
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, "User-Agent": "KODE/0.9 (axe-tsi)" },
3198
+ body: JSON.stringify({ name: slugify(local.name), version, content, format: "skillmd" }),
3199
+ signal: AbortSignal.timeout(20000),
3200
+ });
3201
+ if (res.ok)
3202
+ return `published ${slugify(local.name)}@${version} to the marketplace (quarantined and unverified until it is reviewed; only your account can see it).`;
3203
+ return `error: ${publishFailures[res.status] ?? `the marketplace answered ${res.status}`}`;
3204
+ }
3205
+ catch (e) {
3206
+ return `error publishing skill: ${e.message}`;
3207
+ }
3208
+ }
3162
3209
  export async function localSkills() {
3163
3210
  return listLocalSkills();
3164
3211
  }
@@ -3215,6 +3262,17 @@ export const CLOUD_AGENT_TOOLS = [
3215
3262
  export function cloudAgentToolsFor(settings) {
3216
3263
  return isFeatureEnabled("cloudAgents", settings ?? undefined) ? CLOUD_AGENT_TOOLS : [];
3217
3264
  }
3265
+ // Flag-gated mdoc product tools (config/features.ts `mdoc`): absent from the base registry so a new product
3266
+ // never bloats every session's fixed prefix (the prompt-budget pin) — the session merges them in only when the
3267
+ // `mdoc` feature is on, exactly like the cloud-agent tools. SPEC: products-craft-mdoc.
3268
+ export function mdocToolsFor(settings) {
3269
+ return isFeatureEnabled("mdoc", settings ?? undefined) ? MDOC_TOOLS : [];
3270
+ }
3271
+ // Flag-gated craft product tools (config/features.ts `craft`): absent from the base registry so the stock prompt
3272
+ // prefix is unchanged; the session adds them only when the `craft` feature is on, exactly like mdoc + cloud-agent.
3273
+ export function craftToolsFor(settings) {
3274
+ return isFeatureEnabled("craft", settings ?? undefined) ? CRAFT_TOOLS : [];
3275
+ }
3218
3276
  export function toSchemas(reg = registry) {
3219
3277
  return [...reg.values()].map(t => ({
3220
3278
  type: "function",
package/dist/ui/App.js CHANGED
@@ -96,11 +96,11 @@ export function App(props) {
96
96
  // Tool rows exist before their calls run (TUI plan #8): from the first streamed argument (drafting) through waiting
97
97
  // its turn to running and settled — one row per call, a lone call included, instead of the bare "⠋ name…".
98
98
  const showLiveRows = liveTools.length > 0 && (status === "executing" || phase?.phase === "drafting");
99
- const showSpinner = status === "recovering" || status === "compacting" || (status === "executing" && !showLiveRows) || thinking;
99
+ const showSpinner = status === "recovering" || status === "compacting" || status === "executing" || thinking;
100
100
  // The live activity band (spinner / parallel-tool view) and the bg-agents panel — shared by both layouts.
101
- const activity = (_jsxs(_Fragment, { children: [showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" || status === "compacting" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
102
- : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
103
- : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showLiveRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, paddingLeft: 1, children: [_jsx(Text, { dimColor: true, children: batchHeader(liveTools, termCols()) }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => (_jsxs(React.Fragment, { children: [_jsx(LiveRow, { step: step }), delegate && step.id === delegateRow(liveTools, delegate) ? _jsx(DelegateChild, { view: delegate }) : null] }, step.id))), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), fold ? (() => { const line = foldLine(fold, termCols(), true); return _jsxs(Text, { children: [_jsx(Text, { color: theme.blocked, children: line.slice(0, 1) }), _jsx(Text, { dimColor: true, children: line.slice(1) })] }); })() : null, _jsx(PlanPane, { tasks: tasks, now: planNow }), liveWorkers(mainLane, bgAgents, shellJobs) >= 2
101
+ const activity = (_jsxs(_Fragment, { children: [showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: showLiveRows ? 0 : 1, children: status === "recovering" || status === "compacting" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
102
+ : status === "executing" && !showLiveRows ? _jsx(StepSpinner, { active: true, label: stepLabel })
103
+ : _jsx(ThinkingSpinner, { active: true, verb: status === "executing" ? thinkingVerb ?? "Running" : thinkingVerb, verbs: verbs, metrics: metrics }) })), showLiveRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, paddingLeft: 1, children: [_jsx(Text, { dimColor: true, children: batchHeader(liveTools, termCols()) }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => (_jsxs(React.Fragment, { children: [_jsx(LiveRow, { step: step }), delegate && step.id === delegateRow(liveTools, delegate) ? _jsx(DelegateChild, { view: delegate }) : null] }, step.id))), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), fold ? (() => { const line = foldLine(fold, termCols(), true); return _jsxs(Text, { children: [_jsx(Text, { color: theme.blocked, children: line.slice(0, 1) }), _jsx(Text, { dimColor: true, children: line.slice(1) })] }); })() : null, _jsx(PlanPane, { tasks: tasks, now: planNow }), liveWorkers(mainLane, bgAgents, shellJobs) >= 2
104
104
  ? _jsx(Lanes, { main: mainLane, agents: bgAgents, jobs: shellJobs, mainServing: mainServing, maxRunning: maxRunning })
105
105
  : _jsx(BgPanel, { agents: bgAgents, jobs: shellJobs }), (thinking || status === "executing" || status === "recovering" || status === "compacting") && (_jsx(PhaseLine, { view: phase ?? { phase: status === "executing" ? "tools" : status === "recovering" ? "recovering" : status === "compacting" ? "compacting" : status === "streaming" ? "writing" : "waiting", label: stepLabel }, rows: liveTools, offer: actOffer }))] }));
106
106
  // One input owner at a time. An open overlay — the finder, the focused switcher — keeps the keyboard; a prompt that
@@ -15,7 +15,7 @@ const KIND_RULES = [
15
15
  [/(read_file|read_files|^read$|^cat$|open_file|file_read)/i, "read"],
16
16
  [/(file_write|write_file|^write$|edit|apply_patch|str_replace|notebook|create_file|insert)/i, "write"],
17
17
  [/(web_search|web_fetch|^web|http|browser|^fetch$|curl|^url|download)/i, "web"],
18
- [/(skill_fetch|skill_save|^skill$)/i, "skill"],
18
+ [/(skill_fetch|skill_save|skill_publish|^skill$)/i, "skill"],
19
19
  [/(search|grep|ripgrep|glob|^find$|skill_list|lookup)/i, "search"],
20
20
  [/(^git|git_|checkpoint|^commit|^diff|^branch)/i, "git"], // before shell: "git_command" contains "command"
21
21
  [/(bash|shell|^run$|exec|command|script)/i, "shell"],