@zvada/agent-server 0.3.28 → 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.
Files changed (82) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/core/agents/acp/acp-agent.js +3 -1
  3. package/dist/core/agents/claude-code/claude-agent.js +2 -12
  4. package/dist/core/agents/claude-code/session.js +12 -8
  5. package/dist/core/agents/claude-code/turn.js +6 -2
  6. package/dist/core/agents/gemini/profile.js +2 -1
  7. package/dist/core/runtime/event-processor.js +9 -10
  8. package/dist/operator/errors.js +9 -2
  9. package/dist/operator/index.js +1 -1
  10. package/dist/operator/operator.js +403 -152
  11. package/dist/operator/render.js +31 -15
  12. package/dist/operator/session-tools.js +9 -12
  13. package/dist/operator/view.js +16 -4
  14. package/dist/protocol/config.js +4 -2
  15. package/dist/protocol/conversation.js +2 -0
  16. package/dist/protocol/lifecycle.js +2 -0
  17. package/dist/protocol/part-input.js +2 -6
  18. package/dist/protocol/reduce.js +1 -0
  19. package/dist/protocol/text-parts.js +10 -0
  20. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  21. package/dist/types/core/agents/acp/profile.d.ts +6 -1
  22. package/dist/types/core/agents/acp/profile.d.ts.map +1 -1
  23. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -2
  24. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  25. package/dist/types/core/agents/claude-code/options.d.ts +1 -1
  26. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  27. package/dist/types/core/agents/claude-code/session.d.ts +4 -6
  28. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  29. package/dist/types/core/agents/claude-code/turn.d.ts +3 -2
  30. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  31. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -1
  32. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  33. package/dist/types/operator/errors.d.ts +3 -1
  34. package/dist/types/operator/errors.d.ts.map +1 -1
  35. package/dist/types/operator/index.d.ts +1 -1
  36. package/dist/types/operator/index.d.ts.map +1 -1
  37. package/dist/types/operator/operator.d.ts.map +1 -1
  38. package/dist/types/operator/render.d.ts +2 -0
  39. package/dist/types/operator/render.d.ts.map +1 -1
  40. package/dist/types/operator/session-tools.d.ts +1 -4
  41. package/dist/types/operator/session-tools.d.ts.map +1 -1
  42. package/dist/types/operator/types.d.ts +77 -17
  43. package/dist/types/operator/types.d.ts.map +1 -1
  44. package/dist/types/operator/view.d.ts.map +1 -1
  45. package/dist/types/protocol/config.d.ts +4 -2
  46. package/dist/types/protocol/config.d.ts.map +1 -1
  47. package/dist/types/protocol/conversation.d.ts +3 -0
  48. package/dist/types/protocol/conversation.d.ts.map +1 -1
  49. package/dist/types/protocol/lifecycle.d.ts +2 -0
  50. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  51. package/dist/types/protocol/part-input.d.ts.map +1 -1
  52. package/dist/types/protocol/reduce.d.ts.map +1 -1
  53. package/dist/types/protocol/text-parts.d.ts +10 -0
  54. package/dist/types/protocol/text-parts.d.ts.map +1 -0
  55. package/dist/types/protocol/wire-api.d.ts +1 -0
  56. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  57. package/dist/types/protocol/wire.d.ts +2 -0
  58. package/dist/types/protocol/wire.d.ts.map +1 -1
  59. package/docs/consuming.md +57 -14
  60. package/docs/harnesses.md +14 -7
  61. package/package.json +1 -1
  62. package/src/core/agents/acp/acp-agent.ts +3 -1
  63. package/src/core/agents/acp/profile.ts +6 -0
  64. package/src/core/agents/claude-code/claude-agent.ts +2 -13
  65. package/src/core/agents/claude-code/options.ts +1 -1
  66. package/src/core/agents/claude-code/session.ts +12 -8
  67. package/src/core/agents/claude-code/turn.ts +7 -2
  68. package/src/core/agents/gemini/profile.ts +2 -1
  69. package/src/core/runtime/event-processor.ts +14 -9
  70. package/src/operator/errors.ts +12 -4
  71. package/src/operator/index.ts +1 -1
  72. package/src/operator/operator.ts +508 -152
  73. package/src/operator/render.ts +32 -15
  74. package/src/operator/session-tools.ts +9 -12
  75. package/src/operator/types.ts +81 -16
  76. package/src/operator/view.ts +26 -9
  77. package/src/protocol/config.ts +4 -2
  78. package/src/protocol/conversation.ts +2 -0
  79. package/src/protocol/lifecycle.ts +2 -0
  80. package/src/protocol/part-input.ts +2 -5
  81. package/src/protocol/reduce.ts +2 -0
  82. package/src/protocol/text-parts.ts +10 -0
@@ -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 message is delivered only while the call that carries it is open
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
- * A host's refusal at its commit (`Refused`) as the package's own, the
230
- * sessions it names as this caller sees them; anything else as it is.
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
- caller: Caller<Auth>,
235
- all: readonly Entry[],
236
- about: string,
237
- undone: "archived" | "started in it",
238
- ): unknown {
239
- if (!(error instanceof Refused)) return error;
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,12 +279,25 @@ 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
275
297
  * refusal is thrown as it is.
276
298
  */
277
299
  async function dispatched<T>(scope: Scope, mutation: Promise<T>): Promise<T | undefined> {
300
+ if (scope.report) void mutation.catch(scope.report);
278
301
  try {
279
302
  return await within(scope, mutation);
280
303
  } catch (error) {
@@ -356,7 +379,7 @@ export function createOperator<Auth = unknown>(
356
379
 
357
380
  // ---- references ----------------------------------------------------------------
358
381
 
359
- const everything = (caller: Caller<Auth>, scope: Scope) =>
382
+ const everything = async (caller: Caller<Auth>, scope: Scope) =>
360
383
  within(scope, host.list(caller, { includeArchived: true }));
361
384
 
362
385
  function projectNamed(name: string, projects: readonly ProjectRef[], all: readonly Entry[]) {
@@ -508,8 +531,23 @@ export function createOperator<Auth = unknown>(
508
531
  }
509
532
 
510
533
  /** The host's view in the scope; past it, still working as far as anyone knows. */
511
- const viewIn = (caller: Caller<Auth>, sessionId: string, scope: Scope) =>
512
- within(scope, host.view(caller, sessionId, { last: 20 }), () => UNREAD);
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
+ }
513
551
 
514
552
  /**
515
553
  * The one settlement rule: a session waiting on an answer is settled at
@@ -532,7 +570,7 @@ export function createOperator<Auth = unknown>(
532
570
  if (look.view === UNREAD) return "could not be read before the wait ended";
533
571
  const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
534
572
  if (look.view.status === "error" && !look.view.lastEnded && !look.view.turns.length)
535
- 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)}`;
536
574
  const done =
537
575
  look.settled && look.view.status !== "needs_input" && look.view.status !== "archived";
538
576
  const note =
@@ -599,22 +637,25 @@ export function createOperator<Auth = unknown>(
599
637
 
600
638
  /**
601
639
  * The host's `onError` for one call: shown each unexpected failure once,
602
- * never a refusal; it cannot change the answer, and a throw in it is
603
- * swallowed.
640
+ * never a refusal. A throw or rejection in the hook is swallowed.
604
641
  */
605
642
  function reporter(tool: string, caller: Caller<Auth>) {
606
643
  const seen = new Set<unknown>();
607
- return (error: unknown) => {
644
+ const tell = async (error: unknown) => {
608
645
  const refusal =
609
646
  error instanceof OperatorError || error instanceof Refused || error instanceof Over;
610
- if (!options.onError || refusal || seen.has(error)) return;
611
- seen.add(error);
612
- try {
613
- options.onError(error, tool, caller);
614
- } catch {
615
- // The host's hook changes nothing.
647
+ if (refusal || seen.has(error)) return;
648
+ // A host that stops as the caller gives up rejects with that reason, or wraps it (`AbortError`).
649
+ const { signal } = caller;
650
+ if (signal?.aborted) {
651
+ const cause = error instanceof Error ? error.cause : undefined;
652
+ if (error === signal.reason || cause === signal.reason) return;
616
653
  }
654
+ seen.add(error);
655
+ await options.onError?.(error, tool, caller);
617
656
  };
657
+ // Nothing awaits it, and a detached write calls it: it never throws or rejects.
658
+ return (error: unknown) => void tell(error).catch(() => {});
618
659
  }
619
660
 
620
661
  /** A batch's items, one line each; when every one was refused, the whole answer is a refusal. */
@@ -685,8 +726,7 @@ export function createOperator<Auth = unknown>(
685
726
  lines.push(`you are ${who} (id ${json(caller.id)})`);
686
727
  }
687
728
  const described = host.describe ? await within(scope, host.describe(caller)) : undefined;
688
- if (described) lines.push(oneLine(described));
689
- return lines.join("\n");
729
+ return lines.join("\n") + noteLines(described);
690
730
  },
691
731
  });
692
732
 
@@ -887,31 +927,69 @@ export function createOperator<Auth = unknown>(
887
927
  const listModels = def({
888
928
  name: "list_models",
889
929
  title: "List models",
890
- description:
891
- "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.`,
892
931
  input: {
893
932
  agent: words()
894
933
  .optional()
895
934
  .describe("Only this agent (harness); an unknown agent names those listed here"),
896
935
  },
897
936
  effect: "read",
898
- needs: ["models"],
937
+ needs: [host.agents ? "agents" : "models"],
899
938
  async run({ agent }, caller, scope) {
900
- const models = host.models ? await within(scope, host.models(caller)) : [];
901
- const harnesses = [...new Set(models.map((m) => m.harness))];
902
- if (agent && !harnesses.some((h) => h === agent))
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
+ );
903
971
  throw refuse.invalidInput(
904
972
  "list_models",
905
973
  "agent",
906
974
  `${json(agent)} is unknown here; the agents listed are ${harnesses.map(json).join(", ") || "(none)"}`,
907
975
  );
976
+ }
908
977
  const lines: string[] = [];
909
978
  for (const harness of harnesses) {
910
979
  if (agent && harness !== agent) continue;
911
- const mine = models.filter((m) => m.harness === harness);
912
- lines.push(
913
- `${oneLine(harness)}${mine.some((m) => m.defaultHarness) ? " (default agent)" : ""}`,
914
- );
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");
915
993
  for (const m of mine) {
916
994
  const levels = m.thinkingLevels.length
917
995
  ? `thinking: ${m.thinkingLevels.map(oneLine).join(", ")}${m.defaultThinkingLevel ? ` (default ${oneLine(m.defaultThinkingLevel)})` : ""}`
@@ -921,7 +999,8 @@ export function createOperator<Auth = unknown>(
921
999
  );
922
1000
  }
923
1001
  }
924
- return lines.join("\n") || "no models listed";
1002
+ if (!lines.length && catalog.status === "fulfilled") lines.push("no models listed");
1003
+ return [...lines, ...failures].join("\n");
925
1004
  },
926
1005
  });
927
1006
 
@@ -974,9 +1053,11 @@ export function createOperator<Auth = unknown>(
974
1053
  ];
975
1054
  for (const look of looks) {
976
1055
  if (!look.settled) {
977
- lines.push(
978
- `- ${quoted(look.ref)}: ${look.view === UNREAD ? "could not be read before the wait ended" : "working"}`,
979
- );
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 ")}`);
980
1061
  continue;
981
1062
  }
982
1063
  const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
@@ -1039,7 +1120,7 @@ export function createOperator<Auth = unknown>(
1039
1120
  // ---- sending: one call, one message --------------------------------------------------
1040
1121
 
1041
1122
  /** One turn by id, in the scope; unknown past it. */
1042
- const turnIn = (caller: Caller<Auth>, sessionId: string, turnId: string, scope: Scope) =>
1123
+ const turnIn = async (caller: Caller<Auth>, sessionId: string, turnId: string, scope: Scope) =>
1043
1124
  within<TurnFact>(scope, host.turn(caller, sessionId, turnId), () => ({ state: "unknown" }));
1044
1125
 
1045
1126
  /**
@@ -1058,38 +1139,224 @@ export function createOperator<Auth = unknown>(
1058
1139
  if (!open(caller, cutoff)) throw new Over("the call ended before this was done");
1059
1140
  };
1060
1141
 
1061
- /**
1062
- * Deliver `message` to the session while this call is open: at once when it
1063
- * is idle; after the turn running when the call began ends on its own
1064
- * (`idle`), or after the package stops it (`interrupt`); never when someone
1065
- * stopped that turn, the session waits on an answer, another turn won, or
1066
- * the window ended first. Then its own turn's outcome, by its id.
1067
- */
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
+
1068
1331
  async function deliver(
1069
1332
  caller: Caller<Auth>,
1070
1333
  entry: Entry,
1071
1334
  ref: string,
1072
1335
  message: string,
1073
1336
  all: readonly Entry[],
1074
- interrupt: boolean,
1337
+ when: When,
1075
1338
  scope: Scope,
1076
1339
  ): Promise<string> {
1077
1340
  // Once an interrupt's stop is confirmed, every later outcome of the call says so:
1078
1341
  // a refusal stays one, with the stop in its words; an abort or a failure says it too.
1079
1342
  const done = { stopped: false };
1080
1343
  try {
1081
- return await deliverIn(caller, entry, ref, message, all, interrupt, scope, done);
1344
+ return await deliverIn(caller, entry, ref, message, all, when, scope, done);
1082
1345
  } catch (error) {
1083
1346
  if (!done.stopped) throw error;
1084
- const stop = `stopped ${quoted(ref)}'s turn; not sent:`;
1347
+ const stop = `stopped ${quoted(ref)}'s turn; not sent`;
1085
1348
  if (error instanceof Over)
1086
- 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.`;
1087
1350
  const refusal = asRefusal(error, scope);
1088
- const why = refusal.message
1089
- .replace(/^refused \([a-z_]+\): /, "")
1090
- .replace(/ Nothing was \w+\./, "")
1091
- .replace(/\n {2}/, " ");
1092
- throw OperatorError.said(refusal.code, `refused (${refusal.code}): ${stop} ${why}`);
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
+ });
1093
1360
  }
1094
1361
  }
1095
1362
 
@@ -1099,64 +1366,131 @@ export function createOperator<Auth = unknown>(
1099
1366
  ref: string,
1100
1367
  message: string,
1101
1368
  all: readonly Entry[],
1102
- interrupt: boolean,
1369
+ when: When,
1103
1370
  scope: Scope,
1104
1371
  done: { stopped: boolean },
1105
1372
  ): Promise<string> {
1106
1373
  const you = senderOf(caller, all);
1374
+ const interrupt = when === "interrupt";
1107
1375
  const notSent = (why: string) =>
1108
1376
  done.stopped
1109
1377
  ? `stopped ${quoted(ref)}'s turn; not sent: ${why}`
1110
1378
  : `nothing was sent to ${quoted(ref)}: ${why}`;
1111
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
+ };
1112
1388
  const starter =
1113
1389
  caller.kind === "session" && all.find((e) => e.id === caller.sessionId)?.startedBy;
1114
- const busyHint =
1390
+ const starterHint =
1115
1391
  !interrupt && starter && starter.kind === "session" && starter.sessionId === entry.id
1116
1392
  ? "This session started you. End your turn with your report. If it is waiting for you, its wait receives your reply."
1117
- : `Wait for it, then send again.${again}`;
1118
- const asks = async (view: SessionView) => {
1119
- const context = await waitingContext(caller, entry, ref, view, scope);
1120
- const whose = context.canAnswer ? "your" : "the person's";
1121
- const lines = view.waiting.map((w) => describeWaiting(w, perRequest(context, w)));
1122
- return `${notSent(`it waits on ${whose} answer.`)}\n${lines.join("\n")}`;
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;
1123
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
+ }
1124
1443
  const view = await within(scope, host.view(caller, entry.id, { last: 1 }));
1125
1444
  if (view.status === "needs_input" && !interrupt) return asks(view);
1126
1445
  let paused = false;
1127
1446
  if (view.running) {
1128
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
+ }
1129
1468
  if (interrupt) {
1130
1469
  // The package's stop, of this turn only, asked right before it is made, and only
1131
1470
  // while the message could still be sent after it.
1132
1471
  await assertMay(caller, "destructive", "send_message", scope);
1133
1472
  const cancel = host.cancel as NonNullable<OperatorHost<Auth>["cancel"]>;
1134
- if (!open(caller, scope.deadline <= scope.from ? scope.end : scope.deadline))
1473
+ if (!open(caller, firstCutoff))
1135
1474
  return `${notSent("this call's wait ended first; its turn was not stopped.")} Send again.${again}`;
1136
1475
  const stopped = await dispatched(scope, cancel.call(host, caller, entry.id, running));
1137
1476
  if (stopped === undefined)
1138
1477
  return `${notSent("its turn was asked to stop; that is not confirmed.")}${again}`;
1139
1478
  done.stopped = stopped === "stopped";
1140
1479
  }
1141
- const seen = await waitUntil<{ fact: TurnFact; asking?: SessionView }>(
1142
- scope,
1143
- () => [entry.id],
1144
- async () => {
1145
- const fact = await turnIn(caller, entry.id, running, scope);
1146
- if (fact.state === "ended" || interrupt)
1147
- return { done: fact.state === "ended", value: { fact } };
1148
- // A turn that starts waiting on an answer will not end on its own: say so now.
1149
- const now = await viewIn(caller, entry.id, scope);
1150
- const asking = now.status === "needs_input" && now.running === running ? now : undefined;
1151
- return { done: asking !== undefined, value: { fact, asking } };
1152
- },
1153
- );
1480
+ const seen = await followTurn(caller, entry.id, running, scope, when);
1154
1481
  live(caller);
1155
1482
  paused = seen.paused;
1156
- const { fact, asking } = seen.value;
1157
- if (asking) return asks(asking);
1483
+ const { fact, view: current } = seen.value;
1484
+ if (seen.done && current) return asks(current);
1158
1485
  if (fact.state !== "ended")
1159
- return `${notSent(done.stopped ? "its turn's end was not seen before this call's wait ended." : interrupt ? "its turn was asked to stop and has not yet." : "it was still working when this call's wait ended.")} ${busyHint}`;
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
+ );
1160
1494
  if (fact.outcome === "cancelled" && !interrupt)
1161
1495
  return notSent(
1162
1496
  `its turn was stopped${stoppedBy(fact.cancelledBy, you)} while this call waited, so this message was not sent after it.`,
@@ -1164,61 +1498,65 @@ export function createOperator<Auth = unknown>(
1164
1498
  }
1165
1499
  // The cutoff: the call's grace only for a `wait: 0` call deciding on its first look,
1166
1500
  // else its deadline; checked again after authorising, right before the send.
1167
- const cutoff = !paused && scope.deadline <= scope.from ? scope.end : scope.deadline;
1168
- const late = `${notSent(done.stopped ? "this call's wait ended before the message could follow." : "this call's wait ended first.")} Send again.${again}`;
1169
- if (!open(caller, cutoff)) return late;
1501
+ const cutoff = paused ? scope.deadline : firstCutoff;
1170
1502
  const turnId = generateUUIDv7();
1171
1503
  const input = { turnId, message, origin: you };
1172
- 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 }))}`;
1173
- let sent = false;
1174
- for (let attempt = 0; attempt < 2 && !sent; attempt++) {
1175
- if (attempt > 0) {
1176
- // The same turn id again, which the engine converges on: only while the call
1177
- // is open, within its time, and still allowed.
1178
- if (!open(caller, scope.end)) return unconfirmed;
1179
- try {
1180
- await assertMay(caller, "write", "send_message", scope);
1181
- } catch {
1182
- return unconfirmed;
1183
- }
1184
- if (!open(caller, scope.end)) return unconfirmed;
1185
- } else {
1186
- await assertMay(caller, "write", "send_message", scope);
1187
- if (!open(caller, cutoff)) return late;
1188
- }
1189
- try {
1190
- await within(scope, host.send(caller, entry.id, input));
1191
- sent = true;
1192
- } catch (error) {
1193
- const definite = error instanceof OperatorError || error instanceof Refused;
1194
- if (definite && attempt > 0) return unconfirmed;
1195
- if (definite && (error instanceof Refused ? error.refusal.code : error.code) === "busy")
1196
- return `${notSent("another turn started there first.")} ${busyHint}`;
1197
- if (definite) throw error;
1198
- // No answer: once more with the same turn id.
1199
- }
1200
- }
1201
- if (!sent) return unconfirmed;
1202
1504
  // An interrupt's stop is said in every result, the sent ones included.
1203
1505
  const lead = done.stopped ? `stopped ${quoted(ref)}'s turn; ` : "";
1204
- try {
1205
- return `${lead}sent to ${quoted(ref)}.\n${await ownOutcome(caller, entry, ref, turnId, scope)}`;
1206
- } catch (error) {
1207
- scope.report?.(error);
1208
- return `${lead}sent to ${quoted(ref)} (turn ${json(turnId)}); its outcome could not be read.${line(hint("read_session", { session: ref }))}`;
1209
- }
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
+ );
1210
1523
  }
1211
1524
 
1212
- /**
1213
- * A turn the package minted, followed by its id: its outcome once it ended;
1214
- * what it waits on only while the session's running turn is this one; else
1215
- * that it still works, or that its turn is not known, with a read hint. A
1216
- * successor's question is never taken for its own.
1217
- */
1218
1525
  /** Setup failed before any turn began: the only error a first task's unknown turn may report. */
1219
1526
  const setupFailed = (view: SessionView) =>
1220
1527
  view.status === "error" && !view.running && !view.lastEnded && view.turns.length === 0;
1221
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. */
1222
1560
  async function ownOutcome(
1223
1561
  caller: Caller<Auth>,
1224
1562
  entry: Entry,
@@ -1232,48 +1570,66 @@ export function createOperator<Auth = unknown>(
1232
1570
  async () => {
1233
1571
  const fact = await turnIn(caller, entry.id, turnId, scope);
1234
1572
  const view = await viewIn(caller, entry.id, scope);
1235
- const asks = view.running === turnId && view.status === "needs_input";
1573
+ const asks = turnAsks(view, turnId);
1236
1574
  const failedSetup = fact.state === "unknown" && setupFailed(view);
1237
1575
  return { done: fact.state === "ended" || asks || failedSetup, value: { fact, view } };
1238
1576
  },
1239
1577
  );
1240
1578
  const { fact, view } = value;
1241
1579
  const read = line(hint("read_session", { session: ref }));
1242
- if (fact.state === "ended") {
1243
- const at = view.turns.findIndex((t) => t.turnId === turnId);
1244
- const status =
1245
- fact.outcome === "done" ? "idle" : fact.outcome === "cancelled" ? "stopped" : "error";
1246
- if (at < 0) return `status: ${fact.outcome}${read}`;
1247
- const own: SessionView = { status, turns: view.turns.slice(0, at + 1), waiting: [] };
1248
- const newer = view.turns.slice(at + 1).reduce((n, t) => n + t.messages.length, 0);
1249
- return outcomeOf(caller, { entry, ref, view: own, settled: true }, scope, newer);
1250
- }
1580
+ if (fact.state === "ended") return endedOutcome(caller, entry, ref, turnId, fact, view, scope);
1251
1581
  if (view.running === turnId)
1252
1582
  return outcomeOf(caller, { entry, ref, view, settled: view.status === "needs_input" }, scope);
1253
- if (setupFailed(view)) return outcomeOf(caller, { entry, ref, view, settled: true }, scope);
1254
- if (view.status === "setting_up")
1255
- return `status: setting_up${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
1256
- if (fact.state === "running")
1257
- return `status: working${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
1258
- return `status: unknown (its turn is not known yet)${read}`;
1583
+ if (setupFailed(view)) {
1584
+ const all = (await everything(caller, scope).catch(scope.report)) ?? [];
1585
+ const current = all.find((e) => e.id === entry.id) ?? entry;
1586
+ return outcomeOf(caller, { entry: current, ref, view, settled: true }, scope);
1587
+ }
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}`;
1259
1594
  }
1260
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";
1261
1600
  const sendMessage = def({
1262
1601
  name: "send_message",
1263
1602
  title: "Send message",
1264
- description:
1265
- "Send a message to a session's agent; it is told the message is from you, not the person. It is sent only while this call is open: at once when the session is idle; when it is working, after its turn ends on its own, within this call's wait. If the session that started you is still working, end your turn with your report for its wait. Nothing is left behind: when the wait ends first, someone stops that turn, or another message starts a turn first, nothing is sent and the answer says so. A session waiting on an answer gets nothing (use answer_request), unless when: interrupt, which stops its turn, dropping what it waits on, and sends. Message a session the person started only when the person asked you to.",
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(" "),
1266
1620
  input: {
1267
1621
  session: sessionArg,
1268
1622
  message: words().max(MAX_TEXT).describe("What to tell the agent"),
1269
1623
  when: z
1270
- .enum(["idle", "interrupt"])
1624
+ .enum(modes)
1271
1625
  .optional()
1272
- .describe("idle (default): after its turn ends; interrupt: stop it and send"),
1273
- 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
+ ),
1274
1630
  },
1275
1631
  effect: "write",
1276
- async run({ session, message, when = "idle" }, caller, scope) {
1632
+ async run({ session, message, when = defaultWhen }, caller, scope) {
1277
1633
  const { entry, ref, all } = await find(caller, session, scope);
1278
1634
  if (caller.kind === "session" && entry.id === caller.sessionId) throw refuse.self("session");
1279
1635
  if (entry.status === "archived") throw refuse.archived(hint, ref, entry.project?.name);
@@ -1282,9 +1638,9 @@ export function createOperator<Auth = unknown>(
1282
1638
  if (when === "interrupt" && !host.cancel)
1283
1639
  throw refuse.unsupported("This host cannot stop a turn.");
1284
1640
  return once(
1285
- json(["send", keyOf(caller), entry.id, message]),
1641
+ json(["send", keyOf(caller), entry.id, when, message]),
1286
1642
  scope,
1287
- () => deliver(caller, entry, ref, message, all, when === "interrupt", scope),
1643
+ () => deliver(caller, entry, ref, message, all, when, scope),
1288
1644
  hint("read_session", { session: ref }),
1289
1645
  );
1290
1646
  },
@@ -1464,7 +1820,7 @@ export function createOperator<Auth = unknown>(
1464
1820
  } catch (error) {
1465
1821
  // Refused for certain: nothing was made, so the minute's slot is given back.
1466
1822
  if (error instanceof OperatorError || error instanceof Refused) giveBack();
1467
- throw fromHost(error, caller, now, about, "started in it");
1823
+ throw fromHost(error, scope, { caller, all: now, about, undone: "started in it" });
1468
1824
  }
1469
1825
  });
1470
1826
  const where = into
@@ -1755,7 +2111,7 @@ export function createOperator<Auth = unknown>(
1755
2111
  }
1756
2112
  }
1757
2113
  } catch (error) {
1758
- const refusal = asRefusal(fromHost(error, caller, all, about, "archived"), scope);
2114
+ const refusal = fromHost(error, scope, { caller, all, about, undone: "archived" });
1759
2115
  if (!stopped.length) throw refusal;
1760
2116
  // Still a refusal, so a batch of them is one; its own "nothing was done" is not so:
1761
2117
  // the stops were made.