@zvada/agent-server 0.3.30 → 0.3.31
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 +36 -0
- package/dist/core/runtime/event-processor.js +9 -10
- package/dist/operator/errors.js +9 -2
- package/dist/operator/index.js +1 -1
- package/dist/operator/operator.js +382 -145
- package/dist/operator/render.js +28 -10
- package/dist/operator/session-tools.js +9 -12
- package/dist/operator/view.js +16 -4
- package/dist/protocol/conversation.js +2 -0
- package/dist/protocol/lifecycle.js +2 -0
- package/dist/protocol/reduce.js +1 -0
- package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
- package/dist/types/operator/errors.d.ts +3 -1
- package/dist/types/operator/errors.d.ts.map +1 -1
- package/dist/types/operator/index.d.ts +1 -1
- package/dist/types/operator/index.d.ts.map +1 -1
- package/dist/types/operator/operator.d.ts.map +1 -1
- package/dist/types/operator/render.d.ts +2 -0
- package/dist/types/operator/render.d.ts.map +1 -1
- package/dist/types/operator/session-tools.d.ts +1 -4
- package/dist/types/operator/session-tools.d.ts.map +1 -1
- package/dist/types/operator/types.d.ts +73 -13
- package/dist/types/operator/types.d.ts.map +1 -1
- package/dist/types/operator/view.d.ts.map +1 -1
- package/dist/types/protocol/conversation.d.ts +3 -0
- package/dist/types/protocol/conversation.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +2 -0
- package/dist/types/protocol/lifecycle.d.ts.map +1 -1
- package/dist/types/protocol/reduce.d.ts.map +1 -1
- package/dist/types/protocol/wire-api.d.ts +1 -0
- package/dist/types/protocol/wire-api.d.ts.map +1 -1
- package/dist/types/protocol/wire.d.ts +2 -0
- package/dist/types/protocol/wire.d.ts.map +1 -1
- package/docs/consuming.md +55 -13
- package/package.json +1 -1
- package/src/core/runtime/event-processor.ts +14 -9
- package/src/operator/errors.ts +12 -4
- package/src/operator/index.ts +1 -1
- package/src/operator/operator.ts +489 -146
- package/src/operator/render.ts +29 -8
- package/src/operator/session-tools.ts +9 -12
- package/src/operator/types.ts +77 -12
- package/src/operator/view.ts +26 -9
- package/src/protocol/conversation.ts +2 -0
- package/src/protocol/lifecycle.ts +2 -0
- package/src/protocol/reduce.ts +2 -0
package/src/operator/operator.ts
CHANGED
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
// @ref LLP 0014#decision — the session tools are the engine's; who may call them, and what a session is, stay the host's
|
|
11
|
-
// @ref LLP 0019#one-call-one-message — a
|
|
11
|
+
// @ref LLP 0019#one-call-one-message — a steer names its turn, a queue belongs to the host
|
|
12
12
|
|
|
13
13
|
import { z } from "zod";
|
|
14
14
|
import { tokenDigest } from "../protocol/credentials.ts";
|
|
15
15
|
import { generateUUIDv7 } from "../protocol/ids.ts";
|
|
16
16
|
import { ORIGIN_FIELD_MAX, type Origin, OriginSchema } from "../protocol/origin.ts";
|
|
17
|
-
import { type Hint, OperatorError, Refused, refuse } from "./errors.ts";
|
|
17
|
+
import { type Hint, OperatorError, Refused, readRefusal, refuse } from "./errors.ts";
|
|
18
18
|
import { refOf, resolve as resolveRef } from "./refs.ts";
|
|
19
19
|
import {
|
|
20
20
|
FULL_READ_LIMIT,
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
callHint,
|
|
25
25
|
describeWaiting,
|
|
26
26
|
json,
|
|
27
|
+
noteLines,
|
|
27
28
|
oneLine,
|
|
28
29
|
perRequest,
|
|
29
30
|
personOnly,
|
|
@@ -48,7 +49,9 @@ import type {
|
|
|
48
49
|
ProjectRef,
|
|
49
50
|
Refusal,
|
|
50
51
|
SessionView,
|
|
52
|
+
SteerInput,
|
|
51
53
|
ToolInfo,
|
|
54
|
+
TurnEnded,
|
|
52
55
|
TurnFact,
|
|
53
56
|
WaitCaps,
|
|
54
57
|
Waiting,
|
|
@@ -157,6 +160,9 @@ interface Scope {
|
|
|
157
160
|
/** What a joining call gets when its own wait ends before the call it joined. */
|
|
158
161
|
const PENDING = Symbol("pending");
|
|
159
162
|
|
|
163
|
+
type When = "steer" | "queue" | "interrupt";
|
|
164
|
+
type SteerReceipt = NonNullable<TurnEnded["steers"]>[string];
|
|
165
|
+
|
|
160
166
|
interface Def<Auth> {
|
|
161
167
|
name: string;
|
|
162
168
|
title: string;
|
|
@@ -226,17 +232,21 @@ export function createOperator<Auth = unknown>(
|
|
|
226
232
|
: refuse.unsupported(refusal.detail);
|
|
227
233
|
|
|
228
234
|
/**
|
|
229
|
-
*
|
|
230
|
-
*
|
|
235
|
+
* Word a host's refusal, naming the sessions of a targeted operation
|
|
236
|
+
* as the caller sees them.
|
|
231
237
|
*/
|
|
232
238
|
function fromHost(
|
|
233
239
|
error: unknown,
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
+
scope: Scope,
|
|
241
|
+
target: {
|
|
242
|
+
caller: Caller<Auth>;
|
|
243
|
+
all: readonly Entry[];
|
|
244
|
+
about: string;
|
|
245
|
+
undone: "archived" | "started in it";
|
|
246
|
+
},
|
|
247
|
+
): OperatorError {
|
|
248
|
+
if (!(error instanceof Refused)) return asRefusal(error, scope);
|
|
249
|
+
const { caller, all, about, undone } = target;
|
|
240
250
|
const { code, sessions = [] } = error.refusal;
|
|
241
251
|
const named = sessions.map((id) => all.find((e) => e.id === id));
|
|
242
252
|
const refs = sessions.map((id, i) => {
|
|
@@ -269,6 +279,18 @@ export function createOperator<Auth = unknown>(
|
|
|
269
279
|
return asError(error.refusal);
|
|
270
280
|
}
|
|
271
281
|
|
|
282
|
+
function refusedWrite(error: Refused | OperatorError, ref: string, undone: "sent" | "queued") {
|
|
283
|
+
if (error instanceof OperatorError) return error;
|
|
284
|
+
const { code, detail, retryAfter } = error.refusal;
|
|
285
|
+
const what = undone === "sent" ? "sent to" : "queued for";
|
|
286
|
+
const retry = retryAfter === undefined ? "" : ` Try again in ${retryAfter}s.`;
|
|
287
|
+
return new OperatorError(code, `Nothing was ${what} ${quoted(ref)}.${retry}`, {
|
|
288
|
+
detail: oneLine(detail ?? ""),
|
|
289
|
+
retryAfter,
|
|
290
|
+
next: code === "busy" ? hint("wait_for_sessions", { sessions: [ref] }) : undefined,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
272
294
|
/**
|
|
273
295
|
* A mutation the host was asked to make: its answer, or `undefined` when
|
|
274
296
|
* none came in the call's scope (it may have been made). A definite
|
|
@@ -509,8 +531,23 @@ export function createOperator<Auth = unknown>(
|
|
|
509
531
|
}
|
|
510
532
|
|
|
511
533
|
/** The host's view in the scope; past it, still working as far as anyone knows. */
|
|
512
|
-
const viewIn = (caller: Caller<Auth>, sessionId: string, scope: Scope) =>
|
|
513
|
-
within(scope, host.view(caller, sessionId, { last
|
|
534
|
+
const viewIn = (caller: Caller<Auth>, sessionId: string, scope: Scope, last = 20) =>
|
|
535
|
+
within(scope, host.view(caller, sessionId, { last }), () => UNREAD);
|
|
536
|
+
|
|
537
|
+
/** A failed read after delivery still leaves the sender its confirmed receipt. */
|
|
538
|
+
async function viewAfterDelivery(
|
|
539
|
+
caller: Caller<Auth>,
|
|
540
|
+
sessionId: string,
|
|
541
|
+
scope: Scope,
|
|
542
|
+
last: number,
|
|
543
|
+
) {
|
|
544
|
+
try {
|
|
545
|
+
return await viewIn(caller, sessionId, scope, last);
|
|
546
|
+
} catch (error) {
|
|
547
|
+
scope.report?.(error);
|
|
548
|
+
return UNREAD;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
514
551
|
|
|
515
552
|
/**
|
|
516
553
|
* The one settlement rule: a session waiting on an answer is settled at
|
|
@@ -533,7 +570,7 @@ export function createOperator<Auth = unknown>(
|
|
|
533
570
|
if (look.view === UNREAD) return "could not be read before the wait ended";
|
|
534
571
|
const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
|
|
535
572
|
if (look.view.status === "error" && !look.view.lastEnded && !look.view.turns.length)
|
|
536
|
-
return `status: error (could not be set up)\n${quote(look.entry.error ?? "setup failed")}`;
|
|
573
|
+
return `status: error (could not be set up)\n${quote(look.entry.error ?? "setup failed")}${noteLines(look.view.note)}`;
|
|
537
574
|
const done =
|
|
538
575
|
look.settled && look.view.status !== "needs_input" && look.view.status !== "archived";
|
|
539
576
|
const note =
|
|
@@ -689,8 +726,7 @@ export function createOperator<Auth = unknown>(
|
|
|
689
726
|
lines.push(`you are ${who} (id ${json(caller.id)})`);
|
|
690
727
|
}
|
|
691
728
|
const described = host.describe ? await within(scope, host.describe(caller)) : undefined;
|
|
692
|
-
|
|
693
|
-
return lines.join("\n");
|
|
729
|
+
return lines.join("\n") + noteLines(described);
|
|
694
730
|
},
|
|
695
731
|
});
|
|
696
732
|
|
|
@@ -891,31 +927,69 @@ export function createOperator<Auth = unknown>(
|
|
|
891
927
|
const listModels = def({
|
|
892
928
|
name: "list_models",
|
|
893
929
|
title: "List models",
|
|
894
|
-
description:
|
|
895
|
-
"The agents and models a new session can run, with each model's thinking levels and the defaults. Use these names in start_session.",
|
|
930
|
+
description: `The agents and models a new session can run, with each model's thinking levels and the defaults.${host.agents ? " Each agent's state says whether it can run here." : ""} Use these names in start_session.`,
|
|
896
931
|
input: {
|
|
897
932
|
agent: words()
|
|
898
933
|
.optional()
|
|
899
934
|
.describe("Only this agent (harness); an unknown agent names those listed here"),
|
|
900
935
|
},
|
|
901
936
|
effect: "read",
|
|
902
|
-
needs: ["models"],
|
|
937
|
+
needs: [host.agents ? "agents" : "models"],
|
|
903
938
|
async run({ agent }, caller, scope) {
|
|
904
|
-
const
|
|
905
|
-
|
|
906
|
-
|
|
939
|
+
const read = async <T>(source?: (caller: Caller<Auth>) => Promise<T[]>) =>
|
|
940
|
+
source && within(scope, source.call(host, caller));
|
|
941
|
+
const [catalog, readiness] = await Promise.allSettled([read(host.models), read(host.agents)]);
|
|
942
|
+
const failures: string[] = [];
|
|
943
|
+
let refused: OperatorError | undefined;
|
|
944
|
+
function rows<T>(result: PromiseSettledResult<T>, source: string, missing: string) {
|
|
945
|
+
if (result.status === "fulfilled") return result.value;
|
|
946
|
+
const { reason } = result;
|
|
947
|
+
if (
|
|
948
|
+
reason instanceof Refused ||
|
|
949
|
+
reason instanceof OperatorError ||
|
|
950
|
+
reason instanceof Over
|
|
951
|
+
) {
|
|
952
|
+
const error =
|
|
953
|
+
reason instanceof Refused ? readRefusal(reason.refusal) : asRefusal(reason, scope);
|
|
954
|
+
refused ??= error;
|
|
955
|
+
failures.push(`${source}: ${error.message}`);
|
|
956
|
+
} else {
|
|
957
|
+
scope.report?.(reason);
|
|
958
|
+
failures.push(missing);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const models = rows(catalog, "models", "models could not be read");
|
|
962
|
+
const agents = rows(readiness, "agents", "the agents' states could not be read.");
|
|
963
|
+
if (!models && !agents) throw refused ?? refuse.failed();
|
|
964
|
+
const states = new Map(agents?.map((a) => [a.harness, a]));
|
|
965
|
+
const harnesses = [...new Set([...(models ?? []).map((m) => m.harness), ...states.keys()])];
|
|
966
|
+
if (agent && !harnesses.some((h) => h === agent)) {
|
|
967
|
+
if (failures.length)
|
|
968
|
+
return [`${json(agent)} is not in what could be read; try again.`, ...failures].join(
|
|
969
|
+
"\n",
|
|
970
|
+
);
|
|
907
971
|
throw refuse.invalidInput(
|
|
908
972
|
"list_models",
|
|
909
973
|
"agent",
|
|
910
974
|
`${json(agent)} is unknown here; the agents listed are ${harnesses.map(json).join(", ") || "(none)"}`,
|
|
911
975
|
);
|
|
976
|
+
}
|
|
912
977
|
const lines: string[] = [];
|
|
913
978
|
for (const harness of harnesses) {
|
|
914
979
|
if (agent && harness !== agent) continue;
|
|
915
|
-
const mine = models
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
);
|
|
980
|
+
const mine = models?.filter((m) => m.harness === harness) ?? [];
|
|
981
|
+
let label =
|
|
982
|
+
oneLine(harness) + (mine.some((m) => m.defaultHarness) ? " (default agent)" : "");
|
|
983
|
+
const entry = states.get(harness);
|
|
984
|
+
if (entry) {
|
|
985
|
+
const state = ["ready", "signed_out", "not_installed"].includes(entry.state)
|
|
986
|
+
? entry.state.replace("_", " ")
|
|
987
|
+
: "unknown";
|
|
988
|
+
const detail = oneLine(entry.detail ?? "");
|
|
989
|
+
label += ` ${state}${detail ? `: ${detail}` : ""}`;
|
|
990
|
+
}
|
|
991
|
+
lines.push(label);
|
|
992
|
+
if (!mine.length && catalog.status === "fulfilled") lines.push(" no models listed");
|
|
919
993
|
for (const m of mine) {
|
|
920
994
|
const levels = m.thinkingLevels.length
|
|
921
995
|
? `thinking: ${m.thinkingLevels.map(oneLine).join(", ")}${m.defaultThinkingLevel ? ` (default ${oneLine(m.defaultThinkingLevel)})` : ""}`
|
|
@@ -925,7 +999,8 @@ export function createOperator<Auth = unknown>(
|
|
|
925
999
|
);
|
|
926
1000
|
}
|
|
927
1001
|
}
|
|
928
|
-
|
|
1002
|
+
if (!lines.length && catalog.status === "fulfilled") lines.push("no models listed");
|
|
1003
|
+
return [...lines, ...failures].join("\n");
|
|
929
1004
|
},
|
|
930
1005
|
});
|
|
931
1006
|
|
|
@@ -978,9 +1053,11 @@ export function createOperator<Auth = unknown>(
|
|
|
978
1053
|
];
|
|
979
1054
|
for (const look of looks) {
|
|
980
1055
|
if (!look.settled) {
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1056
|
+
const status =
|
|
1057
|
+
look.view === UNREAD
|
|
1058
|
+
? "could not be read before the wait ended"
|
|
1059
|
+
: `working${noteLines(look.view.note)}`;
|
|
1060
|
+
lines.push(`- ${quoted(look.ref)}: ${status.replace(/\n/g, "\n ")}`);
|
|
984
1061
|
continue;
|
|
985
1062
|
}
|
|
986
1063
|
const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
|
|
@@ -1043,7 +1120,7 @@ export function createOperator<Auth = unknown>(
|
|
|
1043
1120
|
// ---- sending: one call, one message --------------------------------------------------
|
|
1044
1121
|
|
|
1045
1122
|
/** One turn by id, in the scope; unknown past it. */
|
|
1046
|
-
const turnIn = (caller: Caller<Auth>, sessionId: string, turnId: string, scope: Scope) =>
|
|
1123
|
+
const turnIn = async (caller: Caller<Auth>, sessionId: string, turnId: string, scope: Scope) =>
|
|
1047
1124
|
within<TurnFact>(scope, host.turn(caller, sessionId, turnId), () => ({ state: "unknown" }));
|
|
1048
1125
|
|
|
1049
1126
|
/**
|
|
@@ -1062,38 +1139,224 @@ export function createOperator<Auth = unknown>(
|
|
|
1062
1139
|
if (!open(caller, cutoff)) throw new Over("the call ended before this was done");
|
|
1063
1140
|
};
|
|
1064
1141
|
|
|
1065
|
-
/**
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1142
|
+
/** A lost send, steer or queue answer gets one retry with the same input. */
|
|
1143
|
+
async function sendWithRetry<T>(
|
|
1144
|
+
{
|
|
1145
|
+
caller,
|
|
1146
|
+
scope,
|
|
1147
|
+
cutoff,
|
|
1148
|
+
ref,
|
|
1149
|
+
undone,
|
|
1150
|
+
late,
|
|
1151
|
+
unconfirmed,
|
|
1152
|
+
busy,
|
|
1153
|
+
}: {
|
|
1154
|
+
caller: Caller<Auth>;
|
|
1155
|
+
scope: Scope;
|
|
1156
|
+
cutoff: number;
|
|
1157
|
+
ref: string;
|
|
1158
|
+
undone: "sent" | "queued";
|
|
1159
|
+
late: () => string;
|
|
1160
|
+
unconfirmed: string;
|
|
1161
|
+
busy?: string;
|
|
1162
|
+
},
|
|
1163
|
+
dispatch: () => Promise<T>,
|
|
1164
|
+
): Promise<string | { answer: T; retried: boolean }> {
|
|
1165
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1166
|
+
const until = attempt === 0 ? cutoff : scope.end;
|
|
1167
|
+
if (!open(caller, until)) return attempt ? unconfirmed : late();
|
|
1168
|
+
try {
|
|
1169
|
+
await assertMay(caller, "write", "send_message", scope);
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
if (attempt === 0) {
|
|
1172
|
+
if (error instanceof Over) return late();
|
|
1173
|
+
throw error;
|
|
1174
|
+
}
|
|
1175
|
+
scope.report?.(error);
|
|
1176
|
+
return unconfirmed;
|
|
1177
|
+
}
|
|
1178
|
+
if (!open(caller, until)) return attempt ? unconfirmed : late();
|
|
1179
|
+
try {
|
|
1180
|
+
const sending = dispatch();
|
|
1181
|
+
if (scope.report) void sending.catch(scope.report);
|
|
1182
|
+
return { answer: await within(scope, sending), retried: attempt > 0 };
|
|
1183
|
+
} catch (error) {
|
|
1184
|
+
scope.report?.(error);
|
|
1185
|
+
if (error instanceof OperatorError || error instanceof Refused) {
|
|
1186
|
+
if (attempt) return unconfirmed;
|
|
1187
|
+
if (busy && error instanceof Refused) {
|
|
1188
|
+
const { code, detail, retryAfter, state, sessions } = error.refusal;
|
|
1189
|
+
if (
|
|
1190
|
+
code === "busy" &&
|
|
1191
|
+
detail === undefined &&
|
|
1192
|
+
retryAfter === undefined &&
|
|
1193
|
+
state === undefined &&
|
|
1194
|
+
sessions === undefined
|
|
1195
|
+
)
|
|
1196
|
+
return busy;
|
|
1197
|
+
}
|
|
1198
|
+
throw refusedWrite(error, ref, undone);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
return unconfirmed;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
const resendHint = (ref: string, when: "queue" | "steer") =>
|
|
1206
|
+
line(
|
|
1207
|
+
hint("send_message", {
|
|
1208
|
+
session: ref,
|
|
1209
|
+
message: "<the same message>",
|
|
1210
|
+
when: when === "steer" && defaultWhen === "steer" ? undefined : when,
|
|
1211
|
+
}),
|
|
1212
|
+
);
|
|
1213
|
+
|
|
1214
|
+
const turnAsks = (view: SessionView, turnId: string) =>
|
|
1215
|
+
view.running === turnId && view.status === "needs_input";
|
|
1216
|
+
|
|
1217
|
+
/** Follow until the named turn ends, asks for input or gives this steer a receipt. */
|
|
1218
|
+
function followTurn(
|
|
1219
|
+
caller: Caller<Auth>,
|
|
1220
|
+
sessionId: string,
|
|
1221
|
+
turnId: string,
|
|
1222
|
+
scope: Scope,
|
|
1223
|
+
when: When,
|
|
1224
|
+
steerId?: string,
|
|
1225
|
+
) {
|
|
1226
|
+
let receipt: SteerReceipt | undefined;
|
|
1227
|
+
return waitUntil<{ fact: TurnFact & { receipt?: SteerReceipt }; view?: SessionView }>(
|
|
1228
|
+
scope,
|
|
1229
|
+
() => [sessionId],
|
|
1230
|
+
async () => {
|
|
1231
|
+
const reading = turnIn(caller, sessionId, turnId, scope);
|
|
1232
|
+
if (steerId) {
|
|
1233
|
+
const fact = await reading.catch((error) => scope.report?.(error));
|
|
1234
|
+
if (fact && fact.state !== "unknown") receipt ??= fact.steers?.[steerId];
|
|
1235
|
+
const ended = fact?.state === "ended";
|
|
1236
|
+
const view = await viewAfterDelivery(caller, sessionId, scope, ended ? 20 : 1);
|
|
1237
|
+
const received =
|
|
1238
|
+
fact?.state === "running" && receipt && (view === UNREAD || view.running === turnId);
|
|
1239
|
+
return {
|
|
1240
|
+
done: !fact || ended || !!received || turnAsks(view, turnId),
|
|
1241
|
+
value: { fact: { ...(fact ?? { state: "unknown" }), receipt }, view },
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
const fact = await reading;
|
|
1245
|
+
if (fact.state === "ended" || when === "interrupt")
|
|
1246
|
+
return { done: fact.state === "ended", value: { fact } };
|
|
1247
|
+
const view = await viewIn(caller, sessionId, scope);
|
|
1248
|
+
return { done: turnAsks(view, turnId), value: { fact, view } };
|
|
1249
|
+
},
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
async function waitsOn(
|
|
1254
|
+
caller: Caller<Auth>,
|
|
1255
|
+
entry: Entry,
|
|
1256
|
+
ref: string,
|
|
1257
|
+
view: SessionView,
|
|
1258
|
+
scope: Scope,
|
|
1259
|
+
afterSteer = false,
|
|
1260
|
+
) {
|
|
1261
|
+
const context = await waitingContext(caller, entry, ref, view, scope);
|
|
1262
|
+
const whose = context.canAnswer ? "your" : "the person's";
|
|
1263
|
+
const lines = view.waiting.map((w) => describeWaiting(w, perRequest(context, w)));
|
|
1264
|
+
return `it waits on ${whose} answer${afterSteer ? " first" : ""}.${noteLines(view.note)}\n${lines.join("\n")}`;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
const queuedSteer = (turnId: string, why: "ended without reading it" | "did not take it") =>
|
|
1268
|
+
`turn ${json(turnId)} ${why}; the product queued it as its own turn.`;
|
|
1269
|
+
|
|
1270
|
+
/** Follow this steer in this turn. Acceptance and the user echo are separate receipts. */
|
|
1271
|
+
async function steerReceipt(
|
|
1272
|
+
caller: Caller<Auth>,
|
|
1273
|
+
entry: Entry,
|
|
1274
|
+
ref: string,
|
|
1275
|
+
{ turnId, steerId, origin }: SteerInput,
|
|
1276
|
+
scope: Scope,
|
|
1277
|
+
) {
|
|
1278
|
+
const lead = `steered ${quoted(ref)} (turn ${json(turnId)}):`;
|
|
1279
|
+
const read = line(hint("read_session", { session: ref }));
|
|
1280
|
+
const unknown = `${lead} accepted; whether it was read is not confirmed`;
|
|
1281
|
+
const seen = await followTurn(caller, entry.id, turnId, scope, "steer", steerId).catch(
|
|
1282
|
+
(error) => scope.report?.(error),
|
|
1283
|
+
);
|
|
1284
|
+
if (!seen) return `${unknown}.${read}`;
|
|
1285
|
+
const { fact, view = UNREAD } = seen.value;
|
|
1286
|
+
const { receipt } = fact;
|
|
1287
|
+
const note = noteLines(view.note);
|
|
1288
|
+
const ended = fact.state === "ended";
|
|
1289
|
+
const stopped = ended && fact.outcome === "cancelled";
|
|
1290
|
+
if (receipt === "undelivered") {
|
|
1291
|
+
if (stopped)
|
|
1292
|
+
return `nothing reached ${quoted(ref)}: its turn was stopped${stoppedBy(fact.cancelledBy, origin)} before reading it.${note}`;
|
|
1293
|
+
const why = ended
|
|
1294
|
+
? "its turn ended before reading it. Send it again."
|
|
1295
|
+
: "its turn did not take it.";
|
|
1296
|
+
return `nothing reached ${quoted(ref)}: ${why}${note}${resendHint(ref, "queue")}`;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
const question =
|
|
1300
|
+
!ended && receipt !== "queued" && turnAsks(view, turnId)
|
|
1301
|
+
? await waitsOn(caller, entry, ref, view, scope, !receipt).catch((error) =>
|
|
1302
|
+
scope.report?.(error),
|
|
1303
|
+
)
|
|
1304
|
+
: undefined;
|
|
1305
|
+
let head: string;
|
|
1306
|
+
if (receipt === "read") head = `${lead} read.`;
|
|
1307
|
+
else if (receipt === "queued") {
|
|
1308
|
+
const who =
|
|
1309
|
+
stopped && fact.cancelledBy ? ` It was stopped${stoppedBy(fact.cancelledBy, origin)}.` : "";
|
|
1310
|
+
head = queuedSteer(turnId, ended ? "ended without reading it" : "did not take it") + who;
|
|
1311
|
+
} else if (fact.state === "running" && fact.steers && view.running === turnId) {
|
|
1312
|
+
const later = host.queue
|
|
1313
|
+
? "If its turn ends first, the product keeps it in its queue."
|
|
1314
|
+
: "If the turn ends before it reads it, nothing of it runs later.";
|
|
1315
|
+
head = `${lead} accepted, not yet read. ${later}`;
|
|
1316
|
+
} else {
|
|
1317
|
+
if (question) return `${unknown}: ${question}`;
|
|
1318
|
+
head = `${unknown}.`;
|
|
1319
|
+
}
|
|
1320
|
+
if (question) return `${head}\n${question}`;
|
|
1321
|
+
if (!ended) return head + note + (receipt ? "" : read);
|
|
1322
|
+
const outcome = await endedOutcome(caller, entry, ref, turnId, fact, view, scope).catch(
|
|
1323
|
+
(error) => {
|
|
1324
|
+
scope.report?.(error);
|
|
1325
|
+
return `status: ${fact.outcome}${note}${read}`;
|
|
1326
|
+
},
|
|
1327
|
+
);
|
|
1328
|
+
return `${head}\n${outcome}${!receipt && !outcome.endsWith(read) ? read : ""}`;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1072
1331
|
async function deliver(
|
|
1073
1332
|
caller: Caller<Auth>,
|
|
1074
1333
|
entry: Entry,
|
|
1075
1334
|
ref: string,
|
|
1076
1335
|
message: string,
|
|
1077
1336
|
all: readonly Entry[],
|
|
1078
|
-
|
|
1337
|
+
when: When,
|
|
1079
1338
|
scope: Scope,
|
|
1080
1339
|
): Promise<string> {
|
|
1081
1340
|
// Once an interrupt's stop is confirmed, every later outcome of the call says so:
|
|
1082
1341
|
// a refusal stays one, with the stop in its words; an abort or a failure says it too.
|
|
1083
1342
|
const done = { stopped: false };
|
|
1084
1343
|
try {
|
|
1085
|
-
return await deliverIn(caller, entry, ref, message, all,
|
|
1344
|
+
return await deliverIn(caller, entry, ref, message, all, when, scope, done);
|
|
1086
1345
|
} catch (error) {
|
|
1087
1346
|
if (!done.stopped) throw error;
|
|
1088
|
-
const stop = `stopped ${quoted(ref)}'s turn; not sent
|
|
1347
|
+
const stop = `stopped ${quoted(ref)}'s turn; not sent`;
|
|
1089
1348
|
if (error instanceof Over)
|
|
1090
|
-
return `${stop} the call ended (its wait, or the caller gave it up) before the message was sent.`;
|
|
1349
|
+
return `${stop}: the call ended (its wait, or the caller gave it up) before the message was sent.`;
|
|
1091
1350
|
const refusal = asRefusal(error, scope);
|
|
1092
|
-
const
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
.
|
|
1096
|
-
|
|
1351
|
+
const body = refusal.message.replace(/^refused \([a-z_]+\): /, "");
|
|
1352
|
+
const target = `Nothing was sent to ${quoted(ref)}.`;
|
|
1353
|
+
const reason = body.startsWith(target)
|
|
1354
|
+
? body.slice(target.length)
|
|
1355
|
+
: body.replace(/ Nothing was \w+\./, "");
|
|
1356
|
+
const why = reason.replace(/\n {2}/, " ").trim();
|
|
1357
|
+
throw new OperatorError(refusal.code, why ? `${stop}: ${why}` : `${stop}.`, {
|
|
1358
|
+
retryAfter: refusal.retryAfter,
|
|
1359
|
+
});
|
|
1097
1360
|
}
|
|
1098
1361
|
}
|
|
1099
1362
|
|
|
@@ -1103,64 +1366,131 @@ export function createOperator<Auth = unknown>(
|
|
|
1103
1366
|
ref: string,
|
|
1104
1367
|
message: string,
|
|
1105
1368
|
all: readonly Entry[],
|
|
1106
|
-
|
|
1369
|
+
when: When,
|
|
1107
1370
|
scope: Scope,
|
|
1108
1371
|
done: { stopped: boolean },
|
|
1109
1372
|
): Promise<string> {
|
|
1110
1373
|
const you = senderOf(caller, all);
|
|
1374
|
+
const interrupt = when === "interrupt";
|
|
1111
1375
|
const notSent = (why: string) =>
|
|
1112
1376
|
done.stopped
|
|
1113
1377
|
? `stopped ${quoted(ref)}'s turn; not sent: ${why}`
|
|
1114
1378
|
: `nothing was sent to ${quoted(ref)}: ${why}`;
|
|
1115
1379
|
const again = line(hint("wait_for_sessions", { sessions: [ref] }));
|
|
1380
|
+
const read = line(hint("read_session", { session: ref }));
|
|
1381
|
+
const late = () => {
|
|
1382
|
+
const why = done.stopped
|
|
1383
|
+
? "this call's wait ended before the message could follow."
|
|
1384
|
+
: "this call's wait ended first.";
|
|
1385
|
+
const retry = interrupt ? again : resendHint(ref, when);
|
|
1386
|
+
return `${notSent(why)} Send again.${retry}`;
|
|
1387
|
+
};
|
|
1116
1388
|
const starter =
|
|
1117
1389
|
caller.kind === "session" && all.find((e) => e.id === caller.sessionId)?.startedBy;
|
|
1118
|
-
const
|
|
1390
|
+
const starterHint =
|
|
1119
1391
|
!interrupt && starter && starter.kind === "session" && starter.sessionId === entry.id
|
|
1120
1392
|
? "This session started you. End your turn with your report. If it is waiting for you, its wait receives your reply."
|
|
1121
|
-
:
|
|
1122
|
-
const
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1393
|
+
: undefined;
|
|
1394
|
+
const busy = (why: string, note?: string) =>
|
|
1395
|
+
`${notSent(why)} ${starterHint ?? "Wait for it, then send again."}${noteLines(note)}${starterHint ? "" : again}`;
|
|
1396
|
+
const advice = starterHint ? ` ${starterHint}` : "";
|
|
1397
|
+
const withOutcome = async (reading: Promise<string>, confirmed: string, unread: string) => {
|
|
1398
|
+
const outcome = await reading.catch((error) => scope.report?.(error));
|
|
1399
|
+
return outcome ? `${confirmed}\n${outcome}` : unread + read;
|
|
1127
1400
|
};
|
|
1401
|
+
const asks = async (view: SessionView) =>
|
|
1402
|
+
notSent(await waitsOn(caller, entry, ref, view, scope));
|
|
1403
|
+
const firstCutoff = scope.deadline <= scope.from ? scope.end : scope.deadline;
|
|
1404
|
+
const delivery = { caller, scope, ref, late, cutoff: firstCutoff };
|
|
1405
|
+
if (when === "queue" && host.queue) {
|
|
1406
|
+
const input = { turnId: generateUUIDv7(), message, origin: you };
|
|
1407
|
+
const result = await sendWithRetry(
|
|
1408
|
+
{
|
|
1409
|
+
...delivery,
|
|
1410
|
+
undone: "queued",
|
|
1411
|
+
unconfirmed: `not confirmed: the request to queue for ${quoted(ref)} got no answer. Do not send it again: the session's note says what its queue holds.${read}`,
|
|
1412
|
+
},
|
|
1413
|
+
() => host.queue!(caller, entry.id, input),
|
|
1414
|
+
);
|
|
1415
|
+
if (typeof result === "string") return result;
|
|
1416
|
+
const { position } = result.answer;
|
|
1417
|
+
const place = position === undefined ? "" : ` (position ${position})`;
|
|
1418
|
+
const lead = `queued for ${quoted(ref)}${place} in the product's queue`;
|
|
1419
|
+
const view = await viewAfterDelivery(caller, entry.id, scope, 1);
|
|
1420
|
+
const { lastEnded, note } = view;
|
|
1421
|
+
const started = `${lead}; it started at once.${advice}`;
|
|
1422
|
+
if (lastEnded?.turnId === input.turnId) {
|
|
1423
|
+
return withOutcome(
|
|
1424
|
+
endedOutcome(caller, entry, ref, input.turnId, lastEnded, view, scope),
|
|
1425
|
+
started,
|
|
1426
|
+
`${started}\nstatus: ${lastEnded.outcome}${noteLines(note)}`,
|
|
1427
|
+
);
|
|
1428
|
+
}
|
|
1429
|
+
if (view.running === input.turnId) {
|
|
1430
|
+
return withOutcome(
|
|
1431
|
+
ownOutcome(caller, entry, ref, input.turnId, scope),
|
|
1432
|
+
started,
|
|
1433
|
+
`${started} Its outcome could not be read.${noteLines(note)}`,
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
const queued = `${lead}.${advice}${noteLines(note)}`;
|
|
1437
|
+
if (view.status !== "needs_input") return queued;
|
|
1438
|
+
const waiting = await waitsOn(caller, entry, ref, { ...view, note: undefined }, scope).catch(
|
|
1439
|
+
(error) => scope.report?.(error),
|
|
1440
|
+
);
|
|
1441
|
+
return waiting ? `${queued}\n${waiting}` : queued;
|
|
1442
|
+
}
|
|
1128
1443
|
const view = await within(scope, host.view(caller, entry.id, { last: 1 }));
|
|
1129
1444
|
if (view.status === "needs_input" && !interrupt) return asks(view);
|
|
1130
1445
|
let paused = false;
|
|
1131
1446
|
if (view.running) {
|
|
1132
1447
|
const running = view.running;
|
|
1448
|
+
if (when === "steer") {
|
|
1449
|
+
const input = { turnId: running, steerId: generateUUIDv7(), message, origin: you };
|
|
1450
|
+
const unconfirmed = `not confirmed: read ${quoted(ref)} to see whether the steer arrived.${read}`;
|
|
1451
|
+
const result = await sendWithRetry({ ...delivery, undone: "sent", unconfirmed }, () =>
|
|
1452
|
+
host.steer!(caller, entry.id, input),
|
|
1453
|
+
);
|
|
1454
|
+
if (typeof result === "string") return result;
|
|
1455
|
+
if (result.retried && result.answer.outcome === "no_active_turn") return unconfirmed;
|
|
1456
|
+
if (result.answer.outcome === "queued") {
|
|
1457
|
+
const current = await viewAfterDelivery(caller, entry.id, scope, 1);
|
|
1458
|
+
return queuedSteer(running, "did not take it") + advice + noteLines(current.note);
|
|
1459
|
+
}
|
|
1460
|
+
if (result.answer.outcome === "no_active_turn")
|
|
1461
|
+
return `${notSent("its turn is not taking messages now.")}${advice}${resendHint(ref, "queue")}`;
|
|
1462
|
+
if (result.answer.outcome === "unsupported")
|
|
1463
|
+
return `${notSent("this agent takes no message while it works.")}${advice}${resendHint(ref, "queue")}`;
|
|
1464
|
+
if (starterHint)
|
|
1465
|
+
return `steered ${quoted(ref)} (turn ${json(running)}): accepted. ${starterHint}`;
|
|
1466
|
+
return steerReceipt(caller, entry, ref, input, scope);
|
|
1467
|
+
}
|
|
1133
1468
|
if (interrupt) {
|
|
1134
1469
|
// The package's stop, of this turn only, asked right before it is made, and only
|
|
1135
1470
|
// while the message could still be sent after it.
|
|
1136
1471
|
await assertMay(caller, "destructive", "send_message", scope);
|
|
1137
1472
|
const cancel = host.cancel as NonNullable<OperatorHost<Auth>["cancel"]>;
|
|
1138
|
-
if (!open(caller,
|
|
1473
|
+
if (!open(caller, firstCutoff))
|
|
1139
1474
|
return `${notSent("this call's wait ended first; its turn was not stopped.")} Send again.${again}`;
|
|
1140
1475
|
const stopped = await dispatched(scope, cancel.call(host, caller, entry.id, running));
|
|
1141
1476
|
if (stopped === undefined)
|
|
1142
1477
|
return `${notSent("its turn was asked to stop; that is not confirmed.")}${again}`;
|
|
1143
1478
|
done.stopped = stopped === "stopped";
|
|
1144
1479
|
}
|
|
1145
|
-
const seen = await
|
|
1146
|
-
scope,
|
|
1147
|
-
() => [entry.id],
|
|
1148
|
-
async () => {
|
|
1149
|
-
const fact = await turnIn(caller, entry.id, running, scope);
|
|
1150
|
-
if (fact.state === "ended" || interrupt)
|
|
1151
|
-
return { done: fact.state === "ended", value: { fact } };
|
|
1152
|
-
// A turn that starts waiting on an answer will not end on its own: say so now.
|
|
1153
|
-
const now = await viewIn(caller, entry.id, scope);
|
|
1154
|
-
const asking = now.status === "needs_input" && now.running === running ? now : undefined;
|
|
1155
|
-
return { done: asking !== undefined, value: { fact, asking } };
|
|
1156
|
-
},
|
|
1157
|
-
);
|
|
1480
|
+
const seen = await followTurn(caller, entry.id, running, scope, when);
|
|
1158
1481
|
live(caller);
|
|
1159
1482
|
paused = seen.paused;
|
|
1160
|
-
const { fact,
|
|
1161
|
-
if (
|
|
1483
|
+
const { fact, view: current } = seen.value;
|
|
1484
|
+
if (seen.done && current) return asks(current);
|
|
1162
1485
|
if (fact.state !== "ended")
|
|
1163
|
-
return
|
|
1486
|
+
return busy(
|
|
1487
|
+
done.stopped
|
|
1488
|
+
? "its turn's end was not seen before this call's wait ended."
|
|
1489
|
+
: interrupt
|
|
1490
|
+
? "its turn was asked to stop and has not yet."
|
|
1491
|
+
: "it was still working when this call's wait ended.",
|
|
1492
|
+
current?.note,
|
|
1493
|
+
);
|
|
1164
1494
|
if (fact.outcome === "cancelled" && !interrupt)
|
|
1165
1495
|
return notSent(
|
|
1166
1496
|
`its turn was stopped${stoppedBy(fact.cancelledBy, you)} while this call waited, so this message was not sent after it.`,
|
|
@@ -1168,66 +1498,65 @@ export function createOperator<Auth = unknown>(
|
|
|
1168
1498
|
}
|
|
1169
1499
|
// The cutoff: the call's grace only for a `wait: 0` call deciding on its first look,
|
|
1170
1500
|
// else its deadline; checked again after authorising, right before the send.
|
|
1171
|
-
const cutoff =
|
|
1172
|
-
const late = `${notSent(done.stopped ? "this call's wait ended before the message could follow." : "this call's wait ended first.")} Send again.${again}`;
|
|
1173
|
-
if (!open(caller, cutoff)) return late;
|
|
1501
|
+
const cutoff = paused ? scope.deadline : firstCutoff;
|
|
1174
1502
|
const turnId = generateUUIDv7();
|
|
1175
1503
|
const input = { turnId, message, origin: you };
|
|
1176
|
-
const unconfirmed = `${done.stopped ? `stopped ${quoted(ref)}'s turn; ` : ""}not confirmed: the send to ${quoted(ref)} got no answer. Read the session to see whether it arrived.${line(hint("read_session", { session: ref }))}`;
|
|
1177
|
-
let sent = false;
|
|
1178
|
-
for (let attempt = 0; attempt < 2 && !sent; attempt++) {
|
|
1179
|
-
if (attempt > 0) {
|
|
1180
|
-
// The same turn id again, which the engine converges on: only while the call
|
|
1181
|
-
// is open, within its time, and still allowed.
|
|
1182
|
-
if (!open(caller, scope.end)) return unconfirmed;
|
|
1183
|
-
try {
|
|
1184
|
-
await assertMay(caller, "write", "send_message", scope);
|
|
1185
|
-
} catch (error) {
|
|
1186
|
-
scope.report?.(error);
|
|
1187
|
-
return unconfirmed;
|
|
1188
|
-
}
|
|
1189
|
-
if (!open(caller, scope.end)) return unconfirmed;
|
|
1190
|
-
} else {
|
|
1191
|
-
await assertMay(caller, "write", "send_message", scope);
|
|
1192
|
-
if (!open(caller, cutoff)) return late;
|
|
1193
|
-
}
|
|
1194
|
-
try {
|
|
1195
|
-
const sending = host.send(caller, entry.id, input);
|
|
1196
|
-
if (scope.report) void sending.catch(scope.report);
|
|
1197
|
-
await within(scope, sending);
|
|
1198
|
-
sent = true;
|
|
1199
|
-
} catch (error) {
|
|
1200
|
-
// A host that threw before it had a promise (each error is told once).
|
|
1201
|
-
scope.report?.(error);
|
|
1202
|
-
const definite = error instanceof OperatorError || error instanceof Refused;
|
|
1203
|
-
if (definite && attempt > 0) return unconfirmed;
|
|
1204
|
-
if (definite && (error instanceof Refused ? error.refusal.code : error.code) === "busy")
|
|
1205
|
-
return `${notSent("another turn started there first.")} ${busyHint}`;
|
|
1206
|
-
if (definite) throw error;
|
|
1207
|
-
// No answer: once more with the same turn id.
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
if (!sent) return unconfirmed;
|
|
1211
1504
|
// An interrupt's stop is said in every result, the sent ones included.
|
|
1212
1505
|
const lead = done.stopped ? `stopped ${quoted(ref)}'s turn; ` : "";
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1506
|
+
const result = await sendWithRetry(
|
|
1507
|
+
{
|
|
1508
|
+
...delivery,
|
|
1509
|
+
cutoff,
|
|
1510
|
+
undone: "sent",
|
|
1511
|
+
busy: busy("another turn started there first."),
|
|
1512
|
+
unconfirmed: `${lead}not confirmed: the send to ${quoted(ref)} got no answer. Read the session to see whether it arrived.${read}`,
|
|
1513
|
+
},
|
|
1514
|
+
() => host.send(caller, entry.id, input),
|
|
1515
|
+
);
|
|
1516
|
+
if (typeof result === "string") return result;
|
|
1517
|
+
const sent = `${lead}sent to ${quoted(ref)}`;
|
|
1518
|
+
return withOutcome(
|
|
1519
|
+
ownOutcome(caller, entry, ref, turnId, scope),
|
|
1520
|
+
`${sent}.`,
|
|
1521
|
+
`${sent} (turn ${json(turnId)}); its outcome could not be read.`,
|
|
1522
|
+
);
|
|
1219
1523
|
}
|
|
1220
1524
|
|
|
1221
|
-
/**
|
|
1222
|
-
* A turn the package minted, followed by its id: its outcome once it ended;
|
|
1223
|
-
* what it waits on only while the session's running turn is this one; else
|
|
1224
|
-
* that it still works, or that its turn is not known, with a read hint. A
|
|
1225
|
-
* successor's question is never taken for its own.
|
|
1226
|
-
*/
|
|
1227
1525
|
/** Setup failed before any turn began: the only error a first task's unknown turn may report. */
|
|
1228
1526
|
const setupFailed = (view: SessionView) =>
|
|
1229
1527
|
view.status === "error" && !view.running && !view.lastEnded && view.turns.length === 0;
|
|
1230
1528
|
|
|
1529
|
+
async function endedOutcome(
|
|
1530
|
+
caller: Caller<Auth>,
|
|
1531
|
+
entry: Entry,
|
|
1532
|
+
ref: string,
|
|
1533
|
+
turnId: string,
|
|
1534
|
+
fact: Omit<TurnEnded, "turnId">,
|
|
1535
|
+
view: SessionView,
|
|
1536
|
+
scope: Scope,
|
|
1537
|
+
) {
|
|
1538
|
+
const at = view.turns.findIndex((t) => t.turnId === turnId);
|
|
1539
|
+
if (at < 0)
|
|
1540
|
+
return `status: ${fact.outcome}${noteLines(view.note)}${line(hint("read_session", { session: ref }))}`;
|
|
1541
|
+
const status =
|
|
1542
|
+
fact.outcome === "done" ? "idle" : fact.outcome === "cancelled" ? "stopped" : "error";
|
|
1543
|
+
const own: SessionView = {
|
|
1544
|
+
status,
|
|
1545
|
+
note: view.note,
|
|
1546
|
+
turns: view.turns.slice(0, at + 1),
|
|
1547
|
+
waiting: [],
|
|
1548
|
+
lastEnded: {
|
|
1549
|
+
turnId,
|
|
1550
|
+
outcome: fact.outcome,
|
|
1551
|
+
steers:
|
|
1552
|
+
fact.steers ?? (view.lastEnded?.turnId === turnId ? view.lastEnded.steers : undefined),
|
|
1553
|
+
},
|
|
1554
|
+
};
|
|
1555
|
+
const newer = view.turns.slice(at + 1).reduce((n, t) => n + t.messages.length, 0);
|
|
1556
|
+
return outcomeOf(caller, { entry, ref, view: own, settled: true }, scope, newer);
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/** Follow only the turn the call started. A successor's question belongs to the successor. */
|
|
1231
1560
|
async function ownOutcome(
|
|
1232
1561
|
caller: Caller<Auth>,
|
|
1233
1562
|
entry: Entry,
|
|
@@ -1241,22 +1570,14 @@ export function createOperator<Auth = unknown>(
|
|
|
1241
1570
|
async () => {
|
|
1242
1571
|
const fact = await turnIn(caller, entry.id, turnId, scope);
|
|
1243
1572
|
const view = await viewIn(caller, entry.id, scope);
|
|
1244
|
-
const asks = view
|
|
1573
|
+
const asks = turnAsks(view, turnId);
|
|
1245
1574
|
const failedSetup = fact.state === "unknown" && setupFailed(view);
|
|
1246
1575
|
return { done: fact.state === "ended" || asks || failedSetup, value: { fact, view } };
|
|
1247
1576
|
},
|
|
1248
1577
|
);
|
|
1249
1578
|
const { fact, view } = value;
|
|
1250
1579
|
const read = line(hint("read_session", { session: ref }));
|
|
1251
|
-
if (fact.state === "ended")
|
|
1252
|
-
const at = view.turns.findIndex((t) => t.turnId === turnId);
|
|
1253
|
-
const status =
|
|
1254
|
-
fact.outcome === "done" ? "idle" : fact.outcome === "cancelled" ? "stopped" : "error";
|
|
1255
|
-
if (at < 0) return `status: ${fact.outcome}${read}`;
|
|
1256
|
-
const own: SessionView = { status, turns: view.turns.slice(0, at + 1), waiting: [] };
|
|
1257
|
-
const newer = view.turns.slice(at + 1).reduce((n, t) => n + t.messages.length, 0);
|
|
1258
|
-
return outcomeOf(caller, { entry, ref, view: own, settled: true }, scope, newer);
|
|
1259
|
-
}
|
|
1580
|
+
if (fact.state === "ended") return endedOutcome(caller, entry, ref, turnId, fact, view, scope);
|
|
1260
1581
|
if (view.running === turnId)
|
|
1261
1582
|
return outcomeOf(caller, { entry, ref, view, settled: view.status === "needs_input" }, scope);
|
|
1262
1583
|
if (setupFailed(view)) {
|
|
@@ -1264,29 +1585,51 @@ export function createOperator<Auth = unknown>(
|
|
|
1264
1585
|
const current = all.find((e) => e.id === entry.id) ?? entry;
|
|
1265
1586
|
return outcomeOf(caller, { entry: current, ref, view, settled: true }, scope);
|
|
1266
1587
|
}
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
return `status:
|
|
1271
|
-
|
|
1588
|
+
const note = noteLines(view.note);
|
|
1589
|
+
if (view.status === "setting_up" || fact.state === "running") {
|
|
1590
|
+
const status = view.status === "setting_up" ? "setting_up" : "working";
|
|
1591
|
+
return `status: ${status}${note}${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
|
|
1592
|
+
}
|
|
1593
|
+
return `status: unknown (its turn is not known yet)${note}${read}`;
|
|
1272
1594
|
}
|
|
1273
1595
|
|
|
1596
|
+
const modes: When[] = ["queue"];
|
|
1597
|
+
if (host.steer) modes.unshift("steer");
|
|
1598
|
+
if (host.cancel) modes.push("interrupt");
|
|
1599
|
+
const defaultWhen = host.steer ? "steer" : "queue";
|
|
1274
1600
|
const sendMessage = def({
|
|
1275
1601
|
name: "send_message",
|
|
1276
1602
|
title: "Send message",
|
|
1277
|
-
description:
|
|
1278
|
-
"Send a message to a session's agent
|
|
1603
|
+
description: [
|
|
1604
|
+
"Send a message to a session's agent. It is told who sent it.",
|
|
1605
|
+
host.steer &&
|
|
1606
|
+
"Use steer for a correction or fact about the work in progress, and queue for a separate task after this one. With steer, an idle session starts a turn at once.",
|
|
1607
|
+
host.queue
|
|
1608
|
+
? "With queue, the task goes to the product's queue even if nothing is running. If it starts at once, this call follows its turn."
|
|
1609
|
+
: "With queue, an idle session starts a turn at once. This call waits for a running turn to end on its own. If the wait ends first or the turn is stopped, nothing is sent.",
|
|
1610
|
+
"A session waiting on an answer needs answer_request.",
|
|
1611
|
+
host.queue && "You can queue a separate task while the question stays open.",
|
|
1612
|
+
host.cancel &&
|
|
1613
|
+
"Use interrupt to stop the running turn and send now. Any question it waits on is dropped.",
|
|
1614
|
+
host.cancel && host.queue && "The product keeps its unread steers in its queue.",
|
|
1615
|
+
host.cancel && !host.queue && host.steer && "Its unread steers are dropped.",
|
|
1616
|
+
"If the session that started you is still working, end your turn with your report for its wait. Message a session the person started only when the person asked you to.",
|
|
1617
|
+
]
|
|
1618
|
+
.filter(Boolean)
|
|
1619
|
+
.join(" "),
|
|
1279
1620
|
input: {
|
|
1280
1621
|
session: sessionArg,
|
|
1281
1622
|
message: words().max(MAX_TEXT).describe("What to tell the agent"),
|
|
1282
1623
|
when: z
|
|
1283
|
-
.enum(
|
|
1624
|
+
.enum(modes)
|
|
1284
1625
|
.optional()
|
|
1285
|
-
.describe(
|
|
1286
|
-
wait: waitArg
|
|
1626
|
+
.describe(`How to deliver the message (default ${defaultWhen})`),
|
|
1627
|
+
wait: waitArg.describe(
|
|
1628
|
+
"Seconds to follow the message (0 looks once), until a steer is read or a new turn settles. To keep waiting, use read_session or wait_for_sessions. Sending again sends another message.",
|
|
1629
|
+
),
|
|
1287
1630
|
},
|
|
1288
1631
|
effect: "write",
|
|
1289
|
-
async run({ session, message, when =
|
|
1632
|
+
async run({ session, message, when = defaultWhen }, caller, scope) {
|
|
1290
1633
|
const { entry, ref, all } = await find(caller, session, scope);
|
|
1291
1634
|
if (caller.kind === "session" && entry.id === caller.sessionId) throw refuse.self("session");
|
|
1292
1635
|
if (entry.status === "archived") throw refuse.archived(hint, ref, entry.project?.name);
|
|
@@ -1295,9 +1638,9 @@ export function createOperator<Auth = unknown>(
|
|
|
1295
1638
|
if (when === "interrupt" && !host.cancel)
|
|
1296
1639
|
throw refuse.unsupported("This host cannot stop a turn.");
|
|
1297
1640
|
return once(
|
|
1298
|
-
json(["send", keyOf(caller), entry.id, message]),
|
|
1641
|
+
json(["send", keyOf(caller), entry.id, when, message]),
|
|
1299
1642
|
scope,
|
|
1300
|
-
() => deliver(caller, entry, ref, message, all, when
|
|
1643
|
+
() => deliver(caller, entry, ref, message, all, when, scope),
|
|
1301
1644
|
hint("read_session", { session: ref }),
|
|
1302
1645
|
);
|
|
1303
1646
|
},
|
|
@@ -1477,7 +1820,7 @@ export function createOperator<Auth = unknown>(
|
|
|
1477
1820
|
} catch (error) {
|
|
1478
1821
|
// Refused for certain: nothing was made, so the minute's slot is given back.
|
|
1479
1822
|
if (error instanceof OperatorError || error instanceof Refused) giveBack();
|
|
1480
|
-
throw
|
|
1823
|
+
throw fromHost(error, scope, { caller, all: now, about, undone: "started in it" });
|
|
1481
1824
|
}
|
|
1482
1825
|
});
|
|
1483
1826
|
const where = into
|
|
@@ -1768,7 +2111,7 @@ export function createOperator<Auth = unknown>(
|
|
|
1768
2111
|
}
|
|
1769
2112
|
}
|
|
1770
2113
|
} catch (error) {
|
|
1771
|
-
const refusal =
|
|
2114
|
+
const refusal = fromHost(error, scope, { caller, all, about, undone: "archived" });
|
|
1772
2115
|
if (!stopped.length) throw refusal;
|
|
1773
2116
|
// Still a refusal, so a batch of them is one; its own "nothing was done" is not so:
|
|
1774
2117
|
// the stops were made.
|