@nones/agentflow-opencode 0.1.0 → 0.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentFlow contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,82 @@
1
1
  # `@nones/agentflow-opencode`
2
2
 
3
- Local OpenCode V2 HTTP provider adapter for AgentFlow. It is deliberately
4
- local-only and has no runtime dependencies.
3
+ Local OpenCode V2 HTTP provider adapter for AgentFlow. It connects to a loopback
4
+ OpenCode service, opens native sessions, submits turns and maps completion,
5
+ rate-limit and interruption signals into AgentFlow contracts.
5
6
 
6
- ## Usage
7
+ The adapter uses the shared contracts from `@nones/agentflow-core` through
8
+ type-only imports, so importing it never loads core or its
9
+ server.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ bun add @nones/agentflow-opencode
15
+ ```
16
+
17
+ Bun 1.4.5 or newer is required.
18
+
19
+ ## Direct use
7
20
 
8
21
  ```ts
9
22
  import { createOpenCodeAdapter } from "@nones/agentflow-opencode";
10
23
 
11
24
  const adapter = createOpenCodeAdapter({
12
- resolveCredential: async (ref) => {
13
- // Trusted host code resolves a credential reference. The adapter never
14
- // reads token files or environment variables itself.
15
- return await myCredentialSource(ref);
25
+ resolveCredential: (ref) => {
26
+ // Trusted host code resolves the reference. The adapter never reads token
27
+ // files, credential stores or environment variables on its own.
28
+ if (ref === "env:OPENCODE_TOKEN") return process.env.OPENCODE_TOKEN;
29
+ return undefined;
16
30
  },
17
31
  });
18
32
 
19
- const sessionId = await adapter.open(agent, profile, {
20
- // Passed only by trusted opt-in module composition.
21
- instructions: "Session-only module instructions.",
22
- permissions: [{ action: "shell", resource: "bd *", effect: "deny" }],
23
- });
33
+ const profile = {
34
+ id: "local",
35
+ adapter: "opencode",
36
+ model: "provider/model",
37
+ settings: {
38
+ endpoint: "http://127.0.0.1:4096",
39
+ auth: { type: "bearer", ref: "env:OPENCODE_TOKEN" },
40
+ },
41
+ };
42
+
43
+ const agent = {
44
+ id: "reviewer",
45
+ prompt: "Review the current diff.",
46
+ cwd: process.cwd(),
47
+ };
48
+
49
+ const sessionId = await adapter.open(agent, profile);
50
+
24
51
  const result = await adapter.turn({
25
52
  sessionId,
26
- turnId,
53
+ turnId: crypto.randomUUID(),
27
54
  agent,
28
55
  profile,
29
- prompt: "Do the work",
30
- onReceipt: (id) => saveReceipt(id),
56
+ prompt: agent.prompt,
57
+ onReceipt: (id) => {
58
+ // Persist the receipt so an ambiguous transport can be reconciled later.
59
+ console.error(`receipt: ${id}`);
60
+ },
31
61
  });
62
+
63
+ console.log(result.status);
32
64
  ```
33
65
 
66
+ With `@nones/agentflow-core`, pass the adapter in `serve({ adapters })`. With
67
+ the CLI package, `agentflow serve` composes it automatically for profiles whose
68
+ `adapter` is `"opencode"`. See
69
+ [`examples/server.ts`](https://github.com/nones-tools/agentflow/blob/main/examples/server.ts).
70
+
34
71
  ## Profile settings
35
72
 
36
73
  ```ts
37
74
  {
38
75
  endpoint: "http://127.0.0.1:4096", // or endpointName + resolveEndpoint
39
- auth: { type: "bearer", ref: "opencode-local" },
40
- model: "openai/gpt-4.1", // profile.model also works
76
+ auth: { type: "bearer", ref: "env:OPENCODE_TOKEN" },
77
+ model: "provider/model", // profile.model also works
41
78
  directory: "/path/to/worktree", // or settings.cwd
42
- turnDelivery: "queue", // or "steer"
79
+ turnDelivery: "queue", // or "steer"
43
80
  timeouts: {
44
81
  requestMs: 15_000,
45
82
  sessionReadyMs: 5_000,
@@ -51,23 +88,52 @@ const result = await adapter.turn({
51
88
  }
52
89
  ```
53
90
 
54
- `directory` / `cwd` is used for profile-level operations such as `doctor`,
55
- where it is sent as the `location[directory]` query. `createOpenCodeAdapter`
56
- may also receive an explicit `defaultCwd` fallback; the adapter never invents a
57
- cwd.
91
+ `directory` / `cwd` is used for profile-level operations such as `doctor`, where
92
+ it is sent as the `location[directory]` query. `createOpenCodeAdapter` may also
93
+ receive an explicit `defaultCwd` fallback; the adapter never invents a cwd.
58
94
 
59
- Endpoints must be loopback (`localhost`, `127.0.0.0/8`, or `::1`) unless
60
- `allowNonLoopback` is explicitly set on the adapter. Port discovery is not
61
- automatic; a named endpoint must be registered deliberately.
95
+ Endpoints must be loopback (`localhost`, `127.0.0.0/8` or `::1`) unless
96
+ `allowNonLoopback: true` is explicitly set on the adapter. Port discovery is not
97
+ automatic; a named endpoint must be registered deliberately through
98
+ `endpoints` or `resolveEndpoint`.
62
99
 
63
100
  The adapter requests a concrete `provider/model` when creating a session and
64
101
  polls `GET /api/session/{id}` until the native session exposes that model.
65
102
 
103
+ ## Authentication references
104
+
105
+ Authentication is configured as a reference in local profile settings. The
106
+ adapter passes the reference to your `resolveCredential` callback and never
107
+ reads credentials itself. AgentFlow's CLI accepts only environment references;
108
+ trusted host code may resolve them from whatever local source it already owns.
109
+
110
+ Bearer:
111
+
112
+ ```ts
113
+ auth: { type: "bearer", ref: "env:OPENCODE_TOKEN" }
114
+ ```
115
+
116
+ Custom header:
117
+
118
+ ```ts
119
+ auth: {
120
+ type: "header",
121
+ name: "Authorization",
122
+ ref: "env:OPENCODE_AUTHORIZATION",
123
+ }
124
+ ```
125
+
126
+ A bare string is treated as a bearer reference. The CLI resolves only explicit
127
+ `env:NAME`, `$NAME` or bare environment-variable references and never prints or
128
+ inventories the value. Credential files and provider auth stores are never read
129
+ by either package.
130
+
66
131
  ## Native endpoints used
67
132
 
68
133
  - `POST /api/session`
69
134
  - `GET /api/session/{sessionID}`
70
- - `PUT /api/experimental/session/{sessionID}/instructions/entries/agentflow_modules` (only when session instructions are supplied)
135
+ - `PUT /api/experimental/session/{sessionID}/instructions/entries/agentflow_modules`
136
+ (only when session instructions are supplied)
71
137
  - `POST /api/session/{sessionID}/prompt`
72
138
  - `POST /api/experimental/session/{sessionID}/wait` (completion hint)
73
139
  - `GET /api/session/{sessionID}/message`
@@ -80,36 +146,50 @@ Both bare responses and `{ data: ... }` wrappers are accepted.
80
146
  ## Admission and observation semantics
81
147
 
82
148
  - An explicit HTTP 429 before admission produces `status: "rate_limited"` with
83
- `safeToRetry: true`, the classified reason, and `Retry-After` when present.
84
- - A transport failure after a prompt submission is treated as ambiguous and
85
- maps to `status: "interrupted"`. The adapter never resubmits automatically.
149
+ `safeToRetry: true`, the classified reason and `Retry-After` when present.
150
+ - A transport failure after prompt submission is ambiguous and maps to
151
+ `status: "interrupted"`. The adapter never resubmits automatically.
86
152
  - Receipts scope observation. Assistant messages are grouped only when they can
87
- be attributed to the current receipt or turn; baseline message ids and event
88
- timestamps prevent older terminal events from completing a new turn. A
89
- completed intermediate step whose finish reason is tool-calls/tool-use is not
90
- terminal; the turn continues until an explicit session idle/error or
153
+ be attributed to the current receipt or turn. Baseline message IDs and event
154
+ timestamps prevent older terminal events from completing a new turn.
155
+ - A completed intermediate step whose finish reason is tool calls is not
156
+ terminal. The turn continues until an explicit session idle/error or
91
157
  `session.execution.*` completion.
92
158
  - A confirmed native `retry.scheduled` event with an HTTP 429 signal is emitted
93
159
  to `onEvent` as `{ type: "provider.rate_limit", data: { reason, retryAfterMs } }`.
94
160
  It is an observation only and never submits a duplicate turn.
95
- - SSE and experimental-wait cancellation are awaited at turn close. Reader
96
- cancellation and observer tasks always carry rejection handlers, so an open
97
- stream cannot surface an unhandled `AbortError`.
161
+ - SSE and experimental-wait cancellation are awaited at turn close. Reader and
162
+ observer tasks carry rejection handlers, so an open stream cannot surface an
163
+ unhandled `AbortError`.
98
164
  - `reconcile` requires a receipt and returns a result only for a terminal
99
165
  assistant message attributed to that receipt. Otherwise it returns
100
166
  `undefined` rather than guessing.
101
167
  - `doctor` checks endpoint reachability and, when `/api/model` is available,
102
168
  whether the configured model is listed. HTTP 401/403 is reported with
103
- `ok: false`. An empty catalogue, an unavailable catalogue, or an unknown
104
- catalogue shape is never treated as model verification.
169
+ `ok: false`. An empty, unavailable or unknown catalogue is never treated as
170
+ successful model verification.
105
171
 
106
172
  ## Tests
107
173
 
174
+ From a repository checkout:
175
+
108
176
  ```sh
109
177
  bun test providers/opencode
110
178
  ```
111
179
 
112
180
  Tests use an injected fetch and synthetic fixtures only. They do not contact a
113
- server, read credentials, inspect environment variables, or touch token files.
181
+ server, read credentials, inspect environment variables or touch token files.
114
182
  Auth coverage uses `resolveCredential`; the adapter has no literal-token or
115
183
  environment-variable default.
184
+
185
+ ## Documentation
186
+
187
+ - [Core contracts](https://github.com/nones-tools/agentflow/blob/main/docs/contracts.md)
188
+ - [Server bootstrap example](https://github.com/nones-tools/agentflow/blob/main/examples/server.ts)
189
+ - [CLI package](https://github.com/nones-tools/agentflow/tree/main/apps/cli)
190
+ - [Repository README](https://github.com/nones-tools/agentflow/blob/main/README.md)
191
+ - [Issues](https://github.com/nones-tools/agentflow/issues)
192
+
193
+ ## License
194
+
195
+ MIT. See [LICENSE](https://github.com/nones-tools/agentflow/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nones/agentflow-opencode",
3
- "version": "0.1.0",
3
+ "version": "0.6.0",
4
4
  "description": "Local OpenCode V2 HTTP provider adapter for AgentFlow",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -34,5 +34,12 @@
34
34
  "scripts": {
35
35
  "build": "bun build ./src/index.ts --target=bun --outdir=.tmp/build --packages external",
36
36
  "test": "bun test"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/nones-tools/agentflow/issues"
40
+ },
41
+ "license": "MIT",
42
+ "dependencies": {
43
+ "@nones/agentflow-core": "0.6.0"
37
44
  }
38
45
  }
package/src/adapter.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  OpenCodeHttpError,
14
14
  OpenCodeRateLimitError,
15
15
  OpenCodeTimeoutError,
16
+ OpenCodeTransportError,
16
17
  } from "./errors";
17
18
  import { HttpClient, combineSignals, type HttpResult } from "./http";
18
19
  import {
@@ -21,6 +22,7 @@ import {
21
22
  classifyRateLimit,
22
23
  combineAssistantText,
23
24
  errorMessage,
25
+ extractActiveCatalogue,
24
26
  extractMessages,
25
27
  extractModelListing,
26
28
  extractSession,
@@ -46,8 +48,15 @@ import {
46
48
  type NormalizedEvent,
47
49
  type TerminalInfo,
48
50
  } from "./normalize";
51
+ import { bindHistoryCapability } from "./provider-history";
49
52
  import { SseParser, type SseMessage } from "./sse";
53
+ import {
54
+ parseTranscriptPage,
55
+ type TranscriptPage,
56
+ type TranscriptPageRequest,
57
+ } from "./transcript";
50
58
  import type {
59
+ ActiveModel,
51
60
  AgentSpec,
52
61
  CancelRequest,
53
62
  ModelRef,
@@ -526,14 +535,11 @@ export class OpenCodeAdapter implements ProviderAdapter {
526
535
  base.configuredModel = modelToString(configuredModel);
527
536
  }
528
537
 
529
- const params = new URLSearchParams();
530
- if (directory) params.set("location[directory]", directory);
531
- const query = params.toString();
532
538
  let response: HttpResult;
533
539
  try {
534
540
  response = await this.request(connection, {
535
541
  method: "GET",
536
- path: `/api/model${query ? `?${query}` : ""}`,
542
+ path: this.modelCataloguePath(directory),
537
543
  });
538
544
  } catch (error) {
539
545
  base.limitations.push(`Endpoint unreachable: ${errorMessage(error)}`);
@@ -610,6 +616,110 @@ export class OpenCodeAdapter implements ProviderAdapter {
610
616
  return base;
611
617
  }
612
618
 
619
+ /**
620
+ * List the models the connected local endpoint currently exposes.
621
+ *
622
+ * Resolution reuses the same authenticated connection as the rest of the
623
+ * adapter, so the catalogue reflects only providers this endpoint has
624
+ * configured or authenticated. Providers explicitly advertised as
625
+ * unconnected or as public inventory are excluded and never returned.
626
+ *
627
+ * Failure reporting is deliberate: an unreachable endpoint, an HTTP rejection
628
+ * (including 401/403) or an unrecognised catalogue throws. A verified,
629
+ * authenticated catalogue with no active models resolves to an empty array.
630
+ * This lets callers tell a concrete error from a true empty catalogue.
631
+ */
632
+ async listModels(profile: Profile): Promise<readonly ActiveModel[]> {
633
+ const connection = await resolveConnection(profile, this.options);
634
+ const directory = resolveDirectory(profile, this.options);
635
+ let response: HttpResult;
636
+ try {
637
+ response = await this.request(connection, {
638
+ method: "GET",
639
+ path: this.modelCataloguePath(directory),
640
+ });
641
+ } catch (error) {
642
+ throw new OpenCodeTransportError(
643
+ `OpenCode model catalogue is unreachable: ${errorMessage(error)}`,
644
+ { cause: error },
645
+ );
646
+ }
647
+
648
+ if (response.status === 401 || response.status === 403) {
649
+ throw new OpenCodeHttpError(
650
+ `OpenCode rejected authentication for the model catalogue with HTTP ${response.status}; no active models can be listed.`,
651
+ response.status,
652
+ response.body,
653
+ );
654
+ }
655
+ if (!response.ok) {
656
+ throw new OpenCodeHttpError(
657
+ this.httpMessage(response, "GET /api/model"),
658
+ response.status,
659
+ response.body,
660
+ );
661
+ }
662
+
663
+ const catalogue = extractActiveCatalogue(response.body);
664
+ if (catalogue.shape !== "known") {
665
+ throw new OpenCodeConfigError(
666
+ "The /api/model response shape was not recognised; active model listing requires an explicit catalogue.",
667
+ );
668
+ }
669
+
670
+ const defaultModel = catalogue.defaultModel;
671
+ const models: ActiveModel[] = [];
672
+ for (const provider of catalogue.providers) {
673
+ for (const option of provider.models) {
674
+ const isDefault = option.default === true || option.id === defaultModel;
675
+ models.push({
676
+ id: option.id,
677
+ ...(option.label ? { label: option.label } : {}),
678
+ provider: provider.id,
679
+ ...(option.description ? { description: option.description } : {}),
680
+ ...(isDefault ? { default: true } : {}),
681
+ ...(option.reasoningEfforts
682
+ ? { reasoningEfforts: option.reasoningEfforts }
683
+ : {}),
684
+ });
685
+ }
686
+ }
687
+ return models;
688
+ }
689
+
690
+ createHistory(profile: Profile) {
691
+ return bindHistoryCapability(this, profile, { options: this.options });
692
+ }
693
+
694
+ /**
695
+ * Optional read-only history slice. It uses only the already-supported
696
+ * `GET /api/session/{id}/message` contract and never submits a prompt.
697
+ * Pagination metadata is reported when the endpoint returns it; otherwise the
698
+ * page status says so and callers must not follow a cursor.
699
+ */
700
+ async inspectTranscript(
701
+ profile: Profile,
702
+ sessionId: string,
703
+ request: TranscriptPageRequest & { signal?: AbortSignal } = {},
704
+ ): Promise<TranscriptPage> {
705
+ const connection = await resolveConnection(profile, this.options);
706
+ const params = new URLSearchParams();
707
+ if (request.cursor !== undefined) params.set("cursor", request.cursor);
708
+ if (request.limit !== undefined)
709
+ params.set("limit", String(Math.floor(request.limit)));
710
+ const query = params.toString();
711
+ const response = await this.request(connection, {
712
+ method: "GET",
713
+ path: `/api/session/${encodeURIComponent(sessionId)}/message${query ? `?${query}` : ""}`,
714
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
715
+ });
716
+ const capturedAt = this.now();
717
+ if (!response.ok) {
718
+ throw this.httpError(response, `GET message ${sessionId}`, false);
719
+ }
720
+ return parseTranscriptPage(response.body, request, capturedAt);
721
+ }
722
+
613
723
  private async awaitConcreteModel(
614
724
  connection: ResolvedConnection,
615
725
  sessionId: string,
@@ -901,6 +1011,14 @@ export class OpenCodeAdapter implements ProviderAdapter {
901
1011
  return this.http.request(connection, options);
902
1012
  }
903
1013
 
1014
+ /** The shared `/api/model` path, with the optional location query. */
1015
+ private modelCataloguePath(directory: string | undefined): string {
1016
+ const params = new URLSearchParams();
1017
+ if (directory) params.set("location[directory]", directory);
1018
+ const query = params.toString();
1019
+ return `/api/model${query ? `?${query}` : ""}`;
1020
+ }
1021
+
904
1022
  private extractReceipt(body: unknown): string | undefined {
905
1023
  const value = unwrapData(body);
906
1024
  if (isRecord(value)) {
package/src/index.ts CHANGED
@@ -1,4 +1,21 @@
1
1
  export { createOpenCodeAdapter, OpenCodeAdapter } from "./adapter";
2
+ export {
3
+ bindHistoryCapability,
4
+ createProviderHistoryCapability,
5
+ historyDisabled,
6
+ historyIntakeEnabled,
7
+ historyProfile,
8
+ toHistoryPage,
9
+ toHistoryRecord,
10
+ } from "./provider-history";
11
+ export type {
12
+ ProfileHistoryBindingOptions,
13
+ ProviderHistoryCapability,
14
+ ProviderHistoryPage,
15
+ ProviderHistoryPart,
16
+ ProviderHistoryRecord,
17
+ ProviderHistorySource,
18
+ } from "./provider-history";
2
19
  export {
3
20
  OpenCodeAmbiguousAdmissionError,
4
21
  OpenCodeConfigError,
@@ -10,6 +27,7 @@ export {
10
27
  } from "./errors";
11
28
  export { SseParser, type SseMessage } from "./sse";
12
29
  export type {
30
+ ActiveModel,
13
31
  AgentSpec,
14
32
  AuthReference,
15
33
  AuthReferenceObject,