@flytedesk/app-kit 16.1.0 → 16.3.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.
Files changed (35) hide show
  1. package/README.md +195 -0
  2. package/dist/chat/owed-replies/constants.d.ts +47 -0
  3. package/dist/chat/owed-replies/constants.js +71 -0
  4. package/dist/chat/owed-replies/constants.js.map +1 -0
  5. package/dist/chat/owed-replies/index.d.ts +16 -0
  6. package/dist/chat/owed-replies/index.js +12 -0
  7. package/dist/chat/owed-replies/index.js.map +1 -0
  8. package/dist/chat/owed-replies/plugin.d.ts +36 -0
  9. package/dist/chat/owed-replies/plugin.js +33 -0
  10. package/dist/chat/owed-replies/plugin.js.map +1 -0
  11. package/dist/chat/owed-replies/state.d.ts +56 -0
  12. package/dist/chat/owed-replies/state.js +33 -0
  13. package/dist/chat/owed-replies/state.js.map +1 -0
  14. package/dist/chat/owed-replies/store.d.ts +155 -0
  15. package/dist/chat/owed-replies/store.js +420 -0
  16. package/dist/chat/owed-replies/store.js.map +1 -0
  17. package/dist/chat/owed-replies/tool.d.ts +24 -0
  18. package/dist/chat/owed-replies/tool.js +77 -0
  19. package/dist/chat/owed-replies/tool.js.map +1 -0
  20. package/dist/chat/tools/index.d.ts +19 -0
  21. package/dist/chat/tools/index.js +16 -2
  22. package/dist/chat/tools/index.js.map +1 -1
  23. package/dist/cli/owed-reply-sync.d.ts +2 -0
  24. package/dist/cli/owed-reply-sync.js +28 -0
  25. package/dist/cli/owed-reply-sync.js.map +1 -0
  26. package/dist/flytebot/testing/fake.d.ts +33 -4
  27. package/dist/flytebot/testing/fake.js +100 -3
  28. package/dist/flytebot/testing/fake.js.map +1 -1
  29. package/dist/flytebot/testing/index.d.ts +1 -1
  30. package/package.json +8 -3
  31. package/prisma/fragments/owed-reply.meta.json +4 -0
  32. package/prisma/fragments/owed-reply.prisma +72 -0
  33. package/prisma/migrations/0006_app_kit_owed_reply_init/migration.sql +63 -0
  34. package/prisma/migrations/0007_app_kit_owed_reply_holds/migration.sql +39 -0
  35. package/prisma/migrations/manifest.json +14 -0
package/README.md CHANGED
@@ -1051,6 +1051,29 @@ fake.deliveries; // [{ runId, url, httpStatus, error }]
1051
1051
  await fake.redeliver(runId); // at-least-once: the same terminal run again
1052
1052
  ```
1053
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
+ // An ack, then an app tool that holds the reply, then the run completes with the reply held; a later run is the wake that answers it:
1068
+ fake.scriptRun({ toolCalls: [call("ack", "On it."), { server: "sms-app-chat", tool: "start_query", arguments: {} }] });
1069
+ // A reply whose fields your accept refuses is a tool error in the run's events, and the reply stays owed:
1070
+ fake.scriptRun({ toolCalls: [{ ...call("reply", "Here."), arguments: { to: owedReplyId, phase: "reply", text: "Here.", proposal: badProposal } }] });
1071
+ fake.scriptRun({}); // calls nothing
1072
+ await fake.scriptsSettled(); // every scripted call sequence has ended its run
1073
+ ```
1074
+
1075
+ A call that cannot be made (no URL or bearer for its server) ends the run `error` with `mcp_unavailable`.
1076
+
1054
1077
  ### Serving your tools to Flytebot (`@flytedesk/app-kit/chat/tools`)
1055
1078
 
1056
1079
  `createRemoteMcpPlugin` serves your `AppRegisteredTool`s (and `createReplyTool`)
@@ -1085,6 +1108,178 @@ A handler that throws is logged and reported to the agent as a tool error (`Tool
1085
1108
  failed.`); a validation error you return as `{ ok: false, retryable: false }` is read by the
1086
1109
  model, and a retryable one is a JSON-RPC error.
1087
1110
 
1111
+ ### Owed replies (`@flytedesk/app-kit/chat/owed-replies`)
1112
+
1113
+ An app whose chat agent runs through Flytebot answers every message with one flow, the same as
1114
+ Flytebot's own chat. A person's message is *owed* an answer. The agent answers it through an MCP
1115
+ `reply` tool with `{ to, phase, text }`: first a short acknowledgement (`phase: "ack"`), then the full
1116
+ answer (`phase: "reply"`), which replaces it. A message is never left without an answer: when a run ends
1117
+ without one, the owed reply fails with a fixed line the person sees. It replaces `createReplyTool`'s
1118
+ progress/final flow; an app that adopts it removes its `createReplyTool` use in the same change
1119
+ (`createReplyTool`, `parseReplyArguments` and `ChatReplyPayload` stay until every app has moved).
1120
+
1121
+ **1. Install the tables.** Run `npx owed-reply-sync init`. It installs the fragment's three models
1122
+ (`OwedReply`, `OwedReplyDispatch`, `OwedReplyHold`, tables `app_kit_owed_reply`, `app_kit_owed_reply_dispatch` and
1123
+ `app_kit_owed_reply_hold`) into your
1124
+ `schema.prisma`. It follows `auth-sync`'s Prisma-migrate mode, because every app that adopts the flow
1125
+ deploys with Prisma migrate: it writes no SQL and runs none. Create the tables with
1126
+ `npx prisma migrate dev --create-only`, append the CHECK statements `init` prints (Prisma's schema language
1127
+ has none), keep the migration one atomic `DO $$ ... $$` block with `SET LOCAL lock_timeout` if it has more
1128
+ than one statement, then apply it. An app that does not use Prisma migrate gets the raw SQL of
1129
+ `0006_app_kit_owed_reply_init` and `0007_app_kit_owed_reply_holds` run for it. `npx owed-reply-sync apply`
1130
+ brings an installed fragment up to date: an app locked at fragment 1.0.0 is shown the SQL of 0007 (the
1131
+ `reply_payload` column and the hold table), to put in its own `prisma migrate dev` migration as one atomic block.
1132
+
1133
+ **2. Make the store.** The store reads and writes through your own generated Prisma client (a structural
1134
+ type: tagged-template `$queryRaw`/`$executeRaw` and an interactive `$transaction`; no new dependency):
1135
+
1136
+ ```ts
1137
+ const owedReplies = createOwedReplyStore({
1138
+ client: prisma,
1139
+ // Writes your own chat message for an owed reply that changed. It runs in the write's own
1140
+ // transaction (`tx` is your transaction client), so a throw undoes the write. `revision` rises on every
1141
+ // write: keep a projected message from going backwards.
1142
+ project: async (tx, reply) => upsertChatMessage(tx, reply.messageRef, shownText(reply), reply.revision),
1143
+ });
1144
+ ```
1145
+
1146
+ An owed reply's `state` is derived on every read, never stored: `sent` (no run has taken it), `taken`,
1147
+ `acked`, `answered` or `failed`. `held` is a flag on an unanswered one (see "Held replies"), and `replyPayload`
1148
+ is what the reply's own fields carried (see "Reply fields"). `shownText(reply)` is what the person's chat
1149
+ shows: the reply, else the failure line, else the acknowledgement.
1150
+
1151
+ **3. Use its three operations around a run.**
1152
+
1153
+ - `receiveMessage({ messageRef, conversationRef, personRef })` when the person's message arrives.
1154
+ Idempotent on `messageRef`: a resent message returns its existing owed reply and never makes a second.
1155
+ - `claimForDispatch(conversationRef, dispatchId)` when you ask Flytebot for a run. Use the run's dispatch id
1156
+ as its `idempotencyKey` in `runs.create`. It binds every `sent` owed reply of the conversation to that
1157
+ dispatch and returns them (give their ids to the agent in its task, as the `to` of its replies).
1158
+ Idempotent for the same dispatch id, so a retried request or a redelivered webhook never makes a second
1159
+ binding. A message that arrives while the run works stays `sent` for the next run.
1160
+ - `settle(dispatchId, end)` from your terminal webhook route (`verifyTerminalWebhook` gives the run;
1161
+ pass its `status`), and when Flytebot refused to create the run or the create never answered (`end` is
1162
+ then `not_started`). Every owed reply the dispatch left unanswered fails with one fixed line from
1163
+ `FAILURE_LINES`: `Stopped.` when the run was cancelled, `Flytebot finished without answering.` when it
1164
+ completed with no reply, one line each for `error`, `timeout`, `crash` and `not_started`. A run that
1165
+ `completed` leaves an owed reply a background job holds (see "Held replies"); any other end fails
1166
+ held ones too and ends their holds. It is idempotent: an answered or failed owed reply is untouched, and
1167
+ an owed reply a later dispatch (a wake) took is that run's, so a terminal redelivered for the earlier run
1168
+ changes nothing. It returns `{ waiting, released, cancelHolds }`: the conversation's remaining `sent` owed
1169
+ replies, its released held owed replies (see "Held replies"), and the hold refs of the failed owed replies
1170
+ whose job was still open, for you to cancel.
1171
+
1172
+ **What to do after `settle`**, in this order, once the run is over (so no run is live for the conversation):
1173
+
1174
+ 1. `waiting` is not empty: dispatch the next run for them (`claimForDispatch`, then `runs.create`).
1175
+ 2. Otherwise `released` is not empty: `claimWake(conversationRef, newDispatchId)` and start the wake run.
1176
+ 3. Otherwise nothing is due.
1177
+
1178
+ A message that arrived while the run worked is answered before a wake, and a wake's run never overlaps another
1179
+ run of the conversation. Do the same after `endHold` when no run is live (`endHold` answers the conversation).
1180
+ Cancel every ref in `cancelHolds`.
1181
+
1182
+ `settle` and a late `reply` take the same row lock (`SELECT ... FOR UPDATE`) on the owed reply: a reply to
1183
+ a failed owed reply is refused with a tool error, and a `settle` after an answer changes nothing.
1184
+
1185
+ **4. Serve the tool.** `createOwedReplyPlugin` is `createRemoteMcpPlugin` with the `reply` tool for the
1186
+ run the bearer belongs to, and every result except a successful reply ending in one line that names the owed replies not yet answered:
1187
+
1188
+ ```ts
1189
+ await app.register(
1190
+ createOwedReplyPlugin({
1191
+ serverName: "sms-app-chat",
1192
+ store: owedReplies,
1193
+ // The bearer is the per-run bearer you sent in runs.create({ tools }). Resolve it to the run only
1194
+ // while that run is running; return null otherwise (401).
1195
+ authenticate: async (bearer) => findRunningRunByToken(bearer),
1196
+ dispatchId: (run) => run.dispatchId,
1197
+ tools: (run) => [/* your other tools */],
1198
+ }),
1199
+ { prefix: "/mcp/chat" },
1200
+ );
1201
+ ```
1202
+
1203
+ `reply` refuses a `to` that is not an owed reply of the run's own dispatch, a reply to a failed owed
1204
+ reply, and a second, different text for an answered one. Resending the same phase with the same text
1205
+ answers ok and changes nothing; an ack is allowed until the owed reply is answered, and a second ack
1206
+ replaces the first. Every successful result of the endpoint, your own tools' included, carries
1207
+ `_meta["flytebot/reply"] = { owed, unheld, reminder }`: `owed` counts the run's unanswered owed replies,
1208
+ `unheld` those no background job holds, and the reminder names the held ones. Name the tool in your Flytebot
1209
+ profile (`reply: { server: "sms-app-chat", tool: "reply" }`): its runner reads the state from any tool of the
1210
+ server, ends the run once `owed` is 0, and blocks the model's first stop while `unheld` is above 0.
1211
+ `createRemoteMcpPlugin`'s `annotateResult(context, call: { tool, ok })` option is what adds both: one call
1212
+ answers `{ notice, meta }`, so the line and the `_meta` describe one moment, and a throw fails the request
1213
+ instead of sending a result without them. A plugin without it returns results exactly as before. The fixed lines (the failure lines, the reminder, the owed-replies line,
1214
+ the refusals) are one module, `constants.ts`, exported from the subpath.
1215
+
1216
+ **5. Reply fields.** An app whose replies carry more than text (an audience proposal, a plan packet) gives
1217
+ `createOwedReplyPlugin` (or `createOwedReplyTool`) `replyFields: { properties, accept }`. The `properties` (JSON
1218
+ Schema properties, never `to`, `phase` or `text`) join the tool's input, allowed with phase `reply` only: fields
1219
+ on an acknowledgement are refused. `accept(tx, { owedReply, text, fields })` validates the packet, in the write's
1220
+ transaction under the owed reply's row lock, before the write (what it writes through `tx` commits or rolls back
1221
+ with the reply), and answers `{ ok: true, payload }` or `{ ok: false, message, retryable }`. A refusal writes
1222
+ nothing and comes back as a tool error. The `payload` (any JSON value; `null` stores none) is written with the
1223
+ reply to `reply_payload` (a CHECK keeps it from existing without `reply_text`) and reaches `project` as
1224
+ `reply.replyPayload`. Resending the same reply (same text) answers ok, changes nothing and does not run `accept`
1225
+ again. Without `replyFields` the tool takes `{ to, phase, text }` only.
1226
+
1227
+ ```ts
1228
+ createOwedReplyPlugin({
1229
+ // ...
1230
+ replyFields: {
1231
+ properties: { proposal: { type: "object", description: "The audience proposal." } },
1232
+ accept: async (tx, { fields }) => {
1233
+ const proposal = parseProposal(fields.proposal);
1234
+ return proposal === null
1235
+ ? { ok: false, message: "The proposal has no audience.", retryable: false }
1236
+ : { ok: true, payload: await saveProposal(tx, proposal) };
1237
+ },
1238
+ },
1239
+ });
1240
+ ```
1241
+
1242
+ **6. Held replies.** An agent that acknowledges, starts a background job (your own tool) and stops leaves its
1243
+ owed reply *held* instead of failing it, and a later wake run answers it. This is Flytebot's own rule.
1244
+
1245
+ - `hold(tx, { dispatchId, to?, holdRef })` from your tool, in the same transaction that inserts the job.
1246
+ It binds the job to an acknowledged, unanswered owed reply of the run (`to`, else its only unanswered one).
1247
+ It refuses with a fixed line (`HOLD_REFUSALS`, `REFUSALS`) when the run has none, several and no `to`, an
1248
+ owed reply that is not the run's, not yet acknowledged, answered or failed, or a `holdRef` already on
1249
+ another owed reply. The same `holdRef` for the same owed reply answers ok and changes nothing.
1250
+ - `endHold(holdRef)` when the job ends, whatever its outcome. Idempotent. It answers the owed reply's
1251
+ conversation (null for an unknown ref), so you can `claimWake` once its run is over.
1252
+ - An owed reply is held while it has an open hold or an ended hold not yet reported to a wake. A held one is
1253
+ acked, so `claimForDispatch` never takes it; a run that completes leaves it (`settle(..., "completed")`).
1254
+ - `claimWake(conversationRef, dispatchId)`, called when the conversation has no live run (after `settle`, and
1255
+ after `endHold`): binds the conversation's *released* held owed replies (acked, unanswered, no open hold, an
1256
+ ended hold not yet reported) to the new dispatch and marks those holds reported in the same transaction. It
1257
+ returns `{ replies, holds }`: the owed replies and the jobs whose outcomes the wake's task tells the agent. It is
1258
+ idempotent for one dispatch id. Start the wake run with that dispatch id as its `idempotencyKey`, as for any
1259
+ run; the agent answers through `reply`.
1260
+ - `abandonWake(conversationRef)` when no wake can run (the asker signed out): fails the released held owed
1261
+ replies with `SIGNED_OUT_LINE` and returns them.
1262
+
1263
+ `endHold` and `claimWake` take the same row lock, so a wake never misses a job that has just ended: whichever
1264
+ comes second sees the other. A claim that raced ahead of the end finds the job open; call `claimWake` again
1265
+ after `endHold`.
1266
+
1267
+ **7. Withdraw and stop.**
1268
+
1269
+ - `withdraw(dispatchId)` takes back a dispatch whose run Flytebot would not start (a `409 conversation_busy`) or
1270
+ that ended before any model call (`session_missing`): its owed replies are `sent` again (the running run's
1271
+ terminal dispatches them), and a wake's holds are untold again. It answers false, and changes nothing, for an
1272
+ unknown dispatch and for one whose owed replies were written since it was bound.
1273
+ - `stop(conversationRef)` for the person's Stop: fails every taken, acked or held unanswered owed reply of the
1274
+ conversation with `Stopped.` and returns `{ stopped, cancelHolds }`. Cancel the run and each hold ref's job; the
1275
+ run's later `settle` changes nothing.
1276
+ - `settle(dispatchId, "not_started")` ends a dispatch whose run Flytebot refused to create (a 4xx) or whose
1277
+ create never answered: every unanswered owed reply fails with `FAILURE_LINES.not_started`.
1278
+
1279
+ **8. Test it.** `createFakeFlytebot` scripts a run that acknowledges and replies through your real
1280
+ endpoint, one that holds a reply with your own tool and then stops, a wake run that answers it, and a reply
1281
+ whose fields your `accept` refuses; see "Testing against the fake".
1282
+
1088
1283
  ## Tests
1089
1284
 
1090
1285
  `npm run check` is the full gate: lint, typecheck, build, unit tests, integration tests
@@ -0,0 +1,47 @@
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
+ * How a dispatch ended: a run's terminal status, or `not_started` for a run Flytebot refused to
10
+ * create or whose create never answered (AK-85).
11
+ */
12
+ export type DispatchEnd = TerminalStatus | "not_started";
13
+ /**
14
+ * What a person sees in place of an answer when the run that took their message ended without
15
+ * answering it, by how the run ended. A run that completed without calling the reply tool is
16
+ * `completed`.
17
+ */
18
+ export declare const FAILURE_LINES: Readonly<Record<DispatchEnd, string>>;
19
+ /** What an owed reply says when its asker's session ended before the wake that answers it could run. */
20
+ export declare const SIGNED_OUT_LINE = "You signed out before the answer was ready; ask again.";
21
+ /**
22
+ * The reminder a reply result carries under `_meta["flytebot/reply"]` while an answer is still owed.
23
+ * `unheld` of the `owed` replies are the ones no background work holds: the run must answer those; a
24
+ * held one is answered by the wake run when its work finishes.
25
+ */
26
+ export declare function owedReminder(toolName: string, owed: number, unheld: number): string;
27
+ /** The line that ends every result of an endpoint that names its owed replies; null when none is owed. */
28
+ export declare function owedRepliesLine(toolName: string, replies: readonly {
29
+ id: string;
30
+ held: boolean;
31
+ }[]): string | null;
32
+ /** What the model reads after a successful call of the reply tool. */
33
+ export declare function deliveredText(toolName: string, phase: "ack" | "reply", owed: number, unheld: number): string;
34
+ /** The refusals of the reply tool, as the model reads them. */
35
+ export declare const REFUSALS: {
36
+ readonly notOwed: "`to` is not an owed reply of this run.";
37
+ readonly failed: "That owed reply already ended without an answer, so it takes no more replies.";
38
+ readonly answered: "That owed reply is already answered.";
39
+ readonly fieldsOnAck: "Reply fields are sent with phase \"reply\" only, not with an acknowledgement.";
40
+ };
41
+ /** The refusals of `hold`, as the app's tool reads them. */
42
+ export declare const HOLD_REFUSALS: {
43
+ readonly nothingToHold: "This run has no unanswered message to hold.";
44
+ readonly ambiguous: "This run has several unanswered messages; say which one the background work is for with `to`.";
45
+ readonly notAcknowledged: "Acknowledge that message first (phase \"ack\"), then start the background work.";
46
+ readonly refInUse: "That hold reference already belongs to another message.";
47
+ };
@@ -0,0 +1,71 @@
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
+ not_started: "Flytebot could not start the run.",
19
+ };
20
+ /** What an owed reply says when its asker's session ended before the wake that answers it could run. */
21
+ export const SIGNED_OUT_LINE = "You signed out before the answer was ready; ask again.";
22
+ const messages = (count) => `${count} message${count === 1 ? "" : "s"}`;
23
+ const waits = (count) => (count === 1 ? "waits" : "wait");
24
+ /**
25
+ * The reminder a reply result carries under `_meta["flytebot/reply"]` while an answer is still owed.
26
+ * `unheld` of the `owed` replies are the ones no background work holds: the run must answer those; a
27
+ * held one is answered by the wake run when its work finishes.
28
+ */
29
+ export function owedReminder(toolName, owed, unheld) {
30
+ if (owed === 0)
31
+ return "Every reply is answered.";
32
+ const held = owed - unheld;
33
+ if (unheld === 0) {
34
+ return `${messages(held)} ${waits(held)} for the background work you started and will be answered when it finishes. You may stop now.`;
35
+ }
36
+ const answer = `You still owe an answer to ${messages(unheld)}. Send each through ${toolName} (phase "reply") before you stop.`;
37
+ return held === 0 ? answer : `${answer} ${held} more ${held === 1 ? "message waits" : "messages wait"} for the background work you started.`;
38
+ }
39
+ /** The line that ends every result of an endpoint that names its owed replies; null when none is owed. */
40
+ export function owedRepliesLine(toolName, replies) {
41
+ const open = replies.filter((reply) => !reply.held).map((reply) => reply.id);
42
+ const held = replies.filter((reply) => reply.held).map((reply) => reply.id);
43
+ const parts = [
44
+ ...(open.length === 0 ? [] : [`Owed replies not yet answered: ${open.join(", ")}. Answer each with ${toolName} (phase "reply").`]),
45
+ ...(held.length === 0 ? [] : [`Held for the background work you started, answered when it finishes: ${held.join(", ")}.`]),
46
+ ];
47
+ return parts.length === 0 ? null : parts.join(" ");
48
+ }
49
+ /** What the model reads after a successful call of the reply tool. */
50
+ export function deliveredText(toolName, phase, owed, unheld) {
51
+ if (phase === "ack")
52
+ return "Acknowledged. Continue with the work, then send your reply.";
53
+ return owed === 0
54
+ ? "Delivered. Every reply is answered: do not send anything further."
55
+ : `Delivered. ${owedReminder(toolName, owed, unheld)}`;
56
+ }
57
+ /** The refusals of the reply tool, as the model reads them. */
58
+ export const REFUSALS = {
59
+ notOwed: "`to` is not an owed reply of this run.",
60
+ failed: "That owed reply already ended without an answer, so it takes no more replies.",
61
+ answered: "That owed reply is already answered.",
62
+ fieldsOnAck: "Reply fields are sent with phase \"reply\" only, not with an acknowledgement.",
63
+ };
64
+ /** The refusals of `hold`, as the app's tool reads them. */
65
+ export const HOLD_REFUSALS = {
66
+ nothingToHold: "This run has no unanswered message to hold.",
67
+ ambiguous: "This run has several unanswered messages; say which one the background work is for with `to`.",
68
+ notAcknowledged: "Acknowledge that message first (phase \"ack\"), then start the background work.",
69
+ refInUse: "That hold reference already belongs to another message.",
70
+ };
71
+ //# 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;AAQ/C;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAA0C;IAClE,SAAS,EAAE,UAAU;IACrB,SAAS,EAAE,sCAAsC;IACjD,KAAK,EAAE,oCAAoC;IAC3C,OAAO,EAAE,uCAAuC;IAChD,KAAK,EAAE,gCAAgC;IACvC,WAAW,EAAE,mCAAmC;CACjD,CAAC;AAEF,wGAAwG;AACxG,MAAM,CAAC,MAAM,eAAe,GAAG,wDAAwD,CAAC;AAExF,MAAM,QAAQ,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,GAAG,KAAK,WAAW,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AACxF,MAAM,KAAK,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,CAAC,KAAK,KAA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CAAkC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,sBAAsB,QAAQ,mBAAmB,CAAC,CAAC;QAClI,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,wEAAwE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KAC3H,CAAC;IACF,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrD,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,KAAsB,EAAE,IAAY,EAAE,MAAc;IAClG,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,EAAE,MAAM,CAAC,EAAE,CAAC;AAC3D,CAAC;AAED,+DAA+D;AAC/D,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,OAAO,EAAE,wCAAwC;IACjD,MAAM,EAAE,+EAA+E;IACvF,QAAQ,EAAE,sCAAsC;IAChD,WAAW,EAAE,+EAA+E;CACpF,CAAC;AAEX,4DAA4D;AAC5D,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,aAAa,EAAE,6CAA6C;IAC5D,SAAS,EAAE,+FAA+F;IAC1G,eAAe,EAAE,iFAAiF;IAClG,QAAQ,EAAE,yDAAyD;CAC3D,CAAC"}
@@ -0,0 +1,16 @@
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, HOLD_REFUSALS, REFUSALS, SIGNED_OUT_LINE, deliveredText, owedRepliesLine, owedReminder, } from "./constants.js";
8
+ export type { DispatchEnd } from "./constants.js";
9
+ export { shownText } from "./state.js";
10
+ export type { OwedReply, OwedReplyState } from "./state.js";
11
+ export { createOwedReplyStore } from "./store.js";
12
+ export type { AcceptReply, AcceptReplyResult, ClaimedWake, HoldInput, HoldResult, OwedReplyClient, OwedReplyStore, OwedReplyStoreOptions, OwedReplyTransaction, ReceiveMessageInput, SettleResult, StopResult, WriteReplyInput, WriteReplyResult, } from "./store.js";
13
+ export { createOwedReplyTool } from "./tool.js";
14
+ export type { OwedReplyFields, OwedReplyToolOptions } from "./tool.js";
15
+ export { createOwedReplyPlugin } from "./plugin.js";
16
+ 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, HOLD_REFUSALS, REFUSALS, SIGNED_OUT_LINE, 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,EACL,uBAAuB,EACvB,aAAa,EACb,aAAa,EACb,QAAQ,EACR,eAAe,EACf,aAAa,EACb,eAAe,EACf,YAAY,GACb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAiBlD,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,36 @@
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
5
+ * answered, and every successful result of the app's own tools carrying the run's owed-reply
6
+ * state under `_meta["flytebot/reply"]` (AK-85), so Flytebot's runner reads it from any tool.
7
+ *
8
+ * await app.register(
9
+ * createOwedReplyPlugin({
10
+ * serverName: "sms-app-chat",
11
+ * store,
12
+ * authenticate: async (bearer) => findRunningRunByToken(bearer), // run or null
13
+ * dispatchId: (run) => run.dispatchId,
14
+ * tools: (run) => [...the app's other tools],
15
+ * }),
16
+ * { prefix: "/mcp/chat" },
17
+ * );
18
+ */
19
+ import type { FastifyPluginAsync } from "fastify";
20
+ import { type RemoteMcpPluginOptions } from "../tools/index.js";
21
+ import type { AppRegisteredTool } from "../types.js";
22
+ import type { OwedReplyStore, OwedReplyTransaction } from "./store.js";
23
+ import { type OwedReplyFields } from "./tool.js";
24
+ export interface OwedReplyPluginOptions<Context, Tx extends OwedReplyTransaction = OwedReplyTransaction> extends Pick<RemoteMcpPluginOptions<Context>, "serverName" | "serverVersion" | "authenticate"> {
25
+ store: OwedReplyStore<Tx>;
26
+ /** The app's reply fields (see `OwedReplyFields`); left out, the reply tool takes `{to, phase, text}` only. */
27
+ replyFields?: OwedReplyFields<Tx>;
28
+ /** The dispatch id of the run a resolved context is: the Idempotency-Key the app sent in `runs.create`. */
29
+ dispatchId: (context: Context) => string;
30
+ /** The other tools the run may call, besides the reply tool. */
31
+ tools?: (context: Context) => AppRegisteredTool[];
32
+ /** The reply tool's name. Default `reply`; the profile's `reply: {server, tool}` names it. */
33
+ replyToolName?: string;
34
+ replyToolDescription?: string;
35
+ }
36
+ export declare function createOwedReplyPlugin<Context, Tx extends OwedReplyTransaction = OwedReplyTransaction>(options: OwedReplyPluginOptions<Context, Tx>): FastifyPluginAsync;
@@ -0,0 +1,33 @@
1
+ import { REPLY_META_KEY } from "../mcp-protocol.js";
2
+ import { createRemoteMcpPlugin } from "../tools/index.js";
3
+ import { DEFAULT_REPLY_TOOL_NAME, owedReminder, owedRepliesLine } from "./constants.js";
4
+ import { createOwedReplyTool } from "./tool.js";
5
+ export function createOwedReplyPlugin(options) {
6
+ const toolName = options.replyToolName ?? DEFAULT_REPLY_TOOL_NAME;
7
+ return createRemoteMcpPlugin({
8
+ serverName: options.serverName,
9
+ serverVersion: options.serverVersion,
10
+ authenticate: options.authenticate,
11
+ tools: (context) => [
12
+ createOwedReplyTool({
13
+ store: options.store,
14
+ replyFields: options.replyFields,
15
+ dispatchId: options.dispatchId(context),
16
+ name: toolName,
17
+ description: options.replyToolDescription,
18
+ }),
19
+ ...(options.tools?.(context) ?? []),
20
+ ],
21
+ // The reply tool's own success reports its state from the write, so it takes neither the line nor a
22
+ // second read. Every other result is annotated from one read, so the line and `_meta` agree.
23
+ annotateResult: async (context, call) => {
24
+ if (call.tool === toolName && call.ok)
25
+ return { notice: null, meta: null };
26
+ const unanswered = await options.store.unansweredOf(options.dispatchId(context));
27
+ const unheld = unanswered.filter((reply) => !reply.held).length;
28
+ const meta = { owed: unanswered.length, unheld, reminder: owedReminder(toolName, unanswered.length, unheld) };
29
+ return { notice: owedRepliesLine(toolName, unanswered), meta: call.ok ? { [REPLY_META_KEY]: meta } : null };
30
+ },
31
+ });
32
+ }
33
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/plugin.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,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC;YAChE,MAAM,IAAI,GAAc,EAAE,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;YACzH,OAAO,EAAE,MAAM,EAAE,eAAe,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAC9G,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,56 @@
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
+ * Held (AK-85) is not a state but a flag on an unanswered one: a background job the app started
10
+ * for it is still working (an open hold), or ended and not yet told to a wake run (an ended hold
11
+ * not yet reported). A held owed reply is acked, and a run that completes leaves it unanswered.
12
+ */
13
+ export type OwedReplyState = "sent" | "taken" | "acked" | "answered" | "failed";
14
+ /** One person's message that is owed an answer, as the store reads it. */
15
+ export interface OwedReply {
16
+ id: string;
17
+ /** The app's own id for the person's message. */
18
+ messageRef: string;
19
+ conversationRef: string;
20
+ personRef: string;
21
+ ackText: string | null;
22
+ replyText: string | null;
23
+ failure: string | null;
24
+ /** What the app's reply fields carried with the reply (`accept`'s payload); null without one. */
25
+ replyPayload: unknown;
26
+ /** A background job holds this owed reply open; see the module comment. */
27
+ held: boolean;
28
+ /** Raised on every write, so an app's projected chat message can tell a stale write. */
29
+ revision: number;
30
+ state: OwedReplyState;
31
+ createdAt: Date;
32
+ ackedAt: Date | null;
33
+ answeredAt: Date | null;
34
+ failedAt: Date | null;
35
+ }
36
+ /** What the person's chat shows for an owed reply: its answer, else its failure line, else its acknowledgement, else nothing. */
37
+ export declare function shownText(reply: Pick<OwedReply, "replyText" | "failure" | "ackText">): string | null;
38
+ /** The columns of one owed reply row as the raw query aliases them. */
39
+ export interface OwedReplyRow {
40
+ id: string;
41
+ messageRef: string;
42
+ conversationRef: string;
43
+ personRef: string;
44
+ ackText: string | null;
45
+ replyText: string | null;
46
+ failure: string | null;
47
+ replyPayload: unknown;
48
+ held: boolean;
49
+ revision: number;
50
+ taken: boolean;
51
+ createdAt: Date;
52
+ ackedAt: Date | null;
53
+ answeredAt: Date | null;
54
+ failedAt: Date | null;
55
+ }
56
+ export declare function owedReplyFromRow(row: OwedReplyRow): OwedReply;
@@ -0,0 +1,33 @@
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
+ replyPayload: row.replyPayload,
24
+ held: row.held,
25
+ revision: row.revision,
26
+ state: deriveState(row),
27
+ createdAt: row.createdAt,
28
+ ackedAt: row.ackedAt,
29
+ answeredAt: row.answeredAt,
30
+ failedAt: row.failedAt,
31
+ };
32
+ }
33
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/chat/owed-replies/state.ts"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