@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,158 @@
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 cliShared from "./cli-shared.js";
5
+ // =============================================================================
6
+ // OpenCode Model
7
+ // =============================================================================
8
+ export class OpenCodeModel {
9
+ capabilities = [
10
+ "text_generation",
11
+ "streaming",
12
+ ];
13
+ provider = "opencode";
14
+ modelId;
15
+ binary;
16
+ config;
17
+ constructor(binary, cfg) {
18
+ this.binary = binary;
19
+ this.config = cfg;
20
+ this.modelId = cfg.model;
21
+ }
22
+ async generateText(options, signal) {
23
+ const args = buildArgs(this.config, options, "json");
24
+ const prompt = cliShared.formatMessagesAsText(options.messages, options.system);
25
+ const process = cliShared.spawnCliProcess(this.binary, args, {
26
+ signal,
27
+ stdinData: prompt,
28
+ });
29
+ const stderrPromise = cliShared.captureStderr(process.stderr);
30
+ try {
31
+ const result = await cliShared.parseTextOutput(process.stdout, this.modelId);
32
+ const exit = await process.waitForExit();
33
+ const stderr = await stderrPromise;
34
+ const exitError = cliShared.classifyExitCode("opencode", exit.code, stderr);
35
+ if (exitError !== null) {
36
+ return results.fail(exitError);
37
+ }
38
+ return results.ok(result);
39
+ }
40
+ finally {
41
+ await cliShared.stopCliProcess(process, stderrPromise);
42
+ }
43
+ }
44
+ async *streamText(options, signal) {
45
+ const args = buildArgs(this.config, options, "stream-json");
46
+ const prompt = cliShared.formatMessagesAsText(options.messages, options.system);
47
+ const process = cliShared.spawnCliProcess(this.binary, args, {
48
+ signal,
49
+ stdinData: prompt,
50
+ });
51
+ const stderrPromise = cliShared.captureStderr(process.stderr);
52
+ try {
53
+ for await (const event of cliShared.parseJsonlStream(process.stdout)) {
54
+ const streamEvent = mapStreamEvent(event);
55
+ if (streamEvent !== null) {
56
+ yield streamEvent;
57
+ }
58
+ }
59
+ const exit = await process.waitForExit();
60
+ const stderr = await stderrPromise;
61
+ const exitError = cliShared.classifyExitCode("opencode", exit.code, stderr);
62
+ if (exitError !== null) {
63
+ yield { kind: "error", error: exitError };
64
+ }
65
+ }
66
+ catch (err) {
67
+ if (err instanceof errors.AiError) {
68
+ yield { kind: "error", error: err };
69
+ }
70
+ else {
71
+ yield {
72
+ kind: "error",
73
+ error: new errors.AiError(err instanceof Error ? err.message : String(err), {
74
+ provider: "opencode",
75
+ cause: err instanceof Error ? err : undefined,
76
+ }),
77
+ };
78
+ }
79
+ }
80
+ finally {
81
+ // Also reached when the consumer stops reading early.
82
+ await cliShared.stopCliProcess(process, stderrPromise);
83
+ }
84
+ }
85
+ close() {
86
+ return Promise.resolve();
87
+ }
88
+ getRawClient() {
89
+ return null;
90
+ }
91
+ }
92
+ // =============================================================================
93
+ // Factory
94
+ // =============================================================================
95
+ export const openCodeFactory = {
96
+ provider: "opencode",
97
+ createModel: async (cfg) => {
98
+ const binary = await cliShared.resolveBinary("opencode", cfg);
99
+ return new OpenCodeModel(binary, cfg);
100
+ },
101
+ };
102
+ // =============================================================================
103
+ // Internal Helpers
104
+ // =============================================================================
105
+ /** Builds the CLI arguments. options.effort is ignored: no effort flag is sent. */
106
+ const buildArgs = (cfg, options, outputFormat) => {
107
+ const args = ["--output-format", outputFormat];
108
+ args.push("--model", cfg.model);
109
+ if (options.maxTokens !== undefined) {
110
+ args.push("--max-tokens", String(options.maxTokens));
111
+ }
112
+ // Pass through additional CLI flags from properties
113
+ const extraArgs = cfg.properties?.["args"];
114
+ if (extraArgs !== undefined) {
115
+ args.push(...extraArgs);
116
+ }
117
+ return args;
118
+ };
119
+ const mapStreamEvent = (event) => {
120
+ if (event === null || typeof event !== "object") {
121
+ return null;
122
+ }
123
+ // Stream events are untyped JSON; each field is checked before use.
124
+ // oxlint-disable-next-line typescript/no-explicit-any
125
+ const obj = event;
126
+ // Content delta
127
+ if (obj.type === "content_block_delta" || obj.type === "assistant") {
128
+ const text = obj.delta?.text ?? obj.message?.content?.[0]?.text;
129
+ if (text !== undefined) {
130
+ return { kind: "content_delta", textDelta: text };
131
+ }
132
+ return null;
133
+ }
134
+ // Result / done
135
+ if (obj.type === "result" || obj.done === true) {
136
+ return {
137
+ kind: "message_done",
138
+ stopReason: "end_turn",
139
+ usage: {
140
+ inputTokens: obj.usage?.input_tokens ?? 0,
141
+ outputTokens: obj.usage?.output_tokens ?? 0,
142
+ totalTokens: (obj.usage?.input_tokens ?? 0) + (obj.usage?.output_tokens ?? 0),
143
+ },
144
+ };
145
+ }
146
+ // Error
147
+ if (obj.type === "error") {
148
+ return {
149
+ kind: "error",
150
+ error: new errors.AiError(obj.error?.message ?? "Unknown OpenCode error", { provider: "opencode" }),
151
+ };
152
+ }
153
+ // Generic text content
154
+ if (obj.content !== undefined && typeof obj.content === "string") {
155
+ return { kind: "content_delta", textDelta: obj.content };
156
+ }
157
+ return null;
158
+ };
@@ -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 VertexAIModel implements model.LanguageModel {
8
+ readonly capabilities: readonly types.ProviderCapability[];
9
+ readonly provider = "vertexai";
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 vertexaiFactory: model.ProviderFactory;
@@ -0,0 +1,96 @@
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
+ // VertexAI Model
7
+ // =============================================================================
8
+ export class VertexAIModel {
9
+ capabilities = [
10
+ "text_generation",
11
+ "streaming",
12
+ "tool_calling",
13
+ "vision",
14
+ "audio",
15
+ "structured_output",
16
+ "reasoning",
17
+ ];
18
+ provider = "vertexai";
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
+ // VertexAI SDK doesn't require explicit cleanup
59
+ }
60
+ getRawClient() {
61
+ return this.client;
62
+ }
63
+ }
64
+ // =============================================================================
65
+ // Factory
66
+ // =============================================================================
67
+ export const vertexaiFactory = {
68
+ provider: "vertexai",
69
+ createModel: async (cfg) => {
70
+ const genai = await import("@google/genai");
71
+ const clientOptions = {
72
+ vertexai: true,
73
+ project: cfg.projectId,
74
+ location: cfg.location ?? "us-central1",
75
+ // Pinned so GOOGLE_GENAI_API_VERSION cannot move it; v1beta1 is the
76
+ // version the Go twin calls (pkg/ajan/aifx/google_client.go).
77
+ apiVersion: "v1beta1",
78
+ };
79
+ if (cfg.apiKey !== undefined) {
80
+ clientOptions["apiKey"] = cfg.apiKey;
81
+ }
82
+ const client = new genai.GoogleGenAI(clientOptions);
83
+ return new VertexAIModel(client, cfg);
84
+ },
85
+ };
86
+ // =============================================================================
87
+ // Internal Helpers
88
+ // =============================================================================
89
+ const classifyError = (err) => {
90
+ if (err instanceof errors.AiError) {
91
+ return err;
92
+ }
93
+ const error = err instanceof Error ? err : new Error(String(err));
94
+ const statusCode = googleShared.classifyGenAIError(err);
95
+ return errors.classifyAndWrap("vertexai", statusCode, error);
96
+ };
@@ -0,0 +1,35 @@
1
+ import type * as generation from "./generation.ts";
2
+ export type BatchStatus = "pending" | "processing" | "completed" | "failed" | "cancelled";
3
+ export type BatchRequestItem = {
4
+ readonly customId: string;
5
+ readonly options: generation.GenerateTextOptions;
6
+ };
7
+ export type BatchRequest = {
8
+ readonly items: readonly BatchRequestItem[];
9
+ };
10
+ export type BatchStorage = {
11
+ readonly type: string;
12
+ readonly inputRef?: string;
13
+ readonly outputRef?: string;
14
+ readonly properties?: Record<string, unknown>;
15
+ };
16
+ export type BatchJob = {
17
+ readonly id: string;
18
+ readonly status: BatchStatus;
19
+ readonly createdAt: Date;
20
+ readonly completedAt?: Date;
21
+ readonly totalCount: number;
22
+ readonly doneCount: number;
23
+ readonly failedCount: number;
24
+ readonly storage?: BatchStorage;
25
+ readonly error?: string;
26
+ };
27
+ export type BatchResult = {
28
+ readonly customId: string;
29
+ readonly result?: generation.GenerateTextResult;
30
+ readonly error?: string;
31
+ };
32
+ export type ListBatchOptions = {
33
+ readonly limit?: number;
34
+ readonly after?: string;
35
+ };
package/dist/batch.js ADDED
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `ai ask` — Send a prompt to an AI provider and stream the response.
3
+ *
4
+ * @module
5
+ */
6
+ import * as results from "@eserstack/primitives/results";
7
+ import type * as shellArgs from "@eserstack/shell/args";
8
+ import * as generationHelpers from "../generation.ts";
9
+ export type { Effort } from "../generation.ts";
10
+ /** The flags and prompt of one `ai ask` call. */
11
+ export type AskArgs = {
12
+ readonly provider: string | null;
13
+ readonly model: string | null;
14
+ readonly maxTokens: number | null;
15
+ readonly effort: generationHelpers.Effort | null;
16
+ readonly json: boolean;
17
+ readonly verbose: boolean;
18
+ readonly prompt: string;
19
+ };
20
+ /**
21
+ * Parses the arguments of `ai ask`. The failure is the message to print: a
22
+ * flag without its value, an invalid value, or no prompt.
23
+ */
24
+ export declare const parseAskArgs: (args: readonly string[]) => results.Result<AskArgs, string>;
25
+ /**
26
+ * Runs `ai ask`: parses the arguments, picks the provider (from `-p` or by
27
+ * detection), sends the prompt and writes the reply to stdout. Invalid
28
+ * arguments fail before a provider is chosen.
29
+ */
30
+ export declare const main: (args?: readonly string[]) => Promise<shellArgs.CliResult<void>>;