@kindgi/handler-runtime 0.0.0-bootstrap.0 → 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 +218 -2
- package/dist/build-extensions.d.ts +75 -0
- package/dist/build-extensions.d.ts.map +1 -0
- package/dist/build-extensions.js +27 -0
- package/dist/build-extensions.js.map +1 -0
- package/dist/discovery.d.ts +19 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +81 -0
- package/dist/discovery.js.map +1 -0
- package/dist/entrypoint.d.ts +10 -0
- package/dist/entrypoint.d.ts.map +1 -0
- package/dist/entrypoint.js +24 -0
- package/dist/entrypoint.js.map +1 -0
- package/dist/handler-runner.d.ts +127 -0
- package/dist/handler-runner.d.ts.map +1 -0
- package/dist/handler-runner.js +318 -0
- package/dist/handler-runner.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/kindgi-index-main.d.ts +2 -0
- package/dist/kindgi-index-main.d.ts.map +1 -0
- package/dist/kindgi-index-main.js +15 -0
- package/dist/kindgi-index-main.js.map +1 -0
- package/dist/kindgi-index.d.ts +316 -0
- package/dist/kindgi-index.d.ts.map +1 -0
- package/dist/kindgi-index.js +1201 -0
- package/dist/kindgi-index.js.map +1 -0
- package/dist/pack-env.d.ts +66 -0
- package/dist/pack-env.d.ts.map +1 -0
- package/dist/pack-env.js +97 -0
- package/dist/pack-env.js.map +1 -0
- package/dist/pack-service/index.d.ts +7 -0
- package/dist/pack-service/index.d.ts.map +1 -0
- package/dist/pack-service/index.js +6 -0
- package/dist/pack-service/index.js.map +1 -0
- package/dist/pack-service/main.d.ts +47 -0
- package/dist/pack-service/main.d.ts.map +1 -0
- package/dist/pack-service/main.js +201 -0
- package/dist/pack-service/main.js.map +1 -0
- package/dist/pack-service/service.d.ts +61 -0
- package/dist/pack-service/service.d.ts.map +1 -0
- package/dist/pack-service/service.js +341 -0
- package/dist/pack-service/service.js.map +1 -0
- package/dist/pack-service/supervisor.d.ts +138 -0
- package/dist/pack-service/supervisor.d.ts.map +1 -0
- package/dist/pack-service/supervisor.js +424 -0
- package/dist/pack-service/supervisor.js.map +1 -0
- package/dist/protocol.d.ts +104 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +116 -0
- package/dist/protocol.js.map +1 -0
- package/package.json +87 -4
- package/src/build-extensions.ts +100 -0
- package/src/discovery.ts +89 -0
- package/src/entrypoint.ts +23 -0
- package/src/handler-runner.ts +500 -0
- package/src/index.ts +66 -0
- package/src/kindgi-index-main.ts +17 -0
- package/src/kindgi-index.ts +1605 -0
- package/src/pack-env.ts +148 -0
- package/src/pack-service/index.ts +17 -0
- package/src/pack-service/main.ts +246 -0
- package/src/pack-service/service.ts +478 -0
- package/src/pack-service/supervisor.ts +600 -0
- package/src/protocol.ts +214 -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 describing the origin of the Work and
|
|
141
|
+
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 Kindgi Inc.
|
|
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
CHANGED
|
@@ -1,3 +1,219 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@kindgi/handler-runtime`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Runs a Kindgi pack's own code: its tool handlers and guardrail checks.
|
|
4
|
+
|
|
5
|
+
- **The pack service**: a long-lived HTTP server that runs a pack's tools and checks over pack protocol v2. It's the process a pack image runs, and `kindgi dev` runs the same process locally, behind a supervisor.
|
|
6
|
+
- **The handler runner** (`runHandler`, `runCheck`): runs one tool call or one check in process. The pack service runs every call through it.
|
|
7
|
+
- **The build-time indexer** (`kindgi-index`): writes the pack's `index.json`, the list of its tools, guardrails, agents and flows that the pack service and the runtime read.
|
|
8
|
+
|
|
9
|
+
## Handler runner
|
|
10
|
+
|
|
11
|
+
`runHandler({ tool, input, ctx })` runs one tool call:
|
|
12
|
+
|
|
13
|
+
1. Validates a copy of `input` against the tool's input JSON Schema (ajv, Draft 2020-12), filling in each property's `default`. When the module exports a Zod schema (`defineTool`'s `inputZod`), it also parses the input with it, so the handler gets what its type says.
|
|
14
|
+
2. Imports `tool.modulePath` and resolves the handler: a bare function export, or `default` / `handler` / `run`, or a `defineTool` export holding one.
|
|
15
|
+
3. Calls `handler(input, ctx)`, awaiting a promise.
|
|
16
|
+
4. Validates the return value against the tool's output JSON Schema.
|
|
17
|
+
|
|
18
|
+
`runCheck({ check, config, trace, abortSignal? })` runs one guardrail check: it imports the module, resolves its `evaluate` (`default`, `check`, or a bare export), and calls `evaluate(config, trace, bindings)`. `bindings` carries only `abortSignal`; a check here has no provider registry, so llm-judge checks run in the server.
|
|
19
|
+
|
|
20
|
+
Neither throws. Each returns `{ kind: 'ok', value }` or `{ kind: 'err', error: HandlerError }`:
|
|
21
|
+
|
|
22
|
+
| `error.code` | When |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `input-validation-failed` | The input failed its schema (`issues` lists why). The handler isn't called. |
|
|
25
|
+
| `output-validation-failed` | The handler's return value failed the output schema. |
|
|
26
|
+
| `handler-import-failed` | Importing the module threw (`cause`). |
|
|
27
|
+
| `handler-shape-invalid` | The module exports no handler. |
|
|
28
|
+
| `handler-throw` | The handler (or `evaluate`) threw (`cause`). |
|
|
29
|
+
| `check-shape-invalid` | The check module exports no `evaluate`. |
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { runHandler } from '@kindgi/handler-runtime';
|
|
33
|
+
|
|
34
|
+
const outcome = await runHandler({
|
|
35
|
+
tool: { id: 'acme.lookup', modulePath: '/app/dist/tools/lookup.js', inputSchema, outputSchema },
|
|
36
|
+
input: { q: 'backpay' },
|
|
37
|
+
ctx: { tenantId, runId, abortSignal },
|
|
38
|
+
});
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`importHandler` / `importCheck` replace the default `import(modulePath)` (tests use them). The runner is not a sandbox: the pack service's process is the boundary, and pack code is the team's own.
|
|
42
|
+
|
|
43
|
+
## Pack service (protocol v2)
|
|
44
|
+
|
|
45
|
+
A long-lived HTTP server that runs a pack's tool handlers and guardrail checks for a runtime. It's the process a pack image runs, and the same process runs locally during development. Imports happen once at boot, calls run concurrently, and handler console output can't corrupt a response.
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
KINDGI_PACK_SERVICE_TOKEN=… PORT=8080 node node_modules/@kindgi/handler-runtime/dist/pack-service/main.js \
|
|
49
|
+
--index dist/index.json # module paths resolve against --module-root (default: the index's directory)
|
|
50
|
+
# --bundle-map <path>: a build's map of the index's source paths to their bundles
|
|
51
|
+
# --host <address>: listen on one address (default: every interface)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
A pack image runs it bundled (`dist/kindgi-pack-service.mjs`) with `--bundle-map`: the index names each module by its source path (`tools/echo/index.ts`), and the map points it at the bundle that loads (`tools/echo/index.mjs`).
|
|
55
|
+
|
|
56
|
+
| Route | Auth | Answer |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `POST /v1/invoke` | `kindgi-pack-token` | `200` with a v2 response message |
|
|
59
|
+
| `GET /v1/info` | `kindgi-pack-token` | pack id, versions, protocol, tools, checks, and the required env names it lacks (`missingEnv`) |
|
|
60
|
+
| `GET /healthz` | none | the process is up |
|
|
61
|
+
| `GET /readyz` | none | prewarmed, not draining, and every required env name set (unless the env check is `warn`) |
|
|
62
|
+
|
|
63
|
+
- **Requests** (`@kindgi/handler-runtime/protocol`) name a tool (`{ id, version? }`) or a check (`{ id }`). The service resolves it from its own `index.json`, so a caller never chooses which module is imported.
|
|
64
|
+
- **Every outcome of running pack code is a message**, answered with `200`: the result, validation failures (with `issues`), a throw, an unknown tool or check, a version mismatch, `deadline-exceeded` (from `kindgi-timeout-ms`), and `cancelled` (the caller disconnected). HTTP statuses are for the transport only: `401`, `404`, `405`, `413`, `415`, `503` with `Retry-After` when the service isn't ready, is draining, or is at its concurrency cap, and `500` if the service itself fails while handling a call.
|
|
65
|
+
- **The declared process env:** a pack lists the environment variables its code reads in `kindgi.config` (`env: { required, optional }`), and the index carries them. With a `required` name unset or empty, the service isn't ready: `/readyz` and every call answer `503` with `{ "error": "missing env", "missingEnv": [...] }`, names only. `KINDGI_PACK_ENV_CHECK=warn` serves anyway and names them in the log (`missing-env`) and `/v1/info`; `kindgi dev` uses it. `resolvePackEnv` and `missingPackEnv` are the shared checks.
|
|
66
|
+
- **Cancellation:** the handler's `ctx.abortSignal` fires on a deadline or a disconnect. Handlers that do slow I/O should pass it on.
|
|
67
|
+
- **Boot fails** (exit `1`, listing every problem) when the index can't be read, a module it names is missing, or one fails to import. SIGTERM drains in-flight calls and exits `0`.
|
|
68
|
+
- **Logs** are JSON lines on stderr. The `listening` line carries the bound port, so a caller can start the service with `PORT=0`.
|
|
69
|
+
- **Programmatic:** `createPackService({ index, resolveModule, token, … })` returns a service whose `handle` is a `node:http` request handler. `startPackService(config)` also listens (`@kindgi/handler-runtime/pack-service`).
|
|
70
|
+
|
|
71
|
+
### Supervisor (local development)
|
|
72
|
+
|
|
73
|
+
`createPackServiceSupervisor({ command, moduleRoot, env, … })` (`@kindgi/handler-runtime/pack-service`) runs a pack service as a child process behind a **front**: one HTTP listener on a fixed loopback address with a session token, for the supervisor's whole life. A caller — a runtime calling tools — holds that one URL and token however often the code changes.
|
|
74
|
+
|
|
75
|
+
- `listen()` opens the front; `start(indexPath)` boots a child on the index (loopback, any port) and switches calls to it once it listens. The previous child finishes its in-flight calls and stops; a child that fails to boot leaves the previous one serving; a child that exits on its own is restarted.
|
|
76
|
+
- The front forwards `POST /v1/invoke` and `GET /v1/info`, and answers `503` with `Retry-After` while no child serves (the call did not run, so a caller may retry) and `502` when a child died mid-call (it may have run). `/healthz` answers while the front listens, `/readyz` while a child serves.
|
|
77
|
+
- `command` is the child's argv; the supervisor appends `--index`, `--module-root` and `--host`. Any pack service with the process contract of [`pack-protocol.schema.json`](../specs/schemas/pack-protocol.schema.json) works: this package's (`[process.execPath, <pack-service-main>]`) or the Python SDK's (`[python, '-m', 'kindgi.pack', 'serve']`).
|
|
78
|
+
- The child's environment is exactly `env()` plus the token and `PORT=0`.
|
|
79
|
+
- Forwarding is a separate `relay` (a request body plus deadline, run and request ids, and a cancel signal), so a listener other than HTTP can reuse it.
|
|
80
|
+
- `stop()` stops the child (the front then answers `503`); `close()` also closes the front.
|
|
81
|
+
|
|
82
|
+
## Build extensions
|
|
83
|
+
|
|
84
|
+
`@kindgi/handler-runtime/build-extensions` (re-exported as `@kindgi/sdk/build`): the types and helpers for `image` in a TypeScript pack's `kindgi.config.*`.
|
|
85
|
+
- `ImageConfig { systemPackages?, extensions?, buildEnv? }`;
|
|
86
|
+
- `BuildExtension { name, contextFiles?, systemPackages?, postInstall?, buildEnv? }`;
|
|
87
|
+
- `prisma({ schema, config? })`: `prisma generate` after the install;
|
|
88
|
+
- `defineBuildExtension()`.
|
|
89
|
+
|
|
90
|
+
They're data only: `kindgi build` renders them into the image's Containerfile.
|
|
91
|
+
|
|
92
|
+
## Build-time indexer
|
|
93
|
+
|
|
94
|
+
`kindgi-index.ts` writes a pack's `index.json`. A pack image's indexer stage runs it over the image's bundles (process entry `kindgi-index-main`, bundled as `dist/kindgi-index.mjs`), and the emitted `/app/index.json` is `COPY --from=indexer`'d into the runtime image; `kindgi build` runs the same bundle locally, so the two indexes compare byte for byte. The pack service reads `index.json` at boot: it serves exactly the tools and checks the index lists.
|
|
95
|
+
|
|
96
|
+
### What the indexer does
|
|
97
|
+
|
|
98
|
+
1. **Discovers** files under `tools/`, `guardrails/`, `agents/`, `flows/` per `kindgi.config.ts` (`.ts` / `.js` / `.mjs` all accepted). Indexing a build (`bundleMap`), the map's source paths are the file list, classified by the same patterns — the source tree needn't be there — each imported from its bundle; the index still records the source path.
|
|
99
|
+
2. **Kind-maps** each file by its containing directory (primary) or by structural detection on the default export (fallback for files matched by custom-discovery globs outside the four default folders).
|
|
100
|
+
3. **Imports** each file and reads the `default` export — accepting either the raw primitive shape or a `Result`-wrapped envelope from `defineTool` / `defineGuardrail` / etc. Fails loud on: no default export, kind mismatch, or a `Result`-wrapped error.
|
|
101
|
+
4. **Converts Zod schemas** — `tool.inputZod` / `tool.outputZod` / `check.configZod` — to their JSON Schema wire form via `@kindgi/schema.toJSONSchemaSync`. JSON-Schema-authored slots pass through verbatim.
|
|
102
|
+
5. **Writes** the `v: 1` `index.json` envelope atomically (write to `.tmp-<pid>-<time>`, then rename) to the configured output path.
|
|
103
|
+
|
|
104
|
+
### Programmatic form
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { runIndexer } from '@kindgi/handler-runtime';
|
|
108
|
+
|
|
109
|
+
const outcome = await runIndexer({
|
|
110
|
+
packDir: '/path/to/pack',
|
|
111
|
+
// Optional overrides
|
|
112
|
+
configPath: '/path/to/kindgi.config.ts',
|
|
113
|
+
outputPath: '/app/index.json',
|
|
114
|
+
artifactVersion: '20260920.1', // pin for reproducible builds
|
|
115
|
+
publishedAt: '2026-09-20T14:32:07.104Z', // pin for byte-determinism
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
if (outcome.kind === 'ok') {
|
|
119
|
+
console.log(outcome.value.counts); // { tools, guardrails, agents, flows }
|
|
120
|
+
console.log(outcome.value.outputPath);
|
|
121
|
+
} else {
|
|
122
|
+
console.error(outcome.error.code, outcome.error.message);
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`runIndexer` never throws — every failure surfaces as a typed `IndexerError`:
|
|
127
|
+
|
|
128
|
+
| Code | When |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `config-not-found` | No `kindgi.config.{ts,mts,mjs,js,cjs}` at the pack root. |
|
|
131
|
+
| `config-parse-failed` | Config file imported but is malformed. |
|
|
132
|
+
| `discovery-empty` | Glob patterns matched zero files. |
|
|
133
|
+
| `file-import-failed` | Dynamic `import()` of a discovered file threw. |
|
|
134
|
+
| `no-default-export` | A discovered file exported no `default`. |
|
|
135
|
+
| `kind-mismatch` | File under `tools/` default-exports a non-tool (or symmetric for the other three folders). |
|
|
136
|
+
| `ambiguous-kind` | Custom-pattern file whose default export doesn't structurally match any primitive shape. |
|
|
137
|
+
| `zod-conversion-failed` | `z.toJSONSchema()` threw for a specific schema. |
|
|
138
|
+
| `manifest-validation-failed` | Inner manifest didn't match the expected shape (or was a `Result`-wrapped error). |
|
|
139
|
+
| `output-write-failed` | Filesystem write error. |
|
|
140
|
+
|
|
141
|
+
### Loading `kindgi.config.*` on its own
|
|
142
|
+
|
|
143
|
+
The indexer's config loader is exported so every tool reads the pack
|
|
144
|
+
config the same way:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { loadKindgiConfig } from '@kindgi/handler-runtime';
|
|
148
|
+
|
|
149
|
+
const r = await loadKindgiConfig('/path/to/pack');
|
|
150
|
+
if (r.kind === 'ok') r.value.pack.id;
|
|
151
|
+
// r.kind === 'err': 'config-not-found' | 'config-parse-failed' (message carries the cause)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
It looks up `KINDGI_CONFIG_FILENAMES` in order and imports the first that
|
|
155
|
+
exists (cache-busted by mtime, so a long-running process sees edits). With
|
|
156
|
+
none, a `pyproject.toml` whose `[tool.kindgi]` table holds the same keys is
|
|
157
|
+
the config — a **Python pack** (`language: 'python'`, unless the table says
|
|
158
|
+
otherwise). It checks `pack.id` / `pack.version` and `language`. Never throws.
|
|
159
|
+
|
|
160
|
+
- `findKindgiConfig(packDir)` — where the config is (`{ path, format: 'module' | 'pyproject' }`), or `undefined`; a `pyproject.toml` without the table is not a pack.
|
|
161
|
+
- `packLanguage(config)` — `'node'` or `'python'`: which indexer reads the pack and which pack service runs it. `runIndexer` refuses a Python pack (`language-mismatch`); `python -m kindgi.pack index` indexes it.
|
|
162
|
+
- `resolveDiscovery(discovery, language)` — the patterns with the language's defaults (`DEFAULT_DISCOVERY`, `DEFAULT_PYTHON_DISCOVERY`).
|
|
163
|
+
|
|
164
|
+
### Command-line form
|
|
165
|
+
|
|
166
|
+
`main(argv)` is the command; the `kindgi-index-main` export runs it as a process (a pack image runs it bundled, as `dist/kindgi-index.mjs`).
|
|
167
|
+
|
|
168
|
+
```
|
|
169
|
+
kindgi-index --pack-dir <path> [--config <path>] [--output <path>]
|
|
170
|
+
[--bundle-map <path> [--module-root <path>]]
|
|
171
|
+
[--artifact-version <str>] [--published-at <iso>]
|
|
172
|
+
[--help] [--version]
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`--bundle-map` indexes a build: a JSON object of source path → bundle path, the bundle paths relative to `--module-root` (default `--pack-dir`).
|
|
176
|
+
|
|
177
|
+
### `index.json` shape
|
|
178
|
+
|
|
179
|
+
```jsonc
|
|
180
|
+
{
|
|
181
|
+
"v": 1,
|
|
182
|
+
"packId": "acme.support",
|
|
183
|
+
"packVersion": "1.0.0",
|
|
184
|
+
"artifactVersion": "20260920.1",
|
|
185
|
+
"publishedAt": "2026-09-20T14:32:07.104Z",
|
|
186
|
+
"tools": [{ "id": "…", "input": { … }, "output": { … }, "effects": [ … ], "modulePath": "tools/…/index.js", "sandbox": "strict", "limits": { … }, "network": { … } }, …],
|
|
187
|
+
"guardrails": [{ "id": "…", "kind": "zero-llm", "action": { "on-violation": "halt" }, "severity": "error", "checkModulePath": "guardrails/…/index.js", "checkId": "…", "configSchema": { … } }, …],
|
|
188
|
+
"agents": [{ "id": "…", "version": "1.0.0", "instructions": "…", "capabilities": [ … ], "tools": [ … ], "modulePath": "agents/…/index.js" }, …],
|
|
189
|
+
"flows": [{ "id": "…", "version": "1.0.0", "nodes": [ … ], "edges": [ … ], "kernelPayloadVersion": 1, "modulePath": "flows/…/index.js" }, …],
|
|
190
|
+
"env": { "optional": ["LOG_LEVEL"], "required": ["DATABASE_URL"] } // only when the pack declares env
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The pack service:
|
|
195
|
+
1. Reads the index at boot (`--index`, else `KINDGI_PACK_INDEX`, else `/app/index.json`) and imports every module it names (prewarm). A missing or failing module fails the boot.
|
|
196
|
+
2. For a call to tool `X`, finds `X` in the index and runs it with `runHandler`, with its module path resolved against `--module-root`. A guardrail check is found by its `checkId`.
|
|
197
|
+
|
|
198
|
+
### Determinism
|
|
199
|
+
|
|
200
|
+
An index computed on a developer's laptop must match one computed by the build server for the same inputs — byte-identical inputs must produce byte-identical outputs. To make that work:
|
|
201
|
+
|
|
202
|
+
- All list fields (`tools` / `guardrails` / `agents` / `flows`) are sorted lexicographically by `id`.
|
|
203
|
+
- JSON serialization writes keys in sorted order at every level.
|
|
204
|
+
- `publishedAt` is accepted as an explicit `opts.publishedAt` (build-arg from the Dockerfile, SOURCE_DATE_EPOCH-shaped). Default: fresh ISO string — non-deterministic; production builds must override it.
|
|
205
|
+
|
|
206
|
+
## Not in this package
|
|
207
|
+
|
|
208
|
+
- Running the indexer as part of a pack build — that is the build tooling's job.
|
|
209
|
+
- Multi-pack workspace indexing (one pack per subfolder).
|
|
210
|
+
- Watch mode / hot re-indexing.
|
|
211
|
+
- A signed `index.json` — the image digest, which contains the file, is what gets signed.
|
|
212
|
+
- Cross-file dependency validation (an agent referencing a tool the pack doesn't have).
|
|
213
|
+
- Bundle-size warnings or thresholds.
|
|
214
|
+
- Handler-side telemetry / cost-tracking hooks.
|
|
215
|
+
- Streaming output for tools that yield incremental results.
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A TypeScript pack image's build extensions: what an app's image needs
|
|
3
|
+
* beyond installing the app's dependencies — Debian packages, a step
|
|
4
|
+
* that generates code after the install (Prisma's client), placeholder
|
|
5
|
+
* env for build steps. `image` in `kindgi.config.*`:
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { prisma } from '@kindgi/sdk/build';
|
|
9
|
+
*
|
|
10
|
+
* export default {
|
|
11
|
+
* pack: { id: 'acme.app', version: '1.0.0' },
|
|
12
|
+
* image: {
|
|
13
|
+
* systemPackages: ['tesseract-ocr'],
|
|
14
|
+
* extensions: [prisma({ schema: 'prisma/schema.prisma', config: 'prisma.config.ts' })],
|
|
15
|
+
* buildEnv: { DATABASE_URL: 'postgresql://build-placeholder' },
|
|
16
|
+
* },
|
|
17
|
+
* };
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* Data only: nothing here runs at build time. `kindgi build` renders it
|
|
21
|
+
* into the image's Containerfile — system packages in the base stage,
|
|
22
|
+
* `buildEnv` in the install stage only (never in the final image), each
|
|
23
|
+
* `postInstall` step after the install and before the prune to
|
|
24
|
+
* production, through the app's own package manager.
|
|
25
|
+
*/
|
|
26
|
+
/** A package's bin, run through the app's package manager (`pnpm exec`, `npx --no`, `yarn`). */
|
|
27
|
+
export interface BuildStep {
|
|
28
|
+
readonly bin: string;
|
|
29
|
+
readonly args?: readonly string[];
|
|
30
|
+
}
|
|
31
|
+
export interface BuildExtension {
|
|
32
|
+
readonly name: string;
|
|
33
|
+
/**
|
|
34
|
+
* Files the steps read, relative to the pack folder: copied into the
|
|
35
|
+
* image's install stage, at the same paths.
|
|
36
|
+
*/
|
|
37
|
+
readonly contextFiles?: readonly string[];
|
|
38
|
+
/** Debian packages the image needs. */
|
|
39
|
+
readonly systemPackages?: readonly string[];
|
|
40
|
+
/**
|
|
41
|
+
* Steps after the install, before the prune: dev dependencies (a
|
|
42
|
+
* generator's CLI) are still there. Run in the pack folder.
|
|
43
|
+
*/
|
|
44
|
+
readonly postInstall?: readonly BuildStep[];
|
|
45
|
+
/**
|
|
46
|
+
* Env for the build steps, and for the indexer stage that imports the
|
|
47
|
+
* pack's modules: non-secret placeholders only. Never in the final
|
|
48
|
+
* image.
|
|
49
|
+
*/
|
|
50
|
+
readonly buildEnv?: Readonly<Record<string, string>>;
|
|
51
|
+
}
|
|
52
|
+
/** `image` in `kindgi.config.*` (a TypeScript pack). */
|
|
53
|
+
export interface ImageConfig {
|
|
54
|
+
/** Debian packages the image needs (as a Python pack's `[tool.kindgi.image] system-packages`). */
|
|
55
|
+
readonly systemPackages?: readonly string[];
|
|
56
|
+
readonly extensions?: readonly BuildExtension[];
|
|
57
|
+
/** Env for the build steps, merged over the extensions' (see `BuildExtension.buildEnv`). */
|
|
58
|
+
readonly buildEnv?: Readonly<Record<string, string>>;
|
|
59
|
+
}
|
|
60
|
+
/** An app's own extension: the shape checked by the type, returned as is. */
|
|
61
|
+
export declare function defineBuildExtension(extension: BuildExtension): BuildExtension;
|
|
62
|
+
export interface PrismaExtensionOptions {
|
|
63
|
+
/** The Prisma schema, relative to the pack folder. */
|
|
64
|
+
readonly schema: string;
|
|
65
|
+
/** The Prisma config file (`prisma.config.ts`), when the app has one; it names the schema. */
|
|
66
|
+
readonly config?: string;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Prisma's generated client in the image. The app's own `postinstall:
|
|
70
|
+
* prisma generate` doesn't run (the image installs with scripts off), so
|
|
71
|
+
* this copies the schema (and config) in and runs `prisma generate` after
|
|
72
|
+
* the install, with the app's `prisma` CLI.
|
|
73
|
+
*/
|
|
74
|
+
export declare function prisma(options: PrismaExtensionOptions): BuildExtension;
|
|
75
|
+
//# sourceMappingURL=build-extensions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-extensions.d.ts","sourceRoot":"","sources":["../src/build-extensions.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,gGAAgG;AAChG,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ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|
|
4
|
+
export function defineBuildExtension(extension) {
|
|
5
|
+
return extension;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Prisma's generated client in the image. The app's own `postinstall:
|
|
9
|
+
* prisma generate` doesn't run (the image installs with scripts off), so
|
|
10
|
+
* this copies the schema (and config) in and runs `prisma generate` after
|
|
11
|
+
* the install, with the app's `prisma` CLI.
|
|
12
|
+
*/
|
|
13
|
+
export function prisma(options) {
|
|
14
|
+
return {
|
|
15
|
+
name: 'prisma',
|
|
16
|
+
contextFiles: options.config !== undefined ? [options.schema, options.config] : [options.schema],
|
|
17
|
+
postInstall: [
|
|
18
|
+
{
|
|
19
|
+
bin: 'prisma',
|
|
20
|
+
args: options.config !== undefined
|
|
21
|
+
? ['generate', '--config', options.config]
|
|
22
|
+
: ['generate', '--schema', options.schema],
|
|
23
|
+
},
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=build-extensions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-extensions.js","sourceRoot":"","sources":["../src/build-extensions.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAiEjC,6EAA6E;AAC7E,MAAM,UAAU,oBAAoB,CAAC,SAAyB;IAC5D,OAAO,SAAS,CAAC;AACnB,CAAC;AASD;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,OAA+B;IACpD,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,YAAY,EACV,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;QACpF,WAAW,EAAE;YACX;gBACE,GAAG,EAAE,QAAQ;gBACb,IAAI,EACF,OAAO,CAAC,MAAM,KAAK,SAAS;oBAC1B,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC;oBAC1C,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC;aAC/C;SACF;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Test / spec files sit next to primitives and are never primitives. */
|
|
2
|
+
export declare const TEST_FILE_REGEX: RegExp;
|
|
3
|
+
/** Compile a discovery pattern to an anchored RegExp over `/`-separated relative paths. */
|
|
4
|
+
export declare function globToRegex(pattern: string): RegExp;
|
|
5
|
+
/**
|
|
6
|
+
* Directory prefix before the first wildcard segment, `''` for the pack
|
|
7
|
+
* root. A pattern without wildcards names a file; its prefix is that
|
|
8
|
+
* file's directory.
|
|
9
|
+
*/
|
|
10
|
+
export declare function globStaticPrefix(pattern: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* The directories to walk or watch for a set of patterns: each pattern's
|
|
13
|
+
* static prefix, with any prefix inside another one dropped. `['']`
|
|
14
|
+
* means the pack root.
|
|
15
|
+
*/
|
|
16
|
+
export declare function discoveryRoots(patterns: readonly string[]): readonly string[];
|
|
17
|
+
/** `(relPath) => true` when the path matches any pattern and is not a test file. */
|
|
18
|
+
export declare function createGlobMatcher(patterns: readonly string[]): (relPath: string) => boolean;
|
|
19
|
+
//# sourceMappingURL=discovery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../src/discovery.ts"],"names":[],"mappings":"AAqBA,yEAAyE;AACzE,eAAO,MAAM,eAAe,QAAoC,CAAC;AAEjE,2FAA2F;AAC3F,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CASnD;AA0BD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAKxD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,MAAM,EAAE,CAK7E;AAED,oFAAoF;AACpF,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAG3F"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
/**
|
|
4
|
+
* Discovery-glob primitives shared by the indexer and anything that
|
|
5
|
+
* watches a pack (a dev watch loop) — so "which files are primitives"
|
|
6
|
+
* has one answer.
|
|
7
|
+
*
|
|
8
|
+
* Supported syntax: `**` (any depth, including none), `*` (within one
|
|
9
|
+
* segment), `?` (one character), `{a,b,c}` alternation. Negations and
|
|
10
|
+
* extglobs are not supported.
|
|
11
|
+
*
|
|
12
|
+
* Every pattern has a **static prefix** — the directory segments before
|
|
13
|
+
* the first wildcard (`kindgi/tools/**\/*.ts` → `kindgi/tools`). Walking
|
|
14
|
+
* or watching only that prefix matters when a pack lives inside a large
|
|
15
|
+
* application: the indexer must not crawl the whole host repo to find
|
|
16
|
+
* `kindgi/**`.
|
|
17
|
+
*/
|
|
18
|
+
const GLOB_CHARS = /[*?{[]/;
|
|
19
|
+
/** Test / spec files sit next to primitives and are never primitives. */
|
|
20
|
+
export const TEST_FILE_REGEX = /\.(test|spec)\.(ts|js|mjs|cjs)$/;
|
|
21
|
+
/** Compile a discovery pattern to an anchored RegExp over `/`-separated relative paths. */
|
|
22
|
+
export function globToRegex(pattern) {
|
|
23
|
+
let re = '';
|
|
24
|
+
let i = 0;
|
|
25
|
+
while (i < pattern.length) {
|
|
26
|
+
const [piece, next] = globToken(pattern, i);
|
|
27
|
+
re += piece;
|
|
28
|
+
i = next;
|
|
29
|
+
}
|
|
30
|
+
return new RegExp(`^${re}$`);
|
|
31
|
+
}
|
|
32
|
+
/** The regex source for the token at `i`, and the index after it. */
|
|
33
|
+
function globToken(pattern, i) {
|
|
34
|
+
const c = pattern.charAt(i);
|
|
35
|
+
if (c === '*' && pattern.charAt(i + 1) === '*') {
|
|
36
|
+
// `**/` may match zero segments; a trailing `**` matches anything.
|
|
37
|
+
return pattern.charAt(i + 2) === '/' ? ['(?:.*/)?', i + 3] : ['.*', i + 2];
|
|
38
|
+
}
|
|
39
|
+
if (c === '*')
|
|
40
|
+
return ['[^/]*', i + 1];
|
|
41
|
+
if (c === '?')
|
|
42
|
+
return ['[^/]', i + 1];
|
|
43
|
+
const close = c === '{' ? pattern.indexOf('}', i) : -1;
|
|
44
|
+
if (close !== -1) {
|
|
45
|
+
const options = pattern
|
|
46
|
+
.slice(i + 1, close)
|
|
47
|
+
.split(',')
|
|
48
|
+
.map(escapeRegex);
|
|
49
|
+
return [`(?:${options.join('|')})`, close + 1];
|
|
50
|
+
}
|
|
51
|
+
return [escapeRegex(c), i + 1];
|
|
52
|
+
}
|
|
53
|
+
function escapeRegex(s) {
|
|
54
|
+
return s.replace(/[.+^$()|[\]\\{}]/g, '\\$&');
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Directory prefix before the first wildcard segment, `''` for the pack
|
|
58
|
+
* root. A pattern without wildcards names a file; its prefix is that
|
|
59
|
+
* file's directory.
|
|
60
|
+
*/
|
|
61
|
+
export function globStaticPrefix(pattern) {
|
|
62
|
+
const segments = pattern.split('/');
|
|
63
|
+
const firstGlob = segments.findIndex((s) => GLOB_CHARS.test(s));
|
|
64
|
+
const dirSegments = firstGlob === -1 ? segments.slice(0, -1) : segments.slice(0, firstGlob);
|
|
65
|
+
return dirSegments.filter((s) => s !== '' && s !== '.').join('/');
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The directories to walk or watch for a set of patterns: each pattern's
|
|
69
|
+
* static prefix, with any prefix inside another one dropped. `['']`
|
|
70
|
+
* means the pack root.
|
|
71
|
+
*/
|
|
72
|
+
export function discoveryRoots(patterns) {
|
|
73
|
+
const prefixes = [...new Set(patterns.map(globStaticPrefix))].sort();
|
|
74
|
+
return prefixes.filter((p) => !prefixes.some((other) => other !== p && (other === '' || p.startsWith(`${other}/`))));
|
|
75
|
+
}
|
|
76
|
+
/** `(relPath) => true` when the path matches any pattern and is not a test file. */
|
|
77
|
+
export function createGlobMatcher(patterns) {
|
|
78
|
+
const regexes = patterns.map(globToRegex);
|
|
79
|
+
return (relPath) => !TEST_FILE_REGEX.test(relPath) && regexes.some((r) => r.test(relPath));
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=discovery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../src/discovery.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC;;;;;;;;;;;;;;GAcG;AAEH,MAAM,UAAU,GAAG,QAAQ,CAAC;AAE5B,yEAAyE;AACzE,MAAM,CAAC,MAAM,eAAe,GAAG,iCAAiC,CAAC;AAEjE,2FAA2F;AAC3F,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAC5C,EAAE,IAAI,KAAK,CAAC;QACZ,CAAC,GAAG,IAAI,CAAC;IACX,CAAC;IACD,OAAO,IAAI,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,qEAAqE;AACrE,SAAS,SAAS,CAAC,OAAe,EAAE,CAAS;IAC3C,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,CAAC,KAAK,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QAC/C,mEA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