@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.
Files changed (46) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/core/runtime/event-processor.js +9 -10
  3. package/dist/operator/errors.js +9 -2
  4. package/dist/operator/index.js +1 -1
  5. package/dist/operator/operator.js +382 -145
  6. package/dist/operator/render.js +28 -10
  7. package/dist/operator/session-tools.js +9 -12
  8. package/dist/operator/view.js +16 -4
  9. package/dist/protocol/conversation.js +2 -0
  10. package/dist/protocol/lifecycle.js +2 -0
  11. package/dist/protocol/reduce.js +1 -0
  12. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  13. package/dist/types/operator/errors.d.ts +3 -1
  14. package/dist/types/operator/errors.d.ts.map +1 -1
  15. package/dist/types/operator/index.d.ts +1 -1
  16. package/dist/types/operator/index.d.ts.map +1 -1
  17. package/dist/types/operator/operator.d.ts.map +1 -1
  18. package/dist/types/operator/render.d.ts +2 -0
  19. package/dist/types/operator/render.d.ts.map +1 -1
  20. package/dist/types/operator/session-tools.d.ts +1 -4
  21. package/dist/types/operator/session-tools.d.ts.map +1 -1
  22. package/dist/types/operator/types.d.ts +73 -13
  23. package/dist/types/operator/types.d.ts.map +1 -1
  24. package/dist/types/operator/view.d.ts.map +1 -1
  25. package/dist/types/protocol/conversation.d.ts +3 -0
  26. package/dist/types/protocol/conversation.d.ts.map +1 -1
  27. package/dist/types/protocol/lifecycle.d.ts +2 -0
  28. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  29. package/dist/types/protocol/reduce.d.ts.map +1 -1
  30. package/dist/types/protocol/wire-api.d.ts +1 -0
  31. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  32. package/dist/types/protocol/wire.d.ts +2 -0
  33. package/dist/types/protocol/wire.d.ts.map +1 -1
  34. package/docs/consuming.md +55 -13
  35. package/package.json +1 -1
  36. package/src/core/runtime/event-processor.ts +14 -9
  37. package/src/operator/errors.ts +12 -4
  38. package/src/operator/index.ts +1 -1
  39. package/src/operator/operator.ts +489 -146
  40. package/src/operator/render.ts +29 -8
  41. package/src/operator/session-tools.ts +9 -12
  42. package/src/operator/types.ts +77 -12
  43. package/src/operator/view.ts +26 -9
  44. package/src/protocol/conversation.ts +2 -0
  45. package/src/protocol/lifecycle.ts +2 -0
  46. package/src/protocol/reduce.ts +2 -0
@@ -7,14 +7,14 @@
7
7
  * the waits, the rules and the limits, and holds nothing between calls.
8
8
  */
9
9
  // @ref LLP 0014#decision — the session tools are the engine's; who may call them, and what a session is, stay the host's
10
- // @ref LLP 0019#one-call-one-message — a message is delivered only while the call that carries it is open
10
+ // @ref LLP 0019#one-call-one-message — a steer names its turn, a queue belongs to the host
11
11
  import { z } from "zod";
12
12
  import { tokenDigest } from "../protocol/credentials.js";
13
13
  import { generateUUIDv7 } from "../protocol/ids.js";
14
14
  import { ORIGIN_FIELD_MAX, OriginSchema } from "../protocol/origin.js";
15
- import { OperatorError, Refused, refuse } from "./errors.js";
15
+ import { OperatorError, Refused, readRefusal, refuse } from "./errors.js";
16
16
  import { refOf, resolve as resolveRef } from "./refs.js";
17
- import { FULL_READ_LIMIT, MAX_LAST, QUOTE, answerFor, callHint, describeWaiting, json, oneLine, perRequest, personOnly, quote, quoted, renderConversation, renderOutcome, sameOrigin, senderLabel, } from "./render.js";
17
+ import { FULL_READ_LIMIT, MAX_LAST, QUOTE, answerFor, callHint, describeWaiting, json, noteLines, oneLine, perRequest, personOnly, quote, quoted, renderConversation, renderOutcome, sameOrigin, senderLabel, } from "./render.js";
18
18
  import { settledStatus } from "./view.js";
19
19
  /** Declare a tool, typed by its input. Hosts use this for their own (`effect`: what it does, honestly). */
20
20
  export function tool(def) {
@@ -118,12 +118,13 @@ export function createOperator(host, options = {}) {
118
118
  ? refuse.access(refusal.detail)
119
119
  : refuse.unsupported(refusal.detail);
120
120
  /**
121
- * A host's refusal at its commit (`Refused`) as the package's own, the
122
- * sessions it names as this caller sees them; anything else as it is.
121
+ * Word a host's refusal, naming the sessions of a targeted operation
122
+ * as the caller sees them.
123
123
  */
124
- function fromHost(error, caller, all, about, undone) {
124
+ function fromHost(error, scope, target) {
125
125
  if (!(error instanceof Refused))
126
- return error;
126
+ return asRefusal(error, scope);
127
+ const { caller, all, about, undone } = target;
127
128
  const { code, sessions = [] } = error.refusal;
128
129
  const named = sessions.map((id) => all.find((e) => e.id === id));
129
130
  const refs = sessions.map((id, i) => {
@@ -147,6 +148,18 @@ export function createOperator(host, options = {}) {
147
148
  return refuse.archived(hint, refs[0] ?? about);
148
149
  return asError(error.refusal);
149
150
  }
151
+ function refusedWrite(error, ref, undone) {
152
+ if (error instanceof OperatorError)
153
+ return error;
154
+ const { code, detail, retryAfter } = error.refusal;
155
+ const what = undone === "sent" ? "sent to" : "queued for";
156
+ const retry = retryAfter === undefined ? "" : ` Try again in ${retryAfter}s.`;
157
+ return new OperatorError(code, `Nothing was ${what} ${quoted(ref)}.${retry}`, {
158
+ detail: oneLine(detail ?? ""),
159
+ retryAfter,
160
+ next: code === "busy" ? hint("wait_for_sessions", { sessions: [ref] }) : undefined,
161
+ });
162
+ }
150
163
  /**
151
164
  * A mutation the host was asked to make: its answer, or `undefined` when
152
165
  * none came in the call's scope (it may have been made). A definite
@@ -372,7 +385,17 @@ export function createOperator(host, options = {}) {
372
385
  }
373
386
  }
374
387
  /** The host's view in the scope; past it, still working as far as anyone knows. */
375
- const viewIn = (caller, sessionId, scope) => within(scope, host.view(caller, sessionId, { last: 20 }), () => UNREAD);
388
+ const viewIn = (caller, sessionId, scope, last = 20) => within(scope, host.view(caller, sessionId, { last }), () => UNREAD);
389
+ /** A failed read after delivery still leaves the sender its confirmed receipt. */
390
+ async function viewAfterDelivery(caller, sessionId, scope, last) {
391
+ try {
392
+ return await viewIn(caller, sessionId, scope, last);
393
+ }
394
+ catch (error) {
395
+ scope.report?.(error);
396
+ return UNREAD;
397
+ }
398
+ }
376
399
  /**
377
400
  * The one settlement rule: a session waiting on an answer is settled at
378
401
  * once; otherwise it is settled when no turn runs and it is not being set up.
@@ -388,7 +411,7 @@ export function createOperator(host, options = {}) {
388
411
  return "could not be read before the wait ended";
389
412
  const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
390
413
  if (look.view.status === "error" && !look.view.lastEnded && !look.view.turns.length)
391
- return `status: error (could not be set up)\n${quote(look.entry.error ?? "setup failed")}`;
414
+ return `status: error (could not be set up)\n${quote(look.entry.error ?? "setup failed")}${noteLines(look.view.note)}`;
392
415
  const done = look.settled && look.view.status !== "needs_input" && look.view.status !== "archived";
393
416
  const note = done && host.outcome
394
417
  ? await within(scope, host.outcome(caller, look.entry), () => undefined)
@@ -521,9 +544,7 @@ export function createOperator(host, options = {}) {
521
544
  lines.push(`you are ${who} (id ${json(caller.id)})`);
522
545
  }
523
546
  const described = host.describe ? await within(scope, host.describe(caller)) : undefined;
524
- if (described)
525
- lines.push(oneLine(described));
526
- return lines.join("\n");
547
+ return lines.join("\n") + noteLines(described);
527
548
  },
528
549
  });
529
550
  const listSessions = def({
@@ -705,25 +726,63 @@ export function createOperator(host, options = {}) {
705
726
  const listModels = def({
706
727
  name: "list_models",
707
728
  title: "List models",
708
- description: "The agents and models a new session can run, with each model's thinking levels and the defaults. Use these names in start_session.",
729
+ 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.`,
709
730
  input: {
710
731
  agent: words()
711
732
  .optional()
712
733
  .describe("Only this agent (harness); an unknown agent names those listed here"),
713
734
  },
714
735
  effect: "read",
715
- needs: ["models"],
736
+ needs: [host.agents ? "agents" : "models"],
716
737
  async run({ agent }, caller, scope) {
717
- const models = host.models ? await within(scope, host.models(caller)) : [];
718
- const harnesses = [...new Set(models.map((m) => m.harness))];
719
- if (agent && !harnesses.some((h) => h === agent))
738
+ const read = async (source) => source && within(scope, source.call(host, caller));
739
+ const [catalog, readiness] = await Promise.allSettled([read(host.models), read(host.agents)]);
740
+ const failures = [];
741
+ let refused;
742
+ function rows(result, source, missing) {
743
+ if (result.status === "fulfilled")
744
+ return result.value;
745
+ const { reason } = result;
746
+ if (reason instanceof Refused ||
747
+ reason instanceof OperatorError ||
748
+ reason instanceof Over) {
749
+ const error = reason instanceof Refused ? readRefusal(reason.refusal) : asRefusal(reason, scope);
750
+ refused ??= error;
751
+ failures.push(`${source}: ${error.message}`);
752
+ }
753
+ else {
754
+ scope.report?.(reason);
755
+ failures.push(missing);
756
+ }
757
+ }
758
+ const models = rows(catalog, "models", "models could not be read");
759
+ const agents = rows(readiness, "agents", "the agents' states could not be read.");
760
+ if (!models && !agents)
761
+ throw refused ?? refuse.failed();
762
+ const states = new Map(agents?.map((a) => [a.harness, a]));
763
+ const harnesses = [...new Set([...(models ?? []).map((m) => m.harness), ...states.keys()])];
764
+ if (agent && !harnesses.some((h) => h === agent)) {
765
+ if (failures.length)
766
+ return [`${json(agent)} is not in what could be read; try again.`, ...failures].join("\n");
720
767
  throw refuse.invalidInput("list_models", "agent", `${json(agent)} is unknown here; the agents listed are ${harnesses.map(json).join(", ") || "(none)"}`);
768
+ }
721
769
  const lines = [];
722
770
  for (const harness of harnesses) {
723
771
  if (agent && harness !== agent)
724
772
  continue;
725
- const mine = models.filter((m) => m.harness === harness);
726
- lines.push(`${oneLine(harness)}${mine.some((m) => m.defaultHarness) ? " (default agent)" : ""}`);
773
+ const mine = models?.filter((m) => m.harness === harness) ?? [];
774
+ let label = oneLine(harness) + (mine.some((m) => m.defaultHarness) ? " (default agent)" : "");
775
+ const entry = states.get(harness);
776
+ if (entry) {
777
+ const state = ["ready", "signed_out", "not_installed"].includes(entry.state)
778
+ ? entry.state.replace("_", " ")
779
+ : "unknown";
780
+ const detail = oneLine(entry.detail ?? "");
781
+ label += ` ${state}${detail ? `: ${detail}` : ""}`;
782
+ }
783
+ lines.push(label);
784
+ if (!mine.length && catalog.status === "fulfilled")
785
+ lines.push(" no models listed");
727
786
  for (const m of mine) {
728
787
  const levels = m.thinkingLevels.length
729
788
  ? `thinking: ${m.thinkingLevels.map(oneLine).join(", ")}${m.defaultThinkingLevel ? ` (default ${oneLine(m.defaultThinkingLevel)})` : ""}`
@@ -731,7 +790,9 @@ export function createOperator(host, options = {}) {
731
790
  lines.push(` - ${oneLine(m.id)} ${quoted(m.label)} ${levels}${m.default ? " default" : ""}`);
732
791
  }
733
792
  }
734
- return lines.join("\n") || "no models listed";
793
+ if (!lines.length && catalog.status === "fulfilled")
794
+ lines.push("no models listed");
795
+ return [...lines, ...failures].join("\n");
735
796
  },
736
797
  });
737
798
  const waitForSessions = def({
@@ -782,7 +843,10 @@ export function createOperator(host, options = {}) {
782
843
  ];
783
844
  for (const look of looks) {
784
845
  if (!look.settled) {
785
- lines.push(`- ${quoted(look.ref)}: ${look.view === UNREAD ? "could not be read before the wait ended" : "working"}`);
846
+ const status = look.view === UNREAD
847
+ ? "could not be read before the wait ended"
848
+ : `working${noteLines(look.view.note)}`;
849
+ lines.push(`- ${quoted(look.ref)}: ${status.replace(/\n/g, "\n ")}`);
786
850
  continue;
787
851
  }
788
852
  const context = await waitingContext(caller, look.entry, look.ref, look.view, scope);
@@ -835,7 +899,7 @@ export function createOperator(host, options = {}) {
835
899
  }
836
900
  // ---- sending: one call, one message --------------------------------------------------
837
901
  /** One turn by id, in the scope; unknown past it. */
838
- const turnIn = (caller, sessionId, turnId, scope) => within(scope, host.turn(caller, sessionId, turnId), () => ({ state: "unknown" }));
902
+ const turnIn = async (caller, sessionId, turnId, scope) => within(scope, host.turn(caller, sessionId, turnId), () => ({ state: "unknown" }));
839
903
  /**
840
904
  * Whether a dispatch may go now, checked at its call site with no await
841
905
  * before it: the call not given up, and before `cutoff`.
@@ -850,177 +914,327 @@ export function createOperator(host, options = {}) {
850
914
  if (!open(caller, cutoff))
851
915
  throw new Over("the call ended before this was done");
852
916
  };
853
- /**
854
- * Deliver `message` to the session while this call is open: at once when it
855
- * is idle; after the turn running when the call began ends on its own
856
- * (`idle`), or after the package stops it (`interrupt`); never when someone
857
- * stopped that turn, the session waits on an answer, another turn won, or
858
- * the window ended first. Then its own turn's outcome, by its id.
859
- */
860
- async function deliver(caller, entry, ref, message, all, interrupt, scope) {
917
+ /** A lost send, steer or queue answer gets one retry with the same input. */
918
+ async function sendWithRetry({ caller, scope, cutoff, ref, undone, late, unconfirmed, busy, }, dispatch) {
919
+ for (let attempt = 0; attempt < 2; attempt++) {
920
+ const until = attempt === 0 ? cutoff : scope.end;
921
+ if (!open(caller, until))
922
+ return attempt ? unconfirmed : late();
923
+ try {
924
+ await assertMay(caller, "write", "send_message", scope);
925
+ }
926
+ catch (error) {
927
+ if (attempt === 0) {
928
+ if (error instanceof Over)
929
+ return late();
930
+ throw error;
931
+ }
932
+ scope.report?.(error);
933
+ return unconfirmed;
934
+ }
935
+ if (!open(caller, until))
936
+ return attempt ? unconfirmed : late();
937
+ try {
938
+ const sending = dispatch();
939
+ if (scope.report)
940
+ void sending.catch(scope.report);
941
+ return { answer: await within(scope, sending), retried: attempt > 0 };
942
+ }
943
+ catch (error) {
944
+ scope.report?.(error);
945
+ if (error instanceof OperatorError || error instanceof Refused) {
946
+ if (attempt)
947
+ return unconfirmed;
948
+ if (busy && error instanceof Refused) {
949
+ const { code, detail, retryAfter, state, sessions } = error.refusal;
950
+ if (code === "busy" &&
951
+ detail === undefined &&
952
+ retryAfter === undefined &&
953
+ state === undefined &&
954
+ sessions === undefined)
955
+ return busy;
956
+ }
957
+ throw refusedWrite(error, ref, undone);
958
+ }
959
+ }
960
+ }
961
+ return unconfirmed;
962
+ }
963
+ const resendHint = (ref, when) => line(hint("send_message", {
964
+ session: ref,
965
+ message: "<the same message>",
966
+ when: when === "steer" && defaultWhen === "steer" ? undefined : when,
967
+ }));
968
+ const turnAsks = (view, turnId) => view.running === turnId && view.status === "needs_input";
969
+ /** Follow until the named turn ends, asks for input or gives this steer a receipt. */
970
+ function followTurn(caller, sessionId, turnId, scope, when, steerId) {
971
+ let receipt;
972
+ return waitUntil(scope, () => [sessionId], async () => {
973
+ const reading = turnIn(caller, sessionId, turnId, scope);
974
+ if (steerId) {
975
+ const fact = await reading.catch((error) => scope.report?.(error));
976
+ if (fact && fact.state !== "unknown")
977
+ receipt ??= fact.steers?.[steerId];
978
+ const ended = fact?.state === "ended";
979
+ const view = await viewAfterDelivery(caller, sessionId, scope, ended ? 20 : 1);
980
+ const received = fact?.state === "running" && receipt && (view === UNREAD || view.running === turnId);
981
+ return {
982
+ done: !fact || ended || !!received || turnAsks(view, turnId),
983
+ value: { fact: { ...(fact ?? { state: "unknown" }), receipt }, view },
984
+ };
985
+ }
986
+ const fact = await reading;
987
+ if (fact.state === "ended" || when === "interrupt")
988
+ return { done: fact.state === "ended", value: { fact } };
989
+ const view = await viewIn(caller, sessionId, scope);
990
+ return { done: turnAsks(view, turnId), value: { fact, view } };
991
+ });
992
+ }
993
+ async function waitsOn(caller, entry, ref, view, scope, afterSteer = false) {
994
+ const context = await waitingContext(caller, entry, ref, view, scope);
995
+ const whose = context.canAnswer ? "your" : "the person's";
996
+ const lines = view.waiting.map((w) => describeWaiting(w, perRequest(context, w)));
997
+ return `it waits on ${whose} answer${afterSteer ? " first" : ""}.${noteLines(view.note)}\n${lines.join("\n")}`;
998
+ }
999
+ const queuedSteer = (turnId, why) => `turn ${json(turnId)} ${why}; the product queued it as its own turn.`;
1000
+ /** Follow this steer in this turn. Acceptance and the user echo are separate receipts. */
1001
+ async function steerReceipt(caller, entry, ref, { turnId, steerId, origin }, scope) {
1002
+ const lead = `steered ${quoted(ref)} (turn ${json(turnId)}):`;
1003
+ const read = line(hint("read_session", { session: ref }));
1004
+ const unknown = `${lead} accepted; whether it was read is not confirmed`;
1005
+ const seen = await followTurn(caller, entry.id, turnId, scope, "steer", steerId).catch((error) => scope.report?.(error));
1006
+ if (!seen)
1007
+ return `${unknown}.${read}`;
1008
+ const { fact, view = UNREAD } = seen.value;
1009
+ const { receipt } = fact;
1010
+ const note = noteLines(view.note);
1011
+ const ended = fact.state === "ended";
1012
+ const stopped = ended && fact.outcome === "cancelled";
1013
+ if (receipt === "undelivered") {
1014
+ if (stopped)
1015
+ return `nothing reached ${quoted(ref)}: its turn was stopped${stoppedBy(fact.cancelledBy, origin)} before reading it.${note}`;
1016
+ const why = ended
1017
+ ? "its turn ended before reading it. Send it again."
1018
+ : "its turn did not take it.";
1019
+ return `nothing reached ${quoted(ref)}: ${why}${note}${resendHint(ref, "queue")}`;
1020
+ }
1021
+ const question = !ended && receipt !== "queued" && turnAsks(view, turnId)
1022
+ ? await waitsOn(caller, entry, ref, view, scope, !receipt).catch((error) => scope.report?.(error))
1023
+ : undefined;
1024
+ let head;
1025
+ if (receipt === "read")
1026
+ head = `${lead} read.`;
1027
+ else if (receipt === "queued") {
1028
+ const who = stopped && fact.cancelledBy ? ` It was stopped${stoppedBy(fact.cancelledBy, origin)}.` : "";
1029
+ head = queuedSteer(turnId, ended ? "ended without reading it" : "did not take it") + who;
1030
+ }
1031
+ else if (fact.state === "running" && fact.steers && view.running === turnId) {
1032
+ const later = host.queue
1033
+ ? "If its turn ends first, the product keeps it in its queue."
1034
+ : "If the turn ends before it reads it, nothing of it runs later.";
1035
+ head = `${lead} accepted, not yet read. ${later}`;
1036
+ }
1037
+ else {
1038
+ if (question)
1039
+ return `${unknown}: ${question}`;
1040
+ head = `${unknown}.`;
1041
+ }
1042
+ if (question)
1043
+ return `${head}\n${question}`;
1044
+ if (!ended)
1045
+ return head + note + (receipt ? "" : read);
1046
+ const outcome = await endedOutcome(caller, entry, ref, turnId, fact, view, scope).catch((error) => {
1047
+ scope.report?.(error);
1048
+ return `status: ${fact.outcome}${note}${read}`;
1049
+ });
1050
+ return `${head}\n${outcome}${!receipt && !outcome.endsWith(read) ? read : ""}`;
1051
+ }
1052
+ async function deliver(caller, entry, ref, message, all, when, scope) {
861
1053
  // Once an interrupt's stop is confirmed, every later outcome of the call says so:
862
1054
  // a refusal stays one, with the stop in its words; an abort or a failure says it too.
863
1055
  const done = { stopped: false };
864
1056
  try {
865
- return await deliverIn(caller, entry, ref, message, all, interrupt, scope, done);
1057
+ return await deliverIn(caller, entry, ref, message, all, when, scope, done);
866
1058
  }
867
1059
  catch (error) {
868
1060
  if (!done.stopped)
869
1061
  throw error;
870
- const stop = `stopped ${quoted(ref)}'s turn; not sent:`;
1062
+ const stop = `stopped ${quoted(ref)}'s turn; not sent`;
871
1063
  if (error instanceof Over)
872
- return `${stop} the call ended (its wait, or the caller gave it up) before the message was sent.`;
1064
+ return `${stop}: the call ended (its wait, or the caller gave it up) before the message was sent.`;
873
1065
  const refusal = asRefusal(error, scope);
874
- const why = refusal.message
875
- .replace(/^refused \([a-z_]+\): /, "")
876
- .replace(/ Nothing was \w+\./, "")
877
- .replace(/\n {2}/, " ");
878
- throw OperatorError.said(refusal.code, `refused (${refusal.code}): ${stop} ${why}`);
1066
+ const body = refusal.message.replace(/^refused \([a-z_]+\): /, "");
1067
+ const target = `Nothing was sent to ${quoted(ref)}.`;
1068
+ const reason = body.startsWith(target)
1069
+ ? body.slice(target.length)
1070
+ : body.replace(/ Nothing was \w+\./, "");
1071
+ const why = reason.replace(/\n {2}/, " ").trim();
1072
+ throw new OperatorError(refusal.code, why ? `${stop}: ${why}` : `${stop}.`, {
1073
+ retryAfter: refusal.retryAfter,
1074
+ });
879
1075
  }
880
1076
  }
881
- async function deliverIn(caller, entry, ref, message, all, interrupt, scope, done) {
1077
+ async function deliverIn(caller, entry, ref, message, all, when, scope, done) {
882
1078
  const you = senderOf(caller, all);
1079
+ const interrupt = when === "interrupt";
883
1080
  const notSent = (why) => done.stopped
884
1081
  ? `stopped ${quoted(ref)}'s turn; not sent: ${why}`
885
1082
  : `nothing was sent to ${quoted(ref)}: ${why}`;
886
1083
  const again = line(hint("wait_for_sessions", { sessions: [ref] }));
1084
+ const read = line(hint("read_session", { session: ref }));
1085
+ const late = () => {
1086
+ const why = done.stopped
1087
+ ? "this call's wait ended before the message could follow."
1088
+ : "this call's wait ended first.";
1089
+ const retry = interrupt ? again : resendHint(ref, when);
1090
+ return `${notSent(why)} Send again.${retry}`;
1091
+ };
887
1092
  const starter = caller.kind === "session" && all.find((e) => e.id === caller.sessionId)?.startedBy;
888
- const busyHint = !interrupt && starter && starter.kind === "session" && starter.sessionId === entry.id
1093
+ const starterHint = !interrupt && starter && starter.kind === "session" && starter.sessionId === entry.id
889
1094
  ? "This session started you. End your turn with your report. If it is waiting for you, its wait receives your reply."
890
- : `Wait for it, then send again.${again}`;
891
- const asks = async (view) => {
892
- const context = await waitingContext(caller, entry, ref, view, scope);
893
- const whose = context.canAnswer ? "your" : "the person's";
894
- const lines = view.waiting.map((w) => describeWaiting(w, perRequest(context, w)));
895
- return `${notSent(`it waits on ${whose} answer.`)}\n${lines.join("\n")}`;
1095
+ : undefined;
1096
+ const busy = (why, note) => `${notSent(why)} ${starterHint ?? "Wait for it, then send again."}${noteLines(note)}${starterHint ? "" : again}`;
1097
+ const advice = starterHint ? ` ${starterHint}` : "";
1098
+ const withOutcome = async (reading, confirmed, unread) => {
1099
+ const outcome = await reading.catch((error) => scope.report?.(error));
1100
+ return outcome ? `${confirmed}\n${outcome}` : unread + read;
896
1101
  };
1102
+ const asks = async (view) => notSent(await waitsOn(caller, entry, ref, view, scope));
1103
+ const firstCutoff = scope.deadline <= scope.from ? scope.end : scope.deadline;
1104
+ const delivery = { caller, scope, ref, late, cutoff: firstCutoff };
1105
+ if (when === "queue" && host.queue) {
1106
+ const input = { turnId: generateUUIDv7(), message, origin: you };
1107
+ const result = await sendWithRetry({
1108
+ ...delivery,
1109
+ undone: "queued",
1110
+ 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}`,
1111
+ }, () => host.queue(caller, entry.id, input));
1112
+ if (typeof result === "string")
1113
+ return result;
1114
+ const { position } = result.answer;
1115
+ const place = position === undefined ? "" : ` (position ${position})`;
1116
+ const lead = `queued for ${quoted(ref)}${place} in the product's queue`;
1117
+ const view = await viewAfterDelivery(caller, entry.id, scope, 1);
1118
+ const { lastEnded, note } = view;
1119
+ const started = `${lead}; it started at once.${advice}`;
1120
+ if (lastEnded?.turnId === input.turnId) {
1121
+ return withOutcome(endedOutcome(caller, entry, ref, input.turnId, lastEnded, view, scope), started, `${started}\nstatus: ${lastEnded.outcome}${noteLines(note)}`);
1122
+ }
1123
+ if (view.running === input.turnId) {
1124
+ return withOutcome(ownOutcome(caller, entry, ref, input.turnId, scope), started, `${started} Its outcome could not be read.${noteLines(note)}`);
1125
+ }
1126
+ const queued = `${lead}.${advice}${noteLines(note)}`;
1127
+ if (view.status !== "needs_input")
1128
+ return queued;
1129
+ const waiting = await waitsOn(caller, entry, ref, { ...view, note: undefined }, scope).catch((error) => scope.report?.(error));
1130
+ return waiting ? `${queued}\n${waiting}` : queued;
1131
+ }
897
1132
  const view = await within(scope, host.view(caller, entry.id, { last: 1 }));
898
1133
  if (view.status === "needs_input" && !interrupt)
899
1134
  return asks(view);
900
1135
  let paused = false;
901
1136
  if (view.running) {
902
1137
  const running = view.running;
1138
+ if (when === "steer") {
1139
+ const input = { turnId: running, steerId: generateUUIDv7(), message, origin: you };
1140
+ const unconfirmed = `not confirmed: read ${quoted(ref)} to see whether the steer arrived.${read}`;
1141
+ const result = await sendWithRetry({ ...delivery, undone: "sent", unconfirmed }, () => host.steer(caller, entry.id, input));
1142
+ if (typeof result === "string")
1143
+ return result;
1144
+ if (result.retried && result.answer.outcome === "no_active_turn")
1145
+ return unconfirmed;
1146
+ if (result.answer.outcome === "queued") {
1147
+ const current = await viewAfterDelivery(caller, entry.id, scope, 1);
1148
+ return queuedSteer(running, "did not take it") + advice + noteLines(current.note);
1149
+ }
1150
+ if (result.answer.outcome === "no_active_turn")
1151
+ return `${notSent("its turn is not taking messages now.")}${advice}${resendHint(ref, "queue")}`;
1152
+ if (result.answer.outcome === "unsupported")
1153
+ return `${notSent("this agent takes no message while it works.")}${advice}${resendHint(ref, "queue")}`;
1154
+ if (starterHint)
1155
+ return `steered ${quoted(ref)} (turn ${json(running)}): accepted. ${starterHint}`;
1156
+ return steerReceipt(caller, entry, ref, input, scope);
1157
+ }
903
1158
  if (interrupt) {
904
1159
  // The package's stop, of this turn only, asked right before it is made, and only
905
1160
  // while the message could still be sent after it.
906
1161
  await assertMay(caller, "destructive", "send_message", scope);
907
1162
  const cancel = host.cancel;
908
- if (!open(caller, scope.deadline <= scope.from ? scope.end : scope.deadline))
1163
+ if (!open(caller, firstCutoff))
909
1164
  return `${notSent("this call's wait ended first; its turn was not stopped.")} Send again.${again}`;
910
1165
  const stopped = await dispatched(scope, cancel.call(host, caller, entry.id, running));
911
1166
  if (stopped === undefined)
912
1167
  return `${notSent("its turn was asked to stop; that is not confirmed.")}${again}`;
913
1168
  done.stopped = stopped === "stopped";
914
1169
  }
915
- const seen = await waitUntil(scope, () => [entry.id], async () => {
916
- const fact = await turnIn(caller, entry.id, running, scope);
917
- if (fact.state === "ended" || interrupt)
918
- return { done: fact.state === "ended", value: { fact } };
919
- // A turn that starts waiting on an answer will not end on its own: say so now.
920
- const now = await viewIn(caller, entry.id, scope);
921
- const asking = now.status === "needs_input" && now.running === running ? now : undefined;
922
- return { done: asking !== undefined, value: { fact, asking } };
923
- });
1170
+ const seen = await followTurn(caller, entry.id, running, scope, when);
924
1171
  live(caller);
925
1172
  paused = seen.paused;
926
- const { fact, asking } = seen.value;
927
- if (asking)
928
- return asks(asking);
1173
+ const { fact, view: current } = seen.value;
1174
+ if (seen.done && current)
1175
+ return asks(current);
929
1176
  if (fact.state !== "ended")
930
- 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}`;
1177
+ return busy(done.stopped
1178
+ ? "its turn's end was not seen before this call's wait ended."
1179
+ : interrupt
1180
+ ? "its turn was asked to stop and has not yet."
1181
+ : "it was still working when this call's wait ended.", current?.note);
931
1182
  if (fact.outcome === "cancelled" && !interrupt)
932
1183
  return notSent(`its turn was stopped${stoppedBy(fact.cancelledBy, you)} while this call waited, so this message was not sent after it.`);
933
1184
  }
934
1185
  // The cutoff: the call's grace only for a `wait: 0` call deciding on its first look,
935
1186
  // else its deadline; checked again after authorising, right before the send.
936
- const cutoff = !paused && scope.deadline <= scope.from ? scope.end : scope.deadline;
937
- const late = `${notSent(done.stopped ? "this call's wait ended before the message could follow." : "this call's wait ended first.")} Send again.${again}`;
938
- if (!open(caller, cutoff))
939
- return late;
1187
+ const cutoff = paused ? scope.deadline : firstCutoff;
940
1188
  const turnId = generateUUIDv7();
941
1189
  const input = { turnId, message, origin: you };
942
- 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 }))}`;
943
- let sent = false;
944
- for (let attempt = 0; attempt < 2 && !sent; attempt++) {
945
- if (attempt > 0) {
946
- // The same turn id again, which the engine converges on: only while the call
947
- // is open, within its time, and still allowed.
948
- if (!open(caller, scope.end))
949
- return unconfirmed;
950
- try {
951
- await assertMay(caller, "write", "send_message", scope);
952
- }
953
- catch (error) {
954
- scope.report?.(error);
955
- return unconfirmed;
956
- }
957
- if (!open(caller, scope.end))
958
- return unconfirmed;
959
- }
960
- else {
961
- await assertMay(caller, "write", "send_message", scope);
962
- if (!open(caller, cutoff))
963
- return late;
964
- }
965
- try {
966
- const sending = host.send(caller, entry.id, input);
967
- if (scope.report)
968
- void sending.catch(scope.report);
969
- await within(scope, sending);
970
- sent = true;
971
- }
972
- catch (error) {
973
- // A host that threw before it had a promise (each error is told once).
974
- scope.report?.(error);
975
- const definite = error instanceof OperatorError || error instanceof Refused;
976
- if (definite && attempt > 0)
977
- return unconfirmed;
978
- if (definite && (error instanceof Refused ? error.refusal.code : error.code) === "busy")
979
- return `${notSent("another turn started there first.")} ${busyHint}`;
980
- if (definite)
981
- throw error;
982
- // No answer: once more with the same turn id.
983
- }
984
- }
985
- if (!sent)
986
- return unconfirmed;
987
1190
  // An interrupt's stop is said in every result, the sent ones included.
988
1191
  const lead = done.stopped ? `stopped ${quoted(ref)}'s turn; ` : "";
989
- try {
990
- return `${lead}sent to ${quoted(ref)}.\n${await ownOutcome(caller, entry, ref, turnId, scope)}`;
991
- }
992
- catch (error) {
993
- scope.report?.(error);
994
- return `${lead}sent to ${quoted(ref)} (turn ${json(turnId)}); its outcome could not be read.${line(hint("read_session", { session: ref }))}`;
995
- }
1192
+ const result = await sendWithRetry({
1193
+ ...delivery,
1194
+ cutoff,
1195
+ undone: "sent",
1196
+ busy: busy("another turn started there first."),
1197
+ unconfirmed: `${lead}not confirmed: the send to ${quoted(ref)} got no answer. Read the session to see whether it arrived.${read}`,
1198
+ }, () => host.send(caller, entry.id, input));
1199
+ if (typeof result === "string")
1200
+ return result;
1201
+ const sent = `${lead}sent to ${quoted(ref)}`;
1202
+ return withOutcome(ownOutcome(caller, entry, ref, turnId, scope), `${sent}.`, `${sent} (turn ${json(turnId)}); its outcome could not be read.`);
996
1203
  }
997
- /**
998
- * A turn the package minted, followed by its id: its outcome once it ended;
999
- * what it waits on only while the session's running turn is this one; else
1000
- * that it still works, or that its turn is not known, with a read hint. A
1001
- * successor's question is never taken for its own.
1002
- */
1003
1204
  /** Setup failed before any turn began: the only error a first task's unknown turn may report. */
1004
1205
  const setupFailed = (view) => view.status === "error" && !view.running && !view.lastEnded && view.turns.length === 0;
1206
+ async function endedOutcome(caller, entry, ref, turnId, fact, view, scope) {
1207
+ const at = view.turns.findIndex((t) => t.turnId === turnId);
1208
+ if (at < 0)
1209
+ return `status: ${fact.outcome}${noteLines(view.note)}${line(hint("read_session", { session: ref }))}`;
1210
+ const status = fact.outcome === "done" ? "idle" : fact.outcome === "cancelled" ? "stopped" : "error";
1211
+ const own = {
1212
+ status,
1213
+ note: view.note,
1214
+ turns: view.turns.slice(0, at + 1),
1215
+ waiting: [],
1216
+ lastEnded: {
1217
+ turnId,
1218
+ outcome: fact.outcome,
1219
+ steers: fact.steers ?? (view.lastEnded?.turnId === turnId ? view.lastEnded.steers : undefined),
1220
+ },
1221
+ };
1222
+ const newer = view.turns.slice(at + 1).reduce((n, t) => n + t.messages.length, 0);
1223
+ return outcomeOf(caller, { entry, ref, view: own, settled: true }, scope, newer);
1224
+ }
1225
+ /** Follow only the turn the call started. A successor's question belongs to the successor. */
1005
1226
  async function ownOutcome(caller, entry, ref, turnId, scope) {
1006
1227
  const { value } = await waitUntil(scope, () => [entry.id], async () => {
1007
1228
  const fact = await turnIn(caller, entry.id, turnId, scope);
1008
1229
  const view = await viewIn(caller, entry.id, scope);
1009
- const asks = view.running === turnId && view.status === "needs_input";
1230
+ const asks = turnAsks(view, turnId);
1010
1231
  const failedSetup = fact.state === "unknown" && setupFailed(view);
1011
1232
  return { done: fact.state === "ended" || asks || failedSetup, value: { fact, view } };
1012
1233
  });
1013
1234
  const { fact, view } = value;
1014
1235
  const read = line(hint("read_session", { session: ref }));
1015
- if (fact.state === "ended") {
1016
- const at = view.turns.findIndex((t) => t.turnId === turnId);
1017
- const status = fact.outcome === "done" ? "idle" : fact.outcome === "cancelled" ? "stopped" : "error";
1018
- if (at < 0)
1019
- return `status: ${fact.outcome}${read}`;
1020
- const own = { status, turns: view.turns.slice(0, at + 1), waiting: [] };
1021
- const newer = view.turns.slice(at + 1).reduce((n, t) => n + t.messages.length, 0);
1022
- return outcomeOf(caller, { entry, ref, view: own, settled: true }, scope, newer);
1023
- }
1236
+ if (fact.state === "ended")
1237
+ return endedOutcome(caller, entry, ref, turnId, fact, view, scope);
1024
1238
  if (view.running === turnId)
1025
1239
  return outcomeOf(caller, { entry, ref, view, settled: view.status === "needs_input" }, scope);
1026
1240
  if (setupFailed(view)) {
@@ -1028,27 +1242,50 @@ export function createOperator(host, options = {}) {
1028
1242
  const current = all.find((e) => e.id === entry.id) ?? entry;
1029
1243
  return outcomeOf(caller, { entry: current, ref, view, settled: true }, scope);
1030
1244
  }
1031
- if (view.status === "setting_up")
1032
- return `status: setting_up${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
1033
- if (fact.state === "running")
1034
- return `status: working${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
1035
- return `status: unknown (its turn is not known yet)${read}`;
1245
+ const note = noteLines(view.note);
1246
+ if (view.status === "setting_up" || fact.state === "running") {
1247
+ const status = view.status === "setting_up" ? "setting_up" : "working";
1248
+ return `status: ${status}${note}${line(hint("wait_for_sessions", { sessions: [ref] }))}`;
1249
+ }
1250
+ return `status: unknown (its turn is not known yet)${note}${read}`;
1036
1251
  }
1252
+ const modes = ["queue"];
1253
+ if (host.steer)
1254
+ modes.unshift("steer");
1255
+ if (host.cancel)
1256
+ modes.push("interrupt");
1257
+ const defaultWhen = host.steer ? "steer" : "queue";
1037
1258
  const sendMessage = def({
1038
1259
  name: "send_message",
1039
1260
  title: "Send message",
1040
- description: "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.",
1261
+ description: [
1262
+ "Send a message to a session's agent. It is told who sent it.",
1263
+ host.steer &&
1264
+ "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.",
1265
+ host.queue
1266
+ ? "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."
1267
+ : "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.",
1268
+ "A session waiting on an answer needs answer_request.",
1269
+ host.queue && "You can queue a separate task while the question stays open.",
1270
+ host.cancel &&
1271
+ "Use interrupt to stop the running turn and send now. Any question it waits on is dropped.",
1272
+ host.cancel && host.queue && "The product keeps its unread steers in its queue.",
1273
+ host.cancel && !host.queue && host.steer && "Its unread steers are dropped.",
1274
+ "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.",
1275
+ ]
1276
+ .filter(Boolean)
1277
+ .join(" "),
1041
1278
  input: {
1042
1279
  session: sessionArg,
1043
1280
  message: words().max(MAX_TEXT).describe("What to tell the agent"),
1044
1281
  when: z
1045
- .enum(["idle", "interrupt"])
1282
+ .enum(modes)
1046
1283
  .optional()
1047
- .describe("idle (default): after its turn ends; interrupt: stop it and send"),
1048
- wait: waitArg,
1284
+ .describe(`How to deliver the message (default ${defaultWhen})`),
1285
+ wait: waitArg.describe("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."),
1049
1286
  },
1050
1287
  effect: "write",
1051
- async run({ session, message, when = "idle" }, caller, scope) {
1288
+ async run({ session, message, when = defaultWhen }, caller, scope) {
1052
1289
  const { entry, ref, all } = await find(caller, session, scope);
1053
1290
  if (caller.kind === "session" && entry.id === caller.sessionId)
1054
1291
  throw refuse.self("session");
@@ -1060,7 +1297,7 @@ export function createOperator(host, options = {}) {
1060
1297
  throw refuse.busy(hint, ref, "being set up", "sent");
1061
1298
  if (when === "interrupt" && !host.cancel)
1062
1299
  throw refuse.unsupported("This host cannot stop a turn.");
1063
- return once(json(["send", keyOf(caller), entry.id, message]), scope, () => deliver(caller, entry, ref, message, all, when === "interrupt", scope), hint("read_session", { session: ref }));
1300
+ return once(json(["send", keyOf(caller), entry.id, when, message]), scope, () => deliver(caller, entry, ref, message, all, when, scope), hint("read_session", { session: ref }));
1064
1301
  },
1065
1302
  });
1066
1303
  // ---- starting ------------------------------------------------------------------
@@ -1221,7 +1458,7 @@ export function createOperator(host, options = {}) {
1221
1458
  // Refused for certain: nothing was made, so the minute's slot is given back.
1222
1459
  if (error instanceof OperatorError || error instanceof Refused)
1223
1460
  giveBack();
1224
- throw asRefusal(fromHost(error, caller, now, about, "started in it"), scope);
1461
+ throw fromHost(error, scope, { caller, all: now, about, undone: "started in it" });
1225
1462
  }
1226
1463
  });
1227
1464
  const where = into
@@ -1478,7 +1715,7 @@ export function createOperator(host, options = {}) {
1478
1715
  }
1479
1716
  }
1480
1717
  catch (error) {
1481
- const refusal = asRefusal(fromHost(error, caller, all, about, "archived"), scope);
1718
+ const refusal = fromHost(error, scope, { caller, all, about, undone: "archived" });
1482
1719
  if (!stopped.length)
1483
1720
  throw refusal;
1484
1721
  // Still a refusal, so a batch of them is one; its own "nothing was done" is not so: