@huaweicloud/agentarts-protocol-agui 0.0.0-stage → 0.0.7

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,190 @@
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) the references of,
46
+ the Work.
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 attribution notices normally appear.
116
+ The content of the NOTICE file is for informational purposes only
117
+ and does 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
+ Copyright 2024 huaweicloud
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # AgentArts AG-UI protocols
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
+ Optional AG-UI 1.0 HTTP/SSE package using official core, encoder and client 1.0.5. Base SDK imports do not load this package.
4
+
5
+ ```ts
6
+ import { AgentArtsRuntimeApp, FileProtocolStorage } from '@huaweicloud/agentarts-sdk/sdk/runtime';
7
+ import { createAguiAgent, EventType } from '@huaweicloud/agentarts-protocol-agui';
8
+ const runtime = new AgentArtsRuntimeApp({ maxConcurrency: 4 });
9
+ runtime.use(createAguiAgent({ authenticate, storage: new FileProtocolStorage('./.agentarts-protocol'),
10
+ execute(input, context) {
11
+ context.emit({ type: EventType.STATE_SNAPSHOT, snapshot: { ready: true } });
12
+ context.emitText('Hello');
13
+ },
14
+ }));
15
+ runtime.run();
16
+ ```
17
+
18
+ The full producer accepts validated multimodal input and all standard message roles. It supports tools/results, state snapshots/patches, interrupt/resume, reasoning/activity/subagent/step/custom/raw events and official chunk expansion. Official sequencing validation and state/message reduction run before durable completion.
19
+
20
+ `context.interrupt(interrupts, checkpoint)` ends the run with an interrupt outcome. Resume using a new runId, the same threadId and an explicit answer for each pending interrupt. Checkpoints, state and completed snapshots survive reopening FileProtocolStorage. Active-run reconnect is not provided: interrupted execution requires a new runId and explicit business recovery.
21
+
22
+ `callTool` emits a tool invocation, never executes untrusted client code. Frontend results return in subsequent tool messages. Application code must authorize tools, state and privileged messages. Media references are preserved without automatic URL access.
23
+
24
+ Authentication is required; identities are derived from verified credentials, not payload IDs. CORS is exact allowlist only. Disconnect requests cancellation and retains the shared runtime permit until cleanup really finishes. Output, replay, stored data and authentication are bounded. Local persistence supports optional AES-GCM; one OS process per directory, no distributed ownership guarantee.
25
+
26
+ `createAguiAdapter()` remains the legacy text-only convenience profile. Use createAguiAgent for the full producer. Example: `pnpm --filter agentarts-protocol-example start:full` after building and configuring AGENTARTS_PROTOCOL_TOKEN. See docs/cn/sdk_user_guide/runtime_protocols.md for limits and contracts. Packages are not yet published; cloud gateway and multi-instance deployment are unverified.
@@ -0,0 +1,34 @@
1
+ import type { Event, RunAgentInput, RunFinishedOutcome, Interrupt, ToolMessage } from '@ag-ui/core';
2
+ import { type ProtocolAuthenticator, type ProtocolStorage, type RuntimeProtocol, type ExecutionPrincipal } from '@huaweicloud/agentarts-sdk/sdk/runtime';
3
+ export interface AguiAgentContext {
4
+ readonly principal: ExecutionPrincipal;
5
+ readonly signal: AbortSignal;
6
+ readonly checkpoint: unknown;
7
+ readonly resume: NonNullable<RunAgentInput['resume']>;
8
+ readonly state: unknown;
9
+ emit(event: Event): void;
10
+ emitText(delta: string): void;
11
+ saveCheckpoint(value: unknown): Promise<void>;
12
+ callTool(name: string, args: unknown): string;
13
+ toolResult(id: string, content: ToolMessage['content']): void;
14
+ interrupt(interrupts: Interrupt[], checkpoint?: unknown): AguiAgentResult;
15
+ }
16
+ export interface AguiAgentResult {
17
+ result?: unknown;
18
+ outcome?: RunFinishedOutcome;
19
+ }
20
+ export interface AguiAgentOptions {
21
+ authenticate: ProtocolAuthenticator;
22
+ execute: (input: RunAgentInput, context: AguiAgentContext) => AguiAgentResult | void | Promise<AguiAgentResult | void>;
23
+ storage?: ProtocolStorage;
24
+ path?: string;
25
+ namespace?: string;
26
+ allowedOrigins?: readonly string[];
27
+ maxBodyBytes?: number;
28
+ bodyTimeoutMs?: number;
29
+ executionTimeoutMs?: number;
30
+ maxOutputBytes?: number;
31
+ }
32
+ /** Full AG-UI producer: official event verification plus persisted, identity-scoped thread checkpoints. */
33
+ export declare function createAguiAgent(options: AguiAgentOptions): RuntimeProtocol;
34
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,kBAAkB,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEpG,OAAO,EAIL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S,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAWD,2GAA2G;AAC3G,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,eAAe,CAgL1E"}
package/dist/agent.js ADDED
@@ -0,0 +1,257 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { EventEncoder } from '@ag-ui/encoder';
3
+ import { EventType } from '@ag-ui/core';
4
+ import { InterruptSchema } from '@ag-ui/core/schemas';
5
+ import { MemoryProtocolStorage, ProtocolEventJournal, ProtocolHttpError, Response, StreamingResponse, authenticateProtocol, protocolCors, protocolFailure, protocolOrigins, protocolSnapshot, requireIdentifier, protocolFingerprint, boundedInteger, } from '@huaweicloud/agentarts-sdk/sdk/runtime';
6
+ import { textInput } from './input.js';
7
+ import { AguiSession } from './session.js';
8
+ function compact(record) {
9
+ const snapshot = { ...record, runs: [...record.runs] };
10
+ while (snapshot.runs.length > 1 && Buffer.byteLength(JSON.stringify(snapshot)) > 3 * 1024 * 1024)
11
+ snapshot.runs.shift();
12
+ return snapshot;
13
+ }
14
+ const eventWindowBytes = 512 * 1024;
15
+ const instances = new Map();
16
+ /** Full AG-UI producer: official event verification plus persisted, identity-scoped thread checkpoints. */
17
+ export function createAguiAgent(options) {
18
+ const path = options.path ?? '/ag-ui';
19
+ const namespace = options.namespace ?? `agui:${path}`;
20
+ const storage = options.storage ?? new MemoryProtocolStorage();
21
+ const origins = protocolOrigins(options.allowedOrigins);
22
+ const instance = randomUUID();
23
+ instances.set(instance, new Set());
24
+ let stopping = false;
25
+ const claims = new Set();
26
+ const live = new Map();
27
+ const encoder = new EventEncoder({ accept: 'text/event-stream' });
28
+ boundedInteger(options.executionTimeoutMs ?? 120000, 'executionTimeoutMs', 2147483647);
29
+ boundedInteger(options.maxOutputBytes ?? 1024 * 1024, 'maxOutputBytes', 16 * 1024 * 1024);
30
+ if (typeof options.authenticate !== 'function' || typeof options.execute !== 'function')
31
+ throw new TypeError('authenticate and execute are required');
32
+ return {
33
+ routes: [{ path, methods: ['POST', 'OPTIONS'] }],
34
+ async shutdown() {
35
+ stopping = true;
36
+ await Promise.all(claims);
37
+ const active = [...live.values()];
38
+ for (const run of active)
39
+ run.cancel();
40
+ await Promise.all(active.map(run => run.done));
41
+ instances.delete(instance);
42
+ },
43
+ async handle(request, host) {
44
+ let cors = {};
45
+ try {
46
+ cors = protocolCors(request, origins, ['POST'], ['authorization', 'content-type']);
47
+ if (request.method === 'OPTIONS')
48
+ return new Response({ statusCode: 204, headers: cors });
49
+ if (stopping)
50
+ throw new ProtocolHttpError(503, 'SHUTTING_DOWN', 'Agent is shutting down');
51
+ const principal = await authenticateProtocol(request, options.authenticate);
52
+ const input = textInput(await request.json(options.maxBodyBytes, options.bodyTimeoutMs), message => host.logger.warn(message), true);
53
+ requireIdentifier(input.threadId, 'threadId');
54
+ requireIdentifier(input.runId, 'runId');
55
+ const scope = createHash('sha256').update(JSON.stringify([namespace, principal.tenantId, principal.subject])).digest('hex');
56
+ const key = input.threadId;
57
+ const local = `${scope}:${key}`;
58
+ if (live.has(local))
59
+ throw new ProtocolHttpError(409, 'RUN_ALREADY_ACTIVE', 'Thread already has an active run');
60
+ const fingerprint = protocolFingerprint(input);
61
+ const previous = await storage.get(scope, key);
62
+ const old = previous?.runs.find(run => run.id === input.runId);
63
+ if (old) {
64
+ if (old.fingerprint !== fingerprint)
65
+ throw new ProtocolHttpError(409, 'RUN_CONFLICT', 'Run id already used with different input');
66
+ if (old.status === 'running')
67
+ throw new ProtocolHttpError(409, 'RUN_INTERRUPTED', 'Interrupted execution requires a new run id');
68
+ const replay = [
69
+ { type: EventType.RUN_STARTED, threadId: input.threadId, runId: input.runId, protocolVersion: '1.0' },
70
+ { type: EventType.MESSAGES_SNAPSHOT, messages: old.messages },
71
+ { type: EventType.STATE_SNAPSHOT, snapshot: old.state },
72
+ old.status === 'failed' ? { type: EventType.RUN_ERROR, message: 'Agent execution failed', code: 'EXECUTION_FAILED' }
73
+ : { type: EventType.RUN_FINISHED, threadId: input.threadId, runId: input.runId, outcome: old.outcome, ...(old.result !== undefined ? { result: old.result } : {}) },
74
+ ];
75
+ return new StreamingResponse((async function* () { for (const event of replay)
76
+ yield encoder.encodeSSE(event); })(), { headers: cors });
77
+ }
78
+ const openInterrupts = previous?.interrupts ?? [];
79
+ const supplied = new Map(input.resume?.map(entry => [entry.interruptId, entry]) ?? []);
80
+ if (supplied.size !== (input.resume?.length ?? 0))
81
+ throw new ProtocolHttpError(400, 'INVALID_RESUME', 'Duplicate resume entries');
82
+ for (const interrupt of openInterrupts) {
83
+ const answer = supplied.get(interrupt.id);
84
+ if (!answer)
85
+ throw new ProtocolHttpError(400, 'INCOMPLETE_RESUME', 'Every pending interrupt needs an explicit answer');
86
+ if (answer.status === 'resolved' && interrupt.expiresAt && Number.isFinite(Date.parse(interrupt.expiresAt)) && Date.parse(interrupt.expiresAt) <= Date.now())
87
+ throw new ProtocolHttpError(400, 'EXPIRED_INTERRUPT', 'Expired interrupt must be cancelled');
88
+ }
89
+ if ([...supplied.keys()].some(id => !openInterrupts.some(interrupt => interrupt.id === id)))
90
+ host.logger.warn('AG-UI ignored unknown resume entries');
91
+ let claimedPrior = previous;
92
+ if (stopping)
93
+ throw new ProtocolHttpError(503, 'SHUTTING_DOWN', 'Agent is shutting down');
94
+ const lease = host.acquireSlot();
95
+ const controller = new AbortController();
96
+ const journal = new ProtocolEventJournal(256, eventWindowBytes);
97
+ let done;
98
+ const finished = new Promise(resolve => { done = resolve; });
99
+ let releaseClaim;
100
+ const claim = new Promise(resolve => { releaseClaim = resolve; });
101
+ claims.add(claim);
102
+ try {
103
+ await storage.update(scope, key, record => {
104
+ if ((record?.owner && instances.has(record.owner) && !instances.get(record.owner).has(local)) || live.has(local))
105
+ throw new ProtocolHttpError(409, 'RUN_ALREADY_ACTIVE', 'Thread already active');
106
+ if (record?.runs.some(run => run.id === input.runId))
107
+ throw new ProtocolHttpError(409, 'RUN_ALREADY_EXISTS', 'Run id already claimed');
108
+ for (const pending of record?.interrupts ?? []) {
109
+ const answer = supplied.get(pending.id);
110
+ if (!answer)
111
+ throw new ProtocolHttpError(400, 'INCOMPLETE_RESUME', 'Every pending interrupt needs an explicit answer');
112
+ if (answer.status === 'resolved' && pending.expiresAt && Date.parse(pending.expiresAt) <= Date.now())
113
+ throw new ProtocolHttpError(400, 'EXPIRED_INTERRUPT', 'Expired interrupt must be cancelled');
114
+ }
115
+ claimedPrior = record;
116
+ return compact({ ...record, owner: instance, interrupts: record?.interrupts ?? [], runs: [...(record?.runs ?? []).slice(-7), {
117
+ id: input.runId, fingerprint, status: 'running', messages: input.messages, state: input.state ?? record?.runs.at(-1)?.state ?? {},
118
+ }] });
119
+ });
120
+ }
121
+ catch (error) {
122
+ claims.delete(claim);
123
+ releaseClaim();
124
+ lease.release();
125
+ throw error;
126
+ }
127
+ for (const failed of instances.values())
128
+ failed.delete(local);
129
+ if (input.state === undefined)
130
+ input.state = claimedPrior?.runs.at(-1)?.state ?? {};
131
+ input.resume = [...supplied.values()].filter(entry => claimedPrior?.interrupts.some(interrupt => interrupt.id === entry.interruptId));
132
+ live.set(local, { cancel: () => controller.abort(), done: finished });
133
+ claims.delete(claim);
134
+ releaseClaim();
135
+ const events = journal.subscribe(0, request.signal);
136
+ const cancel = () => controller.abort();
137
+ request.signal.addEventListener('abort', cancel, { once: true });
138
+ if (stopping || request.signal.aborted)
139
+ cancel();
140
+ const timeout = setTimeout(cancel, options.executionTimeoutMs ?? 120000);
141
+ timeout.unref();
142
+ void (async () => {
143
+ let session;
144
+ let checkpoint = claimedPrior?.checkpoint;
145
+ let requestedInterrupt;
146
+ let final;
147
+ let terminal;
148
+ let outputBytes = 0;
149
+ try {
150
+ session = new AguiSession(input, event => {
151
+ outputBytes += Buffer.byteLength(JSON.stringify(event));
152
+ if (outputBytes > (options.maxOutputBytes ?? 1024 * 1024))
153
+ throw new Error('Run output limit');
154
+ if (event.type === 'RUN_FINISHED' || event.type === 'RUN_ERROR') {
155
+ terminal = protocolSnapshot(event, eventWindowBytes);
156
+ }
157
+ else
158
+ journal.publish(event);
159
+ });
160
+ const skippedExecution = controller.signal.aborted;
161
+ const result = skippedExecution ? undefined : await options.execute(input, {
162
+ principal, signal: controller.signal, get checkpoint() { return checkpoint; }, resume: input.resume ?? [],
163
+ get state() { return session.state; },
164
+ emit: event => session.emit(event), emitText: delta => session.text(delta),
165
+ async saveCheckpoint(value) {
166
+ checkpoint = protocolSnapshot(value, 256 * 1024);
167
+ await storage.update(scope, key, record => {
168
+ if (!record || record.owner !== instance)
169
+ throw new Error('Lost thread ownership');
170
+ return { ...record, checkpoint };
171
+ });
172
+ },
173
+ callTool(name, args) {
174
+ if (!input.tools.some(tool => tool.name === name))
175
+ throw new Error('Tool is not advertised');
176
+ const id = randomUUID();
177
+ session.emit({ type: EventType.TOOL_CALL_START, toolCallId: id, toolCallName: name });
178
+ session.emit({ type: EventType.TOOL_CALL_ARGS, toolCallId: id, delta: JSON.stringify(protocolSnapshot(args)) });
179
+ session.emit({ type: EventType.TOOL_CALL_END, toolCallId: id });
180
+ return id;
181
+ },
182
+ toolResult(id, content) { session.emit({ type: EventType.TOOL_CALL_RESULT, toolCallId: id, messageId: randomUUID(), content }); },
183
+ interrupt(interrupts, value) {
184
+ requestedInterrupt = interrupts.map(item => InterruptSchema.parse(item));
185
+ if (!requestedInterrupt.length || new Set(requestedInterrupt.map(item => item.id)).size !== requestedInterrupt.length)
186
+ throw new Error('Interrupt ids must be nonempty and unique');
187
+ if (value !== undefined)
188
+ checkpoint = protocolSnapshot(value, 256 * 1024);
189
+ return { outcome: { type: 'interrupt', interrupts: requestedInterrupt } };
190
+ },
191
+ });
192
+ const outcome = controller.signal.aborted ? { type: 'cancelled' } : requestedInterrupt ? { type: 'interrupt', interrupts: requestedInterrupt } : result?.outcome ?? { type: 'success' };
193
+ if (outcome.type === 'interrupt') {
194
+ outcome.interrupts = outcome.interrupts.map(item => InterruptSchema.parse(item));
195
+ if (!outcome.interrupts.length || new Set(outcome.interrupts.map(item => item.id)).size !== outcome.interrupts.length)
196
+ throw new Error('Invalid interrupt identities');
197
+ }
198
+ const resultValue = result?.result === undefined ? undefined : protocolSnapshot(result.result, 1024 * 1024);
199
+ // Verify before committing success; buffer the terminal until the durable write succeeds.
200
+ await session.finish(outcome, outcome.type !== 'cancelled' ? resultValue : undefined);
201
+ final = { id: input.runId, fingerprint, status: 'finished', outcome, ...(resultValue !== undefined && outcome.type !== 'cancelled' ? { result: resultValue } : {}), messages: session.messages, state: session.state };
202
+ await storage.update(scope, key, record => {
203
+ if (!record || record.owner !== instance)
204
+ throw new Error('Lost thread ownership');
205
+ return compact({ ...record, owner: undefined, checkpoint, interrupts: skippedExecution ? record.interrupts : outcome.type === 'interrupt' ? outcome.interrupts : [], runs: record.runs.map(run => run.id === input.runId ? final : run) });
206
+ });
207
+ journal.publish(terminal);
208
+ }
209
+ catch {
210
+ instances.get(instance)?.add(local);
211
+ await session?.fail().catch(() => { });
212
+ final = { id: input.runId, fingerprint, status: 'failed', messages: session?.messages ?? input.messages, state: session?.state ?? input.state ?? {} };
213
+ await storage.update(scope, key, record => record ? compact({ ...record, owner: undefined, checkpoint, runs: record.runs.map(run => run.id === input.runId ? final : run) }) : undefined).catch(() => { });
214
+ journal.publish({ type: EventType.RUN_ERROR, message: 'Agent execution failed', code: 'EXECUTION_FAILED' });
215
+ }
216
+ finally {
217
+ session?.dispose();
218
+ clearTimeout(timeout);
219
+ request.signal.removeEventListener('abort', cancel);
220
+ lease.release();
221
+ live.delete(local);
222
+ journal.finish();
223
+ done();
224
+ }
225
+ })();
226
+ const stream = (async function* () {
227
+ try {
228
+ for await (const event of events)
229
+ yield encoder.encodeSSE(event);
230
+ }
231
+ catch {
232
+ if (!request.signal.aborted)
233
+ yield encoder.encodeSSE({ type: EventType.RUN_ERROR, message: 'Event history unavailable', code: 'HISTORY_LOST' });
234
+ }
235
+ finally {
236
+ await events.return?.();
237
+ if (live.has(local)) {
238
+ cancel();
239
+ await finished;
240
+ }
241
+ }
242
+ })();
243
+ const owned = {
244
+ [Symbol.asyncIterator]() { return this; }, next: () => stream.next(),
245
+ async return() { cancel(); await events.return?.(); await finished; return stream.return(); },
246
+ };
247
+ return new StreamingResponse(owned, { headers: { ...cors, 'cache-control': 'no-store', 'x-accel-buffering': 'no' } });
248
+ }
249
+ catch (error) {
250
+ const failure = protocolFailure(error);
251
+ Object.assign(failure.headers, cors);
252
+ throw failure;
253
+ }
254
+ },
255
+ };
256
+ }
257
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACL,qBAAqB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,iBAAiB,EAC3F,oBAAoB,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EACzG,mBAAmB,EAAE,cAAc,GAEpC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AA8B3C,SAAS,OAAO,CAAC,MAAoB;IACnC,MAAM,QAAQ,GAAG,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,IAA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CAAC,EAAE,CAAC;4BAAC,MAAM,EAAE,CAAC;4BAAC,MAAM,QAAQ,CAAC;wBAAC,CAAC;oBAAC,CAAC;gBACzF,CAAC,CAAC,EAAE,CAAC;gBACL,MAAM,KAAK,GAAkC;oBAC3C,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE;oBACpE,KAAK,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,QAAQ,CAAC,CAAC,OAAO,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;iBAC9F,CAAC;gBACF,OAAO,IAAI,iBAAiB,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,eAAe,EAAE,UAAU,EAAE,mBAAmB,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;YACxH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;gBAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAAC,MAAM,OAAO,CAAC;YAAC,CAAC;QAClH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ export { createAguiAgent } from './agent.js';
2
+ export { EventType } from '@ag-ui/core';
3
+ export type { Event, RunAgentInput, Message, Tool, Interrupt, RunFinishedOutcome } from '@ag-ui/core';
4
+ export type { AguiAgentOptions, AguiAgentContext, AguiAgentResult } from './agent.js';
5
+ import { type ProtocolAuthenticator, type RuntimeProtocol, type TextExecutor } from '@huaweicloud/agentarts-sdk/sdk/runtime';
6
+ export interface AguiAdapterOptions {
7
+ authenticate: ProtocolAuthenticator;
8
+ execute: TextExecutor;
9
+ path?: string;
10
+ maxBodyBytes?: number;
11
+ bodyTimeoutMs?: number;
12
+ allowedOrigins?: readonly string[];
13
+ }
14
+ /** AG-UI 1.0 text profile. Connection loss cancels this run; no active-run resume. */
15
+ export declare function createAguiAdapter(options: AguiAdapterOptions): RuntimeProtocol;
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,YAAY,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtG,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACtF,OAAO,EASL,KAAK,qBAAqB,EAG1B,KAAK,eAAe,EACpB,KAAK,YAAY,EAClB,MAAM,wCAAwC,CAAC;AAEhD,MAAM,WAAW,kBAAkB;IACjC,YAAY,EAAE,qBAAqB,CAAC;IACpC,OAAO,EAAE,YAAY,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AACD,sFAAsF;AACtF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,eAAe,CAyK9E"}
package/dist/index.js ADDED
@@ -0,0 +1,186 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { EventType } from '@ag-ui/core';
3
+ import { textInput } from './input.js';
4
+ import { EventEncoder } from '@ag-ui/encoder';
5
+ export { createAguiAgent } from './agent.js';
6
+ export { EventType } from '@ag-ui/core';
7
+ import { authenticateProtocol, protocolFailure, protocolOrigins, protocolCors, ProtocolHttpError, Response, StreamingResponse, requireIdentifier, } from '@huaweicloud/agentarts-sdk/sdk/runtime';
8
+ /** AG-UI 1.0 text profile. Connection loss cancels this run; no active-run resume. */
9
+ export function createAguiAdapter(options) {
10
+ if (typeof options.authenticate !== 'function' || typeof options.execute !== 'function')
11
+ throw new TypeError('authenticate and execute are required');
12
+ const path = options.path ?? '/ag-ui';
13
+ const origins = protocolOrigins(options.allowedOrigins);
14
+ const encoder = new EventEncoder({ accept: 'text/event-stream' });
15
+ return {
16
+ routes: [{ path, methods: ['POST', 'OPTIONS'] }],
17
+ async handle(request, host) {
18
+ let cors = {};
19
+ try {
20
+ cors = protocolCors(request, origins, ['POST'], ['authorization', 'content-type']);
21
+ if (request.method === 'OPTIONS')
22
+ return new Response({ statusCode: 204, headers: cors });
23
+ const principal = await authenticateProtocol(request, options.authenticate);
24
+ const raw = await request.json(options.maxBodyBytes, options.bodyTimeoutMs);
25
+ const input = textInput(raw, (message) => host.logger.warn(message));
26
+ requireIdentifier(input.threadId, 'threadId');
27
+ requireIdentifier(input.runId, 'runId');
28
+ const key = createHash('sha256')
29
+ .update(JSON.stringify([path, input.threadId, input.runId]))
30
+ .digest('hex');
31
+ let active = false;
32
+ try {
33
+ active = !host.executions.get(principal, key).outcome;
34
+ }
35
+ catch (error) {
36
+ if (protocolFailure(error).status !== 404)
37
+ throw error;
38
+ }
39
+ if (active)
40
+ throw new ProtocolHttpError(409, 'RUN_ALREADY_ACTIVE', 'An active run cannot be resumed');
41
+ // Strip optional undefined defaults produced by schema validation. No wire
42
+ // identity/headers are ever copied into the execution principal.
43
+ const handle = host.executions.start(principal, key, JSON.parse(JSON.stringify(input)), options.execute);
44
+ const initialOutput = handle.output;
45
+ const initialOutcome = handle.outcome;
46
+ let events;
47
+ try {
48
+ events = handle.events(handle.sequence, request.signal);
49
+ }
50
+ catch (error) {
51
+ if (!handle.outcome)
52
+ void handle.cancel();
53
+ throw error;
54
+ }
55
+ const cancel = () => {
56
+ void handle.cancel();
57
+ };
58
+ request.signal.addEventListener('abort', cancel, { once: true });
59
+ if (request.signal.aborted)
60
+ cancel();
61
+ const stream = (async function* () {
62
+ let textStarted = false;
63
+ const encode = (event) => encoder.encodeSSE(event);
64
+ try {
65
+ yield encode({
66
+ type: EventType.RUN_STARTED,
67
+ threadId: input.threadId,
68
+ runId: input.runId,
69
+ protocolVersion: '1.0',
70
+ });
71
+ if (initialOutput) {
72
+ textStarted = true;
73
+ yield encode({
74
+ type: EventType.TEXT_MESSAGE_START,
75
+ messageId: handle.executionId,
76
+ role: 'assistant',
77
+ });
78
+ yield encode({
79
+ type: EventType.TEXT_MESSAGE_CONTENT,
80
+ messageId: handle.executionId,
81
+ delta: initialOutput,
82
+ });
83
+ }
84
+ if (initialOutcome) {
85
+ if (textStarted)
86
+ yield encode({ type: EventType.TEXT_MESSAGE_END, messageId: handle.executionId });
87
+ if (initialOutcome.state === 'failed')
88
+ yield encode({
89
+ type: EventType.RUN_ERROR,
90
+ message: 'Agent execution failed',
91
+ code: 'EXECUTION_FAILED',
92
+ });
93
+ else
94
+ yield encode({
95
+ type: EventType.RUN_FINISHED,
96
+ threadId: input.threadId,
97
+ runId: input.runId,
98
+ result: initialOutcome.state === 'completed' ? initialOutcome.output : undefined,
99
+ outcome: { type: initialOutcome.state === 'canceled' ? 'cancelled' : 'success' },
100
+ });
101
+ return;
102
+ }
103
+ for await (const event of events) {
104
+ if (event.type === 'text') {
105
+ if (!textStarted) {
106
+ textStarted = true;
107
+ yield encode({
108
+ type: EventType.TEXT_MESSAGE_START,
109
+ messageId: handle.executionId,
110
+ role: 'assistant',
111
+ });
112
+ }
113
+ yield encode({
114
+ type: EventType.TEXT_MESSAGE_CONTENT,
115
+ messageId: handle.executionId,
116
+ delta: event.delta,
117
+ });
118
+ }
119
+ else {
120
+ const finalOutcome = await handle.done;
121
+ if (textStarted)
122
+ yield encode({ type: EventType.TEXT_MESSAGE_END, messageId: handle.executionId });
123
+ if (event.outcome?.state === 'failed')
124
+ yield encode({
125
+ type: EventType.RUN_ERROR,
126
+ message: 'Agent execution failed',
127
+ code: 'EXECUTION_FAILED',
128
+ });
129
+ else
130
+ yield encode({
131
+ type: EventType.RUN_FINISHED,
132
+ threadId: input.threadId,
133
+ runId: input.runId,
134
+ result: finalOutcome.state === 'completed' ? finalOutcome.output : undefined,
135
+ outcome: {
136
+ type: event.outcome?.state === 'canceled' ? 'cancelled' : 'success',
137
+ },
138
+ });
139
+ }
140
+ }
141
+ }
142
+ catch {
143
+ if (!request.signal.aborted) {
144
+ if (textStarted)
145
+ yield encode({ type: EventType.TEXT_MESSAGE_END, messageId: handle.executionId });
146
+ yield encode({
147
+ type: EventType.RUN_ERROR,
148
+ message: 'Event stream unavailable',
149
+ code: 'REPLAY_UNAVAILABLE',
150
+ });
151
+ }
152
+ }
153
+ finally {
154
+ request.signal.removeEventListener('abort', cancel);
155
+ await events.return?.();
156
+ if (!handle.outcome)
157
+ await handle.cancel();
158
+ }
159
+ })();
160
+ // Closing before the generator starts must also unsubscribe/cancel.
161
+ const owned = {
162
+ [Symbol.asyncIterator]() {
163
+ return this;
164
+ },
165
+ next: () => stream.next(),
166
+ async return() {
167
+ request.signal.removeEventListener('abort', cancel);
168
+ await events.return?.();
169
+ if (!handle.outcome)
170
+ await handle.cancel();
171
+ return stream.return();
172
+ },
173
+ };
174
+ return new StreamingResponse(owned, {
175
+ headers: { ...cors, 'cache-control': 'no-store', 'x-accel-buffering': 'no' },
176
+ });
177
+ }
178
+ catch (error) {
179
+ const failure = protocolFailure(error);
180
+ Object.assign(failure.headers, cors);
181
+ throw failure;
182
+ }
183
+ },
184
+ };
185
+ }
186
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAc,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,SAA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eAAe,CAAC,KAAK,CAAC,CAAC;gBACvC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBACrC,MAAM,OAAO,CAAC;YAChB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { RunAgentInput } from '@ag-ui/core';
2
+ /** Protocol objects are closed; metadata, state, tool parameters and forwardedProps are open. */
3
+ export declare function textInput(raw: unknown, onWarning: (message: string) => void, rich?: boolean): RunAgentInput;
4
+ //# sourceMappingURL=input.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../src/input.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AA4BjD,iGAAiG;AACjG,wBAAgB,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,EAAE,IAAI,UAAQ,GAAG,aAAa,CAgIzG"}
package/dist/input.js ADDED
@@ -0,0 +1,143 @@
1
+ import * as schemas from '@ag-ui/core/schemas';
2
+ import { ProtocolHttpError } from '@huaweicloud/agentarts-sdk/sdk/runtime';
3
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const messages = {
5
+ user: schemas.UserMessageSchema,
6
+ assistant: schemas.AssistantMessageSchema,
7
+ system: schemas.SystemMessageSchema,
8
+ developer: schemas.DeveloperMessageSchema,
9
+ tool: schemas.ToolMessageSchema,
10
+ activity: schemas.ActivityMessageSchema,
11
+ reasoning: schemas.ReasoningMessageSchema,
12
+ };
13
+ const parts = {
14
+ text: schemas.TextPartSchema,
15
+ image: schemas.ImagePartSchema,
16
+ audio: schemas.AudioPartSchema,
17
+ video: schemas.VideoPartSchema,
18
+ document: schemas.DocumentPartSchema,
19
+ };
20
+ const sources = {
21
+ data: schemas.DataSourceSchema,
22
+ url: schemas.UrlSourceSchema,
23
+ file: schemas.FileSourceSchema,
24
+ };
25
+ /** Protocol objects are closed; metadata, state, tool parameters and forwardedProps are open. */
26
+ export function textInput(raw, onWarning, rich = false) {
27
+ let warnings = 0;
28
+ const warn = (message) => {
29
+ if (warnings++ < 8)
30
+ onWarning(message);
31
+ else if (warnings === 9)
32
+ onWarning('AG-UI additional input compatibility warnings suppressed');
33
+ };
34
+ const pick = (value, schema, path) => {
35
+ if (!object(value))
36
+ return value; // Known malformed values must reach validation unchanged.
37
+ const result = {};
38
+ for (const [key, item] of Object.entries(value)) {
39
+ if (Object.hasOwn(schema.shape, key))
40
+ result[key] = item;
41
+ else
42
+ warn(`AG-UI stripped an unknown property at ${path}.${JSON.stringify(key.slice(0, 64))}`);
43
+ }
44
+ return result;
45
+ };
46
+ const map = (value, transform, path) => (Array.isArray(value) ? value.map((item, i) => transform(item, `${path}[${i}]`)) : value);
47
+ const content = (value, path) => {
48
+ if (!Array.isArray(value))
49
+ return value;
50
+ return value.flatMap((item, i) => {
51
+ const at = `${path}[${i}]`;
52
+ if (!object(item) || typeof item.type !== 'string')
53
+ return [item];
54
+ if (!Object.hasOwn(parts, item.type)) {
55
+ warn(`AG-UI dropped an unknown content part at ${at}`);
56
+ return [];
57
+ }
58
+ const result = pick(item, parts[item.type], at);
59
+ if (item.type !== 'text' && object(result.source)) {
60
+ const kind = result.source.type;
61
+ if (typeof kind === 'string' && !Object.hasOwn(sources, kind)) {
62
+ warn(`AG-UI dropped a content part with an unknown source at ${at}`);
63
+ return [];
64
+ }
65
+ if (typeof kind === 'string')
66
+ result.source = pick(result.source, sources[kind], `${at}.source`);
67
+ }
68
+ return [result];
69
+ });
70
+ };
71
+ const clean = pick(raw, schemas.RunAgentInputSchema, 'input');
72
+ if (object(clean)) {
73
+ if (Array.isArray(clean.messages))
74
+ clean.messages = clean.messages.flatMap((message, i) => {
75
+ const path = `input.messages[${i}]`;
76
+ if (!object(message) || typeof message.role !== 'string')
77
+ return [message];
78
+ if (!Object.hasOwn(messages, message.role)) {
79
+ warn(`AG-UI dropped an unknown message variant at ${path}`);
80
+ return [];
81
+ }
82
+ const result = pick(message, messages[message.role], path);
83
+ if (['user', 'tool'].includes(message.role))
84
+ result.content = content(result.content, `${path}.content`);
85
+ if (result.toolCalls !== undefined)
86
+ result.toolCalls = map(result.toolCalls, (call, at) => {
87
+ const cleaned = pick(call, schemas.ToolCallSchema, at);
88
+ if (object(cleaned) && cleaned.function !== undefined)
89
+ cleaned.function = pick(cleaned.function, schemas.FunctionCallSchema, `${at}.function`);
90
+ return cleaned;
91
+ }, `${path}.toolCalls`);
92
+ return [result];
93
+ });
94
+ for (const [key, schema] of [
95
+ ['tools', schemas.ToolSchema],
96
+ ['context', schemas.ContextSchema],
97
+ ['resume', schemas.ResumeEntrySchema],
98
+ ]) {
99
+ if (clean[key] !== undefined)
100
+ clean[key] = map(clean[key], (item, path) => pick(item, schema, path), `input.${key}`);
101
+ }
102
+ }
103
+ const parsed = schemas.RunAgentInputSchema.safeParse(clean);
104
+ if (!parsed.success)
105
+ throw new ProtocolHttpError(400, 'INVALID_INPUT', 'Invalid AG-UI input');
106
+ const input = parsed.data;
107
+ if (input.protocolVersion !== undefined) {
108
+ const version = /^(\d+)\.(\d+)$/.exec(input.protocolVersion);
109
+ if (version && (version[1].replace(/^0+/, '') || '0') !== '1')
110
+ throw new ProtocolHttpError(400, 'UNSUPPORTED_VERSION', 'Unsupported AG-UI major version');
111
+ if (input.protocolVersion !== '1.0')
112
+ warn('AG-UI peer declares a newer or unrecognised version; serving 1.0');
113
+ }
114
+ if (!rich && (input.tools.length ||
115
+ input.resume?.length ||
116
+ (input.state != null && (!object(input.state) || Object.keys(input.state).length)) ||
117
+ input.messages.length > 128 ||
118
+ input.messages.some((message) => !['user', 'assistant'].includes(message.role) ||
119
+ (message.role === 'assistant' && message.toolCalls?.length))))
120
+ throw new ProtocolHttpError(400, 'UNSUPPORTED_CAPABILITY', 'Only user/assistant text conversations are supported');
121
+ if (rich)
122
+ return input;
123
+ // Do not access URLs or opaque provider handles. Validate known parts above before dropping media.
124
+ input.messages = input.messages.map((message, index) => {
125
+ let value = 'content' in message ? message.content : undefined;
126
+ if (Array.isArray(value)) {
127
+ value = value
128
+ .map((part, i) => {
129
+ if (part.type === 'text')
130
+ return part.text;
131
+ warn(`AG-UI skipped unusable media at input.messages[${index}].content[${i}]`);
132
+ return '';
133
+ })
134
+ .join('');
135
+ }
136
+ const text = value ?? '';
137
+ if (typeof text !== 'string' || text.length > 65536)
138
+ throw new ProtocolHttpError(400, 'INVALID_INPUT', 'Text content limit exceeded');
139
+ return { ...message, content: text };
140
+ });
141
+ return input;
142
+ }
143
+ //# sourceMappingURL=input.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input.js","sourceRoot":"","sources":["../src/input.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,qBAAqB,CAAC;AAE/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AAG3E,MAAM,MAAM,GAAG,CAAC,KAAc,EAAoC,EAAE,CAClE,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACvE,MAAM,QAAQ,GAAiC;IAC7C,IAAI,EAAE,OAAO,CAAC,iBAAiB;IAC/B,SAAS,EAAE,OAAO,CAAC,sBAAsB;IACzC,MAAM,EAAE,OAAO,CAAC,mBAAmB;IACnC,SAAS,EAAE,OAAO,CAAC,sBAAsB;IACzC,IAAI,EAAE,OAAO,CAAC,iBAAiB;IAC/B,QAAQ,EAAE,OAAO,CAAC,qBAAqB;IACvC,SAAS,EAAE,OAAO,CAAC,sBAAsB;CAC1C,CAAC;AACF,MAAM,KAAK,GAAiC;IAC1C,IAAI,EAAE,OAAO,CAAC,cAAc;IAC5B,KAAK,EAAE,OAAO,CAAC,eAAe;IAC9B,KAAK,EAAE,OAAO,CAAC,eAAe;IAC9B,KAAK,EAAE,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AAI;QAAE,OAAO,KAAK,CAAC;IACvB,mGAAmG;IACnG,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;QACrD,IAAI,KAAK,GAAG,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,GAAG,KAAK;iBACV,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE;gBACf,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM;oBAAE,OAAO,IAAI,CAAC,IAAI,CAAC;gBAC3C,IAAI,CAAC,kDAAkD,KAAK,aAAa,CAAC,GAAG,CAAC,CAAC;gBAC/E,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC;iBACD,IAAI,CAAC,EAAE,CAAC,CAAC;QACd,CAAC;QACD,MAAM,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QACzB,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK;YACjD,MAAM,IAAI,iBAAiB,CAAC,GAAG,EAAE,eAAe,EAAE,6BAA6B,CAAC,CAAC;QACnF,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAoB,CAAC;IACzD,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { Event, RunAgentInput, Message, State, RunFinishedOutcome } from '@ag-ui/core';
2
+ /** Use the official sequencing verifier/reducer for all 31 event types, not a second partial FSM. */
3
+ export declare class AguiSession {
4
+ readonly input: RunAgentInput;
5
+ private readonly inputEvents;
6
+ private readonly checkedEvents;
7
+ private failure;
8
+ private terminal;
9
+ private helperMessage?;
10
+ private readonly agent;
11
+ private readonly subscriptions;
12
+ private readonly reduced;
13
+ private currentState;
14
+ constructor(input: RunAgentInput, publish: (event: Event) => void);
15
+ get messages(): Message[];
16
+ get state(): State;
17
+ private send;
18
+ emit(event: Event): void;
19
+ text(delta: string): void;
20
+ finish(outcome: RunFinishedOutcome, result?: unknown): Promise<void>;
21
+ fail(): Promise<void>;
22
+ dispose(): void;
23
+ }
24
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAO5F,qGAAqG;AACrG,qBAAa,WAAW;IAUV,QAAQ,CAAC,KAAK,EAAE,aAAa;IATzC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAwB;IACpD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAwB;IACtD,OAAO,CAAC,OAAO,CAAU;IACzB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC;IAC/B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,YAAY,CAAQ;gBACP,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI;IAgC1E,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAkD;IAC3E,IAAI,KAAK,IAAI,KAAK,CAAgD;IAClE,OAAO,CAAC,IAAI;IAMZ,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAIxB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAOnB,MAAM,CAAC,OAAO,EAAE,kBAAkB,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAM3B,OAAO,IAAI,IAAI;CAIhB"}
@@ -0,0 +1,113 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { AbstractAgent, defaultApplyEvents, transformChunks, verifyEvents } from '@ag-ui/client';
3
+ import { EMPTY, Subject } from 'rxjs';
4
+ import { EventSchema } from '@ag-ui/core/schemas';
5
+ import { EventType } from '@ag-ui/core';
6
+ import { protocolSnapshot } from '@huaweicloud/agentarts-sdk/sdk/runtime';
7
+ import jsonPatch from 'fast-json-patch';
8
+ class SnapshotAgent extends AbstractAgent {
9
+ run() { return EMPTY; }
10
+ }
11
+ /** Use the official sequencing verifier/reducer for all 31 event types, not a second partial FSM. */
12
+ export class AguiSession {
13
+ input;
14
+ inputEvents = new Subject();
15
+ checkedEvents = new Subject();
16
+ failure;
17
+ terminal = false;
18
+ helperMessage;
19
+ agent;
20
+ subscriptions;
21
+ reduced;
22
+ currentState;
23
+ constructor(input, publish) {
24
+ this.input = input;
25
+ this.agent = new SnapshotAgent({ threadId: input.threadId, initialMessages: input.messages, initialState: input.state ?? {} });
26
+ this.currentState = protocolSnapshot(input.state ?? {});
27
+ let resolveReduced;
28
+ let rejectReduced;
29
+ this.reduced = new Promise((resolve, reject) => { resolveReduced = resolve; rejectReduced = reject; });
30
+ void this.reduced.catch(() => { });
31
+ const reduce = defaultApplyEvents(input, this.checkedEvents, this.agent, [], false).subscribe({
32
+ next: update => {
33
+ if (update.messages)
34
+ this.agent.setMessages(update.messages);
35
+ if (update.state !== undefined)
36
+ this.agent.setState(update.state);
37
+ },
38
+ error: error => { this.failure = error; rejectReduced(error); },
39
+ complete: resolveReduced,
40
+ });
41
+ const verify = this.inputEvents.pipe(transformChunks(false), verifyEvents(false)).subscribe({
42
+ next: event => {
43
+ try {
44
+ const value = protocolSnapshot(EventSchema.parse(event));
45
+ if (value.type === EventType.STATE_SNAPSHOT)
46
+ this.currentState = protocolSnapshot(value.snapshot);
47
+ if (value.type === EventType.STATE_DELTA)
48
+ this.currentState = jsonPatch.applyPatch(protocolSnapshot(this.currentState), value.delta, true, false, true).newDocument;
49
+ this.checkedEvents.next(value);
50
+ if (this.failure)
51
+ throw this.failure;
52
+ publish(value);
53
+ }
54
+ catch (error) {
55
+ this.failure = error;
56
+ }
57
+ },
58
+ error: error => { this.failure = error; this.checkedEvents.complete(); rejectReduced(error); },
59
+ complete: () => this.checkedEvents.complete(),
60
+ });
61
+ this.subscriptions = [reduce, verify];
62
+ this.send({ type: EventType.RUN_STARTED, threadId: input.threadId, runId: input.runId, protocolVersion: '1.0', ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}) });
63
+ }
64
+ get messages() { return protocolSnapshot(this.agent.messages); }
65
+ get state() { return protocolSnapshot(this.currentState); }
66
+ send(event) {
67
+ if (this.failure)
68
+ throw this.failure;
69
+ const value = protocolSnapshot(EventSchema.parse(event));
70
+ this.inputEvents.next(value);
71
+ if (this.failure)
72
+ throw this.failure;
73
+ }
74
+ emit(event) {
75
+ if (this.terminal || ['RUN_STARTED', 'RUN_FINISHED', 'RUN_ERROR'].includes(event.type))
76
+ throw new Error('Run lifecycle is owned by the adapter');
77
+ this.send(event);
78
+ }
79
+ text(delta) {
80
+ if (!this.helperMessage) {
81
+ this.helperMessage = randomUUID();
82
+ this.emit({ type: EventType.TEXT_MESSAGE_START, messageId: this.helperMessage, role: 'assistant' });
83
+ }
84
+ this.emit({ type: EventType.TEXT_MESSAGE_CONTENT, messageId: this.helperMessage, delta });
85
+ }
86
+ async finish(outcome, result) {
87
+ if (this.helperMessage) {
88
+ this.emit({ type: EventType.TEXT_MESSAGE_END, messageId: this.helperMessage });
89
+ this.helperMessage = undefined;
90
+ }
91
+ this.send({ type: EventType.RUN_FINISHED, threadId: this.input.threadId, runId: this.input.runId, outcome, ...(result !== undefined ? { result } : {}) });
92
+ this.terminal = true;
93
+ this.inputEvents.complete();
94
+ await this.reduced;
95
+ if (this.failure)
96
+ throw this.failure;
97
+ }
98
+ async fail() {
99
+ if (!this.failure && !this.terminal)
100
+ this.send({ type: EventType.RUN_ERROR, message: 'Agent execution failed', code: 'EXECUTION_FAILED' });
101
+ this.terminal = true;
102
+ this.inputEvents.complete();
103
+ this.checkedEvents.complete();
104
+ await this.reduced.catch(() => { });
105
+ }
106
+ dispose() {
107
+ this.inputEvents.complete();
108
+ this.checkedEvents.complete();
109
+ for (const subscription of this.subscriptions)
110
+ subscription.unsubscribe();
111
+ }
112
+ }
113
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AACjG,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,SAAS,MAAM,iBAAiB,CAAC;AAExC,MAAM,aAAc,SAAQ,aAAa;IAC9B,GAAG,KAAK,OAAO,KAAK,CAAC,CAAC,CAAC;CACjC;AACD,qGAAqG;AACrG,MAAM,OAAO,WAAW;IAUD;IATJ,WAAW,GAAG,IAAI,OAAO,EAAS,CAAC;IACnC,aAAa,GAAG,IAAI,OAAO,EAAS,CAAC;IAC9C,OAAO,CAAU;IACjB,QAAQ,GAAG,KAAK,CAAC;IACjB,aAAa,CAAU;IACd,KAAK,CAAgB;IACrB,aAAa,CAAC;IACd,OAAO,CAAgB;IAChC,YAAY,CAAQ;IAC5B,YAAqB,KAAoB,EAAE,OAA+B;QAArD,UAAK,GAAL,KAAK,CAAe;QACvC,IAAI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AC;QAC3I,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;QAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;QAC3D,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACrC,CAAC;IACD,OAAO;QACL,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;QAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;QAC3D,KAAK,MAAM,YAAY,IAAI,IAAI,CAAC,aAAa;YAAE,YAAY,CAAC,WAAW,EAAE,CAAC;IAC5E,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@huaweicloud/agentarts-protocol-agui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.7",
4
+ "type": "module",
5
+ "description": "Optional AgentArts AGUI runtime adapter",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "license": "Apache-2.0",
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "dependencies": {
24
+ "@ag-ui/client": "1.0.5",
25
+ "@ag-ui/core": "1.0.5",
26
+ "@ag-ui/encoder": "1.0.5",
27
+ "fast-json-patch": "3.1.2",
28
+ "rxjs": "7.8.1",
29
+ "zod": "4.6.7"
30
+ },
31
+ "peerDependencies": {
32
+ "@huaweicloud/agentarts-sdk": "^0.0.7"
33
+ },
34
+ "devDependencies": {
35
+ "@huaweicloud/agentarts-sdk": "0.0.7"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.json",
39
+ "clean": "node ../../scripts/clean.mjs"
40
+ }
6
41
  }