@crasi/bisque-conductor 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/index.js +997 -0
- package/dist/index.js.map +7 -0
- package/dist/serve.js +735 -0
- package/dist/serve.js.map +7 -0
- package/dist/types/anthropic.d.ts +26 -0
- package/dist/types/app.d.ts +10 -0
- package/dist/types/conductor.d.ts +67 -0
- package/dist/types/env.d.ts +3 -0
- package/dist/types/fallback.d.ts +16 -0
- package/dist/types/gemini.d.ts +33 -0
- package/dist/types/index.d.ts +12 -0
- package/dist/types/limits.d.ts +29 -0
- package/dist/types/model.d.ts +90 -0
- package/dist/types/openai.d.ts +43 -0
- package/dist/types/prompt.d.ts +7 -0
- package/dist/types/proposals.d.ts +44 -0
- package/dist/types/registry.d.ts +44 -0
- package/dist/types/serve.d.ts +1 -0
- package/dist/types/usage.d.ts +49 -0
- package/package.json +62 -3
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/serve.ts", "../src/anthropic.ts", "../src/app.ts", "../src/conductor.ts", "../src/limits.ts", "../src/prompt.ts", "../src/proposals.ts", "../src/env.ts", "../src/registry.ts", "../src/usage.ts"],
|
|
4
|
+
"sourcesContent": ["import { serve } from \"@hono/node-server\";\nimport { ENV, PRODUCT } from \"@crasi/bisque-core\";\nimport { AnthropicProvider } from \"./anthropic\";\nimport { createConductorApp } from \"./app\";\nimport { appsFromEnv, limiterFromEnv } from \"./env\";\nimport { fileProposals } from \"./proposals\";\nimport { fileRegistry } from \"./registry\";\nimport { jsonlUsage } from \"./usage\";\n\n/**\n * Single-node conductor. Configuration:\n * BISQUE_APPS JSON array of { app, secretKey, allowedOrigins }, or\n * BISQUE_APP + BISQUE_SECRET_KEY + BISQUE_ALLOWED_ORIGINS (comma-separated)\n * BISQUE_MODEL defaults to claude-opus-5-5\n * BISQUE_DATA_DIR where pushed contracts and usage.jsonl live\n * BISQUE_PROPOSALS_DIR keeps open proposals in owner-only files here, not in\n * memory, so they survive a restart. They hold user prompts\n * until they expire.\n * BISQUE_LIMIT_USER_PER_MINUTE, BISQUE_LIMIT_TENANT_PER_MINUTE,\n * BISQUE_LIMIT_TENANT_TOKENS_PER_DAY override the limits in DEFAULT_LIMITS\n * ANTHROPIC_API_KEY the conductor's own provider key (decision D2)\n */\nconst dataDir = process.env.BISQUE_DATA_DIR ?? `.${PRODUCT.slug}-conductor`;\nconst port = Number(process.env.PORT ?? 8787);\nconst app = createConductorApp({\n registry: fileRegistry(appsFromEnv(), `${dataDir}/contracts`),\n model: new AnthropicProvider({ model: process.env[ENV.model] }),\n usage: jsonlUsage(`${dataDir}/usage.jsonl`),\n ...(process.env.BISQUE_PROPOSALS_DIR ? { proposals: fileProposals(process.env.BISQUE_PROPOSALS_DIR) } : {}),\n limiter: limiterFromEnv(),\n});\nserve({ fetch: app.fetch, port });\nconsole.log(`${PRODUCT.name} conductor on http://localhost:${port}`);\n", "import Anthropic from \"@anthropic-ai/sdk\";\nimport type { ModelBlock, ModelProvider, ModelRequest, ModelResponse } from \"./model\";\n\nexport const DEFAULT_MODEL = \"claude-opus-5-5\";\n\nexport type AnthropicProviderOptions = {\n /** Defaults to ANTHROPIC_API_KEY (or another credential the SDK resolves). */\n apiKey?: string;\n model?: string;\n /**\n * Server-side refusal fallback (`fallbacks: \"default\"`). On by default.\n * Turn it off if the host was promised zero data retention and the\n * fallback route could reach a model outside those terms (\u00A73.4).\n */\n fallbacks?: boolean;\n};\n\n/**\n * Claude via the official SDK. Non-streaming: proposals are small (Table 2:\n * \u22641.5k output tokens for a spec), and the conductor needs the whole tool\n * call before it can validate anything.\n */\nexport class AnthropicProvider implements ModelProvider {\n readonly name = \"anthropic\";\n private readonly client: Anthropic;\n readonly model: string;\n private readonly fallbacks: boolean;\n\n constructor(opts: AnthropicProviderOptions = {}) {\n this.client = new Anthropic(opts.apiKey ? { apiKey: opts.apiKey } : {});\n this.model = opts.model ?? DEFAULT_MODEL;\n this.fallbacks = opts.fallbacks ?? true;\n }\n\n async complete(req: ModelRequest): Promise<ModelResponse> {\n const system: Anthropic.Beta.BetaTextBlockParam[] = req.system.map((s) => ({\n type: \"text\",\n text: s.text,\n ...(s.cache ? { cache_control: { type: \"ephemeral\" as const } } : {}),\n }));\n const messages: Anthropic.Beta.BetaMessageParam[] = req.messages.map((m) => ({\n role: m.role,\n content: m.content.map(toParam),\n }));\n const tools: Anthropic.Beta.BetaTool[] = req.tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema as Anthropic.Beta.BetaTool.InputSchema,\n }));\n const response = await this.client.beta.messages.create({\n model: this.model,\n max_tokens: req.maxTokens,\n system,\n messages,\n tools,\n // Forced tool_choice is rejected on this model family; the system prompt asks for exactly one tool call.\n tool_choice: { type: \"auto\", disable_parallel_tool_use: true },\n output_config: { effort: req.effort },\n ...(this.fallbacks ? { betas: [\"server-side-fallback-2026-07-01\"], fallbacks: \"default\" as const } : {}),\n });\n return {\n content: response.content.map(fromBlock),\n stopReason: response.stop_reason ?? \"end_turn\",\n usage: {\n input: response.usage.input_tokens,\n output: response.usage.output_tokens,\n cacheRead: response.usage.cache_read_input_tokens ?? 0,\n cacheWrite: response.usage.cache_creation_input_tokens ?? 0,\n },\n model: response.model,\n provider: this.name,\n };\n }\n}\n\nfunction toParam(b: ModelBlock): Anthropic.Beta.BetaContentBlockParam {\n switch (b.type) {\n case \"text\":\n return { type: \"text\", text: b.text };\n case \"tool_use\":\n return { type: \"tool_use\", id: b.id, name: b.name, input: b.input as Record<string, unknown> };\n case \"tool_result\":\n return { type: \"tool_result\", tool_use_id: b.tool_use_id, content: b.content, is_error: b.is_error };\n case \"opaque\":\n return b.raw as Anthropic.Beta.BetaContentBlockParam;\n }\n}\n\nfunction fromBlock(b: Anthropic.Beta.BetaContentBlock): ModelBlock {\n if (b.type === \"text\") return { type: \"text\", text: b.text };\n if (b.type === \"tool_use\") return { type: \"tool_use\", id: b.id, name: b.name, input: b.input };\n // Thinking blocks and fallback markers go back to the API exactly as received.\n return { type: \"opaque\", raw: b };\n}\n", "import { Hono, type Context } from \"hono\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { cors } from \"hono/cors\";\nimport { HTTPException } from \"hono/http-exception\";\nimport { Conductor, ConductorError, type ConductorOptions } from \"./conductor\";\n\n/** A push carries a whole manifest; a proposal, at most 500 shared values per field and one draft. */\nconst DEFAULT_MAX_BODY_BYTES = 1024 * 1024;\n\nasync function readJson(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch (e) {\n // The size limit surfaces while the body is read, so it has to pass through.\n if (e instanceof HTTPException) throw e;\n throw new ConductorError(400, \"the request body is not valid JSON\");\n }\n}\n\n/**\n * HTTP surface of the conductor. A separate service, never inside the host's\n * process, so the custody boundary is real and testable (Appendix C.4).\n */\nexport function createConductorApp(\n opts: ConductorOptions & { conductor?: Conductor; maxBodyBytes?: number /** e.g. \"/api/bisque\" when mounted in a host route. */; basePath?: string },\n) {\n const conductor = opts.conductor ?? new Conductor(opts);\n const app = opts.basePath ? new Hono().basePath(opts.basePath.replace(/\\/$/, \"\")) : new Hono();\n\n app.use(\n \"/v1/*\",\n cors({\n // Preflights carry no credentials, so allow any origin some registered app lists.\n origin: (origin) => (opts.registry.apps().some((a) => a.allowedOrigins.includes(origin)) ? origin : null),\n allowHeaders: [\"authorization\", \"content-type\"],\n allowMethods: [\"POST\", \"GET\", \"OPTIONS\"],\n maxAge: 600,\n }),\n );\n app.use(\"/v1/*\", bodyLimit({ maxSize: opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES, onError: (c) => c.json({ error: \"the request body is too large\" }, 413) }));\n\n app.onError((err, c) => {\n if (err instanceof HTTPException) return err.getResponse();\n if (err instanceof ConductorError) {\n if (err.retryAfterSeconds) c.header(\"retry-after\", String(err.retryAfterSeconds));\n return c.json({ error: err.message, problems: err.problems }, err.status);\n }\n console.error(err);\n return c.json({ error: \"internal error\" }, 500);\n });\n\n app.get(\"/health\", (c) => c.json({ ok: true, model: opts.model.name }));\n\n app.post(\"/v1/apps/:app/contracts\", async (c) => c.json(await conductor.push(c.req.param(\"app\"), c.req.header(\"authorization\"), await readJson(c))));\n\n app.post(\"/v1/propose\", async (c) => {\n const claims = await conductor.authenticate(c.req.header(\"authorization\"));\n return c.json(await conductor.propose(claims, await readJson(c)));\n });\n\n app.post(\"/v1/proposals/:id/diagnostics\", async (c) => {\n const claims = await conductor.authenticate(c.req.header(\"authorization\"));\n return c.json(await conductor.diagnostics(claims, c.req.param(\"id\"), await readJson(c)));\n });\n\n return app;\n}\n", "import { constantTimeEqual, formatProblems, verifyToken, type Problem, type TokenClaims } from \"@crasi/bisque-core\";\nimport { contractHash, sharedFieldKeys, type ContractManifest } from \"@crasi/bisque-contract\";\nimport {\n DiagnosticsSchema,\n PushRequestSchema,\n ProposeRequestSchema,\n repairReason,\n validateAutomation,\n validateDraft,\n validateThemeTokens,\n type DiagnosticsResponse,\n type ProposeResponse,\n} from \"@crasi/bisque-spec\";\nimport { memoryLimiter, type LimitReason, type Limiter } from \"./limits\";\nimport type { CallType, Effort, ModelBlock, ModelMessage, ModelProvider, ModelRequest, ModelResponse } from \"./model\";\nimport { systemBlocks, TOOLS } from \"./prompt\";\nimport { memoryProposals, type ProposalStore } from \"./proposals\";\nimport type { ContractRegistry } from \"./registry\";\nimport type { UsageSink } from \"./usage\";\n\nexport type ConductorOptions = {\n registry: ContractRegistry;\n model: ModelProvider;\n usage?: UsageSink;\n /**\n * Called before every user-initiated model call (not repairs). Return a\n * message to refuse it, e.g. a plan without the feature or a daily cap.\n */\n admit?: (claims: TokenClaims, callType: CallType) => Promise<string | null> | string | null;\n maxTokens?: number;\n effort?: Partial<Record<CallType, Effort>>;\n /** How long a proposal stays open for its diagnostics repair. */\n proposalTtlMs?: number;\n /** Where open proposals wait for diagnostics. Defaults to one process's memory; use a shared store on serverless hosts. See {@link ProposalStore}. */\n proposals?: ProposalStore;\n /** Rate limits and token budgets. Defaults to `memoryLimiter()`; `false` turns them off. */\n limiter?: Limiter | false;\n now?: () => number;\n};\n\nexport class ConductorError extends Error {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422 | 429 | 503,\n message: string,\n readonly problems?: { path: string; message: string }[],\n readonly retryAfterSeconds?: number,\n ) {\n super(message);\n }\n}\n\nfunction limitMessage(reason: LimitReason, retryAfterSeconds: number): string {\n if (reason === \"tenant_budget\") return \"This workspace has reached today's limit for the assistant. Try again tomorrow.\";\n return `Too many requests. Try again in ${retryAfterSeconds} seconds.`;\n}\n\n// Unguessable, so a proposal id alone gives nothing; ownership is still checked.\nconst proposalId = () => `p_${crypto.randomUUID()}`;\n\ntype Outcome = \"proposal\" | \"theme\" | \"automation\" | \"ask\" | \"answer\" | \"limit\" | \"invalid\" | \"error\";\n\ntype TurnCtx = { claims: TokenClaims; m: ContractManifest; hash: string; system: ModelRequest[\"system\"]; automations: boolean };\n\n/**\n * The conductor (Fig. 3). Propose-only: it has no tool that writes host data\n * or saves an artifact (Invariant 2). It validates every proposal with the\n * same validator the host runs, gives the model one repair turn, and returns\n * the result for the host to re-validate and preview.\n */\nexport class Conductor {\n private readonly o: Required<Omit<ConductorOptions, \"usage\" | \"effort\" | \"limiter\" | \"admit\">> &\n Pick<ConductorOptions, \"usage\" | \"admit\"> & { effort: Record<CallType, Effort>; limiter: Limiter | false };\n\n constructor(opts: ConductorOptions) {\n this.o = {\n maxTokens: 16_000,\n proposalTtlMs: 30 * 60_000,\n now: Date.now,\n ...opts,\n proposals: opts.proposals ?? memoryProposals(),\n limiter: opts.limiter ?? memoryLimiter(),\n effort: { spec: \"medium\", refine: \"low\", repair: \"medium\", ...opts.effort },\n };\n }\n\n /** Verifies a session token minted by the host's token route. */\n async authenticate(authorization: string | undefined): Promise<TokenClaims> {\n const token = authorization?.replace(/^Bearer\\s+/i, \"\");\n if (!token) throw new ConductorError(401, \"missing session token\");\n const unverified = decodeApp(token);\n const app = unverified && this.o.registry.app(unverified);\n if (!app) throw new ConductorError(401, \"unknown app\");\n const v = await verifyToken(token, app.secretKey, this.o.now());\n if (!v.ok) throw new ConductorError(401, `session token ${v.error}`);\n return v.claims;\n }\n\n /** `bisque push`: stores a contract manifest, only with a review signed for exactly this hash. */\n async push(app: string, secret: string | undefined, body: unknown): Promise<{ hash: string; version: string }> {\n const cfg = this.o.registry.app(app);\n if (!cfg || !secret || !constantTimeEqual(secret.replace(/^Bearer\\s+/i, \"\"), cfg.secretKey)) throw new ConductorError(401, \"bad secret key\");\n const parsed = PushRequestSchema.safeParse(body);\n if (!parsed.success) throw new ConductorError(400, \"bad push body\");\n const manifest = parsed.data.manifest as unknown as ContractManifest;\n if (manifest.app !== app) throw new ConductorError(400, \"manifest is for another app\");\n const hash = await contractHash(manifest);\n if (parsed.data.review.contractHash !== hash) throw new ConductorError(422, \"the review sheet was signed for a different contract; run bisque review --sign again\");\n await this.o.registry.put({ manifest, hash, review: parsed.data.review, pushedAt: new Date(this.o.now()).toISOString() });\n return { hash, version: manifest.version };\n }\n\n async propose(claims: TokenClaims, body: unknown): Promise<ProposeResponse> {\n const parsed = ProposeRequestSchema.safeParse(body);\n if (!parsed.success)\n throw new ConductorError(\n 400,\n \"bad request\",\n parsed.error.issues.map((i) => ({ path: i.path.join(\".\"), message: i.message })),\n );\n const req = parsed.data;\n if (req.contract.app !== claims.app) throw new ConductorError(403, \"token is for another app\");\n await this.enforceLimits(claims);\n const stored = await this.o.registry.get(req.contract.app, req.contract.hash);\n if (!stored) throw new ConductorError(409, \"contract not pushed; run bisque push\");\n const m = stored.manifest;\n\n // Custody guard, defence in depth behind the provider (P1): only declared\n // context keys, only host-shared fields, only declared theme tokens,\n // nothing else from the page.\n for (const k of Object.keys(req.context.values)) if (!m.context[k]) throw new ConductorError(400, `context \"${k}\" is not declared by the contract`);\n const shareable = new Set(sharedFieldKeys(m));\n for (const k of Object.keys(req.sharedValues ?? {})) if (!shareable.has(k)) throw new ConductorError(400, `${k} is not a shared field`);\n for (const k of Object.keys(req.theme ?? {})) if (!m.theme?.[k]) throw new ConductorError(400, `theme token \"${k}\" is not declared by the contract`);\n if (req.context.slot && !m.slots[req.context.slot]) throw new ConductorError(400, `unknown slot ${req.context.slot}`);\n\n const callType: CallType = req.current || req.currentAutomation ? \"refine\" : \"spec\";\n const automations = !!req.automations && !!m.automations;\n const refused = await this.o.admit?.(claims, callType);\n if (refused) return { type: \"error\", message: refused };\n\n const system = systemBlocks(m, req.sharedValues);\n const messages: ModelMessage[] = [];\n for (const h of req.history) messages.push({ role: h.role, content: [{ type: \"text\", text: h.text }] });\n if (messages[0]?.role === \"assistant\") messages.unshift({ role: \"user\", content: [{ type: \"text\", text: \"(earlier conversation)\" }] });\n const turn = [\n `Context: ${JSON.stringify({ page: req.context.page ?? null, slot: req.context.slot ?? null, locale: req.context.locale, role: claims.role, ...(m.automations ? { automations: automations ? \"on\" : \"off\" } : {}), ...req.context.values })}`,\n req.theme ? `Current theme: ${JSON.stringify(req.theme)}` : \"\",\n req.current ? `Current draft (revise this):\\n${JSON.stringify(req.current)}` : \"\",\n req.currentAutomation ? `Current automation (revise this):\\n${JSON.stringify(req.currentAutomation)}` : \"\",\n `User: ${req.prompt}`,\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n messages.push({ role: \"user\", content: [{ type: \"text\", text: turn }] });\n return this.turn({ claims, m, hash: stored.hash, system, automations }, messages, callType, 1);\n }\n\n private async enforceLimits(claims: TokenClaims) {\n if (!this.o.limiter) return;\n const d = await this.o.limiter.check(claims, this.o.now());\n if (d.ok) return;\n await this.o.usage?.record({ kind: \"limited\", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, reason: d.reason });\n throw new ConductorError(429, limitMessage(d.reason, d.retryAfterSeconds), undefined, d.retryAfterSeconds);\n }\n\n private async call(claims: TokenClaims, system: ModelRequest[\"system\"], messages: ModelMessage[], callType: CallType) {\n const t0 = this.o.now();\n let res: ModelResponse;\n try {\n res = await this.o.model.complete({ system, messages, tools: TOOLS, effort: this.o.effort[callType], maxTokens: this.o.maxTokens, callType });\n } catch (e) {\n // Status and class only: a provider's error text can echo the request.\n const status = (e as { status?: unknown }).status;\n await this.o.usage?.record({\n kind: \"model_error\",\n at: new Date(this.o.now()).toISOString(),\n app: claims.app,\n tenant: claims.tenant,\n callType,\n provider: this.o.model.name,\n latencyMs: this.o.now() - t0,\n status: typeof status === \"number\" ? status : null,\n error: e instanceof Error ? e.constructor.name : \"unknown\",\n });\n throw new ConductorError(503, \"The assistant is unavailable right now. Try again shortly.\");\n }\n if (this.o.limiter) await this.o.limiter.spend(claims, res.usage.input + res.usage.output + res.usage.cacheWrite, this.o.now());\n return { res, latencyMs: this.o.now() - t0 };\n }\n\n private async log(claims: TokenClaims, callType: CallType, res: ModelResponse, latencyMs: number, outcome: Outcome) {\n await this.o.usage?.record({\n kind: \"model_call\",\n at: new Date(this.o.now()).toISOString(),\n app: claims.app,\n tenant: claims.tenant,\n callType,\n model: res.model,\n ...(res.provider ? { provider: res.provider } : {}),\n latencyMs,\n outcome,\n ...res.usage,\n });\n }\n\n /** One repair turn: the host's problems go back to the model as the tool's error result. */\n private async repair(c: TurnCtx, history: ModelMessage[], toolId: string, tool: string, problems: Problem[], repairsLeft: number): Promise<ProposeResponse> {\n if (repairsLeft <= 0) return { type: \"error\", message: \"The proposal did not pass validation.\", problems: problems.map(({ path, message }) => ({ path, message })) };\n history.push({\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n tool_use_id: toolId,\n is_error: true,\n content: `The host rejected this proposal:\\n${formatProblems(problems)}\\nFix these problems and call ${tool} again with the complete proposal, or use explain_limit if it cannot be done.`,\n },\n ],\n });\n const repaired = await this.turn(c, history, \"repair\", repairsLeft - 1);\n return repaired.type === \"proposal\" || repaired.type === \"theme\" || repaired.type === \"automation\" ? { ...repaired, repaired: true } : repaired;\n }\n\n private async turn(c: TurnCtx, messages: ModelMessage[], callType: CallType, repairsLeft: number): Promise<ProposeResponse> {\n const { claims, m } = c;\n const { res, latencyMs } = await this.call(claims, c.system, messages, callType);\n if (res.stopReason === \"refusal\") {\n await this.log(claims, callType, res, latencyMs, \"error\");\n return { type: \"error\", message: \"The assistant declined this request.\" };\n }\n const tool = res.content.find((b): b is Extract<ModelBlock, { type: \"tool_use\" }> => b.type === \"tool_use\");\n const text = res.content\n .filter((b): b is Extract<ModelBlock, { type: \"text\" }> => b.type === \"text\")\n .map((b) => b.text)\n .join(\"\\n\")\n .trim();\n if (!tool) {\n await this.log(claims, callType, res, latencyMs, \"answer\");\n return text ? { type: \"answer\", text } : { type: \"error\", message: \"No proposal came back. Try rephrasing.\" };\n }\n const input = (tool.input ?? {}) as Record<string, unknown>;\n const note = typeof input.note === \"string\" ? input.note.slice(0, 300) : undefined;\n const history: ModelMessage[] = [...messages, { role: \"assistant\", content: res.content }];\n switch (tool.name) {\n case \"ask\":\n await this.log(claims, callType, res, latencyMs, \"ask\");\n return { type: \"ask\", question: String(input.question ?? \"\"), options: Array.isArray(input.options) ? input.options.map(String).slice(0, 4) : [] };\n case \"explain_limit\": {\n await this.log(claims, callType, res, latencyMs, \"limit\");\n const capability = String(input.capability ?? \"unspecified\").slice(0, 80);\n await this.o.usage?.record({ kind: \"ceiling\", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, capability });\n return { type: \"limit\", message: String(input.message ?? \"\"), capability, nearest: input.nearest ? String(input.nearest) : undefined };\n }\n case \"propose_theme\": {\n const v = validateThemeTokens(input.tokens, m, { role: claims.role });\n if (!v.ok) {\n await this.log(claims, callType, res, latencyMs, \"invalid\");\n return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);\n }\n await this.log(claims, callType, res, latencyMs, \"theme\");\n // Nothing to diagnose for a theme: the host previews it on its own chrome.\n return { type: \"theme\", proposalId: proposalId(), tokens: v.tokens, repaired: false, note };\n }\n case \"propose_automation\": {\n if (!c.automations) {\n await this.log(claims, callType, res, latencyMs, \"limit\");\n await this.o.usage?.record({ kind: \"ceiling\", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, capability: \"automations\" });\n return { type: \"limit\", message: \"Automations are not available here.\", capability: \"automations\" };\n }\n const v = validateAutomation(input.automation, m, { role: claims.role });\n if (!v.ok || !v.automation) {\n await this.log(claims, callType, res, latencyMs, \"invalid\");\n return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);\n }\n await this.log(claims, callType, res, latencyMs, \"automation\");\n // No render diagnostics: the composer shows what matches today, and nothing else comes back.\n return { type: \"automation\", proposalId: proposalId(), automation: v.automation, repaired: false, note };\n }\n case \"propose_spec\": {\n const v = validateDraft(input.draft, m, { role: claims.role });\n if (!v.ok || !v.draft) {\n await this.log(claims, callType, res, latencyMs, \"invalid\");\n return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);\n }\n await this.log(claims, callType, res, latencyMs, \"proposal\");\n const id = proposalId();\n await this.o.proposals.put(\n id,\n {\n claims,\n contract: { app: m.app, hash: c.hash },\n system: c.system,\n messages: history,\n toolUseId: tool.id,\n draft: v.draft,\n repairsLeft,\n expires: this.o.now() + this.o.proposalTtlMs,\n },\n this.o.now(),\n );\n return { type: \"proposal\", proposalId: id, draft: v.draft, repaired: false, note };\n }\n default:\n await this.log(claims, callType, res, latencyMs, \"error\");\n return { type: \"error\", message: `unknown tool ${tool.name}` };\n }\n }\n\n /**\n * Render diagnostics from the host's preview (\u00A76.8). Strictly bucketed; the\n * conductor rejects anything else. May spend the proposal's one repair turn.\n */\n async diagnostics(claims: TokenClaims, id: string, body: unknown): Promise<DiagnosticsResponse> {\n const p = await this.o.proposals.get(id);\n if (!p || p.expires < this.o.now()) throw new ConductorError(404, \"unknown or expired proposal\");\n if (p.claims.app !== claims.app || p.claims.tenant !== claims.tenant || p.claims.sub !== claims.sub) throw new ConductorError(403, \"not your proposal\");\n const parsed = DiagnosticsSchema.safeParse(body);\n if (!parsed.success) throw new ConductorError(400, \"diagnostics must be bucketed counts only\");\n const d = parsed.data;\n // Keys must be column names of this proposal's query: never values.\n const columns = new Set([...(p.draft.body.data.groupBy ?? []), ...(p.draft.body.data.select ?? []), ...(p.draft.body.data.measures ?? []).map((x) => x.as)]);\n for (const k of [...Object.keys(d.distinct), ...Object.keys(d.nullShare)])\n if (!columns.has(k)) throw new ConductorError(400, `diagnostics key ${k} is not a column of the proposal`);\n const reason = repairReason(d);\n if (!reason) return { type: \"ok\" };\n if (p.repairsLeft <= 0) return { type: \"ok\", note: \"repair budget used\" };\n const stored = await this.o.registry.get(p.contract.app, p.contract.hash);\n if (!stored) return { type: \"ok\", note: \"contract no longer available\" };\n await this.enforceLimits(claims);\n await this.o.proposals.delete(id);\n const messages: ModelMessage[] = [\n ...p.messages,\n {\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n tool_use_id: p.toolUseId,\n is_error: true,\n content: `The preview rendered, but: ${reason}. Shape seen: ${JSON.stringify({ rows: d.rows, distinct: d.distinct, nullShare: d.nullShare, renderErrors: d.renderErrors })}. Propose a corrected complete draft, or ask the user if you cannot tell what they meant.`,\n },\n ],\n },\n ];\n const r = await this.turn({ claims, m: stored.manifest, hash: stored.hash, system: p.system, automations: false }, messages, \"repair\", 0);\n if (r.type === \"proposal\") return { ...r, repaired: true };\n if (r.type === \"error\") return r;\n return { type: \"ok\", note: r.type === \"answer\" ? r.text : undefined };\n }\n}\n\nfunction decodeApp(token: string): string | undefined {\n try {\n const payload = token.split(\".\")[1];\n const json = JSON.parse(atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\")));\n return typeof json.app === \"string\" ? json.app : undefined;\n } catch {\n return undefined;\n }\n}\n", "import type { TokenClaims } from \"@crasi/bisque-core\";\n\nexport type LimitReason = \"user_rate\" | \"tenant_rate\" | \"tenant_budget\";\nexport type LimitDecision = { ok: true } | { ok: false; reason: LimitReason; retryAfterSeconds: number };\n\n/**\n * What stands between a session token and the model bill. The conductor asks\n * before every request that may call the model, and reports the tokens each\n * call spent. Implement this over a shared store to limit across instances.\n */\nexport interface Limiter {\n check(claims: TokenClaims, now: number): LimitDecision | Promise<LimitDecision>;\n spend(claims: TokenClaims, tokens: number, now: number): void | Promise<void>;\n}\n\nexport type LimitOptions = {\n /** Requests per minute for one user. */\n userPerMinute?: number;\n /** Requests per minute for one tenant, across its users. */\n tenantPerMinute?: number;\n /** Tokens per UTC day for one tenant. */\n tenantTokensPerDay?: number;\n};\n\nexport const DEFAULT_LIMITS: Required<LimitOptions> = { userPerMinute: 20, tenantPerMinute: 120, tenantTokensPerDay: 5_000_000 };\n\nconst MINUTE = 60_000;\nconst DAY = 86_400_000;\nconst MAX_TRACKED_KEYS = 10_000;\n\n/** Per-process limits: each instance of the conductor counts on its own. */\nexport function memoryLimiter(opts: LimitOptions = {}): Limiter {\n const o = { ...DEFAULT_LIMITS, ...opts };\n const hits = new Map<string, number[]>();\n const spent = new Map<string, { day: number; tokens: number }>();\n\n const recent = (key: string, now: number) => (hits.get(key) ?? []).filter((t) => now - t < MINUTE);\n const prune = (now: number) => {\n if (hits.size > MAX_TRACKED_KEYS) for (const [k, ts] of hits) if (!ts.some((t) => now - t < MINUTE)) hits.delete(k);\n const day = Math.floor(now / DAY);\n if (spent.size > MAX_TRACKED_KEYS) for (const [k, s] of spent) if (s.day !== day) spent.delete(k);\n };\n const retryAfter = (ts: number[], now: number) => Math.max(1, Math.ceil((ts[0] + MINUTE - now) / 1000));\n\n return {\n check(claims, now) {\n prune(now);\n const tenantKey = `${claims.app}/${claims.tenant}`;\n const day = Math.floor(now / DAY);\n const budget = spent.get(tenantKey);\n if (budget?.day === day && budget.tokens >= o.tenantTokensPerDay) return { ok: false, reason: \"tenant_budget\", retryAfterSeconds: Math.ceil(((day + 1) * DAY - now) / 1000) };\n const userKey = `${tenantKey}/${claims.sub}`;\n const user = recent(userKey, now);\n if (user.length >= o.userPerMinute) return { ok: false, reason: \"user_rate\", retryAfterSeconds: retryAfter(user, now) };\n const tenant = recent(tenantKey, now);\n if (tenant.length >= o.tenantPerMinute) return { ok: false, reason: \"tenant_rate\", retryAfterSeconds: retryAfter(tenant, now) };\n hits.set(userKey, [...user, now]);\n hits.set(tenantKey, [...tenant, now]);\n return { ok: true };\n },\n spend(claims, tokens, now) {\n const key = `${claims.app}/${claims.tenant}`;\n const day = Math.floor(now / DAY);\n const s = spent.get(key);\n spent.set(key, { day, tokens: (s?.day === day ? s.tokens : 0) + tokens });\n },\n };\n}\n", "import { buildReference, sharedValuesSection, type ContractManifest, type SharedValues } from \"@crasi/bisque-contract\";\nimport { AUTOMATION_GUIDE, CATALOG_LINE, SPEC_GUIDE } from \"@crasi/bisque-spec\";\nimport type { ModelTool } from \"./model\";\n\n/**\n * Static instructions. Byte-stable: they sit in front of the cached\n * reference, and a changed byte would invalidate the cache for every host.\n */\nconst INSTRUCTIONS = `You are the authoring assistant built into a business application (the host). End users describe a view or a small tool they want, and you propose it as a declarative spec that the host validates, previews on the user's own data, and saves only when the user clicks Apply.\n\nWhat you can see: the host's contract (resources, fields, references, glossary, intents, slots), lookup values the host chose to share, the user's words, and page context. You never see the host's records, and nothing you write runs as code. Your tools only propose; you cannot save or change anything.\n\nAnswer every turn with exactly one tool call, except plain how-to questions, which you answer in one or two sentences of text:\n- propose_spec when you can build what was asked. Give the complete draft, including manifest and placement.\n- propose_theme when the user asks to change how the app looks (colours, corners, font, spacing) and the reference lists theme tokens. Give only the tokens that change, with values of the listed types. The theme is workspace-wide: if the context role cannot change it, use explain_limit instead.\n- propose_automation when the user wants something checked or done on a schedule or in the background (\"email me when\u2026\", \"every Monday\u2026\", \"remind me if\u2026\", \"whenever X, do Y\") and the reference lists automations and the context says automations: on. Give the complete automation. Delivery is always to the user who asks; never ask for an address.\n- ask when one genuine ambiguity blocks you and the glossary does not settle it. Offer 2\u20134 short options.\n- explain_limit when the request needs something the contract does not offer: sending email or messages, schedules or background jobs (unless propose_automation applies), messages to anyone other than the user, network access or outside data, resources or fields that are not listed, writes for which no intent exists, changing the host's own calculations, or permission changes. Say plainly what the host does not allow and name the nearest thing you can build inside it.\n\nRules for drafts:\n1. Use only resources, fields, references, intents, navigations, slots and context listed in the reference. Never invent names.\n2. Use the glossary. If a term is defined there (for example \"sales\"), follow the definition without asking.\n3. Prefer a derived resource over recomputing a number the host already computes.\n4. For any name the user mentions (customers, products, accounts), filter with \"match\" and the user's own words. Names under \"values(...)\" are real and may be used as written.\n5. When the slot provides page context (for example month), bind a param to it with \"host.context.<key>\" so the view follows the page, unless the user asks for a fixed value.\n6. Place the artifact in the slot the user started from (given in context) unless they ask for another place. Tools with actions that need room become pages in nav.primary with a short label.\n7. Write title and labels for every host locale listed in the reference.\n8. Keep queries small and readable: a sensible limit, sort by the measure, and otherBucket when there may be many categories.\n9. When a current draft is given, return the whole revised draft and change only what the user asked for.\n10. manifest.reads lists exactly the resources the query touches; manifest.acts lists exactly the intents the spec invokes.\n\nThis is latency-sensitive: keep reasoning brief and go straight to the tool call.`;\n\nexport const TOOLS: ModelTool[] = [\n {\n name: \"propose_spec\",\n description:\n \"Propose an L1 spec artifact. The host validates it, renders a live preview on the user's data and shows Apply / Discard. Nothing is saved until the user applies it.\",\n input_schema: {\n type: \"object\",\n properties: {\n draft: { type: \"object\", description: 'The complete draft: { kind: \"spec\", body, manifest, placement } as described in the spec format.' },\n note: { type: \"string\", description: \"Optional, at most one short sentence to the user, e.g. what you assumed. Do not describe the chart; the host does that.\" },\n },\n required: [\"draft\"],\n },\n },\n {\n name: \"propose_theme\",\n description: \"Propose new values for the host's theme tokens. The host validates them, previews them on its own interface and applies them only when the user clicks Apply.\",\n input_schema: {\n type: \"object\",\n properties: {\n tokens: {\n type: \"object\",\n description: \"Token name to value, only for tokens that change. Colours are hex like #0f5c8a; options are exactly as listed.\",\n additionalProperties: { type: \"string\" },\n },\n note: { type: \"string\", description: \"Optional, at most one short sentence to the user. Do not list the changes; the host does that.\" },\n },\n required: [\"tokens\"],\n },\n },\n {\n name: \"propose_automation\",\n description:\n \"Propose an automation: a query the host checks on a schedule, and one action (notify the user on a declared channel, or run an automatable intent). The host validates it, shows what matches today and saves it only when the user clicks Apply.\",\n input_schema: {\n type: \"object\",\n properties: {\n automation: { type: \"object\", description: \"The complete automation as described in the automation format.\" },\n note: { type: \"string\", description: \"Optional, at most one short sentence to the user, e.g. what you assumed. Do not describe the rule; the host does that.\" },\n },\n required: [\"automation\"],\n },\n },\n {\n name: \"ask\",\n description: \"Ask one clarifying question when a real ambiguity blocks the proposal.\",\n input_schema: {\n type: \"object\",\n properties: {\n question: { type: \"string\" },\n options: { type: \"array\", items: { type: \"string\" }, minItems: 2, maxItems: 4 },\n },\n required: [\"question\", \"options\"],\n },\n },\n {\n name: \"explain_limit\",\n description: \"Explain that the request is above what the host allows, and offer the nearest thing that is possible. The request is logged as demand for the host's roadmap.\",\n input_schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\", description: \"Two sentences at most, to the user.\" },\n capability: { type: \"string\", description: 'Short label for the missing capability, e.g. \"scheduled email\", \"external data\", \"delete orders\".' },\n nearest: { type: \"string\", description: 'The closest thing you can build, as a request the user can accept, e.g. \"A Run-outs, next 4 weeks view in the sidebar\".' },\n },\n required: [\"message\", \"capability\"],\n },\n },\n];\n\nexport function systemBlocks(m: ContractManifest, sharedValues?: SharedValues): { text: string; cache?: boolean }[] {\n const reference = `# Host reference\\n\\n${buildReference(m)}\\n\\n${CATALOG_LINE}`;\n const guides = m.automations ? `${SPEC_GUIDE}\\n\\n${AUTOMATION_GUIDE}` : SPEC_GUIDE;\n const blocks: { text: string; cache?: boolean }[] = [{ text: `${INSTRUCTIONS}\\n\\n${guides}\\n\\n${reference}`, cache: true }];\n const shared = sharedValues ? sharedValuesSection(sharedValues) : \"\";\n // Per-tenant but stable across turns: its own breakpoint keeps the shared prefix reusable across tenants.\n if (shared) blocks.push({ text: `# Shared lookup values\\n\\n${shared}`, cache: true });\n return blocks;\n}\n", "import { chmod, mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { TokenClaims } from \"@crasi/bisque-core\";\nimport type { Draft } from \"@crasi/bisque-spec\";\nimport type { ModelMessage, ModelRequest } from \"./model\";\n\n/**\n * A proposal waiting for its diagnostics round: the conversation so far, so a\n * repair turn can continue it. Plain JSON, so a host running the conductor on\n * serverless functions can keep it in its own database.\n */\nexport type OpenProposal = {\n claims: TokenClaims;\n /** The contract the proposal was made against; the manifest is read back from the registry. */\n contract: { app: string; hash: string };\n system: ModelRequest[\"system\"];\n messages: ModelMessage[];\n toolUseId: string;\n draft: Draft;\n repairsLeft: number;\n /** Epoch milliseconds. */\n expires: number;\n};\n\n/**\n * Where open proposals wait. In memory by default, which is enough for one\n * instance: losing one only means its preview gets no repair turn, since\n * diagnostics are best effort. Several instances need a store they share.\n * Implementations must return plain JSON values, and the conductor checks\n * `expires` itself, so purging is only housekeeping.\n */\nexport interface ProposalStore {\n get(id: string): Promise<OpenProposal | undefined>;\n put(id: string, p: OpenProposal, now: number): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\nexport function memoryProposals(max = 10_000): ProposalStore {\n const open = new Map<string, OpenProposal>();\n return {\n get: async (id) => open.get(id),\n async put(id, p, now) {\n for (const [k, v] of open) if (v.expires < now) open.delete(k);\n open.set(id, p);\n // A Map iterates oldest first, so the oldest open proposal goes first.\n for (const k of open.keys()) {\n if (open.size <= max) break;\n open.delete(k);\n }\n },\n delete: async (id) => void open.delete(id),\n };\n}\n\n/** The name hosts built against the canon-integration branch used. */\nexport const memoryProposalStore = memoryProposals;\n\n/** Ids reach this store from a URL, so anything else is refused before it can name a path. */\nconst SAFE_ID = /^p_[0-9a-f-]{36}$/;\nconst PURGE_EVERY_MS = 60_000;\n\n/**\n * One owner-only file per proposal, for surviving restarts or sharing a\n * volume between instances. These files hold the user's prompts and the\n * shared values until the proposal expires, so keep the directory private.\n */\nexport function fileProposals(dir: string): ProposalStore {\n const path = (id: string) => join(dir, `${id}.json`);\n let ready: Promise<unknown> | null = null;\n let lastPurge = 0;\n const purge = async (now: number) => {\n if (now - lastPurge < PURGE_EVERY_MS) return;\n lastPurge = now;\n for (const f of await readdir(dir)) {\n const file = join(dir, f);\n try {\n if ((JSON.parse(await readFile(file, \"utf8\")) as OpenProposal).expires < now) await rm(file, { force: true });\n } catch {\n // Another instance removed it, or it is mid-write: the next purge decides.\n }\n }\n };\n return {\n async get(id) {\n if (!SAFE_ID.test(id)) return undefined;\n try {\n return JSON.parse(await readFile(path(id), \"utf8\")) as OpenProposal;\n } catch {\n return undefined;\n }\n },\n async put(id, p, now) {\n if (!SAFE_ID.test(id)) throw new Error(`bad proposal id ${id}`);\n ready ??= mkdir(dir, { recursive: true, mode: 0o700 }).then(() => chmod(dir, 0o700));\n await ready;\n await writeFile(path(id), JSON.stringify(p), { mode: 0o600 });\n await purge(now);\n },\n async delete(id) {\n if (SAFE_ID.test(id)) await rm(path(id), { force: true });\n },\n };\n}\n", "import { ENV } from \"@crasi/bisque-core\";\nimport { memoryLimiter } from \"./limits\";\nimport type { AppConfig } from \"./registry\";\n\nexport function appsFromEnv(): AppConfig[] {\n if (process.env.BISQUE_APPS) return JSON.parse(process.env.BISQUE_APPS);\n const app = process.env.BISQUE_APP;\n const secretKey = process.env[ENV.secretKey];\n if (!app || !secretKey) throw new Error(`Set BISQUE_APPS, or BISQUE_APP and ${ENV.secretKey}`);\n return [{ app, secretKey, allowedOrigins: (process.env.BISQUE_ALLOWED_ORIGINS ?? \"\").split(\",\").filter(Boolean) }];\n}\n\nfunction positiveInt(name: string): number | undefined {\n const raw = process.env[name];\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isInteger(n) || n <= 0) throw new Error(`${name} must be a positive whole number`);\n return n;\n}\n\nconst withValue = <K extends string>(k: K, v: number | undefined) => (v === undefined ? {} : ({ [k]: v } as Record<K, number>));\n\nexport function limiterFromEnv() {\n return memoryLimiter({\n ...withValue(\"userPerMinute\", positiveInt(\"BISQUE_LIMIT_USER_PER_MINUTE\")),\n ...withValue(\"tenantPerMinute\", positiveInt(\"BISQUE_LIMIT_TENANT_PER_MINUTE\")),\n ...withValue(\"tenantTokensPerDay\", positiveInt(\"BISQUE_LIMIT_TENANT_TOKENS_PER_DAY\")),\n });\n}\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { contractHash, type ContractManifest } from \"@crasi/bisque-contract\";\nimport { ConductorError } from \"./conductor\";\n\nexport type AppConfig = {\n app: string;\n /** BISQUE_SECRET_KEY: signs session tokens and authorizes `bisque push`. */\n secretKey: string;\n /** Origins allowed to call the conductor from a browser (the host app). */\n allowedOrigins: string[];\n};\n\nexport type ReviewRecord = { contractHash: string; signer: string; signedAt: string; [k: string]: unknown };\nexport type StoredContract = { manifest: ContractManifest; hash: string; review: ReviewRecord; pushedAt: string };\n\n/** Pushed contracts, keyed by app and hash. Contracts only: no data, no artifacts. */\nexport interface ContractRegistry {\n app(app: string): AppConfig | undefined;\n apps(): AppConfig[];\n get(app: string, hash: string): Promise<StoredContract | undefined>;\n put(c: StoredContract): Promise<void>;\n}\n\nexport function memoryRegistry(apps: AppConfig[]): ContractRegistry {\n const contracts = new Map<string, StoredContract>();\n const byApp = new Map(apps.map((a) => [a.app, a]));\n return {\n app: (a) => byApp.get(a),\n apps: () => [...byApp.values()],\n get: async (app, hash) => contracts.get(`${app}/${hash}`),\n put: async (c) => void contracts.set(`${c.manifest.app}/${c.hash}`, c),\n };\n}\n\n/** File-backed registry for a single-node deployment: `<dir>/<app>/<hash>.json`. */\nexport function fileRegistry(apps: AppConfig[], dir: string): ContractRegistry {\n const mem = memoryRegistry(apps);\n return {\n app: mem.app,\n apps: mem.apps,\n async get(app, hash) {\n const hit = await mem.get(app, hash);\n if (hit) return hit;\n if (!/^[0-9a-f]{64}$/.test(hash) || !/^[\\w.-]+$/.test(app)) return undefined;\n try {\n const c = JSON.parse(await readFile(join(dir, app, `${hash}.json`), \"utf8\")) as StoredContract;\n await mem.put(c);\n return c;\n } catch {\n return undefined;\n }\n },\n async put(c) {\n await mem.put(c);\n await mkdir(join(dir, c.manifest.app), { recursive: true });\n await writeFile(join(dir, c.manifest.app, `${c.hash}.json`), JSON.stringify(c, null, 2));\n },\n };\n}\n\nexport type StaticContract = { manifest: ContractManifest; review: ReviewRecord | null };\n\n/**\n * For a conductor running inside the host (a route handler): the contracts\n * come from the host's own bundle instead of `bisque push`, but the rule is\n * the same. A contract is served only when its review sheet is signed for\n * exactly its hash, unless `requireSignature` is off (development only).\n */\nexport function staticRegistry(\n apps: AppConfig[],\n contracts: StaticContract[],\n opts: { requireSignature?: boolean; onUnsigned?: (app: string, hash: string) => void } = {},\n): ContractRegistry {\n const mem = memoryRegistry(apps);\n const requireSignature = opts.requireSignature ?? true;\n /** Bundled contracts refused for want of a signature, so the error can say so instead of \"not pushed\". */\n const unsigned = new Map<string, ReviewRecord | null>();\n let ready: Promise<void> | null = null;\n const load = () =>\n (ready ??= (async () => {\n for (const c of contracts) {\n const hash = await contractHash(c.manifest);\n const signed = c.review?.contractHash === hash;\n if (!signed) opts.onUnsigned?.(c.manifest.app, hash);\n if (!signed && requireSignature) unsigned.set(`${c.manifest.app}/${hash}`, c.review);\n if (signed || !requireSignature)\n await mem.put({\n manifest: c.manifest,\n hash,\n review: c.review ?? { contractHash: hash, signer: \"(unsigned, development)\", signedAt: \"\" },\n pushedAt: new Date(0).toISOString(),\n });\n }\n })());\n return {\n app: mem.app,\n apps: mem.apps,\n async get(app, hash) {\n await load();\n const hit = await mem.get(app, hash);\n if (hit) return hit;\n if (unsigned.has(`${app}/${hash}`)) {\n const review = unsigned.get(`${app}/${hash}`);\n throw new ConductorError(\n 409,\n review\n ? `the review sheet was signed for a different version of the ${app} contract (${review.contractHash.slice(0, 12)}\u2026, not ${hash.slice(0, 12)}\u2026); run bisque review --sign again and redeploy`\n : `the ${app} contract has no signed review sheet; run bisque review --sign and redeploy with bisque.review.json`,\n );\n }\n // The browser sent a contract this server is not running: an old tab after a deploy, usually.\n if (mem.app(app)) throw new ConductorError(409, \"this page was built with a different version of the app; reload it\");\n return undefined;\n },\n async put() {\n throw new Error(\"this registry serves the host's bundled contract; it does not accept pushes\");\n },\n };\n}\n", "import { appendFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { LimitReason } from \"./limits\";\nimport type { CallType, ModelUsage } from \"./model\";\n\n/**\n * Usage events (decision D4: no billing code in v1, log tokens per tenant\n * and call type). Ceiling hits are logged too, as the raw material for\n * demand analytics (Flow D), along with refused requests and failed model\n * calls. None of them carries the user's prompt.\n */\nexport type UsageEvent =\n | ({\n kind: \"model_call\";\n at: string;\n app: string;\n tenant: string;\n callType: CallType;\n model: string;\n /** Set when a fallback chain answered: which provider it was. */\n provider?: string;\n latencyMs: number;\n outcome: \"proposal\" | \"theme\" | \"automation\" | \"ask\" | \"answer\" | \"limit\" | \"invalid\" | \"error\";\n } & ModelUsage)\n | { kind: \"ceiling\"; at: string; app: string; tenant: string; capability: string }\n | { kind: \"limited\"; at: string; app: string; tenant: string; reason: LimitReason }\n | { kind: \"model_error\"; at: string; app: string; tenant: string; callType: CallType; provider: string; latencyMs: number; status: number | null; error: string };\n\nexport interface UsageSink {\n record(e: UsageEvent): void | Promise<void>;\n}\n\nexport function memoryUsage(): UsageSink & { events: UsageEvent[] } {\n const events: UsageEvent[] = [];\n return { events, record: (e) => void events.push(e) };\n}\n\nexport function jsonlUsage(path: string): UsageSink {\n let ready: Promise<unknown> | null = null;\n return {\n async record(e) {\n ready ??= mkdir(dirname(path), { recursive: true });\n await ready;\n await appendFile(path, `${JSON.stringify(e)}\\n`);\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,aAAa;AACtB,SAAS,OAAAA,MAAK,eAAe;;;ACD7B,OAAO,eAAe;AAGf,IAAM,gBAAgB;AAmBtB,IAAM,oBAAN,MAAiD;AAAA,EAC7C,OAAO;AAAA,EACC;AAAA,EACR;AAAA,EACQ;AAAA,EAEjB,YAAY,OAAiC,CAAC,GAAG;AAC/C,SAAK,SAA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,IAAI,uBAAuB,EAAE,WAAW,cAAc,QAAQ,IAAI,oBAAoB,EAAE,IAAI,CAAC;AAAA,EACzG,SAAS,eAAe;AAC1B,CAAC;AACD,MAAM,EAAE,OAAO,IAAI,OAAO,KAAK,CAAC;AAChC,QAAQ,IAAI,GAAG,QAAQ,IAAI,kCAAkC,IAAI,EAAE;",
|
|
6
|
+
"names": ["ENV", "app", "app", "app", "mkdir", "readFile", "writeFile", "join", "contractHash", "app", "readFile", "join", "mkdir", "writeFile", "mkdir", "mkdir", "ENV"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ModelProvider, ModelRequest, ModelResponse } from "./model.js";
|
|
2
|
+
export declare const DEFAULT_MODEL = "claude-opus-5-5";
|
|
3
|
+
export type AnthropicProviderOptions = {
|
|
4
|
+
/** Defaults to ANTHROPIC_API_KEY (or another credential the SDK resolves). */
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
model?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Server-side refusal fallback (`fallbacks: "default"`). On by default.
|
|
9
|
+
* Turn it off if the host was promised zero data retention and the
|
|
10
|
+
* fallback route could reach a model outside those terms (§3.4).
|
|
11
|
+
*/
|
|
12
|
+
fallbacks?: boolean;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Claude via the official SDK. Non-streaming: proposals are small (Table 2:
|
|
16
|
+
* ≤1.5k output tokens for a spec), and the conductor needs the whole tool
|
|
17
|
+
* call before it can validate anything.
|
|
18
|
+
*/
|
|
19
|
+
export declare class AnthropicProvider implements ModelProvider {
|
|
20
|
+
readonly name = "anthropic";
|
|
21
|
+
private readonly client;
|
|
22
|
+
readonly model: string;
|
|
23
|
+
private readonly fallbacks;
|
|
24
|
+
constructor(opts?: AnthropicProviderOptions);
|
|
25
|
+
complete(req: ModelRequest): Promise<ModelResponse>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Conductor, type ConductorOptions } from "./conductor.js";
|
|
2
|
+
/**
|
|
3
|
+
* HTTP surface of the conductor. A separate service, never inside the host's
|
|
4
|
+
* process, so the custody boundary is real and testable (Appendix C.4).
|
|
5
|
+
*/
|
|
6
|
+
export declare function createConductorApp(opts: ConductorOptions & {
|
|
7
|
+
conductor?: Conductor;
|
|
8
|
+
maxBodyBytes?: number /** e.g. "/api/bisque" when mounted in a host route. */;
|
|
9
|
+
basePath?: string;
|
|
10
|
+
}): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema, string, string>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type TokenClaims } from "@crasi/bisque-core";
|
|
2
|
+
import { type DiagnosticsResponse, type ProposeResponse } from "@crasi/bisque-spec";
|
|
3
|
+
import { type Limiter } from "./limits.js";
|
|
4
|
+
import type { CallType, Effort, ModelProvider } from "./model.js";
|
|
5
|
+
import { type ProposalStore } from "./proposals.js";
|
|
6
|
+
import type { ContractRegistry } from "./registry.js";
|
|
7
|
+
import type { UsageSink } from "./usage.js";
|
|
8
|
+
export type ConductorOptions = {
|
|
9
|
+
registry: ContractRegistry;
|
|
10
|
+
model: ModelProvider;
|
|
11
|
+
usage?: UsageSink;
|
|
12
|
+
/**
|
|
13
|
+
* Called before every user-initiated model call (not repairs). Return a
|
|
14
|
+
* message to refuse it, e.g. a plan without the feature or a daily cap.
|
|
15
|
+
*/
|
|
16
|
+
admit?: (claims: TokenClaims, callType: CallType) => Promise<string | null> | string | null;
|
|
17
|
+
maxTokens?: number;
|
|
18
|
+
effort?: Partial<Record<CallType, Effort>>;
|
|
19
|
+
/** How long a proposal stays open for its diagnostics repair. */
|
|
20
|
+
proposalTtlMs?: number;
|
|
21
|
+
/** Where open proposals wait for diagnostics. Defaults to one process's memory; use a shared store on serverless hosts. See {@link ProposalStore}. */
|
|
22
|
+
proposals?: ProposalStore;
|
|
23
|
+
/** Rate limits and token budgets. Defaults to `memoryLimiter()`; `false` turns them off. */
|
|
24
|
+
limiter?: Limiter | false;
|
|
25
|
+
now?: () => number;
|
|
26
|
+
};
|
|
27
|
+
export declare class ConductorError extends Error {
|
|
28
|
+
readonly status: 400 | 401 | 403 | 404 | 409 | 422 | 429 | 503;
|
|
29
|
+
readonly problems?: {
|
|
30
|
+
path: string;
|
|
31
|
+
message: string;
|
|
32
|
+
}[] | undefined;
|
|
33
|
+
readonly retryAfterSeconds?: number | undefined;
|
|
34
|
+
constructor(status: 400 | 401 | 403 | 404 | 409 | 422 | 429 | 503, message: string, problems?: {
|
|
35
|
+
path: string;
|
|
36
|
+
message: string;
|
|
37
|
+
}[] | undefined, retryAfterSeconds?: number | undefined);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The conductor (Fig. 3). Propose-only: it has no tool that writes host data
|
|
41
|
+
* or saves an artifact (Invariant 2). It validates every proposal with the
|
|
42
|
+
* same validator the host runs, gives the model one repair turn, and returns
|
|
43
|
+
* the result for the host to re-validate and preview.
|
|
44
|
+
*/
|
|
45
|
+
export declare class Conductor {
|
|
46
|
+
private readonly o;
|
|
47
|
+
constructor(opts: ConductorOptions);
|
|
48
|
+
/** Verifies a session token minted by the host's token route. */
|
|
49
|
+
authenticate(authorization: string | undefined): Promise<TokenClaims>;
|
|
50
|
+
/** `bisque push`: stores a contract manifest, only with a review signed for exactly this hash. */
|
|
51
|
+
push(app: string, secret: string | undefined, body: unknown): Promise<{
|
|
52
|
+
hash: string;
|
|
53
|
+
version: string;
|
|
54
|
+
}>;
|
|
55
|
+
propose(claims: TokenClaims, body: unknown): Promise<ProposeResponse>;
|
|
56
|
+
private enforceLimits;
|
|
57
|
+
private call;
|
|
58
|
+
private log;
|
|
59
|
+
/** One repair turn: the host's problems go back to the model as the tool's error result. */
|
|
60
|
+
private repair;
|
|
61
|
+
private turn;
|
|
62
|
+
/**
|
|
63
|
+
* Render diagnostics from the host's preview (§6.8). Strictly bucketed; the
|
|
64
|
+
* conductor rejects anything else. May spend the proposal's one repair turn.
|
|
65
|
+
*/
|
|
66
|
+
diagnostics(claims: TokenClaims, id: string, body: unknown): Promise<DiagnosticsResponse>;
|
|
67
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type ModelProvider } from "./model.js";
|
|
2
|
+
/** Rate limits, quota, overload and transient failures: worth trying the next provider. */
|
|
3
|
+
export declare function isRetryable(err: unknown): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Tries providers in order and moves on only for errors {@link isRetryable}
|
|
6
|
+
* accepts (a missing key counts, so a chain can list providers a deployment
|
|
7
|
+
* may not have keys for). The response names the provider that answered.
|
|
8
|
+
*
|
|
9
|
+
* One request is never split across providers: a repair turn starts on the
|
|
10
|
+
* first provider again, with the full history, which every provider here can
|
|
11
|
+
* read because blocks are provider-neutral.
|
|
12
|
+
*/
|
|
13
|
+
export declare function fallbackProvider(providers: ModelProvider[], opts?: {
|
|
14
|
+
retryable?: (e: unknown) => boolean;
|
|
15
|
+
onFallback?: (from: string, to: string, err: unknown) => void;
|
|
16
|
+
}): ModelProvider;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Effort, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse } from "./model.js";
|
|
2
|
+
export type GeminiProviderOptions = {
|
|
3
|
+
/** Defaults to GOOGLE_API_KEY, then GEMINI_API_KEY. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
model?: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
/** Thinking tokens per effort level. Set an entry to 0 to turn thinking off for it. */
|
|
9
|
+
thinking?: Partial<Record<Effort, number>>;
|
|
10
|
+
};
|
|
11
|
+
type Part = Record<string, unknown>;
|
|
12
|
+
/**
|
|
13
|
+
* Gemini over its REST API (no SDK dependency). Function calling with the
|
|
14
|
+
* tools' JSON Schemas passed as `parametersJsonSchema`, so the same tool
|
|
15
|
+
* definitions serve every provider. Prompt-cache breakpoints are ignored:
|
|
16
|
+
* Gemini caches implicitly.
|
|
17
|
+
*/
|
|
18
|
+
export declare class GeminiProvider implements ModelProvider {
|
|
19
|
+
readonly name = "gemini";
|
|
20
|
+
readonly model: string;
|
|
21
|
+
private readonly key;
|
|
22
|
+
private readonly base;
|
|
23
|
+
private readonly f;
|
|
24
|
+
private readonly thinking;
|
|
25
|
+
constructor(opts?: GeminiProviderOptions);
|
|
26
|
+
complete(req: ModelRequest): Promise<ModelResponse>;
|
|
27
|
+
}
|
|
28
|
+
/** Gemini needs the function's name on a response; the conductor's tool_result carries only the call id. */
|
|
29
|
+
export declare function toContents(messages: ModelMessage[]): {
|
|
30
|
+
role: "user" | "model";
|
|
31
|
+
parts: Part[];
|
|
32
|
+
}[];
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "./model.js";
|
|
2
|
+
export * from "./anthropic.js";
|
|
3
|
+
export * from "./gemini.js";
|
|
4
|
+
export * from "./openai.js";
|
|
5
|
+
export * from "./fallback.js";
|
|
6
|
+
export * from "./prompt.js";
|
|
7
|
+
export * from "./proposals.js";
|
|
8
|
+
export * from "./registry.js";
|
|
9
|
+
export * from "./usage.js";
|
|
10
|
+
export * from "./limits.js";
|
|
11
|
+
export * from "./conductor.js";
|
|
12
|
+
export * from "./app.js";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { TokenClaims } from "@crasi/bisque-core";
|
|
2
|
+
export type LimitReason = "user_rate" | "tenant_rate" | "tenant_budget";
|
|
3
|
+
export type LimitDecision = {
|
|
4
|
+
ok: true;
|
|
5
|
+
} | {
|
|
6
|
+
ok: false;
|
|
7
|
+
reason: LimitReason;
|
|
8
|
+
retryAfterSeconds: number;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* What stands between a session token and the model bill. The conductor asks
|
|
12
|
+
* before every request that may call the model, and reports the tokens each
|
|
13
|
+
* call spent. Implement this over a shared store to limit across instances.
|
|
14
|
+
*/
|
|
15
|
+
export interface Limiter {
|
|
16
|
+
check(claims: TokenClaims, now: number): LimitDecision | Promise<LimitDecision>;
|
|
17
|
+
spend(claims: TokenClaims, tokens: number, now: number): void | Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export type LimitOptions = {
|
|
20
|
+
/** Requests per minute for one user. */
|
|
21
|
+
userPerMinute?: number;
|
|
22
|
+
/** Requests per minute for one tenant, across its users. */
|
|
23
|
+
tenantPerMinute?: number;
|
|
24
|
+
/** Tokens per UTC day for one tenant. */
|
|
25
|
+
tenantTokensPerDay?: number;
|
|
26
|
+
};
|
|
27
|
+
export declare const DEFAULT_LIMITS: Required<LimitOptions>;
|
|
28
|
+
/** Per-process limits: each instance of the conductor counts on its own. */
|
|
29
|
+
export declare function memoryLimiter(opts?: LimitOptions): Limiter;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The model seam (decision D2). The conductor talks to this interface; the
|
|
3
|
+
* Anthropic implementation is the v1 default, and a host-key or other
|
|
4
|
+
* provider can replace it without touching the conductor.
|
|
5
|
+
*/
|
|
6
|
+
export type ModelTool = {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
input_schema: Record<string, unknown>;
|
|
10
|
+
};
|
|
11
|
+
export type ModelBlock = {
|
|
12
|
+
type: "text";
|
|
13
|
+
text: string;
|
|
14
|
+
}
|
|
15
|
+
/** `provider` holds provider-specific data (e.g. Gemini's thought signature) that must go back unchanged. */
|
|
16
|
+
| {
|
|
17
|
+
type: "tool_use";
|
|
18
|
+
id: string;
|
|
19
|
+
name: string;
|
|
20
|
+
input: unknown;
|
|
21
|
+
provider?: unknown;
|
|
22
|
+
} | {
|
|
23
|
+
type: "tool_result";
|
|
24
|
+
tool_use_id: string;
|
|
25
|
+
content: string;
|
|
26
|
+
is_error?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Provider-specific blocks (thinking, fallback markers) passed back unchanged. */
|
|
29
|
+
| {
|
|
30
|
+
type: "opaque";
|
|
31
|
+
raw: unknown;
|
|
32
|
+
};
|
|
33
|
+
export type ModelMessage = {
|
|
34
|
+
role: "user" | "assistant";
|
|
35
|
+
content: ModelBlock[];
|
|
36
|
+
};
|
|
37
|
+
export type Effort = "low" | "medium" | "high";
|
|
38
|
+
export type CallType = "spec" | "refine" | "repair";
|
|
39
|
+
export type ModelRequest = {
|
|
40
|
+
/** System blocks in order. `cache: true` puts a prompt-cache breakpoint after the block. */
|
|
41
|
+
system: {
|
|
42
|
+
text: string;
|
|
43
|
+
cache?: boolean;
|
|
44
|
+
}[];
|
|
45
|
+
messages: ModelMessage[];
|
|
46
|
+
tools: ModelTool[];
|
|
47
|
+
effort: Effort;
|
|
48
|
+
maxTokens: number;
|
|
49
|
+
callType: CallType;
|
|
50
|
+
};
|
|
51
|
+
export type ModelUsage = {
|
|
52
|
+
input: number;
|
|
53
|
+
output: number;
|
|
54
|
+
cacheRead: number;
|
|
55
|
+
cacheWrite: number;
|
|
56
|
+
};
|
|
57
|
+
export type ModelResponse = {
|
|
58
|
+
content: ModelBlock[];
|
|
59
|
+
stopReason: "end_turn" | "tool_use" | "max_tokens" | "refusal" | string;
|
|
60
|
+
usage: ModelUsage;
|
|
61
|
+
model: string;
|
|
62
|
+
/** Which provider answered, when a fallback chain is in front of several. */
|
|
63
|
+
provider?: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* A failed provider call with its HTTP status, so a fallback chain can tell
|
|
67
|
+
* a rate limit (try the next provider) from a bad request (stop).
|
|
68
|
+
*/
|
|
69
|
+
export declare class ProviderError extends Error {
|
|
70
|
+
readonly provider: string;
|
|
71
|
+
readonly status: number;
|
|
72
|
+
constructor(provider: string, status: number, message: string);
|
|
73
|
+
}
|
|
74
|
+
export interface ModelProvider {
|
|
75
|
+
readonly name: string;
|
|
76
|
+
complete(req: ModelRequest): Promise<ModelResponse>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* A provider that answers from a function, for tests and for running the
|
|
80
|
+
* demo without a model key. It records every request it receives, which is
|
|
81
|
+
* what the H3 custody test inspects.
|
|
82
|
+
*/
|
|
83
|
+
export declare class ScriptedProvider implements ModelProvider {
|
|
84
|
+
private readonly respond;
|
|
85
|
+
readonly name = "scripted";
|
|
86
|
+
readonly requests: ModelRequest[];
|
|
87
|
+
constructor(respond: (req: ModelRequest, call: number) => ModelBlock[] | Promise<ModelBlock[]>);
|
|
88
|
+
complete(req: ModelRequest): Promise<ModelResponse>;
|
|
89
|
+
}
|
|
90
|
+
export declare function toolUse(name: string, input: unknown): ModelBlock;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type ModelProvider, type ModelRequest, type ModelResponse } from "./model.js";
|
|
2
|
+
export type OpenAIProviderOptions = {
|
|
3
|
+
/** Defaults to OPENAI_API_KEY. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
model?: string;
|
|
6
|
+
/** Any OpenAI-compatible Chat Completions endpoint. */
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
fetch?: typeof fetch;
|
|
9
|
+
/** Send `reasoning_effort` (only reasoning models accept it). */
|
|
10
|
+
reasoning?: boolean;
|
|
11
|
+
};
|
|
12
|
+
type ChatMessage = {
|
|
13
|
+
role: "system" | "user";
|
|
14
|
+
content: string;
|
|
15
|
+
} | {
|
|
16
|
+
role: "assistant";
|
|
17
|
+
content: string | null;
|
|
18
|
+
tool_calls?: {
|
|
19
|
+
id: string;
|
|
20
|
+
type: "function";
|
|
21
|
+
function: {
|
|
22
|
+
name: string;
|
|
23
|
+
arguments: string;
|
|
24
|
+
};
|
|
25
|
+
}[];
|
|
26
|
+
} | {
|
|
27
|
+
role: "tool";
|
|
28
|
+
tool_call_id: string;
|
|
29
|
+
content: string;
|
|
30
|
+
};
|
|
31
|
+
/** OpenAI Chat Completions over REST (no SDK dependency). */
|
|
32
|
+
export declare class OpenAIProvider implements ModelProvider {
|
|
33
|
+
readonly name = "openai";
|
|
34
|
+
readonly model: string;
|
|
35
|
+
private readonly key;
|
|
36
|
+
private readonly base;
|
|
37
|
+
private readonly f;
|
|
38
|
+
private readonly reasoning;
|
|
39
|
+
constructor(opts?: OpenAIProviderOptions);
|
|
40
|
+
complete(req: ModelRequest): Promise<ModelResponse>;
|
|
41
|
+
}
|
|
42
|
+
export declare function toChatMessages(req: Pick<ModelRequest, "system" | "messages">): ChatMessage[];
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ContractManifest, type SharedValues } from "@crasi/bisque-contract";
|
|
2
|
+
import type { ModelTool } from "./model.js";
|
|
3
|
+
export declare const TOOLS: ModelTool[];
|
|
4
|
+
export declare function systemBlocks(m: ContractManifest, sharedValues?: SharedValues): {
|
|
5
|
+
text: string;
|
|
6
|
+
cache?: boolean;
|
|
7
|
+
}[];
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { TokenClaims } from "@crasi/bisque-core";
|
|
2
|
+
import type { Draft } from "@crasi/bisque-spec";
|
|
3
|
+
import type { ModelMessage, ModelRequest } from "./model.js";
|
|
4
|
+
/**
|
|
5
|
+
* A proposal waiting for its diagnostics round: the conversation so far, so a
|
|
6
|
+
* repair turn can continue it. Plain JSON, so a host running the conductor on
|
|
7
|
+
* serverless functions can keep it in its own database.
|
|
8
|
+
*/
|
|
9
|
+
export type OpenProposal = {
|
|
10
|
+
claims: TokenClaims;
|
|
11
|
+
/** The contract the proposal was made against; the manifest is read back from the registry. */
|
|
12
|
+
contract: {
|
|
13
|
+
app: string;
|
|
14
|
+
hash: string;
|
|
15
|
+
};
|
|
16
|
+
system: ModelRequest["system"];
|
|
17
|
+
messages: ModelMessage[];
|
|
18
|
+
toolUseId: string;
|
|
19
|
+
draft: Draft;
|
|
20
|
+
repairsLeft: number;
|
|
21
|
+
/** Epoch milliseconds. */
|
|
22
|
+
expires: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Where open proposals wait. In memory by default, which is enough for one
|
|
26
|
+
* instance: losing one only means its preview gets no repair turn, since
|
|
27
|
+
* diagnostics are best effort. Several instances need a store they share.
|
|
28
|
+
* Implementations must return plain JSON values, and the conductor checks
|
|
29
|
+
* `expires` itself, so purging is only housekeeping.
|
|
30
|
+
*/
|
|
31
|
+
export interface ProposalStore {
|
|
32
|
+
get(id: string): Promise<OpenProposal | undefined>;
|
|
33
|
+
put(id: string, p: OpenProposal, now: number): Promise<void>;
|
|
34
|
+
delete(id: string): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
export declare function memoryProposals(max?: number): ProposalStore;
|
|
37
|
+
/** The name hosts built against the canon-integration branch used. */
|
|
38
|
+
export declare const memoryProposalStore: typeof memoryProposals;
|
|
39
|
+
/**
|
|
40
|
+
* One owner-only file per proposal, for surviving restarts or sharing a
|
|
41
|
+
* volume between instances. These files hold the user's prompts and the
|
|
42
|
+
* shared values until the proposal expires, so keep the directory private.
|
|
43
|
+
*/
|
|
44
|
+
export declare function fileProposals(dir: string): ProposalStore;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type ContractManifest } from "@crasi/bisque-contract";
|
|
2
|
+
export type AppConfig = {
|
|
3
|
+
app: string;
|
|
4
|
+
/** BISQUE_SECRET_KEY: signs session tokens and authorizes `bisque push`. */
|
|
5
|
+
secretKey: string;
|
|
6
|
+
/** Origins allowed to call the conductor from a browser (the host app). */
|
|
7
|
+
allowedOrigins: string[];
|
|
8
|
+
};
|
|
9
|
+
export type ReviewRecord = {
|
|
10
|
+
contractHash: string;
|
|
11
|
+
signer: string;
|
|
12
|
+
signedAt: string;
|
|
13
|
+
[k: string]: unknown;
|
|
14
|
+
};
|
|
15
|
+
export type StoredContract = {
|
|
16
|
+
manifest: ContractManifest;
|
|
17
|
+
hash: string;
|
|
18
|
+
review: ReviewRecord;
|
|
19
|
+
pushedAt: string;
|
|
20
|
+
};
|
|
21
|
+
/** Pushed contracts, keyed by app and hash. Contracts only: no data, no artifacts. */
|
|
22
|
+
export interface ContractRegistry {
|
|
23
|
+
app(app: string): AppConfig | undefined;
|
|
24
|
+
apps(): AppConfig[];
|
|
25
|
+
get(app: string, hash: string): Promise<StoredContract | undefined>;
|
|
26
|
+
put(c: StoredContract): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
export declare function memoryRegistry(apps: AppConfig[]): ContractRegistry;
|
|
29
|
+
/** File-backed registry for a single-node deployment: `<dir>/<app>/<hash>.json`. */
|
|
30
|
+
export declare function fileRegistry(apps: AppConfig[], dir: string): ContractRegistry;
|
|
31
|
+
export type StaticContract = {
|
|
32
|
+
manifest: ContractManifest;
|
|
33
|
+
review: ReviewRecord | null;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* For a conductor running inside the host (a route handler): the contracts
|
|
37
|
+
* come from the host's own bundle instead of `bisque push`, but the rule is
|
|
38
|
+
* the same. A contract is served only when its review sheet is signed for
|
|
39
|
+
* exactly its hash, unless `requireSignature` is off (development only).
|
|
40
|
+
*/
|
|
41
|
+
export declare function staticRegistry(apps: AppConfig[], contracts: StaticContract[], opts?: {
|
|
42
|
+
requireSignature?: boolean;
|
|
43
|
+
onUnsigned?: (app: string, hash: string) => void;
|
|
44
|
+
}): ContractRegistry;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|