sordo 0.0.0-stage → 0.2.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/CHANGELOG.md +101 -0
- package/CLAUDE.md +124 -0
- package/README.md +102 -2
- package/bin/sordo.ts +5 -0
- package/package.json +64 -5
- package/src/adapters/bun.ts +59 -0
- package/src/adapters/edge.ts +38 -0
- package/src/adapters/types.ts +39 -0
- package/src/agents-md/collect.ts +113 -0
- package/src/agents-md/generate.ts +44 -0
- package/src/agents-md/index.ts +9 -0
- package/src/agents-md/render.ts +150 -0
- package/src/agents-md/subprocess-entry.ts +92 -0
- package/src/agents-md/subprocess-runner.ts +111 -0
- package/src/agents-md/write.ts +38 -0
- package/src/agents-md/zod-to-json-schema.ts +18 -0
- package/src/ai/context.ts +72 -0
- package/src/ai/define.ts +15 -0
- package/src/ai/errors.ts +51 -0
- package/src/ai/index.ts +36 -0
- package/src/ai/middleware.ts +21 -0
- package/src/ai/registry.ts +96 -0
- package/src/ai/run.ts +185 -0
- package/src/ai/scan.ts +42 -0
- package/src/ai/stream.ts +71 -0
- package/src/ai/triggers.ts +124 -0
- package/src/ai/types.ts +67 -0
- package/src/ai/validate.ts +82 -0
- package/src/build/assets.ts +48 -0
- package/src/build/client-entry.ts +43 -0
- package/src/build/embedded.ts +66 -0
- package/src/build/hash.ts +21 -0
- package/src/build/index.ts +437 -0
- package/src/build/macros/agents-hash.macro.ts +9 -0
- package/src/build/macros/agents.macro.ts +21 -0
- package/src/build/macros/env.macro.ts +25 -0
- package/src/build/macros/manifest.macro.ts +8 -0
- package/src/build/macros/routes.macro.ts +10 -0
- package/src/build/page-entry.ts +136 -0
- package/src/build/scan-islands.ts +39 -0
- package/src/build/server-entry.ts +237 -0
- package/src/cli/ansi.ts +41 -0
- package/src/cli/build.ts +183 -0
- package/src/cli/commands/add/apply.ts +31 -0
- package/src/cli/commands/add/component-diff.ts +116 -0
- package/src/cli/commands/add/diff.ts +153 -0
- package/src/cli/commands/add/internal.ts +41 -0
- package/src/cli/commands/add/load-catalog.ts +22 -0
- package/src/cli/commands/add/peer-deps.ts +115 -0
- package/src/cli/commands/add/registry-fetch.ts +122 -0
- package/src/cli/commands/add/shadcn.ts +285 -0
- package/src/cli/commands/add/source.ts +273 -0
- package/src/cli/commands/add/stamper.ts +73 -0
- package/src/cli/commands/add/tokens.ts +81 -0
- package/src/cli/commands/add/ui-paths.ts +113 -0
- package/src/cli/commands/add.ts +427 -0
- package/src/cli/commands/deploy.ts +143 -0
- package/src/cli/commands/migrate.ts +149 -0
- package/src/cli/commands/secret.ts +316 -0
- package/src/cli/commands/ui/build.ts +111 -0
- package/src/cli/commands/ui/init.ts +132 -0
- package/src/cli/commands/ui/migrate/git-guard.ts +19 -0
- package/src/cli/commands/ui/migrate/radix.ts +67 -0
- package/src/cli/commands/ui/migrate/rtl.ts +148 -0
- package/src/cli/commands/ui/shadcn.ts +82 -0
- package/src/cli/commands/ui/view.ts +63 -0
- package/src/cli/commands/ui.ts +86 -0
- package/src/cli/commands/update.ts +134 -0
- package/src/cli/commands/upgrade.ts +53 -0
- package/src/cli/commands/view.ts +34 -0
- package/src/cli/dev.ts +393 -0
- package/src/cli/doctor/config-checks.ts +63 -0
- package/src/cli/doctor/deps.ts +295 -0
- package/src/cli/doctor/hydrate.ts +65 -0
- package/src/cli/doctor/monorepo.ts +158 -0
- package/src/cli/doctor/probes.ts +16 -0
- package/src/cli/doctor/report.ts +72 -0
- package/src/cli/doctor/toolchain.ts +95 -0
- package/src/cli/doctor/types.ts +36 -0
- package/src/cli/doctor.ts +127 -0
- package/src/cli/index.ts +163 -0
- package/src/cli/log.ts +135 -0
- package/src/cli/run/affected.ts +79 -0
- package/src/cli/run/cache-key.ts +177 -0
- package/src/cli/run/cache-store.ts +0 -0
- package/src/cli/run/files.ts +96 -0
- package/src/cli/run/git.ts +13 -0
- package/src/cli/run/runner.ts +189 -0
- package/src/cli/run/workspace.ts +216 -0
- package/src/cli/run.ts +184 -0
- package/src/cli/update-check.ts +157 -0
- package/src/client/index.ts +65 -0
- package/src/client/link.tsx +61 -0
- package/src/client/page.ts +250 -0
- package/src/config/define.ts +5 -0
- package/src/config/env.ts +36 -0
- package/src/config/load.ts +147 -0
- package/src/config/schema.ts +110 -0
- package/src/config/secrets.ts +108 -0
- package/src/dev/client.ts +97 -0
- package/src/dev/hot.ts +24 -0
- package/src/dev/index.ts +4 -0
- package/src/dev/tree.ts +95 -0
- package/src/dev/watcher.ts +95 -0
- package/src/index.ts +54 -0
- package/src/internal/hmr-client.ts +52 -0
- package/src/internal/open-in-editor.ts +23 -0
- package/src/internal/runtime.ts +30 -0
- package/src/middleware/cookie-jar.ts +135 -0
- package/src/middleware/cookies.ts +60 -0
- package/src/middleware/index.ts +99 -0
- package/src/middleware/request-id.ts +22 -0
- package/src/middleware/response-helpers.ts +25 -0
- package/src/plugin/index.ts +109 -0
- package/src/render/bootstrap.ts +44 -0
- package/src/render/dev-error.tsx +73 -0
- package/src/render/index.tsx +253 -0
- package/src/render/island.tsx +33 -0
- package/src/render/meta.tsx +48 -0
- package/src/render/shell.tsx +41 -0
- package/src/router/conflict.ts +20 -0
- package/src/router/filesystem.ts +37 -0
- package/src/router/index.ts +247 -0
- package/src/router/match.ts +91 -0
- package/src/router/pattern.ts +88 -0
- package/src/server/index.ts +250 -0
- package/src/types.ts +53 -0
- package/src/ui/schema.ts +68 -0
- package/src/ui/types.ts +10 -0
- package/templates/_internal/cn.ts +6 -0
- package/templates/_internal/slot.ts +50 -0
- package/templates/_internal/variants.ts +1 -0
- package/templates/themes/neutral/tokens.css +46 -0
- package/templates/themes/slate/tokens.css +46 -0
- package/templates/themes/stone/tokens.css +46 -0
- package/templates/themes/zinc/tokens.css +46 -0
- package/templates/tokens.css +46 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Plugin } from "../plugin/index.ts";
|
|
2
|
+
import { collect } from "./collect.ts";
|
|
3
|
+
import { render } from "./render.ts";
|
|
4
|
+
|
|
5
|
+
export interface ResolvedConfigLike {
|
|
6
|
+
appDir?: string;
|
|
7
|
+
env?: { required?: string[]; optional?: string[] };
|
|
8
|
+
plugins?: Plugin[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Public entry point for spec 11. Caller writes the returned string to disk.
|
|
12
|
+
export async function generateAgentsMd(
|
|
13
|
+
appDir: string,
|
|
14
|
+
config: ResolvedConfigLike = {},
|
|
15
|
+
): Promise<string> {
|
|
16
|
+
const envVars: Array<{
|
|
17
|
+
name: string;
|
|
18
|
+
required: boolean;
|
|
19
|
+
description?: string;
|
|
20
|
+
}> = [];
|
|
21
|
+
for (const r of config.env?.required ?? [])
|
|
22
|
+
envVars.push({ name: r, required: true });
|
|
23
|
+
for (const o of config.env?.optional ?? [])
|
|
24
|
+
envVars.push({ name: o, required: false });
|
|
25
|
+
|
|
26
|
+
const data = await collect(appDir, envVars);
|
|
27
|
+
let doc = { markdown: render(data) };
|
|
28
|
+
|
|
29
|
+
for (const p of config.plugins ?? []) {
|
|
30
|
+
const hook = p.hooks?.onAgentsMdGenerate;
|
|
31
|
+
if (typeof hook !== "function") continue;
|
|
32
|
+
try {
|
|
33
|
+
doc = await hook(doc);
|
|
34
|
+
} catch (err) {
|
|
35
|
+
const msg = (err as Error)?.message ?? String(err);
|
|
36
|
+
const wrapped = new Error(
|
|
37
|
+
`[plugin ${p.name}] onAgentsMdGenerate: ${msg}`,
|
|
38
|
+
);
|
|
39
|
+
(wrapped as Error & { cause?: unknown }).cause = err;
|
|
40
|
+
throw wrapped;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return doc.markdown;
|
|
44
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { collect } from "./collect.ts";
|
|
2
|
+
export type { ResolvedConfigLike } from "./generate.ts";
|
|
3
|
+
export { generateAgentsMd } from "./generate.ts";
|
|
4
|
+
export { render } from "./render.ts";
|
|
5
|
+
export {
|
|
6
|
+
MANIFEST_END,
|
|
7
|
+
MANIFEST_START,
|
|
8
|
+
writeManifestToFile,
|
|
9
|
+
} from "./write.ts";
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { CollectedData } from "./collect.ts";
|
|
2
|
+
|
|
3
|
+
// Deterministic Markdown rendering. Stable section order; alphabetical sort
|
|
4
|
+
// inside each section; canonical JSON in code blocks. Byte-identical for
|
|
5
|
+
// identical input — required by spec 11 acceptance.
|
|
6
|
+
export function render(data: CollectedData): string {
|
|
7
|
+
const out: string[] = [];
|
|
8
|
+
out.push(
|
|
9
|
+
"> Generated by `sordo dev/build`. Edits inside the manifest markers are overwritten; content outside is preserved.",
|
|
10
|
+
"",
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
out.push("## Route map", "");
|
|
14
|
+
if (data.routes.length === 0) {
|
|
15
|
+
out.push("_No routes._", "");
|
|
16
|
+
} else {
|
|
17
|
+
out.push("| File | URL | Methods |", "|---|---|---|");
|
|
18
|
+
const rows = data.routes
|
|
19
|
+
.map((r) => ({
|
|
20
|
+
file: relPath(r.filePath),
|
|
21
|
+
pattern: r.bunPattern,
|
|
22
|
+
methods: r.kind === "page" ? "GET" : "(see source)",
|
|
23
|
+
}))
|
|
24
|
+
.sort((a, b) => a.file.localeCompare(b.file));
|
|
25
|
+
for (const r of rows)
|
|
26
|
+
out.push(`| ${r.file} | ${r.pattern} | ${r.methods} |`);
|
|
27
|
+
out.push("");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
out.push("## Islands", "");
|
|
31
|
+
if (data.islands.length === 0) {
|
|
32
|
+
out.push("_No islands._", "");
|
|
33
|
+
} else {
|
|
34
|
+
out.push("| Name | Source |", "|---|---|");
|
|
35
|
+
const rows = [...data.islands].sort((a, b) => a.name.localeCompare(b.name));
|
|
36
|
+
for (const i of rows) out.push(`| ${i.name} | ${i.relPath} |`);
|
|
37
|
+
out.push("");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
out.push("## Agents", "");
|
|
41
|
+
if (data.agents.length === 0) {
|
|
42
|
+
out.push("_No agents._", "");
|
|
43
|
+
} else {
|
|
44
|
+
out.push("| Name | Model | Tools | Triggers |", "|---|---|---|---|");
|
|
45
|
+
const rows = [...data.agents].sort((a, b) => a.name.localeCompare(b.name));
|
|
46
|
+
for (const a of rows) {
|
|
47
|
+
if (!a.ok) {
|
|
48
|
+
out.push(
|
|
49
|
+
`| ${a.name} | _error_ | _error_ | _error: ${escapeCell(a.error ?? "unknown")}_ |`,
|
|
50
|
+
);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const d = a.data as {
|
|
54
|
+
model?: string;
|
|
55
|
+
tools?: string[];
|
|
56
|
+
triggers?: string[];
|
|
57
|
+
};
|
|
58
|
+
out.push(
|
|
59
|
+
`| ${a.name} | ${escapeCell(d.model ?? "")} | ${escapeCell((d.tools ?? []).join(", "))} | ${escapeCell((d.triggers ?? []).join(", "))} |`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
out.push("");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
out.push("## Tools", "");
|
|
66
|
+
if (data.tools.length === 0) {
|
|
67
|
+
out.push("_No tools._", "");
|
|
68
|
+
} else {
|
|
69
|
+
const rows = [...data.tools].sort((a, b) => a.name.localeCompare(b.name));
|
|
70
|
+
for (const t of rows) {
|
|
71
|
+
out.push(`### \`${t.name}\``, "");
|
|
72
|
+
if (!t.ok) {
|
|
73
|
+
out.push(`_error: ${t.error ?? "unknown"}_`, "");
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const d = t.data as { description?: string; input?: unknown };
|
|
77
|
+
out.push(d.description ?? "_(no description)_", "", "Input schema:", "");
|
|
78
|
+
out.push("```json", canonicalJson(d.input ?? {}), "```", "");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
out.push("## Jobs", "");
|
|
83
|
+
if (data.jobs.length === 0) {
|
|
84
|
+
out.push("_No jobs._", "");
|
|
85
|
+
} else {
|
|
86
|
+
out.push("| Name | Schedule | TZ |", "|---|---|---|");
|
|
87
|
+
const rows = [...data.jobs].sort((a, b) => a.name.localeCompare(b.name));
|
|
88
|
+
for (const j of rows) {
|
|
89
|
+
if (!j.ok) {
|
|
90
|
+
out.push(
|
|
91
|
+
`| ${j.name} | _error_ | _error: ${escapeCell(j.error ?? "unknown")}_ |`,
|
|
92
|
+
);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const d = j.data as { schedule?: string; tz?: string };
|
|
96
|
+
out.push(
|
|
97
|
+
`| ${j.name} | ${escapeCell(d.schedule ?? "")} | ${escapeCell(d.tz ?? "")} |`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
out.push("");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
out.push("## Middleware", "");
|
|
104
|
+
if (data.middlewareDocComment) {
|
|
105
|
+
out.push(data.middlewareDocComment, "");
|
|
106
|
+
} else {
|
|
107
|
+
out.push("_No global middleware._", "");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
out.push("## Environment variables", "");
|
|
111
|
+
if (data.envVars.length === 0) {
|
|
112
|
+
out.push("_No declared env vars._", "");
|
|
113
|
+
} else {
|
|
114
|
+
out.push("| Name | Required | Description |", "|---|---|---|");
|
|
115
|
+
const rows = [...data.envVars].sort((a, b) => a.name.localeCompare(b.name));
|
|
116
|
+
for (const e of rows) {
|
|
117
|
+
out.push(
|
|
118
|
+
`| ${e.name} | ${e.required ? "yes" : "no"} | ${escapeCell(e.description ?? "")} |`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
out.push("");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return out.join("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function relPath(absPath: string): string {
|
|
128
|
+
const cwd = process.cwd().replace(/\/+$/, "");
|
|
129
|
+
if (absPath.startsWith(`${cwd}/`)) return absPath.slice(cwd.length + 1);
|
|
130
|
+
return absPath;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function escapeCell(s: string): string {
|
|
134
|
+
return s.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function canonicalJson(value: unknown): string {
|
|
138
|
+
return JSON.stringify(sortKeys(value), null, 2);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function sortKeys(value: unknown): unknown {
|
|
142
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
143
|
+
if (value && typeof value === "object") {
|
|
144
|
+
const obj = value as Record<string, unknown>;
|
|
145
|
+
const out: Record<string, unknown> = {};
|
|
146
|
+
for (const k of Object.keys(obj).sort()) out[k] = sortKeys(obj[k]);
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Standalone script run via Bun.spawn from subprocess-runner.ts.
|
|
2
|
+
// Protocol (line-delimited JSON over stdio):
|
|
3
|
+
// stdin → { id: string, file: string, kind: "agent" | "tool" | "job" }
|
|
4
|
+
// stdout → { id: string, ok: true, data: ... } | { id: string, ok: false, error: string }
|
|
5
|
+
//
|
|
6
|
+
// `data` for tools includes a JSON-Schema rendering of the Zod input schema so
|
|
7
|
+
// the parent process doesn't need to import the user's Zod build.
|
|
8
|
+
|
|
9
|
+
import { zodToJsonSchema } from "./zod-to-json-schema.ts";
|
|
10
|
+
|
|
11
|
+
interface Request {
|
|
12
|
+
id: string;
|
|
13
|
+
file: string;
|
|
14
|
+
kind: "agent" | "tool" | "job";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function main(): Promise<void> {
|
|
18
|
+
const decoder = new TextDecoder();
|
|
19
|
+
let buf = "";
|
|
20
|
+
for await (const chunk of Bun.stdin.stream() as unknown as AsyncIterable<Uint8Array>) {
|
|
21
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
22
|
+
const lines = buf.split("\n");
|
|
23
|
+
buf = lines.pop() ?? "";
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
const trimmed = line.trim();
|
|
26
|
+
if (!trimmed) continue;
|
|
27
|
+
const req = JSON.parse(trimmed) as Request;
|
|
28
|
+
const res = await handle(req);
|
|
29
|
+
process.stdout.write(`${JSON.stringify(res)}\n`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function handle(
|
|
35
|
+
req: Request,
|
|
36
|
+
): Promise<{ id: string; ok: boolean; data?: unknown; error?: string }> {
|
|
37
|
+
try {
|
|
38
|
+
const mod = (await import(req.file)) as { default?: unknown };
|
|
39
|
+
const cfg = mod.default as Record<string, unknown> | undefined;
|
|
40
|
+
if (!cfg)
|
|
41
|
+
return { id: req.id, ok: false, error: "module has no default export" };
|
|
42
|
+
if (req.kind === "tool") {
|
|
43
|
+
const inputSchema = cfg.input;
|
|
44
|
+
const inputJson = zodToJsonSchema(inputSchema);
|
|
45
|
+
return {
|
|
46
|
+
id: req.id,
|
|
47
|
+
ok: true,
|
|
48
|
+
data: {
|
|
49
|
+
name: cfg.name,
|
|
50
|
+
description: cfg.description,
|
|
51
|
+
input: inputJson,
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (req.kind === "agent") {
|
|
56
|
+
return {
|
|
57
|
+
id: req.id,
|
|
58
|
+
ok: true,
|
|
59
|
+
data: {
|
|
60
|
+
name: cfg.name,
|
|
61
|
+
model: cfg.model,
|
|
62
|
+
tools: cfg.tools ?? [],
|
|
63
|
+
triggers: cfg.triggers ?? [],
|
|
64
|
+
systemPrompt: cfg.systemPrompt,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// job
|
|
69
|
+
return {
|
|
70
|
+
id: req.id,
|
|
71
|
+
ok: true,
|
|
72
|
+
data: {
|
|
73
|
+
name: cfg.name,
|
|
74
|
+
schedule: cfg.schedule,
|
|
75
|
+
tz: cfg.tz,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
} catch (err) {
|
|
79
|
+
return {
|
|
80
|
+
id: req.id,
|
|
81
|
+
ok: false,
|
|
82
|
+
error: (err as Error)?.message ?? String(err),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
main().catch((err) => {
|
|
88
|
+
process.stderr.write(
|
|
89
|
+
`subprocess-entry fatal: ${(err as Error)?.message ?? String(err)}\n`,
|
|
90
|
+
);
|
|
91
|
+
process.exit(1);
|
|
92
|
+
});
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
export interface ModuleQuery {
|
|
2
|
+
kind: "agent" | "tool" | "job";
|
|
3
|
+
file: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface ModuleResult {
|
|
7
|
+
query: ModuleQuery;
|
|
8
|
+
ok: boolean;
|
|
9
|
+
data?: unknown;
|
|
10
|
+
error?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Runs a batch of module loads inside a single isolated subprocess. Each
|
|
14
|
+
// module's top-level side effects die with the subprocess. A module whose
|
|
15
|
+
// top-level throws produces a per-query error, not a build crash.
|
|
16
|
+
export async function runSubprocessBatch(
|
|
17
|
+
entryScript: string,
|
|
18
|
+
queries: ModuleQuery[],
|
|
19
|
+
opts: { timeoutMs?: number } = {},
|
|
20
|
+
): Promise<ModuleResult[]> {
|
|
21
|
+
if (queries.length === 0) return [];
|
|
22
|
+
|
|
23
|
+
const timeoutMs = opts.timeoutMs ?? 30_000;
|
|
24
|
+
|
|
25
|
+
const proc = Bun.spawn(["bun", entryScript], {
|
|
26
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
27
|
+
env: process.env,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const results = new Map<string, ModuleResult>();
|
|
31
|
+
const sink = proc.stdin as {
|
|
32
|
+
write: (chunk: string) => void;
|
|
33
|
+
end: () => void;
|
|
34
|
+
} | null;
|
|
35
|
+
for (let i = 0; i < queries.length; i++) {
|
|
36
|
+
const id = String(i);
|
|
37
|
+
const line =
|
|
38
|
+
JSON.stringify({ id, file: queries[i]?.file, kind: queries[i]?.kind }) +
|
|
39
|
+
"\n";
|
|
40
|
+
sink?.write(line);
|
|
41
|
+
}
|
|
42
|
+
sink?.end();
|
|
43
|
+
|
|
44
|
+
const reader = proc.stdout.getReader();
|
|
45
|
+
const decoder = new TextDecoder();
|
|
46
|
+
let buf = "";
|
|
47
|
+
|
|
48
|
+
const timeout = new Promise<never>((_, reject) =>
|
|
49
|
+
setTimeout(
|
|
50
|
+
() => reject(new Error(`subprocess timeout after ${timeoutMs}ms`)),
|
|
51
|
+
timeoutMs,
|
|
52
|
+
),
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
const readAll = (async () => {
|
|
56
|
+
while (true) {
|
|
57
|
+
const { value, done } = await reader.read();
|
|
58
|
+
if (done) break;
|
|
59
|
+
buf += decoder.decode(value, { stream: true });
|
|
60
|
+
const lines = buf.split("\n");
|
|
61
|
+
buf = lines.pop() ?? "";
|
|
62
|
+
for (const line of lines) {
|
|
63
|
+
const t = line.trim();
|
|
64
|
+
if (!t) continue;
|
|
65
|
+
const parsed = JSON.parse(t) as {
|
|
66
|
+
id: string;
|
|
67
|
+
ok: boolean;
|
|
68
|
+
data?: unknown;
|
|
69
|
+
error?: string;
|
|
70
|
+
};
|
|
71
|
+
const q = queries[Number(parsed.id)];
|
|
72
|
+
if (!q) continue;
|
|
73
|
+
results.set(parsed.id, {
|
|
74
|
+
query: q,
|
|
75
|
+
ok: parsed.ok,
|
|
76
|
+
data: parsed.data,
|
|
77
|
+
error: parsed.error,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
})();
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
await Promise.race([readAll, timeout]);
|
|
85
|
+
} finally {
|
|
86
|
+
try {
|
|
87
|
+
proc.kill();
|
|
88
|
+
} catch {
|
|
89
|
+
// ignore
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
await proc.exited;
|
|
93
|
+
|
|
94
|
+
const out: ModuleResult[] = [];
|
|
95
|
+
for (let i = 0; i < queries.length; i++) {
|
|
96
|
+
const r = results.get(String(i));
|
|
97
|
+
const q = queries[i];
|
|
98
|
+
if (!q) continue;
|
|
99
|
+
if (!r) {
|
|
100
|
+
const stderrText = await new Response(proc.stderr).text().catch(() => "");
|
|
101
|
+
out.push({
|
|
102
|
+
query: q,
|
|
103
|
+
ok: false,
|
|
104
|
+
error: `no response from subprocess (stderr: ${stderrText.slice(0, 500) || "<empty>"})`,
|
|
105
|
+
});
|
|
106
|
+
} else {
|
|
107
|
+
out.push(r);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Writes the generated manifest to a target file while preserving any
|
|
2
|
+
// human-written content around it. The manifest lives between two HTML
|
|
3
|
+
// comment markers so regeneration is a deterministic in-place splice — rules
|
|
4
|
+
// or notes above (and below) the section survive every `sordo dev/build`.
|
|
5
|
+
|
|
6
|
+
export const MANIFEST_START = "<!-- sordo:manifest-start -->";
|
|
7
|
+
export const MANIFEST_END = "<!-- sordo:manifest-end -->";
|
|
8
|
+
|
|
9
|
+
const SECTION_RE = new RegExp(
|
|
10
|
+
`${escapeRe(MANIFEST_START)}[\\s\\S]*?${escapeRe(MANIFEST_END)}`,
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
function escapeRe(s: string): string {
|
|
14
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function wrap(manifest: string): string {
|
|
18
|
+
const body = manifest.endsWith("\n") ? manifest : `${manifest}\n`;
|
|
19
|
+
return `${MANIFEST_START}\n${body}${MANIFEST_END}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function writeManifestToFile(
|
|
23
|
+
path: string,
|
|
24
|
+
manifest: string,
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
const file = Bun.file(path);
|
|
27
|
+
if (!(await file.exists())) {
|
|
28
|
+
await Bun.write(path, `${wrap(manifest)}\n`);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const existing = await file.text();
|
|
32
|
+
if (SECTION_RE.test(existing)) {
|
|
33
|
+
await Bun.write(path, existing.replace(SECTION_RE, wrap(manifest)));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const sep = existing.endsWith("\n") ? "\n" : "\n\n";
|
|
37
|
+
await Bun.write(path, `${existing}${sep}${wrap(manifest)}\n`);
|
|
38
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
// Wrap zod v4's built-in toJSONSchema with a never-throw guard so a single bad
|
|
4
|
+
// schema can't fail AGENTS.md generation. Falls back to { type: "unknown" }.
|
|
5
|
+
export function zodToJsonSchema(schema: unknown, warnings?: string[]): unknown {
|
|
6
|
+
if (!schema || typeof schema !== "object") return { type: "unknown" };
|
|
7
|
+
try {
|
|
8
|
+
const out = z.toJSONSchema(schema as z.ZodType) as Record<string, unknown>;
|
|
9
|
+
// Drop the $schema marker so we don't bloat the AGENTS.md JSON blocks.
|
|
10
|
+
delete out.$schema;
|
|
11
|
+
return out;
|
|
12
|
+
} catch (err) {
|
|
13
|
+
warnings?.push(
|
|
14
|
+
`zod->json-schema failed: ${(err as Error).message ?? String(err)}`,
|
|
15
|
+
);
|
|
16
|
+
return { type: "unknown" };
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { runtimeEnv } from "../internal/runtime.ts";
|
|
2
|
+
import { generateRequestId } from "../middleware/request-id.ts";
|
|
3
|
+
import { AnthropicSdkNotInstalled, MissingAnthropicKey } from "./errors.ts";
|
|
4
|
+
import type { AiContext, AnthropicLike } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
export interface CreateAiContextOptions {
|
|
7
|
+
requestId?: string;
|
|
8
|
+
user?: unknown;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
vars?: Record<string, unknown>;
|
|
11
|
+
// Inject a client (for tests or programmatic callers wanting per-context isolation).
|
|
12
|
+
anthropic?: AnthropicLike;
|
|
13
|
+
// Inject a constructor (for tests). Defaults to the real `@anthropic-ai/sdk`.
|
|
14
|
+
anthropicCtor?: new (opts: {
|
|
15
|
+
apiKey: string;
|
|
16
|
+
}) => AnthropicLike;
|
|
17
|
+
apiKey?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createAiContext(opts: CreateAiContextOptions = {}): AiContext {
|
|
21
|
+
const requestId = opts.requestId ?? generateRequestId();
|
|
22
|
+
let cached: AnthropicLike | null = opts.anthropic ?? null;
|
|
23
|
+
|
|
24
|
+
const ctx: AiContext = {
|
|
25
|
+
requestId,
|
|
26
|
+
user: opts.user,
|
|
27
|
+
signal: opts.signal,
|
|
28
|
+
vars: opts.vars ?? {},
|
|
29
|
+
get anthropic() {
|
|
30
|
+
if (cached) return cached;
|
|
31
|
+
cached = buildAnthropic(opts);
|
|
32
|
+
return cached;
|
|
33
|
+
},
|
|
34
|
+
} as AiContext & { anthropic: AnthropicLike };
|
|
35
|
+
|
|
36
|
+
return ctx;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function buildAnthropic(opts: CreateAiContextOptions): AnthropicLike {
|
|
40
|
+
const apiKey = opts.apiKey ?? readApiKey();
|
|
41
|
+
if (!apiKey) throw new MissingAnthropicKey();
|
|
42
|
+
|
|
43
|
+
if (opts.anthropicCtor) {
|
|
44
|
+
return new opts.anthropicCtor({ apiKey });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let SdkCtor: new (opts: { apiKey: string }) => AnthropicLike;
|
|
48
|
+
try {
|
|
49
|
+
// Dynamic require so the dep stays optional. `Bun.resolveSync` throws if absent.
|
|
50
|
+
const mod = (
|
|
51
|
+
globalThis as unknown as { require?: (id: string) => unknown }
|
|
52
|
+
).require?.("@anthropic-ai/sdk") as
|
|
53
|
+
| { default?: unknown; Anthropic?: unknown }
|
|
54
|
+
| undefined;
|
|
55
|
+
const Ctor = (mod?.default ?? mod?.Anthropic) as
|
|
56
|
+
| (new (opts: {
|
|
57
|
+
apiKey: string;
|
|
58
|
+
}) => AnthropicLike)
|
|
59
|
+
| undefined;
|
|
60
|
+
if (!Ctor) throw new AnthropicSdkNotInstalled();
|
|
61
|
+
SdkCtor = Ctor;
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (err instanceof AnthropicSdkNotInstalled) throw err;
|
|
64
|
+
throw new AnthropicSdkNotInstalled(err);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return new SdkCtor({ apiKey });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function readApiKey(): string | undefined {
|
|
71
|
+
return runtimeEnv().ANTHROPIC_API_KEY;
|
|
72
|
+
}
|
package/src/ai/define.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AgentConfig, JobConfig, ToolConfig } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
export function defineAgent(config: AgentConfig): AgentConfig {
|
|
4
|
+
return config;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function defineTool<TInput, TOutput>(
|
|
8
|
+
config: ToolConfig<TInput, TOutput>,
|
|
9
|
+
): ToolConfig<TInput, TOutput> {
|
|
10
|
+
return config;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function defineJob(config: JobConfig): JobConfig {
|
|
14
|
+
return config;
|
|
15
|
+
}
|
package/src/ai/errors.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
|
|
3
|
+
export class MissingAnthropicKey extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super(
|
|
6
|
+
"ANTHROPIC_API_KEY is not set. Sordo agents require an Anthropic API key. " +
|
|
7
|
+
"Set ANTHROPIC_API_KEY in your environment (or .env.local) before invoking an agent.",
|
|
8
|
+
);
|
|
9
|
+
this.name = "MissingAnthropicKey";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class AgentNotFound extends Error {
|
|
14
|
+
constructor(name: string, available: string[]) {
|
|
15
|
+
super(
|
|
16
|
+
`Agent "${name}" is not registered. Available agents: ${available.length ? available.join(", ") : "(none)"}.`,
|
|
17
|
+
);
|
|
18
|
+
this.name = "AgentNotFound";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class ToolNotFound extends Error {
|
|
23
|
+
constructor(name: string, available: string[]) {
|
|
24
|
+
super(
|
|
25
|
+
`Tool "${name}" is not registered. Available tools: ${available.length ? available.join(", ") : "(none)"}.`,
|
|
26
|
+
);
|
|
27
|
+
this.name = "ToolNotFound";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class ToolInputInvalid extends Error {
|
|
32
|
+
readonly issues: z.ZodIssue[];
|
|
33
|
+
readonly tool: string;
|
|
34
|
+
constructor(tool: string, issues: z.ZodIssue[]) {
|
|
35
|
+
super(`Tool "${tool}" received invalid input: ${issues.length} issue(s).`);
|
|
36
|
+
this.name = "ToolInputInvalid";
|
|
37
|
+
this.tool = tool;
|
|
38
|
+
this.issues = issues;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class AnthropicSdkNotInstalled extends Error {
|
|
43
|
+
constructor(cause?: unknown) {
|
|
44
|
+
super(
|
|
45
|
+
'"@anthropic-ai/sdk" is required to run agents but is not installed. ' +
|
|
46
|
+
"Install it with `bun add @anthropic-ai/sdk`.",
|
|
47
|
+
);
|
|
48
|
+
this.name = "AnthropicSdkNotInstalled";
|
|
49
|
+
if (cause) (this as { cause?: unknown }).cause = cause;
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/ai/index.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type { CreateAiContextOptions } from "./context.ts";
|
|
2
|
+
export { createAiContext } from "./context.ts";
|
|
3
|
+
export { defineAgent, defineJob, defineTool } from "./define.ts";
|
|
4
|
+
export {
|
|
5
|
+
AgentNotFound,
|
|
6
|
+
AnthropicSdkNotInstalled,
|
|
7
|
+
MissingAnthropicKey,
|
|
8
|
+
ToolInputInvalid,
|
|
9
|
+
ToolNotFound,
|
|
10
|
+
} from "./errors.ts";
|
|
11
|
+
export { createAiContextMiddleware } from "./middleware.ts";
|
|
12
|
+
export {
|
|
13
|
+
getAgent,
|
|
14
|
+
getJob,
|
|
15
|
+
getTool,
|
|
16
|
+
hasAny,
|
|
17
|
+
listAgents,
|
|
18
|
+
listJobs,
|
|
19
|
+
listTools,
|
|
20
|
+
registerAgent,
|
|
21
|
+
registerJob,
|
|
22
|
+
registerTool,
|
|
23
|
+
} from "./registry.ts";
|
|
24
|
+
export { runAgent } from "./run.ts";
|
|
25
|
+
export { streamObject, streamText } from "./stream.ts";
|
|
26
|
+
export type {
|
|
27
|
+
AgentConfig,
|
|
28
|
+
AgentRunResult,
|
|
29
|
+
AiContext,
|
|
30
|
+
AnthropicLike,
|
|
31
|
+
JobConfig,
|
|
32
|
+
RegisteredAgent,
|
|
33
|
+
RegisteredJob,
|
|
34
|
+
RegisteredTool,
|
|
35
|
+
ToolConfig,
|
|
36
|
+
} from "./types.ts";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Middleware } from "../middleware/index.ts";
|
|
2
|
+
import { type CreateAiContextOptions, createAiContext } from "./context.ts";
|
|
3
|
+
|
|
4
|
+
// Populates ctx.aiContext on every request. Registered automatically by the
|
|
5
|
+
// router when the agent/tool registry is non-empty.
|
|
6
|
+
export function createAiContextMiddleware(
|
|
7
|
+
defaults: CreateAiContextOptions = {},
|
|
8
|
+
): Middleware {
|
|
9
|
+
return async (req, ctx, next) => {
|
|
10
|
+
if (!ctx.aiContext) {
|
|
11
|
+
ctx.aiContext = createAiContext({
|
|
12
|
+
...defaults,
|
|
13
|
+
// Reuse the composer-generated correlation id so logs/agent traces
|
|
14
|
+
// line up: ctx.aiContext.requestId === ctx.requestId.
|
|
15
|
+
requestId: defaults.requestId ?? ctx.requestId,
|
|
16
|
+
signal: req.signal,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return next();
|
|
20
|
+
};
|
|
21
|
+
}
|