sordo 0.5.0 → 1.0.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.
Files changed (152) hide show
  1. package/CHANGELOG.md +6 -126
  2. package/README.md +8 -178
  3. package/bin/sordo.ts +1 -4
  4. package/package.json +17 -41
  5. package/src/agents-md.ts +1 -0
  6. package/src/ai.ts +1 -0
  7. package/src/build.ts +1 -0
  8. package/src/client.ts +1 -0
  9. package/src/config.ts +1 -0
  10. package/src/dev.ts +1 -0
  11. package/src/index.ts +1 -55
  12. package/src/middleware.ts +1 -0
  13. package/src/plugin.ts +1 -0
  14. package/src/render.ts +1 -0
  15. package/src/router.ts +1 -0
  16. package/src/server.ts +1 -0
  17. package/CLAUDE.md +0 -124
  18. package/src/adapters/bun.ts +0 -59
  19. package/src/adapters/edge.ts +0 -75
  20. package/src/adapters/types.ts +0 -43
  21. package/src/agents-md/collect.ts +0 -113
  22. package/src/agents-md/generate.ts +0 -44
  23. package/src/agents-md/index.ts +0 -9
  24. package/src/agents-md/render.ts +0 -151
  25. package/src/agents-md/subprocess-entry.ts +0 -92
  26. package/src/agents-md/subprocess-runner.ts +0 -111
  27. package/src/agents-md/write.ts +0 -38
  28. package/src/agents-md/zod-to-json-schema.ts +0 -18
  29. package/src/ai/context.ts +0 -72
  30. package/src/ai/define.ts +0 -15
  31. package/src/ai/errors.ts +0 -51
  32. package/src/ai/index.ts +0 -36
  33. package/src/ai/middleware.ts +0 -21
  34. package/src/ai/registry.ts +0 -96
  35. package/src/ai/run.ts +0 -185
  36. package/src/ai/scan.ts +0 -42
  37. package/src/ai/stream.ts +0 -71
  38. package/src/ai/triggers.ts +0 -124
  39. package/src/ai/types.ts +0 -67
  40. package/src/ai/validate.ts +0 -82
  41. package/src/build/assets.ts +0 -48
  42. package/src/build/client-entry.ts +0 -43
  43. package/src/build/css.ts +0 -128
  44. package/src/build/embedded.ts +0 -66
  45. package/src/build/hash.ts +0 -21
  46. package/src/build/index.ts +0 -505
  47. package/src/build/macros/agents-hash.macro.ts +0 -9
  48. package/src/build/macros/agents.macro.ts +0 -21
  49. package/src/build/macros/env.macro.ts +0 -25
  50. package/src/build/macros/inline-assets.macro.ts +0 -34
  51. package/src/build/macros/manifest.macro.ts +0 -8
  52. package/src/build/macros/routes.macro.ts +0 -10
  53. package/src/build/page-entry.ts +0 -136
  54. package/src/build/scan-islands.ts +0 -39
  55. package/src/build/server-entry.ts +0 -256
  56. package/src/cli/ansi.ts +0 -41
  57. package/src/cli/build.ts +0 -195
  58. package/src/cli/commands/add/apply.ts +0 -31
  59. package/src/cli/commands/add/component-diff.ts +0 -116
  60. package/src/cli/commands/add/diff.ts +0 -153
  61. package/src/cli/commands/add/internal.ts +0 -41
  62. package/src/cli/commands/add/load-catalog.ts +0 -22
  63. package/src/cli/commands/add/peer-deps.ts +0 -115
  64. package/src/cli/commands/add/registry-fetch.ts +0 -122
  65. package/src/cli/commands/add/shadcn.ts +0 -285
  66. package/src/cli/commands/add/source.ts +0 -273
  67. package/src/cli/commands/add/stamper.ts +0 -73
  68. package/src/cli/commands/add/tokens.ts +0 -81
  69. package/src/cli/commands/add/ui-paths.ts +0 -113
  70. package/src/cli/commands/add.ts +0 -427
  71. package/src/cli/commands/deploy.ts +0 -143
  72. package/src/cli/commands/migrate.ts +0 -149
  73. package/src/cli/commands/secret.ts +0 -316
  74. package/src/cli/commands/ui/build.ts +0 -111
  75. package/src/cli/commands/ui/init.ts +0 -135
  76. package/src/cli/commands/ui/migrate/git-guard.ts +0 -19
  77. package/src/cli/commands/ui/migrate/radix.ts +0 -67
  78. package/src/cli/commands/ui/migrate/rtl.ts +0 -148
  79. package/src/cli/commands/ui/shadcn.ts +0 -82
  80. package/src/cli/commands/ui/view.ts +0 -63
  81. package/src/cli/commands/ui.ts +0 -86
  82. package/src/cli/commands/update.ts +0 -134
  83. package/src/cli/commands/upgrade.ts +0 -53
  84. package/src/cli/commands/view.ts +0 -34
  85. package/src/cli/dev.ts +0 -393
  86. package/src/cli/doctor/config-checks.ts +0 -63
  87. package/src/cli/doctor/deps.ts +0 -295
  88. package/src/cli/doctor/hydrate.ts +0 -65
  89. package/src/cli/doctor/monorepo.ts +0 -158
  90. package/src/cli/doctor/probes.ts +0 -16
  91. package/src/cli/doctor/report.ts +0 -72
  92. package/src/cli/doctor/toolchain.ts +0 -95
  93. package/src/cli/doctor/types.ts +0 -36
  94. package/src/cli/doctor.ts +0 -127
  95. package/src/cli/index.ts +0 -168
  96. package/src/cli/log.ts +0 -135
  97. package/src/cli/run/affected.ts +0 -79
  98. package/src/cli/run/cache-key.ts +0 -177
  99. package/src/cli/run/cache-store.ts +0 -0
  100. package/src/cli/run/files.ts +0 -96
  101. package/src/cli/run/git.ts +0 -13
  102. package/src/cli/run/runner.ts +0 -189
  103. package/src/cli/run/workspace.ts +0 -216
  104. package/src/cli/run.ts +0 -184
  105. package/src/cli/start.ts +0 -99
  106. package/src/cli/update-check.ts +0 -157
  107. package/src/client/index.ts +0 -65
  108. package/src/client/link.tsx +0 -61
  109. package/src/client/page.ts +0 -250
  110. package/src/config/define.ts +0 -5
  111. package/src/config/env.ts +0 -36
  112. package/src/config/load.ts +0 -152
  113. package/src/config/schema.ts +0 -135
  114. package/src/config/secrets.ts +0 -108
  115. package/src/dev/client.ts +0 -112
  116. package/src/dev/hot.ts +0 -24
  117. package/src/dev/index.ts +0 -4
  118. package/src/dev/tree.ts +0 -95
  119. package/src/dev/watcher.ts +0 -95
  120. package/src/internal/hmr-client.ts +0 -52
  121. package/src/internal/open-in-editor.ts +0 -23
  122. package/src/internal/runtime.ts +0 -30
  123. package/src/middleware/cookie-jar.ts +0 -135
  124. package/src/middleware/cookies.ts +0 -60
  125. package/src/middleware/index.ts +0 -135
  126. package/src/middleware/request-id.ts +0 -22
  127. package/src/middleware/response-helpers.ts +0 -25
  128. package/src/plugin/index.ts +0 -109
  129. package/src/render/bootstrap.ts +0 -44
  130. package/src/render/dev-error.tsx +0 -73
  131. package/src/render/index.tsx +0 -261
  132. package/src/render/island.tsx +0 -33
  133. package/src/render/meta.tsx +0 -48
  134. package/src/render/shell.tsx +0 -41
  135. package/src/router/conflict.ts +0 -20
  136. package/src/router/filesystem.ts +0 -37
  137. package/src/router/index.ts +0 -269
  138. package/src/router/match.ts +0 -91
  139. package/src/router/pattern.ts +0 -104
  140. package/src/server/index.ts +0 -250
  141. package/src/server/inline-assets.ts +0 -57
  142. package/src/types.ts +0 -53
  143. package/src/ui/schema.ts +0 -68
  144. package/src/ui/types.ts +0 -10
  145. package/templates/_internal/cn.ts +0 -6
  146. package/templates/_internal/slot.ts +0 -50
  147. package/templates/_internal/variants.ts +0 -1
  148. package/templates/themes/neutral/tokens.css +0 -46
  149. package/templates/themes/slate/tokens.css +0 -46
  150. package/templates/themes/stone/tokens.css +0 -46
  151. package/templates/themes/zinc/tokens.css +0 -46
  152. package/templates/tokens.css +0 -46
@@ -1,38 +0,0 @@
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
- }
@@ -1,18 +0,0 @@
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
- }
package/src/ai/context.ts DELETED
@@ -1,72 +0,0 @@
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 DELETED
@@ -1,15 +0,0 @@
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 DELETED
@@ -1,51 +0,0 @@
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 DELETED
@@ -1,36 +0,0 @@
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";
@@ -1,21 +0,0 @@
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
- }
@@ -1,96 +0,0 @@
1
- import { AgentNotFound, ToolNotFound } from "./errors.ts";
2
- import { runAgent } from "./run.ts";
3
- import type {
4
- AgentConfig,
5
- JobConfig,
6
- RegisteredAgent,
7
- RegisteredJob,
8
- RegisteredTool,
9
- ToolConfig,
10
- } from "./types.ts";
11
-
12
- const agents = new Map<string, RegisteredAgent>();
13
- const tools = new Map<string, RegisteredTool>();
14
- const jobs = new Map<string, RegisteredJob>();
15
-
16
- export function registerAgent(config: AgentConfig, filePath?: string): void {
17
- if (agents.has(config.name)) {
18
- const existing = agents.get(config.name);
19
- throw new Error(
20
- `Duplicate agent name "${config.name}": already registered from ${existing?.filePath ?? "(unknown)"}, ` +
21
- `cannot register from ${filePath ?? "(unknown)"}.`,
22
- );
23
- }
24
- agents.set(config.name, {
25
- config,
26
- filePath,
27
- run: (input, ctx) => runAgent(config, input, ctx),
28
- });
29
- }
30
-
31
- export function registerTool<TInput, TOutput>(
32
- config: ToolConfig<TInput, TOutput>,
33
- filePath?: string,
34
- ): void {
35
- if (tools.has(config.name)) {
36
- const existing = tools.get(config.name);
37
- throw new Error(
38
- `Duplicate tool name "${config.name}": already registered from ${existing?.filePath ?? "(unknown)"}, ` +
39
- `cannot register from ${filePath ?? "(unknown)"}.`,
40
- );
41
- }
42
- tools.set(config.name, {
43
- config: config as ToolConfig,
44
- filePath,
45
- });
46
- }
47
-
48
- export function registerJob(config: JobConfig, filePath?: string): void {
49
- if (jobs.has(config.name)) {
50
- const existing = jobs.get(config.name);
51
- throw new Error(
52
- `Duplicate job name "${config.name}": already registered from ${existing?.filePath ?? "(unknown)"}, ` +
53
- `cannot register from ${filePath ?? "(unknown)"}.`,
54
- );
55
- }
56
- jobs.set(config.name, { config, filePath });
57
- }
58
-
59
- export function getAgent(name: string): RegisteredAgent {
60
- const a = agents.get(name);
61
- if (!a) throw new AgentNotFound(name, [...agents.keys()]);
62
- return a;
63
- }
64
-
65
- export function getTool(name: string): RegisteredTool {
66
- const t = tools.get(name);
67
- if (!t) throw new ToolNotFound(name, [...tools.keys()]);
68
- return t;
69
- }
70
-
71
- export function getJob(name: string): RegisteredJob | undefined {
72
- return jobs.get(name);
73
- }
74
-
75
- export function listAgents(): RegisteredAgent[] {
76
- return [...agents.values()];
77
- }
78
-
79
- export function listTools(): RegisteredTool[] {
80
- return [...tools.values()];
81
- }
82
-
83
- export function listJobs(): RegisteredJob[] {
84
- return [...jobs.values()];
85
- }
86
-
87
- export function hasAny(): boolean {
88
- return agents.size > 0 || tools.size > 0;
89
- }
90
-
91
- // Test-only — reset module state between test runs.
92
- export function __resetRegistry(): void {
93
- agents.clear();
94
- tools.clear();
95
- jobs.clear();
96
- }
package/src/ai/run.ts DELETED
@@ -1,185 +0,0 @@
1
- import { z } from "zod";
2
- import { ToolInputInvalid } from "./errors.ts";
3
- import { getTool } from "./registry.ts";
4
- import { streamText } from "./stream.ts";
5
- import type { AgentConfig, AgentRunResult, AiContext } from "./types.ts";
6
-
7
- const MAX_TOOL_ROUNDS = 8;
8
-
9
- export async function runAgent(
10
- config: AgentConfig,
11
- input: { message: string } & Record<string, unknown>,
12
- ctx: AiContext,
13
- ): Promise<AgentRunResult> {
14
- // Resolve tool defs eagerly so missing tools throw before we open a stream.
15
- const toolDefs = (config.tools ?? []).map((name) => {
16
- const t = getTool(name);
17
- return {
18
- name: t.config.name,
19
- description: t.config.description,
20
- input_schema: zodToJsonSchemaLite(t.config.input),
21
- };
22
- });
23
-
24
- const messages: Array<{ role: "user" | "assistant"; content: unknown }> = [
25
- { role: "user", content: input.message },
26
- ];
27
-
28
- const encoder = new TextEncoder();
29
-
30
- const stream = new ReadableStream<Uint8Array>({
31
- async start(controller) {
32
- try {
33
- for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
34
- const events = streamText({
35
- ctx,
36
- model: config.model,
37
- system: config.systemPrompt,
38
- tools: toolDefs.length > 0 ? toolDefs : undefined,
39
- messages,
40
- maxTokens: config.maxTokens ?? 1024,
41
- });
42
-
43
- const accumulated = await consumeStream(events, controller, encoder);
44
-
45
- if (accumulated.toolUses.length === 0) break;
46
-
47
- messages.push({
48
- role: "assistant",
49
- content: accumulated.assistantContent,
50
- });
51
-
52
- const toolResults: Array<{
53
- type: "tool_result";
54
- tool_use_id: string;
55
- content: string;
56
- is_error?: boolean;
57
- }> = [];
58
- for (const use of accumulated.toolUses) {
59
- const tool = getTool(use.name);
60
- const parsed = tool.config.input.safeParse(use.input);
61
- if (!parsed.success) {
62
- throw new ToolInputInvalid(use.name, parsed.error.issues);
63
- }
64
- const out = await tool.config.handler(parsed.data, ctx);
65
- toolResults.push({
66
- type: "tool_result",
67
- tool_use_id: use.id,
68
- content: typeof out === "string" ? out : JSON.stringify(out),
69
- });
70
- }
71
- messages.push({ role: "user", content: toolResults });
72
- }
73
- controller.close();
74
- } catch (err) {
75
- controller.error(err);
76
- }
77
- },
78
- });
79
-
80
- return { stream };
81
- }
82
-
83
- interface Accumulated {
84
- toolUses: Array<{ id: string; name: string; input: unknown }>;
85
- assistantContent: unknown[];
86
- }
87
-
88
- async function consumeStream(
89
- events: AsyncIterable<unknown>,
90
- controller: ReadableStreamDefaultController<Uint8Array>,
91
- encoder: TextEncoder,
92
- ): Promise<Accumulated> {
93
- const toolUses: Array<{ id: string; name: string; input: unknown }> = [];
94
- const assistantContent: unknown[] = [];
95
- let currentToolJson = "";
96
- let currentToolIndex = -1;
97
-
98
- for await (const ev of events as AsyncIterable<Record<string, unknown>>) {
99
- const type = ev.type as string | undefined;
100
-
101
- if (type === "content_block_start") {
102
- const block = ev.content_block as {
103
- type: string;
104
- id?: string;
105
- name?: string;
106
- text?: string;
107
- };
108
- if (block.type === "tool_use") {
109
- currentToolIndex = toolUses.length;
110
- toolUses.push({
111
- id: block.id ?? "",
112
- name: block.name ?? "",
113
- input: {},
114
- });
115
- currentToolJson = "";
116
- assistantContent.push({
117
- type: "tool_use",
118
- id: block.id,
119
- name: block.name,
120
- input: {},
121
- });
122
- } else if (block.type === "text") {
123
- assistantContent.push({ type: "text", text: block.text ?? "" });
124
- }
125
- continue;
126
- }
127
-
128
- if (type === "content_block_delta") {
129
- const delta = ev.delta as {
130
- type: string;
131
- text?: string;
132
- partial_json?: string;
133
- };
134
- if (delta.type === "text_delta" && delta.text) {
135
- controller.enqueue(encoder.encode(delta.text));
136
- const last = assistantContent[assistantContent.length - 1] as {
137
- type: string;
138
- text?: string;
139
- };
140
- if (last && last.type === "text")
141
- last.text = (last.text ?? "") + delta.text;
142
- } else if (
143
- delta.type === "input_json_delta" &&
144
- typeof delta.partial_json === "string"
145
- ) {
146
- currentToolJson += delta.partial_json;
147
- }
148
- continue;
149
- }
150
-
151
- if (type === "content_block_stop") {
152
- if (currentToolIndex >= 0 && currentToolJson) {
153
- const tu = toolUses[currentToolIndex];
154
- if (tu) {
155
- try {
156
- const parsed = JSON.parse(currentToolJson) as unknown;
157
- tu.input = parsed;
158
- const ac = assistantContent.find(
159
- (c) => (c as { id?: string }).id === tu.id,
160
- ) as { input?: unknown } | undefined;
161
- if (ac) ac.input = parsed;
162
- } catch {
163
- tu.input = currentToolJson;
164
- }
165
- }
166
- currentToolIndex = -1;
167
- currentToolJson = "";
168
- }
169
- }
170
-
171
- // message_delta / message_stop / message_start: nothing to emit
172
- }
173
-
174
- return { toolUses, assistantContent };
175
- }
176
-
177
- function zodToJsonSchemaLite(schema: unknown): unknown {
178
- try {
179
- const out = z.toJSONSchema(schema as z.ZodType) as Record<string, unknown>;
180
- delete out.$schema;
181
- return out;
182
- } catch {
183
- return { type: "object" };
184
- }
185
- }
package/src/ai/scan.ts DELETED
@@ -1,42 +0,0 @@
1
- const TEST_FILE_RE = /\.test\.tsx?$/;
2
-
3
- export interface ScannedModule {
4
- name: string;
5
- filePath: string;
6
- }
7
-
8
- async function scanDir(
9
- appDir: string,
10
- sub: "agents" | "tools" | "jobs",
11
- ): Promise<ScannedModule[]> {
12
- const dir = `${appDir.replace(/\/+$/, "")}/${sub}`;
13
- const glob = new Bun.Glob("**/*.ts");
14
- const out: ScannedModule[] = [];
15
- try {
16
- for await (const rel of glob.scan({ cwd: dir, onlyFiles: true })) {
17
- const base = rel.split("/").pop() ?? rel;
18
- if (base.startsWith("_")) continue;
19
- if (TEST_FILE_RE.test(base)) continue;
20
- const name = base.replace(/\.ts$/, "");
21
- out.push({ name, filePath: `${dir}/${rel}` });
22
- }
23
- } catch (err) {
24
- const msg = (err as Error)?.message ?? "";
25
- if (/ENOENT|no such file/i.test(msg)) return [];
26
- throw err;
27
- }
28
- out.sort((a, b) => a.filePath.localeCompare(b.filePath));
29
- return out;
30
- }
31
-
32
- export function scanAgents(appDir: string): Promise<ScannedModule[]> {
33
- return scanDir(appDir, "agents");
34
- }
35
-
36
- export function scanTools(appDir: string): Promise<ScannedModule[]> {
37
- return scanDir(appDir, "tools");
38
- }
39
-
40
- export function scanJobs(appDir: string): Promise<ScannedModule[]> {
41
- return scanDir(appDir, "jobs");
42
- }
package/src/ai/stream.ts DELETED
@@ -1,71 +0,0 @@
1
- import type { AiContext } from "./types.ts";
2
-
3
- export interface StreamTextOptions {
4
- ctx: AiContext;
5
- model: string;
6
- system?: string;
7
- messages: Array<{ role: "user" | "assistant"; content: unknown }>;
8
- tools?: Array<{ name: string; description: string; input_schema: unknown }>;
9
- maxTokens?: number;
10
- }
11
-
12
- // Thin wrapper that defaults prompt caching on for system + tool definitions.
13
- // Returns the underlying stream object (an AsyncIterable of events). Callers
14
- // pipe it to a Response or iterate manually.
15
- export function streamText(opts: StreamTextOptions): AsyncIterable<unknown> {
16
- const params = buildParams(opts);
17
- const result = opts.ctx.anthropic.messages.stream(
18
- params,
19
- ) as AsyncIterable<unknown>;
20
- return result;
21
- }
22
-
23
- export interface StreamObjectOptions extends StreamTextOptions {
24
- // Structured-output schema name; the model is asked to emit a single
25
- // tool_use matching this name.
26
- schemaName: string;
27
- schema: unknown;
28
- }
29
-
30
- export function streamObject(
31
- opts: StreamObjectOptions,
32
- ): AsyncIterable<unknown> {
33
- const tools = [
34
- {
35
- name: opts.schemaName,
36
- description: "Structured output schema.",
37
- input_schema: opts.schema,
38
- },
39
- ];
40
- return streamText({ ...opts, tools, system: opts.system });
41
- }
42
-
43
- function buildParams(opts: StreamTextOptions): Record<string, unknown> {
44
- const cachedSystem = opts.system
45
- ? [
46
- {
47
- type: "text",
48
- text: opts.system,
49
- cache_control: { type: "ephemeral" },
50
- },
51
- ]
52
- : undefined;
53
- const cachedTools =
54
- opts.tools && opts.tools.length > 0
55
- ? opts.tools.map((t, i, arr) => {
56
- // Cache only the last tool to anchor the cache breakpoint at the end
57
- // of the tools block (Anthropic caches prefix up to the breakpoint).
58
- if (i === arr.length - 1)
59
- return { ...t, cache_control: { type: "ephemeral" } };
60
- return t;
61
- })
62
- : undefined;
63
-
64
- return {
65
- model: opts.model,
66
- max_tokens: opts.maxTokens ?? 1024,
67
- system: cachedSystem,
68
- tools: cachedTools,
69
- messages: opts.messages,
70
- };
71
- }