@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.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/CHANGELOG.md +77 -0
- package/LICENSE +21 -0
- package/OPERATIONS.md +57 -0
- package/README.md +448 -2
- package/ROADMAP.md +158 -0
- package/TESTING.md +1061 -0
- package/agents.ts +8 -0
- package/examples/README.md +114 -0
- package/examples/gated.ts +28 -0
- package/index.ts +9 -0
- package/package.json +93 -4
- package/skills/pi-delegates/SKILL.md +147 -0
- package/skills/pi-delegates/references/control.md +159 -0
- package/skills/pi-delegates/references/definitions.md +163 -0
- package/skills/pi-delegates/references/gates.md +175 -0
- package/skills/pi-delegates/references/launch.md +156 -0
- package/src/domain/definitions.test.ts +41 -0
- package/src/domain/definitions.ts +161 -0
- package/src/domain/ids.ts +13 -0
- package/src/domain/names.ts +35 -0
- package/src/domain/orchestration/admission.ts +78 -0
- package/src/domain/orchestration/control.test.ts +1298 -0
- package/src/domain/orchestration/control.ts +436 -0
- package/src/domain/orchestration/fanout.test.ts +419 -0
- package/src/domain/orchestration/fanout.ts +334 -0
- package/src/domain/orchestration/gates.test.ts +686 -0
- package/src/domain/orchestration/gates.ts +360 -0
- package/src/domain/orchestration/launch.test.ts +173 -0
- package/src/domain/orchestration/launch.ts +581 -0
- package/src/domain/orchestration/requests.test.ts +700 -0
- package/src/domain/orchestration/requests.ts +769 -0
- package/src/domain/orchestration/review.test.ts +214 -0
- package/src/domain/orchestration/review.ts +168 -0
- package/src/domain/orchestration/run-wait.test.ts +262 -0
- package/src/domain/orchestration/run-wait.ts +256 -0
- package/src/domain/orchestration/workflow-section.test.ts +62 -0
- package/src/domain/orchestration/workflow-section.ts +99 -0
- package/src/domain/orchestration/workflow.test.ts +1425 -0
- package/src/domain/orchestration/workflow.ts +705 -0
- package/src/domain/run-records.test.ts +27 -0
- package/src/domain/run-records.ts +527 -0
- package/src/domain/shapes.test.ts +165 -0
- package/src/domain/skills.test.ts +466 -0
- package/src/domain/skills.ts +97 -0
- package/src/domain/tool-schema.test.ts +46 -0
- package/src/domain/tool-schema.ts +20 -0
- package/src/domain/toolkit.test.ts +201 -0
- package/src/domain/toolkit.ts +379 -0
- package/src/domain/view.test.ts +739 -0
- package/src/domain/view.ts +459 -0
- package/src/example.test.ts +15 -0
- package/src/extension/commands.test.ts +481 -0
- package/src/extension/commands.ts +227 -0
- package/src/extension/entry.test.ts +1118 -0
- package/src/extension/entry.ts +342 -0
- package/src/extension/gate-alerts.test.ts +235 -0
- package/src/extension/gate-alerts.ts +143 -0
- package/src/extension/guard.test.ts +48 -0
- package/src/extension/guard.ts +31 -0
- package/src/extension/host-signals.test.ts +20 -0
- package/src/extension/host-signals.ts +13 -0
- package/src/extension/inspector-command.test.ts +1191 -0
- package/src/extension/inspector-command.ts +638 -0
- package/src/extension/prompt.test.ts +110 -0
- package/src/extension/prompt.ts +50 -0
- package/src/extension/request-alerts.test.ts +183 -0
- package/src/extension/request-alerts.ts +181 -0
- package/src/extension/revocation.test.ts +81 -0
- package/src/extension/revocation.ts +84 -0
- package/src/extension/shortcut.test.ts +64 -0
- package/src/extension/shortcut.ts +105 -0
- package/src/extension/tools.test.ts +993 -0
- package/src/extension/tools.ts +505 -0
- package/src/extension/version.test.ts +123 -0
- package/src/extension/version.ts +97 -0
- package/src/harness-policy.test.ts +74 -0
- package/src/package-manifest.test.ts +157 -0
- package/src/presentation/actions.test.ts +221 -0
- package/src/presentation/actions.ts +85 -0
- package/src/presentation/activity.test.ts +387 -0
- package/src/presentation/activity.ts +66 -0
- package/src/presentation/close.test.ts +361 -0
- package/src/presentation/inspector.test.ts +679 -0
- package/src/presentation/inspector.ts +440 -0
- package/src/presentation/overlay.test.ts +555 -0
- package/src/presentation/overlay.ts +229 -0
- package/src/presentation/repaint.test.ts +329 -0
- package/src/presentation/shortcut.ts +2 -0
- package/src/presentation/snapshot.test.ts +530 -0
- package/src/presentation/snapshot.ts +306 -0
- package/src/presentation/strip.test.ts +196 -0
- package/src/presentation/strip.ts +74 -0
- package/src/presentation/wording.test.ts +238 -0
- package/src/presentation/wording.ts +222 -0
- package/src/runtime/bridge.test.ts +131 -0
- package/src/runtime/bridge.ts +134 -0
- package/src/runtime/config.test.ts +44 -0
- package/src/runtime/config.ts +87 -0
- package/src/runtime/context.test.ts +19 -0
- package/src/runtime/context.ts +9 -0
- package/src/runtime/execution-env.test.ts +35 -0
- package/src/runtime/execution-env.ts +15 -0
- package/src/runtime/extensions.test.ts +86 -0
- package/src/runtime/extensions.ts +140 -0
- package/src/runtime/log.test.ts +128 -0
- package/src/runtime/log.ts +68 -0
- package/src/runtime/mcp.test.ts +1453 -0
- package/src/runtime/mcp.ts +938 -0
- package/src/runtime/models.test.ts +145 -0
- package/src/runtime/models.ts +259 -0
- package/src/runtime/observe.test.ts +50 -0
- package/src/runtime/observe.ts +150 -0
- package/src/runtime/session.test.ts +359 -0
- package/src/runtime/session.ts +425 -0
- package/src/runtime/timers.test.ts +31 -0
- package/src/runtime/timers.ts +10 -0
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
|
+
import {
|
|
3
|
+
defineDoc,
|
|
4
|
+
defineDocFamily,
|
|
5
|
+
defineSignal,
|
|
6
|
+
defineTool,
|
|
7
|
+
type JsonObject,
|
|
8
|
+
type ToolExecutionApi,
|
|
9
|
+
type ToolExecutionResult,
|
|
10
|
+
type ToolPark,
|
|
11
|
+
type ToolRegistration,
|
|
12
|
+
} from "@earendil-works/pi-durable";
|
|
13
|
+
import { obj, str } from "@earendil-works/pi-schema";
|
|
14
|
+
import { Schema } from "effect";
|
|
15
|
+
import type { SessionRuntime } from "../../runtime/session.ts";
|
|
16
|
+
import type { LogSink } from "../../runtime/log.ts";
|
|
17
|
+
import type { ViewPort } from "../view.ts";
|
|
18
|
+
import { taskId as toTaskId } from "../ids.ts";
|
|
19
|
+
import { ToolkitDoc } from "../toolkit.ts";
|
|
20
|
+
import { declared, decode } from "../tool-schema.ts";
|
|
21
|
+
import { blockedResult, DAY_MS } from "./gates.ts";
|
|
22
|
+
|
|
23
|
+
/** A prompt, an answer and a description are bounded; a refusal names the field and its bound. */
|
|
24
|
+
export const PROMPT_MAX_BYTES = 4_096;
|
|
25
|
+
export const ANSWER_MAX_BYTES = 4_096;
|
|
26
|
+
export const LABEL_MAX_CHARS = 128;
|
|
27
|
+
export const DESCRIPTION_MAX_BYTES = 1_024;
|
|
28
|
+
export const MIN_OPTIONS = 2;
|
|
29
|
+
export const MAX_OPTIONS = 5;
|
|
30
|
+
|
|
31
|
+
export class InvalidRequestQuestion extends Schema.TaggedError<
|
|
32
|
+
InvalidRequestQuestion,
|
|
33
|
+
{ readonly brand: unique symbol }
|
|
34
|
+
>()("InvalidRequestQuestion", { message: Schema.String }) {}
|
|
35
|
+
export class RequestNotFound extends Schema.TaggedError<
|
|
36
|
+
RequestNotFound,
|
|
37
|
+
{ readonly brand: unique symbol }
|
|
38
|
+
>()("RequestNotFound", { message: Schema.String }) {}
|
|
39
|
+
export class RequestAlreadyAnswered extends Schema.TaggedError<
|
|
40
|
+
RequestAlreadyAnswered,
|
|
41
|
+
{ readonly brand: unique symbol }
|
|
42
|
+
>()("RequestAlreadyAnswered", { message: Schema.String }) {}
|
|
43
|
+
export class RequestAlreadyDecided extends Schema.TaggedError<
|
|
44
|
+
RequestAlreadyDecided,
|
|
45
|
+
{ readonly brand: unique symbol }
|
|
46
|
+
>()("RequestAlreadyDecided", { message: Schema.String }) {}
|
|
47
|
+
export class InvalidRequestAnswer extends Schema.TaggedError<
|
|
48
|
+
InvalidRequestAnswer,
|
|
49
|
+
{ readonly brand: unique symbol }
|
|
50
|
+
>()("InvalidRequestAnswer", { message: Schema.String }) {}
|
|
51
|
+
|
|
52
|
+
/** The record holds the answer; the signal carries who woke the call, nothing else. */
|
|
53
|
+
export const RequestDecided = defineSignal({
|
|
54
|
+
name: "delegates.request-decided",
|
|
55
|
+
version: 1,
|
|
56
|
+
schema: obj({ sessionId: str() }),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export const RequestOption = Schema.Struct({
|
|
60
|
+
label: Schema.String,
|
|
61
|
+
description: Schema.NullOr(Schema.String),
|
|
62
|
+
recommended: Schema.Boolean,
|
|
63
|
+
});
|
|
64
|
+
export type RequestOption = typeof RequestOption.Type;
|
|
65
|
+
|
|
66
|
+
export const RequestStatus = Schema.Literals(["pending", "answered", "expired", "cancelled"]);
|
|
67
|
+
export type RequestStatus = typeof RequestStatus.Type;
|
|
68
|
+
|
|
69
|
+
export const RequestRecord = Schema.Struct({
|
|
70
|
+
runId: Schema.String,
|
|
71
|
+
/** The child run whose conversation asked; the same as `runId` for a single launch. */
|
|
72
|
+
childRunId: Schema.String,
|
|
73
|
+
requestId: Schema.String,
|
|
74
|
+
conversationId: Schema.Finite,
|
|
75
|
+
prompt: Schema.String,
|
|
76
|
+
options: Schema.Array(RequestOption),
|
|
77
|
+
allowOther: Schema.Boolean,
|
|
78
|
+
status: RequestStatus,
|
|
79
|
+
taskIds: Schema.Array(Schema.Finite),
|
|
80
|
+
requestedAt: Schema.Finite,
|
|
81
|
+
deadline: Schema.Finite,
|
|
82
|
+
answer: Schema.NullOr(Schema.String),
|
|
83
|
+
answeredBy: Schema.NullOr(Schema.Struct({ sessionId: Schema.String })),
|
|
84
|
+
reason: Schema.NullOr(Schema.String),
|
|
85
|
+
});
|
|
86
|
+
export type RequestRecord = typeof RequestRecord.Type;
|
|
87
|
+
|
|
88
|
+
export const RequestDoc = defineDocFamily<
|
|
89
|
+
RequestRecord & JsonObject,
|
|
90
|
+
{ requestId: string } & JsonObject
|
|
91
|
+
>({
|
|
92
|
+
kind: "delegates.request",
|
|
93
|
+
version: 1,
|
|
94
|
+
scope: "session",
|
|
95
|
+
family: true,
|
|
96
|
+
initial: (seed) => ({
|
|
97
|
+
runId: "",
|
|
98
|
+
childRunId: "",
|
|
99
|
+
requestId: seed.requestId,
|
|
100
|
+
conversationId: 0,
|
|
101
|
+
prompt: "",
|
|
102
|
+
options: [],
|
|
103
|
+
allowOther: true,
|
|
104
|
+
status: "pending",
|
|
105
|
+
taskIds: [],
|
|
106
|
+
requestedAt: 0,
|
|
107
|
+
deadline: 0,
|
|
108
|
+
answer: null,
|
|
109
|
+
answeredBy: null,
|
|
110
|
+
reason: null,
|
|
111
|
+
}),
|
|
112
|
+
checkpointWhen: () => true,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
/** A read model: one row per request, written in the same commit as the record. */
|
|
116
|
+
export const RequestIndexRow = Schema.Struct({
|
|
117
|
+
key: Schema.String,
|
|
118
|
+
runId: Schema.String,
|
|
119
|
+
requestId: Schema.String,
|
|
120
|
+
requestedAt: Schema.Finite,
|
|
121
|
+
deadline: Schema.Finite,
|
|
122
|
+
status: RequestStatus,
|
|
123
|
+
});
|
|
124
|
+
export type RequestIndexRow = typeof RequestIndexRow.Type;
|
|
125
|
+
|
|
126
|
+
export const RequestIndexDoc = defineDoc<{ rows: RequestIndexRow[] } & JsonObject>({
|
|
127
|
+
kind: "delegates.request-index",
|
|
128
|
+
version: 1,
|
|
129
|
+
scope: "session",
|
|
130
|
+
initial: () => ({ rows: [] }),
|
|
131
|
+
checkpointWhen: () => true,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
/** The request id is the conversation and the call; it is stable across a wake and a resume. */
|
|
135
|
+
export const requestKey = (conversationId: number, callId: string): string =>
|
|
136
|
+
`${conversationId}:${callId}`;
|
|
137
|
+
|
|
138
|
+
/** The document reads a request listing needs; live and read-only runtimes both satisfy it. */
|
|
139
|
+
type SnapshotPort = Pick<ViewPort, "snapshot"> & { readonly now?: () => number };
|
|
140
|
+
|
|
141
|
+
const clockOf = (runtime: SnapshotPort): number => (runtime.now ?? Date.now)();
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The state a reader derives without a write: a pending record past its deadline
|
|
145
|
+
* is expired, whatever its committed status says.
|
|
146
|
+
*/
|
|
147
|
+
export const requestState = (
|
|
148
|
+
record: Pick<RequestRecord, "status" | "deadline">,
|
|
149
|
+
now: number,
|
|
150
|
+
): RequestStatus =>
|
|
151
|
+
record.status === "pending" && record.deadline > 0 && now >= record.deadline
|
|
152
|
+
? "expired"
|
|
153
|
+
: record.status;
|
|
154
|
+
|
|
155
|
+
/** The stored record as a plain value; a draft may not outlive its commit. */
|
|
156
|
+
const recordOf = (doc: RequestRecord & JsonObject): RequestRecord => ({
|
|
157
|
+
runId: doc.runId,
|
|
158
|
+
childRunId: doc.childRunId,
|
|
159
|
+
requestId: doc.requestId,
|
|
160
|
+
conversationId: doc.conversationId,
|
|
161
|
+
prompt: doc.prompt,
|
|
162
|
+
options: doc.options.map((option) => ({
|
|
163
|
+
label: option.label,
|
|
164
|
+
description: option.description,
|
|
165
|
+
recommended: option.recommended,
|
|
166
|
+
})),
|
|
167
|
+
allowOther: doc.allowOther,
|
|
168
|
+
status: doc.status,
|
|
169
|
+
taskIds: [...doc.taskIds],
|
|
170
|
+
requestedAt: doc.requestedAt,
|
|
171
|
+
deadline: doc.deadline,
|
|
172
|
+
answer: doc.answer,
|
|
173
|
+
answeredBy: doc.answeredBy === null ? null : { sessionId: doc.answeredBy.sessionId },
|
|
174
|
+
reason: doc.reason,
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
/** The index row a commit writes beside the record, in the same commit by the same writer. */
|
|
178
|
+
const upsertRow = (
|
|
179
|
+
index: { rows: RequestIndexRow[] },
|
|
180
|
+
key: string,
|
|
181
|
+
record: Pick<RequestRecord, "runId" | "requestId" | "requestedAt" | "deadline" | "status">,
|
|
182
|
+
): void => {
|
|
183
|
+
const row: RequestIndexRow = {
|
|
184
|
+
key,
|
|
185
|
+
runId: record.runId,
|
|
186
|
+
requestId: record.requestId,
|
|
187
|
+
requestedAt: record.requestedAt,
|
|
188
|
+
deadline: record.deadline,
|
|
189
|
+
status: record.status,
|
|
190
|
+
};
|
|
191
|
+
const at = index.rows.findIndex((candidate) => candidate.key === key);
|
|
192
|
+
if (at === -1) index.rows.push(row);
|
|
193
|
+
else index.rows[at] = row;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const bytes = (text: string): number => Buffer.byteLength(text, "utf8");
|
|
197
|
+
|
|
198
|
+
const refusal = (message: string): InvalidRequestQuestion =>
|
|
199
|
+
InvalidRequestQuestion.make({ message });
|
|
200
|
+
|
|
201
|
+
interface NormalizedOption {
|
|
202
|
+
readonly label: string;
|
|
203
|
+
readonly description: string | null;
|
|
204
|
+
readonly recommended: boolean;
|
|
205
|
+
}
|
|
206
|
+
export type { NormalizedOption };
|
|
207
|
+
|
|
208
|
+
/** The exact fields the envelope carries, checked against the bounds before any write. */
|
|
209
|
+
export interface QuestionShape {
|
|
210
|
+
readonly prompt: string;
|
|
211
|
+
readonly options: readonly NormalizedOption[];
|
|
212
|
+
readonly allowOther: boolean;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const normalizePrompt = (prompt: string): string => {
|
|
216
|
+
const size = bytes(prompt);
|
|
217
|
+
if (prompt.trim().length === 0) {
|
|
218
|
+
throw refusal(`The prompt is required; a prompt may be at most ${PROMPT_MAX_BYTES} bytes.`);
|
|
219
|
+
}
|
|
220
|
+
if (size > PROMPT_MAX_BYTES) {
|
|
221
|
+
throw refusal(
|
|
222
|
+
`The prompt is ${size} bytes; a prompt may be at most ${PROMPT_MAX_BYTES} bytes.`,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return prompt;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const normalizeOptions = (
|
|
229
|
+
options: readonly {
|
|
230
|
+
readonly label: string;
|
|
231
|
+
readonly description?: string | undefined;
|
|
232
|
+
readonly recommended?: boolean | undefined;
|
|
233
|
+
}[],
|
|
234
|
+
): NormalizedOption[] => {
|
|
235
|
+
if (options.length === 1 || options.length > MAX_OPTIONS) {
|
|
236
|
+
throw refusal(
|
|
237
|
+
options.length === 1
|
|
238
|
+
? `An option list needs ${MIN_OPTIONS}-${MAX_OPTIONS} labels or none; omit options to ask ` +
|
|
239
|
+
`for free text.`
|
|
240
|
+
: `An option list holds at most ${MAX_OPTIONS} labels; this one has ${options.length}.`,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const normalized: NormalizedOption[] = [];
|
|
244
|
+
const labels = new Set<string>();
|
|
245
|
+
let recommendedAt = -1;
|
|
246
|
+
for (const [position, option] of options.entries()) {
|
|
247
|
+
const index = position + 1;
|
|
248
|
+
if (option.label.length === 0) {
|
|
249
|
+
throw refusal(`Option ${index} has an empty label.`);
|
|
250
|
+
}
|
|
251
|
+
const labelLength = Array.from(option.label).length;
|
|
252
|
+
if (labelLength > LABEL_MAX_CHARS) {
|
|
253
|
+
throw refusal(
|
|
254
|
+
`Option ${index} has a label of ${labelLength} characters; a label may be at ` +
|
|
255
|
+
`most ${LABEL_MAX_CHARS} characters.`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const description = option.description ?? null;
|
|
259
|
+
if (description !== null && bytes(description) > DESCRIPTION_MAX_BYTES) {
|
|
260
|
+
throw refusal(
|
|
261
|
+
`Option ${index} has a description of ${bytes(description)} bytes; a description may be ` +
|
|
262
|
+
`at most ${DESCRIPTION_MAX_BYTES} bytes.`,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
const folded = option.label.toLowerCase();
|
|
266
|
+
if (labels.has(folded)) {
|
|
267
|
+
throw refusal(`Option ${index} repeats the label "${option.label}"; labels must be unique.`);
|
|
268
|
+
}
|
|
269
|
+
labels.add(folded);
|
|
270
|
+
const recommended = option.recommended ?? false;
|
|
271
|
+
if (recommended) {
|
|
272
|
+
if (recommendedAt !== -1) {
|
|
273
|
+
throw refusal(
|
|
274
|
+
`Options ${recommendedAt} and ${index} are both recommended; at most one option may be ` +
|
|
275
|
+
`recommended.`,
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
recommendedAt = index;
|
|
279
|
+
}
|
|
280
|
+
normalized.push({ label: option.label, description, recommended });
|
|
281
|
+
}
|
|
282
|
+
return normalized;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const normalizedQuestion = (input: {
|
|
286
|
+
readonly prompt: string;
|
|
287
|
+
readonly options?: readonly {
|
|
288
|
+
readonly label: string;
|
|
289
|
+
readonly description?: string | undefined;
|
|
290
|
+
readonly recommended?: boolean | undefined;
|
|
291
|
+
}[];
|
|
292
|
+
readonly allowOther?: boolean | undefined;
|
|
293
|
+
}): QuestionShape => {
|
|
294
|
+
const options = normalizeOptions(input.options ?? []);
|
|
295
|
+
const allowOther = input.allowOther ?? true;
|
|
296
|
+
if (!allowOther && options.length === 0) {
|
|
297
|
+
throw refusal(
|
|
298
|
+
"A request with no options must allow free text; add options or leave allowOther true.",
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
return { prompt: normalizePrompt(input.prompt), options, allowOther };
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/** One commit expires the record and its row; the caller reports the refusal. */
|
|
305
|
+
export const expireRequest = async (
|
|
306
|
+
api: ToolExecutionApi,
|
|
307
|
+
key: string,
|
|
308
|
+
context: Context,
|
|
309
|
+
): Promise<void> => {
|
|
310
|
+
await api.commit(async (tx) => {
|
|
311
|
+
const doc = await tx.doc(RequestDoc, key, { requestId: key });
|
|
312
|
+
if (doc.status === "pending") {
|
|
313
|
+
doc.status = "expired";
|
|
314
|
+
doc.reason = "deadline";
|
|
315
|
+
}
|
|
316
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
317
|
+
upsertRow(index, key, recordOf(doc));
|
|
318
|
+
}, context);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
export interface QuestionRequest {
|
|
322
|
+
readonly key: string;
|
|
323
|
+
readonly runId: string;
|
|
324
|
+
readonly childRunId: string;
|
|
325
|
+
readonly conversationId: number;
|
|
326
|
+
readonly prompt: string;
|
|
327
|
+
readonly options?: readonly {
|
|
328
|
+
readonly label: string;
|
|
329
|
+
readonly description?: string | undefined;
|
|
330
|
+
readonly recommended?: boolean | undefined;
|
|
331
|
+
}[];
|
|
332
|
+
readonly allowOther?: boolean | undefined;
|
|
333
|
+
readonly until: number;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* One commit writes the pending record, its parked task and its index row. The
|
|
338
|
+
* record it returns is the one the tool must act on: an answer may have landed
|
|
339
|
+
* between the tool's read and this commit.
|
|
340
|
+
*/
|
|
341
|
+
export const requestQuestion = async (
|
|
342
|
+
api: ToolExecutionApi,
|
|
343
|
+
request: QuestionRequest,
|
|
344
|
+
context: Context,
|
|
345
|
+
): Promise<RequestRecord> => {
|
|
346
|
+
const question = normalizedQuestion(request);
|
|
347
|
+
return api.commit(async (tx) => {
|
|
348
|
+
const doc = await tx.doc(RequestDoc, request.key, { requestId: request.key });
|
|
349
|
+
if (doc.status !== "pending") return recordOf(doc);
|
|
350
|
+
if (doc.requestedAt === 0) {
|
|
351
|
+
doc.runId = request.runId;
|
|
352
|
+
doc.childRunId = request.childRunId;
|
|
353
|
+
doc.requestId = request.key;
|
|
354
|
+
doc.conversationId = request.conversationId;
|
|
355
|
+
doc.prompt = question.prompt;
|
|
356
|
+
doc.options = question.options.map((option) => ({
|
|
357
|
+
label: option.label,
|
|
358
|
+
description: option.description,
|
|
359
|
+
recommended: option.recommended,
|
|
360
|
+
}));
|
|
361
|
+
doc.allowOther = question.allowOther;
|
|
362
|
+
doc.requestedAt = api.now();
|
|
363
|
+
doc.deadline = request.until;
|
|
364
|
+
}
|
|
365
|
+
const taskIds = doc.taskIds ?? [];
|
|
366
|
+
if (!taskIds.includes(api.taskId)) taskIds.push(api.taskId);
|
|
367
|
+
doc.taskIds = taskIds;
|
|
368
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
369
|
+
upsertRow(index, request.key, recordOf(doc));
|
|
370
|
+
return recordOf(doc);
|
|
371
|
+
}, context);
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const answerResult = (answer: string): ToolExecutionResult => ({
|
|
375
|
+
output: [{ type: "text", text: `The user answered: ${answer}` }],
|
|
376
|
+
structuredOutput: { answer, source: "user" },
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
const AskOption = Schema.Struct({
|
|
380
|
+
label: Schema.String,
|
|
381
|
+
description: Schema.optional(Schema.String),
|
|
382
|
+
recommended: Schema.optional(Schema.Boolean),
|
|
383
|
+
});
|
|
384
|
+
const AskOptionList = Schema.Array(AskOption);
|
|
385
|
+
const AskParameters = Schema.Struct({
|
|
386
|
+
prompt: Schema.String,
|
|
387
|
+
options: Schema.optional(AskOptionList),
|
|
388
|
+
allowOther: Schema.optional(Schema.Boolean),
|
|
389
|
+
});
|
|
390
|
+
const AskArgs = declared(AskParameters);
|
|
391
|
+
const AskOutput = Schema.Struct({ answer: Schema.String, source: Schema.Literal("user") });
|
|
392
|
+
const AskResult = declared(AskOutput);
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The child-facing question. It writes one pending request, then parks on the
|
|
396
|
+
* decision; a replay reads the committed record instead of asking twice.
|
|
397
|
+
*/
|
|
398
|
+
export const askTool = (log: LogSink): ToolRegistration =>
|
|
399
|
+
defineTool({
|
|
400
|
+
name: "ask",
|
|
401
|
+
description:
|
|
402
|
+
"Ask the user one question and wait for the answer. Use it only when the answer changes " +
|
|
403
|
+
"your next step; give 2-5 options when the answer is a choice.",
|
|
404
|
+
parameters: AskArgs.json,
|
|
405
|
+
callers: ["model"],
|
|
406
|
+
replay: "safe",
|
|
407
|
+
structuredOutputSchema: AskResult.json,
|
|
408
|
+
execute: async (raw, api, context): Promise<ToolExecutionResult | ToolPark> => {
|
|
409
|
+
const toolkit = await api.snapshot(ToolkitDoc, api.conversationId, context);
|
|
410
|
+
if (toolkit === undefined) return blockedResult("ask needs a child conversation.");
|
|
411
|
+
const { prompt, options, allowOther } = decode(AskArgs.schema, raw);
|
|
412
|
+
const key = requestKey(api.conversationId, api.callId);
|
|
413
|
+
const record = await api.snapshot(RequestDoc, key, context);
|
|
414
|
+
if (record?.status === "answered") return answerResult(record.answer ?? "");
|
|
415
|
+
if (record?.status === "pending" && requestState(record, api.now()) === "expired") {
|
|
416
|
+
await expireRequest(api, key, context);
|
|
417
|
+
return blockedResult(
|
|
418
|
+
`Request ${key} expired before an answer; its deadline was ${record.deadline}.`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (record !== undefined && record.status !== "pending") {
|
|
422
|
+
const reason =
|
|
423
|
+
record.reason === null ? record.status : `${record.status}: ${record.reason}`;
|
|
424
|
+
return blockedResult(`Request ${key} was not answered (${reason}).`);
|
|
425
|
+
}
|
|
426
|
+
// The record owns the deadline; the memo only fixes the first call's value.
|
|
427
|
+
const until =
|
|
428
|
+
record?.status === "pending"
|
|
429
|
+
? record.deadline
|
|
430
|
+
: await api.memo(`request.deadline.${key}`, api.now() + DAY_MS, context);
|
|
431
|
+
let committed: RequestRecord;
|
|
432
|
+
try {
|
|
433
|
+
committed = await requestQuestion(
|
|
434
|
+
api,
|
|
435
|
+
{
|
|
436
|
+
key,
|
|
437
|
+
runId: toolkit.runId,
|
|
438
|
+
childRunId: toolkit.childRunId,
|
|
439
|
+
conversationId: api.conversationId,
|
|
440
|
+
prompt,
|
|
441
|
+
...(options === undefined ? {} : { options }),
|
|
442
|
+
...(allowOther === undefined ? {} : { allowOther }),
|
|
443
|
+
until,
|
|
444
|
+
},
|
|
445
|
+
context,
|
|
446
|
+
);
|
|
447
|
+
} catch (error) {
|
|
448
|
+
if (error instanceof InvalidRequestQuestion) return blockedResult(error.message);
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
// An answer can land between the read above and this commit; the signal then reaches no
|
|
452
|
+
// registered task, so return the outcome instead of parking (decision 37).
|
|
453
|
+
if (committed.status === "answered") return answerResult(committed.answer ?? "");
|
|
454
|
+
if (committed.status !== "pending") {
|
|
455
|
+
return blockedResult(`Request ${key} was not answered (${committed.status}).`);
|
|
456
|
+
}
|
|
457
|
+
return {
|
|
458
|
+
sleep: {
|
|
459
|
+
checkpoint: { args: raw as JsonObject },
|
|
460
|
+
signals: [RequestDecided.key(key)],
|
|
461
|
+
until,
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
},
|
|
465
|
+
// Durable's only cleanup hook: an aborted parked call must not leave a pending request behind.
|
|
466
|
+
cancel: async (_args, api, context) => {
|
|
467
|
+
const key = requestKey(api.conversationId, api.callId);
|
|
468
|
+
const cancelled = await api.commit(async (tx) => {
|
|
469
|
+
const doc = await tx.doc(RequestDoc, key, { requestId: key });
|
|
470
|
+
if (doc.status !== "pending") return undefined;
|
|
471
|
+
doc.status = "cancelled";
|
|
472
|
+
doc.reason = "stopped";
|
|
473
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
474
|
+
upsertRow(index, key, recordOf(doc));
|
|
475
|
+
return { runId: doc.runId, requestId: key };
|
|
476
|
+
}, context);
|
|
477
|
+
if (cancelled !== undefined) log.write("info", "request.cancelled", cancelled);
|
|
478
|
+
},
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
/** Every request record of one run, or of the whole session, oldest first. */
|
|
482
|
+
export const requestRecords = async (
|
|
483
|
+
runtime: SnapshotPort,
|
|
484
|
+
runId?: string,
|
|
485
|
+
): Promise<readonly RequestRecord[]> => {
|
|
486
|
+
const index = await runtime.snapshot(RequestIndexDoc);
|
|
487
|
+
const rows = (index?.rows ?? []).filter((row) => runId === undefined || row.runId === runId);
|
|
488
|
+
const records: RequestRecord[] = [];
|
|
489
|
+
for (const row of rows) {
|
|
490
|
+
const record = await runtime.snapshot(RequestDoc, row.key);
|
|
491
|
+
if (record !== undefined) records.push(record);
|
|
492
|
+
}
|
|
493
|
+
return records.sort((left, right) => left.requestedAt - right.requestedAt);
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
/** Pending requests of one run, or of the whole session, oldest first. */
|
|
497
|
+
export const pendingRequests = async (
|
|
498
|
+
runtime: SnapshotPort,
|
|
499
|
+
runId?: string,
|
|
500
|
+
): Promise<readonly RequestRecord[]> => {
|
|
501
|
+
const now = clockOf(runtime);
|
|
502
|
+
return (await requestRecords(runtime, runId)).filter(
|
|
503
|
+
(record) => requestState(record, now) === "pending",
|
|
504
|
+
);
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
const answerRefusal = (message: string): InvalidRequestAnswer =>
|
|
508
|
+
InvalidRequestAnswer.make({ message });
|
|
509
|
+
|
|
510
|
+
const NUMBERED = /^\d+\.\s+/;
|
|
511
|
+
const NUMBER = /^\d+$/;
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Trim, compare case-insensitively, strip a leading `N. ` and accept an in-range
|
|
515
|
+
* number. Free text is trimmed and canonicalized when it matches a label; a
|
|
516
|
+
* mismatch is refused and names the allowed labels.
|
|
517
|
+
*/
|
|
518
|
+
export const normalizeAnswer = (record: RequestRecord, raw: string): string => {
|
|
519
|
+
const trimmed = raw.trim();
|
|
520
|
+
if (trimmed.length === 0) {
|
|
521
|
+
throw answerRefusal("An answer is required.");
|
|
522
|
+
}
|
|
523
|
+
const size = bytes(trimmed);
|
|
524
|
+
if (size > ANSWER_MAX_BYTES) {
|
|
525
|
+
throw answerRefusal(
|
|
526
|
+
`The answer is ${size} bytes; an answer may be at most ${ANSWER_MAX_BYTES} bytes.`,
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
const candidate = trimmed.replace(NUMBERED, "").trim();
|
|
530
|
+
const folded = candidate.toLowerCase();
|
|
531
|
+
const match = record.options.find((option) => option.label.toLowerCase() === folded);
|
|
532
|
+
if (match !== undefined) return match.label;
|
|
533
|
+
const labels = record.options.map((option) => option.label).join(", ");
|
|
534
|
+
if (NUMBER.test(candidate)) {
|
|
535
|
+
const option = record.options[Number(candidate) - 1];
|
|
536
|
+
if (option !== undefined) return option.label;
|
|
537
|
+
if (!record.allowOther) {
|
|
538
|
+
throw answerRefusal(
|
|
539
|
+
`The answer ${candidate} is outside the options; they are numbered 1-${record.options.length}. ` +
|
|
540
|
+
`The labels are: ${labels}.`,
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (!record.allowOther) {
|
|
545
|
+
throw answerRefusal(`An answer must be one of: ${labels || "(none)"}.`);
|
|
546
|
+
}
|
|
547
|
+
return trimmed;
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
export interface RequestDecisionInput {
|
|
551
|
+
readonly run: string;
|
|
552
|
+
readonly request: string;
|
|
553
|
+
readonly sessionId: string;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
export interface RequestDecisionOutcome {
|
|
557
|
+
readonly record: RequestRecord;
|
|
558
|
+
readonly deliveredTaskIds: readonly number[];
|
|
559
|
+
readonly endedTaskIds: readonly number[];
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** One signal per parked task; `closed` and `not_found` end it, everything else is delivered. */
|
|
563
|
+
const deliver = async (
|
|
564
|
+
runtime: SessionRuntime,
|
|
565
|
+
key: string,
|
|
566
|
+
record: RequestRecord,
|
|
567
|
+
): Promise<RequestDecisionOutcome> => {
|
|
568
|
+
const deliveredTaskIds: number[] = [];
|
|
569
|
+
const endedTaskIds: number[] = [];
|
|
570
|
+
for (const taskId of new Set(record.taskIds)) {
|
|
571
|
+
const delivery = await runtime.run((context) =>
|
|
572
|
+
runtime.harness.signal(
|
|
573
|
+
toTaskId(taskId),
|
|
574
|
+
RequestDecided,
|
|
575
|
+
key,
|
|
576
|
+
{ sessionId: runtime.sessionId },
|
|
577
|
+
context,
|
|
578
|
+
),
|
|
579
|
+
);
|
|
580
|
+
if (delivery === "closed" || delivery === "not_found") endedTaskIds.push(taskId);
|
|
581
|
+
else deliveredTaskIds.push(taskId);
|
|
582
|
+
}
|
|
583
|
+
return { record, deliveredTaskIds, endedTaskIds };
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
const decidedRefusal = (record: RequestRecord): RequestAlreadyDecided => {
|
|
587
|
+
const reason = record.reason === null ? record.status : `${record.status}: ${record.reason}`;
|
|
588
|
+
return RequestAlreadyDecided.make({
|
|
589
|
+
message: `Request ${record.requestId} is ${reason}.`,
|
|
590
|
+
});
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
const answeredRefusal = (record: RequestRecord): RequestAlreadyAnswered =>
|
|
594
|
+
RequestAlreadyAnswered.make({
|
|
595
|
+
message: `Request ${record.requestId} is already ${record.status}.`,
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
/** The record a control write addresses, or a refusal for an unknown request or another run. */
|
|
599
|
+
const loadRequest = async (
|
|
600
|
+
input: RequestDecisionInput,
|
|
601
|
+
runtime: SessionRuntime,
|
|
602
|
+
): Promise<RequestRecord> => {
|
|
603
|
+
const current = await runtime.snapshot(RequestDoc, input.request);
|
|
604
|
+
if (current === undefined || (current.runId !== input.run && current.childRunId !== input.run)) {
|
|
605
|
+
throw RequestNotFound.make({
|
|
606
|
+
message: `Request ${input.request} of run ${input.run} not found.`,
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
return current;
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
/** A pending record past its deadline is committed expired before anything else is read. */
|
|
613
|
+
const expireBeforeDeciding = async (
|
|
614
|
+
record: RequestRecord,
|
|
615
|
+
runtime: SessionRuntime,
|
|
616
|
+
): Promise<void> => {
|
|
617
|
+
if (record.status !== "pending" || requestState(record, runtime.now()) !== "expired") return;
|
|
618
|
+
await runtime.run((context) =>
|
|
619
|
+
runtime.harness.commit(async (tx) => {
|
|
620
|
+
const doc = await tx.doc(RequestDoc, record.requestId, { requestId: record.requestId });
|
|
621
|
+
if (doc.status === "pending") {
|
|
622
|
+
doc.status = "expired";
|
|
623
|
+
doc.reason = "deadline";
|
|
624
|
+
}
|
|
625
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
626
|
+
upsertRow(index, record.requestId, recordOf(doc));
|
|
627
|
+
}, context),
|
|
628
|
+
);
|
|
629
|
+
throw RequestAlreadyDecided.make({
|
|
630
|
+
message: `Request ${record.requestId} expired before an answer.`,
|
|
631
|
+
});
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* One commit wins the answer and updates its index row; only the winner signals
|
|
636
|
+
* the parked tasks. A second answer, a wrong run, an expired or declined request
|
|
637
|
+
* and an answer outside the options are refused without a commit.
|
|
638
|
+
*/
|
|
639
|
+
export const answerRequest = async (
|
|
640
|
+
input: RequestDecisionInput & { readonly answer: string },
|
|
641
|
+
runtime: SessionRuntime,
|
|
642
|
+
): Promise<RequestDecisionOutcome> => {
|
|
643
|
+
const current = await loadRequest(input, runtime);
|
|
644
|
+
await expireBeforeDeciding(current, runtime);
|
|
645
|
+
if (current.status === "answered") throw answeredRefusal(current);
|
|
646
|
+
if (current.status !== "pending") throw decidedRefusal(current);
|
|
647
|
+
const answer = normalizeAnswer(current, input.answer);
|
|
648
|
+
const key = current.requestId;
|
|
649
|
+
const committed = await runtime.run((context) =>
|
|
650
|
+
runtime.harness.commit(async (tx) => {
|
|
651
|
+
const doc = await tx.doc(RequestDoc, key, { requestId: key });
|
|
652
|
+
const won = doc.status === "pending";
|
|
653
|
+
if (won) {
|
|
654
|
+
doc.status = "answered";
|
|
655
|
+
doc.answer = answer;
|
|
656
|
+
doc.answeredBy = { sessionId: input.sessionId };
|
|
657
|
+
doc.reason = null;
|
|
658
|
+
}
|
|
659
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
660
|
+
upsertRow(index, key, recordOf(doc));
|
|
661
|
+
return { won, record: recordOf(doc) };
|
|
662
|
+
}, context),
|
|
663
|
+
);
|
|
664
|
+
if (!committed.won) {
|
|
665
|
+
throw committed.record.status === "answered"
|
|
666
|
+
? answeredRefusal(committed.record)
|
|
667
|
+
: decidedRefusal(committed.record);
|
|
668
|
+
}
|
|
669
|
+
return deliver(runtime, key, committed.record);
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
/** One commit cancels the request with reason `declined`, then wakes the parked calls. */
|
|
673
|
+
export const declineRequest = async (
|
|
674
|
+
input: RequestDecisionInput,
|
|
675
|
+
runtime: SessionRuntime,
|
|
676
|
+
): Promise<RequestDecisionOutcome> => {
|
|
677
|
+
const current = await loadRequest(input, runtime);
|
|
678
|
+
await expireBeforeDeciding(current, runtime);
|
|
679
|
+
if (current.status === "answered") throw answeredRefusal(current);
|
|
680
|
+
if (current.status !== "pending") throw decidedRefusal(current);
|
|
681
|
+
const key = current.requestId;
|
|
682
|
+
const committed = await runtime.run((context) =>
|
|
683
|
+
runtime.harness.commit(async (tx) => {
|
|
684
|
+
const doc = await tx.doc(RequestDoc, key, { requestId: key });
|
|
685
|
+
const won = doc.status === "pending";
|
|
686
|
+
if (won) {
|
|
687
|
+
doc.status = "cancelled";
|
|
688
|
+
doc.reason = "declined";
|
|
689
|
+
doc.answeredBy = { sessionId: input.sessionId };
|
|
690
|
+
}
|
|
691
|
+
const index = await tx.doc(RequestIndexDoc);
|
|
692
|
+
upsertRow(index, key, recordOf(doc));
|
|
693
|
+
return { won, record: recordOf(doc) };
|
|
694
|
+
}, context),
|
|
695
|
+
);
|
|
696
|
+
if (!committed.won) throw decidedRefusal(committed.record);
|
|
697
|
+
return deliver(runtime, key, committed.record);
|
|
698
|
+
};
|
|
699
|
+
|
|
700
|
+
/** Every decided request is retired this long after it was requested. */
|
|
701
|
+
export const PRUNE_AFTER_MS = 7 * DAY_MS;
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Stop cancels every pending request of the run in one commit, then wakes the
|
|
705
|
+
* parked calls with no answer. It runs after the abort, before the settling read.
|
|
706
|
+
*/
|
|
707
|
+
export const cancelRequests = async (runId: string, runtime: SessionRuntime): Promise<void> => {
|
|
708
|
+
const index = await runtime.snapshot(RequestIndexDoc);
|
|
709
|
+
const now = runtime.now();
|
|
710
|
+
const keys = (index?.rows ?? [])
|
|
711
|
+
.filter((row) => row.runId === runId && requestState(row, now) === "pending")
|
|
712
|
+
.map((row) => row.key);
|
|
713
|
+
if (keys.length === 0) return;
|
|
714
|
+
const committed = await runtime.run((context) =>
|
|
715
|
+
runtime.harness.commit(async (tx) => {
|
|
716
|
+
const records: RequestRecord[] = [];
|
|
717
|
+
const next = await tx.doc(RequestIndexDoc);
|
|
718
|
+
for (const key of keys) {
|
|
719
|
+
const doc = await tx.doc(RequestDoc, key, { requestId: key });
|
|
720
|
+
if (doc.status !== "pending") continue;
|
|
721
|
+
doc.status = "cancelled";
|
|
722
|
+
doc.reason = "stopped";
|
|
723
|
+
const record = recordOf(doc);
|
|
724
|
+
upsertRow(next, key, record);
|
|
725
|
+
records.push(record);
|
|
726
|
+
}
|
|
727
|
+
return records;
|
|
728
|
+
}, context),
|
|
729
|
+
);
|
|
730
|
+
for (const record of committed) {
|
|
731
|
+
runtime.log.write("info", "request.cancelled", {
|
|
732
|
+
runId: record.runId,
|
|
733
|
+
requestId: record.requestId,
|
|
734
|
+
});
|
|
735
|
+
await deliver(runtime, record.requestId, record);
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* One commit retires every decided request older than `PRUNE_AFTER_MS` and drops
|
|
741
|
+
* its index row; a row without a record is dropped in the same commit. A live
|
|
742
|
+
* runtime calls it once at start, so a session without the watcher still bounds
|
|
743
|
+
* its store; a read-only viewer never calls it.
|
|
744
|
+
*/
|
|
745
|
+
export const pruneRequests = async (runtime: SessionRuntime): Promise<number> => {
|
|
746
|
+
const index = await runtime.snapshot(RequestIndexDoc);
|
|
747
|
+
const now = runtime.now();
|
|
748
|
+
const stale: string[] = [];
|
|
749
|
+
const missing: string[] = [];
|
|
750
|
+
for (const row of index?.rows ?? []) {
|
|
751
|
+
const record = await runtime.snapshot(RequestDoc, row.key);
|
|
752
|
+
if (record === undefined) {
|
|
753
|
+
missing.push(row.key);
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
const state = requestState(record, now);
|
|
757
|
+
if (state !== "pending" && now - record.requestedAt > PRUNE_AFTER_MS) stale.push(row.key);
|
|
758
|
+
}
|
|
759
|
+
if (stale.length === 0 && missing.length === 0) return 0;
|
|
760
|
+
const drop = new Set([...stale, ...missing]);
|
|
761
|
+
return runtime.run((context) =>
|
|
762
|
+
runtime.harness.commit(async (tx) => {
|
|
763
|
+
const next = await tx.doc(RequestIndexDoc);
|
|
764
|
+
next.rows = next.rows.filter((row) => !drop.has(row.key));
|
|
765
|
+
for (const key of stale) await tx.retireDoc(RequestDoc, key);
|
|
766
|
+
return stale.length;
|
|
767
|
+
}, context),
|
|
768
|
+
);
|
|
769
|
+
};
|