@godspeedai/cognate-react 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.
- package/LICENSE +201 -0
- package/README.md +6 -2
- package/package.json +38 -4
- package/src/index.tsx +358 -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,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @godspeedai/cognate-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React 19 bindings over `@godspeedai/cognate-client` (§25.2), via `useSyncExternalStore`.
|
|
4
|
+
|
|
5
|
+
`CognateProvider`, `useCognate`, `useRun`, `useAgent`, `useSharedState` (`{ state, update }` — shared state is bidirectional, spec §29.1: a component can write it and a suspended agent reads the write through `RunContext.state`), `useProjection`, `useCapability` (registers a frontend capability for the component's lifetime; unregistered on unmount — a reversible effect), `useContinuations`, `useArtifact`, `useConnectionStatus`.
|
|
6
|
+
|
|
7
|
+
No Astryx dependency; renderers such as `@godspeedai/cognate-ui-astryx` sit above this package (§3.8). Proof: `test/hooks.test.tsx` (CG-UI-001). Tests register happy-dom through `test/setup-dom.ts` and use render-bound queries.
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@godspeedai/cognate-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "React 19 bindings over the headless client: runs, projections, frontend capabilities, continuations, artifacts (spec §25.2). No Astryx.",
|
|
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/react"
|
|
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.tsx"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@godspeedai/cognate-client": "^0.1.1",
|
|
26
|
+
"@godspeedai/cognate-events": "^0.1.1",
|
|
27
|
+
"@godspeedai/cognate-runtime-api": "^0.1.1"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@godspeedai/cognate-runtime-bun": "workspace:*",
|
|
31
|
+
"@happy-dom/global-registrator": "20.14.5",
|
|
32
|
+
"@testing-library/react": "16.3.3",
|
|
33
|
+
"react": "19.3.0",
|
|
34
|
+
"react-dom": "19.3.0",
|
|
35
|
+
"@types/react": "19.2.2"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"react": "19.3.0"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/index.tsx
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// React 19 bindings over the headless client (spec §25.2). All hooks are thin useSyncExternalStore
|
|
2
|
+
// adapters over the client's framework-neutral Readables; the client remains the single source of truth.
|
|
3
|
+
import type { CognateClient, ConnectionStatus, FrontendHandler, RemoteCapabilityOfferInput, RunState, ThreadSharedState } from "@godspeedai/cognate-client";
|
|
4
|
+
import type { Json, StoredEvent } from "@godspeedai/cognate-events";
|
|
5
|
+
import type { ContinuationView, RunView, StateUpdate } from "@godspeedai/cognate-runtime-api";
|
|
6
|
+
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
7
|
+
|
|
8
|
+
const CognateContext = createContext<CognateClient | undefined>(undefined);
|
|
9
|
+
|
|
10
|
+
export interface RemoteCapabilityRenderRecord {
|
|
11
|
+
/** The durable continuation that selected this exact browser handler. */
|
|
12
|
+
readonly continuationId: string;
|
|
13
|
+
readonly runId: string;
|
|
14
|
+
readonly capability: string;
|
|
15
|
+
readonly contractVersion: string;
|
|
16
|
+
readonly input: Json;
|
|
17
|
+
readonly status: "pending" | "completed" | "failed";
|
|
18
|
+
readonly result: Json | undefined;
|
|
19
|
+
readonly error: string | undefined;
|
|
20
|
+
/** Positions observed from the durable run stream, when the history hook is mounted. */
|
|
21
|
+
readonly durable: { readonly waitingPosition?: number; readonly terminalPosition?: number };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type RemoteCapabilityRenderer = (record: RemoteCapabilityRenderRecord) => ReactNode;
|
|
25
|
+
|
|
26
|
+
interface RendererEntry extends RemoteCapabilityRenderRecord {
|
|
27
|
+
readonly renderer: RemoteCapabilityRenderer;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface DurableEvidence {
|
|
31
|
+
readonly runId: string;
|
|
32
|
+
readonly waitingPosition?: number;
|
|
33
|
+
readonly terminalPosition?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
class RemoteCapabilityRendererRegistry {
|
|
37
|
+
private readonly entries = new Map<string, RendererEntry>();
|
|
38
|
+
private readonly keysByContinuation = new Map<string, string>();
|
|
39
|
+
private readonly evidence = new Map<string, DurableEvidence>();
|
|
40
|
+
private readonly listeners = new Set<() => void>();
|
|
41
|
+
private readonly snapshots = new Map<string, readonly RendererEntry[]>();
|
|
42
|
+
|
|
43
|
+
subscribe(listener: () => void): () => void {
|
|
44
|
+
this.listeners.add(listener);
|
|
45
|
+
return () => this.listeners.delete(listener);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
history(runId: string | undefined): readonly RendererEntry[] {
|
|
49
|
+
if (runId === undefined) return EMPTY_REMOTE_RENDER_HISTORY;
|
|
50
|
+
const cached = this.snapshots.get(runId);
|
|
51
|
+
if (cached) return cached;
|
|
52
|
+
const history = [...this.entries.values()]
|
|
53
|
+
.filter((entry) => entry.runId === runId)
|
|
54
|
+
.sort((a, b) => a.continuationId.localeCompare(b.continuationId));
|
|
55
|
+
this.snapshots.set(runId, history);
|
|
56
|
+
return history;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
bind(context: { readonly continuationId: string; readonly runId: string }, contract: { readonly id: string; readonly version: string }, input: Json, renderer: RemoteCapabilityRenderer): string {
|
|
60
|
+
// The continuation id comes from the durable wait selected by the runtime. Including the
|
|
61
|
+
// contract version prevents a remounted offer from being mistaken for an older call.
|
|
62
|
+
const key = `${context.continuationId}@${contract.version}`;
|
|
63
|
+
const durable = this.evidence.get(context.continuationId);
|
|
64
|
+
this.entries.set(key, {
|
|
65
|
+
continuationId: context.continuationId,
|
|
66
|
+
runId: context.runId,
|
|
67
|
+
capability: contract.id,
|
|
68
|
+
contractVersion: contract.version,
|
|
69
|
+
input,
|
|
70
|
+
status: "pending",
|
|
71
|
+
result: undefined,
|
|
72
|
+
error: undefined,
|
|
73
|
+
durable: durable ?? { runId: context.runId },
|
|
74
|
+
renderer,
|
|
75
|
+
});
|
|
76
|
+
this.keysByContinuation.set(context.continuationId, key);
|
|
77
|
+
this.publish();
|
|
78
|
+
return key;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
complete(key: string, result: Json): void {
|
|
82
|
+
const entry = this.entries.get(key);
|
|
83
|
+
if (!entry) return;
|
|
84
|
+
this.entries.set(key, { ...entry, status: "completed", result, error: undefined });
|
|
85
|
+
this.publish();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fail(key: string, error: unknown): void {
|
|
89
|
+
const entry = this.entries.get(key);
|
|
90
|
+
if (!entry) return;
|
|
91
|
+
this.entries.set(key, { ...entry, status: "failed", error: error instanceof Error ? error.message : String(error) });
|
|
92
|
+
this.publish();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
observe(event: StoredEvent): void {
|
|
96
|
+
if (!event.runId) return;
|
|
97
|
+
if (event.eventType === "run.waiting") {
|
|
98
|
+
const type = field<string>(event.payload, "type");
|
|
99
|
+
const continuationId = field<string>(event.metadata, "continuationId");
|
|
100
|
+
if (!continuationId || !type?.startsWith("remote:")) return;
|
|
101
|
+
this.evidence.set(continuationId, { runId: event.runId, waitingPosition: event.position });
|
|
102
|
+
this.updateDurable(continuationId);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (event.eventType === "run.completed" || event.eventType === "run.failed" || event.eventType === "run.cancelled") {
|
|
106
|
+
for (const [continuationId, evidence] of this.evidence) {
|
|
107
|
+
if (evidence.runId !== event.runId) continue;
|
|
108
|
+
this.evidence.set(continuationId, { ...evidence, terminalPosition: event.position });
|
|
109
|
+
this.updateDurable(continuationId);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private updateDurable(continuationId: string): void {
|
|
115
|
+
const key = this.keysByContinuation.get(continuationId);
|
|
116
|
+
const entry = key ? this.entries.get(key) : undefined;
|
|
117
|
+
const durable = this.evidence.get(continuationId);
|
|
118
|
+
if (!entry || !durable) return;
|
|
119
|
+
this.entries.set(key!, { ...entry, durable });
|
|
120
|
+
this.publish();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private publish(): void {
|
|
124
|
+
this.snapshots.clear();
|
|
125
|
+
for (const listener of this.listeners) listener();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const EMPTY_REMOTE_RENDER_HISTORY: readonly RendererEntry[] = [];
|
|
130
|
+
const RemoteCapabilityRendererContext = createContext<RemoteCapabilityRendererRegistry | undefined>(undefined);
|
|
131
|
+
|
|
132
|
+
function field<T>(value: Json | undefined, key: string): T | undefined {
|
|
133
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && key in value ? (value[key] as T) : undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function RemoteCapabilityRendererProvider({ children }: { readonly children: ReactNode }): ReactNode {
|
|
137
|
+
const registryRef = useRef<RemoteCapabilityRendererRegistry | undefined>(undefined);
|
|
138
|
+
if (!registryRef.current) registryRef.current = new RemoteCapabilityRendererRegistry();
|
|
139
|
+
return <RemoteCapabilityRendererContext.Provider value={registryRef.current}>{children}</RemoteCapabilityRendererContext.Provider>;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function useRemoteCapabilityRendererRegistry(): RemoteCapabilityRendererRegistry {
|
|
143
|
+
const registry = useContext(RemoteCapabilityRendererContext);
|
|
144
|
+
if (!registry) throw new Error("useRemoteCapability renderer registry requires CognateProvider");
|
|
145
|
+
return registry;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function CognateProvider({ client, children }: { readonly client: CognateClient; readonly children: ReactNode }): ReactNode {
|
|
149
|
+
return <CognateContext.Provider value={client}><RemoteCapabilityRendererProvider>{children}</RemoteCapabilityRendererProvider></CognateContext.Provider>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The client from the nearest provider. */
|
|
153
|
+
export function useCognate(): CognateClient {
|
|
154
|
+
const client = useContext(CognateContext);
|
|
155
|
+
if (!client) throw new Error("useCognate: no CognateProvider found in the component tree");
|
|
156
|
+
return client;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Live derived state of a run (undefined id → undefined). Uses useSyncExternalStore over the client's Readable. */
|
|
160
|
+
export function useRun(runId: string | undefined): RunState | undefined {
|
|
161
|
+
const client = useCognate();
|
|
162
|
+
const store = useMemo(() => (runId === undefined ? undefined : client.run(runId)), [client, runId]);
|
|
163
|
+
const subscribe = useCallback((onStoreChange: () => void) => (store ? store.subscribe(onStoreChange) : () => {}), [store]);
|
|
164
|
+
const getSnapshot = useCallback(() => store?.get(), [store]);
|
|
165
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Start runs of one agent and follow the latest. */
|
|
169
|
+
export function useAgent(agent: string): { readonly start: (input: Json) => Promise<RunView>; readonly runId: string | undefined; readonly state: RunState | undefined } {
|
|
170
|
+
const client = useCognate();
|
|
171
|
+
const [runId, setRunId] = useState<string | undefined>(undefined);
|
|
172
|
+
const start = useCallback(
|
|
173
|
+
async (input: Json) => {
|
|
174
|
+
const view = await client.startRun(agent, input);
|
|
175
|
+
setRunId(view.runId);
|
|
176
|
+
return view;
|
|
177
|
+
},
|
|
178
|
+
[client, agent],
|
|
179
|
+
);
|
|
180
|
+
const state = useRun(runId);
|
|
181
|
+
return { start, runId, state };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The run's live shared state (spec §29.1), and a writer that appends a caller-sourced `state.changed` event
|
|
186
|
+
* the agent observes through `RunContext.state`. `state` follows `useRun`'s derived value; `update` resolves
|
|
187
|
+
* once the write is durable.
|
|
188
|
+
*/
|
|
189
|
+
export function useSharedState(runId: string | undefined): { readonly state: Json; readonly update: (update: StateUpdate, options?: { readonly expectedVersion?: number }) => Promise<{ readonly state: Json; readonly version: number }> } {
|
|
190
|
+
const client = useCognate();
|
|
191
|
+
const run = useRun(runId);
|
|
192
|
+
const update = useCallback(
|
|
193
|
+
(stateUpdate: StateUpdate, options?: { readonly expectedVersion?: number }) => {
|
|
194
|
+
if (runId === undefined) throw new Error("useSharedState: no run id");
|
|
195
|
+
return client.updateState(runId, stateUpdate, options);
|
|
196
|
+
},
|
|
197
|
+
[client, runId],
|
|
198
|
+
);
|
|
199
|
+
return { state: run?.state ?? null, update };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Live state shared by all runs in a thread, with a caller update function. */
|
|
203
|
+
export function useThreadSharedState(threadId: string): ThreadSharedState & {
|
|
204
|
+
readonly update: (update: StateUpdate, options?: { readonly expectedVersion?: number }) => Promise<{ readonly state: Json; readonly version: number }>;
|
|
205
|
+
} {
|
|
206
|
+
const client = useCognate();
|
|
207
|
+
const store = useMemo(() => client.threadSharedState(threadId), [client, threadId]);
|
|
208
|
+
const subscribe = useCallback((onStoreChange: () => void) => store.subscribe(onStoreChange), [store]);
|
|
209
|
+
const getSnapshot = useCallback(() => store.get(), [store]);
|
|
210
|
+
const shared = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
211
|
+
const update = useCallback(
|
|
212
|
+
(stateUpdate: StateUpdate, options?: { readonly expectedVersion?: number }) => client.updateThreadSharedState(threadId, stateUpdate, options),
|
|
213
|
+
[client, threadId],
|
|
214
|
+
);
|
|
215
|
+
return { ...shared, update };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function useProjection(name: string): readonly { readonly key: string; readonly value: Json }[] | undefined {
|
|
219
|
+
const client = useCognate();
|
|
220
|
+
const store = useMemo(() => client.projection(name), [client, name]);
|
|
221
|
+
const subscribe = useCallback((onStoreChange: () => void) => store.subscribe(onStoreChange), [store]);
|
|
222
|
+
const getSnapshot = useCallback(() => store.get(), [store]);
|
|
223
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Provide a frontend capability while the component is mounted; unregistered on unmount (a reversible effect). */
|
|
227
|
+
export function useCapability(capability: string, handler: FrontendHandler): void {
|
|
228
|
+
const client = useCognate();
|
|
229
|
+
const handlerRef = useRef(handler);
|
|
230
|
+
useEffect(() => {
|
|
231
|
+
handlerRef.current = handler;
|
|
232
|
+
}, [handler]);
|
|
233
|
+
useEffect(() => {
|
|
234
|
+
return client.provideCapability(capability, (input, context) => handlerRef.current(input, context));
|
|
235
|
+
}, [client, capability]);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Publish a descriptor-backed remote capability for the mounted component lifetime. */
|
|
239
|
+
export function useRemoteCapability(offer: Omit<RemoteCapabilityOfferInput, "leaseId">, handler: FrontendHandler, options?: { readonly render?: RemoteCapabilityRenderer }): { readonly status: "publishing" | "available" | "error"; readonly error: Error | null } {
|
|
240
|
+
const client = useCognate();
|
|
241
|
+
const renderers = useRemoteCapabilityRendererRegistry();
|
|
242
|
+
const handlerRef = useRef(handler);
|
|
243
|
+
const rendererRef = useRef(options?.render);
|
|
244
|
+
const leaseRef = useRef<string>(crypto.randomUUID());
|
|
245
|
+
const offerKey = JSON.stringify(offer);
|
|
246
|
+
const [status, setStatus] = useState<"publishing" | "available" | "error">("publishing");
|
|
247
|
+
const [error, setError] = useState<Error | null>(null);
|
|
248
|
+
useEffect(() => {
|
|
249
|
+
handlerRef.current = handler;
|
|
250
|
+
}, [handler]);
|
|
251
|
+
useEffect(() => {
|
|
252
|
+
rendererRef.current = options?.render;
|
|
253
|
+
}, [options?.render]);
|
|
254
|
+
useEffect(() => {
|
|
255
|
+
let disposed = false;
|
|
256
|
+
let unregister: (() => Promise<void>) | undefined;
|
|
257
|
+
setStatus("publishing");
|
|
258
|
+
setError(null);
|
|
259
|
+
void client.offerCapability({ ...offer, leaseId: leaseRef.current }, async (input, context) => {
|
|
260
|
+
const renderer = rendererRef.current;
|
|
261
|
+
const key = renderer ? renderers.bind(context, offer.contract, input, renderer) : undefined;
|
|
262
|
+
try {
|
|
263
|
+
const result = await handlerRef.current(input, context);
|
|
264
|
+
if (key) renderers.complete(key, result);
|
|
265
|
+
return result;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (key) renderers.fail(key, error);
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
}).then((stop) => {
|
|
271
|
+
if (disposed) void stop();
|
|
272
|
+
else {
|
|
273
|
+
unregister = stop;
|
|
274
|
+
setStatus("available");
|
|
275
|
+
}
|
|
276
|
+
}).catch((cause: unknown) => {
|
|
277
|
+
if (!disposed) {
|
|
278
|
+
setError(cause instanceof Error ? cause : new Error(String(cause)));
|
|
279
|
+
setStatus("error");
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
return () => {
|
|
283
|
+
disposed = true;
|
|
284
|
+
if (unregister) void unregister();
|
|
285
|
+
};
|
|
286
|
+
}, [client, offerKey, renderers]);
|
|
287
|
+
return { status, error };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Same-session renderer provenance for completed or pending remote calls in a run. The hook
|
|
292
|
+
* derives wait/terminal positions from durable events, while the renderer callback itself stays
|
|
293
|
+
* in the mounted CognateProvider's memory and therefore cannot be restored after a full reload.
|
|
294
|
+
*/
|
|
295
|
+
export function useRemoteCapabilityHistory(runId: string | undefined): readonly (RemoteCapabilityRenderRecord & { readonly render: RemoteCapabilityRenderer })[] {
|
|
296
|
+
const client = useCognate();
|
|
297
|
+
const registry = useRemoteCapabilityRendererRegistry();
|
|
298
|
+
useEffect(() => {
|
|
299
|
+
if (runId === undefined) return;
|
|
300
|
+
return client.subscribe({ runId, afterPosition: 0 }, (event) => registry.observe(event));
|
|
301
|
+
}, [client, registry, runId]);
|
|
302
|
+
const subscribe = useCallback((listener: () => void) => registry.subscribe(listener), [registry]);
|
|
303
|
+
const snapshot = useCallback(() => registry.history(runId), [registry, runId]);
|
|
304
|
+
return useSyncExternalStore(subscribe, snapshot, snapshot).map(({ renderer, ...record }) => ({ ...record, render: renderer }));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Open continuations of a run plus a resolver. */
|
|
308
|
+
export function useContinuations(runId: string | undefined): { readonly open: readonly ContinuationView[]; readonly resolve: (id: string, action: "resume" | "cancel", input?: Json) => Promise<void> } {
|
|
309
|
+
const client = useCognate();
|
|
310
|
+
const state = useRun(runId);
|
|
311
|
+
const resolve = useCallback(
|
|
312
|
+
async (id: string, action: "resume" | "cancel", input?: Json) => {
|
|
313
|
+
await client.resolveContinuation(id, action, input);
|
|
314
|
+
},
|
|
315
|
+
[client],
|
|
316
|
+
);
|
|
317
|
+
return { open: state?.openContinuations ?? [], resolve };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function useArtifact(artifactId: string | undefined): { readonly status: "idle" | "loading" | "ready" | "error"; readonly name?: string; readonly mediaType?: string; readonly text?: string; readonly error?: string } {
|
|
321
|
+
const client = useCognate();
|
|
322
|
+
type Result = { readonly status: "idle" | "loading" | "ready" | "error"; readonly name?: string; readonly mediaType?: string; readonly text?: string; readonly error?: string };
|
|
323
|
+
const [result, setResult] = useState<Result>({ status: "idle" });
|
|
324
|
+
|
|
325
|
+
useEffect(() => {
|
|
326
|
+
if (artifactId === undefined) {
|
|
327
|
+
setResult({ status: "idle" });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
let cancelled = false;
|
|
331
|
+
setResult({ status: "loading" });
|
|
332
|
+
client
|
|
333
|
+
.artifact(artifactId)
|
|
334
|
+
.then((record) => {
|
|
335
|
+
if (cancelled) return;
|
|
336
|
+
if (record.mediaType.startsWith("text/")) {
|
|
337
|
+
setResult({ status: "ready", name: record.name, mediaType: record.mediaType, text: new TextDecoder().decode(record.bytes) });
|
|
338
|
+
} else {
|
|
339
|
+
setResult({ status: "ready", name: record.name, mediaType: record.mediaType });
|
|
340
|
+
}
|
|
341
|
+
})
|
|
342
|
+
.catch((error: unknown) => {
|
|
343
|
+
if (!cancelled) setResult({ status: "error", error: error instanceof Error ? error.message : String(error) });
|
|
344
|
+
});
|
|
345
|
+
return () => {
|
|
346
|
+
cancelled = true;
|
|
347
|
+
};
|
|
348
|
+
}, [client, artifactId]);
|
|
349
|
+
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function useConnectionStatus(): ConnectionStatus {
|
|
354
|
+
const client = useCognate();
|
|
355
|
+
const subscribe = useCallback((onStoreChange: () => void) => client.status.subscribe(onStoreChange), [client]);
|
|
356
|
+
const getSnapshot = useCallback(() => client.status.get(), [client]);
|
|
357
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
358
|
+
}
|