@agent-cards/commerce-sdk 0.18.2 → 0.18.4
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/README.md +37 -1
- package/dist/ack.js +2 -1
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +3 -0
- package/dist/buy-tool.d.ts +8 -0
- package/dist/buy-tool.js +25 -10
- package/dist/client.d.ts +20 -1
- package/dist/client.js +8 -2
- package/dist/definition.d.ts +2 -0
- package/dist/definition.js +4 -1
- package/dist/direct.js +3 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/trip-ask.d.ts +33 -0
- package/dist/trip-ask.js +63 -0
- package/dist/turn-reader.d.ts +45 -0
- package/dist/turn-reader.js +148 -0
- package/dist/turn-record.d.ts +31 -0
- package/dist/turn-record.js +26 -0
- package/dist/turn-stream.d.ts +38 -0
- package/dist/turn-stream.js +91 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -178,6 +178,40 @@ onShopperMessage((message) => windows.settle(message));
|
|
|
178
178
|
|
|
179
179
|
`markStepDone`, `keepOfferingStep` and `onShopperMessage` stand for your own code. `settle` closes each open pop-up whose step the message ends and returns `[{ step, outcome }]`. A pop-up the shopper closes before the step ends reaches `onClosed`, checked every 500 milliseconds (`pollMs`): the step is still open, so keep its link on screen, and a tap opens it again. Tapping a step whose pop-up is open brings that window to the front instead of opening a second one. A phone's browser opens the pop-up as a tab, and `settle` closes that tab the same way, since the chat opened it. The pop-up is 480 by 760 pixels by default (`width`, `height`), kept inside the screen. It keeps its opener on purpose: a window opened with `noopener` hands back no handle, so the chat could neither close it nor tell when the shopper closed it. `dispose()` stops watching and leaves every pop-up open, so a chat that remounts never shuts the page a shopper is typing a card into.
|
|
180
180
|
|
|
181
|
+
## Keep the answer when the shopper's connection drops
|
|
182
|
+
|
|
183
|
+
A phone that loses its connection while a reply streams back would show the shopper an error, though the turn finished on your server. Serve the turn with `turnStream` and read it in the browser with `streamTurn`, and the shopper gets the answer anyway. On your server:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { readTurn, turnStream, isTurnId } from '@agent-cards/commerce-sdk';
|
|
187
|
+
|
|
188
|
+
// POST /chat: the browser names the turn in `x-turn-id`.
|
|
189
|
+
const turnId = request.headers.get('x-turn-id');
|
|
190
|
+
if (!isTurnId(turnId)) return Response.json({ error: 'Name the turn.' }, { status: 400 });
|
|
191
|
+
const { stream, finished } = turnStream({ store, key: `${shopperId}:${turnId}`, run: (send) => runTurn(send) });
|
|
192
|
+
waitUntil(finished);
|
|
193
|
+
return new Response(stream, { headers: { 'content-type': 'text/event-stream' } });
|
|
194
|
+
|
|
195
|
+
// GET /chat/turn?id=...: the turn's record, for the browser to pick up where its stream stopped.
|
|
196
|
+
return Response.json(await readTurn(store, `${shopperId}:${id}`));
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`store` is yours, such as Redis: `load(key)` and `save(key, record, ttlSeconds)`. `runTurn` stands for your agent's turn, and `send(event, data)` takes each event the chat shows, the last one included, such as `done`. The turn runs to its end after the browser leaves, and `finished` resolves once its record is saved: hand it to your host's `waitUntil`. The record is kept for ten minutes (`ttlSeconds`). Put your shopper's id in the key, so no shopper reads another's turn. When one turn at a time runs per shopper, answer a message sent during a turn with a 409 whose body names that turn, `{ "error": "...", "turn_id": "..." }`.
|
|
200
|
+
|
|
201
|
+
In the browser:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import { streamTurn, readTurnResponse } from '@agent-cards/commerce-sdk/browser';
|
|
205
|
+
|
|
206
|
+
const { refused } = await streamTurn({
|
|
207
|
+
start: (turnId) => fetch('/chat', { method: 'POST', headers: { 'x-turn-id': turnId }, body }),
|
|
208
|
+
read: (turnId) => fetch(`/chat/turn?id=${turnId}`).then(readTurnResponse),
|
|
209
|
+
onEvent: (event, data) => show(event, data),
|
|
210
|
+
});
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
`onEvent` hears each event once, in order. When the stream drops, before its first event or after it, `streamTurn` reads the turn's record every 1.5 seconds (`pollMs`) and hands over the events the stream did not carry, until the turn's last one. A 409 that names a running turn waits for that turn's answer the same way. Any other refusal comes back in `refused`, the response, for you to show its error. A record that never appears within 15 seconds (`startWaitMs`) means the message never reached your server, and `streamTurn` throws the connection's error.
|
|
214
|
+
|
|
181
215
|
## Answer each shopper message in its own turn
|
|
182
216
|
|
|
183
217
|
A shopper can send a second message before the first is answered. The `sendLink`, `onWorking` and `onResult` you pass to `buyTool` hear every call, whichever message the call answers, so a callback that hands each link to "the message running now" gives the first message's cards to the second. Open a turn for each message instead, and pass the turn to your model in place of the tool:
|
|
@@ -251,6 +285,8 @@ const turn = buy.turn(message, {
|
|
|
251
285
|
onItem: (item) => (item.kind === 'text' ? sendText(shopper.id, item.text) : sendCard(shopper.id, item.link)), // your code
|
|
252
286
|
});
|
|
253
287
|
if (await turn.handled()) {
|
|
288
|
+
// A newer message from the shopper stopped this turn: that message's turn answers and keeps the exchange.
|
|
289
|
+
if (turn.stopped) return;
|
|
254
290
|
// Agentcard answered the shopper: keep the exchange, so your model reads it on the next message.
|
|
255
291
|
const said = turn.items.flatMap((item) => (item.kind === 'text' ? [item.text] : [])).join('\n\n');
|
|
256
292
|
history = [...turn.messages(history), { role: 'assistant', content: said }];
|
|
@@ -432,7 +468,7 @@ const buy = buyTool({
|
|
|
432
468
|
|
|
433
469
|
`ack` takes `'reaction'`, `'text'` or `'none'`. Left out, the tool reacts when the tool or the turn has an `onReaction`, and sends text through `onWorking` otherwise, so an app built on 0.9 with only `onWorking` keeps its text replies. With both callbacks, the shopper gets the 👀 and never the text too. `'none'`, or `false`, sends nothing.
|
|
434
470
|
|
|
435
|
-
In text mode, a streamed search's reply is Agentcard's own line, written from the conversation while it searches, such as `one sec, checking target for la croix`, and it reaches `onWorking` before the cards or not at all. A search `buy.turn` sends straight that has shown the shopper nothing by twice `ackDelayMs`, because Agentcard wrote no line or its line was dropped, sends `one moment` once, and a line of Agentcard's that comes after it is dropped. When your model's run fails before it wrote or called anything, call `turn.end()` before you show your error, so no wait line follows it. With `stream: false`, the tool sends its own reply when Agentcard has not answered a new request within `ackDelayMs`, 1 second by default, so a quick answer arrives alone. It sends one for the calls the model makes in one turn, where a call that starts within 15 seconds of the last one ending counts as the same turn. A slow confirm or pick never hears `looking for`: a pick, of a product, a store or a place in a list such as `the first one`, hears `got it, one moment`, a confirm hears `on it, one moment`, and any other answer hears `one moment`. A turn opened with `buy.turn` that has shown the shopper nothing, no line and no card, after the delay sends that line once. None of them names anything the shopper said, and a code hears nothing. The words rotate through six templates, and one tool never sends the same template twice in a row. A short paraphrase of the request goes in when the tool can read one: it stops before any link, email address, phone number, street address or long number, and a request that starts with one gets a reply that names nothing, such as `looking for that now`. The call waits for `onWorking`, so the shopper reads the reply before any link and before the model answers. An `onWorking` that throws costs only the instant reply.
|
|
471
|
+
In text mode, a streamed search's reply is Agentcard's own line, written from the conversation while it searches, such as `one sec, checking target for la croix`, and it reaches `onWorking` before the cards or not at all. A search `buy.turn` sends straight that has shown the shopper nothing by twice `ackDelayMs`, because Agentcard wrote no line or its line was dropped, sends `one moment` once, and a line of Agentcard's that comes after it is dropped. When your model's run fails before it wrote or called anything, call `turn.end()` before you show your error, so no wait line follows it. When `turn.stopped` is true after a call, the shopper sent a new message while this turn ran and Agentcard stopped the turn for it: end the turn there, with no model call, no error and no saved history, because the new message's turn answers. With `stream: false`, the tool sends its own reply when Agentcard has not answered a new request within `ackDelayMs`, 1 second by default, so a quick answer arrives alone. It sends one for the calls the model makes in one turn, where a call that starts within 15 seconds of the last one ending counts as the same turn. A slow confirm or pick never hears `looking for`: a pick, of a product, a store or a place in a list such as `the first one`, hears `got it, one moment`, a confirm hears `on it, one moment`, and any other answer hears `one moment`. A turn opened with `buy.turn` that has shown the shopper nothing, no line and no card, after the delay sends that line once. None of them names anything the shopper said, and a code hears nothing. The words rotate through six templates, and one tool never sends the same template twice in a row. A short paraphrase of the request goes in when the tool can read one: it stops before any link, email address, phone number, street address or long number, and a request that starts with one gets a reply that names nothing, such as `looking for that now`. The call waits for `onWorking`, so the shopper reads the reply before any link and before the model answers. An `onWorking` that throws costs only the instant reply.
|
|
436
472
|
|
|
437
473
|
Pass `ack: (ask) => text` to write your own text from the shopper's words, where an empty answer sends none, and `ackDelayMs` to change the 1 second for either mode.
|
|
438
474
|
|
package/dist/ack.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* store the shopper saw, such as `order here`, or `Order from Tacos El Grullense` as a store card sends it.
|
|
16
16
|
*/
|
|
17
17
|
import { SENTENCE_END } from './sentences.js';
|
|
18
|
+
import { withoutTripVerb } from './trip-ask.js';
|
|
18
19
|
/** Each template twice: with the paraphrase in place of `{x}`, and without one. */
|
|
19
20
|
const TEMPLATES = [
|
|
20
21
|
['on it, looking for {x}', 'on it, looking for that now'],
|
|
@@ -301,7 +302,7 @@ export function paraphrase(text) {
|
|
|
301
302
|
}
|
|
302
303
|
for (let before = ''; before !== rest;) {
|
|
303
304
|
before = rest;
|
|
304
|
-
rest = rest.replace(LEAD, '');
|
|
305
|
+
rest = withoutTripVerb(rest.replace(LEAD, ''));
|
|
305
306
|
}
|
|
306
307
|
// `order from tacos el grullense` names the store, never `from tacos el grullense`.
|
|
307
308
|
rest = rest.replace(/^(?:from|at)\s+/, '').replace(/[\s,]+(?:please|pls|thanks|thank you|thx|ty)$/, '').replace(/[\s,.:!?]+$/, '');
|
package/dist/browser.d.ts
CHANGED
|
@@ -105,3 +105,5 @@ export interface ActionWindows {
|
|
|
105
105
|
* so the chat could neither close it nor tell when the shopper closed it.
|
|
106
106
|
*/
|
|
107
107
|
export declare function actionWindows(options?: ActionWindowsOptions): ActionWindows;
|
|
108
|
+
export { streamTurn, readTurnResponse, type StreamTurnOptions, type StreamTurnResult, type TurnResponseLike } from './turn-reader.js';
|
|
109
|
+
export { TURN_RECOVERY_ON, isTurnId, type TurnEvent, type TurnRecord } from './turn-record.js';
|
package/dist/browser.js
CHANGED
|
@@ -118,3 +118,6 @@ export function actionWindows(options = {}) {
|
|
|
118
118
|
},
|
|
119
119
|
};
|
|
120
120
|
}
|
|
121
|
+
// A chat turn read in the browser: a dropped connection reads the turn's answer back by the turn's id.
|
|
122
|
+
export { streamTurn, readTurnResponse } from './turn-reader.js';
|
|
123
|
+
export { TURN_RECOVERY_ON, isTurnId } from './turn-record.js';
|
package/dist/buy-tool.d.ts
CHANGED
|
@@ -638,6 +638,14 @@ export interface BuyToolTurn extends Omit<BuyTool, 'instantAck' | 'instantReacti
|
|
|
638
638
|
* again does nothing.
|
|
639
639
|
*/
|
|
640
640
|
end(): void;
|
|
641
|
+
/**
|
|
642
|
+
* True once a call of this turn answered `turn_stopped`: the shopper sent a newer message, and Agentcard stopped this
|
|
643
|
+
* turn for it. The newer message's turn answers the shopper, so this one is over. Do not call your model again, show
|
|
644
|
+
* no error and save no history for it: the cards it already showed stay with the shopper. The call returns to your
|
|
645
|
+
* model as any other, so check `stopped` after each call. The stopped answer goes to no `onResult` and changes nothing
|
|
646
|
+
* a later turn reads, and no wait line or 👀 follows it.
|
|
647
|
+
*/
|
|
648
|
+
readonly stopped: boolean;
|
|
641
649
|
/** The instant reply this turn sent to `onWorking` when it opened, or null when it sent none, as with a reaction. */
|
|
642
650
|
readonly ack: string | null;
|
|
643
651
|
/** The reaction this turn put on the shopper's message, `👀`, when it opened or once a call ran slow, or null while it put none or when `onReaction` threw. */
|
package/dist/buy-tool.js
CHANGED
|
@@ -130,6 +130,8 @@ const APP_TURN_MS = 120_000;
|
|
|
130
130
|
const STEP_LINK_KINDS = new Set(['vault', 'approval', 'store_login']);
|
|
131
131
|
/** The longest a step link waits for its message: an app that never writes one still sends the link. */
|
|
132
132
|
const STEP_LINK_HOLD_MS = 20_000;
|
|
133
|
+
/** The `error_code` of an answer whose turn a newer message from the same shopper stopped: that message's turn answers instead. */
|
|
134
|
+
const TURN_STOPPED = 'turn_stopped';
|
|
133
135
|
const STILL_WORKING = "Agentcard is still working on the shopper's last request. Call this tool again in a moment.";
|
|
134
136
|
const STILL_BUILDING = "The store is still building the cart for the shopper's last request. Its cart and total reach the shopper in a message from Agentcard: once that message has arrived, call this tool again with the shopper's words.";
|
|
135
137
|
const CART_NOT_READY = 'The store is still building the cart, so it has no total yet, and nothing was confirmed. Its cart and total reach the shopper in a message from Agentcard: confirm it only after the shopper says yes to that total.';
|
|
@@ -735,6 +737,15 @@ function checkoutRefusal(conversation) {
|
|
|
735
737
|
return null;
|
|
736
738
|
return { code, merchant: last.merchant_name, message: last.message };
|
|
737
739
|
}
|
|
740
|
+
/** Ends a turn (`turn.end()`, or a call it made that a newer message stopped): no wait line and no 👀 go out after it. */
|
|
741
|
+
function endTurn(state) {
|
|
742
|
+
state.ended = true;
|
|
743
|
+
state.dropWaitLine?.();
|
|
744
|
+
// The acknowledgement a call still running holds, a 👀 or a line for a slow pick, confirm or answer, is cancelled too.
|
|
745
|
+
for (const cancel of state.holds ?? [])
|
|
746
|
+
cancel();
|
|
747
|
+
state.holds?.clear();
|
|
748
|
+
}
|
|
738
749
|
/**
|
|
739
750
|
* A buy tool for one shopper. With a company client, name the shopper with
|
|
740
751
|
* `externalUserId`; with a shopper's own `accessToken`, the token names them.
|
|
@@ -2005,6 +2016,15 @@ export function buyTool(options) {
|
|
|
2005
2016
|
ack?.cancel();
|
|
2006
2017
|
const settled = plan && 'local' in plan ? plan.local : turn ? await settleTurn(turn, startedAt) : await settleRefusal(refusal, confirmSent, startedAt);
|
|
2007
2018
|
await t.ackOut;
|
|
2019
|
+
// A newer message from the shopper stopped this turn, and its own turn answers: this one ends here and says nothing
|
|
2020
|
+
// more. Its empty answer holds no cart and lists no product, so it leaves what the shopper last read, the carts and
|
|
2021
|
+
// the last ask as they were, and the app's onResult never hears it, so no cart panel empties.
|
|
2022
|
+
if (turn?.error_code === TURN_STOPPED) {
|
|
2023
|
+
endTurn(t);
|
|
2024
|
+
t.stopped = true;
|
|
2025
|
+
t.results?.push(settled);
|
|
2026
|
+
return settled;
|
|
2027
|
+
}
|
|
2008
2028
|
// The streamed messages that waited for the answer go out in order: each the answer kept as written, and a card ask or
|
|
2009
2029
|
// a link the answer replaced gives way to its ask for the step Agentcard named, once, after them. All of them go out
|
|
2010
2030
|
// before any link of the answer.
|
|
@@ -2565,7 +2585,8 @@ export function buyTool(options) {
|
|
|
2565
2585
|
return false;
|
|
2566
2586
|
throw error;
|
|
2567
2587
|
}
|
|
2568
|
-
|
|
2588
|
+
// A newer message stopped this turn, and that message's turn answers the shopper: nothing is left for the app's model.
|
|
2589
|
+
if (result.shopper_already_read_reply === true || state.stopped)
|
|
2569
2590
|
return true;
|
|
2570
2591
|
const reply = replyAsWritten(result, { textingStyle: texting });
|
|
2571
2592
|
// The reply goes out where the app hears the turn's messages: onItem or onMessage, else onText. With none of them, the
|
|
@@ -2597,14 +2618,7 @@ export function buyTool(options) {
|
|
|
2597
2618
|
enumerable: false,
|
|
2598
2619
|
},
|
|
2599
2620
|
end: {
|
|
2600
|
-
value: () =>
|
|
2601
|
-
state.ended = true;
|
|
2602
|
-
state.dropWaitLine?.();
|
|
2603
|
-
// The acknowledgement a call still running holds, a 👀 or a line for a slow pick, confirm or answer, is cancelled too.
|
|
2604
|
-
for (const cancel of state.holds ?? [])
|
|
2605
|
-
cancel();
|
|
2606
|
-
state.holds?.clear();
|
|
2607
|
-
},
|
|
2621
|
+
value: () => endTurn(state),
|
|
2608
2622
|
enumerable: false,
|
|
2609
2623
|
},
|
|
2610
2624
|
messages: { value: messagesFor, enumerable: false },
|
|
@@ -2613,7 +2627,8 @@ export function buyTool(options) {
|
|
|
2613
2627
|
links: { get: () => [...links], enumerable: false },
|
|
2614
2628
|
results: { get: () => [...results], enumerable: false },
|
|
2615
2629
|
direct: { value: direct, enumerable: false },
|
|
2616
|
-
|
|
2630
|
+
stopped: { get: () => state.stopped === true, enumerable: false },
|
|
2631
|
+
replyAsWritten: { get: () => (written && results.length > 0 && !state.stopped ? replyAsWritten(results[results.length - 1], { textingStyle: texting }) : null), enumerable: false },
|
|
2617
2632
|
items: { get: () => feed.items.map((item) => (item.kind === 'link' ? { kind: 'link', link: { ...item.link } } : { ...item })), enumerable: false },
|
|
2618
2633
|
// Each message joins the feed the moment it is cut, so a link the tool hands over during a pause never overtakes text already written.
|
|
2619
2634
|
// A step link held for this message goes out right after its last paragraph, once the stream ends.
|
package/dist/client.d.ts
CHANGED
|
@@ -50,6 +50,11 @@ export interface BuyCatalogUpdate {
|
|
|
50
50
|
found: number | null;
|
|
51
51
|
/** The products found past the cards, in the order they were found, to show on "show more" with no new search. */
|
|
52
52
|
more: BuyCatalog['items'];
|
|
53
|
+
/**
|
|
54
|
+
* False while a search of the turn is still out, such as a second flight source: more cards may join these, and a card
|
|
55
|
+
* already shown may come again with a lower price under the same `id`. True once every source answered.
|
|
56
|
+
*/
|
|
57
|
+
final: boolean;
|
|
53
58
|
}
|
|
54
59
|
/**
|
|
55
60
|
* Whether a place a card shows has room at the time the shopper asked for: `checking` while Agentcard's live search runs,
|
|
@@ -424,6 +429,19 @@ export interface BuyChoiceOption {
|
|
|
424
429
|
label: string;
|
|
425
430
|
/** What choosing it adds to the price, in cents: 0 when free, null when the store does not say. */
|
|
426
431
|
price_delta_cents: number | null;
|
|
432
|
+
/** On a `recipe_delivery` choice: the grocery store, when it arrives and what this way costs. Absent on every other choice. */
|
|
433
|
+
delivery?: BuyChoiceDelivery;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* One way a recipe's groceries can come: the DoorDash grocery store, its street when DoorDash names one, its delivery estimate in
|
|
437
|
+
* minutes (null when DoorDash shows none), the total with DoorDash's fees, and the part of that total that ships from Walmart or Amazon.
|
|
438
|
+
*/
|
|
439
|
+
export interface BuyChoiceDelivery {
|
|
440
|
+
store: string;
|
|
441
|
+
store_address: string | null;
|
|
442
|
+
eta_minutes: number | null;
|
|
443
|
+
total_cents: number;
|
|
444
|
+
shipped_cents: number;
|
|
427
445
|
}
|
|
428
446
|
/** One group of values, such as a sandwich's bread or a shirt's size. `min` and `max` count the values picked; `max` null for no limit. */
|
|
429
447
|
export interface BuyChoiceGroup {
|
|
@@ -436,7 +454,8 @@ export interface BuyChoiceGroup {
|
|
|
436
454
|
/**
|
|
437
455
|
* The choice an answer's reply asks the shopper to make, as data: the question, the item it is about, where the values come
|
|
438
456
|
* from (`menu_item`: a restaurant item's options, `store_checkout`: a store's own size or colour question, `catalog_variant`:
|
|
439
|
-
* a product's sizes or colours in stock
|
|
457
|
+
* a product's sizes or colours in stock, `recipe_delivery`: the ways a recipe's groceries can come, each option with its
|
|
458
|
+
* `delivery`), and every group with its values.
|
|
440
459
|
*/
|
|
441
460
|
export interface BuyChoice {
|
|
442
461
|
question: string | null;
|
package/dist/client.js
CHANGED
|
@@ -309,11 +309,17 @@ export function choiceOf(value) {
|
|
|
309
309
|
if (!isRecord(value) || !Array.isArray(value.groups))
|
|
310
310
|
return null;
|
|
311
311
|
const groups = value.groups.filter(isRecord).flatMap((g) => {
|
|
312
|
-
const options = (Array.isArray(g.options) ? g.options : []).filter(isRecord).flatMap((o) => str(o.label) ? [{ id: str(o.id), label: o.label.trim(), price_delta_cents: num(o.price_delta_cents) }] : []);
|
|
312
|
+
const options = (Array.isArray(g.options) ? g.options : []).filter(isRecord).flatMap((o) => str(o.label) ? [{ id: str(o.id), label: o.label.trim(), price_delta_cents: num(o.price_delta_cents), ...deliveryOf(o.delivery) }] : []);
|
|
313
313
|
return options.length ? [{ name: str(g.name) ?? '', required: g.required === true, min: num(g.min) ?? 0, max: num(g.max), options }] : [];
|
|
314
314
|
});
|
|
315
315
|
return groups.length ? { question: str(value.question), item: str(value.item), source: str(value.source) ?? '', groups } : null;
|
|
316
316
|
}
|
|
317
|
+
/** A recipe option's `delivery`, as `{ delivery }` when it names a store and a total, else nothing. */
|
|
318
|
+
function deliveryOf(value) {
|
|
319
|
+
if (!isRecord(value) || !str(value.store) || num(value.total_cents) === null)
|
|
320
|
+
return {};
|
|
321
|
+
return { delivery: { store: value.store, store_address: str(value.store_address), eta_minutes: num(value.eta_minutes), total_cents: num(value.total_cents), shipped_cents: num(value.shipped_cents) ?? 0 } };
|
|
322
|
+
}
|
|
317
323
|
/** A cart being built, as an answer, a refusal or the conversation read names it. */
|
|
318
324
|
export function cartBuildingOf(value) {
|
|
319
325
|
return isRecord(value) && str(value.store) ? { store: value.store, started_at: str(value.started_at) ?? '' } : null;
|
|
@@ -512,7 +518,7 @@ async function readStreamedTurn(res, stream, timeoutMs) {
|
|
|
512
518
|
const asOf = str(block.as_of);
|
|
513
519
|
const shown = countOf(block.shown);
|
|
514
520
|
const found = countOf(block.found);
|
|
515
|
-
const update = { conversationId: data.conversation_id, catalog, asOf, shown, found, more: catalogItemsOf(block.more) };
|
|
521
|
+
const update = { conversationId: data.conversation_id, catalog, asOf, shown, found, more: catalogItemsOf(block.more), final: block.final !== false };
|
|
516
522
|
// The count follows the cards it counts, so an app never shows "8 of 23" above no cards, and it settles before the
|
|
517
523
|
// next event, so a later count never lands before an earlier one. A card display that throws never costs the count.
|
|
518
524
|
deliver(async () => {
|
package/dist/definition.d.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export declare const BUY_TOOL_NAME = "buy";
|
|
9
9
|
/** What the model reads before it calls the tool. Every sentence is a rule the model follows. */
|
|
10
|
+
export declare const BUY_TOOL_RULES: string;
|
|
11
|
+
/** The rules as the model reads them, with travel named when src/trip-ask.ts says so. */
|
|
10
12
|
export declare const BUY_TOOL_DESCRIPTION: string;
|
|
11
13
|
/**
|
|
12
14
|
* What the model sends: `ask`, `confirm` and `new_order` every time, `product_id`, null unless the
|
package/dist/definition.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
* shopper's id are construction options, never model inputs, so a model can
|
|
6
6
|
* neither change where an order goes nor buy for someone else.
|
|
7
7
|
*/
|
|
8
|
+
import { withTravel } from './trip-ask.js';
|
|
8
9
|
export const BUY_TOOL_NAME = 'buy';
|
|
9
10
|
/** What the model reads before it calls the tool. Every sentence is a rule the model follows. */
|
|
10
|
-
export const
|
|
11
|
+
export const BUY_TOOL_RULES = [
|
|
11
12
|
'Buy what this shopper asks for at real stores.',
|
|
12
13
|
"Put the shopper's own words in `ask`.",
|
|
13
14
|
'When the shopper sends a link to a product, such as a buy.trychannel3.com link, put the whole link in `ask` exactly as they sent it, query string included, with their words beside it: Agentcard buys that exact product from the link, so never describe the link in words instead.',
|
|
@@ -65,6 +66,8 @@ export const BUY_TOOL_DESCRIPTION = [
|
|
|
65
66
|
'Ask the shopper to "let me know", never "text me", unless your app is a text-message chat.',
|
|
66
67
|
'Name only the stores and products that reach the shopper as cards in this result, never others in passing, such as "five guys and mcdonald\'s deliver there too", even when `reply` names them: to offer more, ask "want other options?". This is for what you suggest: when you show the cart or ask for a yes to it, name what is in it.',
|
|
67
68
|
].join(' ');
|
|
69
|
+
/** The rules as the model reads them, with travel named when src/trip-ask.ts says so. */
|
|
70
|
+
export const BUY_TOOL_DESCRIPTION = withTravel(BUY_TOOL_RULES);
|
|
68
71
|
/** A fresh copy of the tool's definition, so a caller that edits one never changes another. */
|
|
69
72
|
export function buyToolDefinition() {
|
|
70
73
|
return {
|
package/dist/direct.js
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
* the 188 labelled messages in `test/fixtures/direct-messages.json`, it sends none it should not.
|
|
29
29
|
*/
|
|
30
30
|
import { ABOUT, ACKNOWLEDGED, CAPABILITY, CART_COMMAND, CHECKOUT, CHITCHAT, FILLER, asksForDetails, asksForSimilar, isNewRequest, isPickText, namesStore, plain } from './ack.js';
|
|
31
|
+
import { tripAskGoesStraight } from './trip-ask.js';
|
|
31
32
|
/**
|
|
32
33
|
* A price limit put on what was just shown: `under $20`, `under 20`, `less than 15 bucks`, `between 10 and 20`, `$20 or
|
|
33
34
|
* less`, `over $50`, `cheaper ones`, `menos de 20`. Only whether the message states one: Agentcard reads the limit itself.
|
|
@@ -107,6 +108,8 @@ export function isProductAsk(text) {
|
|
|
107
108
|
return !QUESTION_START.test(bare) && !NOT_SHOPPING.test(words.replace(/\S*https?:\/\/\S+|\S*www\.\S+/g, ''));
|
|
108
109
|
if (!isNewRequest(raw) || CAPABILITY.test(words) || NOT_SHOPPING.test(words) || PAST.test(words) || CORRECTION.test(words) || REFERS.test(words) || COMPLAINT.test(words))
|
|
109
110
|
return false;
|
|
111
|
+
if (tripAskGoesStraight(raw, bare))
|
|
112
|
+
return true;
|
|
110
113
|
// A question goes to the model, unless it asks Agentcard to get something: `can you find me usb-c cables?`.
|
|
111
114
|
const framed = SHOP_FRAME.exec(bare);
|
|
112
115
|
if (/\?/.test(raw) && !(framed && /^(?:can|could|would|will) (?:you|u)\b/.test(bare)))
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { readPurchaseMessage, type PurchaseMessage, type PurchaseMessageKind, ty
|
|
|
3
3
|
export { readShopperMessage, isStale, SHOPPER_EVENT_TYPES, NEXT_STEP_KINDS, type NextStepKind, type ShopperMessage, type ShopperMessageKind, type ShopperFacts, type ShopperEventType, type OrderStatus, } from './shopper-message.js';
|
|
4
4
|
export { ORDER_STEPS, updateOrder, arrivalText, type ShopperOrder, type OrderStep, type OrderPathStep, type OrderStepState, type ArrivalTextOptions, } from './order.js';
|
|
5
5
|
export { agentcardWebhook, purchaseAgentWebhook, type AgentcardWebhookOptions, type AgentcardWebhookHandler, type PurchaseAgentWebhookOptions, type WebhookFetchRequest, type WebhookRequest, type WebhookResponse, } from './handler.js';
|
|
6
|
-
export { AgentcardClient, AgentcardApiError, BUY_TURN_TIMEOUT_MS, DEFAULT_BASE_URL, type AgentcardClientOptions, type AgentcardTraceOptions, type OtelApi, type TraceContext, type FetchLike, type FetchLikeResponse, type BuyProgress, type BuyProgressStage, type BuyCatalogUpdate, type BuyAvailability, type BuyAvailabilityUpdate, type BuyFoundUpdate, type BuyTurnStatus, type BuySegmentUpdate, type BuyCartUpdate, type BuyDeltaUpdate, type BuyStreamHandlers, type Shopper, type BuyLastAnswer, type BuyRequest, type BuyDeliveryAddress, type BuyTurn, type BuyStatus, type BuyCart, type BuyCartBuilding, type BuyCartLine, type BuyCartFeeLine, type BuyStore, type BuyCatalog, type BuyCatalogItem, type BuyFlightItinerary, type BuyPaymentSource, type BuyConversation, type BuyLastCheckout, type BuyOrder, type VaultLink, type BuyNextAction, type BuyPick, type BuyStoreChoice, type BuyStorePick, type BuyStores, type BuyChoice, type BuyChoiceGroup, type BuyChoiceOption, } from './client.js';
|
|
6
|
+
export { AgentcardClient, AgentcardApiError, BUY_TURN_TIMEOUT_MS, DEFAULT_BASE_URL, type AgentcardClientOptions, type AgentcardTraceOptions, type OtelApi, type TraceContext, type FetchLike, type FetchLikeResponse, type BuyProgress, type BuyProgressStage, type BuyCatalogUpdate, type BuyAvailability, type BuyAvailabilityUpdate, type BuyFoundUpdate, type BuyTurnStatus, type BuySegmentUpdate, type BuyCartUpdate, type BuyDeltaUpdate, type BuyStreamHandlers, type Shopper, type BuyLastAnswer, type BuyRequest, type BuyDeliveryAddress, type BuyTurn, type BuyStatus, type BuyCart, type BuyCartBuilding, type BuyCartLine, type BuyCartFeeLine, type BuyStore, type BuyCatalog, type BuyCatalogItem, type BuyFlightItinerary, type BuyPaymentSource, type BuyConversation, type BuyLastCheckout, type BuyOrder, type VaultLink, type BuyNextAction, type BuyPick, type BuyStoreChoice, type BuyStorePick, type BuyStores, type BuyChoice, type BuyChoiceGroup, type BuyChoiceDelivery, type BuyChoiceOption, } from './client.js';
|
|
7
7
|
export { BUY_TOOL_NAME, BUY_TOOL_DESCRIPTION, buyToolDefinition, parseBuyToolInput, type BuyToolDefinition, type BuyToolInput, type BuyToolInputSchema, type BuyToolInputCheck, type BuyToolStandardSchema, type OpenAIBuyTool, } from './definition.js';
|
|
8
8
|
export { toMessages, messageStream, typingDelay, type MessagePace, type MessageStream, type MessageStreamOptions, } from './messages.js';
|
|
9
9
|
export { buyTool, nextStepPrompt, type BuyTool, type BuyToolOptions, type BuyToolResult, type BuyToolStatus, type BuyToolLink, type BuyToolFound, type BuyToolAvailability, type BuyToolProduct, type BuyToolProductAction, productAction, type BuyToolStore, type BuyToolTurn, type BuyToolTurnItem, type BuyToolTurnOptions, type BuyToolTurnMessage, type BuyAckMode, } from './buy-tool.js';
|
|
@@ -15,3 +15,5 @@ export { toAnthropicTool, toOpenRouterTool, type AnthropicBuyTool, type OpenRout
|
|
|
15
15
|
export { listenToAgentcard, type AgentcardListener, type ListenOptions, type ListenCursorStore, type StreamFetch, } from './listen.js';
|
|
16
16
|
export { ACTION_LINK_ENDINGS, ACTION_LINK_KINDS, actionLinkId, actionLinkOutcome, isActionLink, type ActionLinkKind, type ActionLinkMessage, type ActionLinkOutcome, } from './action-links.js';
|
|
17
17
|
export { AGENTCARD_EVENT_TYPES, type AgentcardEventType, } from './events.js';
|
|
18
|
+
export { turnStream, readTurn, TURN_RECORD_TTL_SECONDS, type TurnStream, type TurnStreamOptions } from './turn-stream.js';
|
|
19
|
+
export { TURN_RECOVERY_ON, isTurnId, type TurnEvent, type TurnRecord, type TurnRecordStore } from './turn-record.js';
|
package/dist/index.js
CHANGED
|
@@ -15,3 +15,5 @@ export { toAnthropicTool, toOpenRouterTool, } from './adapters.js';
|
|
|
15
15
|
export { listenToAgentcard, } from './listen.js';
|
|
16
16
|
export { ACTION_LINK_ENDINGS, ACTION_LINK_KINDS, actionLinkId, actionLinkOutcome, isActionLink, } from './action-links.js';
|
|
17
17
|
export { AGENTCARD_EVENT_TYPES, } from './events.js';
|
|
18
|
+
export { turnStream, readTurn, TURN_RECORD_TTL_SECONDS } from './turn-stream.js';
|
|
19
|
+
export { TURN_RECOVERY_ON, isTurnId } from './turn-record.js';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trip asks and the tool's travel wording, kept out of direct.ts, ack.ts and definition.ts, which each call in here once.
|
|
3
|
+
*
|
|
4
|
+
* On 2026-10-28 on chat.opencommerce.sh, "help me plan a trip to Loreto" never reached Agentcard: `directCall` read no
|
|
5
|
+
* shopping verb, and the app's model, whose capability rule named stores and restaurants and no travel, answered "i can't
|
|
6
|
+
* plan itineraries" and offered no flight or hotel. Both switches below ship off and change nothing until a later change
|
|
7
|
+
* turns them on; a test turns them on by setting the field.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* `goStraight` on: a trip, flights or a hotel with the place they are for, `help me plan a trip to Loreto`, `flights to
|
|
11
|
+
* Loreto`, `flights and hotels in loreto` or `a hotel in Chicago next week`, goes straight to Agentcard, which asks for the
|
|
12
|
+
* airport and the dates it needs, and the instant reply reads the trip back without the verb (`a trip to loreto`). Off: such
|
|
13
|
+
* an ask goes straight only with a shopping verb (`book a flight to Loreto`), as before.
|
|
14
|
+
*
|
|
15
|
+
* `inCapabilities` on: the tool's description says it plans and books trips, flights and hotels, tells the model to call it
|
|
16
|
+
* for a trip ask with no dates or airport, and names flights and hotels when the shopper asks what it can do. Off: the
|
|
17
|
+
* description is the text it was before, word for word.
|
|
18
|
+
*/
|
|
19
|
+
export declare const TRAVEL: {
|
|
20
|
+
goStraight: boolean;
|
|
21
|
+
inCapabilities: boolean;
|
|
22
|
+
};
|
|
23
|
+
/** True when the message's words, openings taken off, ask for a trip, flights or a hotel and name the place. */
|
|
24
|
+
export declare function isTripAsk(bare: string): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Whether a message that passed `isProductAsk`'s checks for small talk, the account and a story of what happened goes straight
|
|
27
|
+
* as a trip ask: a question goes only when it asks Agentcard to plan it (`can you help me plan a trip to italy?`).
|
|
28
|
+
*/
|
|
29
|
+
export declare function tripAskGoesStraight(raw: string, bare: string): boolean;
|
|
30
|
+
/** The read-back without the verb that asked for the trip: `plan a trip to loreto` reads back `a trip to loreto`. Any other words, `plan b emergency contraception` too, read back as they are. */
|
|
31
|
+
export declare function withoutTripVerb(text: string): string;
|
|
32
|
+
/** The tool's description with travel named, when `inCapabilities` is on (or `on` says so); the description as given when off. */
|
|
33
|
+
export declare function withTravel(description: string, on?: boolean): string;
|
package/dist/trip-ask.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trip asks and the tool's travel wording, kept out of direct.ts, ack.ts and definition.ts, which each call in here once.
|
|
3
|
+
*
|
|
4
|
+
* On 2026-10-28 on chat.opencommerce.sh, "help me plan a trip to Loreto" never reached Agentcard: `directCall` read no
|
|
5
|
+
* shopping verb, and the app's model, whose capability rule named stores and restaurants and no travel, answered "i can't
|
|
6
|
+
* plan itineraries" and offered no flight or hotel. Both switches below ship off and change nothing until a later change
|
|
7
|
+
* turns them on; a test turns them on by setting the field.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* `goStraight` on: a trip, flights or a hotel with the place they are for, `help me plan a trip to Loreto`, `flights to
|
|
11
|
+
* Loreto`, `flights and hotels in loreto` or `a hotel in Chicago next week`, goes straight to Agentcard, which asks for the
|
|
12
|
+
* airport and the dates it needs, and the instant reply reads the trip back without the verb (`a trip to loreto`). Off: such
|
|
13
|
+
* an ask goes straight only with a shopping verb (`book a flight to Loreto`), as before.
|
|
14
|
+
*
|
|
15
|
+
* `inCapabilities` on: the tool's description says it plans and books trips, flights and hotels, tells the model to call it
|
|
16
|
+
* for a trip ask with no dates or airport, and names flights and hotels when the shopper asks what it can do. Off: the
|
|
17
|
+
* description is the text it was before, word for word.
|
|
18
|
+
*/
|
|
19
|
+
export const TRAVEL = { goStraight: true, inCapabilities: true };
|
|
20
|
+
/** What a trip ask opens with before the trip: `can you help me plan`, `i want to book`, `let's plan`, `plan`. */
|
|
21
|
+
const TRIP_LEAD = "(?:(?:(?:can|could|would|will) (?:you|u) |please |i'?d like (?:you )?to |i want to |i need to |we want to |we need to |let'?s |lets )?(?:help (?:me|us) )?(?:plan|book|organi[sz]e|arrange|find|search for|look for)(?: (?:me|us))? )?";
|
|
22
|
+
/** The trip itself: a trip, a vacation, flights, a hotel, or flights and a hotel together. */
|
|
23
|
+
const TRIP_THING = '(?:(?:a|an|some|the|cheap|cheapest|good) )?(?:(?:(?:weekend|family|beach|ski|honeymoon|birthday|anniversary|business|work|quick|short|long|girls|guys) )?(?:trip|vacation|getaway|holiday)|(?:flights?|hotels?|hotel rooms?|places? to stay)(?: (?:and|&|\\+) (?:a |some )?(?:flights?|hotels?|hotel rooms?|places? to stay))?)';
|
|
24
|
+
/** When the trip is, after its place: `next week`, `this weekend`, `in december`, `on nov 3`, `for 5 days`. */
|
|
25
|
+
const MONTH = '(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)';
|
|
26
|
+
const NUMBER = '(?:a|an|one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2})';
|
|
27
|
+
const WHEN = `(?: (?:next|this) (?:week|weekend|month|year|summer|winter|spring|fall)| tomorrow| tonight| in ${MONTH}| in ${NUMBER} (?:days?|weeks?|months?)| on ${MONTH} \\d{1,2}(?:st|nd|rd|th)?| ${MONTH} \\d{1,2}(?:st|nd|rd|th)?(?: ?- ?\\d{1,2})?| for ${NUMBER} (?:days?|nights?|weeks?)| over (?:thanksgiving|christmas|new year'?s|the holidays|spring break))*`;
|
|
28
|
+
/** A trip with where it goes: one to three words of place, then only words of when. */
|
|
29
|
+
const TRIP_ASK = new RegExp(`^${TRIP_LEAD}${TRIP_THING} (?:to|in|at|near|for|around) (\\p{L}[\\p{L}'.-]*(?: \\p{L}[\\p{L}'.-]*){0,2}?)${WHEN}$`, 'u');
|
|
30
|
+
/** Words that make the place a sentence about a trip already booked or a price: `my flight to jfk is delayed`, `flights to cancun cost a fortune`. */
|
|
31
|
+
const TRIP_TOLD = /\b(?:is|are|was|were|be|been|got|gets|get|delayed|cancell?ed|booked|landed|left|leaves|leaving|late|cheaper|cheap|expensive|pricey|cost|costs|price|prices|worth|good|bad|ok|okay|fine|over|done|sucks?|suck|lol|sounds?|seems?|looks?)\b/;
|
|
32
|
+
/** Places close to home that a trip word can name and no flight or hotel goes to: `a trip to the store`, `a trip to walmart`, `a trip to target.com`. */
|
|
33
|
+
const NOT_A_TRIP_PLACE = /^(?:the (?:store|shop|mall|grocery store|supermarket|gym|doctor|dentist|bank|vet|post office|office|pharmacy|market)|work|school|bed|me|us|you|my|our|it|this|that|walmart|target|costco|best ?buy|home depot|lowe'?s|trader joe'?s|whole foods|safeway|kroger|cvs|walgreens|ikea|aldi|publix|sam'?s club|amazon)\b|\.(?:com|co|net|org|shop|store|us|uk|ca|io)\b/;
|
|
34
|
+
/** The verb a trip ask opens with, read off before the trip reads back. */
|
|
35
|
+
const TRIP_VERB = /^(?:plan|organi[sz]e|arrange)\b[\s,]*/;
|
|
36
|
+
/** True when the message's words, openings taken off, ask for a trip, flights or a hotel and name the place. */
|
|
37
|
+
export function isTripAsk(bare) {
|
|
38
|
+
const match = TRIP_ASK.exec(bare.replace(/\s*\?+$/, ''));
|
|
39
|
+
return match !== null && !TRIP_TOLD.test(match[1]) && !NOT_A_TRIP_PLACE.test(match[1]);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Whether a message that passed `isProductAsk`'s checks for small talk, the account and a story of what happened goes straight
|
|
43
|
+
* as a trip ask: a question goes only when it asks Agentcard to plan it (`can you help me plan a trip to italy?`).
|
|
44
|
+
*/
|
|
45
|
+
export function tripAskGoesStraight(raw, bare) {
|
|
46
|
+
if (!TRAVEL.goStraight || !isTripAsk(bare))
|
|
47
|
+
return false;
|
|
48
|
+
return !/\?/.test(raw) || /^(?:can|could|would|will) (?:you|u)\b/.test(bare);
|
|
49
|
+
}
|
|
50
|
+
/** The read-back without the verb that asked for the trip: `plan a trip to loreto` reads back `a trip to loreto`. Any other words, `plan b emergency contraception` too, read back as they are. */
|
|
51
|
+
export function withoutTripVerb(text) {
|
|
52
|
+
return TRAVEL.goStraight && isTripAsk(text) ? text.replace(TRIP_VERB, '') : text;
|
|
53
|
+
}
|
|
54
|
+
const OPENING_LINE = 'Buy what this shopper asks for at real stores.';
|
|
55
|
+
const TRAVEL_LINES = 'You also plan and book trips: flights and hotels. When the shopper asks to plan a trip, or for flights or a hotel, such as "help me plan a trip to Loreto" or "flights and hotels in loreto", call this tool with their words, even when they name no dates and no place they leave from: Agentcard asks them for what it needs.';
|
|
56
|
+
const CAPABILITY_END = 'so name those, and no other store unless a result showed it.';
|
|
57
|
+
const CAPABILITY_TRAVEL = 'Name flights and hotels for a trip among the kinds of things you can do.';
|
|
58
|
+
/** The tool's description with travel named, when `inCapabilities` is on (or `on` says so); the description as given when off. */
|
|
59
|
+
export function withTravel(description, on = TRAVEL.inCapabilities) {
|
|
60
|
+
if (!on)
|
|
61
|
+
return description;
|
|
62
|
+
return description.replace(OPENING_LINE, `${OPENING_LINE} ${TRAVEL_LINES}`).replace(CAPABILITY_END, `${CAPABILITY_END} ${CAPABILITY_TRAVEL}`);
|
|
63
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `streamTurn` sends the shopper's message and reads the turn's server-sent events in the browser. When the connection
|
|
3
|
+
* drops before the turn's last event, or before the first one, it reads the turn's record by its id from your server
|
|
4
|
+
* (`readTurn` behind a route of yours) and hands over each event the stream did not, so the shopper gets the answer.
|
|
5
|
+
* A 409 that names the turn already running for this shopper (`turn_id`) waits for that turn's answer the same way.
|
|
6
|
+
*/
|
|
7
|
+
import { type TurnRecord } from './turn-record.js';
|
|
8
|
+
/** The part of a fetch `Response` the reader uses. */
|
|
9
|
+
export interface TurnResponseLike {
|
|
10
|
+
ok: boolean;
|
|
11
|
+
status: number;
|
|
12
|
+
body: ReadableStream<Uint8Array> | null;
|
|
13
|
+
text(): Promise<string>;
|
|
14
|
+
}
|
|
15
|
+
export interface StreamTurnOptions {
|
|
16
|
+
/** Sends the shopper's message with the turn's id, such as in an `x-turn-id` header, and returns the response. */
|
|
17
|
+
start(turnId: string): Promise<TurnResponseLike>;
|
|
18
|
+
/** Reads the turn's record from your server, or null while it has none. `readTurn` answers it there. */
|
|
19
|
+
read(turnId: string): Promise<TurnRecord | null>;
|
|
20
|
+
/** Hears each event once, in the order the turn sent them, whether the stream or the record carried it. */
|
|
21
|
+
onEvent(event: string, data: unknown): void;
|
|
22
|
+
/** The turn's id. Defaults to a new random one. */
|
|
23
|
+
turnId?: string;
|
|
24
|
+
/** How often the record is read after a drop, in milliseconds. Defaults to 1,500. */
|
|
25
|
+
pollMs?: number;
|
|
26
|
+
/** How long a record that never appears is waited for before the drop counts as the error, in milliseconds. Defaults to 15,000. */
|
|
27
|
+
startWaitMs?: number;
|
|
28
|
+
/** How long a turn's record is read before giving up, in milliseconds. Defaults to 300,000. */
|
|
29
|
+
waitMs?: number;
|
|
30
|
+
/** Whether a drop reads the record. Defaults to `TURN_RECOVERY_ON`. */
|
|
31
|
+
recover?: boolean;
|
|
32
|
+
/** Stops reading the record once it aborts, as the abort of your own fetch stops the stream. */
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}
|
|
35
|
+
export interface StreamTurnResult {
|
|
36
|
+
/** The id of the turn whose events were heard: the running turn's after a 409 that named one. */
|
|
37
|
+
turnId: string;
|
|
38
|
+
/** True when some of the events came from the record, after a drop or a 409. */
|
|
39
|
+
recovered: boolean;
|
|
40
|
+
/** The response, when the server refused the message and no turn's answer was waited for: read its error from it. */
|
|
41
|
+
refused?: TurnResponseLike;
|
|
42
|
+
}
|
|
43
|
+
export declare function streamTurn(options: StreamTurnOptions): Promise<StreamTurnResult>;
|
|
44
|
+
/** The record your server's route answers, read back: a helper for `read`, such as `(id) => fetch(...).then(readTurnResponse)`. */
|
|
45
|
+
export declare function readTurnResponse(response: TurnResponseLike): Promise<TurnRecord | null>;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `streamTurn` sends the shopper's message and reads the turn's server-sent events in the browser. When the connection
|
|
3
|
+
* drops before the turn's last event, or before the first one, it reads the turn's record by its id from your server
|
|
4
|
+
* (`readTurn` behind a route of yours) and hands over each event the stream did not, so the shopper gets the answer.
|
|
5
|
+
* A 409 that names the turn already running for this shopper (`turn_id`) waits for that turn's answer the same way.
|
|
6
|
+
*/
|
|
7
|
+
import { TURN_RECOVERY_ON, isTurnId, parseTurnRecord } from './turn-record.js';
|
|
8
|
+
const TERMINAL = new Set(['done', 'error']);
|
|
9
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
10
|
+
function newTurnId() {
|
|
11
|
+
const c = globalThis.crypto;
|
|
12
|
+
return c?.randomUUID?.() ?? `turn_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
|
|
13
|
+
}
|
|
14
|
+
export async function streamTurn(options) {
|
|
15
|
+
const recover = options.recover ?? TURN_RECOVERY_ON;
|
|
16
|
+
let turnId = options.turnId ?? newTurnId();
|
|
17
|
+
let heard = 0;
|
|
18
|
+
let ended = false;
|
|
19
|
+
// An error your `onEvent` throws is yours: it ends the read, and the record is not read in its place.
|
|
20
|
+
let appFailed = null;
|
|
21
|
+
const hear = (event, data) => {
|
|
22
|
+
heard++;
|
|
23
|
+
if (TERMINAL.has(event))
|
|
24
|
+
ended = true;
|
|
25
|
+
try {
|
|
26
|
+
options.onEvent(event, data);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
appFailed = { error };
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
// A drop reads the record unless recovery is off, the turn already ended, the app's own code threw or the app aborted.
|
|
34
|
+
const recovers = (error) => recover && !ended && !appFailed && !options.signal?.aborted && error?.name !== 'AbortError';
|
|
35
|
+
// Reads the record until it holds the turn's last event, handing over what the stream had not.
|
|
36
|
+
const fromRecord = async (cause) => {
|
|
37
|
+
const startWaitMs = options.startWaitMs ?? 15_000;
|
|
38
|
+
const waitMs = options.waitMs ?? 300_000;
|
|
39
|
+
const began = Date.now();
|
|
40
|
+
let seen = false;
|
|
41
|
+
const stopIfAborted = () => {
|
|
42
|
+
if (options.signal?.aborted)
|
|
43
|
+
throw options.signal.reason ?? cause;
|
|
44
|
+
};
|
|
45
|
+
for (;;) {
|
|
46
|
+
stopIfAborted();
|
|
47
|
+
// A read that hangs counts as no record once the limit it waits under passes.
|
|
48
|
+
const left = Math.max(0, (seen ? waitMs : Math.min(startWaitMs, waitMs)) - (Date.now() - began));
|
|
49
|
+
const record = await withDeadline(Promise.resolve().then(() => options.read(turnId)), left, options.signal);
|
|
50
|
+
stopIfAborted();
|
|
51
|
+
if (record) {
|
|
52
|
+
seen = true;
|
|
53
|
+
for (const { event, data } of record.events.slice(heard))
|
|
54
|
+
hear(event, data);
|
|
55
|
+
if (record.done || ended)
|
|
56
|
+
return { turnId, recovered: true };
|
|
57
|
+
}
|
|
58
|
+
const waited = Date.now() - began;
|
|
59
|
+
if ((!seen && waited >= startWaitMs) || waited >= waitMs)
|
|
60
|
+
throw cause;
|
|
61
|
+
await sleep(options.pollMs ?? 1_500);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
let response;
|
|
65
|
+
try {
|
|
66
|
+
response = await options.start(turnId);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (!recovers(error))
|
|
70
|
+
throw error;
|
|
71
|
+
return fromRecord(error);
|
|
72
|
+
}
|
|
73
|
+
if (!response.ok || !response.body) {
|
|
74
|
+
if (recover && response.status === 409) {
|
|
75
|
+
const text = await response.text().catch(() => '');
|
|
76
|
+
const running = parseJson(text)?.turn_id;
|
|
77
|
+
if (isTurnId(running)) {
|
|
78
|
+
turnId = running;
|
|
79
|
+
return fromRecord(new Error(`The chat answered ${response.status}.`));
|
|
80
|
+
}
|
|
81
|
+
return { turnId, recovered: false, refused: { ok: response.ok, status: response.status, body: null, text: async () => text } };
|
|
82
|
+
}
|
|
83
|
+
return { turnId, recovered: false, refused: response };
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const reader = response.body.getReader();
|
|
87
|
+
const decoder = new TextDecoder();
|
|
88
|
+
let buffer = '';
|
|
89
|
+
for (;;) {
|
|
90
|
+
const { value, done } = await reader.read();
|
|
91
|
+
if (done)
|
|
92
|
+
break;
|
|
93
|
+
buffer += decoder.decode(value, { stream: true });
|
|
94
|
+
let end;
|
|
95
|
+
while ((end = buffer.indexOf('\n\n')) !== -1) {
|
|
96
|
+
const frame = buffer.slice(0, end);
|
|
97
|
+
buffer = buffer.slice(end + 2);
|
|
98
|
+
const event = /^event: (.*)$/m.exec(frame)?.[1];
|
|
99
|
+
const data = /^data: (.*)$/m.exec(frame)?.[1];
|
|
100
|
+
if (event && data !== undefined)
|
|
101
|
+
hear(event, JSON.parse(data));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (ended || !recover)
|
|
105
|
+
return { turnId, recovered: false };
|
|
106
|
+
return fromRecord(new Error('The chat stream ended before the turn did.'));
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (ended && !appFailed)
|
|
110
|
+
return { turnId, recovered: false };
|
|
111
|
+
if (!recovers(error))
|
|
112
|
+
throw error;
|
|
113
|
+
return fromRecord(error);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** The read's record, or null when it fails, has not answered within `ms`, or the app aborts first. */
|
|
117
|
+
function withDeadline(read, ms, signal) {
|
|
118
|
+
let timer;
|
|
119
|
+
let stop;
|
|
120
|
+
const late = new Promise((resolve) => {
|
|
121
|
+
timer = setTimeout(() => resolve(null), ms);
|
|
122
|
+
stop = () => resolve(null);
|
|
123
|
+
if (signal?.aborted)
|
|
124
|
+
resolve(null);
|
|
125
|
+
else
|
|
126
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
127
|
+
});
|
|
128
|
+
return Promise.race([read.catch(() => null), late]).finally(() => {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
if (stop)
|
|
131
|
+
signal?.removeEventListener('abort', stop);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** A JSON body read leniently: null when it is not JSON. */
|
|
135
|
+
function parseJson(text) {
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(text);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** The record your server's route answers, read back: a helper for `read`, such as `(id) => fetch(...).then(readTurnResponse)`. */
|
|
144
|
+
export async function readTurnResponse(response) {
|
|
145
|
+
if (!response.ok)
|
|
146
|
+
return null;
|
|
147
|
+
return parseTurnRecord(await response.text());
|
|
148
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A turn's record: every event a chat turn sent the shopper's browser, in order, kept under the turn's id in a store
|
|
3
|
+
* the app provides, so a browser whose connection dropped reads the turn's answer back instead of losing it.
|
|
4
|
+
* This file imports nothing, so the server helper (`turnStream`) and the browser reader (`streamTurn`) share it.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Whether a turn keeps its record and a dropped stream reads it back. Off until the pull request that turns it on:
|
|
8
|
+
* while it is off, `turnStream` streams without saving and `streamTurn` reports a drop as the error it was.
|
|
9
|
+
*/
|
|
10
|
+
export declare const TURN_RECOVERY_ON: boolean;
|
|
11
|
+
/** One event of a turn, as its server-sent frame carries it: `event: <event>` and `data: <JSON of data>`. */
|
|
12
|
+
export interface TurnEvent {
|
|
13
|
+
event: string;
|
|
14
|
+
data: unknown;
|
|
15
|
+
}
|
|
16
|
+
/** What a turn sent so far, and whether it ended: `done` is true once the turn's last event is in `events`. */
|
|
17
|
+
export interface TurnRecord {
|
|
18
|
+
events: TurnEvent[];
|
|
19
|
+
done: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** Where a turn's record lives between instances, such as Redis: the same shape as the listener's cursor store. */
|
|
22
|
+
export interface TurnRecordStore {
|
|
23
|
+
/** The record saved last under `key`, or null when none was saved or it expired. */
|
|
24
|
+
load(key: string): Promise<string | null> | string | null;
|
|
25
|
+
/** Saves the record under `key`, to be kept for `ttlSeconds`. */
|
|
26
|
+
save(key: string, record: string, ttlSeconds: number): Promise<void> | void;
|
|
27
|
+
}
|
|
28
|
+
/** A turn id the browser makes up front: 8 to 64 letters, digits, `-` or `_`. Check one before using it in a key. */
|
|
29
|
+
export declare function isTurnId(value: unknown): value is string;
|
|
30
|
+
/** A stored record read back, or null when the text is not one. */
|
|
31
|
+
export declare function parseTurnRecord(text: string | null | undefined): TurnRecord | null;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A turn's record: every event a chat turn sent the shopper's browser, in order, kept under the turn's id in a store
|
|
3
|
+
* the app provides, so a browser whose connection dropped reads the turn's answer back instead of losing it.
|
|
4
|
+
* This file imports nothing, so the server helper (`turnStream`) and the browser reader (`streamTurn`) share it.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Whether a turn keeps its record and a dropped stream reads it back. Off until the pull request that turns it on:
|
|
8
|
+
* while it is off, `turnStream` streams without saving and `streamTurn` reports a drop as the error it was.
|
|
9
|
+
*/
|
|
10
|
+
export const TURN_RECOVERY_ON = false;
|
|
11
|
+
/** A turn id the browser makes up front: 8 to 64 letters, digits, `-` or `_`. Check one before using it in a key. */
|
|
12
|
+
export function isTurnId(value) {
|
|
13
|
+
return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value);
|
|
14
|
+
}
|
|
15
|
+
/** A stored record read back, or null when the text is not one. */
|
|
16
|
+
export function parseTurnRecord(text) {
|
|
17
|
+
if (typeof text !== 'string')
|
|
18
|
+
return null;
|
|
19
|
+
try {
|
|
20
|
+
const record = JSON.parse(text);
|
|
21
|
+
return Array.isArray(record.events) ? { events: record.events, done: record.done === true } : null;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `turnStream` serves one chat turn to the shopper's browser as server-sent events and keeps every event it sends in the
|
|
3
|
+
* app's store under the turn's id. The turn runs to its end whether or not the browser is still there: an event the
|
|
4
|
+
* stream can no longer carry still goes in the record, and `finished` resolves once the record holds the turn's last
|
|
5
|
+
* event. Hand `finished` to your host's `waitUntil` so a serverless function is not stopped before then.
|
|
6
|
+
* `readTurn` hands the record back to the browser's reader (`streamTurn` in `@agent-cards/commerce-sdk/browser`).
|
|
7
|
+
*/
|
|
8
|
+
import { type TurnRecord, type TurnRecordStore } from './turn-record.js';
|
|
9
|
+
/** How long a record is kept by default: ten minutes, past the longest turn a chat waits on. */
|
|
10
|
+
export declare const TURN_RECORD_TTL_SECONDS = 600;
|
|
11
|
+
export interface TurnStreamOptions {
|
|
12
|
+
/** Where the record lives. */
|
|
13
|
+
store: TurnRecordStore;
|
|
14
|
+
/** The record's key: the turn's id together with your shopper's id, so one shopper never reads another's turn. */
|
|
15
|
+
key: string;
|
|
16
|
+
/**
|
|
17
|
+
* Runs the turn. Call `send` for each event the browser shows, the last one included (such as `done` or `error`).
|
|
18
|
+
* A turn that throws ends with an `error` event carrying the message in `failedText`.
|
|
19
|
+
*/
|
|
20
|
+
run(send: (event: string, data: unknown) => void): Promise<void>;
|
|
21
|
+
/** How long the record is kept, in seconds. Defaults to `TURN_RECORD_TTL_SECONDS`. */
|
|
22
|
+
ttlSeconds?: number;
|
|
23
|
+
/** The text of the `error` event a turn that throws ends with. */
|
|
24
|
+
failedText?: string;
|
|
25
|
+
/** Whether to keep the record. Defaults to `TURN_RECOVERY_ON`. */
|
|
26
|
+
recover?: boolean;
|
|
27
|
+
/** Hears each save the store refused: the record then misses events until a later save lands. Log it here. */
|
|
28
|
+
onSaveError?: (error: unknown) => void;
|
|
29
|
+
}
|
|
30
|
+
export interface TurnStream {
|
|
31
|
+
/** The body of the response: `text/event-stream`. */
|
|
32
|
+
stream: ReadableStream<Uint8Array>;
|
|
33
|
+
/** Resolves once the turn ended and its record is saved. It never rejects. */
|
|
34
|
+
finished: Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
export declare function turnStream(options: TurnStreamOptions): TurnStream;
|
|
37
|
+
/** The turn's record under `key`, or null when the store has none, for the browser's reader to pick up where its stream stopped. */
|
|
38
|
+
export declare function readTurn(store: TurnRecordStore, key: string): Promise<TurnRecord | null>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `turnStream` serves one chat turn to the shopper's browser as server-sent events and keeps every event it sends in the
|
|
3
|
+
* app's store under the turn's id. The turn runs to its end whether or not the browser is still there: an event the
|
|
4
|
+
* stream can no longer carry still goes in the record, and `finished` resolves once the record holds the turn's last
|
|
5
|
+
* event. Hand `finished` to your host's `waitUntil` so a serverless function is not stopped before then.
|
|
6
|
+
* `readTurn` hands the record back to the browser's reader (`streamTurn` in `@agent-cards/commerce-sdk/browser`).
|
|
7
|
+
*/
|
|
8
|
+
import { TURN_RECOVERY_ON, parseTurnRecord } from './turn-record.js';
|
|
9
|
+
/** How long a record is kept by default: ten minutes, past the longest turn a chat waits on. */
|
|
10
|
+
export const TURN_RECORD_TTL_SECONDS = 600;
|
|
11
|
+
export function turnStream(options) {
|
|
12
|
+
const recover = options.recover ?? TURN_RECOVERY_ON;
|
|
13
|
+
const ttl = options.ttlSeconds ?? TURN_RECORD_TTL_SECONDS;
|
|
14
|
+
const encoder = new TextEncoder();
|
|
15
|
+
const record = { events: [], done: false };
|
|
16
|
+
let controller = null;
|
|
17
|
+
let gone = false;
|
|
18
|
+
// Saves run one after another, so a slow early save never lands over a later one.
|
|
19
|
+
let saving = Promise.resolve();
|
|
20
|
+
const save = () => {
|
|
21
|
+
if (!recover)
|
|
22
|
+
return;
|
|
23
|
+
const text = JSON.stringify(record);
|
|
24
|
+
saving = saving
|
|
25
|
+
.then(() => options.store.save(options.key, text, ttl))
|
|
26
|
+
.catch((error) => {
|
|
27
|
+
try {
|
|
28
|
+
options.onSaveError?.(error);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
/* the app's logging failing never stops the turn */
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
// Each event is written to JSON once, before it is kept: a value JSON cannot hold throws here, to the turn, and the
|
|
36
|
+
// record keeps a copy, so a later change to the caller's object never rewrites what the shopper was sent.
|
|
37
|
+
const send = (event, data) => {
|
|
38
|
+
if (record.done)
|
|
39
|
+
return;
|
|
40
|
+
const json = JSON.stringify(data) ?? 'null';
|
|
41
|
+
const entry = { event, data: JSON.parse(json) };
|
|
42
|
+
record.events.push(entry);
|
|
43
|
+
save();
|
|
44
|
+
if (gone || !controller)
|
|
45
|
+
return;
|
|
46
|
+
try {
|
|
47
|
+
controller.enqueue(encoder.encode(`event: ${event}\ndata: ${json}\n\n`));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// The browser left: the record still takes every event.
|
|
51
|
+
gone = true;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
let started;
|
|
55
|
+
const ready = new Promise((resolve) => (started = resolve));
|
|
56
|
+
const stream = new ReadableStream({
|
|
57
|
+
start(c) {
|
|
58
|
+
controller = c;
|
|
59
|
+
started();
|
|
60
|
+
},
|
|
61
|
+
cancel() {
|
|
62
|
+
gone = true;
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
const finished = (async () => {
|
|
66
|
+
await ready;
|
|
67
|
+
save();
|
|
68
|
+
try {
|
|
69
|
+
await options.run(send);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
send('error', { error: options.failedText ?? 'The turn could not finish.' });
|
|
73
|
+
}
|
|
74
|
+
record.done = true;
|
|
75
|
+
save();
|
|
76
|
+
await saving;
|
|
77
|
+
if (!gone) {
|
|
78
|
+
try {
|
|
79
|
+
controller?.close();
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
/* already closed */
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
86
|
+
return { stream, finished };
|
|
87
|
+
}
|
|
88
|
+
/** The turn's record under `key`, or null when the store has none, for the browser's reader to pick up where its stream stopped. */
|
|
89
|
+
export async function readTurn(store, key) {
|
|
90
|
+
return parseTurnRecord(await store.load(key));
|
|
91
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-cards/commerce-sdk",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.4",
|
|
4
4
|
"description": "Give your agent one tool that buys for your shoppers at real stores, and post each purchase update Agentcard sends into the shopper's chat, over a connection your server opens or a webhook endpoint.",
|
|
5
|
+
"homepage": "https://opencommerce.sh",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"main": "dist/index.js",
|
|
7
8
|
"types": "dist/index.d.ts",
|