@nones/agentflow-opencode 0.0.0-stage → 0.1.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/src/config.ts ADDED
@@ -0,0 +1,268 @@
1
+ import { OpenCodeConfigError } from "./errors";
2
+ import { asString, isRecord, parseModelRef } from "./normalize";
3
+ import type {
4
+ AgentSpec,
5
+ AuthReference,
6
+ AuthReferenceObject,
7
+ ModelRef,
8
+ OpenCodeAdapterOptions,
9
+ OpenCodeProfileSettings,
10
+ OpenCodeTimeouts,
11
+ Profile,
12
+ } from "./types";
13
+
14
+ export interface ResolvedTimeouts {
15
+ requestMs: number;
16
+ sessionReadyMs: number;
17
+ turnMs: number;
18
+ waitMs: number;
19
+ }
20
+
21
+ export interface ResolvedConnection {
22
+ endpoint: string;
23
+ headers: Record<string, string>;
24
+ timeouts: ResolvedTimeouts;
25
+ settings: OpenCodeProfileSettings;
26
+ }
27
+
28
+ const DEFAULT_TIMEOUTS: ResolvedTimeouts = {
29
+ requestMs: 15_000,
30
+ sessionReadyMs: 5_000,
31
+ turnMs: 120_000,
32
+ waitMs: 10_000,
33
+ };
34
+
35
+ export function readSettings(profile: Profile): OpenCodeProfileSettings {
36
+ return isRecord(profile.settings)
37
+ ? (profile.settings as OpenCodeProfileSettings)
38
+ : {};
39
+ }
40
+
41
+ function mergeTimeouts(
42
+ base: ResolvedTimeouts,
43
+ ...overrides: Array<OpenCodeTimeouts | undefined>
44
+ ): ResolvedTimeouts {
45
+ const result = { ...base };
46
+ for (const override of overrides) {
47
+ if (!override || !isRecord(override)) continue;
48
+ for (const key of Object.keys(result) as Array<keyof ResolvedTimeouts>) {
49
+ const value = override[key];
50
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
51
+ result[key] = value;
52
+ }
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+
58
+ export function resolveEndpoint(
59
+ profile: Profile,
60
+ options: OpenCodeAdapterOptions,
61
+ ): string {
62
+ const settings = readSettings(profile);
63
+ let endpoint = asString(settings.endpoint);
64
+
65
+ if (!endpoint && settings.endpointName) {
66
+ endpoint =
67
+ options.resolveEndpoint?.(settings.endpointName) ??
68
+ options.endpoints?.[settings.endpointName];
69
+ if (!endpoint) {
70
+ throw new OpenCodeConfigError(
71
+ `No endpoint registered for name "${settings.endpointName}". Port discovery is deliberately not automatic.`,
72
+ );
73
+ }
74
+ }
75
+
76
+ if (!endpoint) {
77
+ throw new OpenCodeConfigError(
78
+ `Profile "${profile.id}" has no OpenCode endpoint. Set settings.endpoint or a deliberate settings.endpointName.`,
79
+ );
80
+ }
81
+
82
+ let url: URL;
83
+ try {
84
+ url = new URL(endpoint);
85
+ } catch (error) {
86
+ throw new OpenCodeConfigError(`Invalid OpenCode endpoint "${endpoint}".`, {
87
+ cause: error,
88
+ });
89
+ }
90
+
91
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
92
+ throw new OpenCodeConfigError("OpenCode endpoint must use http or https.");
93
+ }
94
+ if (url.username || url.password) {
95
+ throw new OpenCodeConfigError(
96
+ "OpenCode endpoint must not embed credentials; use settings.auth instead.",
97
+ );
98
+ }
99
+ assertLoopback(url, options.allowNonLoopback === true);
100
+
101
+ url.search = "";
102
+ url.hash = "";
103
+ return url.toString().replace(/\/$/, "");
104
+ }
105
+
106
+ function assertLoopback(url: URL, allowNonLoopback: boolean): void {
107
+ if (allowNonLoopback) return;
108
+ const host = url.hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
109
+ if (
110
+ host === "localhost" ||
111
+ host.endsWith(".localhost") ||
112
+ host === "::1" ||
113
+ host === "0:0:0:0:0:0:0:1" ||
114
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)
115
+ ) {
116
+ return;
117
+ }
118
+ throw new OpenCodeConfigError(
119
+ `OpenCode endpoint "${url.origin}" is not loopback. Local-only adapter; pass allowNonLoopback explicitly only for a deliberate deployment.`,
120
+ );
121
+ }
122
+
123
+ interface NormalizedAuth {
124
+ kind: "bearer" | "header";
125
+ name?: string;
126
+ value?: string;
127
+ ref?: string;
128
+ }
129
+
130
+ function normalizeAuth(auth: AuthReference, profile: Profile): NormalizedAuth {
131
+ if (typeof auth === "string") {
132
+ if (!auth) {
133
+ throw new OpenCodeConfigError(
134
+ `Profile "${profile.id}" has an empty auth reference.`,
135
+ );
136
+ }
137
+ return { kind: "bearer", ref: auth };
138
+ }
139
+ if (!isRecord(auth)) {
140
+ throw new OpenCodeConfigError(
141
+ `Profile "${profile.id}" has an unsupported auth reference.`,
142
+ );
143
+ }
144
+ const object = auth as AuthReferenceObject;
145
+ const kind = object.type === "header" || object.header ? "header" : "bearer";
146
+ const value = object.value ?? object.token;
147
+ const ref = object.ref ?? object.tokenRef;
148
+ if (!value && !ref) {
149
+ throw new OpenCodeConfigError(
150
+ `Profile "${profile.id}" auth reference has neither value nor ref.`,
151
+ );
152
+ }
153
+ if (kind === "header" && !(object.name ?? object.header)) {
154
+ throw new OpenCodeConfigError(
155
+ `Profile "${profile.id}" header auth reference requires a name.`,
156
+ );
157
+ }
158
+ return { kind, name: object.name ?? object.header, value, ref };
159
+ }
160
+
161
+ async function resolveAuthValue(
162
+ reference: { value?: string; ref?: string },
163
+ profile: Profile,
164
+ options: OpenCodeAdapterOptions,
165
+ ): Promise<string> {
166
+ if (reference.value) return reference.value;
167
+ if (!reference.ref) {
168
+ throw new OpenCodeConfigError(
169
+ `Profile "${profile.id}" auth reference has neither value nor ref.`,
170
+ );
171
+ }
172
+ if (!options.resolveCredential) {
173
+ throw new OpenCodeConfigError(
174
+ `Profile "${profile.id}" uses credential reference "${reference.ref}" but no resolveCredential function was supplied.`,
175
+ );
176
+ }
177
+ const value = await options.resolveCredential(reference.ref, profile);
178
+ if (!value) {
179
+ throw new OpenCodeConfigError(
180
+ `Credential reference "${reference.ref}" for profile "${profile.id}" resolved to nothing.`,
181
+ );
182
+ }
183
+ return value;
184
+ }
185
+
186
+ export async function resolveConnection(
187
+ profile: Profile,
188
+ options: OpenCodeAdapterOptions,
189
+ ): Promise<ResolvedConnection> {
190
+ const settings = readSettings(profile);
191
+ const endpoint = resolveEndpoint(profile, options);
192
+ const headers: Record<string, string> = {
193
+ ...(options.headers ?? {}),
194
+ ...(settings.headers ?? {}),
195
+ };
196
+
197
+ if (settings.auth !== undefined) {
198
+ const auth = normalizeAuth(settings.auth, profile);
199
+ const token = await resolveAuthValue(auth, profile, options);
200
+ if (auth.kind === "bearer") {
201
+ headers.authorization = `Bearer ${token}`;
202
+ } else {
203
+ headers[auth.name as string] = token;
204
+ }
205
+ }
206
+
207
+ const timeouts = mergeTimeouts(
208
+ DEFAULT_TIMEOUTS,
209
+ options.timeouts,
210
+ settings.timeouts,
211
+ );
212
+
213
+ return { endpoint, headers, timeouts, settings };
214
+ }
215
+
216
+ /**
217
+ * Resolve the concrete native model. A model is required: OpenCode sessions
218
+ * are verified by polling for an explicitly requested provider/model pair.
219
+ */
220
+ export function resolveModel(agent: AgentSpec, profile: Profile): ModelRef {
221
+ const settings = readSettings(profile);
222
+ const candidates: Array<[string, unknown]> = [
223
+ ["agent.model", agent.model],
224
+ ["agent.settings.model", agent.settings?.model],
225
+ ["profile.model", profile.model],
226
+ ["profile.settings.model", settings.model],
227
+ ];
228
+ for (const [source, value] of candidates) {
229
+ if (value === undefined || value === null || value === "") continue;
230
+ return parseModelRef(value, source);
231
+ }
232
+ throw new OpenCodeConfigError(
233
+ `No concrete model configured for profile "${profile.id}" (agent "${agent.id}").`,
234
+ );
235
+ }
236
+
237
+ export function tryResolveModel(
238
+ agent: AgentSpec,
239
+ profile: Profile,
240
+ ): ModelRef | undefined {
241
+ try {
242
+ return resolveModel(agent, profile);
243
+ } catch {
244
+ return undefined;
245
+ }
246
+ }
247
+
248
+ export function resolveTurnDelivery(
249
+ settings: OpenCodeProfileSettings,
250
+ ): "queue" | "steer" {
251
+ return settings.turnDelivery === "steer" ? "steer" : "queue";
252
+ }
253
+
254
+ /**
255
+ * Resolve the native location directory. Only explicit profile settings or an
256
+ * explicit host-provided default are used; the adapter never invents a cwd.
257
+ */
258
+ export function resolveDirectory(
259
+ profile: Profile,
260
+ options: OpenCodeAdapterOptions,
261
+ ): string | undefined {
262
+ const settings = readSettings(profile);
263
+ return (
264
+ asString(settings.directory) ??
265
+ asString(settings.cwd) ??
266
+ asString(options.defaultCwd)
267
+ );
268
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { RateLimitInfo } from "./types";
2
+
3
+ /** Base class for adapter failures that are safe to inspect programmatically. */
4
+ export class OpenCodeError extends Error {
5
+ readonly code: string;
6
+
7
+ constructor(
8
+ message: string,
9
+ code = "opencode_error",
10
+ options?: ErrorOptions,
11
+ ) {
12
+ super(message, options);
13
+ this.name = new.target.name;
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ export class OpenCodeConfigError extends OpenCodeError {
19
+ constructor(message: string, options?: ErrorOptions) {
20
+ super(message, "opencode_config", options);
21
+ }
22
+ }
23
+
24
+ export class OpenCodeHttpError extends OpenCodeError {
25
+ readonly status: number;
26
+ readonly body: unknown;
27
+ readonly retryAfterMs?: number;
28
+
29
+ constructor(
30
+ message: string,
31
+ status: number,
32
+ body: unknown,
33
+ retryAfterMs?: number,
34
+ options?: ErrorOptions,
35
+ code = "opencode_http",
36
+ ) {
37
+ super(message, code, options);
38
+ this.status = status;
39
+ this.body = body;
40
+ this.retryAfterMs = retryAfterMs;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * An explicit 429 rejection. The server rejected the submission before
46
+ * accepting it, therefore resubmission is safe under the caller's retry
47
+ * policy.
48
+ */
49
+ export class OpenCodeRateLimitError extends OpenCodeHttpError {
50
+ readonly rateLimit: RateLimitInfo;
51
+
52
+ constructor(
53
+ message: string,
54
+ status: number,
55
+ body: unknown,
56
+ rateLimit: RateLimitInfo,
57
+ options?: ErrorOptions,
58
+ ) {
59
+ super(
60
+ message,
61
+ status,
62
+ body,
63
+ rateLimit.retryAfterMs,
64
+ options,
65
+ "opencode_rate_limited",
66
+ );
67
+ this.rateLimit = rateLimit;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The request may or may not have been admitted. Callers must not retry
73
+ * automatically; the safest mapping is an interrupted turn.
74
+ */
75
+ export class OpenCodeAmbiguousAdmissionError extends OpenCodeError {
76
+ constructor(message: string, options?: ErrorOptions) {
77
+ super(message, "opencode_ambiguous_admission", options);
78
+ }
79
+ }
80
+
81
+ export class OpenCodeTransportError extends OpenCodeError {
82
+ constructor(
83
+ message: string,
84
+ options?: ErrorOptions,
85
+ code = "opencode_transport",
86
+ ) {
87
+ super(message, code, options);
88
+ }
89
+ }
90
+
91
+ export class OpenCodeTimeoutError extends OpenCodeTransportError {
92
+ constructor(message: string, options?: ErrorOptions) {
93
+ super(message, options, "opencode_timeout");
94
+ }
95
+ }
package/src/http.ts ADDED
@@ -0,0 +1,169 @@
1
+ import type { ResolvedConnection } from "./config";
2
+ import { OpenCodeTimeoutError, OpenCodeTransportError } from "./errors";
3
+
4
+ export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
5
+
6
+ export interface HttpResult {
7
+ status: number;
8
+ ok: boolean;
9
+ headers: Headers;
10
+ text: string;
11
+ body: unknown;
12
+ }
13
+
14
+ export interface HttpRequestOptions {
15
+ method: "GET" | "POST" | "PUT";
16
+ path: string;
17
+ body?: unknown;
18
+ signal?: AbortSignal;
19
+ timeoutMs?: number;
20
+ }
21
+
22
+ export function combineSignals(
23
+ signals: readonly (AbortSignal | undefined)[],
24
+ ): AbortSignal {
25
+ const present = signals.filter(
26
+ (signal): signal is AbortSignal => signal !== undefined,
27
+ );
28
+ if (present.length === 0) return new AbortController().signal;
29
+ if (present.length === 1) return present[0];
30
+ const anySignal = (
31
+ AbortSignal as unknown as {
32
+ any?: (signals: AbortSignal[]) => AbortSignal;
33
+ }
34
+ ).any;
35
+ if (typeof anySignal === "function")
36
+ return anySignal.call(AbortSignal, present);
37
+
38
+ const controller = new AbortController();
39
+ const abort = (signal: AbortSignal) => {
40
+ if (!controller.signal.aborted) controller.abort();
41
+ };
42
+ for (const signal of present) {
43
+ if (signal.aborted) {
44
+ abort(signal);
45
+ break;
46
+ }
47
+ signal.addEventListener("abort", () => abort(signal), { once: true });
48
+ }
49
+ return controller.signal;
50
+ }
51
+
52
+ export function joinUrl(endpoint: string, path: string): string {
53
+ return `${endpoint.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
54
+ }
55
+
56
+ function parseBody(text: string): unknown {
57
+ const trimmed = text.trim();
58
+ if (!trimmed) return undefined;
59
+ if (!(
60
+ trimmed.startsWith("{") ||
61
+ trimmed.startsWith("[") ||
62
+ trimmed.startsWith('"')
63
+ )) {
64
+ return undefined;
65
+ }
66
+ try {
67
+ return JSON.parse(trimmed);
68
+ } catch {
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ export class HttpClient {
74
+ constructor(
75
+ private readonly fetchImpl: FetchLike,
76
+ private readonly now: () => number,
77
+ ) {}
78
+
79
+ async request(
80
+ connection: ResolvedConnection,
81
+ options: HttpRequestOptions,
82
+ ): Promise<HttpResult> {
83
+ const controller = new AbortController();
84
+ const timeoutMs = options.timeoutMs ?? connection.timeouts.requestMs;
85
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
86
+ const signal = combineSignals([options.signal, controller.signal]);
87
+ const headers: Record<string, string> = {
88
+ accept: "application/json",
89
+ ...connection.headers,
90
+ };
91
+ let body: string | undefined;
92
+ if (options.body !== undefined) {
93
+ headers["content-type"] = "application/json";
94
+ body = JSON.stringify(options.body);
95
+ }
96
+
97
+ try {
98
+ const response = await this.fetchImpl(
99
+ joinUrl(connection.endpoint, options.path),
100
+ {
101
+ method: options.method,
102
+ headers,
103
+ body,
104
+ signal,
105
+ redirect: "error",
106
+ },
107
+ );
108
+ const text = await response.text();
109
+ return {
110
+ status: response.status,
111
+ ok: response.ok,
112
+ headers: response.headers,
113
+ text,
114
+ body: parseBody(text),
115
+ };
116
+ } catch (error) {
117
+ if (options.signal?.aborted) {
118
+ throw new OpenCodeTransportError("Request aborted by caller.", {
119
+ cause: error,
120
+ });
121
+ }
122
+ if (controller.signal.aborted) {
123
+ throw new OpenCodeTimeoutError(
124
+ `OpenCode request timed out after ${timeoutMs}ms: ${options.method} ${options.path}`,
125
+ { cause: error },
126
+ );
127
+ }
128
+ throw new OpenCodeTransportError(
129
+ `OpenCode transport failure for ${options.method} ${options.path}: ${error instanceof Error ? error.message : String(error)}`,
130
+ { cause: error },
131
+ );
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+
137
+ async stream(
138
+ connection: ResolvedConnection,
139
+ path: string,
140
+ signal: AbortSignal,
141
+ ): Promise<Response> {
142
+ const headers: Record<string, string> = {
143
+ accept: "text/event-stream",
144
+ ...connection.headers,
145
+ };
146
+ try {
147
+ return await this.fetchImpl(joinUrl(connection.endpoint, path), {
148
+ method: "GET",
149
+ headers,
150
+ signal,
151
+ redirect: "error",
152
+ });
153
+ } catch (error) {
154
+ if (signal.aborted) {
155
+ throw new OpenCodeTransportError("Event stream aborted.", {
156
+ cause: error,
157
+ });
158
+ }
159
+ throw new OpenCodeTransportError(
160
+ `OpenCode event stream failed for ${path}: ${error instanceof Error ? error.message : String(error)}`,
161
+ { cause: error },
162
+ );
163
+ }
164
+ }
165
+
166
+ nowMs(): number {
167
+ return this.now();
168
+ }
169
+ }
package/src/index.ts ADDED
@@ -0,0 +1,31 @@
1
+ export { createOpenCodeAdapter, OpenCodeAdapter } from "./adapter";
2
+ export {
3
+ OpenCodeAmbiguousAdmissionError,
4
+ OpenCodeConfigError,
5
+ OpenCodeError,
6
+ OpenCodeHttpError,
7
+ OpenCodeRateLimitError,
8
+ OpenCodeTimeoutError,
9
+ OpenCodeTransportError,
10
+ } from "./errors";
11
+ export { SseParser, type SseMessage } from "./sse";
12
+ export type {
13
+ AgentSpec,
14
+ AuthReference,
15
+ AuthReferenceObject,
16
+ CancelRequest,
17
+ ModelRef,
18
+ OpenCodeAdapterOptions,
19
+ OpenCodeProfileSettings,
20
+ OpenCodeTimeouts,
21
+ Profile,
22
+ ProviderAdapter,
23
+ ProviderEvent,
24
+ RateLimitInfo,
25
+ SendRequest,
26
+ SessionConfiguration,
27
+ SessionPermission,
28
+ TurnRequest,
29
+ TurnResult,
30
+ TurnStatus,
31
+ } from "./types";