@h-ai/runner 0.0.0-stage → 1.0.0-beta.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2026] [idealworld.group]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.en.md ADDED
@@ -0,0 +1,332 @@
1
+ # @h-ai/runner
2
+
3
+ [简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
4
+
5
+ [Framework home](../../README.en.md) · [Relational database](../reldb/README.en.md) · [AI agents](../ai/README.en.md)
6
+
7
+ Runner executes managed agent workers and tool jobs on Node.js. API nodes submit work, read status, and request cancellation. Executor nodes claim work and own its containers. A relational database shares tasks, leases, events, and execution results.
8
+
9
+ ## Quick Start
10
+
11
+ ```sh
12
+ pnpm add @h-ai/runner @h-ai/reldb
13
+ ```
14
+
15
+ Start RelDB before Runner. This Node.js startup example uses SQLite and a trusted server-side handler, so it needs no container engine. In an application, derive `tenantId` and `userId` from the authenticated identity and check business authorization before invoking Runner.
16
+
17
+ ```ts
18
+ import { setTimeout as delay } from 'node:timers/promises' // Provides bounded polling for this example.
19
+ import { reldb } from '@h-ai/reldb' // Supplies Runner's relational database.
20
+ import { runner } from '@h-ai/runner' // The process-wide Runner instance.
21
+
22
+ const database = await reldb.init({ type: 'sqlite', database: ':memory:' }) // Success is { success: true, data: undefined }.
23
+ if (!database.success)
24
+ throw new Error(database.error.message) // Stop startup if the database is unavailable.
25
+
26
+ try {
27
+ const started = await runner.init({ nodeId: 'worker-east' }) // The default role is executor. isExecutor becomes true on success.
28
+ if (!started.success)
29
+ throw new Error(started.error.message) // Stop startup before submitting work.
30
+
31
+ const registration = runner.register('report.v1', async (input, context) => { // Success returns an unregister callback.
32
+ if (typeof input !== 'string')
33
+ throw new TypeError('Expected report title') // Validate business input in the handler.
34
+ const event = await context.emit({ phase: 'ready' }) // Success persists sequence 1 for other nodes to read.
35
+ if (!event.success)
36
+ throw new Error(event.error.message) // Stop the handler if event persistence fails.
37
+ return { title: input } // Becomes output on the successful execution.
38
+ })
39
+ if (!registration.success)
40
+ throw new Error(registration.error.message) // Duplicate registration fails.
41
+
42
+ const scope = { tenantId: 'studio', userId: 'alice' } // Example identity. Derive it from server authentication in production.
43
+ const accepted = await runner.submit({
44
+ scope,
45
+ kind: 'report.v1',
46
+ idempotencyKey: 'report-nov',
47
+ input: 'Monthly report'
48
+ }) // Returns a queued receipt with a task id.
49
+ if (!accepted.success)
50
+ throw new Error(accepted.error.message) // A failed result has no usable receipt.
51
+
52
+ const deadline = Date.now() + 5_000 // Wait at most five seconds in this example.
53
+ let completed = false // Set to true only after reading a successful terminal state.
54
+ while (Date.now() < deadline) {
55
+ const task = await runner.get(scope, accepted.data.id) // Read status and result for the same principal.
56
+ if (!task.success)
57
+ throw new Error(task.error.message) // Stop if lookup fails.
58
+ if (task.data.status === 'succeeded') {
59
+ process.stdout.write(`${JSON.stringify(task.data.output)}\n`) // Prints {"title":"Monthly report"}.
60
+ completed = true
61
+ break
62
+ }
63
+ if (task.data.status !== 'queued' && task.data.status !== 'running')
64
+ throw new Error(task.data.failure ?? task.data.status) // Execution failure is separate from lookup failure.
65
+ await delay(100) // Wait 100 ms, then return undefined.
66
+ }
67
+ if (!completed)
68
+ throw new Error('Timed out waiting for the report') // Report a timeout. Shutdown attempts to cancel this node's work.
69
+ registration.data() // Unregister the handler and return undefined.
70
+ }
71
+ finally {
72
+ try {
73
+ const closed = await runner.close() // Stop claiming, cancel local work, and wait for cleanup confirmation.
74
+ if (!closed.success) {
75
+ process.stderr.write(`${closed.error.message}\n`) // Report unconfirmed cleanup and leave the database available.
76
+ process.exitCode = 1
77
+ }
78
+ else {
79
+ const released = await reldb.close() // Release database connections. Success is { success: true, data: undefined }.
80
+ if (!released.success) {
81
+ process.stderr.write(`${released.error.message}\n`)
82
+ process.exitCode = 1
83
+ }
84
+ }
85
+ }
86
+ catch (cause) {
87
+ process.stderr.write(`${String(cause)}\n`) // Preserve the original task exception.
88
+ process.exitCode = 1
89
+ }
90
+ }
91
+ ```
92
+
93
+ ## Features
94
+
95
+ | Capability | Use | Public entry points |
96
+ | -------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
97
+ | Node lifecycle | Start API and executor nodes and inspect environments | `init`, `close`, `isExecutor`, `environment`, `createRunner` |
98
+ | Tasks and events | Submit durably, recover a receipt, query, cancel, and page through events | `register`, `submit`, `find`, `get`, `events`, `cancel` |
99
+ | Containers and files | Run a pinned image, use standard streams, and retrieve authorized artifacts | `context.start`, `context.emit`, `process.wait`, `artifact`, `close` |
100
+ | Child jobs and warm pools | Route controls to the parent's node and reserve tool capacity | `submit({ parentId })`, `registerWarmPool` |
101
+ | Unknown execution reconciliation | Verify that a container or host process has stopped and record the operator and reason | `reconcileUnknown` |
102
+
103
+ ### Set node roles and inspect an environment
104
+
105
+ Use `runner` for a single-process app. `createRunner()` returns an independent instance for dependency injection or isolated tests. Multi-node production deployments use shared PostgreSQL or MySQL and consistent environment definitions and concurrency limits. Executor node IDs must be unique and stable across restarts. The example assumes RelDB is running. The deployment supplies `imageId`, an OCI image ID or manifest digest cached on each executor.
106
+
107
+ ```ts
108
+ import type { RunnerConfigInput } from '@h-ai/runner' // Checks settings shared by both roles.
109
+ import { createRunner, RunnerConfigSchema } from '@h-ai/runner' // Factory for instances and Schema for validating settings.
110
+
111
+ function prepareApi(imageId: string) {
112
+ const settings: RunnerConfigInput = {
113
+ nodeId: 'api-east', // Node ID. Give executors their own IDs.
114
+ executor: false, // Submit, query, and cancel tasks from this node.
115
+ environments: [
116
+ {
117
+ id: 'docs', // The environmentId to use at submission.
118
+ image: imageId, // A pinned digest already prepared on executors.
119
+ capabilities: ['documents.extract'], // Allows the caller to choose an environment by capability.
120
+ resources: {
121
+ cpu: 1,
122
+ memoryMiB: 256,
123
+ pids: 64,
124
+ scratchMiB: 64
125
+ }, // Upper limits for this environment.
126
+ }
127
+ ],
128
+ }
129
+ return RunnerConfigSchema.safeParse(settings) // Valid data includes the default podman engine and offline policy.
130
+ }
131
+
132
+ async function startApi(imageId: string) {
133
+ const settings = prepareApi(imageId) // Invalid resource settings or image digests produce Zod issues.
134
+ if (!settings.success)
135
+ throw new Error(settings.error.message)
136
+ const api = createRunner() // A new instance. isExecutor is false before initialization.
137
+ const started = await api.init(settings.data) // Successful result has data: undefined.
138
+ if (!started.success)
139
+ throw new Error(started.error.message)
140
+ const docs = api.environment('docs') // Success contains a configuration copy with data.image equal to imageId.
141
+ if (!docs.success)
142
+ throw new Error(docs.error.message)
143
+ return api // On shutdown, call and check api.close() before closing RelDB.
144
+ }
145
+ ```
146
+
147
+ Executors start with `executor: true` and register trusted handlers with `register(kind, handler)`. API nodes can use the same setup code. Their `register` returns a no-op unregister callback. `environment(id)` returns `NOT_FOUND` for an unknown ID.
148
+
149
+ ### Recover tasks, read events, and cancel
150
+
151
+ Retry an identical submission under the same principal, task kind, and idempotency key to obtain its original receipt. A changed submission returns `CONFLICT`. Trusted services can use `reuseKey` for active executions such as a user's worker. `find` takes the idempotency key. The service manages reuse keys. This function takes an authenticated principal and the idempotency key of an existing `report.v1` receipt.
152
+
153
+ ```ts
154
+ import type { RunnerScope } from '@h-ai/runner' // Contains tenantId and userId.
155
+ import { runner } from '@h-ai/runner' // Initialized against the database that holds the task.
156
+
157
+ async function cancelReport(scope: RunnerScope, key: string) {
158
+ const found = await runner.find(scope, 'report.v1', key) // Returns the original receipt, or success with data: undefined when absent.
159
+ if (!found.success || !found.data)
160
+ return found // Preserve the error or the missing result.
161
+ const id = found.data.id // Use this task id for events, lookup, and cancellation.
162
+ const page = await runner.events(scope, id, 0, 20) // First 20 events with sequence > 0. An empty page is [].
163
+ if (!page.success)
164
+ return page // Preserve a lookup error.
165
+ const after = page.data.at(-1)?.sequence ?? 0 // The last event sequence is the cursor for the next page.
166
+ const next = await runner.events(scope, id, after, 20) // Up to 20 subsequent events in sequence order.
167
+ if (!next.success)
168
+ return next
169
+ const cancelled = await runner.cancel(scope, id) // A queued task goes to cancelled. A running task typically goes to cancelling first.
170
+ if (!cancelled.success)
171
+ return cancelled
172
+ return runner.get(scope, id) // Read current status. Continue polling if needed to confirm the stop.
173
+ }
174
+ ```
175
+
176
+ Cancelling a finished task returns its current state. `events` defaults to `after: 0` and `limit: 100`, with a limit range of `1–100`. Submissions, individual events, and outputs each have a 512 KiB JSON limit. Each execution can persist 16 MiB of events in total, and `maxEvents` also caps their count. Use business object references or executor-side secret management for large files and credentials.
177
+
178
+ Executors use the database clock to remove terminal jobs, reconciled unknown jobs, and their events in batches after `retentionMs`, which defaults to seven days. Unreconciled `unknown` jobs and parents with remaining child records stay in storage. After removal, `find` returns no record and `get` and `events` return `NOT_FOUND`. An idempotency key can be submitted again after expiration. Retry within the retention window and manage longer external idempotency requirements in the application.
179
+
180
+ ### Run an isolated container, stage files, and retrieve artifacts
181
+
182
+ Executors require Linux cgroup v2, Podman or Docker with CPU, memory, and PID limits, and cached pinned images. An image needs `/bin/sh`, must work under UID/GID 1000, and may not declare extra image volumes. The default is offline with a read-only root filesystem. `/state`, `/workspace`, and `/tmp` use bounded temporary filesystems. Networked environments use `networkPolicy: 'internal'` and a named internal network verified by the engine. The deployment owns trust zones and egress rules.
183
+
184
+ This example assumes `docs` is registered and its image provides `cat` and `/usr/bin/python3`. The handler uses a fixed fixture. For real files, recheck the authorized file ID using `context.scope` on the executor, publish the artifact, and return its business ID.
185
+
186
+ ```ts
187
+ import { Buffer } from 'node:buffer' // Encode the input file and decode the returned bytes.
188
+ import { once } from 'node:events' // Wait for the artifact readiness notification on stdout.
189
+ import { core } from '@h-ai/core' // Log unconfirmed cleanup.
190
+ import { runner } from '@h-ai/runner' // Run on an executor node.
191
+
192
+ const registration = runner.register('copy.v1', async (_input, context) => { // Returns an unregister callback. Only the lease owner runs the handler.
193
+ const launched = await context.start({
194
+ command: '/bin/sh', // Trusted entry point in the pinned image.
195
+ args: ['-ec', 'cat /input/source.txt > /output/result.txt; printf ready; read -r done || true'], // Announces readiness and waits for stdin to close.
196
+ inputs: {
197
+ 'source.txt': Buffer.from('hello').toString('base64')
198
+ }, // Creates read-only /input/source.txt containing hello.
199
+ }) // Success contains stdin, stdout, stderr, wait, artifact, and close on a process handle.
200
+ if (!launched.success)
201
+ throw new Error(launched.error.message)
202
+ const process = launched.data // Read the artifact before the container exits.
203
+ try {
204
+ process.stderr.resume() // Drain stderr so it does not block the subprocess.
205
+ await once(process.stdout, 'data', { signal: context.signal }) // The first data comes from the fixed command's readiness notification.
206
+ const artifact = await process.artifact('result.txt', 64) // Success is { success: true, data: 'aGVsbG8=' }.
207
+ if (!artifact.success)
208
+ throw new Error(artifact.error.message)
209
+ process.stdin.end() // Close stdin so the example command can exit.
210
+ const exit = await process.wait() // Normal exit here is { code: 0, signal: null }.
211
+ if (exit.code !== 0)
212
+ throw new Error('Copy failed')
213
+ return {
214
+ text: Buffer.from(artifact.data, 'base64').toString('utf8')
215
+ } // Example output is { text: 'hello' }.
216
+ }
217
+ finally {
218
+ const stopped = await process.close() // Success confirms container removal and returns data: undefined.
219
+ if (!stopped.success)
220
+ core.logger.error('Container cleanup unconfirmed', { code: stopped.error.code }) // Runner checks cleanup after the handler returns.
221
+ }
222
+ })
223
+ if (!registration.success)
224
+ throw new Error(registration.error.message)
225
+ ```
226
+
227
+ Submit `{ scope, kind: 'copy.v1', input: null, environmentId: 'docs' }` to queue the job. `context.start` is available once per job. `files` puts startup text files in `/state`, `env` goes to the container process, and `cwd` defaults to `/workspace`. `inputs` accepts up to 8 flat files with a total decoded size capped at the smaller of 50 MiB and `scratchMiB`. `artifact` reads a regular file from `/output` in a still-running container and applies both the requested `maxBytes` and a 50 MiB hard limit. Check artifact ownership before providing downloads.
228
+
229
+ ### Route child jobs, cap tool concurrency, and prewarm
230
+
231
+ `parentId` routes a child job to the current executor and generation of a running parent under the same principal. Use this for controls on an open connection. `maxControlRunning` caps concurrent control jobs. `capacityClass: 'tool'` uses a separate tool budget. `concurrency: { key, limit }` caps active jobs of the same kind and service key across nodes.
232
+
233
+ ```ts
234
+ import type { RunnerScope } from '@h-ai/runner' // Comes from server authentication or the trusted parent handler.
235
+ import { runner } from '@h-ai/runner' // Connected to the shared database.
236
+
237
+ async function sendControl(scope: RunnerScope, parentId: string) {
238
+ return runner.submit({
239
+ scope,
240
+ parentId,
241
+ kind: 'worker.control',
242
+ input: { operation: 'status' }
243
+ }) // A queued receipt, or a conflict for an ended or mismatched parent.
244
+ }
245
+
246
+ function registerCopyPool() {
247
+ return runner.registerWarmPool({
248
+ key: 'docs-copy',
249
+ kind: 'copy.v1',
250
+ environmentId: 'docs',
251
+ minReady: 1,
252
+ maxRunning: 2,
253
+ maxTotal: 3
254
+ }) // Success returns an unregister callback. Executors must first register copy.v1.
255
+ }
256
+
257
+ async function queuePrewarmedCopy(scope: RunnerScope) {
258
+ return runner.submit({
259
+ scope,
260
+ kind: 'copy.v1',
261
+ input: null,
262
+ environmentId: 'docs',
263
+ capacityClass: 'tool',
264
+ warmPool: true,
265
+ concurrency: { key: 'docs-copy', limit: 2 }
266
+ }) // Returns a queued receipt. An executor assigns a single-use container.
267
+ }
268
+ ```
269
+
270
+ Register `worker.control` on executor nodes. Call `registerCopyPool()` once at startup and check `success`, with the same configuration on API and executor nodes. Each prewarmed container handles one job and receives user files only after claim. `maxTotal` includes preparing, standby, running, cleaning, and unverified instances. `maxRunning` limits active jobs. Prewarming requires `/usr/bin/python3` and an offline environment. Launch jobs with `inputs`, the `/workspace` working directory, and empty `env` and `files`. To retire the pool, stop accepting its jobs and invoke the unregister callback to release locally unclaimed containers.
271
+
272
+ ### Reconcile an unknown execution
273
+
274
+ A lost lease or unconfirmed cleanup can mark a task `unknown` while retaining its resource reservation. Inspect the actual container and external effects before calling the administrative operation on the original executor. Runner verifies engine identity, container removal, and local staging cleanup, and retains an audit record.
275
+
276
+ For a trusted host job without a container, supply `hostResourcesStopped: true` after checking that all application-managed resources have stopped. Runner verifies the original process has exited on the same Linux host, boot, and PID namespace. A child control job also requires a terminal or reconciled parent. Legacy records without process evidence and container jobs missing their container receipt keep their reservation.
277
+
278
+ ```ts
279
+ import type { RunnerScope } from '@h-ai/runner' // Obtain from task ownership and an authenticated administrative session.
280
+ import { runner } from '@h-ai/runner' // Use the Runner instance on the original executor node.
281
+
282
+ async function reconcile(scope: RunnerScope, id: string) {
283
+ const checked = await runner.reconcileUnknown(scope, id, { operatorId: 'ops-1', reason: 'INC-47: container cleanup verified' }) // Success returns an unknown receipt with reconciledAt.
284
+ if (!checked.success)
285
+ return checked // Preserve the error and reservation when evidence is missing, the container is running, or the engine differs.
286
+ return checked // Resource budget and reuse key are released. The application still verifies external effects.
287
+ }
288
+
289
+ async function reconcileHost(scope: RunnerScope, id: string) {
290
+ const checked = await runner.reconcileUnknown(scope, id, { operatorId: 'ops-1', reason: 'INC-48: host resources verified', hostResourcesStopped: true }) // Submit the operator's attestation and read an unknown receipt with reconciledAt on success.
291
+ if (!checked.success)
292
+ return checked // Keep the reservation if the original process is alive, the parent is unresolved, or local evidence is missing.
293
+ return checked // Resources were released. The application still verifies external effects.
294
+ }
295
+ ```
296
+
297
+ ## Configuration
298
+
299
+ Pass an object to `runner.init(config)` from the application's deployment configuration. Use `RunnerConfigSchema.safeParse(config)` to validate it ahead of startup. Durations below are in milliseconds. The host must have resources for both node budgets.
300
+
301
+ | Field | Default | Purpose |
302
+ | ------------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
303
+ | `nodeId` | Required | Stable node ID across restarts |
304
+ | `executor`, `engine` | `true`, `podman` | Role and container engine. Also supports `docker` |
305
+ | `capacity` | `4 CPU / 4096 MiB / 512 PID / 2048 MiB` | Ordinary budget for CPU, memory, PIDs, and scratch |
306
+ | `toolCapacity`, `toolMaxRunning` | `1 CPU / 1024 MiB / 128 PID / 512 MiB`, `4` | Separate per-node tool budget and concurrency |
307
+ | `maxRunning`, `maxRunningPerScope`, `maxControlRunning` | `8`, `4`, `8` | Ordinary node, principal, and node control-job concurrency |
308
+ | `maxQueued`, `maxEvents` | `5000`, `10000` | Queue limits for ordinary and control jobs, and durable event count per execution |
309
+ | `retentionMs` | `604800000` | Retention for terminal jobs and events, from 1 hour to 365 days. Use the same value on all nodes in a deployment |
310
+ | `leaseMs`, `pollMs`, `closeTimeoutMs` | `10000`, `50`, `20000` | Lease, polling, and shutdown wait. `pollMs × 3` must be below `leaseMs` |
311
+ | `environments` | `[]` | IDs, pinned images, resource limits, optional `architecture` and `capabilities`. `offline` is the default. `internal` requires `network` |
312
+
313
+ Use `resources` to request lower limits than the selected environment. `queueTimeoutMs` and `runTimeoutMs` both default to `300000`. Trusted services can pin a job to `nodeId` or attach it to a running parent with `parentId`. Warm jobs use the registered environment limits.
314
+
315
+ ## Error Handling
316
+
317
+ Check `result.success` before reading `data` or `error`. `HaiRunnerError` defines initialization, invalid input, missing task, conflict, capacity, lost lease, and unconfirmed cleanup errors. Handler failures appear as `status: 'failed'` and `failure` inside a successful `get()` result. Successful `cancel()` acknowledges the request. Read the task state to confirm its stop. If `close()` cannot confirm cleanup, keep the database connection available while inspecting or retrying shutdown.
318
+
319
+ ## Development
320
+
321
+ Run from the repository root (use `pnpm.cmd` in PowerShell). SQLite covers task flow, PostgreSQL and MySQL cover shared ownership, and Podman/Docker cover actual container limits, cancellation, and artifacts. Set `HAI_TEST_CONTAINER_ENGINE` to choose the container engine. Database tests also need a Docker-compatible Testcontainers endpoint. Set `HAI_TEST_RUNNER_ARTIFACT_IMAGE` to a prebuilt tool test image to enable artifact and cross-node warm-pool tests.
322
+
323
+ ```sh
324
+ pnpm --filter @h-ai/runner typecheck
325
+ pnpm --filter @h-ai/runner lint
326
+ pnpm --filter @h-ai/runner build
327
+ pnpm --filter @h-ai/runner test
328
+ ```
329
+
330
+ ## License
331
+
332
+ Apache-2.0