@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/sse.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Minimal server-sent-events parser.
3
+ *
4
+ * It accepts split UTF-8 chunks, LF/CRLF/CR endings, comments, multi-line
5
+ * `data:` fields, and the `event`, `id`, and `retry` fields. No external
6
+ * dependency is used.
7
+ */
8
+
9
+ export interface SseMessage {
10
+ event?: string;
11
+ data: string;
12
+ id?: string;
13
+ retry?: number;
14
+ }
15
+
16
+ export class SseParser {
17
+ private buffer = "";
18
+ private pendingCR = false;
19
+ private event: string | undefined;
20
+ private id: string | undefined;
21
+ private retry: number | undefined;
22
+ private data: string[] = [];
23
+
24
+ push(chunk: string): SseMessage[] {
25
+ let text = chunk;
26
+ if (this.pendingCR) {
27
+ if (text.startsWith("\n")) text = text.slice(1);
28
+ this.pendingCR = false;
29
+ }
30
+ this.pendingCR = text.endsWith("\r");
31
+ this.buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
32
+
33
+ const messages: SseMessage[] = [];
34
+ let newline = this.buffer.indexOf("\n");
35
+ while (newline >= 0) {
36
+ const line = this.buffer.slice(0, newline);
37
+ this.buffer = this.buffer.slice(newline + 1);
38
+ this.consumeLine(line, messages);
39
+ newline = this.buffer.indexOf("\n");
40
+ }
41
+ return messages;
42
+ }
43
+
44
+ flush(): SseMessage[] {
45
+ const messages: SseMessage[] = [];
46
+ if (this.buffer.length > 0) {
47
+ const line = this.pendingCR ? this.buffer.slice(0, -1) : this.buffer;
48
+ this.buffer = "";
49
+ this.pendingCR = false;
50
+ this.consumeLine(line, messages);
51
+ }
52
+ this.dispatch(messages);
53
+ return messages;
54
+ }
55
+
56
+ private consumeLine(line: string, messages: SseMessage[]): void {
57
+ if (line.length === 0) {
58
+ this.dispatch(messages);
59
+ return;
60
+ }
61
+ if (line.startsWith(":")) return;
62
+
63
+ const colon = line.indexOf(":");
64
+ const field = colon >= 0 ? line.slice(0, colon) : line;
65
+ let value = colon >= 0 ? line.slice(colon + 1) : "";
66
+ if (value.startsWith(" ")) value = value.slice(1);
67
+
68
+ switch (field) {
69
+ case "event":
70
+ this.event = value;
71
+ break;
72
+ case "data":
73
+ this.data.push(value);
74
+ break;
75
+ case "id":
76
+ this.id = value;
77
+ break;
78
+ case "retry": {
79
+ const parsed = Number(value);
80
+ if (Number.isFinite(parsed)) this.retry = parsed;
81
+ break;
82
+ }
83
+ default:
84
+ break;
85
+ }
86
+ }
87
+
88
+ private dispatch(messages: SseMessage[]): void {
89
+ if (this.data.length === 0 && this.event === undefined) {
90
+ this.id = undefined;
91
+ this.retry = undefined;
92
+ return;
93
+ }
94
+ messages.push({
95
+ event: this.event,
96
+ data: this.data.join("\n"),
97
+ id: this.id,
98
+ retry: this.retry,
99
+ });
100
+ this.event = undefined;
101
+ this.id = undefined;
102
+ this.retry = undefined;
103
+ this.data = [];
104
+ }
105
+ }
package/src/types.ts ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Structural copies of the shared AgentFlow contracts.
3
+ *
4
+ * The provider deliberately keeps its own declarations so that importing the
5
+ * adapter never loads `@nones/agentflow-core` (which owns the server). These shapes
6
+ * are assignable to the contract shapes in `docs/contracts.md`.
7
+ */
8
+
9
+ export interface Profile {
10
+ id: string;
11
+ adapter: string;
12
+ settings: Record<string, unknown>;
13
+ model?: string;
14
+ quotaGroup?: string;
15
+ maxConcurrent?: number;
16
+ initialConcurrent?: number;
17
+ startsPerSecond?: number;
18
+ }
19
+
20
+ export interface AgentSpec {
21
+ id: string;
22
+ prompt: string;
23
+ cwd: string;
24
+ profile?: string;
25
+ model?: string;
26
+ settings?: Record<string, unknown>;
27
+ strategy?: string;
28
+ strategyInput?: unknown;
29
+ }
30
+
31
+ export type TurnStatus =
32
+ "succeeded" | "failed" | "interrupted" | "rate_limited";
33
+
34
+ export interface RateLimitInfo {
35
+ reason: "concurrency" | "rate" | "quota" | "unknown";
36
+ retryAfterMs?: number;
37
+ safeToRetry: boolean;
38
+ }
39
+
40
+ export interface TurnResult {
41
+ status: TurnStatus;
42
+ text?: string;
43
+ error?: string;
44
+ rateLimit?: RateLimitInfo;
45
+ artifacts?: Record<string, unknown>;
46
+ }
47
+
48
+ export interface ProviderEvent {
49
+ type: string;
50
+ data?: unknown;
51
+ }
52
+
53
+ export interface TurnRequest {
54
+ sessionId: string;
55
+ turnId: string;
56
+ agent: AgentSpec;
57
+ profile: Profile;
58
+ prompt: string;
59
+ signal?: AbortSignal;
60
+ /** Receipt from an earlier, possibly ambiguous, submission. */
61
+ receipt?: string;
62
+ onReceipt?: (id: string) => void;
63
+ onEvent?: (event: ProviderEvent) => void;
64
+ }
65
+
66
+ export interface SendRequest {
67
+ sessionId: string;
68
+ agent: AgentSpec;
69
+ profile: Profile;
70
+ prompt: string;
71
+ delivery: "steer" | "queue";
72
+ messageId: string;
73
+ }
74
+
75
+ export interface CancelRequest {
76
+ sessionId: string;
77
+ agent: AgentSpec;
78
+ profile: Profile;
79
+ }
80
+
81
+ export interface ProviderAdapter {
82
+ id: string;
83
+ open(
84
+ agent: AgentSpec,
85
+ profile: Profile,
86
+ session?: SessionConfiguration,
87
+ ): Promise<string>;
88
+ turn(request: TurnRequest): Promise<TurnResult>;
89
+ reconcile?(request: TurnRequest): Promise<TurnResult | undefined>;
90
+ send(request: SendRequest): Promise<{ receipt?: string }>;
91
+ cancel(request: CancelRequest): Promise<void>;
92
+ doctor(profile: Profile): Promise<unknown>;
93
+ }
94
+
95
+ export interface SessionPermission {
96
+ action: string;
97
+ resource: string;
98
+ effect: "allow" | "deny";
99
+ }
100
+
101
+ export interface SessionConfiguration {
102
+ instructions?: string;
103
+ permissions?: readonly SessionPermission[];
104
+ }
105
+
106
+ export interface ModelRef {
107
+ providerID: string;
108
+ id: string;
109
+ }
110
+
111
+ /**
112
+ * Authentication is always supplied as a reference. The HTTP client asks the
113
+ * trusted host application to resolve the reference; it never reads token
114
+ * files, environment variables, or credential stores itself.
115
+ */
116
+ export interface AuthReferenceObject {
117
+ type?: "bearer" | "header";
118
+ /** Header name when `type` is `header`. */
119
+ name?: string;
120
+ /** Alias for the header name. */
121
+ header?: string;
122
+ /** Literal value supplied by the trusted host, not read from a store. */
123
+ value?: string;
124
+ /** Alias for a literal value. */
125
+ token?: string;
126
+ /** Credential reference resolved by `OpenCodeAdapterOptions.resolveCredential`. */
127
+ ref?: string;
128
+ /** Alias for a credential reference. */
129
+ tokenRef?: string;
130
+ }
131
+
132
+ /** A bare string is treated as a bearer credential reference. */
133
+ export type AuthReference = string | AuthReferenceObject;
134
+
135
+ export interface OpenCodeTimeouts {
136
+ /** Individual JSON request deadline. */
137
+ requestMs?: number;
138
+ /** How long to poll for the native session's concrete model. */
139
+ sessionReadyMs?: number;
140
+ /** Maximum observed turn duration. */
141
+ turnMs?: number;
142
+ /** Deadline for one `session/wait` attempt. */
143
+ waitMs?: number;
144
+ }
145
+
146
+ export interface OpenCodeProfileSettings {
147
+ /** Direct loopback endpoint, for example `http://127.0.0.1:4096`. */
148
+ endpoint?: string;
149
+ /** Named endpoint resolved by `OpenCodeAdapterOptions.resolveEndpoint`. */
150
+ endpointName?: string;
151
+ /** Authentication reference, resolved by the host application. */
152
+ auth?: AuthReference;
153
+ /** Default model for the profile, either `provider/id` or an object. */
154
+ model?: string | ModelRef;
155
+ /** Native location directory (passed as `location[directory]` when relevant). */
156
+ directory?: string;
157
+ /** Alias for `directory`. */
158
+ cwd?: string;
159
+ /** Delivery mode used by `turn`; defaults to `queue`. */
160
+ turnDelivery?: "queue" | "steer";
161
+ timeouts?: OpenCodeTimeouts;
162
+ /** Non-secret headers merged into every request. */
163
+ headers?: Record<string, string>;
164
+ /** Disable SSE observation (message/wait polling is still used). */
165
+ eventStream?: boolean;
166
+ }
167
+
168
+ export interface OpenCodeAdapterOptions {
169
+ /** Adapter id exposed on `ProviderAdapter.id`. */
170
+ id?: string;
171
+ /** Injectable fetch, typed so tests never touch the network. */
172
+ fetch?: (input: string, init: RequestInit) => Promise<Response>;
173
+ /** Injectable clock, in milliseconds. */
174
+ now?: () => number;
175
+ /** Injectable delay used while polling. */
176
+ sleep?: (ms: number) => Promise<void>;
177
+ /** Resolve `settings.endpointName` to a deliberate local endpoint. */
178
+ resolveEndpoint?: (name: string) => string | undefined;
179
+ /** Optional static named endpoints. */
180
+ endpoints?: Record<string, string>;
181
+ /**
182
+ * Resolve an authentication reference. The function receives only the
183
+ * reference string; credential contents are never inspected by the adapter.
184
+ */
185
+ resolveCredential?: (
186
+ ref: string,
187
+ profile: Profile,
188
+ ) => string | undefined | Promise<string | undefined>;
189
+ /** Non-secret headers merged into every request. */
190
+ headers?: Record<string, string>;
191
+ /** Allow non-loopback endpoints. Off by default; local-only is the norm. */
192
+ allowNonLoopback?: boolean;
193
+ /** Poll interval for session readiness and turn observation. */
194
+ pollIntervalMs?: number;
195
+ /** Default profile timeouts. */
196
+ timeouts?: OpenCodeTimeouts;
197
+ /** Use the experimental wait endpoint as a completion hint. */
198
+ useWaitEndpoint?: boolean;
199
+ /**
200
+ * Fallback execution-context directory for profile-level operations such as
201
+ * `doctor`. Explicit profile `settings.directory` / `settings.cwd` wins.
202
+ */
203
+ defaultCwd?: string;
204
+ }