@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
package/dist/index.js
ADDED
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
// src/model.ts
|
|
2
|
+
var ProviderError = class extends Error {
|
|
3
|
+
constructor(provider, status, message) {
|
|
4
|
+
super(`${provider} ${status}: ${message}`);
|
|
5
|
+
this.provider = provider;
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.name = "ProviderError";
|
|
8
|
+
}
|
|
9
|
+
provider;
|
|
10
|
+
status;
|
|
11
|
+
};
|
|
12
|
+
var ScriptedProvider = class {
|
|
13
|
+
constructor(respond) {
|
|
14
|
+
this.respond = respond;
|
|
15
|
+
}
|
|
16
|
+
respond;
|
|
17
|
+
name = "scripted";
|
|
18
|
+
requests = [];
|
|
19
|
+
async complete(req) {
|
|
20
|
+
this.requests.push(structuredClone(req));
|
|
21
|
+
const content = await this.respond(req, this.requests.length - 1);
|
|
22
|
+
const text = JSON.stringify(req);
|
|
23
|
+
return {
|
|
24
|
+
content,
|
|
25
|
+
stopReason: content.some((b) => b.type === "tool_use") ? "tool_use" : "end_turn",
|
|
26
|
+
usage: { input: Math.ceil(text.length / 4), output: Math.ceil(JSON.stringify(content).length / 4), cacheRead: 0, cacheWrite: 0 },
|
|
27
|
+
model: "scripted"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var toolSeq = 0;
|
|
32
|
+
function toolUse(name, input) {
|
|
33
|
+
return { type: "tool_use", id: `toolu_scripted_${++toolSeq}`, name, input };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/anthropic.ts
|
|
37
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
38
|
+
var DEFAULT_MODEL = "claude-opus-5-5";
|
|
39
|
+
var AnthropicProvider = class {
|
|
40
|
+
name = "anthropic";
|
|
41
|
+
client;
|
|
42
|
+
model;
|
|
43
|
+
fallbacks;
|
|
44
|
+
constructor(opts = {}) {
|
|
45
|
+
this.client = new Anthropic(opts.apiKey ? { apiKey: opts.apiKey } : {});
|
|
46
|
+
this.model = opts.model ?? DEFAULT_MODEL;
|
|
47
|
+
this.fallbacks = opts.fallbacks ?? true;
|
|
48
|
+
}
|
|
49
|
+
async complete(req) {
|
|
50
|
+
const system = req.system.map((s) => ({
|
|
51
|
+
type: "text",
|
|
52
|
+
text: s.text,
|
|
53
|
+
...s.cache ? { cache_control: { type: "ephemeral" } } : {}
|
|
54
|
+
}));
|
|
55
|
+
const messages = req.messages.map((m) => ({
|
|
56
|
+
role: m.role,
|
|
57
|
+
content: m.content.map(toParam)
|
|
58
|
+
}));
|
|
59
|
+
const tools = req.tools.map((t) => ({
|
|
60
|
+
name: t.name,
|
|
61
|
+
description: t.description,
|
|
62
|
+
input_schema: t.input_schema
|
|
63
|
+
}));
|
|
64
|
+
const response = await this.client.beta.messages.create({
|
|
65
|
+
model: this.model,
|
|
66
|
+
max_tokens: req.maxTokens,
|
|
67
|
+
system,
|
|
68
|
+
messages,
|
|
69
|
+
tools,
|
|
70
|
+
// Forced tool_choice is rejected on this model family; the system prompt asks for exactly one tool call.
|
|
71
|
+
tool_choice: { type: "auto", disable_parallel_tool_use: true },
|
|
72
|
+
output_config: { effort: req.effort },
|
|
73
|
+
...this.fallbacks ? { betas: ["server-side-fallback-2026-07-01"], fallbacks: "default" } : {}
|
|
74
|
+
});
|
|
75
|
+
return {
|
|
76
|
+
content: response.content.map(fromBlock),
|
|
77
|
+
stopReason: response.stop_reason ?? "end_turn",
|
|
78
|
+
usage: {
|
|
79
|
+
input: response.usage.input_tokens,
|
|
80
|
+
output: response.usage.output_tokens,
|
|
81
|
+
cacheRead: response.usage.cache_read_input_tokens ?? 0,
|
|
82
|
+
cacheWrite: response.usage.cache_creation_input_tokens ?? 0
|
|
83
|
+
},
|
|
84
|
+
model: response.model,
|
|
85
|
+
provider: this.name
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
function toParam(b) {
|
|
90
|
+
switch (b.type) {
|
|
91
|
+
case "text":
|
|
92
|
+
return { type: "text", text: b.text };
|
|
93
|
+
case "tool_use":
|
|
94
|
+
return { type: "tool_use", id: b.id, name: b.name, input: b.input };
|
|
95
|
+
case "tool_result":
|
|
96
|
+
return { type: "tool_result", tool_use_id: b.tool_use_id, content: b.content, is_error: b.is_error };
|
|
97
|
+
case "opaque":
|
|
98
|
+
return b.raw;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function fromBlock(b) {
|
|
102
|
+
if (b.type === "text") return { type: "text", text: b.text };
|
|
103
|
+
if (b.type === "tool_use") return { type: "tool_use", id: b.id, name: b.name, input: b.input };
|
|
104
|
+
return { type: "opaque", raw: b };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/gemini.ts
|
|
108
|
+
var GeminiProvider = class {
|
|
109
|
+
name = "gemini";
|
|
110
|
+
model;
|
|
111
|
+
key;
|
|
112
|
+
base;
|
|
113
|
+
f;
|
|
114
|
+
thinking;
|
|
115
|
+
constructor(opts = {}) {
|
|
116
|
+
this.key = opts.apiKey ?? globalThis.process?.env?.GOOGLE_API_KEY ?? globalThis.process?.env?.GEMINI_API_KEY ?? "";
|
|
117
|
+
this.model = opts.model ?? "gemini-2.5-flash";
|
|
118
|
+
this.base = (opts.baseUrl ?? "https://generativelanguage.googleapis.com").replace(/\/$/, "");
|
|
119
|
+
this.f = opts.fetch ?? ((...a) => fetch(...a));
|
|
120
|
+
this.thinking = { low: 0, medium: 1024, high: 4096, ...opts.thinking };
|
|
121
|
+
}
|
|
122
|
+
async complete(req) {
|
|
123
|
+
if (!this.key) throw new ProviderError(this.name, 401, "no API key (set GOOGLE_API_KEY)");
|
|
124
|
+
const body = {
|
|
125
|
+
systemInstruction: { parts: [{ text: req.system.map((s) => s.text).join("\n\n") }] },
|
|
126
|
+
contents: toContents(req.messages),
|
|
127
|
+
tools: [{ functionDeclarations: req.tools.map((t) => ({ name: t.name, description: t.description, parametersJsonSchema: t.input_schema })) }],
|
|
128
|
+
toolConfig: { functionCallingConfig: { mode: "AUTO" } },
|
|
129
|
+
generationConfig: { maxOutputTokens: req.maxTokens, thinkingConfig: { thinkingBudget: this.thinking[req.effort] } }
|
|
130
|
+
};
|
|
131
|
+
const res = await this.f(`${this.base}/v1beta/models/${encodeURIComponent(this.model)}:generateContent`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { "content-type": "application/json", "x-goog-api-key": this.key },
|
|
134
|
+
body: JSON.stringify(body)
|
|
135
|
+
});
|
|
136
|
+
const json = await res.json().catch(() => ({}));
|
|
137
|
+
if (!res.ok) throw new ProviderError(this.name, res.status, json.error?.message ?? res.statusText);
|
|
138
|
+
const cand = json.candidates?.[0];
|
|
139
|
+
const parts = cand?.content?.parts ?? [];
|
|
140
|
+
const content = parts.map(fromPart).filter((b) => !!b);
|
|
141
|
+
const finish = cand?.finishReason ?? "STOP";
|
|
142
|
+
const stopReason = finish === "MAX_TOKENS" ? "max_tokens" : finish === "SAFETY" || finish === "PROHIBITED_CONTENT" || finish === "BLOCKLIST" || json.promptFeedback?.blockReason ? "refusal" : content.some((b) => b.type === "tool_use") ? "tool_use" : "end_turn";
|
|
143
|
+
const u = json.usageMetadata ?? {};
|
|
144
|
+
return {
|
|
145
|
+
content,
|
|
146
|
+
stopReason,
|
|
147
|
+
usage: { input: u.promptTokenCount ?? 0, output: (u.candidatesTokenCount ?? 0) + (u.thoughtsTokenCount ?? 0), cacheRead: u.cachedContentTokenCount ?? 0, cacheWrite: 0 },
|
|
148
|
+
model: json.modelVersion ?? this.model,
|
|
149
|
+
provider: this.name
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
var callSeq = 0;
|
|
154
|
+
function fromPart(p) {
|
|
155
|
+
if (p.thought === true) return { type: "opaque", raw: p };
|
|
156
|
+
if (p.functionCall && typeof p.functionCall === "object") {
|
|
157
|
+
const fc = p.functionCall;
|
|
158
|
+
return {
|
|
159
|
+
type: "tool_use",
|
|
160
|
+
id: fc.id ?? `gemini_call_${++callSeq}`,
|
|
161
|
+
name: fc.name,
|
|
162
|
+
input: fc.args ?? {},
|
|
163
|
+
provider: p.thoughtSignature ? { thoughtSignature: p.thoughtSignature } : void 0
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
if (typeof p.text === "string") return { type: "text", text: p.text };
|
|
167
|
+
return { type: "opaque", raw: p };
|
|
168
|
+
}
|
|
169
|
+
function toContents(messages) {
|
|
170
|
+
const names = /* @__PURE__ */ new Map();
|
|
171
|
+
for (const m of messages) for (const b of m.content) if (b.type === "tool_use") names.set(b.id, b.name);
|
|
172
|
+
return messages.map((m) => ({
|
|
173
|
+
role: m.role === "assistant" ? "model" : "user",
|
|
174
|
+
parts: m.content.map((b) => {
|
|
175
|
+
switch (b.type) {
|
|
176
|
+
case "text":
|
|
177
|
+
return { text: b.text };
|
|
178
|
+
case "tool_use": {
|
|
179
|
+
const sig = b.provider?.thoughtSignature;
|
|
180
|
+
return { functionCall: { id: b.id, name: b.name, args: b.input ?? {} }, ...sig ? { thoughtSignature: sig } : {} };
|
|
181
|
+
}
|
|
182
|
+
case "tool_result":
|
|
183
|
+
return {
|
|
184
|
+
functionResponse: { id: b.tool_use_id, name: names.get(b.tool_use_id) ?? "propose_spec", response: { content: b.content, ...b.is_error ? { error: true } : {} } }
|
|
185
|
+
};
|
|
186
|
+
case "opaque":
|
|
187
|
+
return b.raw ?? {};
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
}));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/openai.ts
|
|
194
|
+
var OpenAIProvider = class {
|
|
195
|
+
name = "openai";
|
|
196
|
+
model;
|
|
197
|
+
key;
|
|
198
|
+
base;
|
|
199
|
+
f;
|
|
200
|
+
reasoning;
|
|
201
|
+
constructor(opts = {}) {
|
|
202
|
+
this.key = opts.apiKey ?? globalThis.process?.env?.OPENAI_API_KEY ?? "";
|
|
203
|
+
this.model = opts.model ?? "gpt-4o-mini";
|
|
204
|
+
this.base = (opts.baseUrl ?? "https://api.openai.com/v1").replace(/\/$/, "");
|
|
205
|
+
this.f = opts.fetch ?? ((...a) => fetch(...a));
|
|
206
|
+
this.reasoning = opts.reasoning ?? false;
|
|
207
|
+
}
|
|
208
|
+
async complete(req) {
|
|
209
|
+
if (!this.key) throw new ProviderError(this.name, 401, "no API key (set OPENAI_API_KEY)");
|
|
210
|
+
const body = {
|
|
211
|
+
model: this.model,
|
|
212
|
+
messages: toChatMessages(req),
|
|
213
|
+
tools: req.tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema } })),
|
|
214
|
+
tool_choice: "auto",
|
|
215
|
+
parallel_tool_calls: false,
|
|
216
|
+
max_completion_tokens: req.maxTokens,
|
|
217
|
+
...this.reasoning ? { reasoning_effort: req.effort } : {}
|
|
218
|
+
};
|
|
219
|
+
const res = await this.f(`${this.base}/chat/completions`, {
|
|
220
|
+
method: "POST",
|
|
221
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${this.key}` },
|
|
222
|
+
body: JSON.stringify(body)
|
|
223
|
+
});
|
|
224
|
+
const json = await res.json().catch(() => ({}));
|
|
225
|
+
if (!res.ok) throw new ProviderError(this.name, res.status, json.error?.message ?? res.statusText);
|
|
226
|
+
const choice = json.choices?.[0];
|
|
227
|
+
const msg = choice?.message ?? {};
|
|
228
|
+
const content = [];
|
|
229
|
+
if (msg.content) content.push({ type: "text", text: msg.content });
|
|
230
|
+
for (const c of msg.tool_calls ?? []) {
|
|
231
|
+
let input = {};
|
|
232
|
+
try {
|
|
233
|
+
input = JSON.parse(c.function.arguments || "{}");
|
|
234
|
+
} catch {
|
|
235
|
+
input = {};
|
|
236
|
+
}
|
|
237
|
+
content.push({ type: "tool_use", id: c.id, name: c.function.name, input });
|
|
238
|
+
}
|
|
239
|
+
const finish = choice?.finish_reason;
|
|
240
|
+
return {
|
|
241
|
+
content,
|
|
242
|
+
stopReason: finish === "length" ? "max_tokens" : finish === "content_filter" || msg.refusal ? "refusal" : content.some((b) => b.type === "tool_use") ? "tool_use" : "end_turn",
|
|
243
|
+
usage: { input: json.usage?.prompt_tokens ?? 0, output: json.usage?.completion_tokens ?? 0, cacheRead: json.usage?.prompt_tokens_details?.cached_tokens ?? 0, cacheWrite: 0 },
|
|
244
|
+
model: json.model ?? this.model,
|
|
245
|
+
provider: this.name
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
function toChatMessages(req) {
|
|
250
|
+
const out = [{ role: "system", content: req.system.map((s) => s.text).join("\n\n") }];
|
|
251
|
+
for (const m of req.messages) {
|
|
252
|
+
if (m.role === "assistant") {
|
|
253
|
+
const text2 = m.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
|
|
254
|
+
const calls = m.content.filter((b) => b.type === "tool_use");
|
|
255
|
+
out.push({
|
|
256
|
+
role: "assistant",
|
|
257
|
+
content: text2 || null,
|
|
258
|
+
...calls.length ? { tool_calls: calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) } })) } : {}
|
|
259
|
+
});
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
for (const b of m.content) if (b.type === "tool_result") out.push({ role: "tool", tool_call_id: b.tool_use_id, content: b.content });
|
|
263
|
+
const text = m.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
|
|
264
|
+
if (text) out.push({ role: "user", content: text });
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// src/fallback.ts
|
|
270
|
+
function isRetryable(err) {
|
|
271
|
+
if (err instanceof ProviderError) return err.status === 401 || err.status === 403 || err.status === 408 || err.status === 429 || err.status >= 500;
|
|
272
|
+
const e = err;
|
|
273
|
+
if (typeof e?.status === "number" && (e.status === 429 || e.status >= 500)) return true;
|
|
274
|
+
const m = String(e?.message ?? err).toLowerCase();
|
|
275
|
+
return ["quota", "rate limit", "rate_limit", "resource_exhausted", "overloaded", "too many requests", "unavailable", "timeout", "econnreset", "etimedout", "fetch failed"].some(
|
|
276
|
+
(s) => m.includes(s)
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
function fallbackProvider(providers, opts = {}) {
|
|
280
|
+
if (!providers.length) throw new Error("fallbackProvider needs at least one provider");
|
|
281
|
+
const retryable = opts.retryable ?? isRetryable;
|
|
282
|
+
return {
|
|
283
|
+
name: `fallback(${providers.map((p) => p.name).join(">")})`,
|
|
284
|
+
async complete(req) {
|
|
285
|
+
let last;
|
|
286
|
+
for (const [i, p] of providers.entries()) {
|
|
287
|
+
try {
|
|
288
|
+
const res = await p.complete(req);
|
|
289
|
+
return { ...res, provider: res.provider ?? p.name };
|
|
290
|
+
} catch (e) {
|
|
291
|
+
last = e;
|
|
292
|
+
const next = providers[i + 1];
|
|
293
|
+
if (!next || !retryable(e)) throw e;
|
|
294
|
+
opts.onFallback?.(p.name, next.name, e);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
throw last;
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// src/prompt.ts
|
|
303
|
+
import { buildReference, sharedValuesSection } from "@crasi/bisque-contract";
|
|
304
|
+
import { AUTOMATION_GUIDE, CATALOG_LINE, SPEC_GUIDE } from "@crasi/bisque-spec";
|
|
305
|
+
var 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.
|
|
306
|
+
|
|
307
|
+
What 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.
|
|
308
|
+
|
|
309
|
+
Answer every turn with exactly one tool call, except plain how-to questions, which you answer in one or two sentences of text:
|
|
310
|
+
- propose_spec when you can build what was asked. Give the complete draft, including manifest and placement.
|
|
311
|
+
- 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.
|
|
312
|
+
- 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.
|
|
313
|
+
- ask when one genuine ambiguity blocks you and the glossary does not settle it. Offer 2\u20134 short options.
|
|
314
|
+
- 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.
|
|
315
|
+
|
|
316
|
+
Rules for drafts:
|
|
317
|
+
1. Use only resources, fields, references, intents, navigations, slots and context listed in the reference. Never invent names.
|
|
318
|
+
2. Use the glossary. If a term is defined there (for example "sales"), follow the definition without asking.
|
|
319
|
+
3. Prefer a derived resource over recomputing a number the host already computes.
|
|
320
|
+
4. 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.
|
|
321
|
+
5. 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.
|
|
322
|
+
6. 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.
|
|
323
|
+
7. Write title and labels for every host locale listed in the reference.
|
|
324
|
+
8. Keep queries small and readable: a sensible limit, sort by the measure, and otherBucket when there may be many categories.
|
|
325
|
+
9. When a current draft is given, return the whole revised draft and change only what the user asked for.
|
|
326
|
+
10. manifest.reads lists exactly the resources the query touches; manifest.acts lists exactly the intents the spec invokes.
|
|
327
|
+
|
|
328
|
+
This is latency-sensitive: keep reasoning brief and go straight to the tool call.`;
|
|
329
|
+
var TOOLS = [
|
|
330
|
+
{
|
|
331
|
+
name: "propose_spec",
|
|
332
|
+
description: "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.",
|
|
333
|
+
input_schema: {
|
|
334
|
+
type: "object",
|
|
335
|
+
properties: {
|
|
336
|
+
draft: { type: "object", description: 'The complete draft: { kind: "spec", body, manifest, placement } as described in the spec format.' },
|
|
337
|
+
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." }
|
|
338
|
+
},
|
|
339
|
+
required: ["draft"]
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
{
|
|
343
|
+
name: "propose_theme",
|
|
344
|
+
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.",
|
|
345
|
+
input_schema: {
|
|
346
|
+
type: "object",
|
|
347
|
+
properties: {
|
|
348
|
+
tokens: {
|
|
349
|
+
type: "object",
|
|
350
|
+
description: "Token name to value, only for tokens that change. Colours are hex like #0f5c8a; options are exactly as listed.",
|
|
351
|
+
additionalProperties: { type: "string" }
|
|
352
|
+
},
|
|
353
|
+
note: { type: "string", description: "Optional, at most one short sentence to the user. Do not list the changes; the host does that." }
|
|
354
|
+
},
|
|
355
|
+
required: ["tokens"]
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
{
|
|
359
|
+
name: "propose_automation",
|
|
360
|
+
description: "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.",
|
|
361
|
+
input_schema: {
|
|
362
|
+
type: "object",
|
|
363
|
+
properties: {
|
|
364
|
+
automation: { type: "object", description: "The complete automation as described in the automation format." },
|
|
365
|
+
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." }
|
|
366
|
+
},
|
|
367
|
+
required: ["automation"]
|
|
368
|
+
}
|
|
369
|
+
},
|
|
370
|
+
{
|
|
371
|
+
name: "ask",
|
|
372
|
+
description: "Ask one clarifying question when a real ambiguity blocks the proposal.",
|
|
373
|
+
input_schema: {
|
|
374
|
+
type: "object",
|
|
375
|
+
properties: {
|
|
376
|
+
question: { type: "string" },
|
|
377
|
+
options: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 4 }
|
|
378
|
+
},
|
|
379
|
+
required: ["question", "options"]
|
|
380
|
+
}
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
name: "explain_limit",
|
|
384
|
+
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.",
|
|
385
|
+
input_schema: {
|
|
386
|
+
type: "object",
|
|
387
|
+
properties: {
|
|
388
|
+
message: { type: "string", description: "Two sentences at most, to the user." },
|
|
389
|
+
capability: { type: "string", description: 'Short label for the missing capability, e.g. "scheduled email", "external data", "delete orders".' },
|
|
390
|
+
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".' }
|
|
391
|
+
},
|
|
392
|
+
required: ["message", "capability"]
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
];
|
|
396
|
+
function systemBlocks(m, sharedValues) {
|
|
397
|
+
const reference = `# Host reference
|
|
398
|
+
|
|
399
|
+
${buildReference(m)}
|
|
400
|
+
|
|
401
|
+
${CATALOG_LINE}`;
|
|
402
|
+
const guides = m.automations ? `${SPEC_GUIDE}
|
|
403
|
+
|
|
404
|
+
${AUTOMATION_GUIDE}` : SPEC_GUIDE;
|
|
405
|
+
const blocks = [{ text: `${INSTRUCTIONS}
|
|
406
|
+
|
|
407
|
+
${guides}
|
|
408
|
+
|
|
409
|
+
${reference}`, cache: true }];
|
|
410
|
+
const shared = sharedValues ? sharedValuesSection(sharedValues) : "";
|
|
411
|
+
if (shared) blocks.push({ text: `# Shared lookup values
|
|
412
|
+
|
|
413
|
+
${shared}`, cache: true });
|
|
414
|
+
return blocks;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/proposals.ts
|
|
418
|
+
import { chmod, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
419
|
+
import { join } from "node:path";
|
|
420
|
+
function memoryProposals(max = 1e4) {
|
|
421
|
+
const open = /* @__PURE__ */ new Map();
|
|
422
|
+
return {
|
|
423
|
+
get: async (id) => open.get(id),
|
|
424
|
+
async put(id, p, now) {
|
|
425
|
+
for (const [k, v] of open) if (v.expires < now) open.delete(k);
|
|
426
|
+
open.set(id, p);
|
|
427
|
+
for (const k of open.keys()) {
|
|
428
|
+
if (open.size <= max) break;
|
|
429
|
+
open.delete(k);
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
delete: async (id) => void open.delete(id)
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
var memoryProposalStore = memoryProposals;
|
|
436
|
+
var SAFE_ID = /^p_[0-9a-f-]{36}$/;
|
|
437
|
+
var PURGE_EVERY_MS = 6e4;
|
|
438
|
+
function fileProposals(dir) {
|
|
439
|
+
const path = (id) => join(dir, `${id}.json`);
|
|
440
|
+
let ready = null;
|
|
441
|
+
let lastPurge = 0;
|
|
442
|
+
const purge = async (now) => {
|
|
443
|
+
if (now - lastPurge < PURGE_EVERY_MS) return;
|
|
444
|
+
lastPurge = now;
|
|
445
|
+
for (const f of await readdir(dir)) {
|
|
446
|
+
const file = join(dir, f);
|
|
447
|
+
try {
|
|
448
|
+
if (JSON.parse(await readFile(file, "utf8")).expires < now) await rm(file, { force: true });
|
|
449
|
+
} catch {
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
return {
|
|
454
|
+
async get(id) {
|
|
455
|
+
if (!SAFE_ID.test(id)) return void 0;
|
|
456
|
+
try {
|
|
457
|
+
return JSON.parse(await readFile(path(id), "utf8"));
|
|
458
|
+
} catch {
|
|
459
|
+
return void 0;
|
|
460
|
+
}
|
|
461
|
+
},
|
|
462
|
+
async put(id, p, now) {
|
|
463
|
+
if (!SAFE_ID.test(id)) throw new Error(`bad proposal id ${id}`);
|
|
464
|
+
ready ??= mkdir(dir, { recursive: true, mode: 448 }).then(() => chmod(dir, 448));
|
|
465
|
+
await ready;
|
|
466
|
+
await writeFile(path(id), JSON.stringify(p), { mode: 384 });
|
|
467
|
+
await purge(now);
|
|
468
|
+
},
|
|
469
|
+
async delete(id) {
|
|
470
|
+
if (SAFE_ID.test(id)) await rm(path(id), { force: true });
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// src/registry.ts
|
|
476
|
+
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
|
|
477
|
+
import { join as join2 } from "node:path";
|
|
478
|
+
import { contractHash as contractHash2 } from "@crasi/bisque-contract";
|
|
479
|
+
|
|
480
|
+
// src/conductor.ts
|
|
481
|
+
import { constantTimeEqual, formatProblems, verifyToken } from "@crasi/bisque-core";
|
|
482
|
+
import { contractHash, sharedFieldKeys } from "@crasi/bisque-contract";
|
|
483
|
+
import {
|
|
484
|
+
DiagnosticsSchema,
|
|
485
|
+
PushRequestSchema,
|
|
486
|
+
ProposeRequestSchema,
|
|
487
|
+
repairReason,
|
|
488
|
+
validateAutomation,
|
|
489
|
+
validateDraft,
|
|
490
|
+
validateThemeTokens
|
|
491
|
+
} from "@crasi/bisque-spec";
|
|
492
|
+
|
|
493
|
+
// src/limits.ts
|
|
494
|
+
var DEFAULT_LIMITS = { userPerMinute: 20, tenantPerMinute: 120, tenantTokensPerDay: 5e6 };
|
|
495
|
+
var MINUTE = 6e4;
|
|
496
|
+
var DAY = 864e5;
|
|
497
|
+
var MAX_TRACKED_KEYS = 1e4;
|
|
498
|
+
function memoryLimiter(opts = {}) {
|
|
499
|
+
const o = { ...DEFAULT_LIMITS, ...opts };
|
|
500
|
+
const hits = /* @__PURE__ */ new Map();
|
|
501
|
+
const spent = /* @__PURE__ */ new Map();
|
|
502
|
+
const recent = (key, now) => (hits.get(key) ?? []).filter((t) => now - t < MINUTE);
|
|
503
|
+
const prune = (now) => {
|
|
504
|
+
if (hits.size > MAX_TRACKED_KEYS) {
|
|
505
|
+
for (const [k, ts] of hits) if (!ts.some((t) => now - t < MINUTE)) hits.delete(k);
|
|
506
|
+
}
|
|
507
|
+
const day = Math.floor(now / DAY);
|
|
508
|
+
if (spent.size > MAX_TRACKED_KEYS) {
|
|
509
|
+
for (const [k, s] of spent) if (s.day !== day) spent.delete(k);
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
const retryAfter = (ts, now) => Math.max(1, Math.ceil((ts[0] + MINUTE - now) / 1e3));
|
|
513
|
+
return {
|
|
514
|
+
check(claims, now) {
|
|
515
|
+
prune(now);
|
|
516
|
+
const tenantKey = `${claims.app}/${claims.tenant}`;
|
|
517
|
+
const day = Math.floor(now / DAY);
|
|
518
|
+
const budget = spent.get(tenantKey);
|
|
519
|
+
if (budget?.day === day && budget.tokens >= o.tenantTokensPerDay) return { ok: false, reason: "tenant_budget", retryAfterSeconds: Math.ceil(((day + 1) * DAY - now) / 1e3) };
|
|
520
|
+
const userKey = `${tenantKey}/${claims.sub}`;
|
|
521
|
+
const user = recent(userKey, now);
|
|
522
|
+
if (user.length >= o.userPerMinute) return { ok: false, reason: "user_rate", retryAfterSeconds: retryAfter(user, now) };
|
|
523
|
+
const tenant = recent(tenantKey, now);
|
|
524
|
+
if (tenant.length >= o.tenantPerMinute) return { ok: false, reason: "tenant_rate", retryAfterSeconds: retryAfter(tenant, now) };
|
|
525
|
+
hits.set(userKey, [...user, now]);
|
|
526
|
+
hits.set(tenantKey, [...tenant, now]);
|
|
527
|
+
return { ok: true };
|
|
528
|
+
},
|
|
529
|
+
spend(claims, tokens, now) {
|
|
530
|
+
const key = `${claims.app}/${claims.tenant}`;
|
|
531
|
+
const day = Math.floor(now / DAY);
|
|
532
|
+
const s = spent.get(key);
|
|
533
|
+
spent.set(key, { day, tokens: (s?.day === day ? s.tokens : 0) + tokens });
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/conductor.ts
|
|
539
|
+
var ConductorError = class extends Error {
|
|
540
|
+
constructor(status, message, problems, retryAfterSeconds) {
|
|
541
|
+
super(message);
|
|
542
|
+
this.status = status;
|
|
543
|
+
this.problems = problems;
|
|
544
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
545
|
+
}
|
|
546
|
+
status;
|
|
547
|
+
problems;
|
|
548
|
+
retryAfterSeconds;
|
|
549
|
+
};
|
|
550
|
+
function limitMessage(reason, retryAfterSeconds) {
|
|
551
|
+
if (reason === "tenant_budget") return "This workspace has reached today's limit for the assistant. Try again tomorrow.";
|
|
552
|
+
return `Too many requests. Try again in ${retryAfterSeconds} seconds.`;
|
|
553
|
+
}
|
|
554
|
+
var proposalId = () => `p_${crypto.randomUUID()}`;
|
|
555
|
+
var Conductor = class {
|
|
556
|
+
o;
|
|
557
|
+
constructor(opts) {
|
|
558
|
+
this.o = {
|
|
559
|
+
maxTokens: 16e3,
|
|
560
|
+
proposalTtlMs: 30 * 6e4,
|
|
561
|
+
now: Date.now,
|
|
562
|
+
...opts,
|
|
563
|
+
proposals: opts.proposals ?? memoryProposals(),
|
|
564
|
+
limiter: opts.limiter ?? memoryLimiter(),
|
|
565
|
+
effort: { spec: "medium", refine: "low", repair: "medium", ...opts.effort }
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
/** Verifies a session token minted by the host's token route. */
|
|
569
|
+
async authenticate(authorization) {
|
|
570
|
+
const token = authorization?.replace(/^Bearer\s+/i, "");
|
|
571
|
+
if (!token) throw new ConductorError(401, "missing session token");
|
|
572
|
+
const unverified = decodeApp(token);
|
|
573
|
+
const app = unverified && this.o.registry.app(unverified);
|
|
574
|
+
if (!app) throw new ConductorError(401, "unknown app");
|
|
575
|
+
const v = await verifyToken(token, app.secretKey, this.o.now());
|
|
576
|
+
if (!v.ok) throw new ConductorError(401, `session token ${v.error}`);
|
|
577
|
+
return v.claims;
|
|
578
|
+
}
|
|
579
|
+
/** `bisque push`: stores a contract manifest, only with a review signed for exactly this hash. */
|
|
580
|
+
async push(app, secret, body) {
|
|
581
|
+
const cfg = this.o.registry.app(app);
|
|
582
|
+
if (!cfg || !secret || !constantTimeEqual(secret.replace(/^Bearer\s+/i, ""), cfg.secretKey)) throw new ConductorError(401, "bad secret key");
|
|
583
|
+
const parsed = PushRequestSchema.safeParse(body);
|
|
584
|
+
if (!parsed.success) throw new ConductorError(400, "bad push body");
|
|
585
|
+
const manifest = parsed.data.manifest;
|
|
586
|
+
if (manifest.app !== app) throw new ConductorError(400, "manifest is for another app");
|
|
587
|
+
const hash = await contractHash(manifest);
|
|
588
|
+
if (parsed.data.review.contractHash !== hash) throw new ConductorError(422, "the review sheet was signed for a different contract; run bisque review --sign again");
|
|
589
|
+
await this.o.registry.put({ manifest, hash, review: parsed.data.review, pushedAt: new Date(this.o.now()).toISOString() });
|
|
590
|
+
return { hash, version: manifest.version };
|
|
591
|
+
}
|
|
592
|
+
async propose(claims, body) {
|
|
593
|
+
const parsed = ProposeRequestSchema.safeParse(body);
|
|
594
|
+
if (!parsed.success)
|
|
595
|
+
throw new ConductorError(
|
|
596
|
+
400,
|
|
597
|
+
"bad request",
|
|
598
|
+
parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }))
|
|
599
|
+
);
|
|
600
|
+
const req = parsed.data;
|
|
601
|
+
if (req.contract.app !== claims.app) throw new ConductorError(403, "token is for another app");
|
|
602
|
+
await this.enforceLimits(claims);
|
|
603
|
+
const stored = await this.o.registry.get(req.contract.app, req.contract.hash);
|
|
604
|
+
if (!stored) throw new ConductorError(409, "contract not pushed; run bisque push");
|
|
605
|
+
const m = stored.manifest;
|
|
606
|
+
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`);
|
|
607
|
+
const shareable = new Set(sharedFieldKeys(m));
|
|
608
|
+
for (const k of Object.keys(req.sharedValues ?? {})) if (!shareable.has(k)) throw new ConductorError(400, `${k} is not a shared field`);
|
|
609
|
+
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`);
|
|
610
|
+
if (req.context.slot && !m.slots[req.context.slot]) throw new ConductorError(400, `unknown slot ${req.context.slot}`);
|
|
611
|
+
const callType = req.current || req.currentAutomation ? "refine" : "spec";
|
|
612
|
+
const automations = !!req.automations && !!m.automations;
|
|
613
|
+
const refused = await this.o.admit?.(claims, callType);
|
|
614
|
+
if (refused) return { type: "error", message: refused };
|
|
615
|
+
const system = systemBlocks(m, req.sharedValues);
|
|
616
|
+
const messages = [];
|
|
617
|
+
for (const h of req.history) messages.push({ role: h.role, content: [{ type: "text", text: h.text }] });
|
|
618
|
+
if (messages[0]?.role === "assistant") messages.unshift({ role: "user", content: [{ type: "text", text: "(earlier conversation)" }] });
|
|
619
|
+
const turn = [
|
|
620
|
+
`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 })}`,
|
|
621
|
+
req.theme ? `Current theme: ${JSON.stringify(req.theme)}` : "",
|
|
622
|
+
req.current ? `Current draft (revise this):
|
|
623
|
+
${JSON.stringify(req.current)}` : "",
|
|
624
|
+
req.currentAutomation ? `Current automation (revise this):
|
|
625
|
+
${JSON.stringify(req.currentAutomation)}` : "",
|
|
626
|
+
`User: ${req.prompt}`
|
|
627
|
+
].filter(Boolean).join("\n\n");
|
|
628
|
+
messages.push({ role: "user", content: [{ type: "text", text: turn }] });
|
|
629
|
+
return this.turn({ claims, m, hash: stored.hash, system, automations }, messages, callType, 1);
|
|
630
|
+
}
|
|
631
|
+
async enforceLimits(claims) {
|
|
632
|
+
if (!this.o.limiter) return;
|
|
633
|
+
const d = await this.o.limiter.check(claims, this.o.now());
|
|
634
|
+
if (d.ok) return;
|
|
635
|
+
await this.o.usage?.record({ kind: "limited", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, reason: d.reason });
|
|
636
|
+
throw new ConductorError(429, limitMessage(d.reason, d.retryAfterSeconds), void 0, d.retryAfterSeconds);
|
|
637
|
+
}
|
|
638
|
+
async call(claims, system, messages, callType) {
|
|
639
|
+
const t0 = this.o.now();
|
|
640
|
+
let res;
|
|
641
|
+
try {
|
|
642
|
+
res = await this.o.model.complete({ system, messages, tools: TOOLS, effort: this.o.effort[callType], maxTokens: this.o.maxTokens, callType });
|
|
643
|
+
} catch (e) {
|
|
644
|
+
const status = e.status;
|
|
645
|
+
await this.o.usage?.record({
|
|
646
|
+
kind: "model_error",
|
|
647
|
+
at: new Date(this.o.now()).toISOString(),
|
|
648
|
+
app: claims.app,
|
|
649
|
+
tenant: claims.tenant,
|
|
650
|
+
callType,
|
|
651
|
+
provider: this.o.model.name,
|
|
652
|
+
latencyMs: this.o.now() - t0,
|
|
653
|
+
status: typeof status === "number" ? status : null,
|
|
654
|
+
error: e instanceof Error ? e.constructor.name : "unknown"
|
|
655
|
+
});
|
|
656
|
+
throw new ConductorError(503, "The assistant is unavailable right now. Try again shortly.");
|
|
657
|
+
}
|
|
658
|
+
if (this.o.limiter) await this.o.limiter.spend(claims, res.usage.input + res.usage.output + res.usage.cacheWrite, this.o.now());
|
|
659
|
+
return { res, latencyMs: this.o.now() - t0 };
|
|
660
|
+
}
|
|
661
|
+
async log(claims, callType, res, latencyMs, outcome) {
|
|
662
|
+
await this.o.usage?.record({
|
|
663
|
+
kind: "model_call",
|
|
664
|
+
at: new Date(this.o.now()).toISOString(),
|
|
665
|
+
app: claims.app,
|
|
666
|
+
tenant: claims.tenant,
|
|
667
|
+
callType,
|
|
668
|
+
model: res.model,
|
|
669
|
+
...res.provider ? { provider: res.provider } : {},
|
|
670
|
+
latencyMs,
|
|
671
|
+
outcome,
|
|
672
|
+
...res.usage
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
/** One repair turn: the host's problems go back to the model as the tool's error result. */
|
|
676
|
+
async repair(c, history, toolId, tool, problems, repairsLeft) {
|
|
677
|
+
if (repairsLeft <= 0) return { type: "error", message: "The proposal did not pass validation.", problems: problems.map(({ path, message }) => ({ path, message })) };
|
|
678
|
+
history.push({
|
|
679
|
+
role: "user",
|
|
680
|
+
content: [
|
|
681
|
+
{
|
|
682
|
+
type: "tool_result",
|
|
683
|
+
tool_use_id: toolId,
|
|
684
|
+
is_error: true,
|
|
685
|
+
content: `The host rejected this proposal:
|
|
686
|
+
${formatProblems(problems)}
|
|
687
|
+
Fix these problems and call ${tool} again with the complete proposal, or use explain_limit if it cannot be done.`
|
|
688
|
+
}
|
|
689
|
+
]
|
|
690
|
+
});
|
|
691
|
+
const repaired = await this.turn(c, history, "repair", repairsLeft - 1);
|
|
692
|
+
return repaired.type === "proposal" || repaired.type === "theme" || repaired.type === "automation" ? { ...repaired, repaired: true } : repaired;
|
|
693
|
+
}
|
|
694
|
+
async turn(c, messages, callType, repairsLeft) {
|
|
695
|
+
const { claims, m } = c;
|
|
696
|
+
const { res, latencyMs } = await this.call(claims, c.system, messages, callType);
|
|
697
|
+
if (res.stopReason === "refusal") {
|
|
698
|
+
await this.log(claims, callType, res, latencyMs, "error");
|
|
699
|
+
return { type: "error", message: "The assistant declined this request." };
|
|
700
|
+
}
|
|
701
|
+
const tool = res.content.find((b) => b.type === "tool_use");
|
|
702
|
+
const text = res.content.filter((b) => b.type === "text").map((b) => b.text).join("\n").trim();
|
|
703
|
+
if (!tool) {
|
|
704
|
+
await this.log(claims, callType, res, latencyMs, "answer");
|
|
705
|
+
return text ? { type: "answer", text } : { type: "error", message: "No proposal came back. Try rephrasing." };
|
|
706
|
+
}
|
|
707
|
+
const input = tool.input ?? {};
|
|
708
|
+
const note = typeof input.note === "string" ? input.note.slice(0, 300) : void 0;
|
|
709
|
+
const history = [...messages, { role: "assistant", content: res.content }];
|
|
710
|
+
switch (tool.name) {
|
|
711
|
+
case "ask":
|
|
712
|
+
await this.log(claims, callType, res, latencyMs, "ask");
|
|
713
|
+
return { type: "ask", question: String(input.question ?? ""), options: Array.isArray(input.options) ? input.options.map(String).slice(0, 4) : [] };
|
|
714
|
+
case "explain_limit": {
|
|
715
|
+
await this.log(claims, callType, res, latencyMs, "limit");
|
|
716
|
+
const capability = String(input.capability ?? "unspecified").slice(0, 80);
|
|
717
|
+
await this.o.usage?.record({ kind: "ceiling", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, capability });
|
|
718
|
+
return { type: "limit", message: String(input.message ?? ""), capability, nearest: input.nearest ? String(input.nearest) : void 0 };
|
|
719
|
+
}
|
|
720
|
+
case "propose_theme": {
|
|
721
|
+
const v = validateThemeTokens(input.tokens, m, { role: claims.role });
|
|
722
|
+
if (!v.ok) {
|
|
723
|
+
await this.log(claims, callType, res, latencyMs, "invalid");
|
|
724
|
+
return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);
|
|
725
|
+
}
|
|
726
|
+
await this.log(claims, callType, res, latencyMs, "theme");
|
|
727
|
+
return { type: "theme", proposalId: proposalId(), tokens: v.tokens, repaired: false, note };
|
|
728
|
+
}
|
|
729
|
+
case "propose_automation": {
|
|
730
|
+
if (!c.automations) {
|
|
731
|
+
await this.log(claims, callType, res, latencyMs, "limit");
|
|
732
|
+
await this.o.usage?.record({ kind: "ceiling", at: new Date(this.o.now()).toISOString(), app: claims.app, tenant: claims.tenant, capability: "automations" });
|
|
733
|
+
return { type: "limit", message: "Automations are not available here.", capability: "automations" };
|
|
734
|
+
}
|
|
735
|
+
const v = validateAutomation(input.automation, m, { role: claims.role });
|
|
736
|
+
if (!v.ok || !v.automation) {
|
|
737
|
+
await this.log(claims, callType, res, latencyMs, "invalid");
|
|
738
|
+
return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);
|
|
739
|
+
}
|
|
740
|
+
await this.log(claims, callType, res, latencyMs, "automation");
|
|
741
|
+
return { type: "automation", proposalId: proposalId(), automation: v.automation, repaired: false, note };
|
|
742
|
+
}
|
|
743
|
+
case "propose_spec": {
|
|
744
|
+
const v = validateDraft(input.draft, m, { role: claims.role });
|
|
745
|
+
if (!v.ok || !v.draft) {
|
|
746
|
+
await this.log(claims, callType, res, latencyMs, "invalid");
|
|
747
|
+
return this.repair(c, history, tool.id, tool.name, v.problems, repairsLeft);
|
|
748
|
+
}
|
|
749
|
+
await this.log(claims, callType, res, latencyMs, "proposal");
|
|
750
|
+
const id = proposalId();
|
|
751
|
+
await this.o.proposals.put(
|
|
752
|
+
id,
|
|
753
|
+
{
|
|
754
|
+
claims,
|
|
755
|
+
contract: { app: m.app, hash: c.hash },
|
|
756
|
+
system: c.system,
|
|
757
|
+
messages: history,
|
|
758
|
+
toolUseId: tool.id,
|
|
759
|
+
draft: v.draft,
|
|
760
|
+
repairsLeft,
|
|
761
|
+
expires: this.o.now() + this.o.proposalTtlMs
|
|
762
|
+
},
|
|
763
|
+
this.o.now()
|
|
764
|
+
);
|
|
765
|
+
return { type: "proposal", proposalId: id, draft: v.draft, repaired: false, note };
|
|
766
|
+
}
|
|
767
|
+
default:
|
|
768
|
+
await this.log(claims, callType, res, latencyMs, "error");
|
|
769
|
+
return { type: "error", message: `unknown tool ${tool.name}` };
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Render diagnostics from the host's preview (§6.8). Strictly bucketed; the
|
|
774
|
+
* conductor rejects anything else. May spend the proposal's one repair turn.
|
|
775
|
+
*/
|
|
776
|
+
async diagnostics(claims, id, body) {
|
|
777
|
+
const p = await this.o.proposals.get(id);
|
|
778
|
+
if (!p || p.expires < this.o.now()) throw new ConductorError(404, "unknown or expired proposal");
|
|
779
|
+
if (p.claims.app !== claims.app || p.claims.tenant !== claims.tenant || p.claims.sub !== claims.sub) throw new ConductorError(403, "not your proposal");
|
|
780
|
+
const parsed = DiagnosticsSchema.safeParse(body);
|
|
781
|
+
if (!parsed.success) throw new ConductorError(400, "diagnostics must be bucketed counts only");
|
|
782
|
+
const d = parsed.data;
|
|
783
|
+
const columns = /* @__PURE__ */ new Set([...p.draft.body.data.groupBy ?? [], ...p.draft.body.data.select ?? [], ...(p.draft.body.data.measures ?? []).map((x) => x.as)]);
|
|
784
|
+
for (const k of [...Object.keys(d.distinct), ...Object.keys(d.nullShare)])
|
|
785
|
+
if (!columns.has(k)) throw new ConductorError(400, `diagnostics key ${k} is not a column of the proposal`);
|
|
786
|
+
const reason = repairReason(d);
|
|
787
|
+
if (!reason) return { type: "ok" };
|
|
788
|
+
if (p.repairsLeft <= 0) return { type: "ok", note: "repair budget used" };
|
|
789
|
+
const stored = await this.o.registry.get(p.contract.app, p.contract.hash);
|
|
790
|
+
if (!stored) return { type: "ok", note: "contract no longer available" };
|
|
791
|
+
await this.enforceLimits(claims);
|
|
792
|
+
await this.o.proposals.delete(id);
|
|
793
|
+
const messages = [
|
|
794
|
+
...p.messages,
|
|
795
|
+
{
|
|
796
|
+
role: "user",
|
|
797
|
+
content: [
|
|
798
|
+
{
|
|
799
|
+
type: "tool_result",
|
|
800
|
+
tool_use_id: p.toolUseId,
|
|
801
|
+
is_error: true,
|
|
802
|
+
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.`
|
|
803
|
+
}
|
|
804
|
+
]
|
|
805
|
+
}
|
|
806
|
+
];
|
|
807
|
+
const r = await this.turn({ claims, m: stored.manifest, hash: stored.hash, system: p.system, automations: false }, messages, "repair", 0);
|
|
808
|
+
if (r.type === "proposal") return { ...r, repaired: true };
|
|
809
|
+
if (r.type === "error") return r;
|
|
810
|
+
return { type: "ok", note: r.type === "answer" ? r.text : void 0 };
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
function decodeApp(token) {
|
|
814
|
+
try {
|
|
815
|
+
const payload = token.split(".")[1];
|
|
816
|
+
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
|
817
|
+
return typeof json.app === "string" ? json.app : void 0;
|
|
818
|
+
} catch {
|
|
819
|
+
return void 0;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// src/registry.ts
|
|
824
|
+
function memoryRegistry(apps) {
|
|
825
|
+
const contracts = /* @__PURE__ */ new Map();
|
|
826
|
+
const byApp = new Map(apps.map((a) => [a.app, a]));
|
|
827
|
+
return {
|
|
828
|
+
app: (a) => byApp.get(a),
|
|
829
|
+
apps: () => [...byApp.values()],
|
|
830
|
+
get: async (app, hash) => contracts.get(`${app}/${hash}`),
|
|
831
|
+
put: async (c) => void contracts.set(`${c.manifest.app}/${c.hash}`, c)
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
function fileRegistry(apps, dir) {
|
|
835
|
+
const mem = memoryRegistry(apps);
|
|
836
|
+
return {
|
|
837
|
+
app: mem.app,
|
|
838
|
+
apps: mem.apps,
|
|
839
|
+
async get(app, hash) {
|
|
840
|
+
const hit = await mem.get(app, hash);
|
|
841
|
+
if (hit) return hit;
|
|
842
|
+
if (!/^[0-9a-f]{64}$/.test(hash) || !/^[\w.-]+$/.test(app)) return void 0;
|
|
843
|
+
try {
|
|
844
|
+
const c = JSON.parse(await readFile2(join2(dir, app, `${hash}.json`), "utf8"));
|
|
845
|
+
await mem.put(c);
|
|
846
|
+
return c;
|
|
847
|
+
} catch {
|
|
848
|
+
return void 0;
|
|
849
|
+
}
|
|
850
|
+
},
|
|
851
|
+
async put(c) {
|
|
852
|
+
await mem.put(c);
|
|
853
|
+
await mkdir2(join2(dir, c.manifest.app), { recursive: true });
|
|
854
|
+
await writeFile2(join2(dir, c.manifest.app, `${c.hash}.json`), JSON.stringify(c, null, 2));
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
function staticRegistry(apps, contracts, opts = {}) {
|
|
859
|
+
const mem = memoryRegistry(apps);
|
|
860
|
+
const requireSignature = opts.requireSignature ?? true;
|
|
861
|
+
const unsigned = /* @__PURE__ */ new Map();
|
|
862
|
+
let ready = null;
|
|
863
|
+
const load = () => ready ??= (async () => {
|
|
864
|
+
for (const c of contracts) {
|
|
865
|
+
const hash = await contractHash2(c.manifest);
|
|
866
|
+
const signed = c.review?.contractHash === hash;
|
|
867
|
+
if (!signed) opts.onUnsigned?.(c.manifest.app, hash);
|
|
868
|
+
if (!signed && requireSignature) unsigned.set(`${c.manifest.app}/${hash}`, c.review);
|
|
869
|
+
if (signed || !requireSignature)
|
|
870
|
+
await mem.put({
|
|
871
|
+
manifest: c.manifest,
|
|
872
|
+
hash,
|
|
873
|
+
review: c.review ?? { contractHash: hash, signer: "(unsigned, development)", signedAt: "" },
|
|
874
|
+
pushedAt: (/* @__PURE__ */ new Date(0)).toISOString()
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
})();
|
|
878
|
+
return {
|
|
879
|
+
app: mem.app,
|
|
880
|
+
apps: mem.apps,
|
|
881
|
+
async get(app, hash) {
|
|
882
|
+
await load();
|
|
883
|
+
const hit = await mem.get(app, hash);
|
|
884
|
+
if (hit) return hit;
|
|
885
|
+
if (unsigned.has(`${app}/${hash}`)) {
|
|
886
|
+
const review = unsigned.get(`${app}/${hash}`);
|
|
887
|
+
throw new ConductorError(
|
|
888
|
+
409,
|
|
889
|
+
review ? `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` : `the ${app} contract has no signed review sheet; run bisque review --sign and redeploy with bisque.review.json`
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
if (mem.app(app)) throw new ConductorError(409, "this page was built with a different version of the app; reload it");
|
|
893
|
+
return void 0;
|
|
894
|
+
},
|
|
895
|
+
async put() {
|
|
896
|
+
throw new Error("this registry serves the host's bundled contract; it does not accept pushes");
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// src/usage.ts
|
|
902
|
+
import { appendFile, mkdir as mkdir3 } from "node:fs/promises";
|
|
903
|
+
import { dirname } from "node:path";
|
|
904
|
+
function memoryUsage() {
|
|
905
|
+
const events = [];
|
|
906
|
+
return { events, record: (e) => void events.push(e) };
|
|
907
|
+
}
|
|
908
|
+
function jsonlUsage(path) {
|
|
909
|
+
let ready = null;
|
|
910
|
+
return {
|
|
911
|
+
async record(e) {
|
|
912
|
+
ready ??= mkdir3(dirname(path), { recursive: true });
|
|
913
|
+
await ready;
|
|
914
|
+
await appendFile(path, `${JSON.stringify(e)}
|
|
915
|
+
`);
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/app.ts
|
|
921
|
+
import { Hono } from "hono";
|
|
922
|
+
import { bodyLimit } from "hono/body-limit";
|
|
923
|
+
import { cors } from "hono/cors";
|
|
924
|
+
import { HTTPException } from "hono/http-exception";
|
|
925
|
+
var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
926
|
+
async function readJson(c) {
|
|
927
|
+
try {
|
|
928
|
+
return await c.req.json();
|
|
929
|
+
} catch (e) {
|
|
930
|
+
if (e instanceof HTTPException) throw e;
|
|
931
|
+
throw new ConductorError(400, "the request body is not valid JSON");
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
function createConductorApp(opts) {
|
|
935
|
+
const conductor = opts.conductor ?? new Conductor(opts);
|
|
936
|
+
const app = opts.basePath ? new Hono().basePath(opts.basePath.replace(/\/$/, "")) : new Hono();
|
|
937
|
+
app.use(
|
|
938
|
+
"/v1/*",
|
|
939
|
+
cors({
|
|
940
|
+
// Preflights carry no credentials, so allow any origin some registered app lists.
|
|
941
|
+
origin: (origin) => opts.registry.apps().some((a) => a.allowedOrigins.includes(origin)) ? origin : null,
|
|
942
|
+
allowHeaders: ["authorization", "content-type"],
|
|
943
|
+
allowMethods: ["POST", "GET", "OPTIONS"],
|
|
944
|
+
maxAge: 600
|
|
945
|
+
})
|
|
946
|
+
);
|
|
947
|
+
app.use("/v1/*", bodyLimit({ maxSize: opts.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES, onError: (c) => c.json({ error: "the request body is too large" }, 413) }));
|
|
948
|
+
app.onError((err, c) => {
|
|
949
|
+
if (err instanceof HTTPException) return err.getResponse();
|
|
950
|
+
if (err instanceof ConductorError) {
|
|
951
|
+
if (err.retryAfterSeconds) c.header("retry-after", String(err.retryAfterSeconds));
|
|
952
|
+
return c.json({ error: err.message, problems: err.problems }, err.status);
|
|
953
|
+
}
|
|
954
|
+
console.error(err);
|
|
955
|
+
return c.json({ error: "internal error" }, 500);
|
|
956
|
+
});
|
|
957
|
+
app.get("/health", (c) => c.json({ ok: true, model: opts.model.name }));
|
|
958
|
+
app.post("/v1/apps/:app/contracts", async (c) => c.json(await conductor.push(c.req.param("app"), c.req.header("authorization"), await readJson(c))));
|
|
959
|
+
app.post("/v1/propose", async (c) => {
|
|
960
|
+
const claims = await conductor.authenticate(c.req.header("authorization"));
|
|
961
|
+
return c.json(await conductor.propose(claims, await readJson(c)));
|
|
962
|
+
});
|
|
963
|
+
app.post("/v1/proposals/:id/diagnostics", async (c) => {
|
|
964
|
+
const claims = await conductor.authenticate(c.req.header("authorization"));
|
|
965
|
+
return c.json(await conductor.diagnostics(claims, c.req.param("id"), await readJson(c)));
|
|
966
|
+
});
|
|
967
|
+
return app;
|
|
968
|
+
}
|
|
969
|
+
export {
|
|
970
|
+
AnthropicProvider,
|
|
971
|
+
Conductor,
|
|
972
|
+
ConductorError,
|
|
973
|
+
DEFAULT_LIMITS,
|
|
974
|
+
DEFAULT_MODEL,
|
|
975
|
+
GeminiProvider,
|
|
976
|
+
OpenAIProvider,
|
|
977
|
+
ProviderError,
|
|
978
|
+
ScriptedProvider,
|
|
979
|
+
TOOLS,
|
|
980
|
+
createConductorApp,
|
|
981
|
+
fallbackProvider,
|
|
982
|
+
fileProposals,
|
|
983
|
+
fileRegistry,
|
|
984
|
+
isRetryable,
|
|
985
|
+
jsonlUsage,
|
|
986
|
+
memoryLimiter,
|
|
987
|
+
memoryProposalStore,
|
|
988
|
+
memoryProposals,
|
|
989
|
+
memoryRegistry,
|
|
990
|
+
memoryUsage,
|
|
991
|
+
staticRegistry,
|
|
992
|
+
systemBlocks,
|
|
993
|
+
toChatMessages,
|
|
994
|
+
toContents,
|
|
995
|
+
toolUse
|
|
996
|
+
};
|
|
997
|
+
//# sourceMappingURL=index.js.map
|