@opencode/ai 0.0.0-dev-19996 → 0.0.0-dev-19998
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/README.md +103 -54
- package/dist/generation.d.ts +69 -0
- package/dist/generation.js +84 -0
- package/dist/image-client.d.ts +6 -4
- package/dist/image-client.js +11 -11
- package/dist/image.d.ts +1040 -62
- package/dist/image.js +80 -52
- package/dist/index.d.ts +5 -2
- package/dist/index.js +3 -1
- package/dist/llm.d.ts +9 -1
- package/dist/media.d.ts +212 -0
- package/dist/media.js +228 -0
- package/dist/promise.d.ts +554 -0
- package/dist/promise.js +44 -0
- package/dist/protocols/anthropic-messages.js +7 -17
- package/dist/protocols/bedrock-converse.d.ts +4 -4
- package/dist/protocols/bedrock-converse.js +1 -6
- package/dist/protocols/gemini.d.ts +21 -0
- package/dist/protocols/gemini.js +42 -6
- package/dist/protocols/google-images.d.ts +9 -21
- package/dist/protocols/google-images.js +169 -132
- package/dist/protocols/meta-images.d.ts +7 -12
- package/dist/protocols/meta-images.js +92 -66
- package/dist/protocols/mistral-chat.js +7 -6
- package/dist/protocols/open-responses.d.ts +11 -3
- package/dist/protocols/open-responses.js +23 -12
- package/dist/protocols/openai-chat.js +4 -7
- package/dist/protocols/openai-images.d.ts +9 -20
- package/dist/protocols/openai-images.js +112 -142
- package/dist/protocols/shared.d.ts +12 -12
- package/dist/protocols/shared.js +23 -30
- package/dist/protocols/utils/bedrock-media.d.ts +2 -3
- package/dist/protocols/utils/bedrock-media.js +4 -4
- package/dist/protocols/utils/media-input.d.ts +10 -0
- package/dist/protocols/utils/media-input.js +17 -0
- package/dist/protocols/utils/responses-compaction.js +6 -5
- package/dist/protocols/utils/tool-stream.d.ts +27 -3
- package/dist/protocols/xai-images.d.ts +9 -15
- package/dist/protocols/xai-images.js +85 -83
- package/dist/protocols/zai-images.d.ts +9 -13
- package/dist/protocols/zai-images.js +59 -57
- package/dist/providers/amazon-bedrock.d.ts +2 -2
- package/dist/providers/cerebras.js +6 -1
- package/dist/providers/deepinfra.js +6 -1
- package/dist/providers/google-vertex.d.ts +7 -0
- package/dist/providers/google.d.ts +7 -0
- package/dist/route/client.d.ts +9 -1
- package/dist/route/endpoint.d.ts +10 -10
- package/dist/route/executor-service.d.ts +12 -0
- package/dist/route/executor-service.js +3 -0
- package/dist/route/executor.d.ts +4 -9
- package/dist/route/executor.js +3 -3
- package/dist/route/index.d.ts +2 -0
- package/dist/route/index.js +2 -0
- package/dist/route/media-protocol.d.ts +45 -0
- package/dist/route/media-protocol.js +40 -0
- package/dist/route/media.d.ts +46 -0
- package/dist/route/media.js +64 -0
- package/dist/schema/errors.d.ts +13 -3
- package/dist/schema/errors.js +7 -0
- package/dist/schema/events.d.ts +563 -40
- package/dist/schema/events.js +35 -2
- package/dist/schema/messages.d.ts +98 -8
- package/dist/schema/messages.js +8 -6
- package/dist/schema/options.d.ts +2 -0
- package/dist/schema/options.js +3 -0
- package/dist/testing.d.ts +72 -8
- package/dist/utils/media-type.d.ts +6 -0
- package/dist/utils/media-type.js +49 -0
- package/dist/utils/sanitize.js +3 -1
- package/package.json +7 -3
- package/dist/protocols/utils/image-input.d.ts +0 -21
- package/dist/protocols/utils/image-input.js +0 -20
package/README.md
CHANGED
|
@@ -8,10 +8,10 @@ import { LLM, LLMClient } from "@opencode/ai"
|
|
|
8
8
|
import { RequestExecutor } from "@opencode/ai/route"
|
|
9
9
|
import { OpenAI } from "@opencode/ai/providers"
|
|
10
10
|
|
|
11
|
-
const
|
|
11
|
+
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
12
12
|
|
|
13
13
|
const request = LLM.request({
|
|
14
|
-
model,
|
|
14
|
+
model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead
|
|
15
15
|
system: "You are concise.",
|
|
16
16
|
prompt: "Say hello in one short sentence.",
|
|
17
17
|
generation: { maxTokens: 40 },
|
|
@@ -29,6 +29,43 @@ await Effect.runPromise(program.pipe(Effect.provide(llmLayer)))
|
|
|
29
29
|
|
|
30
30
|
Run `LLMClient.stream(request)` instead of `generate` when you want incremental `LLMEvent`s. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses, Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
|
31
31
|
|
|
32
|
+
The same configured facade names image models. `Image.request` resolves the provider's image route from the ref and
|
|
33
|
+
returns `Media.Asset`s with lazily decoded bytes:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { NodeFileSystem } from "@effect/platform-node"
|
|
37
|
+
import { Image, ImageClient, Media } from "@opencode/ai"
|
|
38
|
+
|
|
39
|
+
const image = Effect.gen(function* () {
|
|
40
|
+
const response = yield* Image.generate({
|
|
41
|
+
model: openai.image("gpt-image-2"),
|
|
42
|
+
prompt: "A robot tending a rooftop garden",
|
|
43
|
+
size: "1024x1024",
|
|
44
|
+
providerOptions: { quality: "high" }, // typed per image model
|
|
45
|
+
})
|
|
46
|
+
yield* Media.write(response.image, "./garden.png")
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
// `asset.bytes()` / `Media.write` also need the executor, so merge it into the environment instead of hiding it.
|
|
50
|
+
const imageLayer = ImageClient.layer.pipe(Layer.provideMerge(RequestExecutor.fetchLayer))
|
|
51
|
+
|
|
52
|
+
await Effect.runPromise(image.pipe(Effect.provide(imageLayer), Effect.provide(NodeFileSystem.layer)))
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Prefer promises? `@opencode/ai/promise` exposes the same LLM and image APIs over one managed runtime:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { AI } from "@opencode/ai/promise"
|
|
59
|
+
|
|
60
|
+
const ai = AI.make()
|
|
61
|
+
const text = await ai.llm.generate({ model: openai.responses("gpt-4o-mini"), prompt: "Say hello." })
|
|
62
|
+
const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
|
|
63
|
+
for await (const event of ai.llm.stream({ model: openai.responses("gpt-4o-mini"), prompt: "Stream hello." })) {
|
|
64
|
+
// LLMEvent
|
|
65
|
+
}
|
|
66
|
+
await ai.dispose()
|
|
67
|
+
```
|
|
68
|
+
|
|
32
69
|
## Experimental evaluation
|
|
33
70
|
|
|
34
71
|
Evaluation models compare shared state with typed choice, score, and boolean questions. The API is
|
|
@@ -365,23 +402,25 @@ citations or separate result blocks. Retain `response.message` for either API's
|
|
|
365
402
|
Use `Image.generate` for one-off generation or editing:
|
|
366
403
|
|
|
367
404
|
```ts
|
|
368
|
-
import { Image,
|
|
405
|
+
import { Image, Media } from "@opencode/ai"
|
|
369
406
|
|
|
370
407
|
const generation = Image.generate({
|
|
371
|
-
model: meta
|
|
408
|
+
model: meta("muse-image-1.0"),
|
|
372
409
|
prompt: "A flat black square on a white background.",
|
|
373
|
-
|
|
410
|
+
n: 1,
|
|
411
|
+
providerOptions: { reasoningStrength: "low" },
|
|
374
412
|
})
|
|
375
413
|
|
|
376
414
|
const edit = Image.generate({
|
|
377
|
-
model: meta
|
|
415
|
+
model: meta("muse-image-1.0"),
|
|
378
416
|
prompt: "Make the square purple.",
|
|
379
|
-
images: [
|
|
380
|
-
|
|
417
|
+
images: [Media.bytes(imageBytes, "image/webp")],
|
|
418
|
+
format: "png",
|
|
419
|
+
providerOptions: { reasoningStrength: "low" },
|
|
381
420
|
})
|
|
382
421
|
```
|
|
383
422
|
|
|
384
|
-
The default image format is WEBP; `
|
|
423
|
+
The default image format is WEBP; `format` also accepts PNG/JPEG and `responseFormat: "url"`
|
|
385
424
|
returns a signed URL. `size` is an aspect-ratio hint. For conversational images, select
|
|
386
425
|
`meta.responses("muse-image-1.0")` with `tools: [Meta.imageGeneration({ reasoningStrength: "low" })]`.
|
|
387
426
|
Generated images are provider-executed tool results with file content. Retain `response.message` to
|
|
@@ -392,29 +431,40 @@ Meta Responses is explicitly HTTP/SSE-only and does not use WebSockets, even whe
|
|
|
392
431
|
|
|
393
432
|
## Image generation
|
|
394
433
|
|
|
395
|
-
Use `Image.generate` with an image model for direct asset generation
|
|
434
|
+
Use `Image.generate` with an image model for direct asset generation. `Image.request` mirrors `LLM.request`: the
|
|
435
|
+
model comes from the facade's `.image(...)` selector (mirroring `.responses(...)`), common fields
|
|
436
|
+
(`images`, `mask`, `n`, `size`, `aspectRatio`, `seed`, `format`) lower natively or fail typed, and
|
|
437
|
+
`providerOptions` is inferred from the selected model:
|
|
396
438
|
|
|
397
439
|
```ts
|
|
398
|
-
import { Image,
|
|
440
|
+
import { Image, Media } from "@opencode/ai"
|
|
399
441
|
import { OpenAI } from "@opencode/ai/providers"
|
|
400
442
|
|
|
443
|
+
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
444
|
+
|
|
401
445
|
const program = Effect.gen(function* () {
|
|
402
446
|
const response = yield* Image.generate({
|
|
403
|
-
model:
|
|
447
|
+
model: openai.image("gpt-image-2"),
|
|
404
448
|
prompt: "A robot tending a rooftop garden",
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
449
|
+
n: 2,
|
|
450
|
+
size: "1024x1024",
|
|
451
|
+
format: "webp",
|
|
452
|
+
providerOptions: {
|
|
408
453
|
quality: "high", // inferred from the OpenAI image model
|
|
409
|
-
outputFormat: "webp",
|
|
410
454
|
future_option: true, // unknown native options pass through unchanged
|
|
411
455
|
},
|
|
412
456
|
})
|
|
413
457
|
|
|
414
|
-
return response.images //
|
|
458
|
+
return response.images // Media.Asset[] with owned bytes or a provider URL
|
|
415
459
|
})
|
|
416
460
|
```
|
|
417
461
|
|
|
462
|
+
`Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
|
|
463
|
+
`asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
|
|
464
|
+
`asset.base64()`, and `asset.dataUrl()` decode or download lazily and cache; `asset.materialize()` pulls a `url`
|
|
465
|
+
asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
|
|
466
|
+
`Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
|
|
467
|
+
|
|
418
468
|
Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
|
|
419
469
|
|
|
420
470
|
```ts
|
|
@@ -424,49 +474,45 @@ const response =
|
|
|
424
474
|
model,
|
|
425
475
|
prompt: "Combine these product photos into one studio scene",
|
|
426
476
|
images: [
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
477
|
+
Media.bytes(firstBytes, "image/png"),
|
|
478
|
+
Media.url("https://example.com/second.webp"),
|
|
479
|
+
Media.ref("openai", "file_123"),
|
|
430
480
|
],
|
|
431
|
-
|
|
481
|
+
providerOptions,
|
|
432
482
|
http,
|
|
433
483
|
})
|
|
434
484
|
```
|
|
435
485
|
|
|
436
|
-
`
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
edits and its JSON reference body for URL or file-ID edits.
|
|
441
|
-
|
|
486
|
+
`Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
|
|
487
|
+
only forward refs that belong to their own provider. Raw strings are not accepted as image inputs, avoiding
|
|
488
|
+
ambiguity between base64, URLs, and provider IDs. Empty or omitted `images` uses text-to-image generation; a
|
|
489
|
+
non-empty array selects the provider's edit behavior without enforcing provider image-count limits locally. OpenAI
|
|
490
|
+
uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. The common `mask`
|
|
491
|
+
field selects inpainting; routes that cannot honor it fail with `UnsupportedOperation`:
|
|
442
492
|
|
|
443
493
|
```ts
|
|
444
494
|
yield *
|
|
445
495
|
Image.generate({
|
|
446
|
-
model:
|
|
496
|
+
model: openai.image("gpt-image-2"),
|
|
447
497
|
prompt,
|
|
448
|
-
images: [
|
|
449
|
-
|
|
498
|
+
images: [Media.bytes(sourceBytes, "image/png")],
|
|
499
|
+
mask: Media.bytes(maskBytes, "image/png"),
|
|
450
500
|
})
|
|
451
501
|
```
|
|
452
502
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
public HTTP URLs, and hosted Z.ai image generation does not accept image inputs. These cases fail with
|
|
458
|
-
`InvalidRequest` before network I/O.
|
|
503
|
+
On multipart requests, `http.body` can override option fields but not structural `model`, `prompt`, `image[]`,
|
|
504
|
+
or `mask` fields, and the transport owns the multipart `Content-Type` boundary. For JSON requests, `http.body`
|
|
505
|
+
remains the final raw-native overlay. Gemini does not fetch public HTTP URLs, and hosted Z.ai image generation does
|
|
506
|
+
not accept image inputs. These cases fail with a typed `AIError` before network I/O.
|
|
459
507
|
|
|
460
508
|
Provider-native image options belong to each request. Raw `http.body` fields have final precedence over them:
|
|
461
509
|
|
|
462
510
|
```ts
|
|
463
|
-
const model = OpenAI.configure({ apiKey }).image("gpt-image-2")
|
|
464
|
-
|
|
465
511
|
yield *
|
|
466
512
|
Image.generate({
|
|
467
|
-
model,
|
|
513
|
+
model: openai.image("gpt-image-2"),
|
|
468
514
|
prompt,
|
|
469
|
-
|
|
515
|
+
providerOptions: { quality: "medium" },
|
|
470
516
|
http,
|
|
471
517
|
})
|
|
472
518
|
```
|
|
@@ -476,11 +522,11 @@ xAI image models use the same request API with xAI-native controls:
|
|
|
476
522
|
```ts
|
|
477
523
|
yield *
|
|
478
524
|
Image.generate({
|
|
479
|
-
model: XAI.configure({ apiKey })
|
|
525
|
+
model: XAI.configure({ apiKey })("any-model-id"),
|
|
480
526
|
prompt,
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
527
|
+
n: 2,
|
|
528
|
+
aspectRatio: "16:9",
|
|
529
|
+
providerOptions: {
|
|
484
530
|
resolution: "1k",
|
|
485
531
|
responseFormat: "b64_json",
|
|
486
532
|
future_option: true,
|
|
@@ -496,12 +542,12 @@ import { Google } from "@opencode/ai/providers"
|
|
|
496
542
|
|
|
497
543
|
const googleProgram = Effect.gen(function* () {
|
|
498
544
|
const response = yield* Image.generate({
|
|
499
|
-
model: Google.configure({ apiKey })
|
|
545
|
+
model: Google.configure({ apiKey })("any-model-id"),
|
|
500
546
|
prompt: "A robot tending a rooftop garden",
|
|
501
|
-
|
|
502
|
-
|
|
547
|
+
aspectRatio: "16:9",
|
|
548
|
+
seed: 42,
|
|
549
|
+
providerOptions: {
|
|
503
550
|
imageSize: "2K",
|
|
504
|
-
seed: 42,
|
|
505
551
|
thinkingLevel: "HIGH",
|
|
506
552
|
includeThoughts: true,
|
|
507
553
|
futureOption: true,
|
|
@@ -523,9 +569,9 @@ Z.ai image models infer open Z.ai-native options from the selected model:
|
|
|
523
569
|
```ts
|
|
524
570
|
yield *
|
|
525
571
|
Image.generate({
|
|
526
|
-
model: ZAI.configure({ apiKey })
|
|
572
|
+
model: ZAI.configure({ apiKey })("any-model-id"),
|
|
527
573
|
prompt,
|
|
528
|
-
|
|
574
|
+
providerOptions: {
|
|
529
575
|
quality: "hd",
|
|
530
576
|
userID: "user-123",
|
|
531
577
|
future_option: true,
|
|
@@ -535,8 +581,8 @@ yield *
|
|
|
535
581
|
```
|
|
536
582
|
|
|
537
583
|
Z.ai does not include trustworthy MIME metadata for output URLs, so generated images use
|
|
538
|
-
`application/octet-stream
|
|
539
|
-
remain available.
|
|
584
|
+
`application/octet-stream` until materialized. Output URLs expire after 30 days; call `asset.materialize()` and
|
|
585
|
+
persist the bytes promptly if they must remain available.
|
|
540
586
|
|
|
541
587
|
Conversational image generation remains part of the LLM interaction. OpenAI Responses exposes it through its hosted image tool:
|
|
542
588
|
|
|
@@ -554,7 +600,7 @@ const program = Effect.gen(function* () {
|
|
|
554
600
|
})
|
|
555
601
|
```
|
|
556
602
|
|
|
557
|
-
The hosted result is represented as a provider-executed tool call and tool result
|
|
603
|
+
The hosted result is represented as a provider-executed tool call and tool result, and the generated image is also emitted as a first-class `media` `LLMEvent` (`response.message` then carries a `media` part). Gemini image-capable models emit the same `media` event for inline image output. Retaining `response.message` preserves the generated image for continuation on both routes.
|
|
558
604
|
|
|
559
605
|
## Public API
|
|
560
606
|
|
|
@@ -563,8 +609,11 @@ The hosted result is represented as a provider-executed tool call and tool resul
|
|
|
563
609
|
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
|
|
564
610
|
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
|
565
611
|
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
|
566
|
-
- **`Image.generate
|
|
612
|
+
- **`Image.request` / `Image.generate` / `Image.stream`** — generate images through a provider-neutral image request and response model.
|
|
567
613
|
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
|
|
614
|
+
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
|
|
615
|
+
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
|
|
616
|
+
- **`@opencode/ai/promise`** — `AI.make({ layer? })` and a default `ai` client exposing `llm` and `image` as Promise / `AsyncIterable` APIs.
|
|
568
617
|
|
|
569
618
|
## Testing
|
|
570
619
|
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Duration, Effect, Schedule, Schema, Stream } from "effect";
|
|
2
|
+
import { AIError } from "./schema/errors.js";
|
|
3
|
+
export declare const Status: Schema.Literals<readonly ["queued", "running", "completed", "failed", "cancelled", "expired"]>;
|
|
4
|
+
export type Status = Schema.Schema.Type<typeof Status>;
|
|
5
|
+
/** Provider-neutral view of one generation observation. */
|
|
6
|
+
export interface Snapshot {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly status: Status;
|
|
9
|
+
/** Normalized 0..1 when the provider reports progress. */
|
|
10
|
+
readonly progress?: number;
|
|
11
|
+
readonly position?: number;
|
|
12
|
+
readonly expiresAt?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Route-owned generation operations. `token` is the route's serializable handle (operation name, task id, response URL)
|
|
16
|
+
* so a generation can be resumed from another process; its shape is opaque to `Generation`.
|
|
17
|
+
*/
|
|
18
|
+
export interface Route<Response> {
|
|
19
|
+
readonly status: (token: unknown) => Effect.Effect<Snapshot, AIError>;
|
|
20
|
+
readonly result: (token: unknown) => Effect.Effect<Response, AIError>;
|
|
21
|
+
readonly cancel?: (token: unknown) => Effect.Effect<void, AIError>;
|
|
22
|
+
/** Provider polling hint (e.g. `openai-poll-after-ms`) that overrides the default interval for the next poll. */
|
|
23
|
+
readonly pollHint?: (snapshot: Snapshot) => Duration.Duration | undefined;
|
|
24
|
+
}
|
|
25
|
+
export interface Poll {
|
|
26
|
+
readonly interval?: Duration.Input;
|
|
27
|
+
readonly timeout?: Duration.Input;
|
|
28
|
+
/** Full override of the polling schedule; `interval` and `pollHint` are ignored when supplied. */
|
|
29
|
+
readonly schedule?: Schedule.Schedule<unknown, Snapshot>;
|
|
30
|
+
}
|
|
31
|
+
export declare const DEFAULT_POLL_INTERVAL: Duration.Duration;
|
|
32
|
+
export declare const DEFAULT_POLL_TIMEOUT: Duration.Duration;
|
|
33
|
+
export type Event = {
|
|
34
|
+
readonly type: "generation-queued";
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly position?: number;
|
|
37
|
+
} | {
|
|
38
|
+
readonly type: "generation-progress";
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly progress?: number;
|
|
41
|
+
} | {
|
|
42
|
+
readonly type: "generation-finished";
|
|
43
|
+
readonly id: string;
|
|
44
|
+
readonly status: Status;
|
|
45
|
+
};
|
|
46
|
+
export declare class Generation<Response> {
|
|
47
|
+
readonly route: Route<Response>;
|
|
48
|
+
readonly token: unknown;
|
|
49
|
+
readonly id: string;
|
|
50
|
+
readonly status: Status;
|
|
51
|
+
readonly progress?: number;
|
|
52
|
+
readonly position?: number;
|
|
53
|
+
readonly expiresAt?: number;
|
|
54
|
+
constructor(route: Route<Response>, token: unknown, snapshot: Snapshot);
|
|
55
|
+
get snapshot(): Snapshot;
|
|
56
|
+
get terminal(): boolean;
|
|
57
|
+
refresh(): Effect.Effect<Generation<Response>, AIError>;
|
|
58
|
+
/** Poll until the generation reaches a terminal status, then fetch the result. Fails with a `Timeout` reason on deadline. */
|
|
59
|
+
await(options?: {
|
|
60
|
+
readonly poll?: Poll;
|
|
61
|
+
}): Effect.Effect<Response, AIError>;
|
|
62
|
+
cancel(): Effect.Effect<void, AIError>;
|
|
63
|
+
/** Status observations as a stream, ending after the first terminal observation. */
|
|
64
|
+
events(options?: {
|
|
65
|
+
readonly poll?: Poll;
|
|
66
|
+
}): Stream.Stream<Event, AIError>;
|
|
67
|
+
private poll;
|
|
68
|
+
private schedule;
|
|
69
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { Duration, Effect, Schedule, Schema, Stream } from "effect";
|
|
2
|
+
import { AIError, TimeoutError } from "./schema/errors.js";
|
|
3
|
+
export const Status = Schema.Literals(["queued", "running", "completed", "failed", "cancelled", "expired"]);
|
|
4
|
+
export const DEFAULT_POLL_INTERVAL = Duration.seconds(5);
|
|
5
|
+
export const DEFAULT_POLL_TIMEOUT = Duration.minutes(10);
|
|
6
|
+
const TERMINAL = new Set(["completed", "failed", "cancelled", "expired"]);
|
|
7
|
+
export class Generation {
|
|
8
|
+
route;
|
|
9
|
+
token;
|
|
10
|
+
id;
|
|
11
|
+
status;
|
|
12
|
+
progress;
|
|
13
|
+
position;
|
|
14
|
+
expiresAt;
|
|
15
|
+
constructor(route, token, snapshot) {
|
|
16
|
+
this.route = route;
|
|
17
|
+
this.token = token;
|
|
18
|
+
this.id = snapshot.id;
|
|
19
|
+
this.status = snapshot.status;
|
|
20
|
+
this.progress = snapshot.progress;
|
|
21
|
+
this.position = snapshot.position;
|
|
22
|
+
this.expiresAt = snapshot.expiresAt;
|
|
23
|
+
}
|
|
24
|
+
get snapshot() {
|
|
25
|
+
return {
|
|
26
|
+
id: this.id,
|
|
27
|
+
status: this.status,
|
|
28
|
+
progress: this.progress,
|
|
29
|
+
position: this.position,
|
|
30
|
+
expiresAt: this.expiresAt,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
get terminal() {
|
|
34
|
+
return TERMINAL.has(this.status);
|
|
35
|
+
}
|
|
36
|
+
refresh() {
|
|
37
|
+
return this.route.status(this.token).pipe(Effect.map((snapshot) => new Generation(this.route, this.token, snapshot)));
|
|
38
|
+
}
|
|
39
|
+
/** Poll until the generation reaches a terminal status, then fetch the result. Fails with a `Timeout` reason on deadline. */
|
|
40
|
+
await(options) {
|
|
41
|
+
const timeout = Duration.fromInputUnsafe(options?.poll?.timeout ?? DEFAULT_POLL_TIMEOUT);
|
|
42
|
+
const settled = this.terminal ? Effect.succeed(this) : this.poll(options?.poll);
|
|
43
|
+
return settled.pipe(
|
|
44
|
+
// Non-completed terminal states also go through `result` so the route can surface its provider failure body.
|
|
45
|
+
Effect.flatMap((generation) => generation.route.result(generation.token)), Effect.timeoutOrElse({
|
|
46
|
+
duration: timeout,
|
|
47
|
+
orElse: () => new AIError({
|
|
48
|
+
reason: new TimeoutError({
|
|
49
|
+
message: `Generation ${this.id} did not finish within ${Duration.format(timeout)}`,
|
|
50
|
+
timeoutMs: Duration.toMillis(timeout),
|
|
51
|
+
}),
|
|
52
|
+
}),
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
cancel() {
|
|
56
|
+
return this.route.cancel?.(this.token) ?? Effect.void;
|
|
57
|
+
}
|
|
58
|
+
/** Status observations as a stream, ending after the first terminal observation. */
|
|
59
|
+
events(options) {
|
|
60
|
+
const observations = this.terminal
|
|
61
|
+
? Stream.make(this)
|
|
62
|
+
: Stream.fromEffectSchedule(this.refresh(), this.schedule(options?.poll)).pipe(Stream.takeUntil((generation) => generation.terminal));
|
|
63
|
+
return observations.pipe(Stream.map((generation) => {
|
|
64
|
+
if (generation.terminal)
|
|
65
|
+
return { type: "generation-finished", id: generation.id, status: generation.status };
|
|
66
|
+
if (generation.status === "queued")
|
|
67
|
+
return { type: "generation-queued", id: generation.id, position: generation.position };
|
|
68
|
+
return { type: "generation-progress", id: generation.id, progress: generation.progress };
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
poll(poll) {
|
|
72
|
+
return this.refresh().pipe(Effect.repeat({ schedule: this.schedule(poll), until: (generation) => generation.terminal }));
|
|
73
|
+
}
|
|
74
|
+
schedule(poll) {
|
|
75
|
+
if (poll?.schedule)
|
|
76
|
+
return poll.schedule.pipe(Schedule.setInputType());
|
|
77
|
+
const interval = poll?.interval ?? DEFAULT_POLL_INTERVAL;
|
|
78
|
+
const pollHint = this.route.pollHint;
|
|
79
|
+
const spaced = Schedule.spaced(interval).pipe(Schedule.setInputType());
|
|
80
|
+
if (!pollHint)
|
|
81
|
+
return spaced;
|
|
82
|
+
return spaced.pipe(Schedule.modifyDelay((metadata) => Effect.succeed(pollHint(metadata.input.snapshot) ?? interval)));
|
|
83
|
+
}
|
|
84
|
+
}
|
package/dist/image-client.d.ts
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
|
-
import { Context, Effect, Layer } from "effect";
|
|
1
|
+
import { Context, Effect, Layer, Stream } from "effect";
|
|
2
2
|
import { RequestExecutor } from "./route/executor.js";
|
|
3
|
-
import {
|
|
4
|
-
import type
|
|
5
|
-
export type Execute = RequestExecutor.Interface["execute"];
|
|
3
|
+
import type { AIError } from "./schema/index.js";
|
|
4
|
+
import { type ImageEvent, type ImageOptions, type ImageRequestFor, type ImageResponse } from "./image.js";
|
|
6
5
|
export interface Interface {
|
|
7
6
|
readonly generate: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Effect.Effect<ImageResponse, AIError>;
|
|
7
|
+
readonly stream: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Stream.Stream<ImageEvent, AIError>;
|
|
8
8
|
}
|
|
9
9
|
declare const Service_base: Context.ServiceClass<Service, "@opencode/ImageClient", Interface>;
|
|
10
10
|
export declare class Service extends Service_base {
|
|
11
11
|
}
|
|
12
12
|
export declare const generate: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Effect.Effect<ImageResponse, AIError, Service>;
|
|
13
|
+
export declare const stream: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Stream.Stream<ImageEvent, AIError, Service>;
|
|
13
14
|
export declare const layer: Layer.Layer<Service, never, RequestExecutor.Service>;
|
|
14
15
|
export declare const ImageClient: {
|
|
15
16
|
readonly Service: typeof Service;
|
|
16
17
|
readonly layer: Layer.Layer<Service, never, RequestExecutor.Service>;
|
|
17
18
|
readonly generate: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Effect.Effect<ImageResponse, AIError, Service>;
|
|
19
|
+
readonly stream: <Options extends ImageOptions>(request: ImageRequestFor<Options>) => Stream.Stream<ImageEvent, AIError, Service>;
|
|
18
20
|
};
|
|
19
21
|
export {};
|
package/dist/image-client.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import { Context, Effect, Layer } from "effect";
|
|
1
|
+
import { Context, Effect, Layer, Stream } from "effect";
|
|
2
2
|
import { RequestExecutor } from "./route/executor.js";
|
|
3
|
-
import {
|
|
4
|
-
import { sanitizeSurrogates } from "./utils/sanitize.js";
|
|
3
|
+
import { responseEvents, } from "./image.js";
|
|
5
4
|
export class Service extends Context.Service()("@opencode/ImageClient") {
|
|
6
5
|
}
|
|
7
6
|
export const generate = (request) => Effect.gen(function* () {
|
|
8
7
|
const client = yield* Service;
|
|
9
8
|
return yield* client.generate(request);
|
|
10
9
|
});
|
|
10
|
+
export const stream = (request) => Stream.unwrap(Effect.gen(function* () {
|
|
11
|
+
const client = yield* Service;
|
|
12
|
+
return client.stream(request);
|
|
13
|
+
}));
|
|
11
14
|
export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
12
15
|
const executor = yield* RequestExecutor.Service;
|
|
16
|
+
const generate = (request) => request.model.route.generate(request, executor.execute);
|
|
13
17
|
return Service.of({
|
|
14
|
-
generate
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
model: undefined,
|
|
18
|
-
http: mergeHttpOptions(request.model.http, request.http),
|
|
19
|
-
}),
|
|
20
|
-
model: request.model,
|
|
21
|
-
}, executor.execute),
|
|
18
|
+
generate,
|
|
19
|
+
// Inline routes have no partial frames yet; the stream is the completed response expanded into events.
|
|
20
|
+
stream: (request) => Stream.unwrap(generate(request).pipe(Effect.map((response) => Stream.fromIterable(responseEvents(response))))),
|
|
22
21
|
});
|
|
23
22
|
}));
|
|
24
23
|
export const ImageClient = {
|
|
25
24
|
Service,
|
|
26
25
|
layer,
|
|
27
26
|
generate,
|
|
27
|
+
stream,
|
|
28
28
|
};
|