@flytedesk/app-kit 16.0.0 → 16.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -0
- package/dist/chat/owed-replies/constants.d.ts +25 -0
- package/dist/chat/owed-replies/constants.js +45 -0
- package/dist/chat/owed-replies/constants.js.map +1 -0
- package/dist/chat/owed-replies/index.d.ts +15 -0
- package/dist/chat/owed-replies/index.js +12 -0
- package/dist/chat/owed-replies/index.js.map +1 -0
- package/dist/chat/owed-replies/plugin.d.ts +31 -0
- package/dist/chat/owed-replies/plugin.js +25 -0
- package/dist/chat/owed-replies/plugin.js.map +1 -0
- package/dist/chat/owed-replies/state.d.ts +46 -0
- package/dist/chat/owed-replies/state.js +31 -0
- package/dist/chat/owed-replies/state.js.map +1 -0
- package/dist/chat/owed-replies/store.d.ts +57 -0
- package/dist/chat/owed-replies/store.js +178 -0
- package/dist/chat/owed-replies/store.js.map +1 -0
- package/dist/chat/owed-replies/tool.d.ts +12 -0
- package/dist/chat/owed-replies/tool.js +61 -0
- package/dist/chat/owed-replies/tool.js.map +1 -0
- package/dist/chat/tools/index.d.ts +13 -0
- package/dist/chat/tools/index.js +18 -2
- package/dist/chat/tools/index.js.map +1 -1
- package/dist/cli/owed-reply-sync.d.ts +2 -0
- package/dist/cli/owed-reply-sync.js +28 -0
- package/dist/cli/owed-reply-sync.js.map +1 -0
- package/dist/connections/client.js +17 -1
- package/dist/connections/client.js.map +1 -1
- package/dist/connections/kinds.d.ts +38 -0
- package/dist/connections/kinds.js +35 -0
- package/dist/connections/kinds.js.map +1 -1
- package/dist/flytebot/testing/fake.d.ts +33 -4
- package/dist/flytebot/testing/fake.js +100 -3
- package/dist/flytebot/testing/fake.js.map +1 -1
- package/dist/flytebot/testing/index.d.ts +1 -1
- package/package.json +8 -3
- package/prisma/fragments/owed-reply.meta.json +4 -0
- package/prisma/fragments/owed-reply.prisma +52 -0
- package/prisma/migrations/0006_app_kit_owed_reply_init/migration.sql +63 -0
- package/prisma/migrations/manifest.json +7 -0
package/README.md
CHANGED
|
@@ -376,6 +376,7 @@ const db = await connections.get("main-db", "postgres");
|
|
|
376
376
|
(not app-writable, unknown, disabled, no permission) throw `ConnectionRefusedError`; an
|
|
377
377
|
unreachable flytedesk ID or a malformed answer throws `ConnectionOutageError`. The value
|
|
378
378
|
travels only in the request body and is never logged or put in an error.
|
|
379
|
+
- **Personal kinds (AK-84):** `slack_user` (settings `teamId`, `userId`; secret `userToken`) and `trello_member` (settings `memberId`, `apiKey`, the key the token was issued with; secret `token`) hold one person's own token, so an app can act as them. Both are app-manageable and carry `personal` (`isPersonalKind(kind)`). There is one connection per person per kind, named `personalConnectionSlug(kind, personId)` (for example `slack-user-<flytedesk ID sub>`), the same in every app. `createConnection`, `changeSettings`, `replaceSecret` and `deleteConnection` refuse, before any request, a personal kind whose slug is not `personalConnectionSlug(kind, onBehalfOf)`, so a person's `onBehalfOf` is always their own id.
|
|
379
380
|
- **Managing its own connections (AK-78, DEC-425):** for a kind that marks `appManageable` (trello; `isAppManageable(kind)`), the app's server calls `connections.createConnection({ slug, kind, name, settings, secrets }, onBehalfOf)` (answers `{ slug, kind, name, status }`; `secrets` is exactly the kind's secrets that are not app-writable), `changeSettings(slug, kind, { name?, settings }, onBehalfOf)` (`settings` is the complete object, replaced whole: a partial one is refused before a request; answers `{ slug, kind, name, status }`), `replaceSecret(slug, kind, field, value, onBehalfOf)` (a secret that is not app-writable; answers `{ field, version }`) and `deleteConnection(slug, kind, onBehalfOf)` (answers `{ slug }`). Each drops the slug's cached value, never logs or returns a secret, and refuses a kind that is not app-manageable with a `ConnectionRefusedError` before a request; flytedesk ID's own kind check decides. A taken slug is a `ConnectionRefusedError` (`slug exists`, 409, `connection_slug_exists`); a kind refusal carries `connection_kind_not_app_manageable`. The app's service principal needs flytedesk ID's `<appId>:connections.edit` permission. Two more refusal codes apply to these four methods and to `writeSecret`: `connection_write_conflict` (409), a lost race with another write of the same secret field, throws a `ConnectionRefusedError` with `reason` `"write conflict"` and `retryable: true` (sending the same request again succeeds); `connection_invalid_request` (400), a refused body, throws one with `reason` `"invalid request"`, distinct from `connection_not_found`. Every other refusal has `retryable: false`.
|
|
380
381
|
- **Listing the app's connections:** `connections.list()` answers every connection of the app, ACTIVE and DISABLED, as `{ slug, kind, name, status }` (`status` is `"ACTIVE"` or `"DISABLED"`), for an admin screen that offers them as a picker. It is metadata only: never a setting, secret, ciphertext or key name. It is never cached (every call asks flytedesk ID, and an outage throws). The principal needs `<appId>:connections.read`. A refusal throws `ConnectionRefusedError` (an empty `slug`); an unreachable flytedesk ID or a malformed answer (an unexpected field included) throws `ConnectionOutageError`; a kind the client does not know throws `ConnectionInvalidError`. The wire contract (`connectionListPath`, `ConnectionListAnswer`, `CONNECTION_LIST_ERROR_CODES`) is exported for flytedesk ID's route.
|
|
381
382
|
- **Testing a connection:** flytedesk ID asks the app to test one (the Test button).
|
|
@@ -1050,6 +1051,25 @@ fake.deliveries; // [{ runId, url, httpStatus, error }]
|
|
|
1050
1051
|
await fake.redeliver(runId); // at-least-once: the same terminal run again
|
|
1051
1052
|
```
|
|
1052
1053
|
|
|
1054
|
+
A run can also call your app's MCP tool server, as Flytebot's runner does. Tell the fake where each
|
|
1055
|
+
server answers (`setToolServer`), name the profile's reply tool, and script the calls. Each call is a JSON-RPC
|
|
1056
|
+
`tools/call` posted with the bearer you gave in `runs.create({ tools })`, recorded as `tool_call` and
|
|
1057
|
+
`tool_result` events. When a call of the reply tool reports nothing owed
|
|
1058
|
+
(`_meta["flytebot/reply"].owed` is 0), the run ends `completed`, as Flytebot's runner does; otherwise it ends
|
|
1059
|
+
as the script says once its calls are done:
|
|
1060
|
+
|
|
1061
|
+
```ts
|
|
1062
|
+
fake.setToolServer("sms-app-chat", `${appUrl}/mcp/chat`);
|
|
1063
|
+
fake.setProfile({ ...summary, reply: { server: "sms-app-chat", tool: "reply" } });
|
|
1064
|
+
const call = (phase, text) => ({ server: "sms-app-chat", tool: "reply", arguments: { to: owedReplyId, phase, text } });
|
|
1065
|
+
fake.scriptRun({ toolCalls: [call("ack", "On it."), call("reply", "Done.")] }); // answers, then ends
|
|
1066
|
+
fake.scriptRun({ toolCalls: [call("ack", "On it.")] }); // acknowledges, then ends with the reply still owed
|
|
1067
|
+
fake.scriptRun({}); // calls nothing
|
|
1068
|
+
await fake.scriptsSettled(); // every scripted call sequence has ended its run
|
|
1069
|
+
```
|
|
1070
|
+
|
|
1071
|
+
A call that cannot be made (no URL or bearer for its server) ends the run `error` with `mcp_unavailable`.
|
|
1072
|
+
|
|
1053
1073
|
### Serving your tools to Flytebot (`@flytedesk/app-kit/chat/tools`)
|
|
1054
1074
|
|
|
1055
1075
|
`createRemoteMcpPlugin` serves your `AppRegisteredTool`s (and `createReplyTool`)
|
|
@@ -1084,6 +1104,93 @@ A handler that throws is logged and reported to the agent as a tool error (`Tool
|
|
|
1084
1104
|
failed.`); a validation error you return as `{ ok: false, retryable: false }` is read by the
|
|
1085
1105
|
model, and a retryable one is a JSON-RPC error.
|
|
1086
1106
|
|
|
1107
|
+
### Owed replies (`@flytedesk/app-kit/chat/owed-replies`)
|
|
1108
|
+
|
|
1109
|
+
An app whose chat agent runs through Flytebot answers every message with one flow, the same as
|
|
1110
|
+
Flytebot's own chat. A person's message is *owed* an answer. The agent answers it through an MCP
|
|
1111
|
+
`reply` tool with `{ to, phase, text }`: first a short acknowledgement (`phase: "ack"`), then the full
|
|
1112
|
+
answer (`phase: "reply"`), which replaces it. A message is never left without an answer: when a run ends
|
|
1113
|
+
without one, the owed reply fails with a fixed line the person sees. It replaces `createReplyTool`'s
|
|
1114
|
+
progress/final flow; an app that adopts it removes its `createReplyTool` use in the same change
|
|
1115
|
+
(`createReplyTool`, `parseReplyArguments` and `ChatReplyPayload` stay until every app has moved).
|
|
1116
|
+
|
|
1117
|
+
**1. Install the tables.** Run `npx owed-reply-sync init`. It installs the fragment's two models
|
|
1118
|
+
(`OwedReply`, `OwedReplyDispatch`, tables `app_kit_owed_reply` and `app_kit_owed_reply_dispatch`) into your
|
|
1119
|
+
`schema.prisma`. It follows `auth-sync`'s Prisma-migrate mode, because every app that adopts the flow
|
|
1120
|
+
deploys with Prisma migrate: it writes no SQL and runs none. Create the tables with
|
|
1121
|
+
`npx prisma migrate dev --create-only`, append the CHECK statements `init` prints (Prisma's schema language
|
|
1122
|
+
has none), keep the migration one atomic `DO $$ ... $$` block with `SET LOCAL lock_timeout` if it has more
|
|
1123
|
+
than one statement, then apply it. An app that does not use Prisma migrate gets the raw SQL of
|
|
1124
|
+
`0006_app_kit_owed_reply_init` run for it. `npx owed-reply-sync apply` brings an installed fragment up to
|
|
1125
|
+
date.
|
|
1126
|
+
|
|
1127
|
+
**2. Make the store.** The store reads and writes through your own generated Prisma client (a structural
|
|
1128
|
+
type: tagged-template `$queryRaw`/`$executeRaw` and an interactive `$transaction`; no new dependency):
|
|
1129
|
+
|
|
1130
|
+
```ts
|
|
1131
|
+
const owedReplies = createOwedReplyStore({
|
|
1132
|
+
client: prisma,
|
|
1133
|
+
// Writes your own chat message for an owed reply that changed. It runs in the write's own
|
|
1134
|
+
// transaction (`tx` is your transaction client), so a throw undoes the write. `revision` rises on every
|
|
1135
|
+
// write: keep a projected message from going backwards.
|
|
1136
|
+
project: async (tx, reply) => upsertChatMessage(tx, reply.messageRef, shownText(reply), reply.revision),
|
|
1137
|
+
});
|
|
1138
|
+
```
|
|
1139
|
+
|
|
1140
|
+
An owed reply's `state` is derived on every read, never stored: `sent` (no run has taken it), `taken`,
|
|
1141
|
+
`acked`, `answered` or `failed`. `shownText(reply)` is what the person's chat shows: the reply, else the
|
|
1142
|
+
failure line, else the acknowledgement.
|
|
1143
|
+
|
|
1144
|
+
**3. Use its three operations around a run.**
|
|
1145
|
+
|
|
1146
|
+
- `receiveMessage({ messageRef, conversationRef, personRef })` when the person's message arrives.
|
|
1147
|
+
Idempotent on `messageRef`: a resent message returns its existing owed reply and never makes a second.
|
|
1148
|
+
- `claimForDispatch(conversationRef, dispatchId)` when you ask Flytebot for a run. Use the run's dispatch id
|
|
1149
|
+
as its `idempotencyKey` in `runs.create`. It binds every `sent` owed reply of the conversation to that
|
|
1150
|
+
dispatch and returns them (give their ids to the agent in its task, as the `to` of its replies).
|
|
1151
|
+
Idempotent for the same dispatch id, so a retried request or a redelivered webhook never makes a second
|
|
1152
|
+
binding. A message that arrives while the run works stays `sent` for the next run.
|
|
1153
|
+
- `settle(dispatchId, run)` from your terminal webhook route (`verifyTerminalWebhook` gives the run).
|
|
1154
|
+
Every owed reply the run left unanswered fails with one fixed line from `FAILURE_LINES`:
|
|
1155
|
+
`Stopped.` when the run was cancelled, `Flytebot finished without answering.` when it completed with
|
|
1156
|
+
no reply, and one line each for `error`, `timeout` and `crash`. It is idempotent: an answered or failed
|
|
1157
|
+
owed reply is untouched. It returns the conversation's remaining `sent` owed replies; when there are any,
|
|
1158
|
+
dispatch the next run for them.
|
|
1159
|
+
|
|
1160
|
+
`settle` and a late `reply` take the same row lock (`SELECT ... FOR UPDATE`) on the owed reply: a reply to
|
|
1161
|
+
a failed owed reply is refused with a tool error, and a `settle` after an answer changes nothing.
|
|
1162
|
+
|
|
1163
|
+
**4. Serve the tool.** `createOwedReplyPlugin` is `createRemoteMcpPlugin` with the `reply` tool for the
|
|
1164
|
+
run the bearer belongs to, and every result except a successful reply ending in one line that names the owed replies not yet answered:
|
|
1165
|
+
|
|
1166
|
+
```ts
|
|
1167
|
+
await app.register(
|
|
1168
|
+
createOwedReplyPlugin({
|
|
1169
|
+
serverName: "sms-app-chat",
|
|
1170
|
+
store: owedReplies,
|
|
1171
|
+
// The bearer is the per-run bearer you sent in runs.create({ tools }). Resolve it to the run only
|
|
1172
|
+
// while that run is running; return null otherwise (401).
|
|
1173
|
+
authenticate: async (bearer) => findRunningRunByToken(bearer),
|
|
1174
|
+
dispatchId: (run) => run.dispatchId,
|
|
1175
|
+
tools: (run) => [/* your other tools */],
|
|
1176
|
+
}),
|
|
1177
|
+
{ prefix: "/mcp/chat" },
|
|
1178
|
+
);
|
|
1179
|
+
```
|
|
1180
|
+
|
|
1181
|
+
`reply` refuses a `to` that is not an owed reply of the run's own dispatch, a reply to a failed owed
|
|
1182
|
+
reply, and a second, different text for an answered one. Resending the same phase with the same text
|
|
1183
|
+
answers ok and changes nothing; an ack is allowed until the owed reply is answered, and a second ack
|
|
1184
|
+
replaces the first. Each result carries `_meta["flytebot/reply"] = { owed, unheld, reminder }` (an app
|
|
1185
|
+
holds no background jobs, so `unheld` equals `owed`). Name the tool in your Flytebot profile
|
|
1186
|
+
(`reply: { server: "sms-app-chat", tool: "reply" }`): its runner then ends the run once `owed` is 0.
|
|
1187
|
+
`createRemoteMcpPlugin`'s new `resultNotice(context, call: { tool, ok })` option is what adds the line; a plugin without it
|
|
1188
|
+
returns results exactly as before. The fixed lines (the failure lines, the reminder, the owed-replies line,
|
|
1189
|
+
the refusals) are one module, `constants.ts`, exported from the subpath.
|
|
1190
|
+
|
|
1191
|
+
**5. Test it.** `createFakeFlytebot` scripts a run that acknowledges and replies through your real
|
|
1192
|
+
endpoint; see "Testing against the fake".
|
|
1193
|
+
|
|
1087
1194
|
## Tests
|
|
1088
1195
|
|
|
1089
1196
|
`npm run check` is the full gate: lint, typecheck, build, unit tests, integration tests
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { TerminalStatus } from "@flytedesk/flytebot-contracts";
|
|
2
|
+
/**
|
|
3
|
+
* Every fixed line of the owed-reply flow, in one place (AK-80): the README quotes these, a
|
|
4
|
+
* person sees the failure lines in their chat, and the model reads the rest.
|
|
5
|
+
*/
|
|
6
|
+
/** The reply tool's name unless the app names it otherwise, and the key a profile's `reply: {server, tool}` points at. */
|
|
7
|
+
export declare const DEFAULT_REPLY_TOOL_NAME = "reply";
|
|
8
|
+
/**
|
|
9
|
+
* What a person sees in place of an answer when the run that took their message ended without
|
|
10
|
+
* answering it, by how the run ended. A run that completed without calling the reply tool is
|
|
11
|
+
* `completed`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const FAILURE_LINES: Readonly<Record<TerminalStatus, string>>;
|
|
14
|
+
/** The reminder a reply result carries under `_meta["flytebot/reply"]` while an answer is still owed. */
|
|
15
|
+
export declare function owedReminder(toolName: string, owed: number): string;
|
|
16
|
+
/** The line that ends every result of an endpoint that names its owed replies; null when none is owed. */
|
|
17
|
+
export declare function owedRepliesLine(toolName: string, ids: readonly string[]): string | null;
|
|
18
|
+
/** What the model reads after a successful call of the reply tool. */
|
|
19
|
+
export declare function deliveredText(toolName: string, phase: "ack" | "reply", owed: number): string;
|
|
20
|
+
/** The refusals of the reply tool, as the model reads them. */
|
|
21
|
+
export declare const REFUSALS: {
|
|
22
|
+
readonly notOwed: "`to` is not an owed reply of this run.";
|
|
23
|
+
readonly failed: "That owed reply already ended without an answer, so it takes no more replies.";
|
|
24
|
+
readonly answered: "That owed reply is already answered.";
|
|
25
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every fixed line of the owed-reply flow, in one place (AK-80): the README quotes these, a
|
|
3
|
+
* person sees the failure lines in their chat, and the model reads the rest.
|
|
4
|
+
*/
|
|
5
|
+
/** The reply tool's name unless the app names it otherwise, and the key a profile's `reply: {server, tool}` points at. */
|
|
6
|
+
export const DEFAULT_REPLY_TOOL_NAME = "reply";
|
|
7
|
+
/**
|
|
8
|
+
* What a person sees in place of an answer when the run that took their message ended without
|
|
9
|
+
* answering it, by how the run ended. A run that completed without calling the reply tool is
|
|
10
|
+
* `completed`.
|
|
11
|
+
*/
|
|
12
|
+
export const FAILURE_LINES = {
|
|
13
|
+
cancelled: "Stopped.",
|
|
14
|
+
completed: "Flytebot finished without answering.",
|
|
15
|
+
error: "Flytebot hit an error and stopped.",
|
|
16
|
+
timeout: "Flytebot ran out of time and stopped.",
|
|
17
|
+
crash: "Flytebot stopped unexpectedly.",
|
|
18
|
+
};
|
|
19
|
+
/** The reminder a reply result carries under `_meta["flytebot/reply"]` while an answer is still owed. */
|
|
20
|
+
export function owedReminder(toolName, owed) {
|
|
21
|
+
return owed === 0
|
|
22
|
+
? "Every reply is answered."
|
|
23
|
+
: `You still owe an answer to ${owed} message${owed === 1 ? "" : "s"}. Send each through ${toolName} (phase "reply") before you stop.`;
|
|
24
|
+
}
|
|
25
|
+
/** The line that ends every result of an endpoint that names its owed replies; null when none is owed. */
|
|
26
|
+
export function owedRepliesLine(toolName, ids) {
|
|
27
|
+
return ids.length === 0
|
|
28
|
+
? null
|
|
29
|
+
: `Owed replies not yet answered: ${ids.join(", ")}. Answer each with ${toolName} (phase "reply").`;
|
|
30
|
+
}
|
|
31
|
+
/** What the model reads after a successful call of the reply tool. */
|
|
32
|
+
export function deliveredText(toolName, phase, owed) {
|
|
33
|
+
if (phase === "ack")
|
|
34
|
+
return "Acknowledged. Continue with the work, then send your reply.";
|
|
35
|
+
return owed === 0
|
|
36
|
+
? "Delivered. Every reply is answered: do not send anything further."
|
|
37
|
+
: `Delivered. ${owedReminder(toolName, owed)}`;
|
|
38
|
+
}
|
|
39
|
+
/** The refusals of the reply tool, as the model reads them. */
|
|
40
|
+
export const REFUSALS = {
|
|
41
|
+
notOwed: "`to` is not an owed reply of this run.",
|
|
42
|
+
failed: "That owed reply already ended without an answer, so it takes no more replies.",
|
|
43
|
+
answered: "That owed reply is already answered.",
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/constants.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH,0HAA0H;AAC1H,MAAM,CAAC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAE/C;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAA6C;IACrE,SAAS,EAAE,UAAU;IACrB,SAAS,EAAE,sCAAsC;IACjD,KAAK,EAAE,oCAAoC;IAC3C,OAAO,EAAE,uCAAuC;IAChD,KAAK,EAAE,gCAAgC;CACxC,CAAC;AAEF,yGAAyG;AACzG,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,IAAY;IACzD,OAAO,IAAI,KAAK,CAAC;QACf,CAAC,CAAC,0BAA0B;QAC5B,CAAC,CAAC,8BAA8B,IAAI,WAAW,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,uBAAuB,QAAQ,mCAAmC,CAAC;AAC3I,CAAC;AAED,0GAA0G;AAC1G,MAAM,UAAU,eAAe,CAAC,QAAgB,EAAE,GAAsB;IACtE,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC;QACrB,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,kCAAkC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,sBAAsB,QAAQ,mBAAmB,CAAC;AACxG,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,KAAsB,EAAE,IAAY;IAClF,IAAI,KAAK,KAAK,KAAK;QAAE,OAAO,6DAA6D,CAAC;IAC1F,OAAO,IAAI,KAAK,CAAC;QACf,CAAC,CAAC,mEAAmE;QACrE,CAAC,CAAC,cAAc,YAAY,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;AACnD,CAAC;AAED,+DAA+D;AAC/D,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,+EAA+E;IACvF,QAAQ,EAAE,sCAAsC;CACxC,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@flytedesk/app-kit/chat/owed-replies`: the owed-reply flow for an app whose chat agent runs
|
|
3
|
+
* through Flytebot (AK-80). A person's message is owed an answer; the agent's run answers it
|
|
4
|
+
* through the `reply` MCP tool, first an acknowledgement, then the reply that replaces it, so
|
|
5
|
+
* a message is never left without an answer. See the README's "Owed replies" section.
|
|
6
|
+
*/
|
|
7
|
+
export { DEFAULT_REPLY_TOOL_NAME, FAILURE_LINES, REFUSALS, deliveredText, owedRepliesLine, owedReminder } from "./constants.js";
|
|
8
|
+
export { shownText } from "./state.js";
|
|
9
|
+
export type { OwedReply, OwedReplyState } from "./state.js";
|
|
10
|
+
export { createOwedReplyStore } from "./store.js";
|
|
11
|
+
export type { OwedReplyClient, OwedReplyStore, OwedReplyStoreOptions, OwedReplyTransaction, ReceiveMessageInput, WriteReplyInput, WriteReplyResult, } from "./store.js";
|
|
12
|
+
export { createOwedReplyTool } from "./tool.js";
|
|
13
|
+
export type { OwedReplyToolOptions } from "./tool.js";
|
|
14
|
+
export { createOwedReplyPlugin } from "./plugin.js";
|
|
15
|
+
export type { OwedReplyPluginOptions } from "./plugin.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@flytedesk/app-kit/chat/owed-replies`: the owed-reply flow for an app whose chat agent runs
|
|
3
|
+
* through Flytebot (AK-80). A person's message is owed an answer; the agent's run answers it
|
|
4
|
+
* through the `reply` MCP tool, first an acknowledgement, then the reply that replaces it, so
|
|
5
|
+
* a message is never left without an answer. See the README's "Owed replies" section.
|
|
6
|
+
*/
|
|
7
|
+
export { DEFAULT_REPLY_TOOL_NAME, FAILURE_LINES, REFUSALS, deliveredText, owedRepliesLine, owedReminder } from "./constants.js";
|
|
8
|
+
export { shownText } from "./state.js";
|
|
9
|
+
export { createOwedReplyStore } from "./store.js";
|
|
10
|
+
export { createOwedReplyTool } from "./tool.js";
|
|
11
|
+
export { createOwedReplyPlugin } from "./plugin.js";
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,uBAAuB,EAAE,aAAa,EAAE,QAAQ,EAAE,aAAa,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAChI,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAUlD,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chat MCP endpoint of an app that answers through the owed-reply flow (AK-80):
|
|
3
|
+
* `createRemoteMcpPlugin` serving the `reply` tool for the run its bearer belongs to, with
|
|
4
|
+
* every result except a successful reply ending in one line that names the owed replies not yet answered.
|
|
5
|
+
*
|
|
6
|
+
* await app.register(
|
|
7
|
+
* createOwedReplyPlugin({
|
|
8
|
+
* serverName: "sms-app-chat",
|
|
9
|
+
* store,
|
|
10
|
+
* authenticate: async (bearer) => findRunningRunByToken(bearer), // run or null
|
|
11
|
+
* dispatchId: (run) => run.dispatchId,
|
|
12
|
+
* tools: (run) => [...the app's other tools],
|
|
13
|
+
* }),
|
|
14
|
+
* { prefix: "/mcp/chat" },
|
|
15
|
+
* );
|
|
16
|
+
*/
|
|
17
|
+
import type { FastifyPluginAsync } from "fastify";
|
|
18
|
+
import { type RemoteMcpPluginOptions } from "../tools/index.js";
|
|
19
|
+
import type { AppRegisteredTool } from "../types.js";
|
|
20
|
+
import type { OwedReplyStore } from "./store.js";
|
|
21
|
+
export interface OwedReplyPluginOptions<Context> extends Pick<RemoteMcpPluginOptions<Context>, "serverName" | "serverVersion" | "authenticate"> {
|
|
22
|
+
store: OwedReplyStore;
|
|
23
|
+
/** The dispatch id of the run a resolved context is: the Idempotency-Key the app sent in `runs.create`. */
|
|
24
|
+
dispatchId: (context: Context) => string;
|
|
25
|
+
/** The other tools the run may call, besides the reply tool. */
|
|
26
|
+
tools?: (context: Context) => AppRegisteredTool[];
|
|
27
|
+
/** The reply tool's name. Default `reply`; the profile's `reply: {server, tool}` names it. */
|
|
28
|
+
replyToolName?: string;
|
|
29
|
+
replyToolDescription?: string;
|
|
30
|
+
}
|
|
31
|
+
export declare function createOwedReplyPlugin<Context>(options: OwedReplyPluginOptions<Context>): FastifyPluginAsync;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createRemoteMcpPlugin } from "../tools/index.js";
|
|
2
|
+
import { DEFAULT_REPLY_TOOL_NAME, owedRepliesLine } from "./constants.js";
|
|
3
|
+
import { createOwedReplyTool } from "./tool.js";
|
|
4
|
+
export function createOwedReplyPlugin(options) {
|
|
5
|
+
const toolName = options.replyToolName ?? DEFAULT_REPLY_TOOL_NAME;
|
|
6
|
+
return createRemoteMcpPlugin({
|
|
7
|
+
serverName: options.serverName,
|
|
8
|
+
serverVersion: options.serverVersion,
|
|
9
|
+
authenticate: options.authenticate,
|
|
10
|
+
tools: (context) => [
|
|
11
|
+
createOwedReplyTool({
|
|
12
|
+
store: options.store,
|
|
13
|
+
dispatchId: options.dispatchId(context),
|
|
14
|
+
name: toolName,
|
|
15
|
+
description: options.replyToolDescription,
|
|
16
|
+
}),
|
|
17
|
+
...(options.tools?.(context) ?? []),
|
|
18
|
+
],
|
|
19
|
+
// A successful reply result already says how many replies are owed, so it takes no second reminder.
|
|
20
|
+
resultNotice: async (context, call) => call.tool === toolName && call.ok
|
|
21
|
+
? null
|
|
22
|
+
: owedRepliesLine(toolName, (await options.store.unansweredOf(options.dispatchId(context))).map((reply) => reply.id)),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=plugin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/plugin.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,qBAAqB,EAA+B,MAAM,mBAAmB,CAAC;AAEvF,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAchD,MAAM,UAAU,qBAAqB,CAAU,OAAwC;IACrF,MAAM,QAAQ,GAAG,OAAO,CAAC,aAAa,IAAI,uBAAuB,CAAC;IAClE,OAAO,qBAAqB,CAAU;QACpC,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC;YAClB,mBAAmB,CAAC;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,UAAU,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;gBACvC,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,OAAO,CAAC,oBAAoB;aAC1C,CAAC;YACF,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;SACpC;QACD,oGAAoG;QACpG,YAAY,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,CACpC,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE;YAC/B,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,eAAe,CACb,QAAQ,EACR,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CACzF;KACR,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An owed reply's state, derived on every read, never stored (AK-80):
|
|
3
|
+
* sent no run has taken it
|
|
4
|
+
* taken a run took it and has written nothing yet
|
|
5
|
+
* acked the run wrote an acknowledgement
|
|
6
|
+
* answered the run wrote the reply (final)
|
|
7
|
+
* failed the run ended without answering; `failure` is the line the person sees
|
|
8
|
+
*/
|
|
9
|
+
export type OwedReplyState = "sent" | "taken" | "acked" | "answered" | "failed";
|
|
10
|
+
/** One person's message that is owed an answer, as the store reads it. */
|
|
11
|
+
export interface OwedReply {
|
|
12
|
+
id: string;
|
|
13
|
+
/** The app's own id for the person's message. */
|
|
14
|
+
messageRef: string;
|
|
15
|
+
conversationRef: string;
|
|
16
|
+
personRef: string;
|
|
17
|
+
ackText: string | null;
|
|
18
|
+
replyText: string | null;
|
|
19
|
+
failure: string | null;
|
|
20
|
+
/** Raised on every write, so an app's projected chat message can tell a stale write. */
|
|
21
|
+
revision: number;
|
|
22
|
+
state: OwedReplyState;
|
|
23
|
+
createdAt: Date;
|
|
24
|
+
ackedAt: Date | null;
|
|
25
|
+
answeredAt: Date | null;
|
|
26
|
+
failedAt: Date | null;
|
|
27
|
+
}
|
|
28
|
+
/** What the person's chat shows for an owed reply: its answer, else its failure line, else its acknowledgement, else nothing. */
|
|
29
|
+
export declare function shownText(reply: Pick<OwedReply, "replyText" | "failure" | "ackText">): string | null;
|
|
30
|
+
/** The columns of one owed reply row as the raw query aliases them. */
|
|
31
|
+
export interface OwedReplyRow {
|
|
32
|
+
id: string;
|
|
33
|
+
messageRef: string;
|
|
34
|
+
conversationRef: string;
|
|
35
|
+
personRef: string;
|
|
36
|
+
ackText: string | null;
|
|
37
|
+
replyText: string | null;
|
|
38
|
+
failure: string | null;
|
|
39
|
+
revision: number;
|
|
40
|
+
taken: boolean;
|
|
41
|
+
createdAt: Date;
|
|
42
|
+
ackedAt: Date | null;
|
|
43
|
+
answeredAt: Date | null;
|
|
44
|
+
failedAt: Date | null;
|
|
45
|
+
}
|
|
46
|
+
export declare function owedReplyFromRow(row: OwedReplyRow): OwedReply;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** What the person's chat shows for an owed reply: its answer, else its failure line, else its acknowledgement, else nothing. */
|
|
2
|
+
export function shownText(reply) {
|
|
3
|
+
return reply.replyText ?? reply.failure ?? reply.ackText;
|
|
4
|
+
}
|
|
5
|
+
function deriveState(row) {
|
|
6
|
+
if (row.failure !== null)
|
|
7
|
+
return "failed";
|
|
8
|
+
if (row.replyText !== null)
|
|
9
|
+
return "answered";
|
|
10
|
+
if (row.ackText !== null)
|
|
11
|
+
return "acked";
|
|
12
|
+
return row.taken ? "taken" : "sent";
|
|
13
|
+
}
|
|
14
|
+
export function owedReplyFromRow(row) {
|
|
15
|
+
return {
|
|
16
|
+
id: row.id,
|
|
17
|
+
messageRef: row.messageRef,
|
|
18
|
+
conversationRef: row.conversationRef,
|
|
19
|
+
personRef: row.personRef,
|
|
20
|
+
ackText: row.ackText,
|
|
21
|
+
replyText: row.replyText,
|
|
22
|
+
failure: row.failure,
|
|
23
|
+
revision: row.revision,
|
|
24
|
+
state: deriveState(row),
|
|
25
|
+
createdAt: row.createdAt,
|
|
26
|
+
ackedAt: row.ackedAt,
|
|
27
|
+
answeredAt: row.answeredAt,
|
|
28
|
+
failedAt: row.failedAt,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/state.ts"],"names":[],"mappings":"AA6BA,iIAAiI;AACjI,MAAM,UAAU,SAAS,CAAC,KAA2D;IACnF,OAAO,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC;AAC3D,CAAC;AAmBD,SAAS,WAAW,CAAC,GAAiB;IACpC,IAAI,GAAG,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,QAAQ,CAAC;IAC1C,IAAI,GAAG,CAAC,SAAS,KAAK,IAAI;QAAE,OAAO,UAAU,CAAC;IAC9C,IAAI,GAAG,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,OAAO,CAAC;IACzC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,GAAiB;IAChD,OAAO;QACL,EAAE,EAAE,GAAG,CAAC,EAAE;QACV,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,eAAe,EAAE,GAAG,CAAC,eAAe;QACpC,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC;QACvB,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,QAAQ,EAAE,GAAG,CAAC,QAAQ;KACvB,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { TerminalStatus } from "@flytedesk/flytebot-contracts";
|
|
2
|
+
import { type OwedReply } from "./state.js";
|
|
3
|
+
/** The raw-SQL half of a Prisma client, or of one of its interactive transactions. */
|
|
4
|
+
export interface OwedReplyTransaction {
|
|
5
|
+
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;
|
|
6
|
+
$executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<number>;
|
|
7
|
+
}
|
|
8
|
+
/** A generated Prisma client (carrying `prisma/fragments/owed-reply.prisma`'s models) satisfies this. */
|
|
9
|
+
export interface OwedReplyClient<Tx extends OwedReplyTransaction> extends OwedReplyTransaction {
|
|
10
|
+
$transaction<T>(fn: (tx: Tx) => Promise<T>, options: {
|
|
11
|
+
timeout: number;
|
|
12
|
+
maxWait: number;
|
|
13
|
+
}): Promise<T>;
|
|
14
|
+
}
|
|
15
|
+
export interface OwedReplyStoreOptions<Tx extends OwedReplyTransaction> {
|
|
16
|
+
client: OwedReplyClient<Tx>;
|
|
17
|
+
/**
|
|
18
|
+
* Writes the app's own chat message for an owed reply that just changed (its acknowledgement,
|
|
19
|
+
* reply or failure line). It runs inside the write's transaction, so a thrown error undoes the
|
|
20
|
+
* write. Use `revision` to keep a projected message from going backwards.
|
|
21
|
+
*/
|
|
22
|
+
project: (tx: Tx, reply: OwedReply) => Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export interface ReceiveMessageInput {
|
|
25
|
+
/** The app's own id for the person's message. */
|
|
26
|
+
messageRef: string;
|
|
27
|
+
conversationRef: string;
|
|
28
|
+
personRef: string;
|
|
29
|
+
}
|
|
30
|
+
export interface WriteReplyInput {
|
|
31
|
+
/** The dispatch id of the run writing: the Idempotency-Key the app sent in `runs.create`. */
|
|
32
|
+
dispatchId: string;
|
|
33
|
+
/** The owed reply written to. */
|
|
34
|
+
to: string;
|
|
35
|
+
phase: "ack" | "reply";
|
|
36
|
+
text: string;
|
|
37
|
+
}
|
|
38
|
+
export type WriteReplyResult =
|
|
39
|
+
/** `owed` counts the run's owed replies still unanswered after this write. */
|
|
40
|
+
{
|
|
41
|
+
ok: true;
|
|
42
|
+
owed: number;
|
|
43
|
+
} | {
|
|
44
|
+
ok: false;
|
|
45
|
+
message: string;
|
|
46
|
+
};
|
|
47
|
+
export interface OwedReplyStore {
|
|
48
|
+
receiveMessage(input: ReceiveMessageInput): Promise<OwedReply>;
|
|
49
|
+
claimForDispatch(conversationRef: string, dispatchId: string): Promise<OwedReply[]>;
|
|
50
|
+
writeReply(input: WriteReplyInput): Promise<WriteReplyResult>;
|
|
51
|
+
settle(dispatchId: string, run: {
|
|
52
|
+
status: TerminalStatus;
|
|
53
|
+
}): Promise<OwedReply[]>;
|
|
54
|
+
/** The owed replies of a run that are neither answered nor failed, oldest first. */
|
|
55
|
+
unansweredOf(dispatchId: string): Promise<OwedReply[]>;
|
|
56
|
+
}
|
|
57
|
+
export declare function createOwedReplyStore<Tx extends OwedReplyTransaction>(options: OwedReplyStoreOptions<Tx>): OwedReplyStore;
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The owed-reply store (AK-80): the app's record of the answers its chat still owes, in its
|
|
3
|
+
* own Postgres database (`prisma/fragments/owed-reply.prisma`, installed with
|
|
4
|
+
* `owed-reply-sync init`).
|
|
5
|
+
*
|
|
6
|
+
* A person's message is owed an answer until the agent's run writes it through the reply
|
|
7
|
+
* tool. The store gives the app three operations around a run:
|
|
8
|
+
* receiveMessage the message arrives; idempotent on its ref
|
|
9
|
+
* claimForDispatch the app asks Flytebot for a run; binds every `sent` owed reply of the
|
|
10
|
+
* conversation to that run's dispatch id
|
|
11
|
+
* settle the run ended (the terminal webhook); every owed reply it left
|
|
12
|
+
* unanswered fails with one fixed line
|
|
13
|
+
* and `writeReply`, which the reply tool calls (see tool.ts).
|
|
14
|
+
*
|
|
15
|
+
* Every write runs in one transaction under the owed reply's row lock, raises `revision` and
|
|
16
|
+
* calls the app's projector (`project`, which writes its own chat message) in that same
|
|
17
|
+
* transaction. `settle` and a late reply therefore serialise on the same row: a reply to a
|
|
18
|
+
* failed owed reply is refused, and a settle after an answer changes nothing.
|
|
19
|
+
*
|
|
20
|
+
* The store talks to the app's own Prisma client through `OwedReplyClient`, a structural type
|
|
21
|
+
* (a generated client satisfies it, as for `PrismaAuthStore`): tagged-template raw SQL and an
|
|
22
|
+
* interactive transaction. It adds no dependency, and SQL is the only way to take
|
|
23
|
+
* `SELECT ... FOR UPDATE`.
|
|
24
|
+
*/
|
|
25
|
+
import { randomUUID } from "node:crypto";
|
|
26
|
+
import { FAILURE_LINES, REFUSALS } from "./constants.js";
|
|
27
|
+
import { owedReplyFromRow } from "./state.js";
|
|
28
|
+
/**
|
|
29
|
+
* Options of every transaction the store opens: `timeout` bounds the transaction's own work once
|
|
30
|
+
* started, `maxWait` how long Prisma queues for a free pooled connection, so a pool under
|
|
31
|
+
* contention fails fast (Prisma's P2028) instead of queueing writes behind a stuck holder.
|
|
32
|
+
*/
|
|
33
|
+
const TRANSACTION_OPTIONS = { timeout: 15_000, maxWait: 5_000 };
|
|
34
|
+
/** The ids a query found. */
|
|
35
|
+
async function idsOf(rows) {
|
|
36
|
+
return (await rows).map((row) => row.id);
|
|
37
|
+
}
|
|
38
|
+
const byCreation = (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1);
|
|
39
|
+
export function createOwedReplyStore(options) {
|
|
40
|
+
const { client, project } = options;
|
|
41
|
+
/** The one read of owed reply rows; every query below only finds ids. */
|
|
42
|
+
async function load(db, ids) {
|
|
43
|
+
if (ids.length === 0)
|
|
44
|
+
return [];
|
|
45
|
+
const rows = await db.$queryRaw `
|
|
46
|
+
SELECT r."id", r."message_ref" AS "messageRef", r."conversation_ref" AS "conversationRef",
|
|
47
|
+
r."person_ref" AS "personRef", r."ack_text" AS "ackText", r."reply_text" AS "replyText",
|
|
48
|
+
r."failure", r."revision", r."created_at" AS "createdAt", r."acked_at" AS "ackedAt",
|
|
49
|
+
r."answered_at" AS "answeredAt", r."failed_at" AS "failedAt",
|
|
50
|
+
EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id") AS "taken"
|
|
51
|
+
FROM "app_kit_owed_reply" r
|
|
52
|
+
WHERE r."id" = ANY(${ids}::text[])`;
|
|
53
|
+
return rows.map(owedReplyFromRow).sort(byCreation);
|
|
54
|
+
}
|
|
55
|
+
async function loadOne(db, id) {
|
|
56
|
+
const [reply] = await load(db, [id]);
|
|
57
|
+
if (reply === undefined)
|
|
58
|
+
throw new Error(`owed reply ${id} vanished inside its own transaction`);
|
|
59
|
+
return reply;
|
|
60
|
+
}
|
|
61
|
+
/** Counts the run's owed replies that are neither answered nor failed. */
|
|
62
|
+
async function owedCount(db, dispatchId) {
|
|
63
|
+
const [row] = await db.$queryRaw `
|
|
64
|
+
SELECT count(*)::int AS "count"
|
|
65
|
+
FROM "app_kit_owed_reply_dispatch" d
|
|
66
|
+
JOIN "app_kit_owed_reply" r ON r."id" = d."owed_reply_id"
|
|
67
|
+
WHERE d."dispatch_id" = ${dispatchId} AND r."reply_text" IS NULL AND r."failure" IS NULL`;
|
|
68
|
+
return row?.count ?? 0;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
async receiveMessage(input) {
|
|
72
|
+
await client.$executeRaw `
|
|
73
|
+
INSERT INTO "app_kit_owed_reply" ("id", "message_ref", "conversation_ref", "person_ref")
|
|
74
|
+
VALUES (${randomUUID()}, ${input.messageRef}, ${input.conversationRef}, ${input.personRef})
|
|
75
|
+
ON CONFLICT ("message_ref") DO NOTHING`;
|
|
76
|
+
const [row] = await client.$queryRaw `
|
|
77
|
+
SELECT "id" FROM "app_kit_owed_reply" WHERE "message_ref" = ${input.messageRef}`;
|
|
78
|
+
if (row === undefined)
|
|
79
|
+
throw new Error(`owed reply for message ${input.messageRef} was not stored`);
|
|
80
|
+
return loadOne(client, row.id);
|
|
81
|
+
},
|
|
82
|
+
async claimForDispatch(conversationRef, dispatchId) {
|
|
83
|
+
return client.$transaction(async (tx) => {
|
|
84
|
+
// Lock the conversation's open owed replies first: a second claim for another run waits here,
|
|
85
|
+
// then (a new statement, a new snapshot) sees the first claim's bindings and binds nothing twice.
|
|
86
|
+
const open = await idsOf(tx.$queryRaw `
|
|
87
|
+
SELECT "id" FROM "app_kit_owed_reply"
|
|
88
|
+
WHERE "conversation_ref" = ${conversationRef} AND "reply_text" IS NULL AND "failure" IS NULL
|
|
89
|
+
ORDER BY "id" FOR UPDATE`);
|
|
90
|
+
// A dispatch that already has bindings was claimed once: a retried request gets those back and binds
|
|
91
|
+
// nothing, so a message that arrived while the run works is never attached to a run that did not see it.
|
|
92
|
+
const [claimed] = await tx.$queryRaw `
|
|
93
|
+
SELECT "owed_reply_id" AS "id" FROM "app_kit_owed_reply_dispatch" WHERE "dispatch_id" = ${dispatchId} LIMIT 1`;
|
|
94
|
+
if (claimed === undefined && open.length > 0) {
|
|
95
|
+
await tx.$executeRaw `
|
|
96
|
+
INSERT INTO "app_kit_owed_reply_dispatch" ("owed_reply_id", "dispatch_id")
|
|
97
|
+
SELECT r."id", ${dispatchId} FROM "app_kit_owed_reply" r
|
|
98
|
+
WHERE r."id" = ANY(${open}::text[])
|
|
99
|
+
AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id")
|
|
100
|
+
ON CONFLICT DO NOTHING`;
|
|
101
|
+
}
|
|
102
|
+
const bound = await idsOf(tx.$queryRaw `
|
|
103
|
+
SELECT "owed_reply_id" AS "id" FROM "app_kit_owed_reply_dispatch" WHERE "dispatch_id" = ${dispatchId}`);
|
|
104
|
+
return load(tx, bound);
|
|
105
|
+
}, TRANSACTION_OPTIONS);
|
|
106
|
+
},
|
|
107
|
+
async writeReply(input) {
|
|
108
|
+
return client.$transaction(async (tx) => {
|
|
109
|
+
const [locked] = await tx.$queryRaw `
|
|
110
|
+
SELECT r."id" FROM "app_kit_owed_reply" r
|
|
111
|
+
WHERE r."id" = ${input.to}
|
|
112
|
+
AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
|
|
113
|
+
WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${input.dispatchId})
|
|
114
|
+
FOR UPDATE OF r`;
|
|
115
|
+
if (locked === undefined)
|
|
116
|
+
return { ok: false, message: REFUSALS.notOwed };
|
|
117
|
+
const current = await loadOne(tx, locked.id);
|
|
118
|
+
if (current.state === "failed")
|
|
119
|
+
return { ok: false, message: REFUSALS.failed };
|
|
120
|
+
const sameText = input.phase === "ack" ? current.ackText : current.replyText;
|
|
121
|
+
if (sameText === input.text)
|
|
122
|
+
return { ok: true, owed: await owedCount(tx, input.dispatchId) };
|
|
123
|
+
if (current.state === "answered")
|
|
124
|
+
return { ok: false, message: REFUSALS.answered };
|
|
125
|
+
if (input.phase === "ack") {
|
|
126
|
+
await tx.$executeRaw `
|
|
127
|
+
UPDATE "app_kit_owed_reply"
|
|
128
|
+
SET "ack_text" = ${input.text}, "acked_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
|
|
129
|
+
WHERE "id" = ${current.id}`;
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
await tx.$executeRaw `
|
|
133
|
+
UPDATE "app_kit_owed_reply"
|
|
134
|
+
SET "reply_text" = ${input.text}, "answered_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
|
|
135
|
+
WHERE "id" = ${current.id}`;
|
|
136
|
+
}
|
|
137
|
+
await project(tx, await loadOne(tx, current.id));
|
|
138
|
+
return { ok: true, owed: await owedCount(tx, input.dispatchId) };
|
|
139
|
+
}, TRANSACTION_OPTIONS);
|
|
140
|
+
},
|
|
141
|
+
async settle(dispatchId, run) {
|
|
142
|
+
const failure = FAILURE_LINES[run.status];
|
|
143
|
+
return client.$transaction(async (tx) => {
|
|
144
|
+
const locked = await idsOf(tx.$queryRaw `
|
|
145
|
+
SELECT r."id" FROM "app_kit_owed_reply" r
|
|
146
|
+
WHERE EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
|
|
147
|
+
WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${dispatchId})
|
|
148
|
+
ORDER BY r."id" FOR UPDATE OF r`);
|
|
149
|
+
const bound = await load(tx, locked);
|
|
150
|
+
for (const reply of bound) {
|
|
151
|
+
if (reply.state === "answered" || reply.state === "failed")
|
|
152
|
+
continue;
|
|
153
|
+
await tx.$executeRaw `
|
|
154
|
+
UPDATE "app_kit_owed_reply"
|
|
155
|
+
SET "failure" = ${failure}, "failed_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
|
|
156
|
+
WHERE "id" = ${reply.id}`;
|
|
157
|
+
await project(tx, await loadOne(tx, reply.id));
|
|
158
|
+
}
|
|
159
|
+
const conversations = [...new Set(bound.map((reply) => reply.conversationRef))];
|
|
160
|
+
if (conversations.length === 0)
|
|
161
|
+
return [];
|
|
162
|
+
return load(tx, await idsOf(tx.$queryRaw `
|
|
163
|
+
SELECT r."id" FROM "app_kit_owed_reply" r
|
|
164
|
+
WHERE r."conversation_ref" = ANY(${conversations}::text[])
|
|
165
|
+
AND r."reply_text" IS NULL AND r."failure" IS NULL
|
|
166
|
+
AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id")`));
|
|
167
|
+
}, TRANSACTION_OPTIONS);
|
|
168
|
+
},
|
|
169
|
+
async unansweredOf(dispatchId) {
|
|
170
|
+
return load(client, await idsOf(client.$queryRaw `
|
|
171
|
+
SELECT d."owed_reply_id" AS "id"
|
|
172
|
+
FROM "app_kit_owed_reply_dispatch" d
|
|
173
|
+
JOIN "app_kit_owed_reply" r ON r."id" = d."owed_reply_id"
|
|
174
|
+
WHERE d."dispatch_id" = ${dispatchId} AND r."reply_text" IS NULL AND r."failure" IS NULL`));
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAqC,MAAM,YAAY,CAAC;AAajF;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAW,CAAC;AA4CzE,6BAA6B;AAC7B,KAAK,UAAU,KAAK,CAAC,IAAsB;IACzC,OAAO,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,GAAG,CAAC,CAAY,EAAE,CAAY,EAAU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