@nimble-way/cloudflare-agents 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Nimbleway
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # Nimble Cloudflare Agents
2
+
3
+ First-party Cloudflare Agents integration for Nimble Agent API V2. It provides
4
+ a Durable Object-backed agent with resumable create, status, and result tools,
5
+ plus a typed adapter for `@nimble-way/nimble-js`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @nimble-way/cloudflare-agents agents
11
+ ```
12
+
13
+ ## Worker configuration
14
+
15
+ Export `NimbleRunAgent` from your Worker entry point and bind it as a SQLite
16
+ Durable Object:
17
+
18
+ ```ts
19
+ export { NimbleRunAgent } from "@nimble-way/cloudflare-agents";
20
+ ```
21
+
22
+ ```jsonc
23
+ {
24
+ "durable_objects": {
25
+ "bindings": [
26
+ { "name": "NIMBLE_RUN_AGENT", "class_name": "NimbleRunAgent" }
27
+ ]
28
+ },
29
+ "migrations": [
30
+ { "tag": "v1", "new_sqlite_classes": ["NimbleRunAgent"] }
31
+ ]
32
+ }
33
+ ```
34
+
35
+ Set `NIMBLE_API_KEY` as a Worker secret. The agent also accepts an ephemeral
36
+ per-request key override; that value is never persisted in its recovery
37
+ snapshot or run ledger.
38
+
39
+ If a Worker serves multiple authenticated principals, route each trusted
40
+ principal to a separately named `NimbleRunAgent` instance. Do not multiplex
41
+ untrusted users into one instance: its deterministic create deduplication and
42
+ durable ledger are intentionally scoped to the Durable Object instance. HTTP
43
+ authentication and trusted-principal derivation remain the consuming Worker's
44
+ responsibility.
45
+
46
+ ## Lifecycle guarantees
47
+
48
+ - Create calls use `maxRetries: 0` to avoid duplicate billable work.
49
+ - A deterministic key deduplicates equivalent create requests.
50
+ - Durable run IDs are recorded before polling begins.
51
+ - Safe status/result reads use bounded retries.
52
+ - Recovery resumes persisted runs and fails closed when an ephemeral key is no
53
+ longer available.
54
+ - Production polling defaults to 10 seconds and rejects shorter intervals.
55
+ - `startRun()` accepts work asynchronously, so its first response can have a
56
+ `null` run ID; read lifecycle status to obtain the durable agent/run IDs.
57
+ - Background polling has a five-minute local budget. If the provider run is
58
+ still active, later status/result reads reconcile it with safe GETs rather
59
+ than treating the local timeout as a provider failure.
60
+
61
+ The package owns resumability and Agent API V2 lifecycle behavior. HTTP auth,
62
+ UI/playgrounds, hosted deployments, and AI Gateway transport remain concerns
63
+ of the consuming Worker and are intentionally outside this repository.
64
+
65
+ ## Development
66
+
67
+ ```sh
68
+ npm ci
69
+ npm run check
70
+ ```
71
+
72
+ ## License
73
+
74
+ Apache-2.0
@@ -0,0 +1,345 @@
1
+ import { Agent, FiberRecoveryContext, FiberRecoveryResult } from 'agents';
2
+
3
+ /**
4
+ * Typed Nimble Agent API V2 adapter.
5
+ *
6
+ * Create uses @nimble-way/nimble-js 1.2.0's generated types with
7
+ * maxRetries=0 for BOTH create routes: `client.agents.runs.create(agentId, ...)`
8
+ * (persistent agent) and `client.agents.run(...)` (agentless, POST
9
+ * /v2/agents/runs — 1.2.0 exposes this as `AgentRunParams`/`AgentRunResponse`).
10
+ * Safe status/result GETs retain the bounded adapter-owned backoff policy.
11
+ */
12
+ declare const NIMBLE_CLIENT_SOURCE = "cloudflare-agents";
13
+ declare const DEFAULT_BASE_URL = "https://sdk.nimbleway.com";
14
+ declare const TERMINAL_STATES: readonly ["completed", "failed", "cancelled"];
15
+ declare const ACTIVE_STATES: readonly ["queued", "running"];
16
+ type TerminalStatus = (typeof TERMINAL_STATES)[number];
17
+ type ActiveStatus = (typeof ACTIVE_STATES)[number];
18
+ /** Statuses this adapter recognizes without inventing semantics for the rest. */
19
+ type KnownRunStatus = ActiveStatus | TerminalStatus;
20
+ type Effort = "low" | "medium" | "high" | "x-high" | "max";
21
+ type SelectableEffort = Effort;
22
+ type UseCase = "research" | "enrichment" | "dataset_building";
23
+ declare const SELECTABLE_EFFORTS: readonly ["low", "medium", "high", "x-high", "max"];
24
+ declare const NIMBLE_ENTERPRISE_CONTACT_URL = "https://www.nimbleway.com/contact";
25
+ declare class GatedFeatureError extends Error {
26
+ readonly feature = "effort:max";
27
+ readonly closestAvailable = "x-high";
28
+ readonly engagementUrl = "https://www.nimbleway.com/contact";
29
+ constructor();
30
+ }
31
+ interface SourceGroup {
32
+ title: string;
33
+ domains: string[];
34
+ order?: number;
35
+ }
36
+ interface SourceGuidance {
37
+ allow?: SourceGroup[];
38
+ block?: SourceGroup[];
39
+ prioritize?: string | null;
40
+ avoid?: string | null;
41
+ }
42
+ interface CreateRunRequest {
43
+ input: string;
44
+ agent_name?: string | null;
45
+ effort?: SelectableEffort;
46
+ input_data?: Record<string, unknown> | Array<Record<string, unknown>>;
47
+ output_schema?: Record<string, unknown>;
48
+ previous_interaction_id?: string | null;
49
+ skill?: string | null;
50
+ sources?: SourceGuidance | null;
51
+ use_case?: UseCase | null;
52
+ enable_events?: boolean;
53
+ }
54
+ interface NimbleRun {
55
+ id: string;
56
+ status: string;
57
+ web_search_agent_id?: string;
58
+ [key: string]: unknown;
59
+ }
60
+ /**
61
+ * Types below mirror @nimble-way/nimble-js 1.2.0's actual result envelope
62
+ * (resources/agents/runs.d.ts RunResultResponse), NOT a guessed flat shape.
63
+ * A completed run's result is `{ output: { content, trust, type }, run }`;
64
+ * a failed run's result is `{ error: { message, ref_id }, run }`. There is
65
+ * no top-level `text`/`json`/`citations`/`trust`/`claims` — those fields,
66
+ * when present, live under `output` and `output.trust`.
67
+ */
68
+ interface NimbleTrustCitation {
69
+ url: string;
70
+ title?: string | null;
71
+ excerpts?: string[] | null;
72
+ }
73
+ interface NimbleTrustClaim {
74
+ confidence: "high" | "medium" | "low" | "pre_existing";
75
+ reasoning: string;
76
+ citations: NimbleTrustCitation[];
77
+ /** Text output: callout marker in the prose. JSON output: JSON path instead. */
78
+ callout?: number;
79
+ path?: string;
80
+ }
81
+ interface NimbleTrustSource {
82
+ type: "primary" | "secondary";
83
+ url: string;
84
+ title?: string | null;
85
+ }
86
+ interface NimbleTrust {
87
+ confidence: "high" | "medium" | "low" | "pre_existing";
88
+ reasoning: string;
89
+ claims: NimbleTrustClaim[];
90
+ sources: NimbleTrustSource[];
91
+ }
92
+ /** Normalized, adapter-facing view of a run's result — never the raw envelope shape. */
93
+ interface NimbleResult {
94
+ outputType: "text" | "json" | "unknown";
95
+ /** Prose for text output, structured data for json output. Null for a failed run. */
96
+ content: string | Record<string, unknown> | unknown[] | null;
97
+ /** output.trust when the run completed with trust metadata; null for a failed run. */
98
+ trust: NimbleTrust | null;
99
+ /** Structured error when the run failed; null for a completed run. */
100
+ error: {
101
+ message: string;
102
+ refId?: string;
103
+ } | null;
104
+ }
105
+ /**
106
+ * Normalizes the raw fetched result body into NimbleResult. Handles both
107
+ * documented envelope shapes (`{output,...}` completed, `{error,...}`
108
+ * failed) — matches @nimble-way/nimble-js 1.2.0's RunResultResponse exactly,
109
+ * not a superset guess.
110
+ */
111
+ declare function normalizeRunResult(raw: unknown): NimbleResult;
112
+ declare class NimbleAgentAPIError extends Error {
113
+ readonly statusCode: number | undefined;
114
+ readonly refId: string | undefined;
115
+ readonly retryAfterSeconds: number | undefined;
116
+ constructor(message: string, opts?: {
117
+ statusCode?: number;
118
+ refId?: string;
119
+ retryAfterSeconds?: number;
120
+ });
121
+ }
122
+ /**
123
+ * A write (create) may or may not have reached Nimble before the transport
124
+ * failed, or Nimble returned a 5xx that gives no signal either way. Never
125
+ * retried automatically — the caller must reconcile (list runs for the
126
+ * agent, or GET the run/agent if an id is already known) before deciding
127
+ * whether to submit a new create. Do NOT resubmit blindly.
128
+ */
129
+ declare class AmbiguousCreateError extends NimbleAgentAPIError {
130
+ }
131
+ /** Nimble returned 429 on a create. Never retried per contract. */
132
+ declare class CreateRateLimitedError extends NimbleAgentAPIError {
133
+ }
134
+ declare class PollTimeoutError extends NimbleAgentAPIError {
135
+ }
136
+ interface RetryPolicy {
137
+ maxAttempts: number;
138
+ baseDelayMs: number;
139
+ maxDelayMs: number;
140
+ }
141
+ declare const DEFAULT_RETRY_POLICY: RetryPolicy;
142
+ interface NimbleClientOptions {
143
+ apiKey: string;
144
+ baseUrl?: string;
145
+ retryPolicy?: RetryPolicy;
146
+ fetchImpl?: typeof fetch;
147
+ sleep?: (ms: number) => Promise<void>;
148
+ }
149
+ /**
150
+ * Adapter for the three Agent API V2 endpoints this starter uses: SDK-backed
151
+ * typed create, plus adapter-owned status/result GETs.
152
+ *
153
+ * Invariant: create is NEVER retried automatically, regardless of status
154
+ * code (including 429). Safe (GET) reads use bounded backoff honoring
155
+ * Retry-After.
156
+ */
157
+ declare class NimbleAgentClient {
158
+ private readonly apiKey;
159
+ private readonly baseUrl;
160
+ private readonly retryPolicy;
161
+ private readonly fetchImpl;
162
+ private readonly sleep;
163
+ constructor(opts: NimbleClientOptions);
164
+ private headers;
165
+ private backoffMs;
166
+ /**
167
+ * POST /v2/agents/{agent_id}/runs (persistent agent) or POST
168
+ * /v2/agents/runs (agentless, server-provisioned agent) — billable,
169
+ * non-idempotent, NEVER retried. Uses @nimble-way/nimble-js 1.2.0's typed
170
+ * `client.agents.runs.create` / `client.agents.run` with a client
171
+ * configured with maxRetries=0.
172
+ *
173
+ * A definite 429 fails immediately with CreateRateLimitedError — never
174
+ * retried. A transport failure or a 5xx (no signal on whether the write
175
+ * landed) fails with AmbiguousCreateError carrying reconciliation
176
+ * guidance — never resubmitted automatically by this adapter.
177
+ */
178
+ createRun(agentId: string | undefined, body: CreateRunRequest): Promise<NimbleRun>;
179
+ /** GET /v2/agents/{agent_id}/runs/{run_id} — safe to retry with backoff. */
180
+ getRunStatus(agentId: string, runId: string): Promise<NimbleRun>;
181
+ /**
182
+ * GET /v2/agents/{agent_id}/runs/{run_id}/result — safe to retry with
183
+ * backoff. Normalizes the raw envelope (`{output,...}` / `{error,...}`)
184
+ * into NimbleResult so every caller (agent.ts, the UI) sees a faithful,
185
+ * generic shape instead of guessing at top-level fields.
186
+ */
187
+ getRunResult(agentId: string, runId: string): Promise<NimbleResult>;
188
+ private safeGet;
189
+ }
190
+ /** Fails closed on any status this adapter does not recognize (no invented semantics). */
191
+ declare function classifyStatus(status: string): "active" | "terminal" | "unknown";
192
+
193
+ interface Env {
194
+ NIMBLE_RUN_AGENT: DurableObjectNamespace<NimbleRunAgent>;
195
+ /** Protected server-secret fallback; overridden per-request by an ephemeral user key. */
196
+ NIMBLE_API_KEY?: string;
197
+ NIMBLE_BASE_URL?: string;
198
+ /** Backend Agent API V2 status interval. Defaults to 10s; production values must be >=10s. */
199
+ NIMBLE_POLL_INTERVAL_MS?: string;
200
+ /** Test-only escape hatch for zero/short polling intervals. Never set in production. */
201
+ NIMBLE_TEST_ALLOW_SHORT_POLL_INTERVALS?: string;
202
+ }
203
+ interface RunLedgerRow {
204
+ agentId: string;
205
+ runId: string | null;
206
+ status: string;
207
+ createdAt: number;
208
+ updatedAt: number;
209
+ pollAttempts: number;
210
+ fiberIdempotencyKey: string;
211
+ recoveredCount: number;
212
+ lastError: string | null;
213
+ /** True if this run was created/polled using an ephemeral per-user key override. */
214
+ usedOverrideKey: boolean;
215
+ }
216
+ interface AgentState {
217
+ runs: Record<string, RunLedgerRow>;
218
+ }
219
+ interface StartRunInput {
220
+ /** Omit to use POST /v2/agents/runs and let Nimble provision the WSA. */
221
+ nimbleAgentId?: string;
222
+ request: CreateRunRequest;
223
+ /** Ephemeral per-user API key override; falls back to env.NIMBLE_API_KEY. */
224
+ apiKeyOverride?: string;
225
+ }
226
+ interface StartRunOutcome {
227
+ fiberKey: string;
228
+ accepted: boolean;
229
+ runId: string | null;
230
+ status: string;
231
+ }
232
+ interface StatusOutcome {
233
+ fiberKey: string;
234
+ runId: string | null;
235
+ /** Nimble's durable web_search_agent_id (wsa_...), distinct from runId (task_run_...). */
236
+ agentId: string | null;
237
+ status: string;
238
+ pollAttempts: number;
239
+ recoveredCount: number;
240
+ lastError: string | null;
241
+ }
242
+ interface ResultOutcome {
243
+ fiberKey: string;
244
+ runId: string | null;
245
+ /** Nimble's durable web_search_agent_id (wsa_...), distinct from runId (task_run_...). */
246
+ agentId: string | null;
247
+ status: string;
248
+ result: NimbleResult | null;
249
+ error: string | null;
250
+ }
251
+ declare const DEFAULT_POLL_INTERVAL_MS = 10000;
252
+ declare function resolvePollIntervalMs(env: Pick<Env, "NIMBLE_POLL_INTERVAL_MS" | "NIMBLE_TEST_ALLOW_SHORT_POLL_INTERVALS">): number;
253
+ /**
254
+ * Deterministic idempotency key: the SAME full create request (every field
255
+ * that affects what Nimble is billed to do — input, agent_name, effort,
256
+ * enable_events, input_data, output_schema, previous_interaction_id, skill,
257
+ * sources, and use_case) never issues a second create.
258
+ *
259
+ * Design notes:
260
+ * - Covers the FULL request, not a subset. Two requests differing only in
261
+ * `effort` or `enable_events` are billed differently by Nimble and must
262
+ * dedupe to DIFFERENT keys, not collapse into "same run".
263
+ * - Uses SHA-256 (Web Crypto, available in workerd) over a canonical JSON
264
+ * encoding, not a 32-bit rolling hash — a 32-bit hash has a ~50% collision
265
+ * chance past ~77k distinct requests (birthday bound) sharing one Durable
266
+ * Object's ledger, which is within reach for a long-lived agent session
267
+ * and would silently merge two unrelated runs into one idempotency key.
268
+ * SHA-256's 256-bit space makes accidental collision practically zero.
269
+ * - Deliberately excludes `apiKeyOverride`: the idempotency key identifies
270
+ * "what work", not "which credential authorized it" — the same task run
271
+ * twice with two different per-user keys should still dedupe (whoever
272
+ * asked first wins the create; see "Recovery for override-backed runs"
273
+ * for how the credential itself is handled separately and never persisted).
274
+ */
275
+ declare function deriveFiberKey(nimbleAgentId: string | undefined, request: CreateRunRequest): Promise<string>;
276
+ /**
277
+ * Durable Object-backed Agent owning one Nimble Agent API V2 run lifecycle
278
+ * per fiber key. Uses agents@0.20.0's startFiber() for durable acceptance,
279
+ * dedupe, and crash recovery.
280
+ */
281
+ declare class NimbleRunAgent extends Agent<Env, AgentState> {
282
+ initialState: AgentState;
283
+ private client;
284
+ private upsertLedger;
285
+ /**
286
+ * "start" tool. Never retries the create; deduplicates via startFiber's
287
+ * idempotencyKey so a duplicate call with the same (agent_id, input) joins
288
+ * the existing run instead of billing a second create.
289
+ */
290
+ startRun(input: StartRunInput): Promise<StartRunOutcome>;
291
+ private pollUntilTerminal;
292
+ /**
293
+ * Self-healing reconciliation for a non-terminal ledger row. The
294
+ * background fiber's own poll loop (pollUntilTerminal) waits on a plain
295
+ * `await new Promise(setTimeout(...))`, which does NOT survive a Durable
296
+ * Object eviction/hibernation — unlike a DO alarm, nothing wakes the
297
+ * isolate to resolve that timer, so if the fiber is evicted while
298
+ * suspended there, the whole callback is gone and onFiberRecovered's
299
+ * automatic resume is the only thing that can restart it. If that SDK
300
+ * hook does not fire (or fires without effect) for some reason, the
301
+ * ledger is otherwise stuck forever with a valid runId and no way
302
+ * forward. This is a general, run-agnostic repair: any time a caller
303
+ * reads status/result for a row that looks stale, do ONE safe GET
304
+ * ourselves to bring the ledger current — never a create, and only ever
305
+ * a GET the caller is already authorized to make.
306
+ *
307
+ * Skips (leaves the ledger untouched) when: there is no runId yet, the
308
+ * row is already terminal, the row is "recovery-blocked" (that state
309
+ * requires the explicit resumeWithOverride() flow, not a background
310
+ * reconcile), the row needs an override the caller did not supply, or
311
+ * less than one poll interval has passed since the last update (avoids
312
+ * turning every status read into an extra live GET for a row that is
313
+ * still being actively polled by a healthy fiber).
314
+ */
315
+ private reconcileIfStale;
316
+ /**
317
+ * Called automatically by the SDK on the next activation if this Agent
318
+ * was evicted mid-fiber. Resumes polling from the stashed run id — never
319
+ * re-issues a create.
320
+ */
321
+ onFiberRecovered(ctx: FiberRecoveryContext): Promise<void | FiberRecoveryResult>;
322
+ /**
323
+ * "status" tool. `apiKeyOverride` is optional and only used to reconcile
324
+ * an override-backed row that has gone stale (see reconcileIfStale) — it
325
+ * is never required just to read the ledger's last-known state.
326
+ */
327
+ getRunLifecycleStatus(fiberKey: string, apiKeyOverride?: string): Promise<StatusOutcome>;
328
+ /**
329
+ * Explicit operator recovery for an already-created run. Performs one
330
+ * safe provider GET regardless of the ordinary poll throttle, then returns
331
+ * the durable ledger state. This can never issue a create.
332
+ */
333
+ reconcileRunLifecycleStatus(fiberKey: string, apiKeyOverride?: string): Promise<StatusOutcome>;
334
+ /** "result" tool. Fetches the typed Nimble result once the run is terminal. */
335
+ getRunTypedResult(fiberKey: string, apiKeyOverride?: string): Promise<ResultOutcome>;
336
+ /**
337
+ * Resumes a "recovery-blocked" override-backed run once the caller
338
+ * re-supplies the same (or an equivalently authorized) API key. Never
339
+ * used to retry the create — only to resume polling an already-created
340
+ * run. See onFiberRecovered's fail-closed handling above.
341
+ */
342
+ resumeWithOverride(fiberKey: string, apiKeyOverride: string): Promise<StatusOutcome>;
343
+ }
344
+
345
+ export { ACTIVE_STATES, type ActiveStatus, type AgentState, AmbiguousCreateError, CreateRateLimitedError, type CreateRunRequest, DEFAULT_BASE_URL, DEFAULT_POLL_INTERVAL_MS, DEFAULT_RETRY_POLICY, type Effort, type Env, GatedFeatureError, type KnownRunStatus, NIMBLE_CLIENT_SOURCE, NIMBLE_ENTERPRISE_CONTACT_URL, NimbleAgentAPIError, NimbleAgentClient, type NimbleClientOptions, type NimbleResult, type NimbleRun, NimbleRunAgent, type NimbleTrust, type NimbleTrustCitation, type NimbleTrustClaim, type NimbleTrustSource, PollTimeoutError, type ResultOutcome, type RetryPolicy, type RunLedgerRow, SELECTABLE_EFFORTS, type SelectableEffort, type SourceGroup, type SourceGuidance, type StartRunInput, type StartRunOutcome, type StatusOutcome, TERMINAL_STATES, type TerminalStatus, type UseCase, classifyStatus, deriveFiberKey, normalizeRunResult, resolvePollIntervalMs };
package/dist/index.js ADDED
@@ -0,0 +1,698 @@
1
+ // src/agent.ts
2
+ import { Agent } from "agents";
3
+
4
+ // src/nimble-client.ts
5
+ import Nimble, { APIConnectionError, APIError } from "@nimble-way/nimble-js";
6
+ var NIMBLE_CLIENT_SOURCE = "cloudflare-agents";
7
+ var DEFAULT_BASE_URL = "https://sdk.nimbleway.com";
8
+ var TERMINAL_STATES = ["completed", "failed", "cancelled"];
9
+ var ACTIVE_STATES = ["queued", "running"];
10
+ var SELECTABLE_EFFORTS = ["low", "medium", "high", "x-high", "max"];
11
+ var NIMBLE_ENTERPRISE_CONTACT_URL = "https://www.nimbleway.com/contact";
12
+ var GatedFeatureError = class extends Error {
13
+ feature = "effort:max";
14
+ closestAvailable = "x-high";
15
+ engagementUrl = NIMBLE_ENTERPRISE_CONTACT_URL;
16
+ constructor() {
17
+ super(
18
+ `Nimble Max effort is a coming-soon custom-budget feature. Contact Nimble to enable it: ${NIMBLE_ENTERPRISE_CONTACT_URL}. To continue now, explicitly select x-high; this integration never silently substitutes it.`
19
+ );
20
+ this.name = "GatedFeatureError";
21
+ }
22
+ };
23
+ function normalizeRunResult(raw) {
24
+ const body = raw && typeof raw === "object" ? raw : {};
25
+ const output = body.output;
26
+ if (output && typeof output === "object") {
27
+ const outputBody = output;
28
+ const trustRaw = outputBody.trust;
29
+ const trust = trustRaw && typeof trustRaw === "object" ? trustRaw : null;
30
+ const outputType = outputBody.type === "json" ? "json" : outputBody.type === "text" ? "text" : "unknown";
31
+ return {
32
+ outputType,
33
+ content: outputBody.content ?? null,
34
+ trust,
35
+ error: null
36
+ };
37
+ }
38
+ const errorRaw = body.error;
39
+ if (errorRaw && typeof errorRaw === "object") {
40
+ const errorBody = errorRaw;
41
+ if (typeof errorBody.message === "string") {
42
+ return {
43
+ outputType: "unknown",
44
+ content: null,
45
+ trust: null,
46
+ error: {
47
+ message: errorBody.message,
48
+ refId: typeof errorBody.ref_id === "string" ? errorBody.ref_id : void 0
49
+ }
50
+ };
51
+ }
52
+ }
53
+ return { outputType: "unknown", content: null, trust: null, error: null };
54
+ }
55
+ var NimbleAgentAPIError = class extends Error {
56
+ statusCode;
57
+ refId;
58
+ retryAfterSeconds;
59
+ constructor(message, opts = {}) {
60
+ super(message);
61
+ this.name = "NimbleAgentAPIError";
62
+ this.statusCode = opts.statusCode;
63
+ this.refId = opts.refId;
64
+ this.retryAfterSeconds = opts.retryAfterSeconds;
65
+ }
66
+ };
67
+ var AmbiguousCreateError = class extends NimbleAgentAPIError {
68
+ };
69
+ var AMBIGUOUS_RECONCILIATION_GUIDANCE = "Do not resubmit automatically. Reconcile first: list runs for the agent (or GET the run/agent by id if you already captured one) to check whether the earlier create actually landed, then decide whether a new create is needed.";
70
+ var CreateRateLimitedError = class extends NimbleAgentAPIError {
71
+ };
72
+ var PollTimeoutError = class extends NimbleAgentAPIError {
73
+ };
74
+ var DEFAULT_RETRY_POLICY = {
75
+ maxAttempts: 3,
76
+ baseDelayMs: 500,
77
+ maxDelayMs: 8e3
78
+ };
79
+ var AGENT_ID_RE = /^wsa_[A-Za-z0-9_-]+$/;
80
+ var RUN_ID_RE = /^task_run_[A-Za-z0-9_-]+$/;
81
+ function requireId(value, pattern, label) {
82
+ if (!pattern.test(value)) {
83
+ throw new Error(`${label} has an unexpected format`);
84
+ }
85
+ return value;
86
+ }
87
+ function parseRetryAfter(headers) {
88
+ const value = headers.get("Retry-After");
89
+ if (!value) return void 0;
90
+ const asNumber = Number(value);
91
+ if (Number.isFinite(asNumber)) return Math.max(0, asNumber);
92
+ const asDate = Date.parse(value);
93
+ if (Number.isNaN(asDate)) return void 0;
94
+ return Math.max(0, (asDate - Date.now()) / 1e3);
95
+ }
96
+ async function safeErrorFromResponse(response) {
97
+ let message = `Nimble request failed with HTTP ${response.status}`;
98
+ let refId;
99
+ try {
100
+ const body = await response.clone().json();
101
+ const candidate = body?.message ?? body?.detail ?? body?.msg;
102
+ if (typeof candidate === "string" && candidate.trim()) {
103
+ message = candidate.trim().slice(0, 500);
104
+ } else if (candidate && typeof candidate === "object") {
105
+ const nested = candidate;
106
+ const nestedMessage = nested.message ?? nested.detail ?? nested.msg;
107
+ if (typeof nestedMessage === "string" && nestedMessage.trim()) {
108
+ message = nestedMessage.trim().slice(0, 500);
109
+ }
110
+ }
111
+ const candidateRef = body?.ref_id ?? body?.task_id;
112
+ if (typeof candidateRef === "string") refId = candidateRef.slice(0, 200);
113
+ } catch {
114
+ }
115
+ return new NimbleAgentAPIError(message, {
116
+ statusCode: response.status,
117
+ refId,
118
+ retryAfterSeconds: parseRetryAfter(response.headers)
119
+ });
120
+ }
121
+ function sdkErrorMessage(error) {
122
+ const body = error.error;
123
+ const candidate = body?.message ?? body?.detail ?? body?.msg;
124
+ if (typeof candidate === "string" && candidate.trim()) {
125
+ return candidate.trim().slice(0, 500);
126
+ }
127
+ if (Array.isArray(candidate)) {
128
+ const issues = candidate.slice(0, 3).map((issue) => {
129
+ if (!issue || typeof issue !== "object") return null;
130
+ const entry = issue;
131
+ const location = Array.isArray(entry.loc) ? entry.loc.filter((part) => typeof part === "string" || typeof part === "number").join(".") : "request";
132
+ const message = typeof entry.msg === "string" ? entry.msg : "validation failed";
133
+ return `${location || "request"}: ${message}`;
134
+ }).filter((issue) => Boolean(issue));
135
+ if (issues.length) return issues.join("; ").slice(0, 500);
136
+ } else if (candidate && typeof candidate === "object") {
137
+ const nested = candidate;
138
+ const nestedMessage = nested.message ?? nested.detail ?? nested.msg;
139
+ if (typeof nestedMessage === "string" && nestedMessage.trim()) {
140
+ return nestedMessage.trim().slice(0, 500);
141
+ }
142
+ }
143
+ return `Nimble request failed with HTTP ${error.status ?? "unknown"}`;
144
+ }
145
+ function sdkErrorRefId(error) {
146
+ const body = error.error;
147
+ const candidate = body?.ref_id ?? body?.task_id;
148
+ return typeof candidate === "string" ? candidate.slice(0, 200) : void 0;
149
+ }
150
+ var NimbleAgentClient = class {
151
+ apiKey;
152
+ baseUrl;
153
+ retryPolicy;
154
+ fetchImpl;
155
+ sleep;
156
+ constructor(opts) {
157
+ if (!opts.apiKey) throw new Error("apiKey is required");
158
+ this.apiKey = opts.apiKey;
159
+ this.baseUrl = opts.baseUrl ?? DEFAULT_BASE_URL;
160
+ this.retryPolicy = opts.retryPolicy ?? DEFAULT_RETRY_POLICY;
161
+ const fetchImpl = opts.fetchImpl ?? fetch;
162
+ this.fetchImpl = (input, init) => fetchImpl(input, init);
163
+ this.sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
164
+ }
165
+ headers() {
166
+ return {
167
+ Authorization: `Bearer ${this.apiKey}`,
168
+ Accept: "application/json",
169
+ "Content-Type": "application/json",
170
+ "X-Client-Source": NIMBLE_CLIENT_SOURCE
171
+ };
172
+ }
173
+ backoffMs(attempt, retryAfterSeconds) {
174
+ if (retryAfterSeconds !== void 0) {
175
+ return Math.min(retryAfterSeconds * 1e3, this.retryPolicy.maxDelayMs);
176
+ }
177
+ const exponential = this.retryPolicy.baseDelayMs * 2 ** (attempt - 1);
178
+ return Math.min(exponential, this.retryPolicy.maxDelayMs);
179
+ }
180
+ /**
181
+ * POST /v2/agents/{agent_id}/runs (persistent agent) or POST
182
+ * /v2/agents/runs (agentless, server-provisioned agent) — billable,
183
+ * non-idempotent, NEVER retried. Uses @nimble-way/nimble-js 1.2.0's typed
184
+ * `client.agents.runs.create` / `client.agents.run` with a client
185
+ * configured with maxRetries=0.
186
+ *
187
+ * A definite 429 fails immediately with CreateRateLimitedError — never
188
+ * retried. A transport failure or a 5xx (no signal on whether the write
189
+ * landed) fails with AmbiguousCreateError carrying reconciliation
190
+ * guidance — never resubmitted automatically by this adapter.
191
+ */
192
+ async createRun(agentId, body) {
193
+ if (agentId) requireId(agentId, AGENT_ID_RE, "agent_id");
194
+ if (!body.input?.trim()) throw new Error("input is required");
195
+ const requestedEffort = body.effort;
196
+ if (requestedEffort === "max") {
197
+ throw new GatedFeatureError();
198
+ }
199
+ if (requestedEffort !== void 0 && !(typeof requestedEffort === "string" && SELECTABLE_EFFORTS.includes(requestedEffort))) {
200
+ throw new Error("effort must be one of: low, medium, high, x-high, max");
201
+ }
202
+ const client = new Nimble({
203
+ apiKey: this.apiKey,
204
+ baseURL: this.baseUrl,
205
+ clientSource: NIMBLE_CLIENT_SOURCE,
206
+ fetch: this.fetchImpl,
207
+ maxRetries: 0
208
+ });
209
+ let run;
210
+ try {
211
+ if (agentId) {
212
+ run = await client.agents.runs.create(agentId, {
213
+ enable_events: false,
214
+ ...body
215
+ });
216
+ } else {
217
+ run = await client.agents.run({
218
+ enable_events: false,
219
+ ...body
220
+ });
221
+ }
222
+ } catch (err) {
223
+ if (err instanceof NimbleAgentAPIError || err instanceof Error && err.name === "NimbleAgentAPIError" && "statusCode" in err) {
224
+ throw err;
225
+ }
226
+ if (err instanceof APIConnectionError) {
227
+ throw new AmbiguousCreateError(
228
+ `Nimble create-run outcome is unknown after a transport failure. ${AMBIGUOUS_RECONCILIATION_GUIDANCE}`,
229
+ {}
230
+ );
231
+ }
232
+ if (err instanceof APIError) {
233
+ const statusCode = err.status;
234
+ const message = sdkErrorMessage(err);
235
+ const refId = sdkErrorRefId(err);
236
+ const retryAfterSeconds = err.headers ? parseRetryAfter(err.headers) : void 0;
237
+ if (statusCode === 429) {
238
+ throw new CreateRateLimitedError(message, {
239
+ statusCode,
240
+ refId,
241
+ retryAfterSeconds
242
+ });
243
+ }
244
+ if (statusCode !== void 0 && statusCode >= 500) {
245
+ throw new AmbiguousCreateError(
246
+ `Nimble create-run returned HTTP ${statusCode} (${message}); outcome is unknown. ${AMBIGUOUS_RECONCILIATION_GUIDANCE}`,
247
+ { statusCode, refId, retryAfterSeconds }
248
+ );
249
+ }
250
+ throw new NimbleAgentAPIError(message, {
251
+ statusCode,
252
+ refId,
253
+ retryAfterSeconds
254
+ });
255
+ }
256
+ throw new AmbiguousCreateError(
257
+ `Nimble create-run outcome is unknown after a transport failure. ${AMBIGUOUS_RECONCILIATION_GUIDANCE}`,
258
+ {}
259
+ );
260
+ }
261
+ requireId(String(run.id ?? ""), RUN_ID_RE, "created run id");
262
+ const resolvedAgentId = requireId(
263
+ String(run.web_search_agent_id ?? agentId ?? ""),
264
+ AGENT_ID_RE,
265
+ "created agent id"
266
+ );
267
+ if (agentId && resolvedAgentId !== agentId) {
268
+ throw new NimbleAgentAPIError(
269
+ `Nimble create-run returned web_search_agent_id ${resolvedAgentId}, which does not match the requested agent_id ${agentId}`
270
+ );
271
+ }
272
+ return { ...run };
273
+ }
274
+ /** GET /v2/agents/{agent_id}/runs/{run_id} — safe to retry with backoff. */
275
+ async getRunStatus(agentId, runId) {
276
+ requireId(agentId, AGENT_ID_RE, "agent_id");
277
+ requireId(runId, RUN_ID_RE, "run_id");
278
+ return this.safeGet(`${this.baseUrl}/v2/agents/${agentId}/runs/${runId}`);
279
+ }
280
+ /**
281
+ * GET /v2/agents/{agent_id}/runs/{run_id}/result — safe to retry with
282
+ * backoff. Normalizes the raw envelope (`{output,...}` / `{error,...}`)
283
+ * into NimbleResult so every caller (agent.ts, the UI) sees a faithful,
284
+ * generic shape instead of guessing at top-level fields.
285
+ */
286
+ async getRunResult(agentId, runId) {
287
+ requireId(agentId, AGENT_ID_RE, "agent_id");
288
+ requireId(runId, RUN_ID_RE, "run_id");
289
+ const raw = await this.safeGet(`${this.baseUrl}/v2/agents/${agentId}/runs/${runId}/result`);
290
+ return normalizeRunResult(raw);
291
+ }
292
+ async safeGet(url) {
293
+ let lastError;
294
+ for (let attempt = 1; attempt <= this.retryPolicy.maxAttempts; attempt++) {
295
+ let response;
296
+ try {
297
+ response = await this.fetchImpl(url, { method: "GET", headers: this.headers() });
298
+ } catch {
299
+ if (attempt === this.retryPolicy.maxAttempts) {
300
+ throw new NimbleAgentAPIError("Nimble request failed after safe retries");
301
+ }
302
+ await this.sleep(this.backoffMs(attempt, void 0));
303
+ continue;
304
+ }
305
+ if (response.ok) {
306
+ return await response.json();
307
+ }
308
+ const retryable = response.status === 408 || response.status === 429 || response.status >= 500;
309
+ if (retryable && attempt < this.retryPolicy.maxAttempts) {
310
+ lastError = await safeErrorFromResponse(response);
311
+ await this.sleep(this.backoffMs(attempt, lastError.retryAfterSeconds));
312
+ continue;
313
+ }
314
+ throw await safeErrorFromResponse(response);
315
+ }
316
+ throw lastError ?? new NimbleAgentAPIError("Nimble request failed after safe retries");
317
+ }
318
+ };
319
+ function classifyStatus(status) {
320
+ if (ACTIVE_STATES.includes(status)) return "active";
321
+ if (TERMINAL_STATES.includes(status)) return "terminal";
322
+ return "unknown";
323
+ }
324
+
325
+ // src/agent.ts
326
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
327
+ var POLL_DEADLINE_MS = 5 * 6e4;
328
+ function resolvePollIntervalMs(env) {
329
+ const raw = env.NIMBLE_POLL_INTERVAL_MS;
330
+ if (raw === void 0 || raw === "") return DEFAULT_POLL_INTERVAL_MS;
331
+ const intervalMs = Number(raw);
332
+ if (!Number.isSafeInteger(intervalMs) || intervalMs < 0) {
333
+ throw new Error("NIMBLE_POLL_INTERVAL_MS must be a non-negative integer");
334
+ }
335
+ if (intervalMs < DEFAULT_POLL_INTERVAL_MS && env.NIMBLE_TEST_ALLOW_SHORT_POLL_INTERVALS !== "true") {
336
+ throw new Error(
337
+ "NIMBLE_POLL_INTERVAL_MS values below 10000 are test-only; set NIMBLE_TEST_ALLOW_SHORT_POLL_INTERVALS=true only in tests"
338
+ );
339
+ }
340
+ return intervalMs;
341
+ }
342
+ function canonicalize(value) {
343
+ if (Array.isArray(value)) return value.map(canonicalize);
344
+ if (value && typeof value === "object") {
345
+ return Object.fromEntries(
346
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, canonicalize(nested)])
347
+ );
348
+ }
349
+ return value;
350
+ }
351
+ async function deriveFiberKey(nimbleAgentId, request) {
352
+ const canonical = JSON.stringify(
353
+ canonicalize({
354
+ agent_id: nimbleAgentId ?? null,
355
+ input: request.input,
356
+ agent_name: request.agent_name ?? null,
357
+ effort: request.effort ?? null,
358
+ enable_events: request.enable_events ?? false,
359
+ input_data: request.input_data ?? null,
360
+ output_schema: request.output_schema ?? null,
361
+ previous_interaction_id: request.previous_interaction_id ?? null,
362
+ skill: request.skill ?? null,
363
+ sources: request.sources ?? null,
364
+ use_case: request.use_case ?? null
365
+ })
366
+ );
367
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
368
+ const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
369
+ return `nimble-run:${nimbleAgentId ?? "generated"}:${hex}`;
370
+ }
371
+ var NimbleRunAgent = class extends Agent {
372
+ initialState = { runs: {} };
373
+ client(apiKeyOverride) {
374
+ const apiKey = apiKeyOverride || this.env.NIMBLE_API_KEY;
375
+ if (!apiKey) {
376
+ throw new Error(
377
+ "No Nimble API key available: no per-user override and NIMBLE_API_KEY is unset"
378
+ );
379
+ }
380
+ return new NimbleAgentClient({
381
+ apiKey,
382
+ baseUrl: this.env.NIMBLE_BASE_URL
383
+ });
384
+ }
385
+ upsertLedger(fiberKey, patch) {
386
+ const now = Date.now();
387
+ const existing = this.state.runs[fiberKey];
388
+ const row = {
389
+ agentId: existing?.agentId ?? "",
390
+ runId: existing?.runId ?? null,
391
+ status: existing?.status ?? "queued",
392
+ createdAt: existing?.createdAt ?? now,
393
+ updatedAt: now,
394
+ pollAttempts: existing?.pollAttempts ?? 0,
395
+ fiberIdempotencyKey: fiberKey,
396
+ recoveredCount: existing?.recoveredCount ?? 0,
397
+ lastError: existing?.lastError ?? null,
398
+ usedOverrideKey: existing?.usedOverrideKey ?? false,
399
+ ...patch
400
+ };
401
+ this.setState({ runs: { ...this.state.runs, [fiberKey]: row } });
402
+ }
403
+ /**
404
+ * "start" tool. Never retries the create; deduplicates via startFiber's
405
+ * idempotencyKey so a duplicate call with the same (agent_id, input) joins
406
+ * the existing run instead of billing a second create.
407
+ */
408
+ async startRun(input) {
409
+ const fiberKey = await deriveFiberKey(input.nimbleAgentId, input.request);
410
+ const usedOverrideKey = Boolean(input.apiKeyOverride);
411
+ if (!this.state.runs[fiberKey]) {
412
+ this.upsertLedger(fiberKey, {
413
+ agentId: input.nimbleAgentId ?? "",
414
+ status: "queued",
415
+ usedOverrideKey
416
+ });
417
+ }
418
+ const receipt = await this.startFiber(
419
+ fiberKey,
420
+ async (ctx) => {
421
+ let run;
422
+ try {
423
+ const client = this.client(input.apiKeyOverride);
424
+ run = await client.createRun(input.nimbleAgentId, input.request);
425
+ } catch (err) {
426
+ const message = err instanceof Error ? err.message : String(err);
427
+ this.upsertLedger(fiberKey, { status: "failed", lastError: message });
428
+ throw err;
429
+ }
430
+ const resolvedAgentId = String(run.web_search_agent_id ?? input.nimbleAgentId ?? "");
431
+ const snapshot = {
432
+ nimbleAgentId: resolvedAgentId,
433
+ runId: run.id,
434
+ usedOverrideKey
435
+ };
436
+ ctx.stash(snapshot);
437
+ this.upsertLedger(fiberKey, {
438
+ agentId: resolvedAgentId,
439
+ runId: run.id,
440
+ status: run.status
441
+ });
442
+ await this.pollUntilTerminal(fiberKey, resolvedAgentId, run.id, ctx.signal, input.apiKeyOverride);
443
+ },
444
+ { idempotencyKey: fiberKey, metadata: { nimbleAgentId: input.nimbleAgentId ?? "generated" } }
445
+ );
446
+ const row = this.state.runs[fiberKey];
447
+ return {
448
+ fiberKey,
449
+ accepted: receipt.accepted,
450
+ runId: row?.runId ?? null,
451
+ status: row?.status ?? "queued"
452
+ };
453
+ }
454
+ async pollUntilTerminal(fiberKey, nimbleAgentId, runId, signal, apiKeyOverride) {
455
+ const client = this.client(apiKeyOverride);
456
+ const deadline = Date.now() + POLL_DEADLINE_MS;
457
+ const pollIntervalMs = resolvePollIntervalMs(this.env);
458
+ while (!signal.aborted) {
459
+ const run = await client.getRunStatus(nimbleAgentId, runId);
460
+ const status = String(run.status);
461
+ const kind = classifyStatus(status);
462
+ const attempts = (this.state.runs[fiberKey]?.pollAttempts ?? 0) + 1;
463
+ this.upsertLedger(fiberKey, { status, pollAttempts: attempts, lastError: null });
464
+ if (kind === "terminal") return;
465
+ if (kind === "unknown") {
466
+ this.upsertLedger(fiberKey, { status: "failed", lastError: `Unknown run status: ${status}` });
467
+ throw new NimbleAgentAPIError(`Unknown run status: ${status}`, { refId: runId });
468
+ }
469
+ if (Date.now() > deadline) {
470
+ this.upsertLedger(fiberKey, { lastError: "Polling deadline exceeded" });
471
+ throw new PollTimeoutError("Timed out waiting for a terminal Nimble run status", {
472
+ refId: runId
473
+ });
474
+ }
475
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
476
+ }
477
+ }
478
+ /**
479
+ * Self-healing reconciliation for a non-terminal ledger row. The
480
+ * background fiber's own poll loop (pollUntilTerminal) waits on a plain
481
+ * `await new Promise(setTimeout(...))`, which does NOT survive a Durable
482
+ * Object eviction/hibernation — unlike a DO alarm, nothing wakes the
483
+ * isolate to resolve that timer, so if the fiber is evicted while
484
+ * suspended there, the whole callback is gone and onFiberRecovered's
485
+ * automatic resume is the only thing that can restart it. If that SDK
486
+ * hook does not fire (or fires without effect) for some reason, the
487
+ * ledger is otherwise stuck forever with a valid runId and no way
488
+ * forward. This is a general, run-agnostic repair: any time a caller
489
+ * reads status/result for a row that looks stale, do ONE safe GET
490
+ * ourselves to bring the ledger current — never a create, and only ever
491
+ * a GET the caller is already authorized to make.
492
+ *
493
+ * Skips (leaves the ledger untouched) when: there is no runId yet, the
494
+ * row is already terminal, the row is "recovery-blocked" (that state
495
+ * requires the explicit resumeWithOverride() flow, not a background
496
+ * reconcile), the row needs an override the caller did not supply, or
497
+ * less than one poll interval has passed since the last update (avoids
498
+ * turning every status read into an extra live GET for a row that is
499
+ * still being actively polled by a healthy fiber).
500
+ */
501
+ async reconcileIfStale(fiberKey, apiKeyOverride, forceSafeRead = false) {
502
+ const row = this.state.runs[fiberKey];
503
+ if (!row?.runId) return;
504
+ if (classifyStatus(row.status) === "terminal") return;
505
+ if (row.status === "recovery-blocked") return;
506
+ if (row.usedOverrideKey && !apiKeyOverride) return;
507
+ const pollIntervalMs = resolvePollIntervalMs(this.env);
508
+ if (!forceSafeRead && Date.now() - row.updatedAt < pollIntervalMs) return;
509
+ try {
510
+ const client = this.client(apiKeyOverride);
511
+ const run = await client.getRunStatus(row.agentId, row.runId);
512
+ const status = String(run.status);
513
+ const kind = classifyStatus(status);
514
+ const attempts = (this.state.runs[fiberKey]?.pollAttempts ?? 0) + 1;
515
+ if (kind === "unknown") {
516
+ this.upsertLedger(fiberKey, {
517
+ status: "failed",
518
+ pollAttempts: attempts,
519
+ lastError: `Unknown run status: ${status}`
520
+ });
521
+ return;
522
+ }
523
+ this.upsertLedger(fiberKey, { status, pollAttempts: attempts, lastError: null });
524
+ } catch (err) {
525
+ const message = err instanceof Error ? err.message : String(err);
526
+ this.upsertLedger(fiberKey, { lastError: message });
527
+ }
528
+ }
529
+ /**
530
+ * Called automatically by the SDK on the next activation if this Agent
531
+ * was evicted mid-fiber. Resumes polling from the stashed run id — never
532
+ * re-issues a create.
533
+ */
534
+ async onFiberRecovered(ctx) {
535
+ const snapshot = ctx.snapshot;
536
+ const fiberKey = ctx.idempotencyKey ?? ctx.name;
537
+ this.upsertLedger(fiberKey, {
538
+ recoveredCount: (this.state.runs[fiberKey]?.recoveredCount ?? 0) + 1
539
+ });
540
+ if (!snapshot?.runId) {
541
+ this.upsertLedger(fiberKey, {
542
+ status: "failed",
543
+ lastError: "Recovered before create was confirmed; not retried (ambiguous write)"
544
+ });
545
+ return { status: "error", error: "create-outcome-unknown-not-retried" };
546
+ }
547
+ if (snapshot.usedOverrideKey) {
548
+ this.upsertLedger(fiberKey, {
549
+ status: "recovery-blocked",
550
+ lastError: "Recovery blocked: this run was authorized with a per-user API key override that is never persisted and cannot be safely re-supplied automatically. The server fallback key was deliberately NOT used to avoid a cross-account credential switch. Re-supply the same override via the result/status tool to continue."
551
+ });
552
+ return {
553
+ status: "error",
554
+ error: "override-key-recovery-blocked-fail-closed",
555
+ snapshot
556
+ };
557
+ }
558
+ try {
559
+ const controller = new AbortController();
560
+ await this.pollUntilTerminal(
561
+ fiberKey,
562
+ snapshot.nimbleAgentId,
563
+ snapshot.runId,
564
+ controller.signal
565
+ );
566
+ return { status: "completed", snapshot };
567
+ } catch (err) {
568
+ const message = err instanceof Error ? err.message : String(err);
569
+ return { status: "error", error: message, snapshot };
570
+ }
571
+ }
572
+ /**
573
+ * "status" tool. `apiKeyOverride` is optional and only used to reconcile
574
+ * an override-backed row that has gone stale (see reconcileIfStale) — it
575
+ * is never required just to read the ledger's last-known state.
576
+ */
577
+ async getRunLifecycleStatus(fiberKey, apiKeyOverride) {
578
+ await this.reconcileIfStale(fiberKey, apiKeyOverride);
579
+ const inspected = await this.inspectFiberByKey(fiberKey);
580
+ const row = this.state.runs[fiberKey];
581
+ return {
582
+ fiberKey,
583
+ runId: row?.runId ?? null,
584
+ agentId: row?.agentId || null,
585
+ status: row?.status ?? inspected?.status ?? "unknown",
586
+ pollAttempts: row?.pollAttempts ?? 0,
587
+ recoveredCount: row?.recoveredCount ?? 0,
588
+ lastError: row?.lastError ?? null
589
+ };
590
+ }
591
+ /**
592
+ * Explicit operator recovery for an already-created run. Performs one
593
+ * safe provider GET regardless of the ordinary poll throttle, then returns
594
+ * the durable ledger state. This can never issue a create.
595
+ */
596
+ async reconcileRunLifecycleStatus(fiberKey, apiKeyOverride) {
597
+ await this.reconcileIfStale(fiberKey, apiKeyOverride, true);
598
+ return this.getRunLifecycleStatus(fiberKey, apiKeyOverride);
599
+ }
600
+ /** "result" tool. Fetches the typed Nimble result once the run is terminal. */
601
+ async getRunTypedResult(fiberKey, apiKeyOverride) {
602
+ await this.reconcileIfStale(fiberKey, apiKeyOverride);
603
+ const row = this.state.runs[fiberKey];
604
+ if (!row?.runId) {
605
+ return {
606
+ fiberKey,
607
+ runId: null,
608
+ agentId: row?.agentId || null,
609
+ status: row?.status ?? "unknown",
610
+ result: null,
611
+ error: row?.lastError ?? "no run id yet"
612
+ };
613
+ }
614
+ if (row.usedOverrideKey && !apiKeyOverride) {
615
+ return {
616
+ fiberKey,
617
+ runId: row.runId,
618
+ agentId: row.agentId || null,
619
+ status: row.status,
620
+ result: null,
621
+ error: "This run was created with a per-user API key override; re-supply the same override to read its result (the server fallback key is never substituted)."
622
+ };
623
+ }
624
+ if (classifyStatus(row.status) !== "terminal") {
625
+ return {
626
+ fiberKey,
627
+ runId: row.runId,
628
+ agentId: row.agentId || null,
629
+ status: row.status,
630
+ result: null,
631
+ error: row.lastError
632
+ };
633
+ }
634
+ const client = this.client(apiKeyOverride);
635
+ try {
636
+ const result = await client.getRunResult(row.agentId, row.runId);
637
+ const noDiagnostic = row.status !== "completed" && result.error === null && result.outputType === "unknown";
638
+ return {
639
+ fiberKey,
640
+ runId: row.runId,
641
+ agentId: row.agentId || null,
642
+ status: row.status,
643
+ result,
644
+ error: noDiagnostic ? `Nimble run ended with status "${row.status}"; the result endpoint returned no diagnostic.` : result.error?.message ?? null
645
+ };
646
+ } catch (err) {
647
+ if (row.status === "completed") throw err;
648
+ return {
649
+ fiberKey,
650
+ runId: row.runId,
651
+ agentId: row.agentId || null,
652
+ status: row.status,
653
+ result: null,
654
+ error: row.lastError ?? (err instanceof Error ? err.message : "Nimble run failed; result details unavailable")
655
+ };
656
+ }
657
+ }
658
+ /**
659
+ * Resumes a "recovery-blocked" override-backed run once the caller
660
+ * re-supplies the same (or an equivalently authorized) API key. Never
661
+ * used to retry the create — only to resume polling an already-created
662
+ * run. See onFiberRecovered's fail-closed handling above.
663
+ */
664
+ async resumeWithOverride(fiberKey, apiKeyOverride) {
665
+ const row = this.state.runs[fiberKey];
666
+ if (!row?.runId) {
667
+ throw new Error("No run to resume for this fiberKey");
668
+ }
669
+ if (row.status !== "recovery-blocked") {
670
+ return this.getRunLifecycleStatus(fiberKey);
671
+ }
672
+ this.upsertLedger(fiberKey, { status: "running", lastError: null });
673
+ const controller = new AbortController();
674
+ await this.pollUntilTerminal(fiberKey, row.agentId, row.runId, controller.signal, apiKeyOverride);
675
+ return this.getRunLifecycleStatus(fiberKey);
676
+ }
677
+ };
678
+ export {
679
+ ACTIVE_STATES,
680
+ AmbiguousCreateError,
681
+ CreateRateLimitedError,
682
+ DEFAULT_BASE_URL,
683
+ DEFAULT_POLL_INTERVAL_MS,
684
+ DEFAULT_RETRY_POLICY,
685
+ GatedFeatureError,
686
+ NIMBLE_CLIENT_SOURCE,
687
+ NIMBLE_ENTERPRISE_CONTACT_URL,
688
+ NimbleAgentAPIError,
689
+ NimbleAgentClient,
690
+ NimbleRunAgent,
691
+ PollTimeoutError,
692
+ SELECTABLE_EFFORTS,
693
+ TERMINAL_STATES,
694
+ classifyStatus,
695
+ deriveFiberKey,
696
+ normalizeRunResult,
697
+ resolvePollIntervalMs
698
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@nimble-way/cloudflare-agents",
3
+ "version": "0.1.0",
4
+ "description": "Resumable Nimble Agent API V2 tools for Cloudflare Agents",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Nimbleway/cloudflare-agents.git"
10
+ },
11
+ "files": ["dist"],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "sideEffects": false,
21
+ "scripts": {
22
+ "build": "tsup src/index.ts --format esm --dts --clean --external agents --external @nimble-way/nimble-js",
23
+ "typecheck": "tsc --noEmit",
24
+ "lint": "eslint src test --ext .ts",
25
+ "test": "vitest run",
26
+ "check": "npm run lint && npm run typecheck && npm run test && npm run build"
27
+ },
28
+ "dependencies": {
29
+ "@nimble-way/nimble-js": "1.2.0"
30
+ },
31
+ "peerDependencies": {
32
+ "agents": ">=0.20.0 <1"
33
+ },
34
+ "devDependencies": {
35
+ "@cloudflare/vitest-pool-workers": "^0.18.8",
36
+ "@cloudflare/workers-types": "^5.20260722.1",
37
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
38
+ "@typescript-eslint/parser": "^8.0.0",
39
+ "agents": "0.20.0",
40
+ "eslint": "^9.0.0",
41
+ "tsup": "^8.5.0",
42
+ "typescript": "^5.6.0",
43
+ "vitest": "^4.1.0",
44
+ "wrangler": "4.114.0"
45
+ },
46
+ "engines": {
47
+ "node": ">=20"
48
+ }
49
+ }