@eserstack/ai 0.0.0-bootstrap.0 → 5.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 (62) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +498 -0
  3. package/dist/adapters/ajan-bridge.d.ts +69 -0
  4. package/dist/adapters/ajan-bridge.js +661 -0
  5. package/dist/adapters/anthropic.d.ts +25 -0
  6. package/dist/adapters/anthropic.js +567 -0
  7. package/dist/adapters/claude-code.d.ts +28 -0
  8. package/dist/adapters/claude-code.js +462 -0
  9. package/dist/adapters/cli-shared.d.ts +36 -0
  10. package/dist/adapters/cli-shared.js +207 -0
  11. package/dist/adapters/gemini.d.ts +19 -0
  12. package/dist/adapters/gemini.js +91 -0
  13. package/dist/adapters/google-shared.d.ts +58 -0
  14. package/dist/adapters/google-shared.js +424 -0
  15. package/dist/adapters/kiro.d.ts +19 -0
  16. package/dist/adapters/kiro.js +195 -0
  17. package/dist/adapters/mod.d.ts +61 -0
  18. package/dist/adapters/mod.js +129 -0
  19. package/dist/adapters/ollama.d.ts +20 -0
  20. package/dist/adapters/ollama.js +226 -0
  21. package/dist/adapters/openai.d.ts +25 -0
  22. package/dist/adapters/openai.js +553 -0
  23. package/dist/adapters/opencode.d.ts +19 -0
  24. package/dist/adapters/opencode.js +158 -0
  25. package/dist/adapters/vertexai.d.ts +19 -0
  26. package/dist/adapters/vertexai.js +96 -0
  27. package/dist/batch.d.ts +35 -0
  28. package/dist/batch.js +2 -0
  29. package/dist/commands/ask.d.ts +30 -0
  30. package/dist/commands/ask.js +404 -0
  31. package/dist/commands/list.d.ts +2 -0
  32. package/dist/commands/list.js +35 -0
  33. package/dist/config.d.ts +21 -0
  34. package/dist/config.js +16 -0
  35. package/dist/content.d.ts +14 -0
  36. package/dist/content.js +103 -0
  37. package/dist/detect.d.ts +9 -0
  38. package/dist/detect.js +125 -0
  39. package/dist/errors.d.ts +62 -0
  40. package/dist/errors.js +135 -0
  41. package/dist/generation.d.ts +126 -0
  42. package/dist/generation.js +96 -0
  43. package/dist/main.d.ts +22 -0
  44. package/dist/main.js +42 -0
  45. package/dist/mod.d.ts +16 -0
  46. package/dist/mod.js +11 -0
  47. package/dist/model.d.ts +27 -0
  48. package/dist/model.js +12 -0
  49. package/dist/module.d.ts +10 -0
  50. package/dist/module.js +21 -0
  51. package/dist/package.json +74 -0
  52. package/dist/registry.d.ts +22 -0
  53. package/dist/registry.js +97 -0
  54. package/dist/streams/layers.d.ts +4 -0
  55. package/dist/streams/layers.js +33 -0
  56. package/dist/streams/mod.d.ts +2 -0
  57. package/dist/streams/mod.js +5 -0
  58. package/dist/streams/sources.d.ts +6 -0
  59. package/dist/streams/sources.js +76 -0
  60. package/dist/types.d.ts +79 -0
  61. package/dist/types.js +2 -0
  62. package/package.json +63 -1
@@ -0,0 +1,207 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ import * as shellExec from "@eserstack/shell/exec";
3
+ import * as errors from "../errors.js";
4
+ // =============================================================================
5
+ // Binary Resolution
6
+ // =============================================================================
7
+ export const resolveBinary = async (defaultName, cfg) => {
8
+ const binPath = cfg.properties?.["binPath"];
9
+ if (binPath !== undefined) {
10
+ return binPath;
11
+ }
12
+ // Try to find the binary on PATH via `which`
13
+ try {
14
+ const resolved = await shellExec.exec `which ${defaultName}`
15
+ .noThrow()
16
+ .text();
17
+ if (resolved.length > 0) {
18
+ return resolved;
19
+ }
20
+ }
21
+ catch {
22
+ // Fall through to error
23
+ }
24
+ throw new errors.AiError(`Binary "${defaultName}" not found. Set properties.binPath in config or ensure it is on PATH.`, { provider: defaultName });
25
+ };
26
+ export const spawnCliProcess = (binary, args, options) => {
27
+ const useStdinPipe = options?.stdinData !== undefined;
28
+ const builder = new shellExec.CommandBuilder(binary, [...args], {
29
+ stdin: useStdinPipe ? "piped" : "null",
30
+ stdout: "piped",
31
+ stderr: "piped",
32
+ cwd: options?.cwd,
33
+ env: options?.env,
34
+ });
35
+ const child = builder.child();
36
+ // Write stdin data and close
37
+ if (useStdinPipe && child.stdin !== null) {
38
+ const encoder = new TextEncoder();
39
+ const writer = child.stdin.getWriter();
40
+ writer
41
+ .write(encoder.encode(options.stdinData))
42
+ .then(() => writer.close())
43
+ .catch(() => {
44
+ // The write fails only when the CLI has already exited; its exit code
45
+ // and stderr tell the caller how it ended.
46
+ });
47
+ }
48
+ const signal = options?.signal;
49
+ let exited = false;
50
+ // An exited process is never signalled: its pid may belong to another
51
+ // process by then.
52
+ const kill = (name) => {
53
+ if (!exited) {
54
+ child.kill(name ?? "SIGTERM");
55
+ }
56
+ };
57
+ const onAbort = () => kill();
58
+ const status = child.status.then((result) => {
59
+ exited = true;
60
+ // A long-lived signal would otherwise hold one listener per request.
61
+ signal?.removeEventListener("abort", onAbort);
62
+ return result;
63
+ });
64
+ if (signal?.aborted === true) {
65
+ kill();
66
+ }
67
+ else {
68
+ signal?.addEventListener("abort", onAbort, { once: true });
69
+ }
70
+ return {
71
+ stdout: child.stdout,
72
+ stderr: child.stderr,
73
+ waitForExit: async () => {
74
+ const result = await status;
75
+ return { code: result.code, success: result.success };
76
+ },
77
+ kill,
78
+ };
79
+ };
80
+ /**
81
+ * Ends a CLI process when the caller is done with it: kills it if it is still
82
+ * running, then waits for its stderr capture to end, which happens when the
83
+ * process exits. Call it from `finally` in the scope that spawned the process.
84
+ * A stream whose consumer stops early otherwise leaves the CLI running, blocked
85
+ * on a stdout pipe that nobody reads.
86
+ */
87
+ export const stopCliProcess = async (process, stderrPromise) => {
88
+ process.kill();
89
+ // The capture is awaited instead of the exit status: the native child
90
+ // settles its streams on every path, but leaves its status pending after a
91
+ // failed read.
92
+ try {
93
+ await stderrPromise;
94
+ }
95
+ catch {
96
+ // stderr fails only together with stdout, whose read already reported the
97
+ // error to the caller, or was abandoned by a caller that stopped reading.
98
+ }
99
+ };
100
+ // =============================================================================
101
+ // JSONL Stream Parsing
102
+ // =============================================================================
103
+ const decoder = new TextDecoder();
104
+ export async function* parseJsonlStream(stdout) {
105
+ const reader = stdout.getReader();
106
+ let buffer = "";
107
+ try {
108
+ let readResult = await reader.read();
109
+ while (readResult.done !== true) {
110
+ buffer += decoder.decode(readResult.value, { stream: true });
111
+ const lines = buffer.split("\n");
112
+ buffer = lines.pop() ?? "";
113
+ for (const line of lines) {
114
+ const trimmed = line.trim();
115
+ if (trimmed.length === 0) {
116
+ continue;
117
+ }
118
+ try {
119
+ yield JSON.parse(trimmed);
120
+ }
121
+ catch {
122
+ // Skip malformed lines
123
+ }
124
+ }
125
+ // Reads stay sequential: each chunk extends the line buffer, and the
126
+ // consumer pulls lines one at a time.
127
+ // oxlint-disable-next-line no-await-in-loop
128
+ readResult = await reader.read();
129
+ }
130
+ // Flush remaining buffer
131
+ const remaining = buffer.trim();
132
+ if (remaining.length > 0) {
133
+ try {
134
+ yield JSON.parse(remaining);
135
+ }
136
+ catch {
137
+ // Skip malformed trailing data
138
+ }
139
+ }
140
+ }
141
+ finally {
142
+ reader.releaseLock();
143
+ }
144
+ }
145
+ // =============================================================================
146
+ // Plain Text Output Parsing
147
+ // =============================================================================
148
+ export const parseTextOutput = async (stdout, modelId) => {
149
+ const chunks = [];
150
+ for await (const chunk of stdout) {
151
+ chunks.push(decoder.decode(chunk, { stream: true }));
152
+ }
153
+ const text = chunks.join("").trim();
154
+ return {
155
+ content: [{ kind: "text", text }],
156
+ stopReason: "end_turn",
157
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
158
+ modelId,
159
+ };
160
+ };
161
+ // =============================================================================
162
+ // Stderr Capture
163
+ // =============================================================================
164
+ export const captureStderr = async (stderr) => {
165
+ const chunks = [];
166
+ for await (const chunk of stderr) {
167
+ chunks.push(decoder.decode(chunk, { stream: true }));
168
+ }
169
+ return chunks.join("").trim();
170
+ };
171
+ // =============================================================================
172
+ // Exit Code Classification
173
+ // =============================================================================
174
+ export const classifyExitCode = (provider, code, stderr) => {
175
+ if (code === 0) {
176
+ return null;
177
+ }
178
+ const message = stderr.length > 0
179
+ ? `${provider} exited with code ${code}: ${stderr}`
180
+ : `${provider} exited with code ${code}`;
181
+ // Common exit code patterns
182
+ if (code === 1) {
183
+ return new errors.AiError(message, { provider });
184
+ }
185
+ if (code === 126 || code === 127) {
186
+ return new errors.AiError(`${provider} binary not found or not executable (exit code ${code})`, { provider });
187
+ }
188
+ return new errors.AiError(message, { provider });
189
+ };
190
+ // =============================================================================
191
+ // Message Formatting
192
+ // =============================================================================
193
+ export const formatMessagesAsText = (messages, system) => {
194
+ const parts = [];
195
+ if (system !== undefined) {
196
+ parts.push(system);
197
+ parts.push("");
198
+ }
199
+ for (const message of messages) {
200
+ for (const block of message.content) {
201
+ if (block.kind === "text") {
202
+ parts.push(block.text);
203
+ }
204
+ }
205
+ }
206
+ return parts.join("\n");
207
+ };
@@ -0,0 +1,19 @@
1
+ import * as results from "@eserstack/primitives/results";
2
+ import type * as types from "../types.ts";
3
+ import type * as config from "../config.ts";
4
+ import type * as generation from "../generation.ts";
5
+ import type * as model from "../model.ts";
6
+ import * as errors from "../errors.ts";
7
+ export declare class GeminiModel implements model.LanguageModel {
8
+ readonly capabilities: readonly types.ProviderCapability[];
9
+ readonly provider = "gemini";
10
+ readonly modelId: string;
11
+ private readonly client;
12
+ private readonly config;
13
+ constructor(client: any, cfg: config.ResolvedConfigTarget);
14
+ generateText(options: generation.GenerateTextOptions, signal?: AbortSignal): Promise<results.Result<generation.GenerateTextResult, errors.AiError>>;
15
+ streamText(options: generation.GenerateTextOptions, signal?: AbortSignal): AsyncIterable<generation.StreamEvent>;
16
+ close(): Promise<void>;
17
+ getRawClient(): unknown;
18
+ }
19
+ export declare const geminiFactory: model.ProviderFactory;
@@ -0,0 +1,91 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ import * as results from "@eserstack/primitives/results";
3
+ import * as errors from "../errors.js";
4
+ import * as googleShared from "./google-shared.js";
5
+ // =============================================================================
6
+ // Gemini Model
7
+ // =============================================================================
8
+ export class GeminiModel {
9
+ capabilities = [
10
+ "text_generation",
11
+ "streaming",
12
+ "tool_calling",
13
+ "vision",
14
+ "audio",
15
+ "structured_output",
16
+ "reasoning",
17
+ ];
18
+ provider = "gemini";
19
+ modelId;
20
+ // The SDK is loaded lazily by the factory; its client type is not in scope.
21
+ // oxlint-disable-next-line typescript/no-explicit-any
22
+ client;
23
+ config;
24
+ // Takes the lazily imported SDK client stored in the field above.
25
+ // oxlint-disable-next-line typescript/no-explicit-any
26
+ constructor(client, cfg) {
27
+ this.client = client;
28
+ this.config = cfg;
29
+ this.modelId = cfg.model;
30
+ }
31
+ async generateText(options, signal) {
32
+ try {
33
+ const request = googleShared.buildGenAIRequest(this.config, options, this.provider, signal);
34
+ const response = await this.client.models.generateContent({
35
+ model: this.config.model,
36
+ ...request,
37
+ });
38
+ return results.ok(googleShared.mapGenAIResponseToResult(response, this.modelId));
39
+ }
40
+ catch (err) {
41
+ return results.fail(classifyError(err));
42
+ }
43
+ }
44
+ async *streamText(options, signal) {
45
+ try {
46
+ const request = googleShared.buildGenAIRequest(this.config, options, this.provider, signal);
47
+ const stream = await this.client.models.generateContentStream({
48
+ model: this.config.model,
49
+ ...request,
50
+ });
51
+ yield* googleShared.mapGenAIStream(stream);
52
+ }
53
+ catch (err) {
54
+ yield { kind: "error", error: classifyError(err) };
55
+ }
56
+ }
57
+ async close() {
58
+ // Gemini SDK doesn't require explicit cleanup
59
+ }
60
+ getRawClient() {
61
+ return this.client;
62
+ }
63
+ }
64
+ // =============================================================================
65
+ // Factory
66
+ // =============================================================================
67
+ export const geminiFactory = {
68
+ provider: "gemini",
69
+ createModel: async (cfg) => {
70
+ const genai = await import("@google/genai");
71
+ // @google/genai 3 defaults the Gemini API to v1 and lets
72
+ // GOOGLE_GENAI_API_VERSION move it; v1beta is the version the Go twin
73
+ // calls (pkg/ajan/aifx/google_client.go).
74
+ const client = new genai.GoogleGenAI({
75
+ apiKey: cfg.apiKey,
76
+ apiVersion: "v1beta",
77
+ });
78
+ return new GeminiModel(client, cfg);
79
+ },
80
+ };
81
+ // =============================================================================
82
+ // Internal Helpers
83
+ // =============================================================================
84
+ const classifyError = (err) => {
85
+ if (err instanceof errors.AiError) {
86
+ return err;
87
+ }
88
+ const error = err instanceof Error ? err : new Error(String(err));
89
+ const statusCode = googleShared.classifyGenAIError(err);
90
+ return errors.classifyAndWrap("gemini", statusCode, error);
91
+ };
@@ -0,0 +1,58 @@
1
+ import type * as types from "../types.ts";
2
+ import type * as config from "../config.ts";
3
+ import * as generation from "../generation.ts";
4
+ export declare const mapRoleToGenAI: (role: types.Role) => string;
5
+ export declare const mapContentBlockToGenAIPart: (block: types.ContentBlock) => Record<string, unknown>;
6
+ export declare const mapMessagesToGenAI: (messages: readonly types.Message[]) => {
7
+ readonly contents: readonly Record<string, unknown>[];
8
+ readonly systemInstruction: string | null;
9
+ };
10
+ export declare const mapToolsToGenAI: (tools: readonly types.ToolDefinition[]) => readonly Record<string, unknown>[];
11
+ /** The `contents` and `config` of a genai `generateContent` request. */
12
+ export type GenAIRequest = {
13
+ readonly contents: readonly Record<string, unknown>[];
14
+ readonly config: Readonly<Record<string, unknown>>;
15
+ };
16
+ /**
17
+ * Maps an effort level to a Gemini thinking level. Gemini's levels stop at
18
+ * `HIGH`, so `"xhigh"` and `"max"` send `HIGH`. The levels a model takes differ
19
+ * per model (gemini-3-pro-preview has no `MEDIUM`) and are not checked here;
20
+ * the API answers for the model, as on `openai`.
21
+ *
22
+ * @throws {errors.BadRequestError} when `effort` is not one of the five
23
+ * levels, which a JavaScript caller can pass.
24
+ */
25
+ export declare const mapEffortToThinkingLevel: (effort: generation.Effort, provider: string) => string;
26
+ /**
27
+ * Builds the genai `generateContent` request of `gemini` and `vertexai`. The
28
+ * SDK reads the system instruction, tools, safety settings and abort signal
29
+ * from `config` only, and drops a field set next to it without an error.
30
+ *
31
+ * An explicit `effort` is sent as `thinkingConfig.thinkingLevel` and wins over
32
+ * `thinkingBudget`, since the API rejects a request that sets both.
33
+ *
34
+ * @throws {errors.BadRequestError} when a `json_schema` response format has no
35
+ * object schema, or `effort` is not a level.
36
+ */
37
+ export declare const buildGenAIRequest: (cfg: config.ResolvedConfigTarget, options: generation.GenerateTextOptions, provider: string, signal: AbortSignal | undefined) => GenAIRequest;
38
+ /**
39
+ * Maps a genai finishReason. Gemini ends a turn that called a tool with
40
+ * `STOP`, so `calledTool` turns that into `"tool_use"`. Any other reason has no
41
+ * closer match than `"stop"`.
42
+ */
43
+ export declare const mapGenAIFinishReason: (finishReason: string, calledTool: boolean) => generation.StopReason;
44
+ /**
45
+ * Reports whether a filter blocked the prompt itself. The response then has no
46
+ * candidates and names the filter in `promptFeedback.blockReason`.
47
+ */
48
+ export declare const isGenAIPromptBlocked: (response: any) => boolean;
49
+ export declare const mapGenAIResponseToResult: (response: any, modelId: string) => generation.GenerateTextResult;
50
+ /**
51
+ * Maps the chunks of a genai stream to stream events. A tool call is
52
+ * remembered across chunks, since the chunk that ends the turn need not be the
53
+ * one with the call. That chunk yields `message_done` even without content: a
54
+ * filtered answer can arrive as a finish reason with no parts, and a blocked
55
+ * prompt as a chunk with no candidates.
56
+ */
57
+ export declare function mapGenAIStream(stream: AsyncIterable<any>): AsyncIterable<generation.StreamEvent>;
58
+ export declare const classifyGenAIError: (error: any) => number;