@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
@@ -0,0 +1,155 @@
1
+ import { type DispatchEnd } from "./constants.js";
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
+ /**
31
+ * What an app's `accept` answers for a reply that carries its own fields: the payload to store
32
+ * with the reply (any JSON value; `null` or `undefined` stores none), or a refusal the model reads as a tool
33
+ * error (`retryable` as for `ChatToolCallResult`).
34
+ */
35
+ export type AcceptReplyResult = {
36
+ ok: true;
37
+ payload: unknown;
38
+ } | {
39
+ ok: false;
40
+ message: string;
41
+ retryable: boolean;
42
+ };
43
+ /**
44
+ * An app's validation of its reply fields. It runs in the write's transaction under the owed
45
+ * reply's row lock, before the write, so what it writes through `tx` commits or fails with the
46
+ * reply. It does not run for a resend of a reply already written.
47
+ */
48
+ export type AcceptReply<Tx extends OwedReplyTransaction> = (tx: Tx, input: {
49
+ owedReply: OwedReply;
50
+ text: string;
51
+ fields: Record<string, unknown>;
52
+ }) => Promise<AcceptReplyResult>;
53
+ export interface WriteReplyInput<Tx extends OwedReplyTransaction = OwedReplyTransaction> {
54
+ /** The dispatch id of the run writing: the Idempotency-Key the app sent in `runs.create`. */
55
+ dispatchId: string;
56
+ /** The owed reply written to. */
57
+ to: string;
58
+ phase: "ack" | "reply";
59
+ text: string;
60
+ /** The app's reply fields and its validation of them; only with phase `reply`. */
61
+ fields?: {
62
+ values: Record<string, unknown>;
63
+ accept: AcceptReply<Tx>;
64
+ };
65
+ }
66
+ export type WriteReplyResult =
67
+ /** `owed` counts the run's owed replies still unanswered after this write, `unheld` those no hold holds. */
68
+ {
69
+ ok: true;
70
+ owed: number;
71
+ unheld: number;
72
+ } | {
73
+ ok: false;
74
+ message: string;
75
+ retryable: boolean;
76
+ };
77
+ export interface HoldInput {
78
+ /** The dispatch id of the run the background job is started in. */
79
+ dispatchId: string;
80
+ /** The owed reply the job is for; left out, the run's only unanswered one. */
81
+ to?: string;
82
+ /** The app's own id for the job; `endHold` takes it. */
83
+ holdRef: string;
84
+ }
85
+ export type HoldResult = {
86
+ ok: true;
87
+ owedReplyId: string;
88
+ } | {
89
+ ok: false;
90
+ message: string;
91
+ };
92
+ /** The result of ending a dispatch: what is waiting for a run, and the jobs the app must stop. */
93
+ export interface SettleResult {
94
+ /** The conversation's remaining `sent` owed replies; when there are any, dispatch the next run for them. */
95
+ waiting: OwedReply[];
96
+ /**
97
+ * The conversation's released held owed replies (acked, no open hold, an ended hold not yet reported):
98
+ * when nothing is `waiting` and no run is live, `claimWake` them.
99
+ */
100
+ released: OwedReply[];
101
+ /** Holds of failed owed replies that were still open: cancel each job. */
102
+ cancelHolds: string[];
103
+ }
104
+ export interface StopResult {
105
+ stopped: OwedReply[];
106
+ /** Holds of stopped owed replies that were still open: cancel each job. */
107
+ cancelHolds: string[];
108
+ }
109
+ export interface ClaimedWake {
110
+ /** The owed replies bound to the wake dispatch, oldest first. */
111
+ replies: OwedReply[];
112
+ /** The holds this wake reports to its run (the jobs whose outcomes its task tells), by owed reply. */
113
+ holds: {
114
+ holdRef: string;
115
+ owedReplyId: string;
116
+ }[];
117
+ }
118
+ export interface OwedReplyStore<Tx extends OwedReplyTransaction = OwedReplyTransaction> {
119
+ receiveMessage(input: ReceiveMessageInput): Promise<OwedReply>;
120
+ claimForDispatch(conversationRef: string, dispatchId: string): Promise<OwedReply[]>;
121
+ writeReply(input: WriteReplyInput<Tx>): Promise<WriteReplyResult>;
122
+ /**
123
+ * Binds a background job to an acknowledged, unanswered owed reply of the run, in the app's
124
+ * own transaction `tx` (so the job row and the hold commit together). Refused with a fixed
125
+ * line otherwise. The same `holdRef` for the same owed reply answers ok and changes nothing.
126
+ */
127
+ hold(tx: OwedReplyTransaction, input: HoldInput): Promise<HoldResult>;
128
+ /**
129
+ * The job ended. Idempotent; an ended hold changes nothing and an unknown one answers null.
130
+ * Answers the conversation of the held owed reply, so the app can `claimWake` it once its run is over.
131
+ */
132
+ endHold(holdRef: string): Promise<{
133
+ conversationRef: string;
134
+ } | null>;
135
+ /** The run ended: `completed` leaves held owed replies held; any other end fails every unanswered one. */
136
+ settle(dispatchId: string, end: DispatchEnd): Promise<SettleResult>;
137
+ /**
138
+ * Called when the conversation has no live run: binds its released held owed replies to
139
+ * `dispatchId` and reports their holds. Idempotent for one dispatch id.
140
+ */
141
+ claimWake(conversationRef: string, dispatchId: string): Promise<ClaimedWake>;
142
+ /** No wake can run (the asker signed out): fails the conversation's released held owed replies. */
143
+ abandonWake(conversationRef: string): Promise<OwedReply[]>;
144
+ /**
145
+ * Takes back a dispatch whose replies have no write yet (Flytebot answered 409 conversation_busy, or
146
+ * the run ended before any model call): its owed replies are `sent` again, a wake's holds unreported
147
+ * again. False when the dispatch is unknown or any of its replies was written since.
148
+ */
149
+ withdraw(dispatchId: string): Promise<boolean>;
150
+ /** The person's Stop: fails every taken, acked or held unanswered owed reply of the conversation. */
151
+ stop(conversationRef: string): Promise<StopResult>;
152
+ /** The owed replies of a run that are neither answered nor failed, oldest first. */
153
+ unansweredOf(dispatchId: string): Promise<OwedReply[]>;
154
+ }
155
+ export declare function createOwedReplyStore<Tx extends OwedReplyTransaction>(options: OwedReplyStoreOptions<Tx>): OwedReplyStore<Tx>;
@@ -0,0 +1,420 @@
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 these 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, or a run that never started);
12
+ * every owed reply it left unanswered fails with one fixed line, except
13
+ * a held one when the run completed
14
+ * withdraw Flytebot would not start the run yet; the dispatch is taken back
15
+ * stop the person stopped the conversation; every unanswered reply fails
16
+ * and `writeReply`, which the reply tool calls (see tool.ts).
17
+ *
18
+ * Held replies (AK-85, the rules of Flytebot's own core, `owedReplyStore.ts` and
19
+ * `replyDispatchStore.ts`). A background job the app starts for an acknowledged owed reply is a
20
+ * hold (`hold`, `endHold`): a run that completes leaves the owed reply unanswered, acked and
21
+ * held, instead of failing it. When the job ends, `claimWake` binds the released owed replies to
22
+ * a new dispatch, whose run answers them; `abandonWake` fails them when no wake can run. Held is
23
+ * derived on every read: a hold not yet reported to a wake (open, or ended and unreported).
24
+ *
25
+ * Every write runs in one transaction under the owed reply's row lock, raises `revision` and
26
+ * calls the app's projector (`project`, which writes its own chat message) in that same
27
+ * transaction. `settle` and a late reply therefore serialise on the same row: a reply to a
28
+ * failed owed reply is refused, and a settle after an answer changes nothing. Every operation
29
+ * that takes several rows locks them in id order, so none deadlocks another.
30
+ *
31
+ * The store talks to the app's own Prisma client through `OwedReplyClient`, a structural type
32
+ * (a generated client satisfies it, as for `PrismaAuthStore`): tagged-template raw SQL and an
33
+ * interactive transaction. It adds no dependency, and SQL is the only way to take
34
+ * `SELECT ... FOR UPDATE`.
35
+ */
36
+ import { randomUUID } from "node:crypto";
37
+ import { FAILURE_LINES, HOLD_REFUSALS, REFUSALS, SIGNED_OUT_LINE } from "./constants.js";
38
+ import { owedReplyFromRow } from "./state.js";
39
+ /**
40
+ * Options of every transaction the store opens: `timeout` bounds the transaction's own work once
41
+ * started, `maxWait` how long Prisma queues for a free pooled connection, so a pool under
42
+ * contention fails fast (Prisma's P2028) instead of queueing writes behind a stuck holder.
43
+ */
44
+ const TRANSACTION_OPTIONS = { timeout: 15_000, maxWait: 5_000 };
45
+ /** Thrown inside the write's transaction to roll it back when the app's `accept` refuses the reply. */
46
+ class ReplyRefused extends Error {
47
+ refusal;
48
+ constructor(refusal) {
49
+ super(refusal.message);
50
+ this.refusal = refusal;
51
+ }
52
+ }
53
+ /** The ids a query found. */
54
+ async function idsOf(rows) {
55
+ return (await rows).map((row) => row.id);
56
+ }
57
+ const byCreation = (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1);
58
+ export function createOwedReplyStore(options) {
59
+ const { client, project } = options;
60
+ /** The one read of owed reply rows; every query below only finds ids. */
61
+ async function load(db, ids) {
62
+ if (ids.length === 0)
63
+ return [];
64
+ const rows = await db.$queryRaw `
65
+ SELECT r."id", r."message_ref" AS "messageRef", r."conversation_ref" AS "conversationRef",
66
+ r."person_ref" AS "personRef", r."ack_text" AS "ackText", r."reply_text" AS "replyText",
67
+ r."reply_payload" AS "replyPayload", r."failure", r."revision", r."created_at" AS "createdAt",
68
+ r."acked_at" AS "ackedAt", r."answered_at" AS "answeredAt", r."failed_at" AS "failedAt",
69
+ EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id") AS "taken",
70
+ (r."reply_text" IS NULL AND r."failure" IS NULL AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_hold" h
71
+ WHERE h."owed_reply_id" = r."id" AND h."reported_at" IS NULL)) AS "held"
72
+ FROM "app_kit_owed_reply" r
73
+ WHERE r."id" = ANY(${ids}::text[])`;
74
+ return rows.map(owedReplyFromRow).sort(byCreation);
75
+ }
76
+ async function loadOne(db, id) {
77
+ const [reply] = await load(db, [id]);
78
+ if (reply === undefined)
79
+ throw new Error(`owed reply ${id} vanished inside its own transaction`);
80
+ return reply;
81
+ }
82
+ /** Counts the run's owed replies that are neither answered nor failed, and of those the ones no hold holds. */
83
+ async function owedState(db, dispatchId) {
84
+ const [row] = await db.$queryRaw `
85
+ SELECT count(*)::int AS "owed",
86
+ (count(*) FILTER (WHERE NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_hold" h
87
+ WHERE h."owed_reply_id" = r."id" AND h."reported_at" IS NULL)))::int AS "unheld"
88
+ FROM "app_kit_owed_reply_dispatch" d
89
+ JOIN "app_kit_owed_reply" r ON r."id" = d."owed_reply_id"
90
+ WHERE d."dispatch_id" = ${dispatchId} AND r."reply_text" IS NULL AND r."failure" IS NULL`;
91
+ return { owed: row?.owed ?? 0, unheld: row?.unheld ?? 0 };
92
+ }
93
+ /** Locks the conversation's unanswered owed replies, in id order, and answers their ids. */
94
+ async function lockOpenOfConversation(tx, conversationRef) {
95
+ return idsOf(tx.$queryRaw `
96
+ SELECT "id" FROM "app_kit_owed_reply"
97
+ WHERE "conversation_ref" = ${conversationRef} AND "reply_text" IS NULL AND "failure" IS NULL
98
+ ORDER BY "id" FOR UPDATE`);
99
+ }
100
+ /** The ids of a dispatch's bindings. */
101
+ async function boundTo(tx, dispatchId) {
102
+ return idsOf(tx.$queryRaw `
103
+ SELECT "owed_reply_id" AS "id" FROM "app_kit_owed_reply_dispatch" WHERE "dispatch_id" = ${dispatchId}`);
104
+ }
105
+ /**
106
+ * Of unanswered owed replies, the released held ones: acked, no open hold, an ended hold not yet
107
+ * reported. A caller that acts on the result holds the rows' locks (`claimWake`, `abandonWake`);
108
+ * `settle` reads without them, so what it reports is advisory and `claimWake` decides again under its own lock.
109
+ */
110
+ async function releasedAmong(tx, ids) {
111
+ if (ids.length === 0)
112
+ return [];
113
+ return idsOf(tx.$queryRaw `
114
+ SELECT r."id" FROM "app_kit_owed_reply" r
115
+ WHERE r."id" = ANY(${ids}::text[]) AND r."ack_text" IS NOT NULL
116
+ AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_hold" h
117
+ WHERE h."owed_reply_id" = r."id" AND h."ended_at" IS NULL)
118
+ AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_hold" h
119
+ WHERE h."owed_reply_id" = r."id" AND h."ended_at" IS NOT NULL AND h."reported_at" IS NULL)
120
+ ORDER BY r."id"`);
121
+ }
122
+ /**
123
+ * Fails locked, unanswered owed replies with `line`: their holds end and are reported (an owed
124
+ * reply that is gone has nothing to wake), and each failure is projected. Answers the jobs that
125
+ * were still open, which the app must cancel.
126
+ */
127
+ async function failLocked(tx, ids, line) {
128
+ if (ids.length === 0)
129
+ return { failed: [], cancelHolds: [] };
130
+ const open = await tx.$queryRaw `
131
+ SELECT "hold_ref" AS "holdRef" FROM "app_kit_owed_reply_hold"
132
+ WHERE "owed_reply_id" = ANY(${ids}::text[]) AND "ended_at" IS NULL ORDER BY "hold_ref"`;
133
+ await tx.$executeRaw `
134
+ UPDATE "app_kit_owed_reply_hold"
135
+ SET "ended_at" = COALESCE("ended_at", CURRENT_TIMESTAMP), "reported_at" = CURRENT_TIMESTAMP
136
+ WHERE "owed_reply_id" = ANY(${ids}::text[]) AND "reported_at" IS NULL`;
137
+ await tx.$executeRaw `
138
+ UPDATE "app_kit_owed_reply"
139
+ SET "failure" = ${line}, "failed_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
140
+ WHERE "id" = ANY(${ids}::text[])`;
141
+ const failed = await load(tx, ids);
142
+ for (const reply of failed)
143
+ await project(tx, reply);
144
+ return { failed, cancelHolds: open.map((row) => row.holdRef) };
145
+ }
146
+ async function writeReplyIn(input) {
147
+ return client.$transaction(async (tx) => {
148
+ const refuse = (message) => ({ ok: false, message, retryable: false });
149
+ const [locked] = await tx.$queryRaw `
150
+ SELECT r."id" FROM "app_kit_owed_reply" r
151
+ WHERE r."id" = ${input.to}
152
+ AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
153
+ WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${input.dispatchId})
154
+ FOR UPDATE OF r`;
155
+ if (locked === undefined)
156
+ return refuse(REFUSALS.notOwed);
157
+ const current = await loadOne(tx, locked.id);
158
+ if (current.state === "failed")
159
+ return refuse(REFUSALS.failed);
160
+ const sameText = input.phase === "ack" ? current.ackText : current.replyText;
161
+ if (sameText === input.text)
162
+ return { ok: true, ...(await owedState(tx, input.dispatchId)) };
163
+ if (current.state === "answered")
164
+ return refuse(REFUSALS.answered);
165
+ if (input.phase === "ack") {
166
+ await tx.$executeRaw `
167
+ UPDATE "app_kit_owed_reply"
168
+ SET "ack_text" = ${input.text}, "acked_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
169
+ WHERE "id" = ${current.id}`;
170
+ }
171
+ else {
172
+ // The app validates its own fields (and may write its own rows) here, in this transaction under
173
+ // the row lock: a refusal rolls everything back, what accept wrote included.
174
+ let payload = null;
175
+ if (input.fields !== undefined) {
176
+ const accepted = await input.fields.accept(tx, {
177
+ owedReply: current,
178
+ text: input.text,
179
+ fields: input.fields.values,
180
+ });
181
+ if (!accepted.ok)
182
+ throw new ReplyRefused({ ok: false, message: accepted.message, retryable: accepted.retryable });
183
+ payload = accepted.payload === null || accepted.payload === undefined ? null : JSON.stringify(accepted.payload);
184
+ }
185
+ await tx.$executeRaw `
186
+ UPDATE "app_kit_owed_reply"
187
+ SET "reply_text" = ${input.text}, "reply_payload" = ${payload}::jsonb,
188
+ "answered_at" = CURRENT_TIMESTAMP, "revision" = "revision" + 1
189
+ WHERE "id" = ${current.id}`;
190
+ }
191
+ await project(tx, await loadOne(tx, current.id));
192
+ return { ok: true, ...(await owedState(tx, input.dispatchId)) };
193
+ }, TRANSACTION_OPTIONS);
194
+ }
195
+ return {
196
+ async receiveMessage(input) {
197
+ await client.$executeRaw `
198
+ INSERT INTO "app_kit_owed_reply" ("id", "message_ref", "conversation_ref", "person_ref")
199
+ VALUES (${randomUUID()}, ${input.messageRef}, ${input.conversationRef}, ${input.personRef})
200
+ ON CONFLICT ("message_ref") DO NOTHING`;
201
+ const [row] = await client.$queryRaw `
202
+ SELECT "id" FROM "app_kit_owed_reply" WHERE "message_ref" = ${input.messageRef}`;
203
+ if (row === undefined)
204
+ throw new Error(`owed reply for message ${input.messageRef} was not stored`);
205
+ return loadOne(client, row.id);
206
+ },
207
+ async claimForDispatch(conversationRef, dispatchId) {
208
+ return client.$transaction(async (tx) => {
209
+ // Lock the conversation's open owed replies first: a second claim for another run waits here,
210
+ // then (a new statement, a new snapshot) sees the first claim's bindings and binds nothing twice.
211
+ const open = await lockOpenOfConversation(tx, conversationRef);
212
+ // A dispatch that already has bindings was claimed once: a retried request gets those back and binds
213
+ // nothing, so a message that arrived while the run works is never attached to a run that did not see it.
214
+ const [claimed] = await boundTo(tx, dispatchId);
215
+ // Only owed replies no dispatch names are `sent`: a held one is acked, so it is bound already and is
216
+ // never taken here; its wake takes it (`claimWake`).
217
+ if (claimed === undefined && open.length > 0) {
218
+ await tx.$executeRaw `
219
+ INSERT INTO "app_kit_owed_reply_dispatch" ("owed_reply_id", "dispatch_id")
220
+ SELECT r."id", ${dispatchId} FROM "app_kit_owed_reply" r
221
+ WHERE r."id" = ANY(${open}::text[])
222
+ AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id")
223
+ ON CONFLICT DO NOTHING`;
224
+ }
225
+ return load(tx, await boundTo(tx, dispatchId));
226
+ }, TRANSACTION_OPTIONS);
227
+ },
228
+ async writeReply(input) {
229
+ try {
230
+ return await writeReplyIn(input);
231
+ }
232
+ catch (error) {
233
+ // The app's `accept` refused: the throw rolled the transaction back, so nothing it wrote stays either.
234
+ if (error instanceof ReplyRefused)
235
+ return error.refusal;
236
+ throw error;
237
+ }
238
+ },
239
+ async hold(tx, input) {
240
+ const refuse = (message) => ({ ok: false, message });
241
+ let target;
242
+ if (input.to !== undefined) {
243
+ const [locked] = await tx.$queryRaw `
244
+ SELECT r."id" FROM "app_kit_owed_reply" r
245
+ WHERE r."id" = ${input.to}
246
+ AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
247
+ WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${input.dispatchId})
248
+ FOR UPDATE OF r`;
249
+ if (locked === undefined)
250
+ return refuse(REFUSALS.notOwed);
251
+ target = await loadOne(tx, locked.id);
252
+ if (target.state === "failed")
253
+ return refuse(REFUSALS.failed);
254
+ if (target.state === "answered")
255
+ return refuse(REFUSALS.answered);
256
+ }
257
+ else {
258
+ const unanswered = await idsOf(tx.$queryRaw `
259
+ SELECT r."id" FROM "app_kit_owed_reply" r
260
+ WHERE r."reply_text" IS NULL AND r."failure" IS NULL
261
+ AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
262
+ WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${input.dispatchId})
263
+ ORDER BY r."id" FOR UPDATE OF r`);
264
+ if (unanswered.length === 0)
265
+ return refuse(HOLD_REFUSALS.nothingToHold);
266
+ if (unanswered.length > 1)
267
+ return refuse(HOLD_REFUSALS.ambiguous);
268
+ target = await loadOne(tx, unanswered[0]);
269
+ }
270
+ if (target.state !== "acked")
271
+ return refuse(HOLD_REFUSALS.notAcknowledged);
272
+ await tx.$executeRaw `
273
+ INSERT INTO "app_kit_owed_reply_hold" ("hold_ref", "owed_reply_id")
274
+ VALUES (${input.holdRef}, ${target.id})
275
+ ON CONFLICT ("hold_ref") DO NOTHING`;
276
+ const [existing] = await tx.$queryRaw `
277
+ SELECT "owed_reply_id" AS "owedReplyId" FROM "app_kit_owed_reply_hold" WHERE "hold_ref" = ${input.holdRef}`;
278
+ if (existing === undefined)
279
+ throw new Error(`hold ${input.holdRef} was not stored`);
280
+ return existing.owedReplyId === target.id ? { ok: true, owedReplyId: target.id } : refuse(HOLD_REFUSALS.refInUse);
281
+ },
282
+ async endHold(holdRef) {
283
+ return client.$transaction(async (tx) => {
284
+ const [row] = await tx.$queryRaw `
285
+ SELECT r."id", r."conversation_ref" AS "conversationRef"
286
+ FROM "app_kit_owed_reply_hold" h
287
+ JOIN "app_kit_owed_reply" r ON r."id" = h."owed_reply_id"
288
+ WHERE h."hold_ref" = ${holdRef}`;
289
+ if (row === undefined)
290
+ return null;
291
+ // The owed reply's row lock is what a wake's claim and a settle take: whichever comes second
292
+ // sees the other's outcome, so a wake never misses a job that has just ended.
293
+ await tx.$queryRaw `SELECT "id" FROM "app_kit_owed_reply" WHERE "id" = ${row.id} FOR UPDATE`;
294
+ await tx.$executeRaw `
295
+ UPDATE "app_kit_owed_reply_hold" SET "ended_at" = CURRENT_TIMESTAMP
296
+ WHERE "hold_ref" = ${holdRef} AND "ended_at" IS NULL`;
297
+ return { conversationRef: row.conversationRef };
298
+ }, TRANSACTION_OPTIONS);
299
+ },
300
+ async settle(dispatchId, end) {
301
+ const line = FAILURE_LINES[end];
302
+ return client.$transaction(async (tx) => {
303
+ // Lock the owed replies bound to this dispatch first, then (a new statement, a new snapshot) keep
304
+ // the ones it still owns: one a later dispatch (a wake) took is that run's, so a terminal
305
+ // redelivered for the earlier run changes nothing, even when it waited on the wake's claim.
306
+ const lockedIds = await idsOf(tx.$queryRaw `
307
+ SELECT r."id" FROM "app_kit_owed_reply" r
308
+ WHERE EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
309
+ WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${dispatchId})
310
+ ORDER BY r."id" FOR UPDATE OF r`);
311
+ const owned = lockedIds.length === 0 ? [] : await idsOf(tx.$queryRaw `
312
+ SELECT r."id" FROM "app_kit_owed_reply" r
313
+ JOIN "app_kit_owed_reply_dispatch" d ON d."owed_reply_id" = r."id" AND d."dispatch_id" = ${dispatchId}
314
+ WHERE r."id" = ANY(${lockedIds}::text[])
315
+ AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" later
316
+ WHERE later."owed_reply_id" = r."id" AND later."created_at" > d."created_at")`);
317
+ const bound = await load(tx, owned);
318
+ const unanswered = bound.filter((reply) => reply.state !== "answered" && reply.state !== "failed");
319
+ // A run that completed leaves an owed reply a background job holds for its wake; any other end
320
+ // means the agent that was to answer is gone, so held ones fail too.
321
+ const failing = end === "completed" ? unanswered.filter((reply) => !reply.held) : unanswered;
322
+ const { cancelHolds } = await failLocked(tx, failing.map((reply) => reply.id), line);
323
+ const conversations = [...new Set(bound.map((reply) => reply.conversationRef))];
324
+ if (conversations.length === 0)
325
+ return { waiting: [], released: [], cancelHolds };
326
+ const waiting = await load(tx, await idsOf(tx.$queryRaw `
327
+ SELECT r."id" FROM "app_kit_owed_reply" r
328
+ WHERE r."conversation_ref" = ANY(${conversations}::text[])
329
+ AND r."reply_text" IS NULL AND r."failure" IS NULL
330
+ AND NOT EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id")`));
331
+ const released = await load(tx, await releasedAmong(tx, await idsOf(tx.$queryRaw `
332
+ SELECT r."id" FROM "app_kit_owed_reply" r
333
+ WHERE r."conversation_ref" = ANY(${conversations}::text[]) AND r."reply_text" IS NULL AND r."failure" IS NULL`)));
334
+ return { waiting, released, cancelHolds };
335
+ }, TRANSACTION_OPTIONS);
336
+ },
337
+ async claimWake(conversationRef, dispatchId) {
338
+ return client.$transaction(async (tx) => {
339
+ const open = await lockOpenOfConversation(tx, conversationRef);
340
+ const [claimed] = await boundTo(tx, dispatchId);
341
+ if (claimed === undefined) {
342
+ const released = await releasedAmong(tx, open);
343
+ if (released.length > 0) {
344
+ await tx.$executeRaw `
345
+ INSERT INTO "app_kit_owed_reply_dispatch" ("owed_reply_id", "dispatch_id")
346
+ SELECT r."id", ${dispatchId} FROM "app_kit_owed_reply" r WHERE r."id" = ANY(${released}::text[])
347
+ ON CONFLICT DO NOTHING`;
348
+ // Reported in the claim's own transaction, so a job is told to exactly one run.
349
+ await tx.$executeRaw `
350
+ UPDATE "app_kit_owed_reply_hold" SET "reported_at" = CURRENT_TIMESTAMP
351
+ WHERE "owed_reply_id" = ANY(${released}::text[]) AND "ended_at" IS NOT NULL AND "reported_at" IS NULL`;
352
+ }
353
+ }
354
+ const replies = await load(tx, await boundTo(tx, dispatchId));
355
+ // The holds this dispatch reported are the ones reported at its own binding time.
356
+ const holds = await tx.$queryRaw `
357
+ SELECT h."hold_ref" AS "holdRef", h."owed_reply_id" AS "owedReplyId"
358
+ FROM "app_kit_owed_reply_hold" h
359
+ JOIN "app_kit_owed_reply_dispatch" d ON d."owed_reply_id" = h."owed_reply_id" AND d."dispatch_id" = ${dispatchId}
360
+ WHERE h."reported_at" = d."created_at"
361
+ ORDER BY h."created_at", h."hold_ref"`;
362
+ return { replies, holds };
363
+ }, TRANSACTION_OPTIONS);
364
+ },
365
+ async abandonWake(conversationRef) {
366
+ return client.$transaction(async (tx) => {
367
+ const released = await releasedAmong(tx, await lockOpenOfConversation(tx, conversationRef));
368
+ return (await failLocked(tx, released, SIGNED_OUT_LINE)).failed;
369
+ }, TRANSACTION_OPTIONS);
370
+ },
371
+ async withdraw(dispatchId) {
372
+ return client.$transaction(async (tx) => {
373
+ const locked = await idsOf(tx.$queryRaw `
374
+ SELECT r."id" FROM "app_kit_owed_reply" r
375
+ WHERE EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d
376
+ WHERE d."owed_reply_id" = r."id" AND d."dispatch_id" = ${dispatchId})
377
+ ORDER BY r."id" FOR UPDATE OF r`);
378
+ if (locked.length === 0)
379
+ return false;
380
+ // A write since the dispatch was bound (an ack, a reply or a failure) means its run started.
381
+ const [written] = await tx.$queryRaw `
382
+ SELECT 1 AS "one"
383
+ FROM "app_kit_owed_reply_dispatch" d
384
+ JOIN "app_kit_owed_reply" r ON r."id" = d."owed_reply_id"
385
+ WHERE d."dispatch_id" = ${dispatchId}
386
+ AND (r."acked_at" >= d."created_at" OR r."answered_at" >= d."created_at" OR r."failed_at" >= d."created_at")
387
+ LIMIT 1`;
388
+ if (written !== undefined)
389
+ return false;
390
+ // A wake's claim reported its holds at the binding's own time: they are untold again.
391
+ await tx.$executeRaw `
392
+ UPDATE "app_kit_owed_reply_hold" h SET "reported_at" = NULL
393
+ FROM "app_kit_owed_reply_dispatch" d
394
+ WHERE d."dispatch_id" = ${dispatchId} AND h."owed_reply_id" = d."owed_reply_id"
395
+ AND h."reported_at" = d."created_at"`;
396
+ await tx.$executeRaw `DELETE FROM "app_kit_owed_reply_dispatch" WHERE "dispatch_id" = ${dispatchId}`;
397
+ return true;
398
+ }, TRANSACTION_OPTIONS);
399
+ },
400
+ async stop(conversationRef) {
401
+ return client.$transaction(async (tx) => {
402
+ const taken = await idsOf(tx.$queryRaw `
403
+ SELECT r."id" FROM "app_kit_owed_reply" r
404
+ WHERE r."conversation_ref" = ${conversationRef} AND r."reply_text" IS NULL AND r."failure" IS NULL
405
+ AND EXISTS (SELECT 1 FROM "app_kit_owed_reply_dispatch" d WHERE d."owed_reply_id" = r."id")
406
+ ORDER BY r."id" FOR UPDATE OF r`);
407
+ const { failed, cancelHolds } = await failLocked(tx, taken, FAILURE_LINES.cancelled);
408
+ return { stopped: failed, cancelHolds };
409
+ }, TRANSACTION_OPTIONS);
410
+ },
411
+ async unansweredOf(dispatchId) {
412
+ return load(client, await idsOf(client.$queryRaw `
413
+ SELECT d."owed_reply_id" AS "id"
414
+ FROM "app_kit_owed_reply_dispatch" d
415
+ JOIN "app_kit_owed_reply" r ON r."id" = d."owed_reply_id"
416
+ WHERE d."dispatch_id" = ${dispatchId} AND r."reply_text" IS NULL AND r."failure" IS NULL`));
417
+ },
418
+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gBACrC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,UAAU,CAAC,EAAE,EAAE,KAAK,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;gBACrF,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;YAC1C,CAAC,EAAE,mBAAmB,CAAC,CAAC;QAC1B,CAAC;QAED,KAAK,CAAC,YAAY,CAAC,UAAU;YAC3B,OAAO,IAAI,CACT,MAAM,EACN,MAAM,KAAK,CAAC,MAAM,CAAC,SAAS,CAAS;;;;qCAIR,UAAU,qDAAqD,CAAC,CAC9F,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { AppRegisteredTool } from "../types.js";
2
+ import type { AcceptReply, OwedReplyStore, OwedReplyTransaction } from "./store.js";
3
+ /**
4
+ * The fields an app's own replies carry beside their text (an audience proposal, a plan packet):
5
+ * the packet is the app's to validate (AK-85). `properties` are JSON Schema properties that join
6
+ * the tool's input; they are allowed with phase `reply` only, because an acknowledgement is
7
+ * words alone. `accept` validates them in the write's transaction (see `AcceptReply`).
8
+ */
9
+ export interface OwedReplyFields<Tx extends OwedReplyTransaction> {
10
+ properties: Record<string, unknown>;
11
+ accept: AcceptReply<Tx>;
12
+ }
13
+ export interface OwedReplyToolOptions<Tx extends OwedReplyTransaction = OwedReplyTransaction> {
14
+ store: OwedReplyStore<Tx>;
15
+ /** The app's reply fields; left out, the tool takes `{to, phase, text}` only. */
16
+ replyFields?: OwedReplyFields<Tx>;
17
+ /** The run this tool serves: the Idempotency-Key the app sent in `runs.create`. A reply to an owed reply this run did not take is refused. */
18
+ dispatchId: string;
19
+ /** Tool name advertised to the agent. Default `reply`. */
20
+ name?: string;
21
+ /** Full description shown to the model; write it in your own product's voice. */
22
+ description?: string;
23
+ }
24
+ export declare function createOwedReplyTool<Tx extends OwedReplyTransaction = OwedReplyTransaction>(options: OwedReplyToolOptions<Tx>): AppRegisteredTool;