@godspeedai/cognate-ag-ui 0.0.0-stage → 0.1.1

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.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +43 -2
  3. package/package.json +33 -4
  4. package/src/index.ts +623 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
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,44 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-ag-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ AG-UI 1.0.0 interoperability adapter (spec §24, §31.8, §32; ADR-0008). An
4
+ optional boundary, not the internal event model: native Cognate execution
5
+ and UI work unchanged if this package is removed (spec §40.H).
6
+
7
+ - `createProjector` folds a run's durable event stream into schema-valid
8
+ AG-UI events (bracketed text messages, tool calls, state snapshots/deltas,
9
+ continuation CUSTOM events, RUN_FINISHED/RUN_ERROR).
10
+ - `createAgUiHandler` is an HTTP endpoint: POST `RunAgentInput` → SSE stream.
11
+ Actions (start, resolve a continuation, cancel) go through
12
+ `RuntimeService` with the transport-authenticated caller. A valid
13
+ `forwardedProps.cognate.cursor` resumes with `STATE_SNAPSHOT` + newer
14
+ events; an unknown/expired cursor triggers a full resync
15
+ (`RUN_STARTED`, `MESSAGES_SNAPSHOT`, `STATE_SNAPSHOT`, …). Disconnecting
16
+ never cancels the durable run.
17
+
18
+ ## Compatibility matrix (`matrix`, `ignoredFrameworkEvents`)
19
+
20
+ All 31 AG-UI 1.0.0 `EventType` values are covered, one row each:
21
+
22
+ - **Supported (outbound):** `RUN_STARTED`, `RUN_FINISHED`, `RUN_ERROR`,
23
+ `TEXT_MESSAGE_*` (not `_CHUNK`), `TOOL_CALL_*` (not `_CHUNK`),
24
+ `STATE_SNAPSHOT`, `STATE_DELTA`, `MESSAGES_SNAPSHOT`, `CUSTOM`.
25
+ - **Unsupported (none):** the `_CHUNK` shorthands, `ACTIVITY_*`, `RAW`,
26
+ `STEP_*`, `REASONING_*`, `SUBAGENT_*` — Cognate has no matching concept
27
+ yet; each row's `note` says why.
28
+ - `TOOL_CALL_ARGS` carries the recorded invocation input (`run.invocation`
29
+ payload `input`; `{}` after that payload is erased).
30
+
31
+ `ignoredFrameworkEvents` lists Cognate event types deliberately not
32
+ projected: `run.step.completed`, `run.resumed`, `run.wait.closed`,
33
+ `run.recall` (replay/determinism bookkeeping). Artifacts are projected as
34
+ `CUSTOM` `cognate.artifact` events (AG-UI 1.0.0 has no artifact event).
35
+
36
+ ## Continuation mapping
37
+
38
+ A `frontend_capability` continuation (or `type: "frontend:<capability>"`,
39
+ runtime-api's convention) becomes `TOOL_CALL_START/ARGS/END` with
40
+ `toolCallId` = the continuation id. A `human_approval` continuation becomes
41
+ `CUSTOM "cognate.continuation"`. Any other kind (e.g. `oauth_callback`) has
42
+ no faithful AG-UI representation and becomes
43
+ `CUSTOM "cognate.unsupported_interaction"`, and the run's `RUN_FINISHED`
44
+ reports `status: "waiting_unsupported"` instead of `"waiting"`.
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-ag-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "AG-UI projection and interoperability adapter: outbound event mapping, inbound actions through native authorization, SSE endpoint with reconnect (spec §24). Internal events are never AG-UI aliases.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "packages/ag-ui"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@ag-ui/core": "1.0.0",
26
+ "@ag-ui/encoder": "1.0.0",
27
+ "@godspeedai/cognate-client": "^0.1.1",
28
+ "@godspeedai/cognate-events": "^0.1.1",
29
+ "@godspeedai/cognate-runtime-api": "^0.1.1"
30
+ },
31
+ "devDependencies": {
32
+ "@ag-ui/client": "1.0.0",
33
+ "@godspeedai/cognate-runtime-bun": "workspace:*"
34
+ }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,623 @@
1
+ // CG-AGUI (spec §24, §31.8, §32; ADR-0008): AG-UI 1.0.0 interoperability adapter.
2
+ // Outbound: durable Cognate events -> schema-valid AG-UI events (never the reverse: AG-UI never becomes
3
+ // the internal event model). Inbound: AG-UI actions pass through RuntimeService with the transport's
4
+ // authenticated caller, never trusting the wire body for identity (spec §32).
5
+ import { EventType } from "@ag-ui/core";
6
+ import { RunAgentInputSchema } from "@ag-ui/core/schemas";
7
+ import { EventEncoder } from "@ag-ui/encoder";
8
+ import type { Json, StoredEvent } from "@godspeedai/cognate-events";
9
+ import { FRONTEND_CAPABILITY } from "@godspeedai/cognate-runtime-api";
10
+ import type { Caller, ContinuationView, RuntimeService } from "@godspeedai/cognate-runtime-api";
11
+ import { ServiceError } from "@godspeedai/cognate-runtime-api";
12
+
13
+ /** One row per AG-UI 1.0.0 EventType (all 31): how Cognate produces or handles it (spec §24 compatibility matrix). */
14
+ export interface MatrixRow {
15
+ readonly agUiType: string;
16
+ readonly direction: "outbound" | "inbound" | "none";
17
+ readonly supported: boolean;
18
+ /** Framework source (e.g. `run.started`, `message.delta`) or the reason it is unsupported. */
19
+ readonly note: string;
20
+ }
21
+
22
+ const row = (agUiType: string, direction: MatrixRow["direction"], supported: boolean, note: string): MatrixRow => ({ agUiType, direction, supported, note });
23
+
24
+ export const matrix: readonly MatrixRow[] = [
25
+ row(EventType.RUN_STARTED, "outbound", true, "run.started"),
26
+ row(EventType.RUN_FINISHED, "outbound", true, "run.completed, or run.waiting once the run stabilizes (result.status: completed | waiting | waiting_unsupported)"),
27
+ row(EventType.RUN_ERROR, "outbound", true, "run.failed, run.cancelled (code: cancelled), or a ServiceError from an inbound action (code: the ServiceErrorCode)"),
28
+ row(EventType.TEXT_MESSAGE_START, "outbound", true, "message.delta (opens a streamed assistant message; emitted once per open message)"),
29
+ row(EventType.TEXT_MESSAGE_CONTENT, "outbound", true, "message.delta"),
30
+ row(EventType.TEXT_MESSAGE_END, "outbound", true, "message.delta (closed before any non-delta projection)"),
31
+ row(EventType.TEXT_MESSAGE_CHUNK, "none", false, "Cognate always emits explicit start/content/end; the chunk shorthand is unused"),
32
+ row(EventType.TOOL_CALL_START, "outbound", true, "run.invocation, model invocation progress, or a frontend capability continuation"),
33
+ row(EventType.TOOL_CALL_ARGS, "outbound", true, "run.invocation input, streamed model arguments, or continuation payload"),
34
+ row(EventType.TOOL_CALL_END, "outbound", true, "run.invocation, model invocation progress, or frontend capability continuation"),
35
+ row(EventType.TOOL_CALL_CHUNK, "none", false, "the chunk shorthand is unused"),
36
+ row(EventType.TOOL_CALL_RESULT, "outbound", true, "run.invocation result or failure, JSON-stringified"),
37
+ row(EventType.STATE_SNAPSHOT, "outbound", true, "state.changed{snapshot}, or a folded snapshot synthesized on reconnect/resync"),
38
+ row(EventType.STATE_DELTA, "outbound", true, "state.changed{patch} (RFC 6902 patch passed through verbatim)"),
39
+ row(EventType.MESSAGES_SNAPSHOT, "outbound", true, "synthesized on a full resync (unknown/expired cursor) from folded message.delta history"),
40
+ row(EventType.ACTIVITY_SNAPSHOT, "none", false, "Cognate has no activity-log concept distinct from state and messages"),
41
+ row(EventType.ACTIVITY_DELTA, "none", false, "Cognate has no activity-log concept distinct from state and messages"),
42
+ row(EventType.RAW, "none", false, "the adapter does not pass through foreign wire events verbatim"),
43
+ row(EventType.CUSTOM, "outbound", true, "human continuations (cognate.continuation), artifacts (cognate.artifact), and continuation kinds with no faithful AG-UI representation (cognate.unsupported_interaction)"),
44
+ row(EventType.STEP_STARTED, "none", false, "ctx.step is internal replay-determinism bookkeeping (run.step.completed), not a user-facing span"),
45
+ row(EventType.STEP_FINISHED, "none", false, "ctx.step is internal replay-determinism bookkeeping, not a user-facing span"),
46
+ row(EventType.REASONING_START, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
47
+ row(EventType.REASONING_MESSAGE_START, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
48
+ row(EventType.REASONING_MESSAGE_CONTENT, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
49
+ row(EventType.REASONING_MESSAGE_END, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
50
+ row(EventType.REASONING_MESSAGE_CHUNK, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
51
+ row(EventType.REASONING_END, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
52
+ row(EventType.REASONING_ENCRYPTED_VALUE, "none", false, "Cognate has no reasoning/thinking channel distinct from message.delta"),
53
+ row(EventType.SUBAGENT_STARTED, "none", false, "Cognate runs are flat; no nested subagent invocation is surfaced yet"),
54
+ row(EventType.SUBAGENT_FINISHED, "none", false, "Cognate runs are flat; no nested subagent invocation is surfaced yet"),
55
+ row(EventType.SUBAGENT_ERROR, "none", false, "Cognate runs are flat; no nested subagent invocation is surfaced yet"),
56
+ ];
57
+
58
+ /** Framework event types deliberately not projected to AG-UI (explicitly ignored, never reinterpreted). */
59
+ export const ignoredFrameworkEvents: readonly string[] = [
60
+ "run.step.completed",
61
+ "run.resumed",
62
+ "run.wait.closed",
63
+ "run.recall",
64
+ "run.remote_offers",
65
+ ];
66
+
67
+ /** AG-UI event as a plain object; `rawEvent.cognate` carries `{ eventId, position, runId }` of the durable source. */
68
+ export type AgUiEvent = { readonly type: string; readonly [key: string]: unknown };
69
+
70
+ const SUPPORTED_CONTINUATION_KINDS = new Set<string>(["human_approval", FRONTEND_CAPABILITY]);
71
+
72
+ function conditionKindOf(view: ContinuationView | undefined): string | undefined {
73
+ const c = view?.condition;
74
+ if (c && typeof c === "object" && !Array.isArray(c) && typeof (c as { kind?: unknown }).kind === "string") return (c as { kind: string }).kind;
75
+ return undefined;
76
+ }
77
+
78
+ function payloadField<T>(event: StoredEvent, key: string): T | undefined {
79
+ const p = event.payload;
80
+ return p && typeof p === "object" && !Array.isArray(p) && key in p ? ((p as { [k: string]: Json })[key] as unknown as T) : undefined;
81
+ }
82
+
83
+ function metaField<T>(event: StoredEvent, key: string): T | undefined {
84
+ const m = event.metadata;
85
+ return m && key in m ? ((m as { [k: string]: Json })[key] as unknown as T) : undefined;
86
+ }
87
+
88
+ // ── JSON Patch (RFC 6902), minimal subset needed to fold state.changed history into a snapshot ─────────
89
+
90
+ type PatchOp = { readonly op: string; readonly path: string; readonly value?: Json; readonly from?: string };
91
+
92
+ function pointer(path: string): readonly string[] {
93
+ if (path === "") return [];
94
+ return path
95
+ .slice(1)
96
+ .split("/")
97
+ .map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
98
+ }
99
+
100
+ function clone(v: Json): Json {
101
+ return v === null ? null : (JSON.parse(JSON.stringify(v)) as Json);
102
+ }
103
+
104
+ function setAt(doc: Json, path: readonly string[], value: Json, mode: "add" | "replace" | "remove"): Json {
105
+ if (path.length === 0) return mode === "remove" ? null : value;
106
+ const result = clone(doc ?? {});
107
+ let cursor: Json = result;
108
+ for (let i = 0; i < path.length - 1; i++) {
109
+ const seg = path[i]!;
110
+ if (Array.isArray(cursor)) cursor = cursor[seg === "-" ? cursor.length - 1 : Number(seg)]!;
111
+ else if (cursor && typeof cursor === "object") cursor = (cursor as { [k: string]: Json })[seg]!;
112
+ }
113
+ const last = path[path.length - 1]!;
114
+ if (Array.isArray(cursor)) {
115
+ const index = last === "-" ? cursor.length : Number(last);
116
+ if (mode === "remove") cursor.splice(index, 1);
117
+ else if (mode === "add") cursor.splice(index, 0, value);
118
+ else cursor[index] = value;
119
+ } else if (cursor && typeof cursor === "object") {
120
+ const record = cursor as { [k: string]: Json };
121
+ if (mode === "remove") delete record[last];
122
+ else record[last] = value;
123
+ }
124
+ return result;
125
+ }
126
+
127
+ function applyPatch(doc: Json, ops: readonly PatchOp[]): Json {
128
+ let result = doc;
129
+ for (const op of ops) {
130
+ if (op.op === "add") result = setAt(result, pointer(op.path), op.value ?? null, "add");
131
+ else if (op.op === "replace") result = setAt(result, pointer(op.path), op.value ?? null, "replace");
132
+ else if (op.op === "remove") result = setAt(result, pointer(op.path), null, "remove");
133
+ else if (op.op === "move" && op.from) {
134
+ result = setAt(result, pointer(op.path), null, "remove");
135
+ }
136
+ }
137
+ return result;
138
+ }
139
+
140
+ /**
141
+ * Stateful per-run projector: feed durable events in order, get schema-valid AG-UI events.
142
+ * Text deltas are bracketed by TEXT_MESSAGE_START/END; invocations become TOOL_CALL_*; state becomes
143
+ * STATE_SNAPSHOT / STATE_DELTA; frontend-capability continuations become client tool calls.
144
+ */
145
+ export function createProjector(options: { readonly threadId: string; readonly runId: string; readonly continuation?: (id: string) => ContinuationView | undefined }): {
146
+ push(event: StoredEvent): readonly AgUiEvent[];
147
+ /** Yields MESSAGES_SNAPSHOT + STATE_SNAPSHOT from everything folded via `push` so far. */
148
+ snapshot(): readonly AgUiEvent[];
149
+ /** Yields only STATE_SNAPSHOT from the current fold (used to anchor a cursor-resumed stream). */
150
+ stateOnly(): readonly AgUiEvent[];
151
+ } {
152
+ let openMessageId: string | undefined;
153
+ const openToolCalls = new Set<string>();
154
+ const knownToolCalls = new Set<string>();
155
+ let text = "";
156
+ let state: Json = null;
157
+
158
+ const cognateOf = (e: StoredEvent) => ({ eventId: e.eventId, position: e.position, runId: e.runId });
159
+
160
+ function closeText(out: AgUiEvent[], cognate: unknown): void {
161
+ if (openMessageId) {
162
+ out.push({ type: "TEXT_MESSAGE_END", messageId: openMessageId, rawEvent: { cognate } });
163
+ openMessageId = undefined;
164
+ }
165
+ }
166
+
167
+ function updateFold(event: StoredEvent): void {
168
+ if (event.eventType === "message.delta" || (event.eventType === "run.invocation.progress" && metaField<string>(event, "capability") === "model.generate" && payloadField<string>(event, "type") === "text")) {
169
+ const t = payloadField<string>(event, "text");
170
+ if (typeof t === "string") text += t;
171
+ } else if (event.eventType === "state.changed") {
172
+ const snapshot = payloadField<Json>(event, "snapshot");
173
+ if (snapshot !== undefined) state = snapshot;
174
+ else {
175
+ const patch = payloadField<readonly PatchOp[]>(event, "patch");
176
+ if (patch) state = applyPatch(state, patch);
177
+ }
178
+ }
179
+ }
180
+
181
+ function project(event: StoredEvent): AgUiEvent[] {
182
+ const out: AgUiEvent[] = [];
183
+ const cognate = cognateOf(event);
184
+ switch (event.eventType) {
185
+ case "run.started":
186
+ out.push({ type: "RUN_STARTED", threadId: options.threadId, runId: options.runId, rawEvent: { cognate } });
187
+ break;
188
+ case "message.delta": {
189
+ const t = payloadField<string>(event, "text");
190
+ if (typeof t !== "string") break;
191
+ if (!openMessageId) {
192
+ openMessageId = event.eventId;
193
+ out.push({ type: "TEXT_MESSAGE_START", messageId: openMessageId, role: "assistant", rawEvent: { cognate } });
194
+ }
195
+ out.push({ type: "TEXT_MESSAGE_CONTENT", messageId: openMessageId, delta: t, rawEvent: { cognate } });
196
+ break;
197
+ }
198
+ case "state.changed": {
199
+ closeText(out, cognate);
200
+ const snapshot = payloadField<Json>(event, "snapshot");
201
+ if (snapshot !== undefined) out.push({ type: "STATE_SNAPSHOT", snapshot, rawEvent: { cognate } });
202
+ else {
203
+ const patch = payloadField<readonly PatchOp[]>(event, "patch");
204
+ if (patch) out.push({ type: "STATE_DELTA", delta: patch, rawEvent: { cognate } });
205
+ }
206
+ break;
207
+ }
208
+ case "run.artifact": {
209
+ // AG-UI 1.0.0 has no artifact event; project explicitly as CUSTOM rather than dropping it.
210
+ closeText(out, cognate);
211
+ out.push({ type: "CUSTOM", name: "cognate.artifact", value: { artifactId: metaField<string>(event, "artifactId") ?? payloadField<string>(event, "artifactId") ?? null }, rawEvent: { cognate } });
212
+ break;
213
+ }
214
+ case "run.invocation.progress": {
215
+ if (metaField<string>(event, "capability") !== "model.generate") break;
216
+ const kind = payloadField<string>(event, "type");
217
+ if (kind === "text") {
218
+ const delta = payloadField<string>(event, "text");
219
+ if (typeof delta !== "string") break;
220
+ if (!openMessageId) {
221
+ openMessageId = event.eventId;
222
+ out.push({ type: "TEXT_MESSAGE_START", messageId: openMessageId, role: "assistant", rawEvent: { cognate } });
223
+ }
224
+ out.push({ type: "TEXT_MESSAGE_CONTENT", messageId: openMessageId, delta, rawEvent: { cognate } });
225
+ break;
226
+ }
227
+ const callId = payloadField<string>(event, "callId");
228
+ if (!callId) break;
229
+ if (kind === "tool_call_start") {
230
+ const name = payloadField<string>(event, "name");
231
+ if (!name) break;
232
+ closeText(out, cognate);
233
+ openToolCalls.add(callId);
234
+ knownToolCalls.add(callId);
235
+ out.push({ type: "TOOL_CALL_START", toolCallId: callId, toolCallName: name, rawEvent: { cognate } });
236
+ } else if (kind === "tool_call_args" && openToolCalls.has(callId)) {
237
+ const delta = payloadField<string>(event, "delta");
238
+ if (typeof delta === "string") out.push({ type: "TOOL_CALL_ARGS", toolCallId: callId, delta, rawEvent: { cognate } });
239
+ } else if (kind === "tool_call_end" && openToolCalls.delete(callId)) {
240
+ out.push({ type: "TOOL_CALL_END", toolCallId: callId, rawEvent: { cognate } });
241
+ }
242
+ break;
243
+ }
244
+ case "run.invocation": {
245
+ if (metaField<string>(event, "capability") === "model.generate") break;
246
+ closeText(out, cognate);
247
+ const stepId = metaField<string>(event, "stepId") ?? event.eventId;
248
+ const capability = metaField<string>(event, "capability") ?? "capability";
249
+ const ok = metaField<boolean>(event, "ok") === true;
250
+ out.push({ type: "TOOL_CALL_START", toolCallId: stepId, toolCallName: capability, rawEvent: { cognate } });
251
+ out.push({ type: "TOOL_CALL_ARGS", toolCallId: stepId, delta: JSON.stringify(payloadField<Json>(event, "input") ?? {}), rawEvent: { cognate } });
252
+ out.push({ type: "TOOL_CALL_END", toolCallId: stepId, rawEvent: { cognate } });
253
+ const content = JSON.stringify(ok ? (payloadField<Json>(event, "result") ?? null) : (payloadField<Json>(event, "failure") ?? null));
254
+ out.push({ type: "TOOL_CALL_RESULT", messageId: `${stepId}:result`, toolCallId: stepId, content, role: "tool", rawEvent: { cognate } });
255
+ break;
256
+ }
257
+ case "run.waiting": {
258
+ closeText(out, cognate);
259
+ const continuationId = metaField<string>(event, "continuationId") ?? "";
260
+ const waitType = payloadField<string>(event, "type") ?? "";
261
+ const view = options.continuation?.(continuationId);
262
+ if (waitType.startsWith("frontend:") || waitType.startsWith("remote:")) {
263
+ const remoteId = metaField<string>(event, "stepId")?.match(/^wait:remote:(.+)$/)?.[1];
264
+ const toolCallId = remoteId ?? continuationId;
265
+ const capability = waitType.slice(waitType.indexOf(":") + 1);
266
+ if (!knownToolCalls.has(toolCallId)) {
267
+ out.push({ type: "TOOL_CALL_START", toolCallId, toolCallName: capability, rawEvent: { cognate } });
268
+ out.push({ type: "TOOL_CALL_ARGS", toolCallId, delta: JSON.stringify(view?.payload ?? {}), rawEvent: { cognate } });
269
+ out.push({ type: "TOOL_CALL_END", toolCallId, rawEvent: { cognate } });
270
+ } else if (openToolCalls.delete(toolCallId)) {
271
+ out.push({ type: "TOOL_CALL_END", toolCallId, rawEvent: { cognate } });
272
+ }
273
+ } else {
274
+ const kind = conditionKindOf(view);
275
+ const supported = kind !== undefined && SUPPORTED_CONTINUATION_KINDS.has(kind);
276
+ // AG-UI 1.0.0 has no interrupt event, so run-level waits surface as CUSTOM. The value is
277
+ // self-sufficient: a generic client can act on it (forwardedProps.cognate.resolve/cancel)
278
+ // without parsing rawEvent, using the ids carried here.
279
+ out.push({
280
+ type: "CUSTOM",
281
+ name: supported ? "cognate.continuation" : "cognate.unsupported_interaction",
282
+ value: { id: continuationId, type: waitType, kind: kind ?? "unknown", payload: view?.payload ?? null, runId: options.runId, threadId: options.threadId },
283
+ rawEvent: { cognate },
284
+ });
285
+ }
286
+ break;
287
+ }
288
+ case "run.resumed": {
289
+ const stepId = metaField<string>(event, "stepId");
290
+ const callId = stepId?.match(/^wait:remote:(.+)$/)?.[1];
291
+ if (!callId) break;
292
+ const resolution = payloadField<Json>(event, "input") ?? null;
293
+ const result = resolution && typeof resolution === "object" && !Array.isArray(resolution) && resolution.ok === true ? (resolution.value ?? null) : resolution;
294
+ out.push({ type: "TOOL_CALL_RESULT", messageId: `${callId}:result`, toolCallId: callId, content: JSON.stringify(result), role: "tool", rawEvent: { cognate } });
295
+ break;
296
+ }
297
+ case "run.completed": {
298
+ closeText(out, cognate);
299
+ out.push({ type: "RUN_FINISHED", threadId: options.threadId, runId: options.runId, result: { status: "completed", output: payloadField<Json>(event, "output") ?? null }, rawEvent: { cognate } });
300
+ break;
301
+ }
302
+ case "run.failed": {
303
+ closeText(out, cognate);
304
+ out.push({ type: "RUN_ERROR", message: payloadField<string>(event, "error") ?? "run failed", code: "failed", rawEvent: { cognate } });
305
+ break;
306
+ }
307
+ case "run.cancelled": {
308
+ closeText(out, cognate);
309
+ out.push({ type: "RUN_ERROR", message: payloadField<string>(event, "reason") ?? "cancelled", code: "cancelled", rawEvent: { cognate } });
310
+ break;
311
+ }
312
+ default:
313
+ break; // ignoredFrameworkEvents and anything unrecognized project to nothing
314
+ }
315
+ return out;
316
+ }
317
+
318
+ return {
319
+ push(event: StoredEvent): readonly AgUiEvent[] {
320
+ updateFold(event);
321
+ return project(event);
322
+ },
323
+ snapshot(): readonly AgUiEvent[] {
324
+ const messages = text ? [{ id: `${options.runId}:assistant`, role: "assistant", content: text }] : [];
325
+ return [
326
+ { type: "MESSAGES_SNAPSHOT", messages },
327
+ { type: "STATE_SNAPSHOT", snapshot: state },
328
+ ];
329
+ },
330
+ stateOnly(): readonly AgUiEvent[] {
331
+ return [{ type: "STATE_SNAPSHOT", snapshot: state }];
332
+ },
333
+ };
334
+ }
335
+
336
+ /** Correlation id grouping the Cognate runs started for one AG-UI thread (mirrors the Harness `session:<id>`). */
337
+ export function threadCorrelationId(threadId: string): string {
338
+ return `agui-thread:${threadId}`;
339
+ }
340
+
341
+ export interface EndpointOptions {
342
+ readonly service: RuntimeService;
343
+ readonly authenticate: (headers: Headers) => Caller | undefined | Promise<Caller | undefined>;
344
+ /** Agent to start for new user messages when `forwardedProps.cognate.agent` is absent. */
345
+ readonly defaultAgent: string;
346
+ }
347
+
348
+ type Message = { readonly id: string; readonly role: string; readonly content?: unknown; readonly toolCallId?: string };
349
+ type RunAgentInput = { readonly threadId: string; readonly runId: string; readonly messages: readonly Message[]; readonly context?: readonly { readonly description: string; readonly value: string }[]; readonly forwardedProps?: Record<string, unknown>; readonly state?: Record<string, unknown> };
350
+ type CognateProps = { readonly agent?: string; readonly cancel?: { readonly reason?: string }; readonly resolve?: { readonly continuationId: string; readonly action: "resume" | "cancel"; readonly input?: Json; readonly expectedVersion?: number }; readonly cursor?: number };
351
+
352
+ function cognateProps(input: RunAgentInput): CognateProps {
353
+ const raw = (input.forwardedProps as { cognate?: CognateProps } | undefined)?.cognate;
354
+ return raw ?? {};
355
+ }
356
+
357
+ const encoder = new EventEncoder();
358
+
359
+ function sseResponse(events: readonly AgUiEvent[]): Response {
360
+ const body = new ReadableStream<Uint8Array>({
361
+ start(controller) {
362
+ const bytes = new TextEncoder();
363
+ for (const event of events) {
364
+ try {
365
+ controller.enqueue(bytes.encode(encoder.encodeSSE(event as never)));
366
+ } catch {
367
+ break;
368
+ }
369
+ }
370
+ try {
371
+ controller.close();
372
+ } catch {
373
+ // already closed by a disconnect
374
+ }
375
+ },
376
+ });
377
+ return new Response(body, { status: 200, headers: { "content-type": encoder.getContentType() } });
378
+ }
379
+
380
+ /**
381
+ * Project a durable event cursor as SSE. Cancelling the HTTP body only aborts this
382
+ * projection: it never cancels the run whose committed history remains resumable.
383
+ */
384
+ function liveSseResponse(produce: (emit: (event: AgUiEvent) => boolean, signal: AbortSignal) => Promise<void>): Response {
385
+ const aborted = new AbortController();
386
+ const body = new ReadableStream<Uint8Array>({
387
+ start(controller) {
388
+ const bytes = new TextEncoder();
389
+ const emit = (event: AgUiEvent): boolean => {
390
+ if (aborted.signal.aborted) return false;
391
+ try {
392
+ controller.enqueue(bytes.encode(encoder.encodeSSE(event as never)));
393
+ return true;
394
+ } catch {
395
+ aborted.abort();
396
+ return false;
397
+ }
398
+ };
399
+ void produce(emit, aborted.signal)
400
+ .catch((error: unknown) => {
401
+ if (!aborted.signal.aborted) controller.error(error);
402
+ })
403
+ .finally(() => {
404
+ if (!aborted.signal.aborted) {
405
+ try {
406
+ controller.close();
407
+ } catch {
408
+ // The consumer may have already cancelled the body.
409
+ }
410
+ }
411
+ });
412
+ },
413
+ cancel() {
414
+ aborted.abort();
415
+ },
416
+ });
417
+ return new Response(body, { status: 200, headers: { "content-type": encoder.getContentType() } });
418
+ }
419
+
420
+ /**
421
+ * HTTP endpoint for AG-UI clients: POST RunAgentInput → SSE stream of AG-UI events. Inbound actions (user message,
422
+ * tool results for frontend capabilities, continuation responses, cancellation) go through RuntimeService with the
423
+ * authenticated caller. `forwardedProps.cognate.cursor` resumes from a durable position; an invalid cursor yields
424
+ * a full resync. Disconnecting never cancels the durable run.
425
+ */
426
+ export function createAgUiHandler(options: EndpointOptions): (request: Request) => Promise<Response> {
427
+ const { service } = options;
428
+
429
+ return async function handle(request: Request): Promise<Response> {
430
+ let body: unknown;
431
+ try {
432
+ body = await request.json();
433
+ } catch {
434
+ return new Response(JSON.stringify({ error: "invalid JSON body" }), { status: 400, headers: { "content-type": "application/json" } });
435
+ }
436
+ const parsed = RunAgentInputSchema.safeParse(body);
437
+ if (!parsed.success) return new Response(JSON.stringify({ error: "invalid RunAgentInput", issues: parsed.error.issues }), { status: 400, headers: { "content-type": "application/json" } });
438
+ const input = parsed.data as unknown as RunAgentInput;
439
+
440
+ const caller = await options.authenticate(request.headers);
441
+ if (!caller) return new Response(null, { status: 401 });
442
+
443
+ const props = cognateProps(input);
444
+ const threadCorrelation = threadCorrelationId(input.threadId);
445
+ const belongsToRunOrThreadState = (event: StoredEvent, runId: string): boolean =>
446
+ event.runId === runId || (event.eventType === "state.changed" && event.metadata?.scope === "thread" && event.correlationId === threadCorrelation);
447
+
448
+ // Thread -> run mapping is served by the runtime's run index (DEBT-019), maintained atomically with
449
+ // run.started, not by scanning the event log: runs started for a thread carry its correlation id, so a
450
+ // restarted server (or another process) routes resolve/cancel/reconnect to the thread's most recent run.
451
+ // `listRuns` is tenant-scoped, so another tenant's thread never matches.
452
+ const resolveRunId = async (): Promise<string> => {
453
+ const runs = await service.listRuns(caller, { correlationId: threadCorrelation });
454
+ const latest = runs.at(-1);
455
+ if (latest) return latest.runId;
456
+ throw new ServiceError("not_found", `no Cognate run is known for thread ${input.threadId}`);
457
+ };
458
+ const positionBeforeAction = async (runId: string): Promise<number> => {
459
+ let position = 0;
460
+ for await (const event of service.events(caller, { runId, afterPosition: 0 })) position = event.position;
461
+ return position;
462
+ };
463
+
464
+ let cognateRunId: string;
465
+ let mode: "full" | "reconnect";
466
+ let afterInboundAction = 0;
467
+ try {
468
+ if (props.cancel) {
469
+ cognateRunId = await resolveRunId();
470
+ afterInboundAction = await positionBeforeAction(cognateRunId);
471
+ await service.cancelRun(caller, { runId: cognateRunId, reason: props.cancel.reason ?? "cancelled", idempotencyKey: `agui:${input.threadId}:${input.runId}:cancel` });
472
+ mode = "full";
473
+ } else if (props.resolve) {
474
+ cognateRunId = await resolveRunId();
475
+ afterInboundAction = await positionBeforeAction(cognateRunId);
476
+ await service.resolveContinuation(caller, {
477
+ continuationId: props.resolve.continuationId,
478
+ action: props.resolve.action,
479
+ input: props.resolve.input ?? null,
480
+ idempotencyKey: `agui:resolve:${props.resolve.continuationId}:${props.resolve.action}`,
481
+ ...(props.resolve.expectedVersion !== undefined ? { expectedVersion: props.resolve.expectedVersion } : {}),
482
+ });
483
+ mode = "full";
484
+ } else if (input.messages.some((m) => m.role === "tool")) {
485
+ const toolMessage = [...input.messages].reverse().find((m) => m.role === "tool")!;
486
+ let value: Json;
487
+ try {
488
+ value = JSON.parse(String(toolMessage.content ?? "null"));
489
+ } catch {
490
+ value = String(toolMessage.content ?? "");
491
+ }
492
+ cognateRunId = await resolveRunId();
493
+ afterInboundAction = await positionBeforeAction(cognateRunId);
494
+ // Frontend waits project the full continuation id as the wire toolCallId; remote-offer waits
495
+ // project the bare remote id (the continuation id is `<runId>.wait.remote:<remoteId>`). A
496
+ // generic AG-UI client echoes whichever id it received, so accept both shapes: a bare id is
497
+ // addressed to the thread's current run's remote wait. An unknown id still fails closed
498
+ // (not_found) through the service's own continuation lookup.
499
+ const continuationId = toolMessage.toolCallId!.includes(".wait.")
500
+ ? toolMessage.toolCallId!
501
+ : `${cognateRunId}.wait.remote:${toolMessage.toolCallId!}`;
502
+ await service.resolveContinuation(caller, { continuationId, action: "resume", input: { ok: true, value }, idempotencyKey: `agui:resolve:${continuationId}:tool` });
503
+ mode = "full";
504
+ } else if (input.messages.some((m) => m.role === "user")) {
505
+ const userMessage = [...input.messages].reverse().find((m) => m.role === "user")!;
506
+ const text = typeof userMessage.content === "string" ? userMessage.content : "";
507
+ // AG-UI clients send `state: {}` by default; only a non-empty object is a real seed (spec §29.1).
508
+ const seedState = input.state && typeof input.state === "object" && Object.keys(input.state).length > 0 ? (input.state as Json) : undefined;
509
+ const view = await service.startRun(caller, {
510
+ agent: props.agent ?? options.defaultAgent,
511
+ // Context is a read-only observation captured at run start. It is distinct from the
512
+ // caller/agent writable `state.changed` stream and remains immutable on replay.
513
+ input: { message: text, context: (input.context ?? []).map(({ description, value }) => ({ description, value })) },
514
+ idempotencyKey: `agui:${input.threadId}:${input.runId}`,
515
+ correlationId: threadCorrelation,
516
+ ...(seedState !== undefined ? { state: seedState } : {}),
517
+ });
518
+ cognateRunId = view.runId;
519
+ mode = "full";
520
+ } else {
521
+ cognateRunId = await resolveRunId();
522
+ mode = "reconnect";
523
+ }
524
+ } catch (error) {
525
+ if (error instanceof ServiceError) return sseResponse([{ type: "RUN_ERROR", message: error.message, code: error.code }]);
526
+ throw error;
527
+ }
528
+
529
+ // The runtime cursor is the source of both catch-up and live delivery. It subscribes before reading
530
+ // history, so a commit between those phases is neither lost nor duplicated. Do not wait for settlement:
531
+ // an SSE consumer must see each committed projection while the run is still executing.
532
+ const readHistory = async (): Promise<StoredEvent[]> => {
533
+ const events: StoredEvent[] = [];
534
+ for await (const event of service.events(caller, { correlationId: threadCorrelation, afterPosition: 0 })) {
535
+ if (belongsToRunOrThreadState(event, cognateRunId)) events.push(event);
536
+ }
537
+ return events;
538
+ };
539
+ return liveSseResponse(async (emit, signal) => {
540
+ let continuationViews: ContinuationView[] = [];
541
+ const byId = new Map<string, ContinuationView>();
542
+ const projector = createProjector({ threadId: input.threadId, runId: input.runId, continuation: (id) => byId.get(id) });
543
+ let settled = false;
544
+
545
+ const refreshContinuations = async (): Promise<void> => {
546
+ continuationViews = await service.listContinuations(caller, { runId: cognateRunId });
547
+ byId.clear();
548
+ for (const continuation of continuationViews) byId.set(continuation.id, continuation);
549
+ };
550
+ const finishWaiting = (): void => {
551
+ const open = continuationViews.filter((v) => v.status === "OPEN");
552
+ const supported = open.every((v) => {
553
+ const kind = conditionKindOf(v);
554
+ return kind !== undefined && SUPPORTED_CONTINUATION_KINDS.has(kind);
555
+ });
556
+ emit({ type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId, result: { status: supported ? "waiting" : "waiting_unsupported", continuations: open.map((v) => ({ id: v.id, type: v.type, version: v.version })) } });
557
+ settled = true;
558
+ };
559
+ const project = async (event: StoredEvent, finishOnWait = true): Promise<void> => {
560
+ if (event.eventType === "run.waiting") await refreshContinuations();
561
+ for (const projected of projector.push(event)) if (!emit(projected)) return;
562
+ if (event.eventType === "run.waiting" && finishOnWait) finishWaiting();
563
+ else if (event.eventType === "run.completed" || event.eventType === "run.failed" || event.eventType === "run.cancelled") settled = true;
564
+ };
565
+
566
+ let afterPosition = afterInboundAction;
567
+ let emitSeededThreadState = false;
568
+ if (mode === "full" && afterInboundAction === 0) {
569
+ const history = await readHistory();
570
+ const started = history.find((event) => event.eventType === "run.started" && event.runId === cognateRunId);
571
+ if (started) {
572
+ for (const event of history) {
573
+ if (event.position >= started.position) break;
574
+ if (event.eventType === "state.changed" && event.metadata?.scope === "thread") {
575
+ projector.push(event);
576
+ emitSeededThreadState = true;
577
+ }
578
+ }
579
+ afterPosition = started.position - 1;
580
+ }
581
+ }
582
+ if (mode === "reconnect") {
583
+ const history = await readHistory();
584
+ const cursor = props.cursor;
585
+ const maxPosition = history.at(-1)?.position ?? 0;
586
+ const validCursor = typeof cursor === "number" && cursor >= 0 && cursor <= maxPosition;
587
+ if (validCursor) {
588
+ for (const event of history) if (event.position <= cursor) projector.push(event);
589
+ for (const event of projector.stateOnly()) if (!emit(event)) return;
590
+ afterPosition = cursor;
591
+ } else {
592
+ const started = history.find((event) => event.eventType === "run.started" && event.runId === cognateRunId);
593
+ if (!emit({ type: "RUN_STARTED", threadId: input.threadId, runId: input.runId, rawEvent: started ? { cognate: { eventId: started.eventId, position: started.position, runId: started.runId } } : undefined })) return;
594
+ for (const event of history) if (event.eventType === "message.delta" || event.eventType === "state.changed" || (event.eventType === "run.invocation.progress" && payloadField<string>(event, "type") === "text")) projector.push(event);
595
+ for (const event of projector.snapshot()) if (!emit(event)) return;
596
+ for (const event of history) {
597
+ if (event.eventType === "run.started" || event.eventType === "message.delta" || event.eventType === "state.changed" || (event.eventType === "run.invocation.progress" && payloadField<string>(event, "type") === "text")) continue;
598
+ await project(event, false);
599
+ if (settled || signal.aborted) return;
600
+ }
601
+ afterPosition = maxPosition;
602
+ // Historical waits are interaction episodes, not terminal history. Only the run's
603
+ // current waiting status should end a resync; an earlier wait may have been resumed.
604
+ if ((await service.getRun(caller, { runId: cognateRunId })).status === "waiting") {
605
+ await refreshContinuations();
606
+ finishWaiting();
607
+ return;
608
+ }
609
+ }
610
+ }
611
+
612
+ for await (const event of service.events(caller, { correlationId: threadCorrelation, afterPosition, follow: true, signal })) {
613
+ if (!belongsToRunOrThreadState(event, cognateRunId)) continue;
614
+ await project(event);
615
+ if (event.eventType === "run.started" && emitSeededThreadState) {
616
+ for (const snapshot of projector.stateOnly()) if (!emit(snapshot)) return;
617
+ emitSeededThreadState = false;
618
+ }
619
+ if (settled || signal.aborted) return;
620
+ }
621
+ });
622
+ };
623
+ }