Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2183]): creative tool registry with gated dispatch
[._.]/ Adam Eivyb3b4247c6965
diff --git a/server/lib/README.md b/server/lib/README.mdindex db17fa10a3..11a3c83866 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -248,7 +248,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `arrayUtils.js` | `shuffle(arr)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). || `asyncMutex.js` | Promise-based async mutex. || `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. |-| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). |+| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware. || `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. |diff --git a/server/lib/domainAutonomy.js b/server/lib/domainAutonomy.jsindex 5fb96e828d..743567da57 100644--- a/server/lib/domainAutonomy.js+++ b/server/lib/domainAutonomy.js@@ -84,3 +84,36 @@ export function getDomainMode(config, domainId) {const candidate = config?.domainAutonomy?.[domainId];return isValidMode(candidate) ? candidate : DEFAULT_DOMAIN_MODE;}++// The `creative` autonomy domain (#2183) governs the Creative Director+// orchestrator's gated tool dispatch (universe/story/pipeline/media generators an+// agent may drive autonomously). It is deliberately kept SEPARATE from the four+// normalized core domains above — it is NOT in DOMAIN_IDS, so it carries no forced+// `execute` default and no parallel budget/usage ledger, and existing budget/UI+// tests are untouched. Its default MIRRORS the `cos` domain's mode so installs+// that already tuned CoS auto-run get consistent orchestrator behavior with no+// migration; an explicit stored `domainAutonomy.creative` value (settable by a+// future settings UI) overrides the mirror. Decision recorded for review: keep+// separate + mirror cos rather than folding into `cos` outright, so the knob can+// diverge later without another migration.+export const CREATIVE_DOMAIN_ID = 'creative';++export const CREATIVE_DOMAIN = Object.freeze({+ id: CREATIVE_DOMAIN_ID,+ label: 'Creative orchestrator',+ description:+ 'Automatically run creative-suite tools (universe, story, pipeline, media) from an orchestrating agent. Defaults to mirror the CoS auto-run mode.'+});++/**+ * Resolve the `creative` domain's mode (off | dry-run | execute). An explicit,+ * valid `domainAutonomy.creative` value wins; otherwise the mode MIRRORS the+ * `cos` domain (which itself defaults to `execute` for an absent config).+ *+ * @param {object|null|undefined} config - CoS config+ * @returns {'off'|'dry-run'|'execute'}+ */+export function getCreativeAutonomyMode(config) {+ const explicit = config?.domainAutonomy?.[CREATIVE_DOMAIN_ID];+ return isValidMode(explicit) ? explicit : getDomainMode(config, 'cos');+}diff --git a/server/lib/domainAutonomy.test.js b/server/lib/domainAutonomy.test.jsindex a9926d3a52..918cc2b6d3 100644--- a/server/lib/domainAutonomy.test.js+++ b/server/lib/domainAutonomy.test.js@@ -5,7 +5,10 @@ import {AUTONOMY_DOMAINS,DOMAIN_IDS,normalizeDomainAutonomy,- getDomainMode+ getDomainMode,+ CREATIVE_DOMAIN,+ CREATIVE_DOMAIN_ID,+ getCreativeAutonomyMode} from './domainAutonomy.js';describe('domainAutonomy constants', () => {@@ -69,3 +72,27 @@ describe('getDomainMode', () => {expect(getDomainMode({ domainAutonomy: { brain: 'haywire' } }, 'brain')).toBe('execute');});});++describe('creative domain (#2183)', () => {+ it('is kept out of the four normalized core domains', () => {+ expect(DOMAIN_IDS).not.toContain(CREATIVE_DOMAIN_ID);+ expect(CREATIVE_DOMAIN.id).toBe('creative');+ expect(CREATIVE_DOMAIN.label).toBeTruthy();+ expect(CREATIVE_DOMAIN.description).toBeTruthy();+ });++ it('mirrors the cos mode when no explicit creative value is stored', () => {+ expect(getCreativeAutonomyMode(undefined)).toBe('execute'); // cos default+ expect(getCreativeAutonomyMode({ domainAutonomy: { cos: 'off' } })).toBe('off');+ expect(getCreativeAutonomyMode({ domainAutonomy: { cos: 'dry-run' } })).toBe('dry-run');+ });++ it('lets an explicit valid creative value override the cos mirror', () => {+ expect(getCreativeAutonomyMode({ domainAutonomy: { cos: 'off', creative: 'execute' } })).toBe('execute');+ expect(getCreativeAutonomyMode({ domainAutonomy: { cos: 'execute', creative: 'off' } })).toBe('off');+ });++ it('falls back to the cos mirror for an invalid creative value', () => {+ expect(getCreativeAutonomyMode({ domainAutonomy: { cos: 'off', creative: 'haywire' } })).toBe('off');+ });+});diff --git a/server/services/creative/creativeRunLedger.js b/server/services/creative/creativeRunLedger.jsnew file mode 100644index 0000000000..cc1f5a411f--- /dev/null+++ b/server/services/creative/creativeRunLedger.js@@ -0,0 +1,112 @@+/**+ * Creative-orchestrator run ledger (#2183, CDO Phase 1).+ *+ * Every gated dispatch through `dispatchCreativeTool` appends a compact audit+ * entry — `{ tool, argsDigest, outcome, mode, costClass, timingMs, at }` — to the+ * calling project's run ledger. This is the observability trail for autonomous+ * creative work: what tool ran, against which project, whether it executed / was+ * planned (dry-run) / rejected (off or over-budget) / errored, and how long it+ * took. It intentionally stores a DIGEST of args, never the raw payload, so a+ * large prompt or image blob never bloats the ledger.+ *+ * Scope note: this is a Phase-1 stand-alone store keyed by projectId+ * (`data/creative/ledger/{projectId}.json`). Phase 2 formalizes the CD project+ * record (`projectsLogic.js#buildProjectRecord`) with its own migration ++ * schema-version gate; the dispatcher takes an injectable `ctx.appendLedger`+ * sink, so Phase 2 can route entries onto the project record without touching the+ * dispatcher. Tests inject a sink (or a `dir` override) and never hit real data.+ *+ * Storage is one small JSON array per project, capped so a long-running+ * orchestration can't grow it without bound; writes serialize on a per-project+ * tail (single-user install — this guards two writes to the SAME project file,+ * not competing actors).+ */++import { createHash } from 'crypto';+import { join } from 'path';+import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';++// Keep the most recent N entries per project — matches the CD project record's+// MAX_PERSISTED_RUNS spirit (bounded audit log, newest kept).+export const MAX_LEDGER_ENTRIES = 500;++const DEFAULT_LEDGER_DIR = join(PATHS.data, 'creative', 'ledger');++// One write tail per project file so two appends to the same ledger can't+// read-modify-write-clobber each other.+const tails = new Map();+function tailFor(key) {+ let tail = tails.get(key);+ if (!tail) {+ tail = createFileWriteQueue();+ tails.set(key, tail);+ }+ return tail;+}++/**+ * Stable short digest of a tool's args — a sha256 hex prefix plus the sorted+ * top-level key list, so the ledger records the SHAPE and a fingerprint of the+ * inputs without persisting the (possibly huge) values themselves.+ *+ * @param {unknown} args+ * @returns {string}+ */+export function argsDigest(args) {+ if (args == null || typeof args !== 'object') return 'none';+ const keys = Object.keys(args).sort();+ let json;+ try {+ json = JSON.stringify(args, Object.keys(args).sort());+ } catch {+ json = String(args);+ }+ const hash = createHash('sha256').update(json).digest('hex').slice(0, 12);+ return keys.length ? `${keys.join(',')}#${hash}` : `#${hash}`;+}++function fileFor(projectId, dir) {+ return join(dir || DEFAULT_LEDGER_DIR, `${sanitizeId(projectId)}.json`);+}++// Keep the on-disk filename to a safe slug — a projectId is normally a uuid, but+// a hand-passed value must never escape the ledger dir.+function sanitizeId(projectId) {+ return String(projectId || 'unknown').replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 128);+}++/**+ * Append one ledger entry for a project. Trims to the most-recent+ * MAX_LEDGER_ENTRIES. `dir` overrides the storage root (tests point it at a+ * scratch dir). Returns the appended entry.+ *+ * @param {string} projectId+ * @param {{tool: string, outcome: string, [k: string]: unknown}} entry+ * @param {{dir?: string}} [opts]+ */+export async function appendCreativeLedgerEntry(projectId, entry, { dir } = {}) {+ const file = fileFor(projectId, dir);+ const record = { at: new Date().toISOString(), ...entry };+ await tailFor(file)(async () => {+ await ensureDir(dir || DEFAULT_LEDGER_DIR);+ const existing = await readJSONFile(file, [], { logError: false });+ const list = Array.isArray(existing) ? existing : [];+ list.push(record);+ const trimmed = list.length > MAX_LEDGER_ENTRIES ? list.slice(-MAX_LEDGER_ENTRIES) : list;+ await atomicWrite(file, trimmed);+ });+ return record;+}++/**+ * Read a project's run ledger (chronological). Empty array when absent.+ *+ * @param {string} projectId+ * @param {{dir?: string}} [opts]+ * @returns {Promise<Array<object>>}+ */+export async function readCreativeLedger(projectId, { dir } = {}) {+ const existing = await readJSONFile(fileFor(projectId, dir), [], { logError: false });+ return Array.isArray(existing) ? existing : [];+}diff --git a/server/services/creative/creativeRunLedger.test.js b/server/services/creative/creativeRunLedger.test.jsnew file mode 100644index 0000000000..f825755464--- /dev/null+++ b/server/services/creative/creativeRunLedger.test.js@@ -0,0 +1,60 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { argsDigest, appendCreativeLedgerEntry, readCreativeLedger, MAX_LEDGER_ENTRIES } from './creativeRunLedger.js';++describe('argsDigest', () => {+ it("returns 'none' for null / non-object", () => {+ expect(argsDigest(null)).toBe('none');+ expect(argsDigest(undefined)).toBe('none');+ expect(argsDigest('str')).toBe('none');+ });++ it('lists sorted keys with a stable hash and is order-independent', () => {+ const a = argsDigest({ b: 1, a: 2 });+ const b = argsDigest({ a: 2, b: 1 });+ expect(a).toBe(b);+ expect(a.startsWith('a,b#')).toBe(true);+ });++ it('changes when a value changes', () => {+ expect(argsDigest({ a: 1 })).not.toBe(argsDigest({ a: 2 }));+ });+});++describe('creative run ledger store', () => {+ let dir;+ beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'creative-ledger-'));+ });+ afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+ });++ it('appends entries and reads them back chronologically', async () => {+ await appendCreativeLedgerEntry('proj-1', { tool: 'a.x', outcome: 'executed' }, { dir });+ await appendCreativeLedgerEntry('proj-1', { tool: 'a.y', outcome: 'planned' }, { dir });+ const list = await readCreativeLedger('proj-1', { dir });+ expect(list.map((e) => e.tool)).toEqual(['a.x', 'a.y']);+ expect(typeof list[0].at).toBe('string');+ });++ it('scopes ledgers per project', async () => {+ await appendCreativeLedgerEntry('proj-1', { tool: 'a.x', outcome: 'executed' }, { dir });+ expect(await readCreativeLedger('proj-2', { dir })).toEqual([]);+ });++ it('caps at MAX_LEDGER_ENTRIES, keeping the most recent', async () => {+ for (let i = 0; i < MAX_LEDGER_ENTRIES + 5; i += 1) {+ await appendCreativeLedgerEntry('proj-1', { tool: `t.${i}`, outcome: 'executed' }, { dir });+ }+ const list = await readCreativeLedger('proj-1', { dir });+ expect(list.length).toBe(MAX_LEDGER_ENTRIES);+ expect(list[list.length - 1].tool).toBe(`t.${MAX_LEDGER_ENTRIES + 4}`);+ });++ it('returns [] for an absent ledger', async () => {+ expect(await readCreativeLedger('missing', { dir })).toEqual([]);+ });+});diff --git a/server/services/creative/toolRegistry.js b/server/services/creative/toolRegistry.jsnew file mode 100644index 0000000000..4642b02876--- /dev/null+++ b/server/services/creative/toolRegistry.js@@ -0,0 +1,237 @@+// Creative Tool Registry + gated dispatch (#2183, CDO Phase 1).+//+// A single registry of creative-suite tools an orchestrating agent (the future+// Creative Director orchestrator, epic #2182) can call, plus the ONE dispatch+// chokepoint that makes autonomous use governable. Follows the voice-tools shape+// (server/services/voice/tools.js: {name, description, parameters, execute} ++// import-time integrity guards + a single dispatch fn) and the palette hydration+// pattern (server/routes/palette.js: reference existing schemas via+// getToolMetadata(), don't duplicate).+//+// Conductor, not re-implementation: every tool wraps an EXISTING service entry+// point (createUniverse, generateStep, startSeriesAutopilot, enqueueJob, …). The+// tools themselves stay UNGUARDED — direct user actions through the existing+// routes behave exactly as before. The gate lives ONLY here in+// dispatchCreativeTool: it enforces the `creative` autonomy mode, charges the+// daily action budget for llm/render tools, and appends to the calling project's+// run ledger. This is the governance point the AI Provider Usage Policy requires+// for autonomous creative work (the audit found only Series Autopilot and+// Writers-Room live mode self-gate today).++import { getCreativeAutonomyMode } from '../../lib/domainAutonomy.js';+import { getToolMetadata } from '../voice/tools.js';+import { loadState } from '../cosState.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';+import { appendCreativeLedgerEntry, argsDigest } from './creativeRunLedger.js';+import { COST_CLASSES, BUDGETED_COST_CLASSES } from './tools/shared.js';+import { UNIVERSE_TOOLS } from './tools/universe.js';+import { STORY_BUILDER_TOOLS } from './tools/storyBuilder.js';+import { WRITERS_ROOM_TOOLS } from './tools/writersRoom.js';+import { PIPELINE_TOOLS } from './tools/pipeline.js';+import { MEDIA_TOOLS } from './tools/media.js';+import { CATALOG_TOOLS } from './tools/catalog.js';++// The daily action budget the creative gate charges against. Creative+// orchestration mirrors the cos autonomy posture (see getCreativeAutonomyMode),+// so it also shares the cos daily budget/usage ledger rather than introducing a+// parallel one — a single autonomous-work budget. A dedicated `creative` budget+// (and its settings UI) can arrive with CDO Phase 4.+const BUDGET_DOMAIN = 'cos';++// The registry. Order isn't load-bearing (consumers resolve by name).+export const CREATIVE_TOOLS = [+ ...UNIVERSE_TOOLS,+ ...STORY_BUILDER_TOOLS,+ ...WRITERS_ROOM_TOOLS,+ ...PIPELINE_TOOLS,+ ...MEDIA_TOOLS,+ ...CATALOG_TOOLS,+];++const COST_SET = new Set(COST_CLASSES);++/**+ * Fail-fast integrity check (navManifest / voice-tools precedent): every tool+ * must carry a unique name, a Zod schema, an execute fn, and a valid cost class;+ * a `hydrateFrom` must reference a real voice tool. Throws on the first offender.+ * Pure + exported so the guard is unit-tested directly against bad inputs, and+ * called at module load so a bad tool blocks boot loudly.+ *+ * @param {Array<object>} tools+ * @param {(id: string) => object|null} [resolveMeta] - voice metadata resolver+ */+export function assertCreativeToolIntegrity(tools, resolveMeta = getToolMetadata) {+ const seen = new Set();+ for (const t of tools) {+ if (!t || typeof t.name !== 'string' || !t.name) {+ throw new Error('creative tools: a tool is missing its name');+ }+ if (seen.has(t.name)) {+ throw new Error(`creative tools: duplicate tool name "${t.name}"`);+ }+ seen.add(t.name);+ if (typeof t.execute !== 'function') {+ throw new Error(`creative tools: "${t.name}" is missing execute()`);+ }+ if (!t.schema || typeof t.schema.parse !== 'function') {+ throw new Error(`creative tools: "${t.name}" is missing a Zod schema`);+ }+ if (!COST_SET.has(t.costClass)) {+ throw new Error(`creative tools: "${t.name}" has invalid costClass "${t.costClass}"`);+ }+ if (t.hydrateFrom && !resolveMeta(t.hydrateFrom)) {+ throw new Error(`creative tools: "${t.name}" hydrateFrom "${t.hydrateFrom}" is not a known voice tool`);+ }+ }+}++assertCreativeToolIntegrity(CREATIVE_TOOLS);++const byName = new Map(CREATIVE_TOOLS.map((t) => [t.name, t]));++// Resolve a tool's advertised description + parameters. When a tool declares+// `hydrateFrom`, pull them from the voice tool of that name (single source of+// schemas — the palette pattern) instead of the tool's own authored fallback.+function resolveDisplay(t) {+ if (t.hydrateFrom) {+ const meta = getToolMetadata(t.hydrateFrom);+ if (meta) return { description: meta.description, parameters: meta.parameters };+ }+ return { description: t.description, parameters: t.parameters };+}++const toSpec = (t) => {+ const { description, parameters } = resolveDisplay(t);+ return { type: 'function', function: { name: t.name, description, parameters } };+};++/**+ * OpenAI-function-style specs for the registry, suitable for inclusion in a CoS+ * agent prompt. Destructive tools (delete/overwrite) are excluded by default so+ * an orchestrator prompt can't casually invoke them; pass `includeDestructive`+ * to surface them for an explicitly-approved flow.+ *+ * @param {{includeDestructive?: boolean}} [opts]+ */+// Pure (exported for the destructive-exclusion test): the tools that belong in+// the default spec set. Destructive tools are dropped unless explicitly included.+export const filterDestructive = (tools, includeDestructive) =>+ tools.filter((t) => includeDestructive || !t.destructive);++export const getToolSpecs = ({ includeDestructive = false } = {}) =>+ filterDestructive(CREATIVE_TOOLS, includeDestructive).map(toSpec);++export const getAllCreativeToolNames = () => CREATIVE_TOOLS.map((t) => t.name);++/**+ * Plain metadata for one tool (for non-LLM consumers, e.g. a plan board or the+ * command palette). Shape-independent from getToolSpecs.+ *+ * @param {string} name+ */+export const getCreativeToolMetadata = (name) => {+ const t = byName.get(name);+ if (!t) return null;+ const { description, parameters } = resolveDisplay(t);+ return {+ id: t.name,+ description,+ parameters,+ costClass: t.costClass,+ longRunning: Boolean(t.longRunning),+ destructive: Boolean(t.destructive),+ };+};++// Best-effort audit append — a ledger write failure must never break the tool+// run. Injected `ctx.appendLedger` wins (Phase 2 will route entries onto the CD+// project record); otherwise a project-scoped file ledger is used when a+// projectId is present. A project-less dispatch simply isn't audited.+async function recordLedger(ctx, entry) {+ try {+ if (typeof ctx?.appendLedger === 'function') {+ await ctx.appendLedger(entry);+ return;+ }+ if (ctx?.projectId) {+ await appendCreativeLedgerEntry(ctx.projectId, entry);+ }+ } catch (err) {+ console.error(`❌ creative ledger append failed for ${entry.tool}: ${err.message}`);+ }+}++/**+ * The single governed dispatch chokepoint for orchestrator tool calls.+ *+ * Flow: validate args (Zod) → resolve the `creative` autonomy mode → gate →+ * (execute mode only) charge budget for llm/render → run → append to the run+ * ledger. Modes:+ * - `off` → reject without executing or charging.+ * - `dry-run` → return a plan frame describing what WOULD run; no side effects.+ * - `execute` → charge budget (llm/render) then run the wrapped entry point.+ *+ * @param {string} name - registered tool name+ * @param {object} args - tool arguments (validated against the tool's schema)+ * @param {{projectId?: string, appendLedger?: Function, [k: string]: unknown}} ctx+ * @returns {Promise<object>}+ */+export async function dispatchCreativeTool(name, args = {}, ctx = {}) {+ const tool = byName.get(name);+ if (!tool) throw new Error(`Unknown creative tool: ${name}`);++ // Validate up front — a Zod parse failure throws before any gating/side effect.+ const parsed = tool.schema.parse(args ?? {});++ const state = await loadState().catch(() => ({ config: {} }));+ const mode = getCreativeAutonomyMode(state.config);+ const base = { tool: name, argsDigest: argsDigest(parsed), costClass: tool.costClass, mode };++ if (mode === 'off') {+ console.log(`🚫 creative dispatch ${name} rejected (creative autonomy: off)`);+ await recordLedger(ctx, { ...base, outcome: 'rejected', timingMs: 0 });+ return { ok: false, rejected: true, reason: 'autonomy-off', mode, tool: name };+ }++ if (mode === 'dry-run') {+ console.log(`📝 creative dispatch ${name} planned (dry-run)`);+ await recordLedger(ctx, { ...base, outcome: 'planned', timingMs: 0 });+ return {+ ok: true,+ planned: true,+ mode,+ tool: name,+ costClass: tool.costClass,+ longRunning: Boolean(tool.longRunning),+ destructive: Boolean(tool.destructive),+ args: parsed,+ };+ }++ // execute mode — charge the daily action budget for llm/render tools first.+ if (BUDGETED_COST_CLASSES.has(tool.costClass)) {+ const status = await getDomainBudgetStatus(BUDGET_DOMAIN);+ if (!status.withinBudget) {+ console.log(`⛔ creative dispatch ${name} over budget (${BUDGET_DOMAIN} ${status.exceeded})`);+ await recordLedger(ctx, { ...base, outcome: 'budget-exceeded', timingMs: 0, exceeded: status.exceeded });+ return { ok: false, rejected: true, reason: 'budget', exceeded: status.exceeded, mode, tool: name };+ }+ await recordDomainUsage(BUDGET_DOMAIN, { actions: 1 });+ }++ const startedAt = Date.now();+ // Outside the Express request lifecycle (called by the orchestrator / CoS+ // agent) — catch so a thrown tool records an `error` ledger entry, then rethrow.+ try {+ const result = await tool.execute(parsed, ctx);+ const timingMs = Date.now() - startedAt;+ console.log(`✅ creative dispatch ${name} executed in ${timingMs}ms`);+ await recordLedger(ctx, { ...base, outcome: 'executed', timingMs });+ return { ok: true, mode, tool: name, longRunning: Boolean(tool.longRunning), result, timingMs };+ } catch (err) {+ const timingMs = Date.now() - startedAt;+ console.error(`❌ creative dispatch ${name} failed: ${err.message}`);+ await recordLedger(ctx, { ...base, outcome: 'error', timingMs, error: err.message });+ throw err;+ }+}diff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.jsnew file mode 100644index 0000000000..4e3c539099--- /dev/null+++ b/server/services/creative/toolRegistry.test.js@@ -0,0 +1,250 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { z } from 'zod';++// Mock the voice registry so hydration + the hydrateFrom guard resolve without+// pulling the heavy voice/tool graph into this unit test.+vi.mock('../voice/tools.js', () => ({+ getToolMetadata: vi.fn((id) =>+ id === 'catalog_lookup'+ ? {+ id: 'catalog_lookup',+ description: 'VOICE catalog search description',+ parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },+ }+ : null),+}));++// Mock the autonomy config + budget/usage services so gating is deterministic.+vi.mock('../cosState.js', () => ({ loadState: vi.fn(async () => ({ config: {} })) }));+vi.mock('../domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => ({ withinBudget: true, exceeded: null })),+ recordDomainUsage: vi.fn(async () => {}),+}));++// Mock every wrapped entry point — keeps the real services (and their heavy+// import side effects) out, and makes each tool's execute an observable spy.+vi.mock('../universeBuilder.js', () => ({ createUniverse: vi.fn(async () => ({ id: 'u1' })) }));+vi.mock('../universeBuilderExpand.js', () => ({ expandWorldTemplate: vi.fn(async () => ({ logline: 'x' })) }));+vi.mock('../universeBuilderRender.js', () => ({ renderUniverseJobs: vi.fn(async () => ({ jobs: [] })) }));+vi.mock('../storyBuilder.js', () => ({+ createStorySession: vi.fn(async () => ({ id: 's1' })),+ generateStep: vi.fn(async () => ({ runId: 'r1' })),+ generateIssuesFromArc: vi.fn(async () => ({ createdIssues: [] })),+}));+vi.mock('../writersRoom/local.js', () => ({ createWork: vi.fn(async () => ({ id: 'w1' })) }));+vi.mock('../writersRoom/evaluator.js', () => ({ runAnalysis: vi.fn(async () => ({ status: 'succeeded' })) }));+vi.mock('../pipeline/series.js', () => ({ createSeries: vi.fn(async () => ({ id: 'ser1' })) }));+vi.mock('../pipeline/seriesGenerate.js', () => ({ generateSeriesConcept: vi.fn(async () => ({ name: 'C' })) }));+vi.mock('../pipeline/textStages.js', () => ({ generateStage: vi.fn(async () => ({ stage: 'st' })) }));+vi.mock('../pipeline/visualStages.js', () => ({ enqueueComicCover: vi.fn(async () => ({ jobId: 'j1' })) }));+vi.mock('../pipeline/seriesAutopilot.js', () => ({ startSeriesAutopilot: vi.fn(async () => ({ runId: 'ap1' })) }));+vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj1' })) }));+vi.mock('../catalogDB.js', () => ({ listIngredients: vi.fn(async () => ({ items: [] })) }));+vi.mock('../creativeDirector/autoCast.js', () => ({ suggestCastForBrief: vi.fn(async () => []) }));++import { loadState } from '../cosState.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';+import { createSeries } from '../pipeline/series.js';+import { generateStage } from '../pipeline/textStages.js';+import { enqueueJob } from '../mediaJobQueue/index.js';+import {+ CREATIVE_TOOLS,+ getToolSpecs,+ getAllCreativeToolNames,+ getCreativeToolMetadata,+ filterDestructive,+ assertCreativeToolIntegrity,+ dispatchCreativeTool,+} from './toolRegistry.js';++const setMode = (mode) => loadState.mockResolvedValue({ config: { domainAutonomy: { cos: mode } } });++beforeEach(() => {+ vi.clearAllMocks();+ loadState.mockResolvedValue({ config: {} });+ getDomainBudgetStatus.mockResolvedValue({ withinBudget: true, exceeded: null });+});++describe('registry shape', () => {+ it('registers the six-domain tool inventory with unique names', () => {+ const names = getAllCreativeToolNames();+ expect(new Set(names).size).toBe(names.length);+ for (const prefix of ['universe.', 'storyBuilder.', 'writersRoom.', 'pipeline.', 'media.', 'catalog.']) {+ expect(names.some((n) => n.startsWith(prefix))).toBe(true);+ }+ });++ it('every tool carries schema + execute + a valid cost class', () => {+ for (const t of CREATIVE_TOOLS) {+ expect(typeof t.execute).toBe('function');+ expect(typeof t.schema.parse).toBe('function');+ expect(['free', 'llm', 'render']).toContain(t.costClass);+ }+ });++ it('getToolSpecs returns OpenAI function specs suitable for a prompt', () => {+ const specs = getToolSpecs();+ expect(specs.length).toBe(CREATIVE_TOOLS.length);+ for (const s of specs) {+ expect(s.type).toBe('function');+ expect(typeof s.function.name).toBe('string');+ expect(s.function.parameters.type).toBe('object');+ }+ });++ it('hydrates catalog.searchIngredients description + parameters from the voice tool', () => {+ const meta = getCreativeToolMetadata('catalog.searchIngredients');+ expect(meta.description).toBe('VOICE catalog search description');+ expect(meta.parameters.required).toEqual(['query']);+ });+});++describe('assertCreativeToolIntegrity', () => {+ const ok = { name: 'a.x', costClass: 'free', schema: z.object({}), execute: () => {} };++ it('accepts a valid tool set', () => {+ expect(() => assertCreativeToolIntegrity([ok])).not.toThrow();+ });+ it('throws on a duplicate name', () => {+ expect(() => assertCreativeToolIntegrity([ok, { ...ok }])).toThrow(/duplicate tool name/);+ });+ it('throws on a missing execute', () => {+ expect(() => assertCreativeToolIntegrity([{ ...ok, execute: undefined }])).toThrow(/missing execute/);+ });+ it('throws on a missing Zod schema', () => {+ expect(() => assertCreativeToolIntegrity([{ ...ok, schema: undefined }])).toThrow(/missing a Zod schema/);+ });+ it('throws on an invalid cost class', () => {+ expect(() => assertCreativeToolIntegrity([{ ...ok, costClass: 'bogus' }])).toThrow(/invalid costClass/);+ });+ it('throws when hydrateFrom names an unknown voice tool', () => {+ expect(() => assertCreativeToolIntegrity([{ ...ok, hydrateFrom: 'nope' }], () => null)).toThrow(/hydrateFrom/);+ });+});++describe('filterDestructive', () => {+ it('excludes destructive tools by default and includes them on request', () => {+ const tools = [{ name: 'a' }, { name: 'b', destructive: true }];+ expect(filterDestructive(tools, false).map((t) => t.name)).toEqual(['a']);+ expect(filterDestructive(tools, true).map((t) => t.name)).toEqual(['a', 'b']);+ });+});++describe('dispatch gating per mode', () => {+ it('off → rejects without executing or charging', async () => {+ setMode('off');+ const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ expect(out).toMatchObject({ ok: false, rejected: true, reason: 'autonomy-off', mode: 'off' });+ expect(createSeries).not.toHaveBeenCalled();+ expect(recordDomainUsage).not.toHaveBeenCalled();+ });++ it('dry-run → returns a plan frame with no side effects', async () => {+ setMode('dry-run');+ const out = await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });+ expect(out).toMatchObject({ ok: true, planned: true, mode: 'dry-run', tool: 'pipeline.generateStage', costClass: 'llm' });+ expect(out.args).toMatchObject({ issueId: 'i1', stageId: 'st1' });+ expect(generateStage).not.toHaveBeenCalled();+ expect(recordDomainUsage).not.toHaveBeenCalled();+ });++ it('execute → runs the wrapped entry point and returns its result', async () => {+ setMode('execute');+ const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ expect(out).toMatchObject({ ok: true, mode: 'execute', tool: 'pipeline.createSeries' });+ expect(out.result).toEqual({ id: 'ser1' });+ expect(createSeries).toHaveBeenCalledWith({ name: 'S' });+ });++ it('creative mode mirrors cos but an explicit creative override wins', async () => {+ loadState.mockResolvedValue({ config: { domainAutonomy: { cos: 'off', creative: 'execute' } } });+ const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ expect(out.ok).toBe(true);+ expect(createSeries).toHaveBeenCalled();+ });++ it('rejects an unknown tool', async () => {+ await expect(dispatchCreativeTool('nope.doThing', {})).rejects.toThrow(/Unknown creative tool/);+ });++ it('throws on invalid args (Zod) before any gating', async () => {+ setMode('execute');+ await expect(dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1' })).rejects.toBeInstanceOf(z.ZodError);+ expect(generateStage).not.toHaveBeenCalled();+ });+});++describe('budget charging', () => {+ it('charges one action for an llm tool on execute', async () => {+ setMode('execute');+ await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });+ expect(generateStage).toHaveBeenCalled();+ });++ it('charges for a render (media) tool on execute', async () => {+ setMode('execute');+ await dispatchCreativeTool('media.enqueueImageJob', { params: { prompt: 'p' } }, { projectId: 'p1' });+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'image', params: { prompt: 'p' }, owner: 'creative-director:p1' });+ });++ it('does not charge a free tool', async () => {+ setMode('execute');+ await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ expect(recordDomainUsage).not.toHaveBeenCalled();+ });++ it('rejects when the budget is exhausted, without executing', async () => {+ setMode('execute');+ getDomainBudgetStatus.mockResolvedValue({ withinBudget: false, exceeded: 'actions' });+ const out = await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });+ expect(out).toMatchObject({ ok: false, rejected: true, reason: 'budget', exceeded: 'actions' });+ expect(generateStage).not.toHaveBeenCalled();+ expect(recordDomainUsage).not.toHaveBeenCalled();+ });+});++describe('run ledger append', () => {+ it('appends an executed entry with tool, digest, outcome and timing', async () => {+ setMode('execute');+ const appendLedger = vi.fn(async () => {});+ await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });+ expect(appendLedger).toHaveBeenCalledTimes(1);+ const entry = appendLedger.mock.calls[0][0];+ expect(entry).toMatchObject({ tool: 'pipeline.createSeries', outcome: 'executed' });+ expect(typeof entry.argsDigest).toBe('string');+ expect(typeof entry.timingMs).toBe('number');+ });++ it('records outcome=rejected when off', async () => {+ setMode('off');+ const appendLedger = vi.fn(async () => {});+ await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { appendLedger });+ expect(appendLedger.mock.calls[0][0].outcome).toBe('rejected');+ });++ it('records outcome=planned in dry-run', async () => {+ setMode('dry-run');+ const appendLedger = vi.fn(async () => {});+ await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { appendLedger });+ expect(appendLedger.mock.calls[0][0].outcome).toBe('planned');+ });++ it('records outcome=error and rethrows when the tool throws', async () => {+ setMode('execute');+ generateStage.mockRejectedValueOnce(new Error('boom'));+ const appendLedger = vi.fn(async () => {});+ await expect(+ dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' }, { appendLedger }),+ ).rejects.toThrow('boom');+ expect(appendLedger.mock.calls[0][0]).toMatchObject({ outcome: 'error', error: 'boom' });+ });++ it('a ledger sink failure never breaks the dispatch', async () => {+ setMode('execute');+ const appendLedger = vi.fn(async () => { throw new Error('disk full'); });+ const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });+ expect(out.ok).toBe(true);+ });+});diff --git a/server/services/creative/tools/catalog.js b/server/services/creative/tools/catalog.jsnew file mode 100644index 0000000000..c2bdcf3947--- /dev/null+++ b/server/services/creative/tools/catalog.js@@ -0,0 +1,48 @@+/**+ * Catalog-domain creative tools (#2183). Conductor wrappers over catalog search+ * and cast suggestion. `catalog.searchIngredients` hydrates its description ++ * parameters from the voice `catalog_lookup` tool (the palette hydration+ * pattern) so the ingredient-search schema has a single source of truth.+ */++import { z } from 'zod';+import { listIngredients } from '../../catalogDB.js';+import { suggestCastForBrief } from '../../creativeDirector/autoCast.js';+import { COST_FREE, COST_LLM } from './shared.js';++export const CATALOG_TOOLS = [+ {+ name: 'catalog.searchIngredients',+ description: 'Search the creative ingredients catalog by name/content, optionally narrowed to one type.',+ costClass: COST_FREE,+ // Reuse the voice catalog_lookup schema instead of duplicating it.+ hydrateFrom: 'catalog_lookup',+ schema: z.object({ query: z.string().min(1), type: z.string().optional(), limit: z.number().int().positive().max(50).optional() }),+ parameters: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Free-text search across name + payload content.' },+ type: { type: 'string', description: 'Optional: restrict to one ingredient kind.' },+ limit: { type: 'integer', description: 'Max results (default 20).' },+ },+ required: ['query'],+ },+ execute: ({ query, type, limit }) => listIngredients({ query, type, limit: limit ?? 20 }),+ },+ {+ name: 'catalog.suggestCastForBrief',+ description: 'Suggest catalog ingredients to cast for a creative brief (ranked). Uses embedding search over the catalog.',+ costClass: COST_LLM,+ schema: z.object({ brief: z.string().min(1), types: z.array(z.string()).optional(), limit: z.number().int().positive().max(50).optional() }),+ parameters: {+ type: 'object',+ properties: {+ brief: { type: 'string', description: 'The creative brief to cast against.' },+ types: { type: 'array', items: { type: 'string' }, description: 'Optional castable types to restrict to.' },+ limit: { type: 'integer', description: 'Max suggestions.' },+ },+ required: ['brief'],+ },+ execute: (args) => suggestCastForBrief(args),+ },+];diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsnew file mode 100644index 0000000000..238939c26e--- /dev/null+++ b/server/services/creative/tools/media.js@@ -0,0 +1,34 @@+/**+ * Media-domain creative tools (#2183). Conductor wrappers over the media job+ * queue. Each enqueue tags the job's `owner` back to the calling project so the+ * orchestration's renders are attributable via `listJobs({ owner })`.+ */++import { z } from 'zod';+import { enqueueJob } from '../../mediaJobQueue/index.js';+import { COST_RENDER, resolveOwner } from './shared.js';++const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.string().optional() });++const mediaTool = (kind, label) => ({+ name: `media.enqueue${label}Job`,+ description: `Enqueue a ${kind} media job. Long-running: returns a job handle; completion arrives via media-job events. Tags the job owner to the calling project.`,+ costClass: COST_RENDER,+ longRunning: true,+ schema: paramsSchema,+ parameters: {+ type: 'object',+ properties: {+ params: { type: 'object', description: `Job parameters for the ${kind} worker.` },+ owner: { type: 'string', description: 'Optional explicit owner tag (defaults to the calling project).' },+ },+ required: ['params'],+ },+ execute: (args, ctx) => enqueueJob({ kind, params: args.params || {}, owner: resolveOwner(args, ctx) }),+});++export const MEDIA_TOOLS = [+ mediaTool('image', 'Image'),+ mediaTool('video', 'Video'),+ mediaTool('audio', 'Audio'),+];diff --git a/server/services/creative/tools/pipeline.js b/server/services/creative/tools/pipeline.jsnew file mode 100644index 0000000000..3027bfb572--- /dev/null+++ b/server/services/creative/tools/pipeline.js@@ -0,0 +1,93 @@+/**+ * Pipeline-domain creative tools (#2183). Conductor wrappers over the existing+ * comic/story production pipeline entry points, including running the Series+ * Autopilot as one orchestrated step.+ */++import { z } from 'zod';+import { createSeries } from '../../pipeline/series.js';+import { generateSeriesConcept } from '../../pipeline/seriesGenerate.js';+import { generateStage } from '../../pipeline/textStages.js';+import { enqueueComicCover } from '../../pipeline/visualStages.js';+import { startSeriesAutopilot } from '../../pipeline/seriesAutopilot.js';+import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';++export const PIPELINE_TOOLS = [+ {+ name: 'pipeline.createSeries',+ description: 'Create a new pipeline series record. Persists a record; returns it.',+ costClass: COST_FREE,+ schema: z.object({}).passthrough(),+ parameters: {+ type: 'object',+ properties: {+ name: { type: 'string', description: 'Optional series name.' },+ universeId: { type: 'string', description: 'Optional universe to attach the series to.' },+ },+ },+ execute: (args) => createSeries(args),+ },+ {+ name: 'pipeline.generateSeriesConcept',+ description: 'Generate a series concept (name, logline, premise, shape) for a universe via the LLM.',+ costClass: COST_LLM,+ schema: z.object({ universeId: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ universeId: { type: 'string', description: 'Universe id to derive a concept from.' },+ options: { type: 'object', description: 'Optional generation options.' },+ },+ required: ['universeId'],+ },+ execute: ({ universeId, options }) => generateSeriesConcept(universeId, options || {}),+ },+ {+ name: 'pipeline.generateStage',+ description: 'Generate one text stage (LLM) for a pipeline issue and persist the updated issue.',+ costClass: COST_LLM,+ schema: z.object({ issueId: z.string().min(1), stageId: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ issueId: { type: 'string', description: 'Issue id.' },+ stageId: { type: 'string', description: 'Stage id to generate.' },+ options: { type: 'object', description: 'Optional generation options.' },+ },+ required: ['issueId', 'stageId'],+ },+ execute: ({ issueId, stageId, options }) => generateStage(issueId, stageId, options || {}),+ },+ {+ name: 'pipeline.enqueueComicCover',+ description: 'Enqueue a comic-cover image render for an issue. Long-running: returns a job handle; completion arrives via media-job events.',+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ issueId: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ issueId: { type: 'string', description: 'Issue id to render a cover for.' },+ options: { type: 'object', description: 'Optional cover render options (variant, fromProof).' },+ },+ required: ['issueId'],+ },+ execute: ({ issueId, options }) => enqueueComicCover(issueId, options || {}),+ },+ {+ name: 'pipeline.startSeriesAutopilot',+ description: 'Start (or no-op resume) the Series Autopilot for a series. Long-running: returns a run handle; progress and pauses arrive via events. Autopilot has its own cos-off gate; the orchestrator gate applies first.',+ costClass: COST_LLM,+ longRunning: true,+ schema: z.object({ seriesId: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ seriesId: { type: 'string', description: 'Series id to run the autopilot on.' },+ options: { type: 'object', description: 'Optional autopilot run options.' },+ },+ required: ['seriesId'],+ },+ execute: ({ seriesId, options }) => startSeriesAutopilot(seriesId, options || {}),+ },+];diff --git a/server/services/creative/tools/shared.js b/server/services/creative/tools/shared.jsnew file mode 100644index 0000000000..39af36cb3c--- /dev/null+++ b/server/services/creative/tools/shared.js@@ -0,0 +1,32 @@+/**+ * Shared vocabulary for the creative tool registry (#2183, CDO Phase 1).+ *+ * Cost classes drive the dispatch budget gate: `free` tools (record creation,+ * DB reads) never charge; `llm` and `render` tools charge one autonomous action+ * against the daily budget. `longRunning` tools return a handle immediately and+ * complete via events (media jobs, autopilot). `destructive` tools (delete /+ * overwrite) are excluded from the default spec set an agent prompt sees.+ */++export const COST_FREE = 'free';+export const COST_LLM = 'llm';+export const COST_RENDER = 'render';+export const COST_CLASSES = [COST_FREE, COST_LLM, COST_RENDER];++// Cost classes that consume the daily autonomous-action budget on execute.+export const BUDGETED_COST_CLASSES = new Set([COST_LLM, COST_RENDER]);++/**+ * Owner tag for a media job enqueued through the orchestrator. Free-form string+ * used only for `listJobs({ owner })` filtering (no enforcement) — we tag it to+ * the calling project so its jobs are attributable back to the orchestration.+ *+ * @param {{owner?: string}} args+ * @param {{projectId?: string}} ctx+ * @returns {string}+ */+export function resolveOwner(args, ctx) {+ if (args?.owner) return String(args.owner);+ if (ctx?.projectId) return `creative-director:${ctx.projectId}`;+ return 'creative';+}diff --git a/server/services/creative/tools/storyBuilder.js b/server/services/creative/tools/storyBuilder.jsnew file mode 100644index 0000000000..ac3568b210--- /dev/null+++ b/server/services/creative/tools/storyBuilder.js@@ -0,0 +1,57 @@+/**+ * Story-builder-domain creative tools (#2183). Conductor wrappers over the+ * existing Story Builder entry points.+ */++import { z } from 'zod';+import { createStorySession, generateStep, generateIssuesFromArc } from '../../storyBuilder.js';+import { COST_FREE, COST_LLM } from './shared.js';++export const STORY_BUILDER_TOOLS = [+ {+ name: 'storyBuilder.createStorySession',+ description: 'Create a new story-builder session (optionally minting a universe). Persists the session; returns its id.',+ costClass: COST_FREE,+ schema: z.object({}).passthrough(),+ parameters: {+ type: 'object',+ properties: {+ name: { type: 'string', description: 'Optional session name.' },+ universeId: { type: 'string', description: 'Optional existing universe to attach to.' },+ },+ },+ execute: (args) => createStorySession(args),+ },+ {+ name: 'storyBuilder.generateStep',+ description: 'Generate one story-builder step (LLM) for a session and persist the result.',+ costClass: COST_LLM,+ schema: z.object({ id: z.string().min(1), stepId: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ id: { type: 'string', description: 'Story session id.' },+ stepId: { type: 'string', description: 'Step id to generate.' },+ options: { type: 'object', description: 'Optional generation options (providerId, model).' },+ },+ required: ['id', 'stepId'],+ },+ execute: ({ id, stepId, options }) => generateStep(id, stepId, options || {}),+ },+ {+ name: 'storyBuilder.generateIssuesFromArc',+ description: 'Generate the issue breakdown for a story arc (LLM). Long-running: creates multiple issue records.',+ costClass: COST_LLM,+ longRunning: true,+ schema: z.object({ id: z.string().min(1), options: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ id: { type: 'string', description: 'Story session id.' },+ options: { type: 'object', description: 'Optional generation options.' },+ },+ required: ['id'],+ },+ execute: ({ id, options }) => generateIssuesFromArc(id, options || {}),+ },+];diff --git a/server/services/creative/tools/universe.js b/server/services/creative/tools/universe.jsnew file mode 100644index 0000000000..d775e8be88--- /dev/null+++ b/server/services/creative/tools/universe.js@@ -0,0 +1,59 @@+/**+ * Universe-domain creative tools (#2183). Conductor wrappers over existing+ * Universe Builder entry points — no re-implementation.+ */++import { z } from 'zod';+import { createUniverse } from '../../universeBuilder.js';+import { expandWorldTemplate } from '../../universeBuilderExpand.js';+import { renderUniverseJobs } from '../../universeBuilderRender.js';+import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';++export const UNIVERSE_TOOLS = [+ {+ name: 'universe.createUniverse',+ description: 'Create a new universe record (a creative world container). Persists a record; does not generate content.',+ costClass: COST_FREE,+ schema: z.object({ name: z.string().min(1) }).passthrough(),+ parameters: {+ type: 'object',+ properties: { name: { type: 'string', description: 'Universe name.' } },+ required: ['name'],+ },+ execute: (args) => createUniverse(args),+ },+ {+ name: 'universe.expandWorldTemplate',+ description: 'Expand a starter prompt into a universe bible (logline, premise, style, canon) via the configured LLM. Returns the parsed bible; does not persist.',+ costClass: COST_LLM,+ schema: z.object({ starterPrompt: z.string().min(1) }).passthrough(),+ parameters: {+ type: 'object',+ properties: {+ starterPrompt: { type: 'string', description: 'Seed prompt describing the world to expand.' },+ influences: { type: 'string', description: 'Optional comma-separated stylistic influences.' },+ providerId: { type: 'string', description: 'Optional LLM provider override.' },+ model: { type: 'string', description: 'Optional model override.' },+ },+ required: ['starterPrompt'],+ },+ execute: (args) => expandWorldTemplate(args),+ },+ {+ name: 'universe.renderUniverseJobs',+ description: "Enqueue a batch of image-generation jobs for a universe's canon/variations/composite sheets (requires local or codex image-gen mode). Long-running: returns job handles; completion arrives via media-job events.",+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ universeId: z.string().min(1), body: z.record(z.any()).optional() }),+ parameters: {+ type: 'object',+ properties: {+ universeId: { type: 'string', description: 'Universe id to render.' },+ body: { type: 'object', description: 'Render options (promptMode, selection, batchPerVariation, extraStyle, negativePrompt, stylePresetId, mode).' },+ },+ required: ['universeId'],+ },+ // mapServiceError is an identity rethrow — the dispatcher owns error surfacing.+ execute: ({ universeId, body }) => renderUniverseJobs(universeId, body || {}, (err) => err),+ },+];diff --git a/server/services/creative/tools/writersRoom.js b/server/services/creative/tools/writersRoom.jsnew file mode 100644index 0000000000..6f9f5096e5--- /dev/null+++ b/server/services/creative/tools/writersRoom.js@@ -0,0 +1,43 @@+/**+ * Writers-room-domain creative tools (#2183). Conductor wrappers over the+ * existing Writers Room entry points.+ */++import { z } from 'zod';+import { createWork } from '../../writersRoom/local.js';+import { runAnalysis } from '../../writersRoom/evaluator.js';+import { COST_FREE, COST_LLM } from './shared.js';++export const WRITERS_ROOM_TOOLS = [+ {+ name: 'writersRoom.createWork',+ description: 'Create a new writers-room work (short-story, novel, etc.). Persists a manifest; returns it.',+ costClass: COST_FREE,+ schema: z.object({ title: z.string().min(1), folderId: z.string().nullish(), kind: z.string().optional() }),+ parameters: {+ type: 'object',+ properties: {+ title: { type: 'string', description: 'Work title.' },+ folderId: { type: 'string', description: 'Optional parent folder id.' },+ kind: { type: 'string', description: "Work kind (default 'short-story')." },+ },+ required: ['title'],+ },+ execute: ({ title, folderId, kind }) => createWork({ title, folderId: folderId ?? null, kind }),+ },+ {+ name: 'writersRoom.runAnalysis',+ description: 'Run an editorial analysis pass (LLM) over a writers-room work and persist the result.',+ costClass: COST_LLM,+ schema: z.object({ workId: z.string().min(1), kind: z.string().optional() }),+ parameters: {+ type: 'object',+ properties: {+ workId: { type: 'string', description: 'Work id to analyze.' },+ kind: { type: 'string', description: 'Analysis kind.' },+ },+ required: ['workId'],+ },+ execute: ({ workId, kind }) => runAnalysis(workId, { kind }),+ },+];