@kindgi/handler 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 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,35 @@
1
1
  # @kindgi/handler
2
2
 
3
- A placeholder. Releases come from https://github.com/kindgi/kindgi-sdk.
3
+ Kindgi™ pack-author authoring surface.
4
+
5
+ **Every handler you write against Kindgi runs against the contract in
6
+ this package.** Runtime implementations (such as the Kindgi runtime)
7
+ execute your handlers against these types.
8
+
9
+ Types plus one error class (`WaitpointCancelledError`); no other runtime
10
+ code.
11
+
12
+ ## Exports
13
+
14
+ | Symbol | Kind | What it is |
15
+ | --- | --- | --- |
16
+ | `NodeHandler` | type | `(input: unknown, ctx: NodeContext) => Promise<HandlerResult \| unknown>` |
17
+ | `NodeContext` | type | What handlers receive: `runId`, `nodeId`, `tenantId`, `nodeOutputs`, `state`, `abortSignal`, `dryRun`, `principal?`, `authorize`, `can`, `check`, `clockNow`, `waitForToken` |
18
+ | `HandlerResult` | type | Optional structured return — `{ output, stateDelta? }` |
19
+ | `HandlerRegistry` | type | `ReadonlyMap<NodeId, NodeHandler>` |
20
+ | `LoopContext` | type | Loop annotation (`loopNodeId`, `iteration`, enclosing-loop `path`) on the journal entries of nodes that ran inside a loop body |
21
+ | `LoopNodeOutput` | type | Return shape of a loop node |
22
+ | `WaitpointCancelledError` | class | Thrown by `ctx.waitForToken(...)` when the wait is cancelled externally |
23
+
24
+ ## What does NOT live here
25
+
26
+ - Wire-vocabulary types (`RunStatus`, `RunResult`, `JournalEntry`,
27
+ trigger schemas, error shapes) — those are in **`@kindgi/runtime`**.
28
+ - Concrete runtime functions (`runGraph`, `resumeRun`, `cancelToken`,
29
+ etc.) — the Kindgi runtime implements them; they are declared on
30
+ `RunBinding` in `@kindgi/runtime` and reached through the
31
+ `KernelBinding` plugged into `createApp`.
32
+
33
+ ## License
34
+
35
+ Apache License 2.0 — see [LICENSE](./LICENSE).
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './suspension.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export * from './types.js';
4
+ export * from './suspension.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { NodeId } from '@kindgi/types';
2
+ /**
3
+ * Thrown from `NodeContext.waitForToken()` on flow replay when the
4
+ * waitpoint was cancelled externally (`RunBinding.cancelToken` in
5
+ * `@kindgi/runtime`, or a timeout) before a decision was recorded.
6
+ * Distinct JS Error class so a handler's `try { ... } catch (e) { ... }`
7
+ * can branch on the cancellation reason.
8
+ *
9
+ * Uncaught → propagates to the executor's dispatch catch, which treats
10
+ * it as a normal handler failure and journals `step.failed` with the
11
+ * reason attributed. Callers who want to handle the cancel gracefully
12
+ * (HITL: turn the reject into a clean `hitl-cancelled` failure) catch
13
+ * it explicitly and translate.
14
+ */
15
+ export declare class WaitpointCancelledError extends Error {
16
+ readonly tokenId: string;
17
+ readonly nodeId: NodeId;
18
+ readonly reason: string;
19
+ constructor(tokenId: string, nodeId: NodeId, reason: string);
20
+ }
21
+ //# sourceMappingURL=suspension.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspension.d.ts","sourceRoot":"","sources":["../src/suspension.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAE5C;;;;;;;;;;;;GAYG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBACZ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAO5D"}
@@ -0,0 +1,28 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ /**
4
+ * Thrown from `NodeContext.waitForToken()` on flow replay when the
5
+ * waitpoint was cancelled externally (`RunBinding.cancelToken` in
6
+ * `@kindgi/runtime`, or a timeout) before a decision was recorded.
7
+ * Distinct JS Error class so a handler's `try { ... } catch (e) { ... }`
8
+ * can branch on the cancellation reason.
9
+ *
10
+ * Uncaught → propagates to the executor's dispatch catch, which treats
11
+ * it as a normal handler failure and journals `step.failed` with the
12
+ * reason attributed. Callers who want to handle the cancel gracefully
13
+ * (HITL: turn the reject into a clean `hitl-cancelled` failure) catch
14
+ * it explicitly and translate.
15
+ */
16
+ export class WaitpointCancelledError extends Error {
17
+ tokenId;
18
+ nodeId;
19
+ reason;
20
+ constructor(tokenId, nodeId, reason) {
21
+ super(`Waitpoint "${tokenId}" at node "${nodeId}" was cancelled: ${reason}`);
22
+ this.name = 'WaitpointCancelledError';
23
+ this.tokenId = tokenId;
24
+ this.nodeId = nodeId;
25
+ this.reason = reason;
26
+ }
27
+ }
28
+ //# sourceMappingURL=suspension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspension.js","sourceRoot":"","sources":["../src/suspension.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAIjC;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACvC,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,MAAM,CAAS;IACxB,YAAY,OAAe,EAAE,MAAc,EAAE,MAAc;QACzD,KAAK,CAAC,cAAc,OAAO,cAAc,MAAM,oBAAoB,MAAM,EAAE,CAAC,CAAC;QAC7E,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF"}
@@ -0,0 +1,169 @@
1
+ import type { Action, Decision, Principal, ResourceRef } from '@kindgi/authz';
2
+ import type { NodeId, RunId, TenantId } from '@kindgi/types';
3
+ /**
4
+ * A node handler is the concrete code the runtime invokes when a flow
5
+ * node becomes ready. The handler is entirely user-authored; the
6
+ * runtime only knows how to route input, capture output, and journal
7
+ * state.
8
+ *
9
+ * Handlers may return:
10
+ * - a bare `unknown` value → recorded as `nodeOutputs[nodeId]`.
11
+ * - a `HandlerResult` with `{ output, stateDelta? }` → same, plus the
12
+ * `stateDelta` is shallow-merged into the run's cumulative `state`.
13
+ *
14
+ * `input` is the node's resolved `inputMapping` when the flow declares one
15
+ * for it; otherwise the output of the single upstream node, or the run
16
+ * input for a `$start` edge. Fan-in handlers (a node with N > 1 upstream
17
+ * edges) without an `inputMapping` receive `input === undefined` and read
18
+ * their siblings' outputs via `ctx.nodeOutputs.get(id)`.
19
+ */
20
+ export type NodeHandler = (input: unknown, ctx: NodeContext) => Promise<HandlerResult | unknown>;
21
+ /**
22
+ * Structured handler return. Prefer this over a bare value when the node
23
+ * contributes to cumulative `state`.
24
+ */
25
+ export interface HandlerResult {
26
+ readonly output: unknown;
27
+ /**
28
+ * Shallow-merged into the run's cumulative `state` on next tick. Under
29
+ * concurrent completions the highest journal sequence wins per key.
30
+ */
31
+ readonly stateDelta?: Readonly<Record<string, unknown>>;
32
+ }
33
+ /**
34
+ * Runtime binding of `NodeId → NodeHandler`. Passed to the runtime
35
+ * alongside the flow. Every node in the flow must have a matching
36
+ * handler entry; missing handlers are rejected at run start.
37
+ */
38
+ export type HandlerRegistry = ReadonlyMap<NodeId, NodeHandler>;
39
+ /**
40
+ * Context passed to a node handler. All non-deterministic operations
41
+ * (clock reads, random) MUST go through this so replay from journal
42
+ * yields the same values.
43
+ *
44
+ * Also exposes the read-only cumulative state and prior node outputs the
45
+ * handler may consult — same view the edge predicates saw when this node
46
+ * was scheduled.
47
+ */
48
+ export interface NodeContext {
49
+ readonly runId: RunId;
50
+ readonly nodeId: NodeId;
51
+ /** The tenant this run belongs to — required for any tenant-scoped I/O. */
52
+ readonly tenantId: TenantId;
53
+ /**
54
+ * Read-only outputs of previously-completed nodes, keyed by `NodeId`.
55
+ * Present for fan-in and cross-branch reads.
56
+ */
57
+ readonly nodeOutputs: ReadonlyMap<NodeId, unknown>;
58
+ /** Read-only cumulative state at the moment this node was dispatched. */
59
+ readonly state: Readonly<Record<string, unknown>>;
60
+ /**
61
+ * Signal that fires when the run is being torn down — either because
62
+ * cancelRun() was invoked or because a sibling handler failed and the
63
+ * runtime is completing outstanding siblings before marking the run failed.
64
+ *
65
+ * Cooperative handlers should observe this and exit early; uncooperative
66
+ * handlers still run to completion, and the runtime journals whatever they
67
+ * return / throw. The run does not become terminal until every in-flight
68
+ * handler settles.
69
+ */
70
+ readonly abortSignal: AbortSignal;
71
+ /**
72
+ * `true` when this run was started with `RunOptions.dryRun: true`.
73
+ * Handlers with side effects (tool invocation, model calls, DB writes,
74
+ * memory writes) should observe this and self-mock — return
75
+ * schema-conformant planned outputs without actually causing the side
76
+ * effect. Runtime-managed journal writes still happen as normal; the
77
+ * run record is marked `dryRun: true`.
78
+ */
79
+ readonly dryRun: boolean;
80
+ /**
81
+ * The Principal that started this run — user session, agent
82
+ * delegation chain, service_account, or systemPrincipal. Present
83
+ * ONLY when the run was started with a `principal`
84
+ * (`RunFlowInput.principal` in `@kindgi/runtime`); absent otherwise.
85
+ *
86
+ * Handlers that need to construct sub-principals for downstream
87
+ * calls (e.g. delegate(agent, this.principal)) read this here.
88
+ */
89
+ readonly principal?: Principal;
90
+ /**
91
+ * Authz check that THROWS on deny. Preferred inside handlers that
92
+ * expect the happy path (invoke tool, read secret). The thrown
93
+ * error is caught by the runtime's dispatch loop and journaled as
94
+ * `step.failed` with reason `permission-denied`.
95
+ *
96
+ * No-op when the run was started without `authz` configured —
97
+ * exists so handlers can be written uniformly for runs with and
98
+ * without authorization.
99
+ */
100
+ authorize(action: Action, resource: ResourceRef): Promise<void>;
101
+ /** Non-throwing check — returns a boolean. For conditional logic. */
102
+ can(action: Action, resource: ResourceRef): Promise<boolean>;
103
+ /** Full Decision — for advanced cases needing reason/evidence. */
104
+ check(action: Action, resource: ResourceRef): Promise<Decision>;
105
+ /** Read the clock. First call journals `Date.now()`; on replay, returns the journaled value. */
106
+ clockNow(): Promise<number>;
107
+ /**
108
+ * Suspend the handler and wait for an external `completeToken(tokenId,
109
+ * value)`. On first invocation: journals `wait.suspended`, inserts a
110
+ * pending waitpoint row, and throws an internal suspension signal — the
111
+ * executor catches this specific class, marks the run `suspended`, and
112
+ * exits the tick loop cleanly (no `step.failed`).
113
+ *
114
+ * On handler re-invocation after `completeToken` + `resumeRun`, the same
115
+ * `ctx.waitForToken(tokenId)` call reads the `wait.resumed` value from
116
+ * the journal and returns it.
117
+ *
118
+ * **Determinism:** callers must issue `waitForToken` with the same
119
+ * `tokenId` in the same call order across replays. The value type `T`
120
+ * is caller-asserted; the runtime does not validate the resolved shape.
121
+ *
122
+ * **Node re-runs on resume.** Any handler side effects that happened
123
+ * before the first `waitForToken` will re-run on each resume — structure
124
+ * work so side effects live *after* the wait, or make them idempotent.
125
+ *
126
+ * `timeoutMs`: optional deadline. When set, the waitpoint timeout
127
+ * sleeper (`WaitpointBinding` in `@kindgi/runtime`) cancels this
128
+ * waitpoint with `reason: 'timeout'` if it hasn't resolved by
129
+ * `Date.now() + timeoutMs`. The handler's re-invocation after cancel
130
+ * throws `WaitpointCancelledError` from `waitForToken`. Timeout is
131
+ * stored on the waitpoint row — durable across process restarts.
132
+ */
133
+ waitForToken<T>(tokenId: string, options?: {
134
+ timeoutMs?: number;
135
+ }): Promise<T>;
136
+ }
137
+ /**
138
+ * Loop-context annotation attached to journal payloads of nodes and edges
139
+ * that ran inside a loop body. Absent on outer-flow entries.
140
+ *
141
+ * `iteration` is the 0-based index within the enclosing loop.
142
+ * `path` is the innermost-first stack of enclosing loops when nested
143
+ * (single-element for a flat loop, N-element for N-deep nesting).
144
+ */
145
+ export interface LoopContext {
146
+ readonly loopNodeId: NodeId;
147
+ readonly iteration: number;
148
+ readonly path: readonly {
149
+ readonly loopNodeId: NodeId;
150
+ readonly iteration: number;
151
+ }[];
152
+ }
153
+ /**
154
+ * The output produced by a loop node (visible to downstream outer-flow
155
+ * nodes as `nodeOutputs.get(loopNodeId)` and matches the loop's declared
156
+ * `outputSchema` for `finalOutput` and each element of `outputs`).
157
+ *
158
+ * `stopReason` on the loop-node output cannot be `'output-schema-violation'`,
159
+ * `'body-failure'`, or `'cancelled'` — those cause the loop node itself
160
+ * to fail (`step.failed`), so no `nodeOutputs` entry is written for the
161
+ * loop.
162
+ */
163
+ export interface LoopNodeOutput<TFinal = unknown> {
164
+ readonly finalOutput: TFinal;
165
+ readonly iterations: number;
166
+ readonly stopReason: 'exit-condition' | 'max-iterations' | 'array-exhausted';
167
+ readonly outputs?: readonly TFinal[];
168
+ }
169
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9E,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE7D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,aAAa,GAAG,OAAO,CAAC,CAAC;AAEjG;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACzD;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAE/D;;;;;;;;GAQG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,2EAA2E;IAC3E,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,yEAAyE;IACzE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAClD;;;;;;;;;OASG;IACH,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC;;;;;;;OAOG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;;;;;;;OAQG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;IAC/B;;;;;;;;;OASG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChE,qEAAqE;IACrE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7D,kEAAkE;IAClE,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAChE,gGAAgG;IAChG,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAChF;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,SAAS;QAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CACvF;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,cAAc,CAAC,MAAM,GAAG,OAAO;IAC9C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,iBAAiB,CAAC;IAC7E,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC"}
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export {};
4
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC"}
package/package.json CHANGED
@@ -1,7 +1,51 @@
1
1
  {
2
2
  "name": "@kindgi/handler",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Placeholder so a trusted publisher can be attached. Releases are published from https://github.com/kindgi/kindgi-sdk with provenance; use 0.1.0 or later.",
3
+ "version": "0.1.0",
4
+ "description": "Kindgi™ pack-author authoring surface. The types a pack author writes handlers against: NodeHandler (the function signature), NodeContext (what handlers receive at invocation — run scope, sibling outputs, waitForToken, authorize, clockNow, etc.), HandlerResult (structured return with optional stateDelta), HandlerRegistry (NodeId → NodeHandler map), LoopContext + LoopNodeOutput (loop-node shapes), plus WaitpointCancelledError (thrown by waitForToken when the wait is cancelled externally). Types plus that one error class — no other runtime code. Every runtime that executes Kindgi handlers implements this contract.",
5
5
  "license": "Apache-2.0",
6
- "repository": { "type": "git", "url": "git+https://github.com/kindgi/kindgi-sdk.git" }
7
- }
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kindgi/kindgi-sdk.git",
9
+ "directory": "packages/handler"
10
+ },
11
+ "homepage": "https://github.com/kindgi/kindgi-sdk/tree/main/packages/handler#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/kindgi/kindgi-sdk/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "src",
27
+ "README.md"
28
+ ],
29
+ "dependencies": {
30
+ "@kindgi/authz": "0.1.0",
31
+ "@kindgi/types": "0.1.0"
32
+ },
33
+ "engines": {
34
+ "node": ">=22.0.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.10.5",
42
+ "typescript": "^5.7.3",
43
+ "vitest": "^2.1.8"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.build.json",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run --typecheck --typecheck.only --passWithNoTests",
49
+ "clean": "rm -rf dist *.tsbuildinfo"
50
+ }
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ export * from './types.js';
5
+ export * from './suspension.js';
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import type { NodeId } from '@kindgi/types';
5
+
6
+ /**
7
+ * Thrown from `NodeContext.waitForToken()` on flow replay when the
8
+ * waitpoint was cancelled externally (`RunBinding.cancelToken` in
9
+ * `@kindgi/runtime`, or a timeout) before a decision was recorded.
10
+ * Distinct JS Error class so a handler's `try { ... } catch (e) { ... }`
11
+ * can branch on the cancellation reason.
12
+ *
13
+ * Uncaught → propagates to the executor's dispatch catch, which treats
14
+ * it as a normal handler failure and journals `step.failed` with the
15
+ * reason attributed. Callers who want to handle the cancel gracefully
16
+ * (HITL: turn the reject into a clean `hitl-cancelled` failure) catch
17
+ * it explicitly and translate.
18
+ */
19
+ export class WaitpointCancelledError extends Error {
20
+ readonly tokenId: string;
21
+ readonly nodeId: NodeId;
22
+ readonly reason: string;
23
+ constructor(tokenId: string, nodeId: NodeId, reason: string) {
24
+ super(`Waitpoint "${tokenId}" at node "${nodeId}" was cancelled: ${reason}`);
25
+ this.name = 'WaitpointCancelledError';
26
+ this.tokenId = tokenId;
27
+ this.nodeId = nodeId;
28
+ this.reason = reason;
29
+ }
30
+ }
package/src/types.ts ADDED
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import type { Action, Decision, Principal, ResourceRef } from '@kindgi/authz';
5
+ import type { NodeId, RunId, TenantId } from '@kindgi/types';
6
+
7
+ /**
8
+ * A node handler is the concrete code the runtime invokes when a flow
9
+ * node becomes ready. The handler is entirely user-authored; the
10
+ * runtime only knows how to route input, capture output, and journal
11
+ * state.
12
+ *
13
+ * Handlers may return:
14
+ * - a bare `unknown` value → recorded as `nodeOutputs[nodeId]`.
15
+ * - a `HandlerResult` with `{ output, stateDelta? }` → same, plus the
16
+ * `stateDelta` is shallow-merged into the run's cumulative `state`.
17
+ *
18
+ * `input` is the node's resolved `inputMapping` when the flow declares one
19
+ * for it; otherwise the output of the single upstream node, or the run
20
+ * input for a `$start` edge. Fan-in handlers (a node with N > 1 upstream
21
+ * edges) without an `inputMapping` receive `input === undefined` and read
22
+ * their siblings' outputs via `ctx.nodeOutputs.get(id)`.
23
+ */
24
+ export type NodeHandler = (input: unknown, ctx: NodeContext) => Promise<HandlerResult | unknown>;
25
+
26
+ /**
27
+ * Structured handler return. Prefer this over a bare value when the node
28
+ * contributes to cumulative `state`.
29
+ */
30
+ export interface HandlerResult {
31
+ readonly output: unknown;
32
+ /**
33
+ * Shallow-merged into the run's cumulative `state` on next tick. Under
34
+ * concurrent completions the highest journal sequence wins per key.
35
+ */
36
+ readonly stateDelta?: Readonly<Record<string, unknown>>;
37
+ }
38
+
39
+ /**
40
+ * Runtime binding of `NodeId → NodeHandler`. Passed to the runtime
41
+ * alongside the flow. Every node in the flow must have a matching
42
+ * handler entry; missing handlers are rejected at run start.
43
+ */
44
+ export type HandlerRegistry = ReadonlyMap<NodeId, NodeHandler>;
45
+
46
+ /**
47
+ * Context passed to a node handler. All non-deterministic operations
48
+ * (clock reads, random) MUST go through this so replay from journal
49
+ * yields the same values.
50
+ *
51
+ * Also exposes the read-only cumulative state and prior node outputs the
52
+ * handler may consult — same view the edge predicates saw when this node
53
+ * was scheduled.
54
+ */
55
+ export interface NodeContext {
56
+ readonly runId: RunId;
57
+ readonly nodeId: NodeId;
58
+ /** The tenant this run belongs to — required for any tenant-scoped I/O. */
59
+ readonly tenantId: TenantId;
60
+ /**
61
+ * Read-only outputs of previously-completed nodes, keyed by `NodeId`.
62
+ * Present for fan-in and cross-branch reads.
63
+ */
64
+ readonly nodeOutputs: ReadonlyMap<NodeId, unknown>;
65
+ /** Read-only cumulative state at the moment this node was dispatched. */
66
+ readonly state: Readonly<Record<string, unknown>>;
67
+ /**
68
+ * Signal that fires when the run is being torn down — either because
69
+ * cancelRun() was invoked or because a sibling handler failed and the
70
+ * runtime is completing outstanding siblings before marking the run failed.
71
+ *
72
+ * Cooperative handlers should observe this and exit early; uncooperative
73
+ * handlers still run to completion, and the runtime journals whatever they
74
+ * return / throw. The run does not become terminal until every in-flight
75
+ * handler settles.
76
+ */
77
+ readonly abortSignal: AbortSignal;
78
+ /**
79
+ * `true` when this run was started with `RunOptions.dryRun: true`.
80
+ * Handlers with side effects (tool invocation, model calls, DB writes,
81
+ * memory writes) should observe this and self-mock — return
82
+ * schema-conformant planned outputs without actually causing the side
83
+ * effect. Runtime-managed journal writes still happen as normal; the
84
+ * run record is marked `dryRun: true`.
85
+ */
86
+ readonly dryRun: boolean;
87
+ /**
88
+ * The Principal that started this run — user session, agent
89
+ * delegation chain, service_account, or systemPrincipal. Present
90
+ * ONLY when the run was started with a `principal`
91
+ * (`RunFlowInput.principal` in `@kindgi/runtime`); absent otherwise.
92
+ *
93
+ * Handlers that need to construct sub-principals for downstream
94
+ * calls (e.g. delegate(agent, this.principal)) read this here.
95
+ */
96
+ readonly principal?: Principal;
97
+ /**
98
+ * Authz check that THROWS on deny. Preferred inside handlers that
99
+ * expect the happy path (invoke tool, read secret). The thrown
100
+ * error is caught by the runtime's dispatch loop and journaled as
101
+ * `step.failed` with reason `permission-denied`.
102
+ *
103
+ * No-op when the run was started without `authz` configured —
104
+ * exists so handlers can be written uniformly for runs with and
105
+ * without authorization.
106
+ */
107
+ authorize(action: Action, resource: ResourceRef): Promise<void>;
108
+ /** Non-throwing check — returns a boolean. For conditional logic. */
109
+ can(action: Action, resource: ResourceRef): Promise<boolean>;
110
+ /** Full Decision — for advanced cases needing reason/evidence. */
111
+ check(action: Action, resource: ResourceRef): Promise<Decision>;
112
+ /** Read the clock. First call journals `Date.now()`; on replay, returns the journaled value. */
113
+ clockNow(): Promise<number>;
114
+ /**
115
+ * Suspend the handler and wait for an external `completeToken(tokenId,
116
+ * value)`. On first invocation: journals `wait.suspended`, inserts a
117
+ * pending waitpoint row, and throws an internal suspension signal — the
118
+ * executor catches this specific class, marks the run `suspended`, and
119
+ * exits the tick loop cleanly (no `step.failed`).
120
+ *
121
+ * On handler re-invocation after `completeToken` + `resumeRun`, the same
122
+ * `ctx.waitForToken(tokenId)` call reads the `wait.resumed` value from
123
+ * the journal and returns it.
124
+ *
125
+ * **Determinism:** callers must issue `waitForToken` with the same
126
+ * `tokenId` in the same call order across replays. The value type `T`
127
+ * is caller-asserted; the runtime does not validate the resolved shape.
128
+ *
129
+ * **Node re-runs on resume.** Any handler side effects that happened
130
+ * before the first `waitForToken` will re-run on each resume — structure
131
+ * work so side effects live *after* the wait, or make them idempotent.
132
+ *
133
+ * `timeoutMs`: optional deadline. When set, the waitpoint timeout
134
+ * sleeper (`WaitpointBinding` in `@kindgi/runtime`) cancels this
135
+ * waitpoint with `reason: 'timeout'` if it hasn't resolved by
136
+ * `Date.now() + timeoutMs`. The handler's re-invocation after cancel
137
+ * throws `WaitpointCancelledError` from `waitForToken`. Timeout is
138
+ * stored on the waitpoint row — durable across process restarts.
139
+ */
140
+ waitForToken<T>(tokenId: string, options?: { timeoutMs?: number }): Promise<T>;
141
+ }
142
+
143
+ /**
144
+ * Loop-context annotation attached to journal payloads of nodes and edges
145
+ * that ran inside a loop body. Absent on outer-flow entries.
146
+ *
147
+ * `iteration` is the 0-based index within the enclosing loop.
148
+ * `path` is the innermost-first stack of enclosing loops when nested
149
+ * (single-element for a flat loop, N-element for N-deep nesting).
150
+ */
151
+ export interface LoopContext {
152
+ readonly loopNodeId: NodeId;
153
+ readonly iteration: number;
154
+ readonly path: readonly { readonly loopNodeId: NodeId; readonly iteration: number }[];
155
+ }
156
+
157
+ /**
158
+ * The output produced by a loop node (visible to downstream outer-flow
159
+ * nodes as `nodeOutputs.get(loopNodeId)` and matches the loop's declared
160
+ * `outputSchema` for `finalOutput` and each element of `outputs`).
161
+ *
162
+ * `stopReason` on the loop-node output cannot be `'output-schema-violation'`,
163
+ * `'body-failure'`, or `'cancelled'` — those cause the loop node itself
164
+ * to fail (`step.failed`), so no `nodeOutputs` entry is written for the
165
+ * loop.
166
+ */
167
+ export interface LoopNodeOutput<TFinal = unknown> {
168
+ readonly finalOutput: TFinal;
169
+ readonly iterations: number;
170
+ readonly stopReason: 'exit-condition' | 'max-iterations' | 'array-exhausted';
171
+ readonly outputs?: readonly TFinal[];
172
+ }