@fungi.computer/shiitake-extensions 0.6.6 → 0.6.7

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.
@@ -44,13 +44,23 @@ export declare const OpenAsk: Schema.Struct<{
44
44
  /**
45
45
  * The Agent this ask waits on first, derived by the host from whom the
46
46
  * asking run's work came from. Absent means a person. An ask waiting on an
47
- * Agent is calm: the Agent answers it or escalates it to a person.
47
+ * Agent is calm: the Agent answers it or escalates it to its own parent.
48
48
  */
49
49
  readonly waitingOn: Schema.optionalKey<Schema.Struct<{
50
50
  readonly agentId: Schema.NonEmptyString;
51
51
  readonly sessionId: Schema.NonEmptyString;
52
52
  readonly name: Schema.NonEmptyString;
53
53
  }>>;
54
+ /** Latest explicit escalation or evidence that the waiting Agent is gone. */
55
+ readonly escalated: Schema.optionalKey<Schema.Struct<{
56
+ readonly by: Schema.Struct<{
57
+ readonly agentId: Schema.NonEmptyString;
58
+ readonly sessionId: Schema.NonEmptyString;
59
+ readonly name: Schema.NonEmptyString;
60
+ }>;
61
+ readonly reason: Schema.Literals<readonly ["escalated", "sender_archived", "sender_absent"]>;
62
+ readonly note: Schema.optionalKey<Schema.String>;
63
+ }>>;
54
64
  /** Decisions awaiting the person's answers. */
55
65
  readonly questions: Schema.$Array<Schema.Struct<{
56
66
  /** Identity used to associate this question with its answer. */
@@ -87,13 +97,23 @@ export declare const AskProjection: Schema.Struct<{
87
97
  /**
88
98
  * The Agent this ask waits on first, derived by the host from whom the
89
99
  * asking run's work came from. Absent means a person. An ask waiting on an
90
- * Agent is calm: the Agent answers it or escalates it to a person.
100
+ * Agent is calm: the Agent answers it or escalates it to its own parent.
91
101
  */
92
102
  readonly waitingOn: Schema.optionalKey<Schema.Struct<{
93
103
  readonly agentId: Schema.NonEmptyString;
94
104
  readonly sessionId: Schema.NonEmptyString;
95
105
  readonly name: Schema.NonEmptyString;
96
106
  }>>;
107
+ /** Latest explicit escalation or evidence that the waiting Agent is gone. */
108
+ readonly escalated: Schema.optionalKey<Schema.Struct<{
109
+ readonly by: Schema.Struct<{
110
+ readonly agentId: Schema.NonEmptyString;
111
+ readonly sessionId: Schema.NonEmptyString;
112
+ readonly name: Schema.NonEmptyString;
113
+ }>;
114
+ readonly reason: Schema.Literals<readonly ["escalated", "sender_archived", "sender_absent"]>;
115
+ readonly note: Schema.optionalKey<Schema.String>;
116
+ }>>;
97
117
  /** Decisions awaiting the person's answers. */
98
118
  readonly questions: Schema.$Array<Schema.Struct<{
99
119
  /** Identity used to associate this question with its answer. */
@@ -219,6 +239,17 @@ export declare const AnsweredBy: Schema.Struct<{
219
239
  }>;
220
240
  /** Outcome of the Agent an Ask waits on passing it on. */
221
241
  export declare const EscalateResult: Schema.Union<readonly [Schema.Struct<{
242
+ /** The Ask was passed one authenticated parent hop upward. */
243
+ readonly result: Schema.Literal<"escalated">;
244
+ /** The next recipient is an Agent, not yet a person. */
245
+ readonly to: Schema.Literal<"agent">;
246
+ /** Exact Agent and Session that now own the decision. */
247
+ readonly waitingOn: Schema.Struct<{
248
+ readonly agentId: Schema.NonEmptyString;
249
+ readonly sessionId: Schema.NonEmptyString;
250
+ readonly name: Schema.NonEmptyString;
251
+ }>;
252
+ }>, Schema.Struct<{
222
253
  /** The Ask now waits on someone else. */
223
254
  readonly result: Schema.Literal<"escalated">;
224
255
  /** Whom it waits on now: a person. */
@@ -243,6 +274,8 @@ export type EscalateResult = Schema.Schema.Type<typeof EscalateResult>;
243
274
  export declare const EscalateInput: Schema.Struct<{
244
275
  /** Ask being passed on. */
245
276
  readonly askId: Schema.String;
277
+ /** Explanation retained with the handoff. */
278
+ readonly note: Schema.optional<Schema.String>;
246
279
  }>;
247
280
  /** The answer conversation carries its draft between decision steps. */
248
281
  export declare const AnswerFlowInput: Schema.Union<readonly [Schema.Struct<{
@@ -400,9 +433,22 @@ export declare const questionContract: {
400
433
  readonly input: Schema.Struct<{
401
434
  /** Ask being passed on. */
402
435
  readonly askId: Schema.String;
436
+ /** Explanation retained with the handoff. */
437
+ readonly note: Schema.optional<Schema.String>;
403
438
  }>;
404
439
  /** Where the Ask waits now, or why it did not move. */
405
440
  readonly output: Schema.Union<readonly [Schema.Struct<{
441
+ /** The Ask was passed one authenticated parent hop upward. */
442
+ readonly result: Schema.Literal<"escalated">;
443
+ /** The next recipient is an Agent, not yet a person. */
444
+ readonly to: Schema.Literal<"agent">;
445
+ /** Exact Agent and Session that now own the decision. */
446
+ readonly waitingOn: Schema.Struct<{
447
+ readonly agentId: Schema.NonEmptyString;
448
+ readonly sessionId: Schema.NonEmptyString;
449
+ readonly name: Schema.NonEmptyString;
450
+ }>;
451
+ }>, Schema.Struct<{
406
452
  /** The Ask now waits on someone else. */
407
453
  readonly result: Schema.Literal<"escalated">;
408
454
  /** Whom it waits on now: a person. */
@@ -468,13 +514,23 @@ export declare const questionContract: {
468
514
  /**
469
515
  * The Agent this ask waits on first, derived by the host from whom the
470
516
  * asking run's work came from. Absent means a person. An ask waiting on an
471
- * Agent is calm: the Agent answers it or escalates it to a person.
517
+ * Agent is calm: the Agent answers it or escalates it to its own parent.
472
518
  */
473
519
  readonly waitingOn: Schema.optionalKey<Schema.Struct<{
474
520
  readonly agentId: Schema.NonEmptyString;
475
521
  readonly sessionId: Schema.NonEmptyString;
476
522
  readonly name: Schema.NonEmptyString;
477
523
  }>>;
524
+ /** Latest explicit escalation or evidence that the waiting Agent is gone. */
525
+ readonly escalated: Schema.optionalKey<Schema.Struct<{
526
+ readonly by: Schema.Struct<{
527
+ readonly agentId: Schema.NonEmptyString;
528
+ readonly sessionId: Schema.NonEmptyString;
529
+ readonly name: Schema.NonEmptyString;
530
+ }>;
531
+ readonly reason: Schema.Literals<readonly ["escalated", "sender_archived", "sender_absent"]>;
532
+ readonly note: Schema.optionalKey<Schema.String>;
533
+ }>>;
478
534
  /** Decisions awaiting the person's answers. */
479
535
  readonly questions: Schema.$Array<Schema.Struct<{
480
536
  /** Identity used to associate this question with its answer. */
@@ -514,13 +570,23 @@ export declare const questionContract: {
514
570
  /**
515
571
  * The Agent this ask waits on first, derived by the host from whom the
516
572
  * asking run's work came from. Absent means a person. An ask waiting on an
517
- * Agent is calm: the Agent answers it or escalates it to a person.
573
+ * Agent is calm: the Agent answers it or escalates it to its own parent.
518
574
  */
519
575
  readonly waitingOn: Schema.optionalKey<Schema.Struct<{
520
576
  readonly agentId: Schema.NonEmptyString;
521
577
  readonly sessionId: Schema.NonEmptyString;
522
578
  readonly name: Schema.NonEmptyString;
523
579
  }>>;
580
+ /** Latest explicit escalation or evidence that the waiting Agent is gone. */
581
+ readonly escalated: Schema.optionalKey<Schema.Struct<{
582
+ readonly by: Schema.Struct<{
583
+ readonly agentId: Schema.NonEmptyString;
584
+ readonly sessionId: Schema.NonEmptyString;
585
+ readonly name: Schema.NonEmptyString;
586
+ }>;
587
+ readonly reason: Schema.Literals<readonly ["escalated", "sender_archived", "sender_absent"]>;
588
+ readonly note: Schema.optionalKey<Schema.String>;
589
+ }>>;
524
590
  /** Decisions awaiting the person's answers. */
525
591
  readonly questions: Schema.$Array<Schema.Struct<{
526
592
  /** Identity used to associate this question with its answer. */
@@ -1,4 +1,4 @@
1
- import { AttentionRecipientSchema, ExtensionId, } from "@fungi.computer/shiitake/extensions";
1
+ import { AttentionRecipientSchema, AttentionEscalationSchema, ExtensionId, } from "@fungi.computer/shiitake/extensions";
2
2
  import * as Schema from "effect/Schema";
3
3
  import { CatalogStep } from "../internal/catalog.js";
4
4
  const text = (maximum) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(maximum), Schema.isPattern(/\S/u));
@@ -41,9 +41,11 @@ export const OpenAsk = Schema.Struct({
41
41
  /**
42
42
  * The Agent this ask waits on first, derived by the host from whom the
43
43
  * asking run's work came from. Absent means a person. An ask waiting on an
44
- * Agent is calm: the Agent answers it or escalates it to a person.
44
+ * Agent is calm: the Agent answers it or escalates it to its own parent.
45
45
  */
46
46
  waitingOn: Schema.optionalKey(AttentionRecipientSchema),
47
+ /** Latest explicit escalation or evidence that the waiting Agent is gone. */
48
+ escalated: Schema.optionalKey(AttentionEscalationSchema),
47
49
  /** Decisions awaiting the person's answers. */
48
50
  questions: Questions,
49
51
  /** Whether the ask is live in a turn or parked for later. */
@@ -133,6 +135,14 @@ export const AnsweredBy = Schema.Struct({
133
135
  });
134
136
  /** Outcome of the Agent an Ask waits on passing it on. */
135
137
  export const EscalateResult = Schema.Union([
138
+ Schema.Struct({
139
+ /** The Ask was passed one authenticated parent hop upward. */
140
+ result: Schema.Literal("escalated"),
141
+ /** The next recipient is an Agent, not yet a person. */
142
+ to: Schema.Literal("agent"),
143
+ /** Exact Agent and Session that now own the decision. */
144
+ waitingOn: AttentionRecipientSchema,
145
+ }),
136
146
  Schema.Struct({
137
147
  /** The Ask now waits on someone else. */
138
148
  result: Schema.Literal("escalated"),
@@ -155,6 +165,8 @@ export const EscalateResult = Schema.Union([
155
165
  export const EscalateInput = Schema.Struct({
156
166
  /** Ask being passed on. */
157
167
  askId: text(256),
168
+ /** Explanation retained with the handoff. */
169
+ note: Schema.optional(Schema.String.check(Schema.isMaxLength(1000))),
158
170
  });
159
171
  const answerStep = {
160
172
  /** Ask whose answer draft is being edited. */
@@ -1,6 +1,6 @@
1
1
  import { nanoid } from "@fungi.computer/cairn";
2
2
  import { Mycelium } from "@fungi.computer/mycelium";
3
- import { defineCollection, defineExtension, ExtensionCommandError, AttentionRecipientSchema, } from "@fungi.computer/shiitake/extensions";
3
+ import { defineCollection, defineExtension, ExtensionCommandError, AttentionRecipientSchema, AttentionEscalationSchema, } from "@fungi.computer/shiitake/extensions";
4
4
  import * as Clock from "effect/Clock";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Option from "effect/Option";
@@ -13,8 +13,8 @@ import { advanceAnswerFlow } from "./answer-flow.js";
13
13
  const config = {
14
14
  maximumOpen: 4,
15
15
  liveWindowMs: 600_000,
16
- // No Agent holds a routed ask forever: past this a person decides.
17
- routedEscalationMs: 900_000,
16
+ // Check presence, never escalate merely because a present Agent took time.
17
+ senderCheckMs: 900_000,
18
18
  routesToSender: false,
19
19
  idle: "Need a person's decision? forage.describe({path:'question'}) first.",
20
20
  guide: "Question tools: ask, withdraw. Use question.ask for decisions that need a person's answer. Put the recommended option first; do not add Other, since free text is always available. Use credential tools for secrets. While a question is parked, finish independent work and end the turn.",
@@ -44,6 +44,7 @@ const Response = Schema.Union([
44
44
  const AskRow = Schema.Struct({
45
45
  askId: OpenAsk.fields.askId,
46
46
  waitingOn: Schema.optional(AttentionRecipientSchema),
47
+ escalated: Schema.optional(AttentionEscalationSchema),
47
48
  questions: Questions,
48
49
  status: OpenAsk.fields.status,
49
50
  createdAt: OpenAsk.fields.createdAt,
@@ -173,7 +174,7 @@ function closeAsk(ctx, row, outcome, followUpWorkId = null, toolCallId) {
173
174
  if (row.expiry !== null)
174
175
  yield* ctx.timers.cancel(`ask:${row.askId}`);
175
176
  if (row.waitingOn !== undefined)
176
- yield* ctx.timers.cancel(routeTimer(row.askId));
177
+ yield* ctx.timers.cancel(checkTimer(row.askId));
177
178
  yield* ctx.attention.clear(row.sessionId, row.askId);
178
179
  yield* ctx.observe(row.sessionId);
179
180
  });
@@ -297,6 +298,8 @@ function project(row) {
297
298
  createdAt: row.createdAt,
298
299
  expiresAt: row.expiry?.at ?? null,
299
300
  };
301
+ if (row.escalated !== undefined)
302
+ Object.assign(open, { escalated: row.escalated });
300
303
  return row.waitingOn === undefined
301
304
  ? open
302
305
  : { ...open, waitingOn: row.waitingOn };
@@ -398,13 +401,6 @@ function expireAsk(ctx, row, now) {
398
401
  return Effect.gen(function* () {
399
402
  if (row.expiry === null || now < row.expiry.at || row.pending !== null)
400
403
  return undefined;
401
- if (row.waitingOn !== undefined) {
402
- // Nobody answered in time. A person decides next; the default never
403
- // stands in for a decision no person has seen.
404
- yield* ctx.timers.cancel(`ask:${row.askId}`);
405
- yield* escalateAsk(ctx, { ...row, expiry: null });
406
- return undefined;
407
- }
408
404
  const response = row.expiry.action === "stop"
409
405
  ? { status: "expired", action: "stop" }
410
406
  : {
@@ -540,31 +536,31 @@ function askAttention(row) {
540
536
  summary: row.questions.map((question) => question.header).join(", "),
541
537
  since: row.createdAt,
542
538
  };
539
+ if (row.escalated !== undefined)
540
+ Object.assign(item, { escalated: row.escalated });
543
541
  const timed = row.expiry === null ? item : { ...item, expiresAt: row.expiry.at };
544
542
  return row.waitingOn === undefined
545
543
  ? timed
546
544
  : { ...timed, waitingOn: row.waitingOn };
547
545
  }
548
546
  /**
549
- * The durable backstop of an ask that waits on an Agent. It is separate from
550
- * the asker's own expiry, so it always hands the ask to a person and never
551
- * applies a default answer.
547
+ * Durable presence checks are separate from the asker's own expiry.
552
548
  */
553
- function routeTimer(askId) {
554
- return `route:${askId}`;
549
+ function checkTimer(askId) {
550
+ return `check:${askId}`;
555
551
  }
556
- /** Hand an ask to a person: it stops waiting on any Agent and needs them. */
557
- function escalateAsk(ctx, row) {
552
+ /** Hand an ask to a person, preserving why it left the Agent chain. */
553
+ function escalateAsk(ctx, row, escalated) {
558
554
  return Effect.gen(function* () {
559
- const moved = { ...row, waitingOn: undefined };
560
- yield* ctx.timers.cancel(routeTimer(row.askId));
555
+ const moved = { ...row, waitingOn: undefined, escalated };
556
+ yield* ctx.timers.cancel(checkTimer(row.askId));
561
557
  yield* ctx.state.asks.put(moved);
562
558
  yield* ctx.attention.set(row.sessionId, askAttention(moved));
563
559
  yield* ctx.observe(row.sessionId);
564
560
  return moved;
565
561
  });
566
562
  }
567
- function escalateFromAgent(ctx, sessionId, askId, caller) {
563
+ function escalateFromAgent(ctx, sessionId, askId, caller, note, next) {
568
564
  return Effect.gen(function* () {
569
565
  const found = yield* ctx.state.asks.get(askId);
570
566
  if (Option.isNone(found) || found.value.sessionId !== sessionId) {
@@ -582,14 +578,53 @@ function escalateFromAgent(ctx, sessionId, askId, caller) {
582
578
  };
583
579
  return answered;
584
580
  }
585
- if (!waitsOn(row, caller.agentId, caller.sessionId)) {
581
+ if (row.waitingOn === undefined ||
582
+ !waitsOn(row, caller.agentId, caller.sessionId)) {
583
+ // Replaying the same handoff lets the host retry its idempotent parent
584
+ // notification after an ambiguous transport failure, without moving it again.
585
+ if (row.escalated?.reason === "escalated" &&
586
+ row.escalated.by.agentId === caller.agentId &&
587
+ row.escalated.by.sessionId === caller.sessionId &&
588
+ row.escalated.note === note)
589
+ return row.waitingOn === undefined
590
+ ? { result: "escalated", to: "person" }
591
+ : {
592
+ result: "escalated",
593
+ to: "agent",
594
+ waitingOn: row.waitingOn,
595
+ };
586
596
  const refused = {
587
597
  result: "refused",
588
598
  reason: "not_sender",
589
599
  };
590
600
  return refused;
591
601
  }
592
- yield* escalateAsk(ctx, row);
602
+ const by = row.waitingOn;
603
+ // Preparation read the host outside SQLite. Do not use absent/stale evidence
604
+ // as proof of a root; closed/replayed items above need no host lookup.
605
+ if (next === undefined)
606
+ return { result: "refused", reason: "not_sender" };
607
+ const provenance = {
608
+ by,
609
+ reason: "escalated",
610
+ };
611
+ if (note !== undefined)
612
+ Object.assign(provenance, { note });
613
+ if (next !== null) {
614
+ const moved = {
615
+ ...row,
616
+ waitingOn: next,
617
+ escalated: provenance,
618
+ };
619
+ yield* ctx.state.asks.put(moved);
620
+ yield* ctx.attention.set(row.sessionId, askAttention(moved));
621
+ yield* ctx.timers.set(checkTimer(row.askId), (yield* Clock.currentTimeMillis) + ctx.config.senderCheckMs);
622
+ yield* ctx.observe(row.sessionId);
623
+ return { result: "escalated", to: "agent", waitingOn: next };
624
+ }
625
+ // An explicit action keeps its actor even when the next parent is gone.
626
+ // Automatic presence-check promotions still name the missing recipient.
627
+ yield* escalateAsk(ctx, row, provenance);
593
628
  const escalated = { result: "escalated", to: "person" };
594
629
  return escalated;
595
630
  });
@@ -876,21 +911,45 @@ export function questionExtensionFor(routesToSender) {
876
911
  timers: true,
877
912
  hooks: {
878
913
  onSettled: (ctx, page) => Effect.forEach(page, (run) => settle(ctx, run), { discard: true }),
879
- onTimer: (ctx, timer) => Effect.gen(function* () {
880
- if (timer.key.startsWith("route:")) {
881
- const row = yield* ctx.state.asks.get(timer.key.slice(6));
882
- if (Option.isSome(row) &&
883
- row.value.waitingOn !== undefined &&
884
- row.value.pending === null)
885
- yield* escalateAsk(ctx, row.value);
886
- return;
887
- }
888
- if (!timer.key.startsWith("ask:"))
889
- return;
890
- const row = yield* ctx.state.asks.get(timer.key.slice(4));
891
- if (Option.isSome(row))
892
- yield* expireAsk(ctx, row.value, timer.firedAt);
893
- }),
914
+ onTimer: {
915
+ prepare: (ctx, timer) => Effect.gen(function* () {
916
+ const checked = timer.key.startsWith("check:")
917
+ ? ctx.state.read(({ asks }) => asks.get(timer.key.slice(6)))
918
+ : Option.none();
919
+ const recipient = Option.isSome(checked)
920
+ ? checked.value.waitingOn
921
+ : undefined;
922
+ const status = recipient === undefined
923
+ ? "unknown"
924
+ : yield* ctx.recipientStatus(recipient);
925
+ return Effect.gen(function* () {
926
+ if (timer.key.startsWith("check:")) {
927
+ const row = yield* ctx.state.asks.get(timer.key.slice(6));
928
+ if (Option.isSome(row) &&
929
+ row.value.waitingOn !== undefined &&
930
+ row.value.pending === null) {
931
+ if (recipient !== undefined &&
932
+ waitsOn(row.value, recipient.agentId, recipient.sessionId) &&
933
+ (status === "archived" || status === "absent"))
934
+ yield* escalateAsk(ctx, row.value, {
935
+ by: row.value.waitingOn,
936
+ reason: status === "archived"
937
+ ? "sender_archived"
938
+ : "sender_absent",
939
+ });
940
+ else
941
+ yield* ctx.timers.set(checkTimer(row.value.askId), timer.firedAt + ctx.config.senderCheckMs);
942
+ }
943
+ return;
944
+ }
945
+ if (!timer.key.startsWith("ask:"))
946
+ return;
947
+ const row = yield* ctx.state.asks.get(timer.key.slice(4));
948
+ if (Option.isSome(row))
949
+ yield* expireAsk(ctx, row.value, timer.firedAt);
950
+ });
951
+ }),
952
+ },
894
953
  },
895
954
  prompt: (ctx) => [{ name: "question", text: ctx.config.idle }],
896
955
  projection: {
@@ -924,14 +983,34 @@ export function questionExtensionFor(routesToSender) {
924
983
  agentId: caller.agentId,
925
984
  },
926
985
  }))),
927
- escalateAgent: ({ sessionId, input, caller }) => Effect.gen(function* () {
928
- if (caller === undefined)
929
- return yield* Effect.fail(new ExtensionCommandError({
930
- reason: "rejected",
931
- message: "Only an authenticated Agent can escalate an Ask",
932
- }));
933
- return yield* escalateFromAgent(ctx, sessionId, input.askId, caller);
934
- }),
986
+ escalateAgent: {
987
+ prepare: ({ sessionId, input, caller }) => Effect.gen(function* () {
988
+ if (caller === undefined)
989
+ return yield* Effect.fail(new ExtensionCommandError({
990
+ reason: "rejected",
991
+ message: "Only an authenticated Agent can escalate an Ask",
992
+ }));
993
+ const found = ctx.state.read(({ asks }) => asks.get(input.askId));
994
+ let next;
995
+ if (Option.isSome(found) &&
996
+ found.value.sessionId === sessionId &&
997
+ found.value.pending === null &&
998
+ found.value.waitingOn !== undefined &&
999
+ waitsOn(found.value, caller.agentId, caller.sessionId)) {
1000
+ const parent = yield* ctx.recipientParent(found.value.waitingOn);
1001
+ if (parent === null)
1002
+ next = null;
1003
+ else {
1004
+ const status = yield* ctx.recipientStatus(parent);
1005
+ next =
1006
+ status === "archived" || status === "absent"
1007
+ ? null
1008
+ : parent;
1009
+ }
1010
+ }
1011
+ return escalateFromAgent(ctx, sessionId, input.askId, caller, input.note, next);
1012
+ }),
1013
+ },
935
1014
  decline: ({ sessionId, input }) => respondPerson(ctx, sessionId, { kind: "decline", ...input }),
936
1015
  list: ({ sessionId }) => ctx.state.asks
937
1016
  .page({ index: sessionId, limit: ctx.config.maximumOpen })
@@ -960,83 +1039,106 @@ export function questionExtensionFor(routesToSender) {
960
1039
  input,
961
1040
  output: ToolResult,
962
1041
  execute: async (value, invocation) => {
963
- const created = await Effect.runPromise(ctx.transact(Effect.gen(function* () {
964
- const questions = yield* Schema.decodeUnknownEffect(Questions)(value.questions).pipe(Effect.mapError(() => new ExtensionCommandError({
965
- reason: "invalid",
966
- message: "Invalid question identifiers or option labels",
967
- })));
968
- const digest = questionDigest(sessionId, workId, questions);
969
- const rows = yield* ctx.state.asks.page({
970
- index: sessionId,
971
- limit: ctx.config.maximumOpen,
972
- });
973
- const open = yield* Effect.forEach(rows, (row) => row.workId === workId &&
974
- row.status === "live" &&
975
- row.runAttemptId !== runAttemptId
976
- ? parkAsk(ctx, row)
977
- : Effect.succeed(row));
978
- const replay = yield* replayQuestion(ctx, open, workId, digest, invocation.toolCallId);
979
- if (replay !== undefined)
980
- return replay;
981
- if (open.length === ctx.config.maximumOpen)
982
- return {
983
- status: "refused",
984
- reason: "session_limit",
985
- askIds: open.map((row) => row.askId),
986
- };
987
- const now = yield* Clock.currentTimeMillis;
988
- const window = invocation.deadlineAt === null
989
- ? 0
990
- : Math.max(0, Math.min(ctx.config.liveWindowMs, invocation.deadlineAt - now - deadlineReserveMs));
991
- // The Agent that sent this work answers later; a live wait
992
- // would stall the turn it may itself be waiting on.
993
- const waitingOn = ctx.config.routesToSender
994
- ? yield* ctx.workSender({ sessionId, workId })
995
- : null;
996
- const live = value.mode === "wait" &&
997
- window > 0 &&
998
- waitingOn === null;
999
- const existingLive = open.filter((row) => row.workId === workId && row.status === "live");
1000
- if (live && existingLive.length > 0)
1001
- return {
1002
- status: "refused",
1003
- reason: "live_limit",
1004
- askIds: existingLive.map((row) => row.askId),
1005
- };
1006
- const row = {
1007
- askId: nanoid(),
1008
- waitingOn: waitingOn ?? undefined,
1009
- sessionId,
1010
- workId,
1011
- digest,
1012
- questions,
1013
- status: live ? "live" : "parked",
1014
- runAttemptId: live ? runAttemptId : null,
1015
- pending: null,
1016
- createdAt: now,
1017
- expiry: "onExpire" in value
1018
- ? {
1019
- at: now + value.onExpire.afterMinutes * 60_000,
1020
- action: value.onExpire.action,
1042
+ const created = await Effect.runPromise(ctx.transact({
1043
+ prepare: Effect.gen(function* () {
1044
+ const waitingOn = ctx.config.routesToSender
1045
+ ? yield* ctx.workSender({ sessionId, workId })
1046
+ : null;
1047
+ const senderStatus = waitingOn === null
1048
+ ? "unknown"
1049
+ : yield* ctx.recipientStatus(waitingOn);
1050
+ return Effect.gen(function* () {
1051
+ const questions = yield* Schema.decodeUnknownEffect(Questions)(value.questions).pipe(Effect.mapError(() => new ExtensionCommandError({
1052
+ reason: "invalid",
1053
+ message: "Invalid question identifiers or option labels",
1054
+ })));
1055
+ const digest = questionDigest(sessionId, workId, questions);
1056
+ const rows = yield* ctx.state.asks.page({
1057
+ index: sessionId,
1058
+ limit: ctx.config.maximumOpen,
1059
+ });
1060
+ const open = yield* Effect.forEach(rows, (row) => row.workId === workId &&
1061
+ row.status === "live" &&
1062
+ row.runAttemptId !== runAttemptId
1063
+ ? parkAsk(ctx, row)
1064
+ : Effect.succeed(row));
1065
+ const replay = yield* replayQuestion(ctx, open, workId, digest, invocation.toolCallId);
1066
+ if (replay !== undefined)
1067
+ return replay;
1068
+ if (open.length === ctx.config.maximumOpen)
1069
+ return {
1070
+ status: "refused",
1071
+ reason: "session_limit",
1072
+ askIds: open.map((row) => row.askId),
1073
+ };
1074
+ const now = yield* Clock.currentTimeMillis;
1075
+ const window = invocation.deadlineAt === null
1076
+ ? 0
1077
+ : Math.max(0, Math.min(ctx.config.liveWindowMs, invocation.deadlineAt -
1078
+ now -
1079
+ deadlineReserveMs));
1080
+ // The Agent that sent this work answers later; a live wait
1081
+ // would stall the turn it may itself be waiting on.
1082
+ const live = value.mode === "wait" &&
1083
+ window > 0 &&
1084
+ waitingOn === null;
1085
+ const existingLive = open.filter((row) => row.workId === workId && row.status === "live");
1086
+ if (live && existingLive.length > 0)
1087
+ return {
1088
+ status: "refused",
1089
+ reason: "live_limit",
1090
+ askIds: existingLive.map((row) => row.askId),
1091
+ };
1092
+ let row = {
1093
+ askId: nanoid(),
1094
+ waitingOn: waitingOn ?? undefined,
1095
+ sessionId,
1096
+ workId,
1097
+ digest,
1098
+ questions,
1099
+ status: live ? "live" : "parked",
1100
+ runAttemptId: live ? runAttemptId : null,
1101
+ pending: null,
1102
+ createdAt: now,
1103
+ expiry: "onExpire" in value
1104
+ ? {
1105
+ at: now + value.onExpire.afterMinutes * 60_000,
1106
+ action: value.onExpire.action,
1107
+ }
1108
+ : null,
1109
+ };
1110
+ if (row.waitingOn !== undefined) {
1111
+ if (senderStatus === "archived" ||
1112
+ senderStatus === "absent")
1113
+ row = {
1114
+ ...row,
1115
+ waitingOn: undefined,
1116
+ escalated: {
1117
+ by: row.waitingOn,
1118
+ reason: senderStatus === "archived"
1119
+ ? "sender_archived"
1120
+ : "sender_absent",
1121
+ },
1122
+ };
1021
1123
  }
1022
- : null,
1023
- };
1024
- yield* ctx.state.asks.put(row);
1025
- if (row.expiry !== null)
1026
- yield* ctx.timers.set(`ask:${row.askId}`, row.expiry.at);
1027
- // Whatever the asker chose, an ask nobody takes up reaches a person.
1028
- if (row.waitingOn !== undefined)
1029
- yield* ctx.timers.set(routeTimer(row.askId), now + ctx.config.routedEscalationMs);
1030
- yield* ctx.attention.set(sessionId, askAttention(row));
1031
- yield* ctx.observe(sessionId);
1032
- return live
1033
- ? {
1034
- status: "waiting",
1035
- askId: row.askId,
1036
- until: now + window,
1037
- }
1038
- : { status: "parked", askId: row.askId };
1039
- })));
1124
+ yield* ctx.state.asks.put(row);
1125
+ if (row.expiry !== null)
1126
+ yield* ctx.timers.set(`ask:${row.askId}`, row.expiry.at);
1127
+ // Silence never escalates; only explicit action or evidence the sender is gone.
1128
+ if (row.waitingOn !== undefined)
1129
+ yield* ctx.timers.set(checkTimer(row.askId), now + ctx.config.senderCheckMs);
1130
+ yield* ctx.attention.set(sessionId, askAttention(row));
1131
+ yield* ctx.observe(sessionId);
1132
+ return live
1133
+ ? {
1134
+ status: "waiting",
1135
+ askId: row.askId,
1136
+ until: now + window,
1137
+ }
1138
+ : { status: "parked", askId: row.askId };
1139
+ });
1140
+ }),
1141
+ }));
1040
1142
  const result = created.status === "waiting"
1041
1143
  ? await waitForResponse(ctx, created.askId, created.until, invocation)
1042
1144
  : created;