@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.40

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 (81) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +51 -1
  3. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  4. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  5. package/dist/console/index.html +2 -2
  6. package/dist/email/account.d.ts +0 -1
  7. package/dist/email/account.js +3 -3
  8. package/dist/email/answer.d.ts +5 -0
  9. package/dist/email/answer.js +35 -0
  10. package/dist/email/mail.js +19 -26
  11. package/dist/email/names.d.ts +30 -0
  12. package/dist/email/names.js +34 -0
  13. package/dist/email/routes.d.ts +1 -0
  14. package/dist/email/routes.js +1 -1
  15. package/dist/email/tools.d.ts +11 -4
  16. package/dist/email/tools.js +91 -46
  17. package/dist/eval-mailbox.d.ts +1 -1
  18. package/dist/eval-mailbox.js +3 -3
  19. package/dist/learn/compile.d.ts +3 -2
  20. package/dist/learn/compile.js +6 -5
  21. package/dist/learn/promote.d.ts +25 -14
  22. package/dist/learn/promote.js +32 -14
  23. package/dist/learning-cost.d.ts +17 -8
  24. package/dist/learning-cost.js +12 -4
  25. package/dist/local-models.d.ts +7 -1
  26. package/dist/local-models.js +11 -5
  27. package/dist/openapi.d.ts +1 -1
  28. package/dist/openapi.js +17 -15
  29. package/dist/port-models.d.ts +4 -1
  30. package/dist/port-models.js +1 -0
  31. package/dist/refusal-words.d.ts +3 -0
  32. package/dist/refusal-words.js +3 -0
  33. package/dist/run-launch.d.ts +2 -0
  34. package/dist/run-launch.js +2 -0
  35. package/dist/run-view.d.ts +3 -4
  36. package/dist/run-view.js +26 -24
  37. package/dist/runner/adapter-loop.d.ts +6 -2
  38. package/dist/runner/adapter-loop.js +45 -12
  39. package/dist/runner/adapter-run-spec.d.ts +1 -0
  40. package/dist/runner/adapter-run-spec.js +37 -1
  41. package/dist/runner/cli-run-spec.js +1 -0
  42. package/dist/runner/journal-kinds.d.ts +22 -0
  43. package/dist/runner/journal-kinds.js +39 -0
  44. package/dist/runner/model-route.d.ts +3 -1
  45. package/dist/runner/model-route.js +18 -3
  46. package/dist/runner/promotion.d.ts +8 -8
  47. package/dist/runner/promotion.js +135 -54
  48. package/dist/server.js +15 -8
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/postgres/connection.d.ts +11 -5
  52. package/dist/store/postgres/connection.js +44 -17
  53. package/dist/store/postgres/dialect.js +5 -0
  54. package/dist/store/postgres/store.d.ts +7 -3
  55. package/dist/store/postgres/store.js +1 -0
  56. package/dist/store/sqlite/connection.js +72 -8
  57. package/dist/store/sqlite/run-launch.d.ts +11 -0
  58. package/dist/store/sqlite/run-launch.js +8 -0
  59. package/dist/store/sqlite/store.js +37 -16
  60. package/dist/store/sqlite/worker.d.ts +2 -0
  61. package/dist/store/sqlite/worker.js +13 -10
  62. package/dist/store/store.d.ts +15 -0
  63. package/dist/store-reads/learning.d.ts +30 -13
  64. package/dist/store-reads/learning.js +125 -51
  65. package/dist/template-eval.js +1 -1
  66. package/dist/templates.d.ts +14 -1
  67. package/dist/templates.js +67 -17
  68. package/dist/tool-gate.d.ts +5 -3
  69. package/dist/tool-gate.js +5 -2
  70. package/dist/tools.d.ts +13 -0
  71. package/dist/tools.js +15 -10
  72. package/dist/trigger-adapter.d.ts +3 -32
  73. package/dist/trigger-email.js +30 -77
  74. package/dist/triggers.d.ts +26 -14
  75. package/dist/triggers.js +99 -76
  76. package/dist/workflow/decision-recovery.js +5 -2
  77. package/dist/workflow/decisions.d.ts +7 -0
  78. package/package.json +9 -9
  79. package/templates/README.md +2 -2
  80. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  81. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -129,6 +129,8 @@ export declare function readLaunchBody(stored: unknown): RunLaunch | undefined;
129
129
  /** The run's learning start (its given notes, its seed sha and its # Learned section), read from one place by learning's
130
130
  * routes and the runner; undefined when the run does not learn. */
131
131
  export declare const learningStartOf: (launch: RunLaunch) => RunLaunch["learning"];
132
+ /** The same start read from a launch body's `learning` member alone (Store.runs.learningStarts), as readLaunchBody reads it. */
133
+ export declare const learningStartOfStored: (stored: unknown) => RunLaunch["learning"];
132
134
  /** Why a learning run starts with nothing learned, as main says it: its agent's learning folder could not be read
133
135
  * (`unreadable`, STOPPED.unreadable), or what was read could not be made into its start (`not_copied`,
134
136
  * STOPPED.notCopied). */
@@ -134,6 +134,8 @@ export function readLaunchBody(stored) {
134
134
  /** The run's learning start (its given notes, its seed sha and its # Learned section), read from one place by learning's
135
135
  * routes and the runner; undefined when the run does not learn. */
136
136
  export const learningStartOf = (launch) => launch.learning;
137
+ /** The same start read from a launch body's `learning` member alone (Store.runs.learningStarts), as readLaunchBody reads it. */
138
+ export const learningStartOfStored = (stored) => (stored === undefined ? undefined : readLearning(stored) ?? { given: [], seed: null, section: "" });
137
139
  const SEED_FAILURES = ["unreadable", "not_copied"];
138
140
  /** A learning start with no seed (no commit of main, runs-over-store.ts learningStartFor): the run learns nothing, is
139
141
  * never asked what to keep, and so is never told it learns. Why is its `seedFailed`, when its start records one. */
@@ -4,7 +4,6 @@ import { type RefusalFigures } from "./cap.js";
4
4
  import type { Turns } from "./turns.js";
5
5
  import type { PendingAsk } from "./browser-person.js";
6
6
  import { type ApprovalPrice, type PendingApproval } from "./tool-gate.js";
7
- import "./email/labels.js";
8
7
  import { type signInReads } from "./sign-ins-store.js";
9
8
  import { type CostWords } from "./runner/metrics.js";
10
9
  import type { CostParts } from "@parcha/agentrun-kernel";
@@ -459,9 +458,9 @@ export declare function outcomeShows(tool: string, answer: {
459
458
  /** The rows of a run whose calls waited for approval, as the runner writes it (store-view.ts): the gate's ask
460
459
  * (agentrun.ask, `asks`) and the person's answer (agentrun.answer, `answers`) are journal entries, and an allowed call runs
461
460
  * in place, so its result row is its real result; a denied one's is the refusal. Each such call reads in order: its call,
462
- * then the approval row at the ask's time, then its result, then, once there is one, the outcome row (before a result is
463
- * in, the approval row and any outcome follow its own rows); its own rows say only that it was held once the
464
- * outcome shows below, and before that what came of the approval so far. Arguments and notes go through `redact`, the
461
+ * then the approval row at the ask's time (above the rows written while it waited), then its result, then, once there
462
+ * is one, the outcome row (before a result is in, any outcome follows its own rows); its own rows say only that it was
463
+ * held once the outcome shows below, and before that what came of the approval so far. Arguments and notes go through `redact`, the
465
464
  * run's redactor, before any cut. The rows this function makes are dropped first, so a pass over its own output gives the
466
465
  * same rows. */
467
466
  export declare function withApprovalRows(rows: readonly TimelineEvent[], asks: ReadonlyMap<string, Approval>, answers: Readonly<Record<string, ApprovalAnswer>>, redact: (text: string) => string): TimelineEvent[];
package/dist/run-view.js CHANGED
@@ -9,10 +9,7 @@
9
9
  import { chargedTool, isMessageRow, NOTE_SUFFIX, registerLabel, registerTurnEnding, scrubUrls } from "./timeline/index.js";
10
10
  import { CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal } from "./cap.js";
11
11
  import { APPROVAL_ROW, previewOf } from "./tool-gate.js";
12
- import { ASK_TOOL } from "./tools.js";
13
- import { EMAIL_FILE, EMAIL_SEND, fileSummary, sendSummary } from "./email/names.js";
14
- // The email tools' timeline lines (registerLabel), registered as this module loads.
15
- import "./email/labels.js";
12
+ import { ASK_TOOL, toolOf } from "./tools.js";
16
13
  import { LEARNING_LABEL } from "./learning.js";
17
14
  import { builtinHarness } from "./harness-table.js";
18
15
  import { cutStrings, redacted, withoutLoopback } from "./key-refusal.js";
@@ -20,7 +17,7 @@ import { pointerHash } from "./sign-ins-store.js";
20
17
  import { MIN_SECRET } from "./learn/secrets.js";
21
18
  import { costWordsOf, usageParts } from "./runner/metrics.js";
22
19
  import { KINDS } from "./runner/journal-kinds.js";
23
- import { ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
20
+ import { ASKED_BECAUSE, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
24
21
  /** The run's newest usage row, which carries its cost. */
25
22
  const usageOf = (rows) => rows.findLast((r) => r.kind === "usage");
26
23
  /** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
@@ -366,14 +363,10 @@ export const pendingOf = (rows) => {
366
363
  return last?.kind === "waiting" ? { kind: "question", question: last.text ?? last.summary ?? "", asked_at: last.timestamp } : null;
367
364
  };
368
365
  /** The run's pending approval (`pending`, kind approval): the call that waits; else undefined. */
369
- /** The tools whose approval card says what the call does in words: email_send's to whom and what, email_file's which
370
- * message and where. */
371
- const SUMMARIES = { [EMAIL_SEND]: sendSummary, [EMAIL_FILE]: fileSummary };
372
- /** A call's approval summary, where its tool has one (SUMMARIES), redacted as its arguments are. */
366
+ /** A call's approval summary, where its tool has one (tools.ts ToolEntry.approvalSummary), then why it asks when its tool
367
+ * asked about it itself (the card's ASKED_BECAUSE, the gate's), redacted as its arguments are. */
373
368
  function summaryOf(approval, redact) {
374
- const summarize = Object.hasOwn(SUMMARIES, approval.tool) ? SUMMARIES[approval.tool] : undefined;
375
- if (!summarize)
376
- return {};
369
+ const summarize = toolOf(approval.tool)?.approvalSummary;
377
370
  let args;
378
371
  try {
379
372
  args = JSON.parse(approval.args_json);
@@ -381,8 +374,9 @@ function summaryOf(approval, redact) {
381
374
  catch {
382
375
  return {};
383
376
  }
384
- const summary = summarize(args);
385
- return summary === undefined ? {} : { summary: redact(summary) };
377
+ const because = typeof args === "object" && args !== null && typeof args[ASKED_BECAUSE] === "string" ? args[ASKED_BECAUSE] : undefined;
378
+ const parts = [summarize?.(args), because === undefined ? undefined : `Asks because ${because}.`].filter((part) => part !== undefined);
379
+ return parts.length ? { summary: redact(parts.join("\n\n")) } : {};
386
380
  }
387
381
  export const approvalOf = (run, redact) => {
388
382
  const waiting = waitingApproval(run);
@@ -650,9 +644,9 @@ const approvalRowId = (callId) => `approval:${callId}`;
650
644
  /** The rows of a run whose calls waited for approval, as the runner writes it (store-view.ts): the gate's ask
651
645
  * (agentrun.ask, `asks`) and the person's answer (agentrun.answer, `answers`) are journal entries, and an allowed call runs
652
646
  * in place, so its result row is its real result; a denied one's is the refusal. Each such call reads in order: its call,
653
- * then the approval row at the ask's time, then its result, then, once there is one, the outcome row (before a result is
654
- * in, the approval row and any outcome follow its own rows); its own rows say only that it was held once the
655
- * outcome shows below, and before that what came of the approval so far. Arguments and notes go through `redact`, the
647
+ * then the approval row at the ask's time (above the rows written while it waited), then its result, then, once there
648
+ * is one, the outcome row (before a result is in, any outcome follows its own rows); its own rows say only that it was
649
+ * held once the outcome shows below, and before that what came of the approval so far. Arguments and notes go through `redact`, the
656
650
  * run's redactor, before any cut. The rows this function makes are dropped first, so a pass over its own output gives the
657
651
  * same rows. */
658
652
  export function withApprovalRows(rows, asks, answers, redact) {
@@ -665,6 +659,11 @@ export function withApprovalRows(rows, asks, answers, redact) {
665
659
  for (const row of given)
666
660
  if (owns(row))
667
661
  lastOf.set(row.tool_use_id, row.id);
662
+ // The call's own row the approval row goes below: its call's (the last of its rows that is not its result).
663
+ const callOf = new Map();
664
+ for (const row of given)
665
+ if (owns(row) && row.kind !== "tool_result")
666
+ callOf.set(row.tool_use_id, row.id);
668
667
  // The result rows of the calls that waited: a Saved row read from such a call's write (pi's `<result>:saved:<n>`) says
669
668
  // a file was written that the park never wrote; an allowed call's file is its outcome row's to say, as on main.
670
669
  const waitedResults = new Set(given.filter((row) => row.kind === "tool_result" && owns(row)).map((row) => row.id));
@@ -687,22 +686,25 @@ export function withApprovalRows(rows, asks, answers, redact) {
687
686
  const own = ran ? (row.kind === "tool_result" && !row.summary?.endsWith(said) ? { ...row, summary: row.summary ? `${row.summary} ${said}` : said } : row)
688
687
  : answer?.decision === "deny" && answer.by === "setting" ? { ...row, summary: DENIED_SINCE }
689
688
  : { ...row, summary: outcome ? HELD : callSays(answer), tool_status: null };
690
- // The approval row sits above the call's result once there is one (the ask came before the call ran), else below its
691
- // last own row; the outcome rows below its last own row.
692
- const askHere = row.id === (result?.id ?? lastOf.get(approval.call_id));
689
+ // The approval row sits right below the call's own row, as the ask came at the call: above what came while it waited
690
+ // (a park's keep, a resume's computer ready again) and above its result. A call with only its result row has it above
691
+ // that. The outcome rows go below its last own row.
692
+ const call = callOf.get(approval.call_id);
693
+ const askHere = row.id === (call ?? result?.id);
693
694
  const last = lastOf.get(approval.call_id) === row.id;
694
695
  if (!askHere && !last)
695
696
  return [own];
696
697
  const args = shownArgs(approval, redact);
697
- // A served row keeps the place it was first served at (rows.ts). The approval row is served while the call waits, above
698
- // the result yet to come, so it keeps its id. The call's result comes in after the answer (the park writes none), so the
699
- // outcome rows take a new id once it is there: served anew below the result, as a person reads it.
698
+ // A served row keeps the place it was first served at (rows.ts). The approval row is served while the call waits, below
699
+ // its call's row, where it stays once the result is in, so it keeps its id. The call's result comes in after the
700
+ // answer (the park writes none), so the outcome rows take a new id once it is there: served anew below the result, as
701
+ // a person reads it.
700
702
  const at = result ? `${approvalRowId(approval.call_id)}:after` : approvalRowId(approval.call_id);
701
703
  const head = !answer ? "Waiting for your approval" : answer.decision === "canceled" ? "Withdrawn when the run was cancelled" : answer.decision === "withdrawn" ? (answer.ended ? "Withdrawn when the run ended" : "Withdrawn when the run was stopped") : answer.by === "message" ? "Declined by your message" : answer.by === "setting" ? (answer.decision === "deny" ? "Denied by the tool's setting on this server" : "Allowed by the tool's setting") : "Asked your approval";
702
704
  // Its time is the ask's (the gate's requestedAt), never the row it was made from.
703
705
  const when = approval.requested_at ? { timestamp: approval.requested_at, created_at: approval.requested_at } : {};
704
706
  const asked = { ...madeFrom(row), ...when, id: approvalRowId(approval.call_id), kind: APPROVAL_ROW, summary: `${head}: ${approval.tool} ${clip(args, 400)}`, text: args, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null };
705
- const placed = !askHere ? [own] : result ? [asked, own] : [own, asked];
707
+ const placed = !askHere ? [own] : row.id === call ? [own, asked] : [asked, own];
706
708
  if (!last || !outcome)
707
709
  return placed;
708
710
  const failed = answer.decision === "allow" && result?.tool_status === "failed";
@@ -1,7 +1,7 @@
1
1
  import { type ConversationId, type ConversationRetryPolicy, type ConversationStreamOptions, Harness, type Tx } from "@earendil-works/pi-durable";
2
2
  import { type AgentAdapter, type Refusal, type SessionRecord, type SessionSpec } from "@parcha/agentrun-kernel";
3
3
  import type { KernelHooks, ToolCall } from "./conformance/subject.js";
4
- import { type BudgetData, type EndData } from "./journal-kinds.js";
4
+ import { type BudgetData, type EndData, type ToolCalls } from "./journal-kinds.js";
5
5
  import { type MessageOrigin } from "../timeline/index.js";
6
6
  type EndCost = Required<Pick<EndData, "costUsd" | "costUpperBound">>;
7
7
  import { type Claim, type EndOfRunTurn, type LoopFactory } from "./loop-contract.js";
@@ -65,8 +65,11 @@ export type GateAnswer = "allow" | "ask" | "deny" | {
65
65
  /** The gate before a call's intent; `askedAs`, when it has one, names a call as a person is asked about it (its settings
66
66
  * key, as main's pending approval names it), else the call is asked about by its own name. `replayed`: asked again for a
67
67
  * call run again after an earlier attempt that may have been sent, so a refusal's words never say nothing was sent. */
68
+ /** `ran`: the calls of a tool the run's journal shows (toolCalls: run to a good end, and every one with a result), read
69
+ * now (a tool's own ask counts by it, with the calls its gate let through that have no result yet). */
68
70
  export type SpecGate = ((call: ToolCall, options?: {
69
71
  readonly replayed?: boolean;
72
+ readonly ran?: (tool: string) => Promise<ToolCalls>;
70
73
  }) => GateAnswer | Promise<GateAnswer>) & {
71
74
  readonly askedAs?: (tool: string, args?: unknown) => string;
72
75
  /** A tool's setting now, by any name a call reaches the gate by (a harness's own, Codex's `web_search`), read again at
@@ -322,7 +325,8 @@ export interface AdapterLoopOptions {
322
325
  /** The gate's clock (epoch ms): when an ask was asked and answered, and when a wait in the claim on the person's answer
323
326
  * started. Default Date.now. */
324
327
  readonly now?: () => number;
325
- /** For tests: awaited as a wait in the claim on the person's answer starts, before it takes their messages. */
328
+ /** For tests: awaited once a turn ended on its question to the person, before the wait in the claim (or the park, with
329
+ * nothing to hold open) takes their messages. */
326
330
  readonly beforePersonWait?: () => Promise<void>;
327
331
  }
328
332
  /** A paid call's refusal an earlier claim kept (KINDS.pausePending) whose pause never landed: the newest one with no
@@ -2,7 +2,7 @@ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/conte
2
2
  import { createModels } from "@earendil-works/pi-ai/models";
3
3
  import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID, ToolTask } from "@earendil-works/pi-durable";
4
4
  import { modelPortFor, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
5
- import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
5
+ import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, toolCalls, withdrawnAnswers } from "./journal-kinds.js";
6
6
  import { turnEndedOnAsk } from "../store-reads/journal.js";
7
7
  import { CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
8
8
  import { raiseFollowUpId } from "../run-view.js";
@@ -27,10 +27,10 @@ const outputRetried = (entries) => {
27
27
  return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
28
  };
29
29
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
30
- import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
30
+ import { ASKED_BECAUSE, deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
31
31
  import { ADAPTER_API } from "../turn-end.js";
32
32
  import { answerText, REFLECT_NOTE_ONLY, REFLECT_PREFIX, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
33
- import { approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
33
+ import { agentEntriesOf, approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
34
34
  import { outputMiss, outputRetryWords } from "../answer-json.js";
35
35
  import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
36
36
  import { isComputerCommand, journalHold } from "./computer-journal.js";
@@ -62,11 +62,12 @@ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool
62
62
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
63
63
  /** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
64
64
  * still names them whatever the input's size, then the call's input, which the model wrote, without any field of
65
- * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's. */
65
+ * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's, and so is the reason a
66
+ * call its setting allows asks anyway (ASKED_BECAUSE). */
66
67
  function cardOf(tool, shown, args) {
67
- if (!shown && tool !== LEARNED_WORKFLOW_TOOL)
68
+ if (!shown && tool !== LEARNED_WORKFLOW_TOOL && !(args && Object.hasOwn(args, ASKED_BECAUSE)))
68
69
  return args;
69
- return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
70
+ return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && key !== ASKED_BECAUSE && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
70
71
  }
71
72
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
72
73
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
@@ -667,6 +668,16 @@ function adapterLoop(specOf, options, deps) {
667
668
  /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
668
669
  * during the end-of-run turn does. */
669
670
  let turnsOver = false;
671
+ /** Set, synchronously, once the claim has decided to park on its question (no wait in the claim holds, or the wait
672
+ * lapsed): from here to the park's seal (its host's release can take a while), a person's message is left untaken for
673
+ * the resume. Placed now, it would start a turn the seal then cuts, its row taken and the run parked with nothing to
674
+ * wake it, the message lost. */
675
+ let askParking = false;
676
+ /** The claim parks on its question: no message is placed from here (askParking). */
677
+ const parkingOnAsk = () => {
678
+ askParking = true;
679
+ return undefined;
680
+ };
670
681
  /** While the run's learned workflow runs first (AdapterRunSpec.workflowFirst): a message waits for it, then goes the way
671
682
  * any message goes once the workflow answered (the run is ending) or handed the job back (the agent's turn runs). */
672
683
  let servingFirst;
@@ -994,7 +1005,7 @@ function adapterLoop(specOf, options, deps) {
994
1005
  };
995
1006
  /** A person's message placed (steer): as the run's next turn, into the turn in flight, or after it. */
996
1007
  const placeSteer = async (command) => {
997
- if (!gate || !session || gate.sealed)
1008
+ if (!gate || !session || gate.sealed || askParking)
998
1009
  return { later: "the run is parking: the steer waits for its resume" };
999
1010
  // The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
1000
1011
  // the message would be the session's first prompt and the input would follow it; it waits for the input instead, then
@@ -1032,6 +1043,9 @@ function adapterLoop(specOf, options, deps) {
1032
1043
  const servedAnswer = reopen && !reopen.sent && session.state === "new" && root !== undefined ? servedAnswerOf(await entriesOf(gate.journal, root.id, context)) : undefined;
1033
1044
  if (!gate || !session || gate.sealed)
1034
1045
  return { later: "the run is parking: the steer waits for its resume" };
1046
+ // The claim parks on its question (askParking), its seal still to come: the message is the resume's answer.
1047
+ if (askParking)
1048
+ return { later: "the run is parking on its question: the message answers it on the resume" };
1035
1049
  // A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
1036
1050
  // between the question's turn end and that wait): never the wait's answer, never placed now. Its firing reads sent (the
1037
1051
  // door took the row), so it is never refused either: left untaken, it runs as a turn of its own after the person's
@@ -2900,7 +2914,7 @@ function adapterLoop(specOf, options, deps) {
2900
2914
  return { deny: wrapUpDeny };
2901
2915
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
2902
2916
  const replayed = call.replayed === true;
2903
- const given = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
2917
+ const given = (await spec.gate?.(kernelCall, { ...(replayed ? { replayed } : {}), ran: ranOf })) ?? "allow";
2904
2918
  // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
2905
2919
  const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
2906
2920
  let decision = shown ? "ask" : given;
@@ -3085,6 +3099,12 @@ function adapterLoop(specOf, options, deps) {
3085
3099
  * end reads withdrawn: its rows said "Not run: the run ended while it waited" of a call that ran. A deny set since still
3086
3100
  * refuses it first. Read from the journal once a claim: an ask written later in the claim parks it, and an answer
3087
3101
  * written later is read by answerOf itself. */
3102
+ /** The calls of `tool` the run's journal shows now (toolCalls): run to a good end, and every one with a result. Read
3103
+ * over every agent conversation of the run (agentEntriesOf): the root's and each subagent's, so a child's calls count
3104
+ * on the claim after a pause as on the one they ran in. */
3105
+ async function ranOf(tool) {
3106
+ return toolCalls(await agentEntriesOf(gate.journal, context), tool);
3107
+ }
3088
3108
  async function askStands(callId) {
3089
3109
  standing ??= (async () => {
3090
3110
  const conversation = await harness.root(context);
@@ -3177,6 +3197,7 @@ function adapterLoop(specOf, options, deps) {
3177
3197
  * the run's next user message and resumes it on the next claim, as on main: the ask_person tool result stays what pi
3178
3198
  * wrote, so nothing is re-asked or re-billed. The summary is plain words, never the question. */
3179
3199
  async function parkOnAsk(on, conversation, theGate, callId) {
3200
+ parkingOnAsk();
3180
3201
  const parkedAt = theGate.expect(writesEntry(KINDS.personAsked, (entry) => entry.callId === callId), { run: { state: "parked", summary: ASK_PERSON_WAITING } });
3181
3202
  parkedAt.catch(() => undefined);
3182
3203
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
@@ -3263,9 +3284,18 @@ function adapterLoop(specOf, options, deps) {
3263
3284
  * or the session went), and the run parks on its question. Undefined when no host holds anything: the run parks. */
3264
3285
  async function waitInClaim(on, callId) {
3265
3286
  const holders = specNow?.lifecycle?.personWait ?? [];
3266
- if (!holders.length || !session || !gate || gate.sealed || !root)
3267
- return undefined;
3268
3287
  await options.beforePersonWait?.();
3288
+ if (!session || !gate || gate.sealed || !root)
3289
+ return parkingOnAsk();
3290
+ if (!holders.length) {
3291
+ // Nothing to hold open: the run parks, unless the answer already came, between the question's turn end and here,
3292
+ // placed as a steer of the idle session (steer): then its turn is the next, at once, never cut by the park's seal.
3293
+ const early = idleSteer;
3294
+ idleSteer = undefined;
3295
+ if (early && (await early.placed))
3296
+ return { next: turnOfRequest(on, root, early.requestId) };
3297
+ return parkingOnAsk();
3298
+ }
3269
3299
  // Set before anything else: an answer sent from here is the claim's next turn, never a steer into no turn.
3270
3300
  const [theSession, theGate, conversation] = [session, gate, root];
3271
3301
  const mine = {};
@@ -3299,7 +3329,7 @@ function adapterLoop(specOf, options, deps) {
3299
3329
  // Nothing held, and no answer placed meanwhile: the run parks.
3300
3330
  if (!waitHolds.length && !mine.sent) {
3301
3331
  endWait(mine);
3302
- return undefined;
3332
+ return parkingOnAsk();
3303
3333
  }
3304
3334
  // The wait's start, once, in the journal, with the row's waiting summary (the server tells run.needs_input by it).
3305
3335
  if (!marked && !mine.sent) {
@@ -3315,9 +3345,12 @@ function adapterLoop(specOf, options, deps) {
3315
3345
  if (done)
3316
3346
  return;
3317
3347
  done = true;
3318
- if (value === "lapsed")
3348
+ if (value === "lapsed") {
3319
3349
  for (const hold of waitHolds)
3320
3350
  hold.confirmed?.();
3351
+ // The run parks on its question (the turn loop's "lapsed"): the person's next message is the resume's.
3352
+ parkingOnAsk();
3353
+ }
3321
3354
  endWait(mine);
3322
3355
  resolve(value);
3323
3356
  };
@@ -208,6 +208,7 @@ export declare function adapterRunGate(store: Pick<Store, "settings">, claim: Pi
208
208
  }): Promise<NonNullable<AdapterRunSpec["gate"]> & {
209
209
  readonly permissions: RunPermissions;
210
210
  readonly learn: (flows: readonly LearnedWorkflow[]) => void;
211
+ readonly askedOn: (host: ToolHost) => void;
211
212
  }>;
212
213
  /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
213
214
  * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
@@ -9,6 +9,7 @@ import { llmTiers, nodeTiers, thinkingLevel, TIERS, tierModelOf, workflowNodes }
9
9
  import { firstMessage, inputMessage, messageText } from "../run-manifest.js";
10
10
  import { learningStartOf, seedFailed } from "../run-launch.js";
11
11
  import { isWebHostTool } from "../tool-list.js";
12
+ import { ASKED_BECAUSE } from "../refusal-words.js";
12
13
  import { deniedText, noApproverText, runGate } from "../tool-gate.js";
13
14
  import { DECISION_PROVIDER_KEYS, loadToolSettings, recheckPlane, TOOL_PLANE_ENV } from "../tool-plane.js";
14
15
  import { readApprovers } from "../server-approvers.js";
@@ -118,9 +119,43 @@ export async function adapterRunGate(store, claim, revision, root, shell, option
118
119
  const gate = runGate({ ...where, ...(shell === undefined ? {} : { computer: shell === "computer" }) }, claim.runId, revision, () => current, approvers);
119
120
  // The run's learned workflows, once its spec has read them (learn): a learned_workflow call is asked about its MCP nodes.
120
121
  let learned = [];
122
+ // The host the run's tools bind through, once the spec has made it (askedOn): a tool's own ask reads it.
123
+ let host;
124
+ // A tool's own ask counts its calls (AskContext.ran): the journal's, run to a good end, and the calls of it this gate let
125
+ // through in this claim that have no result yet (reserved, by tool), so calls made at once never all read the same
126
+ // count. Its calls are asked about one at a time (asking, a chain by tool): the count read and the reservation with
127
+ // nothing between. A reserved call whose result is in the journal leaves it: counted there, or its slot freed (an
128
+ // error, a deny). A new claim's gate starts with none: what finished is the journal's.
129
+ const reserved = new Map();
130
+ const asking = new Map();
131
+ const counted = (ran) => async (tool) => {
132
+ const calls = await ran(tool);
133
+ const held = reserved.get(tool);
134
+ for (const id of held ?? [])
135
+ if (calls.ran.has(id) || calls.ended.has(id))
136
+ held.delete(id);
137
+ return calls.ran.size + calls.unnamed + (held?.size ?? 0);
138
+ };
139
+ const askedOne = (call, asks, made, ran) => {
140
+ const turn = (asking.get(call.tool) ?? Promise.resolve()).then(async () => {
141
+ const because = await asks((call.args ?? {}), { host: made, ran: counted(ran) });
142
+ if (because === undefined && call.callId)
143
+ reserved.set(call.tool, (reserved.get(call.tool) ?? new Set()).add(call.callId));
144
+ return because;
145
+ });
146
+ asking.set(call.tool, turn.catch(() => undefined));
147
+ return turn;
148
+ };
121
149
  const decide = async (call, options = {}) => {
122
150
  current = await storeSettings(store);
123
151
  const decision = await gate.decide(call.tool, call.args, options);
152
+ // A call its setting allows that its tool asks about itself (ToolEntry.asks: email_send past its cap, or to someone
153
+ // outside the run's thread): put to a person with the tool's reason on its card, whatever the setting; where no one
154
+ // can approve, refused in those words. No tool's name is read here: the reason is the tool's.
155
+ const asksOf = decision === "allow" && host && options.ran ? toolOf(call.tool)?.asks : undefined;
156
+ const because = asksOf ? await askedOne(call, asksOf, host, options.ran) : undefined;
157
+ if (because !== undefined)
158
+ return approvers ? { ask: { [ASKED_BECAUSE]: because } } : { deny: noApproverText(gate.askedAs(call.tool, call.args), options.replayed ? "unknown" : "no", because) };
124
159
  // A learned workflow's MCP nodes are the run's own MCP calls, held to the same settings: one set to deny refuses the
125
160
  // whole call in the gate's words before any node runs, nothing sent; the actions set to ask are put to a person on the
126
161
  // call's one card, up front, each with its arguments' shape (learnedAskShown), and the person's allow passes the
@@ -155,7 +190,7 @@ export async function adapterRunGate(store, claim, revision, root, shell, option
155
190
  current = await storeSettings(store);
156
191
  return current.unreadable ? "deny" : gate.policy(tool);
157
192
  };
158
- return Object.assign(decide, { askedAs: (tool, args) => gate.askedAs(tool, args), permissions, permission, learn: (flows) => void (learned = flows) });
193
+ return Object.assign(decide, { askedAs: (tool, args) => gate.askedAs(tool, args), permissions, permission, learn: (flows) => void (learned = flows), askedOn: (made) => void (host = made) });
159
194
  }
160
195
  /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
161
196
  * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
@@ -461,6 +496,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
461
496
  const claimBrowser = computer.computer?.kind === "browser" ? computer.computer.browser : undefined;
462
497
  const fakes = deps.evalFakes?.(runRow.agentId);
463
498
  const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
499
+ gate.askedOn(host);
464
500
  // The run's tools. The hands (read/write/edit/bash and the background tools) are the kernel registry's over the run's
465
501
  // Workspace and computer (runTools.hostTools); the gate is the adapter loop's own (spec.gate), so they run as asked.
466
502
  const results = new Map();
@@ -578,6 +578,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
578
578
  if (webNames.length) {
579
579
  life = hostLifecycle();
580
580
  const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) });
581
+ gate.askedOn(host);
581
582
  webTools = await webHostTools(host, granted, ctx);
582
583
  }
583
584
  if (learns) {
@@ -289,6 +289,28 @@ export interface AnswerData {
289
289
  readonly answeredAt?: string;
290
290
  };
291
291
  }
292
+ /** The calls of a tool a run's journal shows (toolCalls): `ran`, the ids run to a good end, and `unnamed`, those pi
293
+ * recorded with no id; `ended`, every id with a result of any kind (done, an error, a refusal or a deny). */
294
+ export type ToolCalls = {
295
+ readonly ran: ReadonlySet<string>;
296
+ readonly unnamed: number;
297
+ readonly ended: ReadonlySet<string>;
298
+ };
299
+ /** The calls of `tool` `entries` show: a CLI's (agentrun.call.start and its end) and pi's (a pi.tool-result of it), each
300
+ * call id once, however many records say it. Run to a good end: a CLI's end done, a pi result that is no error. */
301
+ export declare function toolCalls(entries: readonly {
302
+ readonly kind: string;
303
+ readonly data?: unknown;
304
+ readonly model?: unknown;
305
+ }[], tool: string): ToolCalls;
306
+ /** How many calls of `tool` `entries` show run to a good end (toolCalls): a call refused, denied, failed or not ended is
307
+ * not counted. What a tool's own ask counts (tools.ts AskContext.ran), with the calls its gate let through and that
308
+ * have no result yet (adapterRunGate). */
309
+ export declare function ranCalls(entries: readonly {
310
+ readonly kind: string;
311
+ readonly data?: unknown;
312
+ readonly model?: unknown;
313
+ }[], tool: string): number;
292
314
  /** The withdrawn answers a stopped end writes in `entries`: for every call still waiting (an ask with no answer), and
293
315
  * for every approved call that had not finished (no result, or one its abort wrote), which the stop overrides, keeping
294
316
  * the allow it was given (main's supersede: an answer the run had not acted on to the end is withdrawn by the stop). A
@@ -147,6 +147,45 @@ export function endedAnswer(tool, end) {
147
147
  const text = typeof end.output === "string" ? end.output : end.status === "interrupted" ? INTERRUPTED_TEXT : `The ${tool} call ended ${end.status}.`;
148
148
  return { text, isError: end.status !== "done" };
149
149
  }
150
+ /** The calls of `tool` `entries` show: a CLI's (agentrun.call.start and its end) and pi's (a pi.tool-result of it), each
151
+ * call id once, however many records say it. Run to a good end: a CLI's end done, a pi result that is no error. */
152
+ export function toolCalls(entries, tool) {
153
+ const started = new Set();
154
+ const ran = new Set();
155
+ const ended = new Set();
156
+ let unnamed = 0;
157
+ for (const entry of entries) {
158
+ if (entry.kind === KINDS.callStart && entry.data.tool === tool)
159
+ started.add(entry.data.callId);
160
+ else if (entry.kind === KINDS.callEnd && started.has(entry.data.callId)) {
161
+ ended.add(entry.data.callId);
162
+ if (entry.data.status === "done")
163
+ ran.add(entry.data.callId);
164
+ }
165
+ else if (entry.kind === "pi.tool-result") {
166
+ const result = entry.model?.[0];
167
+ if (result?.toolName !== tool)
168
+ continue;
169
+ const id = typeof result.toolCallId === "string" && result.toolCallId ? result.toolCallId : undefined;
170
+ if (id)
171
+ ended.add(id);
172
+ if (result.isError === true)
173
+ continue;
174
+ if (id)
175
+ ran.add(id);
176
+ else
177
+ unnamed++;
178
+ }
179
+ }
180
+ return { ran, unnamed, ended };
181
+ }
182
+ /** How many calls of `tool` `entries` show run to a good end (toolCalls): a call refused, denied, failed or not ended is
183
+ * not counted. What a tool's own ask counts (tools.ts AskContext.ran), with the calls its gate let through and that
184
+ * have no result yet (adapterRunGate). */
185
+ export function ranCalls(entries, tool) {
186
+ const calls = toolCalls(entries, tool);
187
+ return calls.ran.size + calls.unnamed;
188
+ }
150
189
  /** Whether `entries` hold a call's finished result: an agentrun.call.end not cut (a CLI's call), or a pi.tool-result
151
190
  * for it that pi did not write for an abort (pi's diagnostics code `aborted`). */
152
191
  function finished(entries, callId) {
@@ -49,7 +49,8 @@ export interface ModelRoute {
49
49
  * takes images) and its input limits (an image's most size), which pi's session and its read size an image by; on a
50
50
  * wire that carries its reasoning (Responses), also whether it reasons, its window, its output ceiling, and the effort
51
51
  * each thinking level asks for (`thinkingLevelMap`: a level mapped to null sends no effort, so pi's thinking off asks
52
- * a model that takes no "none" for none, gpt-6.1-sol's case). */
52
+ * a model that takes no "none" for none, gpt-6.1-sol's case). On the route's own translation, a model that reasons
53
+ * asks its level by name (LEVELS_BY_NAME: `adaptiveThinking`), so the run's effort reaches it. */
53
54
  readonly like?: {
54
55
  readonly reasoning?: boolean;
55
56
  readonly contextWindow?: number;
@@ -57,6 +58,7 @@ export interface ModelRoute {
57
58
  readonly input?: readonly string[];
58
59
  readonly inputLimits?: unknown;
59
60
  readonly developerRole?: boolean;
61
+ readonly adaptiveThinking?: boolean;
60
62
  readonly thinkingLevelMap?: ThinkingLevelMap;
61
63
  };
62
64
  /** A request's price from its usage (the proxy's booking reads it): pi-ai's calculateCost, tiers included. */
@@ -73,8 +73,10 @@ export async function routeOf(model, env = process.env, tier = "default", wires
73
73
  };
74
74
  }
75
75
  // The translation writes an answer's cost in its usage only where pi-ai read the provider's own (OpenRouter's): the
76
- // proxy reads it on ROUTE_ORIGIN (statesUsageCost).
77
- return { ...route, provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
76
+ // proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
77
+ // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
78
+ // model, mapped and clamped by its own catalog entry.
79
+ return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
78
80
  }
79
81
  /** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
80
82
  const OPENROUTER_HOST = "openrouter.ai";
@@ -126,7 +128,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
126
128
  // On OpenRouter, each answer's end is kept as it streams by, for a rate limit it ends in (limitedWords).
127
129
  const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
128
130
  const sendWith = tap?.fetch ?? upstream;
129
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
131
+ const level = levelOf(body);
132
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
130
133
  const events = models.streamSimple(target, context, streamOptions);
131
134
  const encoder = new TextEncoder();
132
135
  const stream = new ReadableStream({
@@ -377,6 +380,18 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
377
380
  }
378
381
  /** pi-ai's stop reason as Messages says it. */
379
382
  const stopReasonOf = (reason) => (reason === "toolUse" ? "tool_use" : reason === "length" ? "max_tokens" : "end_turn");
383
+ /** pi-ai's thinking levels past off, each asked by its own name. */
384
+ const NAMED_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
385
+ /** How the route's translation has pi's session register a model that reasons: on Messages, with adaptive thinking whose
386
+ * effort is the level's own name (a thinkingLevelMap of each level to itself), so a request carries the session's level
387
+ * as it is, `output_config.effort`, and no budget the translation would have to read a level back from. Off maps to
388
+ * nothing: a session at off sends thinking disabled, and no level reaches the model. */
389
+ const LEVELS_BY_NAME = { reasoning: true, adaptiveThinking: true, thinkingLevelMap: Object.fromEntries(NAMED_LEVELS.map((level) => [level, level])) };
390
+ /** The thinking level a Messages request from pi's session asks (LEVELS_BY_NAME), else undefined: none asked, or off. */
391
+ function levelOf(body) {
392
+ const effort = body.output_config?.effort;
393
+ return body.thinking?.type === "adaptive" && NAMED_LEVELS.includes(effort) ? effort : undefined;
394
+ }
380
395
  const textOf = (content) => (typeof content === "string" ? content : (content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n"));
381
396
  /** A Messages block as pi-ai's part: a text as text, a base64 image as an image; anything else none. */
382
397
  const partOf = (block) => block.type === "text" ? [{ type: "text", text: block.text ?? "" }] : block.type === "image" && block.source?.data ? [{ type: "image", data: block.source.data, mimeType: block.source.media_type ?? "image/png" }] : [];