@gravity-rail/cli 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -33,7 +33,7 @@ import {
33
33
  startAccountPhoneVerify,
34
34
  stderr,
35
35
  unwrapItems
36
- } from "./chunk-JRFAKSL3.js";
36
+ } from "./chunk-GQB43YPD.js";
37
37
  import {
38
38
  AGUIClient,
39
39
  formatTimestamp,
@@ -42,7 +42,7 @@ import {
42
42
  isRecord,
43
43
  performOAuthFlow,
44
44
  selectFromList
45
- } from "./chunk-3KKC4CY7.js";
45
+ } from "./chunk-RMZJJR2T.js";
46
46
  import {
47
47
  AuthRequiredError,
48
48
  CLIError,
@@ -414,7 +414,14 @@ function formatOutboundCallFailure(call, memberId) {
414
414
  function isLikelySeedPhoneNumber(phone) {
415
415
  return SEED_PHONE_PATTERN.test(phone);
416
416
  }
417
+ function describeOutboundCallReceipt(receipt) {
418
+ if (!receipt) return "";
419
+ return `queued (intent ${receipt.intentUuid}, ${receipt.intentState})`;
420
+ }
417
421
  async function waitForOutboundPhoneCallOutcome(client3, workspaceUuid, chatId, memberId, options) {
422
+ if (options?.receipt?.status === "queued") {
423
+ return options.receipt;
424
+ }
418
425
  const timeoutMs = options?.timeoutMs ?? 2e4;
419
426
  const intervalMs = options?.intervalMs ?? 500;
420
427
  const deadline = Date.now() + timeoutMs;
@@ -1479,6 +1486,13 @@ var COLUMNS2 = [
1479
1486
  { header: "CHANNEL", getValue: (item) => item.channel ?? "" },
1480
1487
  COL.created()
1481
1488
  ];
1489
+ var CREATE_COLUMNS = [
1490
+ ...COLUMNS2,
1491
+ {
1492
+ header: "OUTBOUND_CALL",
1493
+ getValue: (item) => describeOutboundCallReceipt(item.outboundCallReceipt)
1494
+ }
1495
+ ];
1482
1496
  var LABEL_COLUMNS = [
1483
1497
  COL.id(),
1484
1498
  COL.uuid(),
@@ -1630,7 +1644,7 @@ var chatsDomain = {
1630
1644
  entityName: "chat",
1631
1645
  listMethod: "getChats",
1632
1646
  // getMethod omitted — the custom get below takes --id or --uuid
1633
- createMethod: "createChat",
1647
+ // createMethod omitted — the custom create below shows the call receipt
1634
1648
  updateMethod: "updateChat",
1635
1649
  deleteMethod: "deleteChat",
1636
1650
  archiveMethod: "archiveChat",
@@ -1638,8 +1652,23 @@ var chatsDomain = {
1638
1652
  columns: COLUMNS2,
1639
1653
  paginationSupport: "full",
1640
1654
  listArgs: [
1641
- { name: "search", description: "Search by name" },
1655
+ {
1656
+ name: "search",
1657
+ description: "Search chat titles, summaries, message content, participant names, emails and phone numbers"
1658
+ },
1642
1659
  { name: "channel", description: "Filter by channel (phone, sms, web, email)" },
1660
+ {
1661
+ name: "workflow-id",
1662
+ description: "Only chats whose assignment pins any revision of this workflow"
1663
+ },
1664
+ {
1665
+ name: "created-after",
1666
+ description: "Only chats created on or after this ISO-8601 timestamp"
1667
+ },
1668
+ {
1669
+ name: "created-before",
1670
+ description: "Only chats created on or before this ISO-8601 timestamp"
1671
+ },
1643
1672
  {
1644
1673
  name: "is-anonymous",
1645
1674
  description: "Show only anonymous chats (requires CHATS_ADMIN)",
@@ -1653,6 +1682,21 @@ var chatsDomain = {
1653
1682
  }
1654
1683
  ]
1655
1684
  }),
1685
+ {
1686
+ path: ["chats", "create"],
1687
+ description: "Create a chat",
1688
+ mutates: true,
1689
+ requiresWorkspace: true,
1690
+ examples: [
1691
+ `gr chats create -w $WORKSPACE_UUID --data '{"channel":"phone-voice","workflowId":12,"memberId":34}' --allow-write`
1692
+ ],
1693
+ handler: async ({ ctx, workspace, data }) => {
1694
+ if (!data) throw new CLIError("JSON data required (--data, --file, or stdin)");
1695
+ const client3 = requireAuth(ctx).apiClient;
1696
+ const chat = await client3.createChat(workspace, data);
1697
+ outputSingle(chat, ctx, CREATE_COLUMNS);
1698
+ }
1699
+ },
1656
1700
  {
1657
1701
  path: ["chats", "get"],
1658
1702
  description: "Get a chat by ID or UUID",
@@ -3204,6 +3248,12 @@ Assistant / models (live on the DRAFT revision \u2014 publish to go live)
3204
3248
  "voiceModel":"xai:voice:ara"}}
3205
3249
  realtimeModelConfig (object|null) Realtime config. Omit on update to keep the
3206
3250
  stored config. null replaces it.
3251
+ enableVoicemailDetection (bool|null) Wait for a voicemail greeting to end on
3252
+ outbound calls (adds 3-5 s on a human
3253
+ pickup). null inherits the workspace
3254
+ phone setting. Omit on update to keep
3255
+ the stored choice; null resets it to
3256
+ inherit.
3207
3257
  copyFromAgentId (number) Copy full assistant settings from an agent
3208
3258
  copyFromWorkflowRevisionId (number) Copy assistant settings from a revision
3209
3259
 
@@ -6424,11 +6474,12 @@ var ACTION_PARAM_HINTS = {
6424
6474
  ]
6425
6475
  },
6426
6476
  "webhook:send": {
6427
- summary: "POST the event payload to a URL",
6477
+ summary: "legacy: existing rules only \u2014 POST the event payload to a URL",
6428
6478
  shape: ['{"webhookUrl":"https://example.com/hook"}'],
6429
6479
  notes: [
6430
- "webhookUrl is required and must be https in production.",
6431
- "signingSecret is generated for you when omitted on create; an update that omits it keeps the stored secret."
6480
+ "New webhook:send rules are refused; set up new integrations under Organization \u2192 Webhooks.",
6481
+ "This shape is for updating an existing rule: webhookUrl must be https in production,",
6482
+ "and an update that omits signingSecret keeps the stored secret."
6432
6483
  ]
6433
6484
  },
6434
6485
  "assistant:message": {
@@ -6481,7 +6532,7 @@ Field reference for --data JSON (create/update):
6481
6532
  Required
6482
6533
  objectType (string) task | routine | journey | workflow | calendar | ...
6483
6534
  eventType (string) e.g. routine:triggered, journey_step:execute, chat:created
6484
- actionType (string) e.g. chat:create, member:label, sms:send, webhook:send
6535
+ actionType (string) e.g. chat:create, member:label, sms:send, email:send
6485
6536
 
6486
6537
  Common optional
6487
6538
  name (string)
@@ -6737,8 +6788,11 @@ ${EVENT_RULE_FIELD_REFERENCE}`,
6737
6788
  "Common eventTypes: journey_step:execute, journey:enrolled, routine:triggered,",
6738
6789
  " task:created, chat:created, data_record:created, member:created",
6739
6790
  "",
6740
- "Common actionTypes: member:label, member:notify, webhook:send, email:send,",
6741
- " sms:send, chat:create, member:upsert",
6791
+ "Common actionTypes: member:label, member:notify, email:send, sms:send,",
6792
+ " chat:create, member:upsert",
6793
+ "",
6794
+ "New webhook:send rules are refused: set up outbound webhooks under",
6795
+ "Organization \u2192 Webhooks. Existing webhook:send rules can still be updated or disabled.",
6742
6796
  "",
6743
6797
  'member:label actionParams: {"addLabelIds":["uuid"],"removeLabelIds":["uuid"]}'
6744
6798
  ]
@@ -6844,8 +6898,8 @@ var createRoutineRuleCmd = {
6844
6898
  { name: "delay", description: "Seconds to wait before running the action (default: 0)" }
6845
6899
  ],
6846
6900
  examples: [
6847
- "Trigger: routine:triggered. Common actions: chat:create, webhook:send,",
6848
- "email:send, member:notify.",
6901
+ "Trigger: routine:triggered. Common actions: chat:create, email:send,",
6902
+ "member:notify.",
6849
6903
  "",
6850
6904
  "Scheduled outbound voice check-in:",
6851
6905
  "gr events rules create-routine-rule -w $WID --allow-write \\",
@@ -6853,12 +6907,12 @@ var createRoutineRuleCmd = {
6853
6907
  ' --workflow-uuid "$(gr workflows get --id 3 -w $WID --jq .uuid)" \\',
6854
6908
  ` --action-params '{"channel":"phone-voice","phoneNumberUUID":"<uuid>"}'`,
6855
6909
  "",
6856
- "Webhook on every fire, only for high-priority members:",
6910
+ "Notify the member on every fire, only for high-priority members:",
6857
6911
  "gr events rules create-routine-rule -w $WID --allow-write \\",
6858
- " --routine-id 12 --action-type webhook:send \\",
6859
- ` --action-params '{"webhookUrl":"https://example.com/hook"}' \\`,
6912
+ " --routine-id 12 --action-type member:notify \\",
6913
+ ` --action-params '{"recipientMode":"target_member","messageTemplate":"Time for your check-in."}' \\`,
6860
6914
  ` --conditions 'member.labels.exists(l, l == "priority")'`,
6861
- ...actionParamExampleLines(["chat:create", "webhook:send", "email:send", "member:notify"]),
6915
+ ...actionParamExampleLines(["chat:create", "email:send", "member:notify"]),
6862
6916
  ...VERIFY_EXAMPLE_LINES
6863
6917
  ],
6864
6918
  handler: async (hctx) => {
@@ -6935,7 +6989,8 @@ var createDataRecordRuleCmd = {
6935
6989
  ],
6936
6990
  examples: [
6937
6991
  "Triggers: data_record:created, data_record:updated. Common actions:",
6938
- "chat:create, webhook:send, email:send, member:label.",
6992
+ "chat:create, email:send, member:label. To tell an external system about",
6993
+ "record changes, use Organization \u2192 Webhooks, not an event rule.",
6939
6994
  "",
6940
6995
  "CEL conditions read record fields as record.data.<fieldname>:",
6941
6996
  "gr events rules create-data-record-rule -w $WID --allow-write \\",
@@ -6944,11 +6999,11 @@ var createDataRecordRuleCmd = {
6944
6999
  " --conditions 'record.data.total_score >= 15' \\",
6945
7000
  ` --action-params '{"recipientMode":"specific_member","memberId":<staff-member-id>,"messageTemplate":"High-risk screening submitted."}'`,
6946
7001
  "",
6947
- "Webhook on every update of the form:",
7002
+ "Label the member on every update of the form:",
6948
7003
  "gr events rules create-data-record-rule -w $WID --allow-write \\",
6949
7004
  " --data-type-id 45 --event-type data_record:updated \\",
6950
- ` --action-type webhook:send --action-params '{"webhookUrl":"https://example.com/hook"}'`,
6951
- ...actionParamExampleLines(["chat:create", "webhook:send", "email:send", "member:label"]),
7005
+ ` --action-type member:label --action-params '{"addLabelIds":["<label-uuid>"]}'`,
7006
+ ...actionParamExampleLines(["chat:create", "email:send", "member:label"]),
6952
7007
  ...VERIFY_EXAMPLE_LINES
6953
7008
  ],
6954
7009
  handler: async (hctx) => {
@@ -7181,18 +7236,19 @@ var experimentsDomain = {
7181
7236
  args: [
7182
7237
  ...LIST_PAGINATION_ARGS,
7183
7238
  {
7184
- name: "include-archived",
7185
- description: "Include archived experiments",
7239
+ name: "archived",
7240
+ description: "List archived experiments instead of active experiments",
7241
+ isFlag: true,
7186
7242
  required: false
7187
7243
  }
7188
7244
  ],
7189
7245
  handler: async ({ ctx, workspace, args }) => {
7190
- const includeArchived = args["include-archived"] === "true";
7246
+ const archived = args.archived === true;
7191
7247
  const pag = parsePaginationArgs(args);
7192
7248
  const result = await requireAuth(ctx).apiClient.getExperiments(workspace, {
7193
7249
  ...pag.page ? { page: pag.page } : {},
7194
7250
  ...pag.pageSize ? { pageSize: pag.pageSize } : {},
7195
- includeArchived
7251
+ archived
7196
7252
  });
7197
7253
  outputData(listResult(result, true), ctx, EXPERIMENT_COLUMNS);
7198
7254
  }
@@ -8668,10 +8724,11 @@ var journeysDomain = {
8668
8724
  mutates: true,
8669
8725
  requiresWorkspace: true,
8670
8726
  examples: [
8671
- `gr journeys create -w $WID --data '{"name":"Onboarding","description":"New patient flow","status":"draft"}'`,
8727
+ `gr journeys create -w $WID --data '{"name":"Onboarding","description":"New patient flow","status":"draft","executionModel":"v2"}'`,
8672
8728
  "",
8673
8729
  "Fields: name (required), description, status (draft|active|paused)",
8674
- " ownerId (member ID), autoEnrollFilterId (legacy filter ID), executionModel (legacy|v2)",
8730
+ " ownerId (member ID), autoEnrollFilterId (legacy filter ID)",
8731
+ " executionModel: v2 (the default when omitted; new legacy Journeys cannot be created)",
8675
8732
  " enrollmentConditions (V2): array of {uuid?, name?, filterId OR memberPredicate}"
8676
8733
  ],
8677
8734
  handler: async ({ ctx, workspace, data }) => {
@@ -9503,6 +9560,13 @@ var metricsDomain = {
9503
9560
  prefix: ["metrics"],
9504
9561
  entityName: "metric",
9505
9562
  listMethod: "listMetrics",
9563
+ listArgs: [
9564
+ {
9565
+ name: "archived",
9566
+ description: "List archived metrics instead of active metrics",
9567
+ isFlag: true
9568
+ }
9569
+ ],
9506
9570
  getMethod: "getMetric",
9507
9571
  createMethod: "createMetric",
9508
9572
  updateMethod: "updateMetric",
@@ -9802,11 +9866,45 @@ function parseMaxBudgetUsd(raw, flagName) {
9802
9866
  var REALTIME_MAX_CONCURRENCY = 4;
9803
9867
  function summarizeCriterionResults(run) {
9804
9868
  if (!run.criterionResults?.length) return void 0;
9805
- return run.criterionResults.map((c) => ({
9806
- name: c.criterionName ?? `criterion-${c.criterionId}`,
9807
- passed: c.passed ?? null,
9808
- score: c.score ?? null
9809
- }));
9869
+ return run.criterionResults.map((c) => {
9870
+ const data = c.evaluationData ?? {};
9871
+ const status = data.status === "skipped" && data.reason === "expression_criterion_failed" ? "skipped" : data.error_type != null || data.error != null ? "grading_error" : c.passed === true ? "passed" : c.passed === false ? "failed" : "not_graded";
9872
+ return {
9873
+ name: c.criterionName ?? `criterion-${c.criterionId}`,
9874
+ passed: c.passed ?? null,
9875
+ score: c.score ?? null,
9876
+ status
9877
+ };
9878
+ });
9879
+ }
9880
+ function batchEvaluationStatus(row) {
9881
+ if (row.batch_skipped) return "skipped";
9882
+ if (row.launch_refused) return "launch_refused";
9883
+ if (isConfigurationBlockerFailure(row.failure_reason)) return "configuration_blocker";
9884
+ if (row.outcome === "instrument_failure") return "instrument_failure";
9885
+ if (row.failure_reason?.startsWith("Grading did not finish:") || row.criterion_results?.some((c) => c.status === "grading_error"))
9886
+ return "grading_error";
9887
+ if (row.error || row.failure_reason) return "execution_error";
9888
+ if (!row.evaluated_at) return "not_evaluated";
9889
+ if (row.passed === true) return "passed";
9890
+ if (row.passed === false) return "criterion_failed";
9891
+ return "not_evaluated";
9892
+ }
9893
+ function qualificationRunDiagnostics(run) {
9894
+ const row = runToBatchRow(
9895
+ { round: 0, warmup: false, scenarioId: run.scenarioId ?? 0, modelId: "" },
9896
+ run.workflowId ?? 0,
9897
+ run
9898
+ );
9899
+ const criterionCounts = {};
9900
+ for (const criterion of row.criterion_results ?? []) {
9901
+ criterionCounts[criterion.status] = (criterionCounts[criterion.status] ?? 0) + 1;
9902
+ }
9903
+ return { evaluationStatus: batchEvaluationStatus(row), criterionCounts };
9904
+ }
9905
+ function isLaunchRefusal(error) {
9906
+ if (typeof error !== "object" || error === null || !("statusCode" in error)) return false;
9907
+ return [400, 401, 403, 404, 409, 422].includes(Number(error.statusCode));
9810
9908
  }
9811
9909
  function formatRevisionLabel(row) {
9812
9910
  const pin = row.workflow_revision_pinned ? "(pinned)" : "";
@@ -9841,6 +9939,8 @@ function runToBatchRow(job, workflowId, run, error, batchLabel, pinnedRevisionId
9841
9939
  assistant_realtime_model_id: run?.assistantRealtimeModelId ?? null,
9842
9940
  error,
9843
9941
  failure_reason: run?.failureReason ?? null,
9942
+ simulated_datetime: run?.simulatedDatetime ?? null,
9943
+ simulated_timezone: run?.simulatedTimezone ?? null,
9844
9944
  passed: run?.passed ?? null,
9845
9945
  overall_score: run?.overallScore ?? null,
9846
9946
  timing_summary: run?.timingSummary ?? null,
@@ -9877,13 +9977,13 @@ async function waitForRunTerminal(api, workspace, runId, timeoutMs, pollMs, slee
9877
9977
  }
9878
9978
  throw new BatchWaitTimeoutError(`Timed out waiting for run ${runId} to complete`, lastPolled);
9879
9979
  }
9880
- async function waitForEvaluation(api, workspace, runId, timeoutMs, pollMs, sleep2) {
9980
+ async function waitForEvaluation(api, workspace, runId, timeoutMs, pollMs, sleep2, previousEvaluatedAt, previousFailureReason) {
9881
9981
  let lastPolled;
9882
9982
  const deadline = Date.now() + timeoutMs;
9883
9983
  while (Date.now() < deadline) {
9884
9984
  const run = await api.getTestChatRun(workspace, runId);
9885
9985
  lastPolled = run;
9886
- if (run.evaluatedAt) {
9986
+ if (run.evaluatedAt && run.evaluatedAt !== previousEvaluatedAt || run.failureReason?.startsWith("Grading did not finish:") && run.failureReason !== previousFailureReason) {
9887
9987
  return run;
9888
9988
  }
9889
9989
  if (run.failedAt) {
@@ -9897,10 +9997,11 @@ function formatBatchProgressLine(job, row) {
9897
9997
  const ttftP50 = row.timing_summary && typeof row.timing_summary === "object" && row.timing_summary.ttft_ms && typeof row.timing_summary.ttft_ms === "object" && "p50" in row.timing_summary.ttft_ms ? String(row.timing_summary.ttft_ms.p50) : "-";
9898
9998
  const cfg = isConfigurationBlockerFailure(row.failure_reason) ? " CONFIG_BLOCKER" : "";
9899
9999
  const skipped = row.batch_skipped ? " SKIPPED" : "";
9900
- return `r${job.round} ${job.modelId} scenario=${job.scenarioId} rev=${formatRevisionLabel(row)} run=${row.run_id ?? "ERR"} passed=${row.passed ?? "-"} score=${row.overall_score != null ? row.overall_score.toFixed(2) : "-"} ttft_p50=${ttftP50}ms${row.error ? ` [${formatProgressError(row.error)}]` : ""}${cfg}${skipped}${job.warmup ? " WARM" : ""}`;
10000
+ return `r${job.round} ${job.modelId} scenario=${job.scenarioId} rev=${formatRevisionLabel(row)} run=${row.run_id ?? "ERR"} lane=${row.lane ?? "?"} status=${row.evaluation_status ?? batchEvaluationStatus(row)} passed=${row.passed ?? "-"} ` + (row.evaluation_request ? `evaluation=${row.evaluation_request} ` : "") + `score=${row.overall_score != null ? row.overall_score.toFixed(2) : "-"} ttft_p50=${ttftP50}ms${row.error ? ` [${formatProgressError(row.error, 60)}]` : ""}${cfg}${skipped}${job.warmup ? " WARM" : ""}`;
9901
10001
  }
9902
10002
  async function executeModelEvalJob(api, options, job, waitTimeoutMs, pollMs, sleep2) {
9903
10003
  let run;
10004
+ let evaluationRequest;
9904
10005
  try {
9905
10006
  const started = await api.startTestChatRun(options.workspace, options.workflowId, {
9906
10007
  scenarioId: job.scenarioId,
@@ -9911,6 +10012,7 @@ async function executeModelEvalJob(api, options, job, waitTimeoutMs, pollMs, sle
9911
10012
  ...options.realtimeConfig ? { assistantRealtimeModelConfig: options.realtimeConfig } : {}
9912
10013
  } : { assistantChatModelId: job.modelId }
9913
10014
  });
10015
+ run = started.run;
9914
10016
  run = await waitForRunTerminal(
9915
10017
  api,
9916
10018
  options.workspace,
@@ -9920,35 +10022,49 @@ async function executeModelEvalJob(api, options, job, waitTimeoutMs, pollMs, sle
9920
10022
  sleep2
9921
10023
  );
9922
10024
  if (options.evaluate && run.completedAt && !run.failedAt) {
9923
- await api.evaluateTestChatRun(options.workspace, run.id);
9924
- run = await waitForEvaluation(
9925
- api,
9926
- options.workspace,
9927
- run.id,
9928
- waitTimeoutMs,
9929
- pollMs,
9930
- sleep2
9931
- );
10025
+ const previousEvaluatedAt = run.evaluatedAt;
10026
+ const previousFailureReason = run.failureReason;
10027
+ const response = await api.evaluateTestChatRun(options.workspace, run.id);
10028
+ evaluationRequest = response?.alreadyEvaluated ? "retained_existing_grade" : "requested";
10029
+ if (!response?.alreadyEvaluated) {
10030
+ run = await waitForEvaluation(
10031
+ api,
10032
+ options.workspace,
10033
+ run.id,
10034
+ waitTimeoutMs,
10035
+ pollMs,
10036
+ sleep2,
10037
+ previousEvaluatedAt,
10038
+ previousFailureReason
10039
+ );
10040
+ }
9932
10041
  }
9933
- return runToBatchRow(
9934
- job,
9935
- options.workflowId,
9936
- run,
9937
- void 0,
9938
- options.batchLabel,
9939
- options.workflowRevisionId
9940
- );
10042
+ return {
10043
+ ...runToBatchRow(
10044
+ job,
10045
+ options.workflowId,
10046
+ run,
10047
+ void 0,
10048
+ options.batchLabel,
10049
+ options.workflowRevisionId
10050
+ ),
10051
+ ...evaluationRequest ? { evaluation_request: evaluationRequest } : {}
10052
+ };
9941
10053
  } catch (e) {
9942
10054
  const message = e instanceof Error ? e.message : String(e);
9943
10055
  const lastKnown = (e instanceof BatchWaitTimeoutError ? e.lastPolledRun : void 0) ?? run ?? null;
9944
- return runToBatchRow(
9945
- job,
9946
- options.workflowId,
9947
- lastKnown,
9948
- message,
9949
- options.batchLabel,
9950
- options.workflowRevisionId
9951
- );
10056
+ return {
10057
+ ...runToBatchRow(
10058
+ job,
10059
+ options.workflowId,
10060
+ lastKnown,
10061
+ message,
10062
+ options.batchLabel,
10063
+ options.workflowRevisionId
10064
+ ),
10065
+ ...!run && isLaunchRefusal(e) ? { launch_refused: true } : {},
10066
+ ...evaluationRequest ? { evaluation_request: evaluationRequest } : {}
10067
+ };
9952
10068
  }
9953
10069
  }
9954
10070
  function createSpacingGate(spacingSec, sleep2) {
@@ -9988,6 +10104,9 @@ async function executeModelEvalBatch(api, options) {
9988
10104
  `);
9989
10105
  }
9990
10106
  };
10107
+ emitProgress(
10108
+ `Batch: ${jobs.length} run(s), Workflow ${options.workflowId}, revision ${options.workflowRevisionId != null ? `id${options.workflowRevisionId} (pinned)` : "active at each launch (use --workflow-revision-id for a fixed comparison)"}.`
10109
+ );
9991
10110
  const realtimeJobCount = jobs.filter((j) => j.realtime).length;
9992
10111
  let concurrency = options.concurrency ?? 1;
9993
10112
  if (realtimeJobCount > 0 && concurrency > REALTIME_MAX_CONCURRENCY) {
@@ -10009,6 +10128,7 @@ async function executeModelEvalBatch(api, options) {
10009
10128
  }
10010
10129
  }
10011
10130
  const recordRow = (job, row) => {
10131
+ row.evaluation_status = batchEvaluationStatus(row);
10012
10132
  rows.push(row);
10013
10133
  if (options.outPath) {
10014
10134
  appendFileSync(options.outPath, `${JSON.stringify(row)}
@@ -10033,16 +10153,16 @@ async function executeModelEvalBatch(api, options) {
10033
10153
  return makeSkippedRow(job);
10034
10154
  }
10035
10155
  const row = await executeModelEvalJob(api, options, job, waitTimeoutMs, pollMs, sleep2);
10036
- if (isConfigurationBlockerFailure(row.failure_reason)) {
10156
+ if (row.launch_refused || isConfigurationBlockerFailure(row.failure_reason)) {
10037
10157
  stopBatch = true;
10038
10158
  }
10039
- if (job.realtime && !row.batch_skipped) {
10159
+ if (job.realtime && !row.batch_skipped && !row.launch_refused) {
10040
10160
  actualSpendUsd += actualRealtimeRowCostUsd(row, job.modelId);
10041
10161
  if (options.maxBudgetUsd != null && actualSpendUsd >= options.maxBudgetUsd && !stopBatch) {
10042
10162
  stopBatch = true;
10043
10163
  budgetStopped = true;
10044
10164
  emitProgress(
10045
- `realtime budget: actual spend ~$${actualSpendUsd.toFixed(2)} reached cap $${options.maxBudgetUsd.toFixed(2)} \u2014 stopping dispatch`
10165
+ `realtime budget: attributed spend ~$${actualSpendUsd.toFixed(2)} reached cap $${options.maxBudgetUsd.toFixed(2)} \u2014 stopping dispatch`
10046
10166
  );
10047
10167
  }
10048
10168
  }
@@ -10063,7 +10183,14 @@ async function executeModelEvalBatch(api, options) {
10063
10183
  }
10064
10184
  } else {
10065
10185
  const results = new Array(jobs.length);
10066
- let nextIndex = 0;
10186
+ const firstJob = jobs[0];
10187
+ if (firstJob) {
10188
+ emitProgress("Checking the first run before parallel dispatch (no extra test run).");
10189
+ const firstRow = await runOne(firstJob);
10190
+ results[0] = firstRow;
10191
+ recordRow(firstJob, firstRow);
10192
+ }
10193
+ let nextIndex = 1;
10067
10194
  const worker = async () => {
10068
10195
  while (true) {
10069
10196
  if (stopBatch) {
@@ -10097,7 +10224,45 @@ async function executeModelEvalBatch(api, options) {
10097
10224
  }
10098
10225
  }
10099
10226
  if (realtimeJobCount > 0) {
10100
- emitProgress(`realtime budget: total actual spend ~$${actualSpendUsd.toFixed(2)}`);
10227
+ emitProgress(
10228
+ `realtime budget: total attributed spend ~$${actualSpendUsd.toFixed(2)} (measured duration where available; estimated otherwise)`
10229
+ );
10230
+ }
10231
+ const counts = rows.reduce((result, row) => {
10232
+ const status = row.evaluation_status ?? batchEvaluationStatus(row);
10233
+ result[status] = (result[status] ?? 0) + 1;
10234
+ return result;
10235
+ }, {});
10236
+ emitProgress(
10237
+ `Batch results: ${Object.entries(counts).map(([status, count]) => `${status}=${count}`).join(" ")}. Criterion failures are not necessarily model defects.`
10238
+ );
10239
+ const criteria = rows.flatMap((row) => row.criterion_results ?? []);
10240
+ if (criteria.length) {
10241
+ const criterionCounts = criteria.reduce((result, criterion) => {
10242
+ result[criterion.status] = (result[criterion.status] ?? 0) + 1;
10243
+ return result;
10244
+ }, {});
10245
+ emitProgress(
10246
+ `Criteria: ${Object.entries(criterionCounts).map(([status, count]) => `${status}=${count}`).join(
10247
+ " "
10248
+ )}. Inspect individual criteria; runtime/setup checks can fail independently of the Agent.`
10249
+ );
10250
+ }
10251
+ const skippedCriteria = criteria.filter((c) => c.status === "skipped").length;
10252
+ if (skippedCriteria)
10253
+ emitProgress(
10254
+ `Rubric criteria skipped after expression failure: ${skippedCriteria}; these are not failing grades.`
10255
+ );
10256
+ if (rows.some((row) => row.simulated_datetime)) {
10257
+ emitProgress(
10258
+ "Simulated time does not change external service clocks. Verify captured routing time separately."
10259
+ );
10260
+ }
10261
+ const refusalRow = rows.find((row) => row.launch_refused);
10262
+ if (refusalRow) {
10263
+ throw new CLIError(
10264
+ `Batch stopped: the API refused a run before launch. Check the scenario persona Member role or the workspace default role, request permissions, and Workflow/model settings. No role or permission was changed. Remaining jobs were not started. Last refusal: ${formatProgressError(refusalRow.error ?? "", 200)}`
10265
+ );
10101
10266
  }
10102
10267
  const blockerRow = rows.find((r) => isConfigurationBlockerFailure(r.failure_reason));
10103
10268
  if (blockerRow) {
@@ -10154,6 +10319,16 @@ var RUN_COLUMNS = [
10154
10319
  header: "DRIVER",
10155
10320
  getValue: (item) => item.driverMemberId == null ? "auto" : item.driverMemberName ?? `member #${item.driverMemberId}`
10156
10321
  },
10322
+ { header: "STATUS", getValue: (item) => item.evaluationStatus ?? "" },
10323
+ {
10324
+ header: "MODEL",
10325
+ getValue: (item) => item.assistantRealtimeModelId ?? item.assistantChatModelId ?? ""
10326
+ },
10327
+ {
10328
+ header: "REVISION",
10329
+ getValue: (item) => String(item.workflowRevisionNumber ?? item.workflowRevisionId ?? "")
10330
+ },
10331
+ { header: "LANE", getValue: (item) => item.lane ?? "" },
10157
10332
  { header: "STARTED", getValue: (item) => item.startedAt ?? "" },
10158
10333
  { header: "COMPLETED", getValue: (item) => item.completedAt ?? "" },
10159
10334
  {
@@ -10298,7 +10473,14 @@ var qualificationsDomain = {
10298
10473
  ...assistantChatModelId ? { assistantChatModelId } : {}
10299
10474
  }
10300
10475
  );
10301
- outputData(result, ctx, RUN_COLUMNS);
10476
+ outputData(
10477
+ result.map((run) => ({
10478
+ ...run,
10479
+ ...qualificationRunDiagnostics(run)
10480
+ })),
10481
+ ctx,
10482
+ RUN_COLUMNS
10483
+ );
10302
10484
  }
10303
10485
  },
10304
10486
  {
@@ -10311,7 +10493,7 @@ var qualificationsDomain = {
10311
10493
  workspace,
10312
10494
  requireNumber(args, "id")
10313
10495
  );
10314
- outputSingle(result, ctx);
10496
+ outputSingle({ ...result, ...qualificationRunDiagnostics(result) }, ctx);
10315
10497
  }
10316
10498
  },
10317
10499
  {
@@ -10428,11 +10610,12 @@ var qualificationsDomain = {
10428
10610
  requiresWorkspace: true,
10429
10611
  args: [{ name: "id", description: "Test chat run ID", required: true }],
10430
10612
  handler: async ({ ctx, workspace, args }) => {
10431
- await requireAuth(ctx).apiClient.evaluateTestChatRun(
10613
+ const result = await requireAuth(ctx).apiClient.evaluateTestChatRun(
10432
10614
  workspace,
10433
10615
  requireNumber(args, "id")
10434
10616
  );
10435
- process.stdout.write(`Evaluation started for test chat run ${args["id"]}
10617
+ const message = result.alreadyEvaluated ? `Test chat run ${args["id"]} is already evaluated; its stored grade is unchanged.` : `Evaluation requested for test chat run ${args["id"]}.`;
10618
+ process.stdout.write(`${message}
10436
10619
  `);
10437
10620
  }
10438
10621
  },
@@ -12043,9 +12226,9 @@ function buildQueryRequest(args, now) {
12043
12226
  if (groupBy) request.groupBy = groupBy;
12044
12227
  const eventTypes = parseEventTypes(args);
12045
12228
  if (eventTypes.length > 0) request.eventTypes = eventTypes;
12046
- const subject = parseSubject(args);
12047
- if (subject) {
12048
- request.subject = subject;
12229
+ const subject2 = parseSubject(args);
12230
+ if (subject2) {
12231
+ request.subject = subject2;
12049
12232
  if (!request.grain) request.grain = ActivityGrain.event;
12050
12233
  }
12051
12234
  const scope = parseScope(args);
@@ -13003,7 +13186,7 @@ var COLUMNS16 = [
13003
13186
  { header: "PREFIX", getValue: (item) => item.prefix ?? "" },
13004
13187
  COL.created()
13005
13188
  ];
13006
- var CREATE_COLUMNS = [
13189
+ var CREATE_COLUMNS2 = [
13007
13190
  COL.id(),
13008
13191
  COL.name(),
13009
13192
  { header: "KEY", getValue: (item) => item.key ?? "" },
@@ -13030,7 +13213,7 @@ var apiKeysDomain = {
13030
13213
  requiresWorkspace: true,
13031
13214
  handler: async ({ ctx, workspace, data }) => {
13032
13215
  const result = await requireAuth(ctx).apiClient.createApiKey(workspace, data);
13033
- outputSingle(result, ctx, CREATE_COLUMNS);
13216
+ outputSingle(result, ctx, CREATE_COLUMNS2);
13034
13217
  if (ctx.outputFormat === "table") {
13035
13218
  process.stdout.write("\n\u26A0 This key will not be shown again. Copy it now.\n");
13036
13219
  }
@@ -13065,7 +13248,7 @@ var apiKeysDomain = {
13065
13248
  requiresWorkspace: false,
13066
13249
  handler: async ({ ctx, data }) => {
13067
13250
  const result = await requireAuth(ctx).apiClient.createGlobalApiKey(data);
13068
- outputSingle(result, ctx, CREATE_COLUMNS);
13251
+ outputSingle(result, ctx, CREATE_COLUMNS2);
13069
13252
  if (ctx.outputFormat === "table") {
13070
13253
  process.stdout.write("\n\u26A0 This key will not be shown again. Copy it now.\n");
13071
13254
  }
@@ -13925,6 +14108,10 @@ var inboxesDomain = {
13925
14108
  createMethod: "createInbox",
13926
14109
  updateMethod: "updateInbox",
13927
14110
  deleteMethod: "deleteInbox",
14111
+ // One-way, like a phone number: the inbox leaves the Active list,
14112
+ // refuses new mail, and keeps its emails. Delete stays the verb that
14113
+ // finally removes it.
14114
+ archiveMethod: "archiveInbox",
13928
14115
  columns: COLUMNS19
13929
14116
  }),
13930
14117
  {
@@ -14363,6 +14550,125 @@ var operatorGroupsDomain = {
14363
14550
  ]
14364
14551
  };
14365
14552
 
14553
+ // src/domains/org-billing.ts
14554
+ async function subject(hctx) {
14555
+ const auth = requireAuth(hctx.ctx);
14556
+ const billing = await auth.apiClient.getOrgBillingCustomer(requireOrgRef(hctx.args));
14557
+ if (!billing.hasAccess || !billing.customerUuid || !billing.subscriptionId) {
14558
+ throw new CLIError("A billing role on this organization\u2019s billing customer is required");
14559
+ }
14560
+ return { auth, billing };
14561
+ }
14562
+ var orgBillingCommands = [
14563
+ {
14564
+ path: ["org", "billing", "get"],
14565
+ description: "Read only this organization\u2019s billable subscription",
14566
+ args: [ORG_UUID_ARG],
14567
+ handler: async (hctx) => {
14568
+ const { auth, billing } = await subject(hctx);
14569
+ outputSingle(
14570
+ await auth.apiClient.getMyCustomerSubscriptions(billing.customerUuid, {
14571
+ subscriptionId: billing.subscriptionId,
14572
+ pageSize: 1
14573
+ }),
14574
+ hctx.ctx
14575
+ );
14576
+ }
14577
+ },
14578
+ {
14579
+ path: ["org", "billing", "update"],
14580
+ description: "Update this organization\u2019s subscription credit settings (billing owner required)",
14581
+ args: [ORG_UUID_ARG],
14582
+ mutates: true,
14583
+ acceptsJsonInput: true,
14584
+ handler: async (hctx) => {
14585
+ const { auth, billing } = await subject(hctx);
14586
+ if (!hctx.data || typeof hctx.data !== "object" || Array.isArray(hctx.data))
14587
+ throw new CLIError("Provide credit settings as a JSON object with --data");
14588
+ outputSingle(
14589
+ await auth.apiClient.updateSubscription(billing.subscriptionId, hctx.data),
14590
+ hctx.ctx
14591
+ );
14592
+ }
14593
+ },
14594
+ {
14595
+ path: ["org", "billing", "purchase-credits"],
14596
+ description: "Purchase extra credits for this organization (charges the billing owner\u2019s payment method)",
14597
+ args: [
14598
+ ORG_UUID_ARG,
14599
+ { name: "amount-cents", description: "Amount to charge in cents", required: true },
14600
+ {
14601
+ name: "idempotency-key",
14602
+ description: "Stable operation key to prevent a duplicate charge"
14603
+ }
14604
+ ],
14605
+ mutates: true,
14606
+ handler: async (hctx) => {
14607
+ const { auth, billing } = await subject(hctx);
14608
+ const amount = Number(hctx.args["amount-cents"]);
14609
+ if (!Number.isInteger(amount) || amount < 100 || amount > 1e7)
14610
+ throw new CLIError("Use an integer amount between 100 and 10000000 cents");
14611
+ outputSingle(
14612
+ await auth.apiClient.purchaseCredits(
14613
+ billing.subscriptionId,
14614
+ amount,
14615
+ hctx.args["idempotency-key"]
14616
+ ),
14617
+ hctx.ctx
14618
+ );
14619
+ }
14620
+ }
14621
+ ];
14622
+
14623
+ // src/domains/org-api.ts
14624
+ var orgApiCommands = [
14625
+ {
14626
+ path: ["org", "api"],
14627
+ description: "Call an organization management endpoint. --path is relative to /o/{org}. Use the same method and JSON body as the org UI. Covers members, invitations, workspaces, brands/campaigns, phone numbers, domains, SSO, connectors, billing policy and webhooks. Workspace data and credential changes keep their existing authorization gates.",
14628
+ args: [
14629
+ ORG_UUID_ARG,
14630
+ {
14631
+ name: "path",
14632
+ description: "Org-relative API path, e.g. /members or /a2p-brands",
14633
+ required: true
14634
+ },
14635
+ { name: "method", description: "GET, POST, PUT, PATCH or DELETE", default: "GET" }
14636
+ ],
14637
+ mutates: true,
14638
+ acceptsJsonInput: true,
14639
+ examples: [
14640
+ "gr org api --org $ORG_UUID --path /members --allow-write",
14641
+ `gr org api --org $ORG_UUID --path /invitations --method POST --data '{"email":"colleague@example.test","role":"member"}' --allow-write`
14642
+ ],
14643
+ handler: async ({ ctx, args, data }) => {
14644
+ const auth = requireAuth(ctx);
14645
+ const method = String(args.method).toUpperCase();
14646
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) {
14647
+ throw new CLIError("Use GET, POST, PUT, PATCH or DELETE");
14648
+ }
14649
+ const org = encodeURIComponent(requireOrgRef(args));
14650
+ const path4 = String(args.path);
14651
+ const prefix = `/api/v2/o/${org}`;
14652
+ const base = new URL(auth.envConfig.apiUrl);
14653
+ const url = new URL(`${prefix}${path4}`, base);
14654
+ if (!path4.startsWith("/") || path4.startsWith("//") || path4.includes("\\") || /%(?:2e|2f|5c)/i.test(path4.split("?")[0] ?? "") || url.origin !== base.origin || url.pathname !== prefix && !url.pathname.startsWith(prefix + "/")) {
14655
+ throw new CLIError("Use a path within this organization");
14656
+ }
14657
+ const response = await fetch(url, {
14658
+ method,
14659
+ redirect: "error",
14660
+ headers: {
14661
+ Authorization: `Bearer ${auth.accessToken}`,
14662
+ "Content-Type": "application/json"
14663
+ },
14664
+ ...data !== void 0 && method !== "GET" ? { body: JSON.stringify(data) } : {}
14665
+ });
14666
+ if (!response.ok) throw new CLIError(`Organization request failed (${response.status})`);
14667
+ outputSingle(response.status === 204 ? { success: true } : await response.json(), ctx);
14668
+ }
14669
+ }
14670
+ ];
14671
+
14366
14672
  // src/domains/org.ts
14367
14673
  import {
14368
14674
  ApiError as ApiError3
@@ -14571,7 +14877,7 @@ var ORG_MEMBER_ID_ARG = {
14571
14877
  };
14572
14878
  var ORG_MEMBER_ROLE_ARG = {
14573
14879
  name: "role",
14574
- description: "New role: member, admin, owner, or platform_support"
14880
+ description: "New role: member, developer, admin, owner, or platform_support"
14575
14881
  };
14576
14882
  var ORG_MEMBER_NAME_ARG = {
14577
14883
  name: "name",
@@ -15429,6 +15735,8 @@ var orgDomain = {
15429
15735
  name: "org",
15430
15736
  description: "Organization membership, domains, webhook endpoints, and workspace labels",
15431
15737
  commands: [
15738
+ ...orgApiCommands,
15739
+ ...orgBillingCommands,
15432
15740
  {
15433
15741
  path: ["org", "list"],
15434
15742
  description: "List my organizations",
@@ -15462,6 +15770,7 @@ var orgDomain = {
15462
15770
  // src/domains/org-legal-entities.ts
15463
15771
  var LEGAL_ENTITY_COLUMNS = [
15464
15772
  { header: "UUID", getValue: (e) => e.uuid ?? "" },
15773
+ { header: "LABEL", getValue: (e) => e.displayName ?? e.legalName ?? "" },
15465
15774
  { header: "LEGAL NAME", getValue: (e) => e.legalName ?? "" },
15466
15775
  { header: "PRIMARY", getValue: (e) => e.isPrimary ? "yes" : "" },
15467
15776
  { header: "ID TYPE", getValue: (e) => e.registrationIdentifierType ?? "" },
@@ -15545,12 +15854,13 @@ var commands2 = [
15545
15854
  },
15546
15855
  {
15547
15856
  path: ["org", "legal-entities", "create"],
15548
- description: "Create a legal entity (its business profile is filled in separately)",
15857
+ description: "Create a legal entity (its business profile is filled in separately). displayName defaults to legalName; give a second entity for the same business (another region) a distinct label.",
15549
15858
  mutates: true,
15550
15859
  requiresWorkspace: false,
15551
15860
  args: [ORG_UUID_ARG],
15552
15861
  examples: [
15553
- `yarn gr org legal-entities create --org-uuid $ORG_UUID --data '{"legalName":"Acme Health"}' --allow-write`
15862
+ `yarn gr org legal-entities create --org-uuid $ORG_UUID --data '{"legalName":"Acme Health"}' --allow-write`,
15863
+ `yarn gr org legal-entities create --org-uuid $ORG_UUID --data '{"legalName":"Leapcure","displayName":"Leapcure (Australia)"}' --allow-write`
15554
15864
  ],
15555
15865
  handler: async (hctx) => {
15556
15866
  const result = await requireAuth(hctx.ctx).apiClient.createLegalEntity(
@@ -15730,11 +16040,14 @@ var commands3 = [
15730
16040
  { name: "org-uuid", aliases: ["org"], description: "Organization UUID", required: true },
15731
16041
  {
15732
16042
  name: "country",
15733
- description: "ISO country code, e.g. US, AU, GB (default: US)",
16043
+ description: "Country: US or AU (default: US)",
15734
16044
  default: "US"
15735
16045
  },
15736
- { name: "number-type", description: "Number type: local or toll_free", default: "local" },
15737
- { name: "area-code", description: "Area code filter" },
16046
+ {
16047
+ name: "number-type",
16048
+ description: "US: local or toll_free (default: local); AU: mobile (default: mobile)"
16049
+ },
16050
+ { name: "area-code", description: "US local area code filter" },
15738
16051
  { name: "contains", description: "Phone number pattern to match" },
15739
16052
  { name: "limit", description: "Maximum results (default: 20)" }
15740
16053
  ],
@@ -15742,9 +16055,10 @@ var commands3 = [
15742
16055
  columns: AVAILABLE_PHONE_COLUMNS,
15743
16056
  handler: async (hctx) => {
15744
16057
  const orgUuid = requireOrgRef(hctx.args);
16058
+ const country = hctx.args.country ?? "US";
15745
16059
  const result = await getOrgApi(hctx).searchPhoneNumbers(orgUuid, {
15746
- country: hctx.args.country ?? "US",
15747
- numberType: hctx.args["number-type"] ?? "local",
16060
+ country,
16061
+ numberType: hctx.args["number-type"] ?? (country.toUpperCase() === "AU" ? "mobile" : "local"),
15748
16062
  areaCode: hctx.args["area-code"],
15749
16063
  contains: hctx.args.contains,
15750
16064
  limit: hctx.args.limit ? Number(hctx.args.limit) : void 0
@@ -15759,19 +16073,26 @@ var commands3 = [
15759
16073
  args: [
15760
16074
  { name: "org-uuid", aliases: ["org"], description: "Organization UUID", required: true },
15761
16075
  { name: "phone-number", description: "E.164 phone number to purchase", required: true },
15762
- { name: "number-type", description: "Number type: local or toll_free", default: "local" },
16076
+ {
16077
+ name: "number-type",
16078
+ description: "US: local or toll_free (default: local); AU: mobile (default: mobile)"
16079
+ },
15763
16080
  {
15764
16081
  name: "country",
15765
- description: "ISO country code of the number, e.g. US, AU (default: US)",
16082
+ description: "Country: US or AU (default: US)",
15766
16083
  default: "US"
15767
16084
  },
16085
+ {
16086
+ name: "legal-entity",
16087
+ description: "Approved business UUID for Australian mobile numbers"
16088
+ },
15768
16089
  {
15769
16090
  name: "bundle-sid",
15770
- description: "Twilio regulatory bundle SID (BUxxxx) \u2014 required for regulated countries like AU"
16091
+ description: "Twilio regulatory bundle SID (BUxxxx); not accepted for AU, use --legal-entity"
15771
16092
  },
15772
16093
  {
15773
16094
  name: "address-sid",
15774
- description: "Twilio address SID (ADxxxx) \u2014 required alongside the bundle for regulated countries"
16095
+ description: "Twilio address SID (ADxxxx); not accepted for AU, use --legal-entity"
15775
16096
  }
15776
16097
  ],
15777
16098
  requiresWorkspace: false,
@@ -15780,13 +16101,15 @@ var commands3 = [
15780
16101
  const orgUuid = requireOrgRef(hctx.args);
15781
16102
  const phoneNumber = hctx.args["phone-number"];
15782
16103
  if (!phoneNumber) throw new CLIError("Missing required argument: --phone-number");
15783
- const numberType = hctx.args["number-type"] ?? "local";
16104
+ const country = hctx.args.country ?? "US";
16105
+ const numberType = hctx.args["number-type"] ?? (country.toUpperCase() === "AU" ? "mobile" : "local");
15784
16106
  const result = await getOrgApi(hctx).purchasePhoneNumber(
15785
16107
  orgUuid,
15786
16108
  phoneNumber,
15787
16109
  numberType,
15788
16110
  {
15789
- country: hctx.args.country ?? "US",
16111
+ country,
16112
+ legalEntityUuid: hctx.args["legal-entity"],
15790
16113
  bundleSid: hctx.args["bundle-sid"],
15791
16114
  addressSid: hctx.args["address-sid"]
15792
16115
  }
@@ -18722,6 +19045,44 @@ var COLUMNS31 = [
18722
19045
  { header: "URL", getValue: (item) => item.baseUrl ?? "" },
18723
19046
  COL.status()
18724
19047
  ];
19048
+ var COLUMNS_WITH_SYNC_STATE = [
19049
+ ...COLUMNS31,
19050
+ {
19051
+ header: "LAST SYNC OK",
19052
+ getValue: (item) => item.syncState?.lastSuccessfulAt ?? ""
19053
+ },
19054
+ {
19055
+ header: "SYNC STATUS",
19056
+ getValue: (item) => item.syncState?.lastStatus ?? ""
19057
+ }
19058
+ ];
19059
+ var SYNC_CONFIG_COLUMNS = [
19060
+ { header: "SYNC KEY", getValue: (config) => config.syncKey ?? "default" },
19061
+ {
19062
+ header: "POLL (MIN)",
19063
+ getValue: (config) => config.inboundPollIntervalMinutes == null ? "" : String(config.inboundPollIntervalMinutes)
19064
+ },
19065
+ {
19066
+ header: "LAST ATTEMPTED",
19067
+ getValue: (config) => config.connectionParams?.ecwEncounterSyncState?.lastAttemptedAt ?? ""
19068
+ },
19069
+ {
19070
+ header: "LAST SUCCESSFUL",
19071
+ getValue: (config) => config.connectionParams?.ecwEncounterSyncState?.lastSuccessfulAt ?? ""
19072
+ },
19073
+ {
19074
+ header: "STATUS",
19075
+ getValue: (config) => config.connectionParams?.ecwEncounterSyncState?.lastStatus ?? ""
19076
+ },
19077
+ {
19078
+ header: "LAST ERROR",
19079
+ getValue: (config) => config.connectionParams?.ecwEncounterSyncState?.lastError ?? ""
19080
+ },
19081
+ {
19082
+ header: "PATIENT REFRESH",
19083
+ getValue: (config) => config.connectionParams?.ecwEncounterSyncState?.lastPatientRefreshStatus ?? ""
19084
+ }
19085
+ ];
18725
19086
  function summarizeReasons(collections, key) {
18726
19087
  if (!collections?.length) return "";
18727
19088
  const parts = [];
@@ -18763,13 +19124,61 @@ var fhirConnectionsDomain = {
18763
19124
  prefix: ["fhir-connections"],
18764
19125
  entityName: "FHIR connection",
18765
19126
  listMethod: "getFhirConnections",
18766
- getMethod: "getFhirConnection",
18767
19127
  createMethod: "createFhirConnection",
18768
19128
  updateMethod: "updateFhirConnection",
18769
19129
  deleteMethod: "deleteFhirConnection",
18770
19130
  columns: COLUMNS31,
18771
19131
  paginationSupport: "full"
18772
19132
  }),
19133
+ {
19134
+ path: ["fhir-connections", "get"],
19135
+ description: "Get a FHIR connection by ID, optionally with its eCW encounter-sync state",
19136
+ requiresWorkspace: true,
19137
+ args: [
19138
+ { name: "id", description: "FHIR connection ID", required: true },
19139
+ {
19140
+ name: "with-sync-state",
19141
+ description: "Also read the connection sync config and include syncState (one extra request)",
19142
+ isFlag: true
19143
+ }
19144
+ ],
19145
+ examples: [
19146
+ "fhir-connections get --id 12",
19147
+ "fhir-connections get --id 12 --with-sync-state --output-format json"
19148
+ ],
19149
+ handler: async ({ ctx, workspace, args }) => {
19150
+ const api = requireAuth(ctx).apiClient;
19151
+ const id = requireNumber(args, "id");
19152
+ const connection = await api.getFhirConnection(workspace, id);
19153
+ if (!args["with-sync-state"]) {
19154
+ outputSingle(connection, ctx, COLUMNS31);
19155
+ return;
19156
+ }
19157
+ const config = await api.getFhirConnectionSyncConfig(workspace, id);
19158
+ const withState = {
19159
+ ...connection,
19160
+ syncState: config.connectionParams?.ecwEncounterSyncState ?? null
19161
+ };
19162
+ outputSingle(withState, ctx, COLUMNS_WITH_SYNC_STATE);
19163
+ }
19164
+ },
19165
+ {
19166
+ path: ["fhir-connections", "sync-config"],
19167
+ description: "Get the FHIR connection sync configuration and its eCW encounter-sync watermark",
19168
+ requiresWorkspace: true,
19169
+ args: [{ name: "id", description: "FHIR connection ID", required: true }],
19170
+ examples: [
19171
+ "fhir-connections sync-config --id 12",
19172
+ "fhir-connections sync-config --id 12 --output-format json"
19173
+ ],
19174
+ handler: async ({ ctx, workspace, args }) => {
19175
+ const config = await requireAuth(ctx).apiClient.getFhirConnectionSyncConfig(
19176
+ workspace,
19177
+ requireNumber(args, "id")
19178
+ );
19179
+ outputSingle(config, ctx, SYNC_CONFIG_COLUMNS);
19180
+ }
19181
+ },
18773
19182
  {
18774
19183
  path: ["fhir-connections", "test"],
18775
19184
  description: "Test a FHIR connection",
@@ -22561,6 +22970,7 @@ var ChatTUI = class {
22561
22970
  activeToolName = "";
22562
22971
  pausedForPrompt = false;
22563
22972
  turnInProgress = false;
22973
+ queuedMessageCount = 0;
22564
22974
  constructor(options) {
22565
22975
  this.options = options;
22566
22976
  this.debugPanelVisible = !!options.debug;
@@ -22644,6 +23054,10 @@ var ChatTUI = class {
22644
23054
  this.activeToolName = "";
22645
23055
  this.dirty();
22646
23056
  }
23057
+ setQueuedMessageCount(count) {
23058
+ this.queuedMessageCount = count;
23059
+ this.dirty();
23060
+ }
22647
23061
  /** Whether a local user→assistant turn is currently in progress. */
22648
23062
  get isTurnInProgress() {
22649
23063
  return this.turnInProgress;
@@ -22998,10 +23412,6 @@ var ChatTUI = class {
22998
23412
  this.dirty();
22999
23413
  }
23000
23414
  handleEnter() {
23001
- if (this.turnInProgress) {
23002
- this.dirty();
23003
- return;
23004
- }
23005
23415
  const text = this.inputBuffer.trim();
23006
23416
  this.inputBuffer = "";
23007
23417
  if (!text) {
@@ -23159,6 +23569,7 @@ var ChatTUI = class {
23159
23569
  break;
23160
23570
  }
23161
23571
  if (status) parts.push(status);
23572
+ if (this.queuedMessageCount) parts.push(`${this.queuedMessageCount} queued`);
23162
23573
  const line = parts.join(` ${DIM3}|${RESET3} `);
23163
23574
  return truncateAnsi(line, this.cols);
23164
23575
  }
@@ -23412,6 +23823,49 @@ function buildDebugSummary(_direction, msg) {
23412
23823
  return type;
23413
23824
  }
23414
23825
 
23826
+ // src/lib/chat-turn-queue.ts
23827
+ var ChatTurnQueue = class {
23828
+ constructor(send, onCount, onError) {
23829
+ this.send = send;
23830
+ this.onCount = onCount;
23831
+ this.onError = onError;
23832
+ }
23833
+ send;
23834
+ onCount;
23835
+ onError;
23836
+ pending = [];
23837
+ running = false;
23838
+ closed = false;
23839
+ enqueue(text) {
23840
+ if (this.closed) return;
23841
+ this.pending.push(text);
23842
+ this.onCount(this.running ? this.pending.length : Math.max(0, this.pending.length - 1));
23843
+ void this.drain();
23844
+ }
23845
+ close() {
23846
+ this.closed = true;
23847
+ this.pending = [];
23848
+ this.onCount(0);
23849
+ }
23850
+ async drain() {
23851
+ if (this.running || this.closed) return;
23852
+ this.running = true;
23853
+ try {
23854
+ while (!this.closed && this.pending.length) {
23855
+ const text = this.pending.shift();
23856
+ this.onCount(this.pending.length);
23857
+ try {
23858
+ await this.send(text);
23859
+ } catch (error) {
23860
+ if (!this.closed) this.onError(error);
23861
+ }
23862
+ }
23863
+ } finally {
23864
+ this.running = false;
23865
+ }
23866
+ }
23867
+ };
23868
+
23415
23869
  // src/lib/agui-tui-events.ts
23416
23870
  function handleAguiEvent(tui, event) {
23417
23871
  const type = event.type?.toLowerCase() ?? "";
@@ -24020,14 +24474,20 @@ async function interactiveChatSession(session, debug, autoApprove, allowWrite) {
24020
24474
  };
24021
24475
  const feedController = new AbortController();
24022
24476
  const canSubscribeToFeed = !!session.workspaceUuid && session.chatId > 0;
24477
+ const queue = new ChatTurnQueue(
24478
+ sendTurn,
24479
+ (count) => tui.setQueuedMessageCount(count),
24480
+ (error) => tui.showError(error instanceof Error ? error.message : String(error))
24481
+ );
24023
24482
  await new Promise((resolve) => {
24024
24483
  tui = new ChatTUI({
24025
24484
  title: session.label,
24026
24485
  subtitle: session.chatTitle,
24027
24486
  onSend: (text) => {
24028
- void sendTurn(text);
24487
+ queue.enqueue(text);
24029
24488
  },
24030
24489
  onExit: () => {
24490
+ queue.close();
24031
24491
  feedController.abort();
24032
24492
  tui.stop();
24033
24493
  resolve();
@@ -25169,7 +25629,7 @@ var topLevelCommands = [
25169
25629
  mutates: true,
25170
25630
  args: [{ name: "phone", description: "E.164 phone number (optional; prompts if omitted)" }],
25171
25631
  handler: async (hctx) => {
25172
- const { accountVerifyPhoneCommand } = await import("./account-verify-phone-CVPAKVHQ.js");
25632
+ const { accountVerifyPhoneCommand } = await import("./account-verify-phone-SH7TN3KG.js");
25173
25633
  await accountVerifyPhoneCommand(hctx);
25174
25634
  }
25175
25635
  },
@@ -25295,6 +25755,7 @@ export {
25295
25755
  createPublicAuthenticatedContext,
25296
25756
  createPublicContext,
25297
25757
  crudCommands,
25758
+ describeOutboundCallReceipt,
25298
25759
  detectOutputFormat,
25299
25760
  devImportLocalCommand,
25300
25761
  extractPaginationMeta,