@gnldev/server 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 +201 -0
- package/README.md +181 -0
- package/dist/edge-errors.d.ts +32 -0
- package/dist/edge-errors.js +71 -0
- package/dist/edge-errors.js.map +1 -0
- package/dist/handler.d.ts +65 -0
- package/dist/handler.js +39 -0
- package/dist/handler.js.map +1 -0
- package/dist/index.d.ts +222 -0
- package/dist/index.js +2121 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +35 -0
- package/dist/node.js +94 -0
- package/dist/node.js.map +1 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +215 -0
- package/dist/openapi.js.map +1 -0
- package/dist/sse.d.ts +57 -0
- package/dist/sse.js +228 -0
- package/dist/sse.js.map +1 -0
- package/package.json +71 -0
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 the
|
|
141
|
+
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 Karaca Yılmaz (https://gnl.dev)
|
|
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,181 @@
|
|
|
1
|
+
# @gnldev/server
|
|
2
|
+
|
|
3
|
+
Exposes the `createGnl` registry as **auto-REST + OpenAPI + SSE**. Every endpoint bottoms out in `runDurable` → the journal, replay and the [at-most-once side-effect guarantee](../durable/README.md#what-never-charged-twice-actually-means) are inherited for free. (The durable counterpart to the common auto-REST pattern.)
|
|
4
|
+
|
|
5
|
+
> Install: `pnpm add @gnldev/server` — or use it from a [repo clone](https://github.com/Karaca7/gnldev): `pnpm install && pnpm -r build`.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @gnldev/server # peer: @gnldev/durable · dep: hono
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createRestApi } from '@gnldev/server';
|
|
13
|
+
import { serve } from '@hono/node-server';
|
|
14
|
+
import { SqliteStorage } from '@gnldev/durable/sqlite';
|
|
15
|
+
|
|
16
|
+
const api = createRestApi({
|
|
17
|
+
journal: new SqliteStorage('runs.db').runs,
|
|
18
|
+
agents: { support: { model: 'anthropic/claude-opus-4-8', tools, guard, maxSteps: 8 } },
|
|
19
|
+
});
|
|
20
|
+
serve({ fetch: api.fetch, port: 3000 }); // on its own port
|
|
21
|
+
// app.mount('/api', api) // inside a Hono app
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Binding it to a Node server
|
|
25
|
+
|
|
26
|
+
`createRestApi` returns a fetch handler — callable, and carrying `.fetch`. On Node, bind it with the
|
|
27
|
+
bridge on this package's own subpath:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { createServer } from 'node:http';
|
|
31
|
+
import { toNodeHandler } from '@gnldev/server/node';
|
|
32
|
+
|
|
33
|
+
express().use('/api', toNodeHandler(api)); // Express
|
|
34
|
+
await fastify.register(middie); fastify.use('/api', toNodeHandler(api)); // Fastify + @fastify/middie
|
|
35
|
+
koa.use(c2k((req, res, _next) => toNodeHandler(api)(req, res))); // Koa + koa-connect
|
|
36
|
+
createServer(toNodeHandler(api)).listen(3000); // node:http
|
|
37
|
+
nestApp.use('/api', toNodeHandler(api)); // Nest (Express or Fastify)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Two rules, both measured on live servers rather than reasoned about:
|
|
41
|
+
|
|
42
|
+
**Bind at the middleware layer, not as a route.** On Fastify the difference is the whole story:
|
|
43
|
+
middleware runs before body parsing, a route runs after it. `fastify.all('/api/*', …)` looks correct,
|
|
44
|
+
passes every GET, and answers 400 to a perfectly good POST — because Fastify's built-in JSON parser
|
|
45
|
+
has already drained the stream.
|
|
46
|
+
|
|
47
|
+
**On Koa, declare the third parameter.** `koa-connect` switches on `fn.length`: a middleware with
|
|
48
|
+
fewer than three parameters is assumed not to terminate the response, so it calls `next()` straight
|
|
49
|
+
after and Koa writes its own 404 over what was already sent — measured, `ERR_HTTP_HEADERS_SENT` and
|
|
50
|
+
404 on every route. Naming `next` without calling it selects the branch that waits, which is what a
|
|
51
|
+
handler that owns the response needs.
|
|
52
|
+
|
|
53
|
+
**Mount before whatever parses request bodies.** A parser that runs first reads the stream to the end
|
|
54
|
+
and hands the result to the framework, not to us. Get it wrong and the bridge says so
|
|
55
|
+
(`body_consumed_upstream`) instead of blaming your request. Your own routes keep the parser: it still
|
|
56
|
+
runs for everything mounted after.
|
|
57
|
+
|
|
58
|
+
## Endpoints (per agent)
|
|
59
|
+
| Method | Path | Description |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| GET | `/agents` | List of registered agent metadata (client/playground selector) |
|
|
62
|
+
| POST | `/agents/:name/run` | Durable run `{runId, prompt\|messages, threadId?, approvals?}` → `{ok, runId, text, interrupts}` |
|
|
63
|
+
| POST | `/agents/:name/stream` | **SSE** streaming run (schema below) |
|
|
64
|
+
| POST | `/agents/:name/resume` | `{runId, approvals?}` — the input is read from the journal |
|
|
65
|
+
| GET | `/runs` · `/runs/:id` | Run summaries / journal timeline |
|
|
66
|
+
| GET | `/openapi.json` | Generated schema |
|
|
67
|
+
| GET | `/health` | Liveness — process is alive. No storage access. **Unauthenticated** |
|
|
68
|
+
| GET | `/ready` | Readiness — can serve traffic; 503 if the journal is unreachable. **Unauthenticated** |
|
|
69
|
+
|
|
70
|
+
### Health checks
|
|
71
|
+
|
|
72
|
+
`/health` and `/ready` answer two different questions, and pointing the wrong probe at the wrong one
|
|
73
|
+
causes the wrong action:
|
|
74
|
+
|
|
75
|
+
- **`/health`** — is the process alive? It touches nothing. A failing *dependency* must not make an
|
|
76
|
+
orchestrator kill and restart a healthy process: restarting it does not reconnect your database, it
|
|
77
|
+
only discards whatever the process still had in flight. Use this for liveness probes.
|
|
78
|
+
- **`/ready`** — can it serve? It reads from the journal, with a 2s budget because an unreachable
|
|
79
|
+
database usually *hangs* rather than refusing. On failure the instance leaves the load balancer while
|
|
80
|
+
staying alive to recover. Use this for readiness/traffic probes.
|
|
81
|
+
|
|
82
|
+
Both are deliberately unauthenticated — probes run before any credential exists, and usually never get
|
|
83
|
+
one. For the same reason they report reachability and nothing else: no agent names, no counts, no
|
|
84
|
+
configuration, and never the underlying error, which for a database failure routinely carries the host,
|
|
85
|
+
database and user. That detail goes to your logs.
|
|
86
|
+
|
|
87
|
+
```yaml
|
|
88
|
+
# Kubernetes
|
|
89
|
+
livenessProbe: { httpGet: { path: /health, port: 3000 } }
|
|
90
|
+
readinessProbe: { httpGet: { path: /ready, port: 3000 } }
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### SSE schema (`/stream`)
|
|
94
|
+
`event` + JSON `data`: `text-delta {text}` · `tool-call {toolCallId,toolName,input}` · `tool-result {...}` · `error {error}` · `interrupt {interrupts[]}` (when the stream ends) · `done {runId,finishReason,usage}`. The same schema is also used in the `@gnldev/studio` playground → [`@gnldev/client`](../client) connects to both ends.
|
|
95
|
+
|
|
96
|
+
### Reconnect recovery (resumable SSE, opt-in)
|
|
97
|
+
Every SSE event carries a deterministic, monotonically increasing `id:` field starting at 0. Calling the
|
|
98
|
+
stream again with the same `runId` is deterministic journal replay (the model/tools do NOT actually run
|
|
99
|
+
again) → fullStream produces the same chunk sequence, so the same event sequence comes out with the SAME ids.
|
|
100
|
+
|
|
101
|
+
The browser's `EventSource` automatically sends the last `id:` it saw via the `Last-Event-ID` header when
|
|
102
|
+
reconnecting after a dropped connection — the server reads this (or `lastEventId` in the body) and for
|
|
103
|
+
events with `id <= lastEventId` it **produces them but does not write them to the client** (production is
|
|
104
|
+
cheap: replay does not call the model/tools). Only events with `id > lastEventId` are sent. If `lastEventId`
|
|
105
|
+
is not given, behavior is identical to before (aside from the added id).
|
|
106
|
+
|
|
107
|
+
## Frontend
|
|
108
|
+
For type-safe calls use [`@gnldev/client`](../client) (core) + `@gnldev/client/react` (hooks). For REST + Studio Playground in one command use [`@gnldev/cli`](../cli) `gnl dev`.
|
|
109
|
+
|
|
110
|
+
## How it works
|
|
111
|
+
Every call to `/run` and `/stream` names one of two things, and exactly one:
|
|
112
|
+
|
|
113
|
+
- **`workKey`** — your name for a unit of work, not for a conversation. The engine derives the run's
|
|
114
|
+
id from it and returns that id in the `X-Gnl-Run-Id` header. Calling again with the same `workKey`
|
|
115
|
+
is routed to the same run: durable replay, side effects once. A `workKey` is a *business name* (the
|
|
116
|
+
invoice being issued, tonight's reconciliation batch) — keep sensitive data out of it, because it
|
|
117
|
+
is reflected in error details and shown on Studio screens. Coming from `thread_id`? There the same
|
|
118
|
+
key means *continue this conversation*; here it means *this is the same job*. A conversation is
|
|
119
|
+
`threadId`, a separate field you can send at the same time.
|
|
120
|
+
- **`runId`** — a raw id you already hold (a resume, a fork, an id you stored).
|
|
121
|
+
|
|
122
|
+
Sending both is a 400: two identities for one call is a question with no honest answer. Sending
|
|
123
|
+
neither is also a 400. `Idempotency-Key` is accepted as a `workKey` alias — it names the work, which
|
|
124
|
+
is what that header has always meant — and it is read only when the body named nothing itself.
|
|
125
|
+
|
|
126
|
+
A `workKey` in the default `resource` scope needs a subject to be unique *within*: name the end user
|
|
127
|
+
(`resourceId`, or an authenticated principal), or the call is refused rather than run for nobody.
|
|
128
|
+
|
|
129
|
+
**How long a `workKey` stays unique:** as long as the run record lives — not a minute longer. Your
|
|
130
|
+
retention window should not be shorter than the longest retry your clients can produce.
|
|
131
|
+
|
|
132
|
+
**Was this call new work, or an answer you already had?** Every response to `/run` and `/stream`
|
|
133
|
+
carries `X-Gnl-Idempotency-Status`: `new` when this call started the run, `replay` when the run had
|
|
134
|
+
already been driven and the answer came from the journal. Nothing re-ran in the `replay` case — no
|
|
135
|
+
model call, no tool, no charge. It is the header to log if you want to know how much of your traffic
|
|
136
|
+
is retries, and the one to assert on if you are verifying that your client's retry logic is actually
|
|
137
|
+
deduplicating.
|
|
138
|
+
|
|
139
|
+
**`run_busy` (409) is a narrower condition than it looks.** It does not mean "this id has been used";
|
|
140
|
+
it means the run is executing **right now**, in this process or another one. A per-run lock is taken
|
|
141
|
+
before execution and renewed by a heartbeat while it lasts, and a concurrent second call — a
|
|
142
|
+
double-click, two tabs, a retry racing its original — is declined instead of executing a second time.
|
|
143
|
+
Three consequences:
|
|
144
|
+
|
|
145
|
+
- The response carries `Retry-After`. The *same* request is correct; it is only early. Honour the
|
|
146
|
+
delay and send it again — it will replay.
|
|
147
|
+
- A process that dies without releasing holds the run only until the lock's TTL expires (default
|
|
148
|
+
300 000 ms), after which a retry is admitted and replays from the journal.
|
|
149
|
+
- A long run does not time itself out of its own lock: the heartbeat keeps it alive, so the TTL bounds
|
|
150
|
+
crash recovery, not run length.
|
|
151
|
+
|
|
152
|
+
A run that has already **finished** does not produce this at all — it replays (see the header above).
|
|
153
|
+
|
|
154
|
+
**Auth (opt-in, but no silent openness in production):** `createRestApi(config, { auth })` accepts an `AuthProvider` (the free `@gnldev/auth` `roleAuth`, or the paid `@gnldev/auth-ee`) or a backward-compatible `{read, write}` pair. If `auth` is not given, endpoints are open; but under `NODE_ENV=production` this is only possible DELIBERATELY, via `allowOpenAccess: true` — without the flag, setup throws a clear error ("auth required in production"). Outside production, a setup without auth works, with a one-time `console.warn` on the first request, so a silent fail-open cannot survive unnoticed.
|
|
155
|
+
|
|
156
|
+
**This server is not for browsers.** It is a backend service your own backend calls; your users reach
|
|
157
|
+
your application, and your application reaches this. Nothing here authenticates an end user, and no
|
|
158
|
+
credential below is safe to ship to a client device.
|
|
159
|
+
|
|
160
|
+
**Which credential your application carries:** `client`, not `admin` — see
|
|
161
|
+
[@gnldev/auth](../auth/README.md) for the four classes. `admin` cancels runs, reads the whole
|
|
162
|
+
organization's history and reads `/usage`; an application that runs agents needs none of that. A
|
|
163
|
+
`client` credential is a whitelist (`agents:run`, `workflow:run`, `run:cancel`, plus reads), so routes
|
|
164
|
+
added in later versions are refused rather than silently granted.
|
|
165
|
+
|
|
166
|
+
**Every `client` request names the end user it acts for.** One application credential serves many
|
|
167
|
+
users, so `resourceId` in the body (or `?resourceId=` on a read) says which one:
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
POST /agents/:name/run { runId, prompt, threadId, resourceId } → 400 without resourceId
|
|
171
|
+
GET /runs?resourceId=u-ayse → only that user's runs
|
|
172
|
+
GET /threads?resourceId=u-ayse → only that user's conversations
|
|
173
|
+
GET /runs/:id?resourceId=u-mehmet → 403 if the run is someone else's
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
That id is what keeps two of your users' conversations, memories and runs apart — the memory layer
|
|
177
|
+
scopes on it. Operator credentials may omit it; they work across the organization by design.
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code by the name of the refusal that prints it. The keys are for readers and for the failure
|
|
3
|
+
* message in the docs check; the VALUES are the contract — the same string in the HTTP body, in the
|
|
4
|
+
* SSE `error` frame, and in whatever the client library re-throws.
|
|
5
|
+
*/
|
|
6
|
+
export declare const EDGE_ERROR_CODES: {
|
|
7
|
+
/** 422, `resumable` — `limits` ceiling met (`server/index.ts`, `sse.ts`, `agui/route.ts`). */
|
|
8
|
+
readonly runLimitExceeded: "run_limit_exceeded";
|
|
9
|
+
/** 422, `resumable` — one tool, the same arguments, no progress (same three sites). */
|
|
10
|
+
readonly toolLoopDetected: "tool_loop_detected";
|
|
11
|
+
/** 403 — the agent is pending, changed since approval, or blocked (`requireAgentApproval`). */
|
|
12
|
+
readonly agentNotApproved: "agent_not_approved";
|
|
13
|
+
/** 403 — `opts.resourceAuth` refused this principal for this agent (the paid FGA layer). */
|
|
14
|
+
readonly resourceDenied: "resource_denied";
|
|
15
|
+
/** 402 — the organization's budget is spent; a NEW run is refused, a resume is not. */
|
|
16
|
+
readonly budgetExceeded: "budget_exceeded";
|
|
17
|
+
/** 401 — an A2A call arrived without the `x-gnl-signature`/`x-gnl-timestamp` pair. */
|
|
18
|
+
readonly a2aSignatureMissing: "a2a_signature_missing";
|
|
19
|
+
/** 401 — the A2A timestamp is outside the ±300s window (replay suspicion). */
|
|
20
|
+
readonly a2aTimestampInvalid: "a2a_timestamp_invalid";
|
|
21
|
+
/** 401 — the A2A HMAC did not verify. */
|
|
22
|
+
readonly a2aSignatureInvalid: "a2a_signature_invalid";
|
|
23
|
+
/** 500 — a body parser upstream of the handler already drained the request (`node.ts`). */
|
|
24
|
+
readonly bodyConsumedUpstream: "body_consumed_upstream";
|
|
25
|
+
};
|
|
26
|
+
export type EdgeErrorCode = (typeof EDGE_ERROR_CODES)[keyof typeof EDGE_ERROR_CODES];
|
|
27
|
+
/**
|
|
28
|
+
* HTTP status per edge code — the docs-checker's source of truth for this family, same contract as
|
|
29
|
+
* `WIRE_ERROR_STATUS` in @gnldev/durable: routes are pinned to these numbers by their tests, docs
|
|
30
|
+
* are pinned to them by `check:errors`, and a new code without an entry fails the gate.
|
|
31
|
+
*/
|
|
32
|
+
export declare const EDGE_ERROR_STATUS: Record<string, number>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The error codes the HTTP EDGE puts on the wire, in one enumerable place.
|
|
2
|
+
//
|
|
3
|
+
// WHY THIS FILE EXISTS. `@gnldev/durable` already owns two maps — `CALLER_CONFLICT_CODES` and
|
|
4
|
+
// `BLOCKED_ERROR_CODES` — and because they are exported values, `scripts/check-error-pages.mjs`
|
|
5
|
+
// enumerates them and nobody has to remember anything: a new engine code with no page under
|
|
6
|
+
// `docs/errors/` turns the build red in the same commit that invents it. The codes written HERE had
|
|
7
|
+
// no such map. They were string literals spelled at the point of response, and the docs check knew
|
|
8
|
+
// about them only through a hand-written list inside the script itself, which said so out loud:
|
|
9
|
+
// "a fourth literal added at an edge tomorrow is caught by nothing".
|
|
10
|
+
//
|
|
11
|
+
// Measured before this file existed: the list named three codes, and the edge was printing NINE. The
|
|
12
|
+
// six it did not know about — both A2A signature refusals, the timestamp one, `resource_denied`,
|
|
13
|
+
// `budget_exceeded` and `body_consumed_upstream` — had shipped with no page at all. The weak spot was
|
|
14
|
+
// not hypothetical and did not take until tomorrow.
|
|
15
|
+
//
|
|
16
|
+
// WHY IN @gnldev/server RATHER THAN @gnldev/durable. These are route-level facts: an HTTP status is
|
|
17
|
+
// attached to each one, and the engine has no routes and no statuses — putting them next to
|
|
18
|
+
// `RunBusyError` would say the engine produces them, and it does not. Server is also the lowest
|
|
19
|
+
// package that every printer shares: `@gnldev/agui` depends on `@gnldev/server` already (it imports
|
|
20
|
+
// `interruptsFromSteps`), so both edges can read the same constant.
|
|
21
|
+
//
|
|
22
|
+
// Deliberately its own module rather than a block inside `index.ts`: the docs check imports the
|
|
23
|
+
// BUILT value, and importing `dist/index.js` would drag Hono and the whole route table into a
|
|
24
|
+
// documentation script. This file imports nothing.
|
|
25
|
+
//
|
|
26
|
+
// ONE PRINTER IS NOT WIRED TO IT, on purpose: `@gnldev/studio`'s `node.ts` carries its own copy of
|
|
27
|
+
// the `body_consumed_upstream` guard and does NOT depend on `@gnldev/server`, so it keeps the
|
|
28
|
+
// literal. The code is the same string and now has a page; adding a package dependency for one
|
|
29
|
+
// constant would be the more expensive of the two mistakes.
|
|
30
|
+
/**
|
|
31
|
+
* Code by the name of the refusal that prints it. The keys are for readers and for the failure
|
|
32
|
+
* message in the docs check; the VALUES are the contract — the same string in the HTTP body, in the
|
|
33
|
+
* SSE `error` frame, and in whatever the client library re-throws.
|
|
34
|
+
*/
|
|
35
|
+
export const EDGE_ERROR_CODES = {
|
|
36
|
+
/** 422, `resumable` — `limits` ceiling met (`server/index.ts`, `sse.ts`, `agui/route.ts`). */
|
|
37
|
+
runLimitExceeded: 'run_limit_exceeded',
|
|
38
|
+
/** 422, `resumable` — one tool, the same arguments, no progress (same three sites). */
|
|
39
|
+
toolLoopDetected: 'tool_loop_detected',
|
|
40
|
+
/** 403 — the agent is pending, changed since approval, or blocked (`requireAgentApproval`). */
|
|
41
|
+
agentNotApproved: 'agent_not_approved',
|
|
42
|
+
/** 403 — `opts.resourceAuth` refused this principal for this agent (the paid FGA layer). */
|
|
43
|
+
resourceDenied: 'resource_denied',
|
|
44
|
+
/** 402 — the organization's budget is spent; a NEW run is refused, a resume is not. */
|
|
45
|
+
budgetExceeded: 'budget_exceeded',
|
|
46
|
+
/** 401 — an A2A call arrived without the `x-gnl-signature`/`x-gnl-timestamp` pair. */
|
|
47
|
+
a2aSignatureMissing: 'a2a_signature_missing',
|
|
48
|
+
/** 401 — the A2A timestamp is outside the ±300s window (replay suspicion). */
|
|
49
|
+
a2aTimestampInvalid: 'a2a_timestamp_invalid',
|
|
50
|
+
/** 401 — the A2A HMAC did not verify. */
|
|
51
|
+
a2aSignatureInvalid: 'a2a_signature_invalid',
|
|
52
|
+
/** 500 — a body parser upstream of the handler already drained the request (`node.ts`). */
|
|
53
|
+
bodyConsumedUpstream: 'body_consumed_upstream',
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* HTTP status per edge code — the docs-checker's source of truth for this family, same contract as
|
|
57
|
+
* `WIRE_ERROR_STATUS` in @gnldev/durable: routes are pinned to these numbers by their tests, docs
|
|
58
|
+
* are pinned to them by `check:errors`, and a new code without an entry fails the gate.
|
|
59
|
+
*/
|
|
60
|
+
export const EDGE_ERROR_STATUS = {
|
|
61
|
+
run_limit_exceeded: 422,
|
|
62
|
+
tool_loop_detected: 422,
|
|
63
|
+
agent_not_approved: 403,
|
|
64
|
+
resource_denied: 403,
|
|
65
|
+
budget_exceeded: 402,
|
|
66
|
+
a2a_signature_missing: 401,
|
|
67
|
+
a2a_timestamp_invalid: 401,
|
|
68
|
+
a2a_signature_invalid: 401,
|
|
69
|
+
body_consumed_upstream: 500,
|
|
70
|
+
};
|
|
71
|
+
//# sourceMappingURL=edge-errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edge-errors.js","sourceRoot":"","sources":["../src/edge-errors.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,EAAE;AACF,8FAA8F;AAC9F,gGAAgG;AAChG,4FAA4F;AAC5F,oGAAoG;AACpG,mGAAmG;AACnG,gGAAgG;AAChG,qEAAqE;AACrE,EAAE;AACF,qGAAqG;AACrG,iGAAiG;AACjG,sGAAsG;AACtG,oDAAoD;AACpD,EAAE;AACF,oGAAoG;AACpG,4FAA4F;AAC5F,gGAAgG;AAChG,oGAAoG;AACpG,oEAAoE;AACpE,EAAE;AACF,gGAAgG;AAChG,8FAA8F;AAC9F,mDAAmD;AACnD,EAAE;AACF,mGAAmG;AACnG,8FAA8F;AAC9F,+FAA+F;AAC/F,4DAA4D;AAE5D;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,8FAA8F;IAC9F,gBAAgB,EAAE,oBAAoB;IACtC,uFAAuF;IACvF,gBAAgB,EAAE,oBAAoB;IACtC,+FAA+F;IAC/F,gBAAgB,EAAE,oBAAoB;IACtC,4FAA4F;IAC5F,cAAc,EAAE,iBAAiB;IACjC,uFAAuF;IACvF,cAAc,EAAE,iBAAiB;IACjC,sFAAsF;IACtF,mBAAmB,EAAE,uBAAuB;IAC5C,8EAA8E;IAC9E,mBAAmB,EAAE,uBAAuB;IAC5C,yCAAyC;IACzC,mBAAmB,EAAE,uBAAuB;IAC5C,2FAA2F;IAC3F,oBAAoB,EAAE,wBAAwB;CACtC,CAAC;AAIX;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA2B;IACvD,kBAAkB,EAAE,GAAG;IACvB,kBAAkB,EAAE,GAAG;IACvB,kBAAkB,EAAE,GAAG;IACvB,eAAe,EAAE,GAAG;IACpB,eAAe,EAAE,GAAG;IACpB,qBAAqB,EAAE,GAAG;IAC1B,qBAAqB,EAAE,GAAG;IAC1B,qBAAqB,EAAE,GAAG;IAC1B,sBAAsB,EAAE,GAAG;CAC5B,CAAC","sourcesContent":["// The error codes the HTTP EDGE puts on the wire, in one enumerable place.\n//\n// WHY THIS FILE EXISTS. `@gnldev/durable` already owns two maps — `CALLER_CONFLICT_CODES` and\n// `BLOCKED_ERROR_CODES` — and because they are exported values, `scripts/check-error-pages.mjs`\n// enumerates them and nobody has to remember anything: a new engine code with no page under\n// `docs/errors/` turns the build red in the same commit that invents it. The codes written HERE had\n// no such map. They were string literals spelled at the point of response, and the docs check knew\n// about them only through a hand-written list inside the script itself, which said so out loud:\n// \"a fourth literal added at an edge tomorrow is caught by nothing\".\n//\n// Measured before this file existed: the list named three codes, and the edge was printing NINE. The\n// six it did not know about — both A2A signature refusals, the timestamp one, `resource_denied`,\n// `budget_exceeded` and `body_consumed_upstream` — had shipped with no page at all. The weak spot was\n// not hypothetical and did not take until tomorrow.\n//\n// WHY IN @gnldev/server RATHER THAN @gnldev/durable. These are route-level facts: an HTTP status is\n// attached to each one, and the engine has no routes and no statuses — putting them next to\n// `RunBusyError` would say the engine produces them, and it does not. Server is also the lowest\n// package that every printer shares: `@gnldev/agui` depends on `@gnldev/server` already (it imports\n// `interruptsFromSteps`), so both edges can read the same constant.\n//\n// Deliberately its own module rather than a block inside `index.ts`: the docs check imports the\n// BUILT value, and importing `dist/index.js` would drag Hono and the whole route table into a\n// documentation script. This file imports nothing.\n//\n// ONE PRINTER IS NOT WIRED TO IT, on purpose: `@gnldev/studio`'s `node.ts` carries its own copy of\n// the `body_consumed_upstream` guard and does NOT depend on `@gnldev/server`, so it keeps the\n// literal. The code is the same string and now has a page; adding a package dependency for one\n// constant would be the more expensive of the two mistakes.\n\n/**\n * Code by the name of the refusal that prints it. The keys are for readers and for the failure\n * message in the docs check; the VALUES are the contract — the same string in the HTTP body, in the\n * SSE `error` frame, and in whatever the client library re-throws.\n */\nexport const EDGE_ERROR_CODES = {\n /** 422, `resumable` — `limits` ceiling met (`server/index.ts`, `sse.ts`, `agui/route.ts`). */\n runLimitExceeded: 'run_limit_exceeded',\n /** 422, `resumable` — one tool, the same arguments, no progress (same three sites). */\n toolLoopDetected: 'tool_loop_detected',\n /** 403 — the agent is pending, changed since approval, or blocked (`requireAgentApproval`). */\n agentNotApproved: 'agent_not_approved',\n /** 403 — `opts.resourceAuth` refused this principal for this agent (the paid FGA layer). */\n resourceDenied: 'resource_denied',\n /** 402 — the organization's budget is spent; a NEW run is refused, a resume is not. */\n budgetExceeded: 'budget_exceeded',\n /** 401 — an A2A call arrived without the `x-gnl-signature`/`x-gnl-timestamp` pair. */\n a2aSignatureMissing: 'a2a_signature_missing',\n /** 401 — the A2A timestamp is outside the ±300s window (replay suspicion). */\n a2aTimestampInvalid: 'a2a_timestamp_invalid',\n /** 401 — the A2A HMAC did not verify. */\n a2aSignatureInvalid: 'a2a_signature_invalid',\n /** 500 — a body parser upstream of the handler already drained the request (`node.ts`). */\n bodyConsumedUpstream: 'body_consumed_upstream',\n} as const;\n\nexport type EdgeErrorCode = (typeof EDGE_ERROR_CODES)[keyof typeof EDGE_ERROR_CODES];\n\n/**\n * HTTP status per edge code — the docs-checker's source of truth for this family, same contract as\n * `WIRE_ERROR_STATUS` in @gnldev/durable: routes are pinned to these numbers by their tests, docs\n * are pinned to them by `check:errors`, and a new code without an entry fails the gate.\n */\nexport const EDGE_ERROR_STATUS: Record<string, number> = {\n run_limit_exceeded: 422,\n tool_loop_detected: 422,\n agent_not_approved: 403,\n resource_denied: 403,\n budget_exceeded: 402,\n a2a_signature_missing: 401,\n a2a_timestamp_invalid: 401,\n a2a_signature_invalid: 401,\n body_consumed_upstream: 500,\n};\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Hono } from 'hono';
|
|
2
|
+
/** One mounted route, as `{ method, path }` — see `FetchHandler.routeTable`. */
|
|
3
|
+
export interface RouteInfo {
|
|
4
|
+
/** Uppercase HTTP method, or `ALL` for a method-agnostic mount. */
|
|
5
|
+
method: string;
|
|
6
|
+
/** The registered path pattern, parameters included (`/agents/:name/run`). */
|
|
7
|
+
path: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* NAMED `routeTable`, not `routes`, and that is not a style choice.
|
|
11
|
+
*
|
|
12
|
+
* `routes` is Hono's OWN property: `app.route(path, app)` does `app.routes.map((r) => r.handler)`.
|
|
13
|
+
* A fetch handler is not a Hono instance and `.route()` was never the supported way to mount one —
|
|
14
|
+
* `.mount()` is — but with a `routes` array present the wrong call SUCCEEDS at boot and then throws
|
|
15
|
+
* `r.handler is not a function` on every request. Measured against Hono 4.12:
|
|
16
|
+
*
|
|
17
|
+
* routes present -> boot OK, every request 500
|
|
18
|
+
* routes absent -> boot throws "Cannot read properties of undefined (reading 'map')"
|
|
19
|
+
*
|
|
20
|
+
* The second is the better failure: unsupported usage should fail where it is written, not on the
|
|
21
|
+
* first request in production. Colliding with the framework's own name turned a loud boot error into
|
|
22
|
+
* a quiet one, which is a worse outcome than the introspection is worth.
|
|
23
|
+
*/
|
|
24
|
+
export type FetchHandler = ((request: Request, ...rest: unknown[]) => Promise<Response>) & {
|
|
25
|
+
fetch: (request: Request, ...rest: unknown[]) => Promise<Response>;
|
|
26
|
+
/**
|
|
27
|
+
* Every route this handler serves, deduplicated and sorted. Introspection only — the Hono instance
|
|
28
|
+
* itself stays hidden, and so do the handler functions.
|
|
29
|
+
*
|
|
30
|
+
* Exists so a test can ask the handler what it exposes instead of maintaining a second list by hand.
|
|
31
|
+
* Every isolation defect this package has shipped had the same shape: a rule applied to the routes
|
|
32
|
+
* someone was looking at rather than to all of them — the scoped-memory check reached 6 of 9 routes,
|
|
33
|
+
* the workflow-store refusal 2 of 3, and the third was found by someone re-reading the file. A list
|
|
34
|
+
* written by hand is a list that goes stale the next time a route is added, which is precisely when
|
|
35
|
+
* the gap appears. Reading it off the router means a new route shows up in the conformance suite
|
|
36
|
+
* without anyone remembering to add it.
|
|
37
|
+
*/
|
|
38
|
+
routeTable: readonly RouteInfo[];
|
|
39
|
+
};
|
|
40
|
+
export declare function toFetchHandler(app: Hono): FetchHandler;
|
|
41
|
+
/**
|
|
42
|
+
* Reads Hono's route table into a stable, deduplicated inventory.
|
|
43
|
+
*
|
|
44
|
+
* Hono registers one entry per handler, so a path with middleware in front of it appears several
|
|
45
|
+
* times; the conformance suite wants each `method + path` once. Sorted so a snapshot of the inventory
|
|
46
|
+
* does not churn when a route is moved within the file.
|
|
47
|
+
*
|
|
48
|
+
* `ALL` ENTRIES ARE USUALLY MIDDLEWARE. `app.use('*', …)` lands in the same table as a route, recorded
|
|
49
|
+
* as `ALL /*`, and nothing in the entry distinguishes it from a genuine `app.all('/path')` — the only
|
|
50
|
+
* observable difference is the handler's arity, which is a coincidence of how it happens to be
|
|
51
|
+
* written, not a contract. So they are kept, and a caller that DRIVES these entries has to skip them
|
|
52
|
+
* or it will request the literal path `/*`.
|
|
53
|
+
*
|
|
54
|
+
* The reason that warning is here rather than in a note: whether they appear at all depends on
|
|
55
|
+
* configuration. `@gnldev/server` emits none in any configuration, and `@gnldev/studio` emits none
|
|
56
|
+
* either until `org` or `auth` is set, at which point one appears. A suite written against a fixture
|
|
57
|
+
* that has neither turned on never learns the filter is needed, and breaks the first time someone runs
|
|
58
|
+
* it with auth on. An empty `ALL` list proves nothing about the next fixture.
|
|
59
|
+
*
|
|
60
|
+
* Each entry is frozen, not just the array. The same array is handed to every caller, so a single
|
|
61
|
+
* consumer writing `routes[0].path = …` in place would corrupt the inventory for every later reader —
|
|
62
|
+
* and the intended consumer is a test suite, which is exactly where that happens. One consequence:
|
|
63
|
+
* `routeTable.sort(…)` throws (it sorts in place); copy first — `[...routeTable].sort(…)`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function routeInventory(app: Hono): readonly RouteInfo[];
|
package/dist/handler.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function toFetchHandler(app) {
|
|
2
|
+
const call = (request, ...rest) => app.fetch(request, ...rest);
|
|
3
|
+
return Object.assign(call, { fetch: call, routeTable: routeInventory(app) });
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Reads Hono's route table into a stable, deduplicated inventory.
|
|
7
|
+
*
|
|
8
|
+
* Hono registers one entry per handler, so a path with middleware in front of it appears several
|
|
9
|
+
* times; the conformance suite wants each `method + path` once. Sorted so a snapshot of the inventory
|
|
10
|
+
* does not churn when a route is moved within the file.
|
|
11
|
+
*
|
|
12
|
+
* `ALL` ENTRIES ARE USUALLY MIDDLEWARE. `app.use('*', …)` lands in the same table as a route, recorded
|
|
13
|
+
* as `ALL /*`, and nothing in the entry distinguishes it from a genuine `app.all('/path')` — the only
|
|
14
|
+
* observable difference is the handler's arity, which is a coincidence of how it happens to be
|
|
15
|
+
* written, not a contract. So they are kept, and a caller that DRIVES these entries has to skip them
|
|
16
|
+
* or it will request the literal path `/*`.
|
|
17
|
+
*
|
|
18
|
+
* The reason that warning is here rather than in a note: whether they appear at all depends on
|
|
19
|
+
* configuration. `@gnldev/server` emits none in any configuration, and `@gnldev/studio` emits none
|
|
20
|
+
* either until `org` or `auth` is set, at which point one appears. A suite written against a fixture
|
|
21
|
+
* that has neither turned on never learns the filter is needed, and breaks the first time someone runs
|
|
22
|
+
* it with auth on. An empty `ALL` list proves nothing about the next fixture.
|
|
23
|
+
*
|
|
24
|
+
* Each entry is frozen, not just the array. The same array is handed to every caller, so a single
|
|
25
|
+
* consumer writing `routes[0].path = …` in place would corrupt the inventory for every later reader —
|
|
26
|
+
* and the intended consumer is a test suite, which is exactly where that happens. One consequence:
|
|
27
|
+
* `routeTable.sort(…)` throws (it sorts in place); copy first — `[...routeTable].sort(…)`.
|
|
28
|
+
*/
|
|
29
|
+
export function routeInventory(app) {
|
|
30
|
+
const seen = new Map();
|
|
31
|
+
for (const r of app.routes ?? []) {
|
|
32
|
+
const method = String(r.method).toUpperCase();
|
|
33
|
+
const key = `${method} ${r.path}`;
|
|
34
|
+
if (!seen.has(key))
|
|
35
|
+
seen.set(key, Object.freeze({ method, path: r.path }));
|
|
36
|
+
}
|
|
37
|
+
return Object.freeze([...seen.values()].sort((a, b) => (a.path === b.path ? a.method.localeCompare(b.method) : a.path.localeCompare(b.path))));
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handler.js","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AA6CA,MAAM,UAAU,cAAc,CAAC,GAAS;IACtC,MAAM,IAAI,GAAG,CAAC,OAAgB,EAAE,GAAG,IAAe,EAAE,EAAE,CAAE,GAAG,CAAC,KAAa,CAAC,OAAO,EAAE,GAAG,IAAI,CAAsB,CAAC;IACjH,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAC/E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,cAAc,CAAC,GAAS;IACtC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAqB,CAAC;IAC1C,KAAK,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC;QACjC,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9C,MAAM,GAAG,GAAG,GAAG,MAAM,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACjJ,CAAC","sourcesContent":["// What this package hands a host: a request in, a response out — not a Hono instance.\n// See @gnldev/studio/src/handler.ts for the reasoning; the shape is deliberately identical, and\n// structurally compatible, without either package depending on the other.\nimport type { Hono } from 'hono';\n\n/** One mounted route, as `{ method, path }` — see `FetchHandler.routeTable`. */\nexport interface RouteInfo {\n /** Uppercase HTTP method, or `ALL` for a method-agnostic mount. */\n method: string;\n /** The registered path pattern, parameters included (`/agents/:name/run`). */\n path: string;\n}\n\n/**\n * NAMED `routeTable`, not `routes`, and that is not a style choice.\n *\n * `routes` is Hono's OWN property: `app.route(path, app)` does `app.routes.map((r) => r.handler)`.\n * A fetch handler is not a Hono instance and `.route()` was never the supported way to mount one —\n * `.mount()` is — but with a `routes` array present the wrong call SUCCEEDS at boot and then throws\n * `r.handler is not a function` on every request. Measured against Hono 4.12:\n *\n * routes present -> boot OK, every request 500\n * routes absent -> boot throws \"Cannot read properties of undefined (reading 'map')\"\n *\n * The second is the better failure: unsupported usage should fail where it is written, not on the\n * first request in production. Colliding with the framework's own name turned a loud boot error into\n * a quiet one, which is a worse outcome than the introspection is worth.\n */\nexport type FetchHandler = ((request: Request, ...rest: unknown[]) => Promise<Response>) & {\n fetch: (request: Request, ...rest: unknown[]) => Promise<Response>;\n /**\n * Every route this handler serves, deduplicated and sorted. Introspection only — the Hono instance\n * itself stays hidden, and so do the handler functions.\n *\n * Exists so a test can ask the handler what it exposes instead of maintaining a second list by hand.\n * Every isolation defect this package has shipped had the same shape: a rule applied to the routes\n * someone was looking at rather than to all of them — the scoped-memory check reached 6 of 9 routes,\n * the workflow-store refusal 2 of 3, and the third was found by someone re-reading the file. A list\n * written by hand is a list that goes stale the next time a route is added, which is precisely when\n * the gap appears. Reading it off the router means a new route shows up in the conformance suite\n * without anyone remembering to add it.\n */\n routeTable: readonly RouteInfo[];\n}\n\nexport function toFetchHandler(app: Hono): FetchHandler {\n const call = (request: Request, ...rest: unknown[]) => (app.fetch as any)(request, ...rest) as Promise<Response>;\n return Object.assign(call, { fetch: call, routeTable: routeInventory(app) });\n}\n\n/**\n * Reads Hono's route table into a stable, deduplicated inventory.\n *\n * Hono registers one entry per handler, so a path with middleware in front of it appears several\n * times; the conformance suite wants each `method + path` once. Sorted so a snapshot of the inventory\n * does not churn when a route is moved within the file.\n *\n * `ALL` ENTRIES ARE USUALLY MIDDLEWARE. `app.use('*', …)` lands in the same table as a route, recorded\n * as `ALL /*`, and nothing in the entry distinguishes it from a genuine `app.all('/path')` — the only\n * observable difference is the handler's arity, which is a coincidence of how it happens to be\n * written, not a contract. So they are kept, and a caller that DRIVES these entries has to skip them\n * or it will request the literal path `/*`.\n *\n * The reason that warning is here rather than in a note: whether they appear at all depends on\n * configuration. `@gnldev/server` emits none in any configuration, and `@gnldev/studio` emits none\n * either until `org` or `auth` is set, at which point one appears. A suite written against a fixture\n * that has neither turned on never learns the filter is needed, and breaks the first time someone runs\n * it with auth on. An empty `ALL` list proves nothing about the next fixture.\n *\n * Each entry is frozen, not just the array. The same array is handed to every caller, so a single\n * consumer writing `routes[0].path = …` in place would corrupt the inventory for every later reader —\n * and the intended consumer is a test suite, which is exactly where that happens. One consequence:\n * `routeTable.sort(…)` throws (it sorts in place); copy first — `[...routeTable].sort(…)`.\n */\nexport function routeInventory(app: Hono): readonly RouteInfo[] {\n const seen = new Map<string, RouteInfo>();\n for (const r of app.routes ?? []) {\n const method = String(r.method).toUpperCase();\n const key = `${method} ${r.path}`;\n if (!seen.has(key)) seen.set(key, Object.freeze({ method, path: r.path }));\n }\n return Object.freeze([...seen.values()].sort((a, b) => (a.path === b.path ? a.method.localeCompare(b.method) : a.path.localeCompare(b.path))));\n}\n"]}
|