@howaboua/pi-durable-openai-responses 0.0.0-stage → 0.9.1
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 +21 -0
- package/NOTICE +82 -0
- package/README.md +109 -2
- package/dist/cache-keepalive.d.ts +28 -0
- package/dist/completion.d.ts +15 -0
- package/dist/configuration-updates.d.ts +6 -0
- package/dist/constrained-sampling.d.ts +17 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +6403 -0
- package/dist/lifecycle.d.ts +12 -0
- package/dist/lite-images.d.ts +14 -0
- package/dist/openai-codex/constants.d.ts +20 -0
- package/dist/openai-codex/continuation-diagnostics.d.ts +26 -0
- package/dist/openai-codex/daybreak.d.ts +7 -0
- package/dist/openai-codex/device-code.d.ts +21 -0
- package/dist/openai-codex/diagnostic-failure.d.ts +3 -0
- package/dist/openai-codex/errors.d.ts +14 -0
- package/dist/openai-codex/header-record.d.ts +1 -0
- package/dist/openai-codex/headers.d.ts +9 -0
- package/dist/openai-codex/model-catalog.d.ts +2 -0
- package/dist/openai-codex/node-runtime.d.ts +8 -0
- package/dist/openai-codex/oauth.d.ts +2 -0
- package/dist/openai-codex/recovery-budget.d.ts +37 -0
- package/dist/openai-codex/request-body.d.ts +5 -0
- package/dist/openai-codex/request-serialization.d.ts +6 -0
- package/dist/openai-codex/responses-lite-model.d.ts +6 -0
- package/dist/openai-codex/responses-lite-tools.d.ts +2 -0
- package/dist/openai-codex/responses-lite.d.ts +18 -0
- package/dist/openai-codex/session-continuity.d.ts +29 -0
- package/dist/openai-codex/sse-request.d.ts +4 -0
- package/dist/openai-codex/sse.d.ts +14 -0
- package/dist/openai-codex/stream-events.d.ts +23 -0
- package/dist/openai-codex/transport-recovery.d.ts +29 -0
- package/dist/openai-codex/transport-state.d.ts +28 -0
- package/dist/openai-codex/turn-state.d.ts +14 -0
- package/dist/openai-codex/types.d.ts +250 -0
- package/dist/openai-codex/usage.d.ts +12 -0
- package/dist/openai-codex/websocket-connection.d.ts +14 -0
- package/dist/openai-codex/websocket-continuation.d.ts +3 -0
- package/dist/openai-codex/websocket-parser.d.ts +3 -0
- package/dist/openai-codex/websocket-session-cache.d.ts +14 -0
- package/dist/openai-codex/websocket-stream.d.ts +16 -0
- package/dist/openai-codex/websocket.d.ts +4 -0
- package/dist/openai-codex/worker-websocket.d.ts +3 -0
- package/dist/openai-responses/compaction-v2-feature.d.ts +3 -0
- package/dist/openai-responses/message-history.d.ts +4 -0
- package/dist/openai-responses/native-items.d.ts +48 -0
- package/dist/openai-responses/oauth.d.ts +3 -0
- package/dist/openai-responses/remote-delivery-protocol.d.ts +10 -0
- package/dist/openai-responses/shared.d.ts +32 -0
- package/dist/openai-responses/signatures.d.ts +7 -0
- package/dist/openai-responses/stream.d.ts +5 -0
- package/dist/openai-responses/tool-history.d.ts +2 -0
- package/dist/preparation.d.ts +7 -0
- package/dist/prewarm.d.ts +13 -0
- package/dist/protocol.d.ts +10 -0
- package/package.json +43 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Igor Warzocha
|
|
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/NOTICE
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
OpenAI Codex Responses provider adapted from @howaboua/pi-codex-conversion
|
|
2
|
+
at 5dc8fa4bbded063f9c158e2af7a8a53eeaea7fbb.
|
|
3
|
+
Source: https://github.com/IgorWarzocha/howaboua-pi-stuff
|
|
4
|
+
Modifications: standalone pi-ai Provider for Durable hosts, instance-owned
|
|
5
|
+
transport lifecycle, native Node transport and image preparation.
|
|
6
|
+
The Pi extension, TUI and session-manager adapters are not included.
|
|
7
|
+
Request-local transient WebSocket fallback follows Pi Stuff revision
|
|
8
|
+
e4aa5bb43c560b722829a5123b3f2e05d3d9a19d, openai-codex/transport-recovery.ts.
|
|
9
|
+
Selected protocol refreshes from snapshot 69f50cf70e8a7b05c2349be6227f521b6504f80e:
|
|
10
|
+
SSE opening retry budget from 5a109ed787b2a2e947f262be21f610ed3b732c4f;
|
|
11
|
+
partial_answer signatures and replay from b7d92bd90aa5fa6b25b18080a88539aab54254b5.
|
|
12
|
+
Daybreak account-catalog discovery and Ultrafast pricing adapted from PR491,
|
|
13
|
+
snapshot 88c08f52bbf05be17525ec47a6f1d9958f07fdab, PR head 2a24e1d3.
|
|
14
|
+
Modifications: provider-instance bounded identity cache, Web Crypto identity
|
|
15
|
+
digest for Node and Workers, explicit opt-in settings, and final-body pricing.
|
|
16
|
+
Pi configuration, UI and native compaction integration are not included.
|
|
17
|
+
Selected provider refreshes from snapshot 036dc876da5afc4ec27b64878ebb1cfb30c8211d:
|
|
18
|
+
interrupted tool-stream recovery (9a669ac0, c337c9a8), strict final tool arguments
|
|
19
|
+
and model-switch thinking removal (1985f069), advisory Codex routing (1fd72ce4)
|
|
20
|
+
and WebSocket timing-metric requests (93895b22), plus the GPT-6.1 Sol context
|
|
21
|
+
window correction (1fd63f8e).
|
|
22
|
+
Modifications: routing hints are bounded and Codex-only; explicit no-fallback
|
|
23
|
+
policy is preserved. Pi diagnostics logging and integration are not included.
|
|
24
|
+
|
|
25
|
+
Selected provider refreshes from exact snapshot
|
|
26
|
+
7f3295e67a8e6146b2a6922b56a06fa4db5c3a32, including its local commits:
|
|
27
|
+
bounded fresh WebSocket retries and independent SSE recovery, raw socket errors,
|
|
28
|
+
bounded continuation diagnostics and socket request ordinals, gateway-first
|
|
29
|
+
request serialisation, explicit routing affinity and developer-input instructions.
|
|
30
|
+
Modifications: instance-owned recovery and cancellation; speculative handshake
|
|
31
|
+
failures count against retry admission; terminal observer failures never replay;
|
|
32
|
+
case-insensitive request affinity reconnects without merging native socket lanes.
|
|
33
|
+
Pi usage ledgers, UI, V2 session compaction and experimental GPT prompt-policy
|
|
34
|
+
brokers are excluded. Durable owns native session identity and lifecycle.
|
|
35
|
+
Pi 1.4 additions-only transcript folding and native-session diagnostic selection
|
|
36
|
+
follow snapshot 3d0faf5a6f0bc67c0bd9248d07da6ddfa901b281.
|
|
37
|
+
Modifications: transport cleanup remains provider-instance owned. No Pi-global
|
|
38
|
+
session cleanup callback, footer or logging adapter is installed.
|
|
39
|
+
|
|
40
|
+
Opt-in generated-current keepalive scheduling and current transport selection
|
|
41
|
+
follow snapshot 12c4357b2c401fe9be8c6c82d2ae252c0f986937, including d08c31c9.
|
|
42
|
+
Source owners: adapter/activation/cache-keepalive.ts and extension/runtime.ts.
|
|
43
|
+
Modifications: explicit host-prepared snapshot and currentness callbacks,
|
|
44
|
+
session-scoped provider-owned scheduling, cancellation and usage reporting.
|
|
45
|
+
No Pi idle hooks, configuration UI, global paths or automatic adoption.
|
|
46
|
+
|
|
47
|
+
Logical SSE retry admission, elapsed overload/advice deadlines and Terra model
|
|
48
|
+
metadata follow merged PR552 snapshot
|
|
49
|
+
84bd5bce60a77c4298484d4b7c810d4fe5220a1b, compared with 1338b66a.
|
|
50
|
+
Source owners: openai-codex/transport/recovery-budget.ts and sse-request.ts.
|
|
51
|
+
Modifications: instance-owned lifecycle and existing maxRetryDelayMs policy;
|
|
52
|
+
completion observers and interrupted tool streams remain non-replayable.
|
|
53
|
+
|
|
54
|
+
Portions of the Responses conversion and streaming implementation derive
|
|
55
|
+
from Pi, Copyright (c) 2025 Mario Zechner, MIT licensed.
|
|
56
|
+
|
|
57
|
+
Direct Responses request preparation and OAuth refresh behavior are adapted
|
|
58
|
+
from @earendil-works/pi-ai 1.0.2, published dist/api/openai-responses.js and
|
|
59
|
+
dist/auth/oauth/openai-chatgpt.js. Source: https://github.com/earendil-works/pi
|
|
60
|
+
Copyright (c) 2025 Mario Zechner, MIT licensed.
|
|
61
|
+
|
|
62
|
+
MIT License
|
|
63
|
+
|
|
64
|
+
Copyright (c) 2026 Igor Warzocha
|
|
65
|
+
|
|
66
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
67
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
68
|
+
in the Software without restriction, including without limitation the rights
|
|
69
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
70
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
71
|
+
furnished to do so, subject to the following conditions:
|
|
72
|
+
|
|
73
|
+
The above copyright notice and this permission notice shall be included in all
|
|
74
|
+
copies or substantial portions of the Software.
|
|
75
|
+
|
|
76
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
77
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
78
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
79
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
80
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
81
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
82
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,110 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OpenAI Responses
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Our optimised Responses provider for Pi Durable. It carries cached WebSockets, validated continuation, grammar tools and stream recovery without the coding-agent extension. Codex mode also supports Responses Lite.
|
|
4
|
+
|
|
5
|
+
Codex mode remains the default. Explicit direct mode targets OpenAI's ordinary Responses endpoint and accepts Pi's `openai` direct-subscription OAuth credential. Direct mode uses WebSockets only and never falls back to SSE.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Requires pi-ai 1.4.0. Node.js 22.19 or newer is supported, with Linux tested. Cloudflare Workers with `nodejs_compat` use an explicit native Upgrade runtime, described below.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.9.1/howaboua-pi-durable-openai-responses-0.9.1.tgz
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Register the provider with the same Models collection your Harness uses:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createModels } from "@earendil-works/pi-ai";
|
|
19
|
+
import { createOpenAIResponsesProvider } from "@howaboua/pi-durable-openai-responses";
|
|
20
|
+
|
|
21
|
+
const provider = createOpenAIResponsesProvider();
|
|
22
|
+
const models = createModels({ credentials: credentialStore });
|
|
23
|
+
models.setProvider(provider);
|
|
24
|
+
|
|
25
|
+
// Pass models to Harness.open(...).
|
|
26
|
+
// Select { provider: "openai-codex", modelId: "gpt-6-luna" }.
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`credentialStore` is your application's pi-ai CredentialStore containing the `openai-codex` OAuth credential. Models owns refresh and storage. The provider never reads Pi's authentication files. New accounts can use `provider.auth.oauth.login(interaction)` through your host's normal authentication interface. Browser login and headless device-code login are included.
|
|
30
|
+
|
|
31
|
+
This replaces `openai-codex` in that Models collection. It is not a tool extension and does not use `registry.install` or `pi install`. A custom `id`, `baseUrl` and model catalog are supported for explicitly Codex-compatible routes.
|
|
32
|
+
|
|
33
|
+
## Direct OpenAI WebSockets
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
const provider = createOpenAIResponsesProvider({
|
|
37
|
+
mode: "direct",
|
|
38
|
+
runtime: "workerd", // Omit on Node or Bun.
|
|
39
|
+
});
|
|
40
|
+
models.setProvider(provider);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Direct mode replaces `openai` in the host's Models collection, uses the stock OpenAI catalog and connects to `wss://api.openai.com/v1/responses`. The existing `openai` OAuth credential must include its issued `clientId` for refresh. Refresh is fetch-native. Interactive login delegates to stock pi-ai and belongs on a Node host, not inside a Worker.
|
|
44
|
+
|
|
45
|
+
Workers use authenticated native `fetch` Upgrade with `response.webSocket.accept()`. Node proxy environment routing does not apply to this runtime. Keep the provider on the conversation's owning Durable Object instance. Socket state is in memory and cannot survive an instance restart.
|
|
46
|
+
|
|
47
|
+
Cached continuation, grammar tools, native input items, explicit prewarm, usage observers, cancellation, session reset and close use the same implementation in both modes. Direct mode rejects Responses Lite and Codex compaction requests. HTTP-only `stream` and `background` fields are omitted from direct WebSocket events. Subscription credentials omit unsupported temperature, output-token caps and cache-retention controls, matching stock pi-ai. Normal API keys retain those supported request controls.
|
|
48
|
+
|
|
49
|
+
`websocketFallback: "error"` explicitly disables SSE recovery in Codex mode too. Direct mode always requires that policy. Upgrade rejection, oversized messages and exhausted retries remain visible errors rather than changing transport. An explicit direct request with `transport: "sse"` is rejected.
|
|
50
|
+
|
|
51
|
+
## What changes
|
|
52
|
+
|
|
53
|
+
- Cached WebSockets are the default. A matching completed request allows later calls to send only new input with `previous_response_id`. Changed history, tools, model or request settings require full input.
|
|
54
|
+
- Socket handshakes overlap final payload preparation. Connection identity includes credentials, endpoint, proxy and headers.
|
|
55
|
+
- WebSocket failures have bounded retries. Codex mode permits visible SSE fallback unless disabled. Upgrade-required and oversized-message failures keep SSE active for that session. Authentication fallback is limited to the current request. Direct mode never changes transport.
|
|
56
|
+
- In Codex mode, Responses Lite is automatic for supported models when a grammar tool is declared. Code and Notebook qualify through their ordinary tool declarations. Lite relocates tools and instructions into the input, uses the `functions` namespace and disables parallel tool calls. Ordinary function-only requests keep normal Responses formatting and parallel calls.
|
|
57
|
+
- Historical function and custom-tool calls keep their recorded family when current declarations change. Encrypted reasoning, native web and image items, cache usage and service-tier pricing remain available.
|
|
58
|
+
|
|
59
|
+
Configure Codex defaults with `transport`, `responsesLite`, `forceCachedWebSockets`, `originator` and `diagnostics`. Set `responsesLite: false` to disable Lite, or `true` only for a route known to support it. Per-request pi-ai options supply reasoning effort, service tier, verbosity, cancellation, timeouts and retries. Codex deliberately omits `maxTokens` because its endpoint rejects an output-token cap. Deferred generation is not supported. Named tool selection is available in direct mode, but not Codex mode.
|
|
60
|
+
|
|
61
|
+
Explicit `transport: "websocket"` sends full requests without cached continuation. The default remains `"websocket-cached"`. Only explicit `forceCachedWebSockets: true` upgrades a plain WebSocket preference. Connection preconnect follows WebSocket availability independently of that override. Ordinary prewarm skips plain WebSockets and SSE.
|
|
62
|
+
|
|
63
|
+
Codex accepts `serviceTier: "ultrafast"`. Cost estimates use the final sent payload's tier and model after payload hooks. Ultrafast applies the source's sixfold multiplier only to `gpt-6-astra` and `gpt-6.1-sol`. Other models retain a base-rate estimate because no Ultrafast multiplier is known for them.
|
|
64
|
+
|
|
65
|
+
A payload hook that changes the model must select an ID registered in this provider's `models` catalog. Its pricing metadata replaces the original model's rates without changing the authorized endpoint or headers. An unknown target fails before generation rather than reporting another model's prices.
|
|
66
|
+
|
|
67
|
+
Set `daybreak: true` on the provider or request to opt into account-catalog eligibility discovery. Request settings override provider defaults. The connected server must advertise `daybreak_blue` or `daybreak_red` for the final payload model. Blue is preferred. Unknown eligibility fails visibly without switching models. Explicit `false` also queries the catalog and sends `standard` only when advertised, otherwise leaving access programs unset. Omit the setting to preserve existing behavior with no catalog request. Model aliases do not establish eligibility. Direct mode does not support this setting.
|
|
68
|
+
|
|
69
|
+
Discovery uses the request's endpoint, credentials, model headers, request headers and custom fetch route. It does not follow redirects. Eligibility evidence is bounded to eight identities per provider instance, retained for five minutes on success and thirty seconds on failure. Discovery is cancelled with the request and joined on provider close. Credentials are not logged or retained in cache keys.
|
|
70
|
+
|
|
71
|
+
`diagnostics(event)` receives transport decisions and usage counts without prompts, tool arguments, credentials or response IDs. Prewarm readiness and continuation reuse do not prove a prompt-cache hit. Only provider-reported cache usage does. This package makes no general latency or billing guarantee.
|
|
72
|
+
|
|
73
|
+
## Lifecycle
|
|
74
|
+
|
|
75
|
+
For trusted host admission, `onPreparedRequest(body, model)` can adjust a converted request before final serialization. `onCompletion(observation)` receives the exact sent JSON after an actual successful `response.completed`, correlated by response ID, model and session. Both SSE and WebSockets are covered, including the WebSocket event envelope and continuation payload. Bodies above 96 KiB are not observed. Observations contain no authentication headers and are not persisted. `canonicalSubscription` is false for direct mode, custom routes, custom routing or authentication headers, and custom fetch. Ordinary configured headers, including residency, remain supported. Observer failure reports an error without replaying the completed request. These callbacks are host capabilities, not agent tools.
|
|
76
|
+
|
|
77
|
+
Durable supplies a persisted provider session ID for each conversation. Direct pi-ai callers should supply their own stable `sessionId`. State is isolated per provider instance and is not restored after a process restart.
|
|
78
|
+
|
|
79
|
+
Call `await provider.resetSession(sessionId)` when explicitly discarding a conversation's transport state. It cancels active work and clears sockets, continuation, canonical history and sticky fallback. New requests for that session are rejected until reset completes.
|
|
80
|
+
|
|
81
|
+
Close the provider when disposing the host, after stopping its Harness:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
await harness.close(context);
|
|
85
|
+
await provider.close();
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`close()` cancels and joins remaining streams, prewarms and owned connections. A closed provider rejects new work. Keep one provider alive across ordinary turns rather than recreating it for every request.
|
|
89
|
+
|
|
90
|
+
## Explicit prewarm and checkpoints
|
|
91
|
+
|
|
92
|
+
`provider.prewarm(model, context, options)` prepares a complete request and warms its WebSocket. Options require resolved `apiKey` and `sessionId`. `provider.prewarmPrepared(model, body, options)` accepts an already prepared final payload. The host must run its normal prompt and tool preparation first. Neither method knows about pending host edits.
|
|
93
|
+
|
|
94
|
+
Default prewarm uses `generate: false`. `mode: "keepalive"` explicitly generates a billable response on an isolated socket lane without advancing the main conversation. Nothing schedules generated keepalive by default. Returned usage belongs to the caller's accounting, not a Durable generation task.
|
|
95
|
+
|
|
96
|
+
Generated keepalive also returns `billedUsage`, a cost estimate based on its actual sent model and tier. Ordinary preparation returns token usage only. Daybreak selection applies to both prewarm methods when explicitly configured.
|
|
97
|
+
|
|
98
|
+
Codex hosts can opt into `provider.armCacheKeepalive(model, preparedBody, options)`, which returns a cancellation function. Options extend `PrewarmOptions` without `mode` and require `policy`, synchronous `isCurrent()`, `onResult(result)` and `onError(error)`. Result and error callbacks may return promises. The host supplies resolved credentials, headers, session ID and an optional cancellation signal. `onResult` owns billable accounting, including results received during cancellation. Callback promises must settle before session reset or provider close can finish.
|
|
99
|
+
|
|
100
|
+
Capture the final body through `onPreparedRequest` after normal prompt and tool preparation. Arm only after the host settles idle, with no quota block or pending continuation or rollover. The provider copies and validates the snapshot, rejecting continuation-only bodies and `cacheRetention: "none"`. `isCurrent` must confirm idle state, credentials, model, settings and snapshot identity before each refresh. Returning false stops the arm. The host must rearm with a new authoritative snapshot after relevant changes. This API does not infer readiness from a completed response or reconstruct host context.
|
|
101
|
+
|
|
102
|
+
All policy defaults are off: `cacheKeepalive` defaults to false and `lunaCacheKeepaliveMinutes` to 0. Explicit `cacheKeepalive: true` refreshes Astra, Sol and Terra every 25 minutes, or 55 with `cacheKeepaliveIntervalMinutes: 55`. Luna, including `gpt-reserve`, accepts a 5, 10 or 15 minute duration cap and a 2.5 minute default interval, or 4.5 with `lunaCacheKeepaliveIntervalMinutes: 4.5`. Its attempt cap is the duration divided by the interval, rounded down. Other models do not arm.
|
|
103
|
+
|
|
104
|
+
Refreshes use the isolated billable lane. Successful and failed attempts rearm within the policy caps. Errors reach `onError`; a skipped transport or stale snapshot stops scheduling. A failing error callback stops scheduling and logs the failure. Ordinary streams and explicit prewarms cancel only their session's arm. `resetSession` cancels and drains that session; `close` cancels and joins all arms and requests. Cancellation never retries an uncertain paid request. The host must install this provider and explicitly adopt this API before any automatic refresh can run.
|
|
105
|
+
|
|
106
|
+
`provider.getCanonicalRequest(model, sessionId, apiKey, reconstructedInput)` exposes a validated completed-request snapshot for host-owned native checkpoints. `reconstructedInput` excludes Lite's leading tool and instruction items. Account, endpoint, model and history must match. A mismatch returns a decision without a body. This does not install a compaction policy, persist encrypted checkpoints or replace Durable's context management.
|
|
107
|
+
|
|
108
|
+
Lite prepares inline images with a native codec, a 2048-pixel dimension limit and a 2500-patch budget. Unsupported remote image URLs and undecodable images become explicit omission text, matching the source policy.
|
|
109
|
+
|
|
110
|
+
[Parity and validation](../../docs/parity/openai-responses.md) distinguish carried behavior, intentional fixes and live evidence.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { CodexDiagnosticsSink, CodexPrewarmResult, ResponsesBody } from "./openai-codex/types.ts";
|
|
3
|
+
import type { PrewarmOptions } from "./prewarm.ts";
|
|
4
|
+
export interface CacheKeepalivePolicy {
|
|
5
|
+
/** Astra, Sol and Terra. Default false. */
|
|
6
|
+
cacheKeepalive?: boolean;
|
|
7
|
+
/** Default 25. */
|
|
8
|
+
cacheKeepaliveIntervalMinutes?: 25 | 55;
|
|
9
|
+
/** Luna duration cap. Default 0, disabled. */
|
|
10
|
+
lunaCacheKeepaliveMinutes?: 0 | 5 | 10 | 15;
|
|
11
|
+
/** Default 2.5. */
|
|
12
|
+
lunaCacheKeepaliveIntervalMinutes?: 2.5 | 4.5;
|
|
13
|
+
}
|
|
14
|
+
export type CacheKeepaliveOptions = Omit<PrewarmOptions, "mode"> & {
|
|
15
|
+
policy: CacheKeepalivePolicy;
|
|
16
|
+
/** Recheck idle, quota, credentials and prepared snapshot identity synchronously. */
|
|
17
|
+
isCurrent: () => boolean;
|
|
18
|
+
/** Account for generated usage, including a result arriving during cancellation. */
|
|
19
|
+
onResult: (result: CodexPrewarmResult) => void | Promise<void>;
|
|
20
|
+
onError: (error: unknown) => void | Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
/** Provider-owned timers and tasks. Hosts supply authority, never an inferred transcript. */
|
|
23
|
+
export declare function createCacheKeepalive(warm: (model: Model<Api>, body: ResponsesBody, options: PrewarmOptions) => Promise<CodexPrewarmResult | undefined>, getDiagnostics: (sessionId: string) => CodexDiagnosticsSink | undefined): {
|
|
24
|
+
cancel: (sessionId: string) => void | undefined;
|
|
25
|
+
drain(sessionId?: string): Promise<void>;
|
|
26
|
+
close(): void;
|
|
27
|
+
arm(model: Model<Api>, body: ResponsesBody, options: CacheKeepaliveOptions): () => void;
|
|
28
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Ephemeral transport evidence. Contains no authentication headers or credentials. */
|
|
2
|
+
export interface CompletionObservation {
|
|
3
|
+
responseId: string;
|
|
4
|
+
provider: string;
|
|
5
|
+
api: string;
|
|
6
|
+
model: string;
|
|
7
|
+
sessionId: string | undefined;
|
|
8
|
+
/** HTTP-equivalent endpoint, including when the request used WebSockets. */
|
|
9
|
+
url: string;
|
|
10
|
+
transport: "sse" | "websocket";
|
|
11
|
+
/** Exact sent JSON, including the WebSocket event envelope. */
|
|
12
|
+
requestBody: string;
|
|
13
|
+
canonicalSubscription: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type CompletionObserver = (observation: CompletionObservation) => void;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Tool } from "@earendil-works/pi-ai";
|
|
2
|
+
export declare function getJsonSchemaToolParameters(tool: Tool, strict: boolean | undefined): Tool["parameters"];
|
|
3
|
+
export declare function resolveJsonSchemaStrictSampling(tool: Tool, supportsStrictMode: boolean): boolean | undefined;
|
|
4
|
+
export interface GrammarConstrainedSampling {
|
|
5
|
+
format: "lark" | "regex";
|
|
6
|
+
definition: string;
|
|
7
|
+
inputProperty: string;
|
|
8
|
+
}
|
|
9
|
+
export interface GrammarToolInputJsonBuffer {
|
|
10
|
+
input: string;
|
|
11
|
+
started: boolean;
|
|
12
|
+
closed: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function getGrammarToolInput(toolName: string, arguments_: Record<string, unknown>, inputProperty: string): string;
|
|
15
|
+
export declare function appendGrammarToolInputJsonDelta(buffer: GrammarToolInputJsonBuffer, inputProperty: string, nextInput: string, close: boolean): string | undefined;
|
|
16
|
+
export declare function resolveGrammarConstrainedSampling(tool: Tool, supportsOpenAIGrammarTools: boolean): GrammarConstrainedSampling | undefined;
|
|
17
|
+
export declare function createGrammarToolInputProperties(tools: Tool[] | undefined, supportsOpenAIGrammarTools: boolean): ReadonlyMap<string, string>;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type Api, type Context, type Model, type Provider, type Transport } from "@earendil-works/pi-ai";
|
|
2
|
+
import { type CacheKeepaliveOptions } from "./cache-keepalive.ts";
|
|
3
|
+
import type { CompletionObserver } from "./completion.ts";
|
|
4
|
+
export type { CompletionObservation, CompletionObserver, } from "./completion.ts";
|
|
5
|
+
import { type CodexCompactionReplayDecision, type CodexDiagnosticsSink, type CodexPrewarmResult, type ResponsesBody } from "./openai-codex/types.ts";
|
|
6
|
+
import { type PrewarmOptions } from "./prewarm.ts";
|
|
7
|
+
import { type WebSocketFallback, type WebSocketRuntime } from "./protocol.ts";
|
|
8
|
+
export type { CacheKeepaliveOptions, CacheKeepalivePolicy, } from "./cache-keepalive.ts";
|
|
9
|
+
export type { CodexDiagnosticsEvent, CodexDiagnosticsSink, CodexPrewarmResult, OpenAICodexStreamOptions, ResponsesBody, } from "./openai-codex/types.ts";
|
|
10
|
+
export type { PrewarmOptions } from "./prewarm.ts";
|
|
11
|
+
type ResponsesApi = "openai-codex-responses" | "openai-responses";
|
|
12
|
+
export interface OpenAIResponsesProviderOptions<TApi extends ResponsesApi = "openai-codex-responses"> {
|
|
13
|
+
/** Codex remains the default. Direct uses ordinary OpenAI Responses auth and catalog. */
|
|
14
|
+
mode?: TApi extends "openai-responses" ? "direct" : "codex";
|
|
15
|
+
/** workerd uses native authenticated fetch Upgrade, with no Node proxy routing. */
|
|
16
|
+
runtime?: WebSocketRuntime;
|
|
17
|
+
/** Direct is WebSocket-only. Codex keeps its existing SSE recovery unless explicitly disabled. */
|
|
18
|
+
websocketFallback?: WebSocketFallback;
|
|
19
|
+
id?: string;
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
models?: readonly Model<TApi>[];
|
|
22
|
+
/** Auto enables Lite for supported models with grammar-constrained tools. */
|
|
23
|
+
responsesLite?: boolean | "auto";
|
|
24
|
+
/** Codex account eligibility. Undefined makes no catalog request. */
|
|
25
|
+
daybreak?: boolean;
|
|
26
|
+
transport?: Transport;
|
|
27
|
+
/** Explicitly upgrade plain WebSockets to cached continuation. Default false. */
|
|
28
|
+
forceCachedWebSockets?: boolean;
|
|
29
|
+
originator?: string;
|
|
30
|
+
diagnostics?: CodexDiagnosticsSink;
|
|
31
|
+
/** Select once per request by native session ID, never by cache affinity. Overrides diagnostics. */
|
|
32
|
+
getDiagnostics?: (sessionId: string | undefined) => CodexDiagnosticsSink | undefined;
|
|
33
|
+
/** Opt-in ephemeral evidence of an actually completed sent request. */
|
|
34
|
+
onCompletion?: CompletionObserver;
|
|
35
|
+
/** Trusted host preparation, after provider conversion and before serialization. */
|
|
36
|
+
onPreparedRequest?: (body: ResponsesBody, model: Model<Api>) => void;
|
|
37
|
+
}
|
|
38
|
+
export interface OpenAIResponsesProvider<TApi extends ResponsesApi = "openai-codex-responses"> extends Provider<TApi> {
|
|
39
|
+
prewarm(model: Model<Api>, context: Context, options: PrewarmOptions): Promise<CodexPrewarmResult | undefined>;
|
|
40
|
+
/** Warm an authoritative final payload already prepared by the host. */
|
|
41
|
+
prewarmPrepared(model: Model<Api>, body: ResponsesBody, options: PrewarmOptions): Promise<CodexPrewarmResult | undefined>;
|
|
42
|
+
/** Opt-in billable idle refresh of a host-authoritative final prepared snapshot. */
|
|
43
|
+
armCacheKeepalive(model: Model<Api>, body: ResponsesBody, options: CacheKeepaliveOptions): () => void;
|
|
44
|
+
/** A validated snapshot for host-owned native checkpoint requests. Input excludes Lite's request prefix. */
|
|
45
|
+
getCanonicalRequest(model: Model<Api>, sessionId: string, apiKey: string, reconstructedInput: readonly unknown[]): {
|
|
46
|
+
body?: ResponsesBody;
|
|
47
|
+
decision: CodexCompactionReplayDecision;
|
|
48
|
+
};
|
|
49
|
+
resetSession(sessionId: string): Promise<void>;
|
|
50
|
+
close(): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
/** Register with the host's Models collection, not the Durable tool registry. */
|
|
53
|
+
export declare function createOpenAIResponsesProvider(options: OpenAIResponsesProviderOptions<"openai-responses"> & {
|
|
54
|
+
mode: "direct";
|
|
55
|
+
}): OpenAIResponsesProvider<"openai-responses">;
|
|
56
|
+
export declare function createOpenAIResponsesProvider(options?: OpenAIResponsesProviderOptions<"openai-codex-responses"> & {
|
|
57
|
+
mode?: "codex";
|
|
58
|
+
}): OpenAIResponsesProvider<"openai-codex-responses">;
|