@skrr-ai/cli 0.1.231 → 0.1.233

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 (161) hide show
  1. package/README.md +42 -4
  2. package/bin/dev.cjs +4 -1
  3. package/bin/run.js +0 -15
  4. package/dist/base-command.d.ts +6 -11
  5. package/dist/base-command.js +34 -43
  6. package/dist/commands/agenda/plan.d.ts +2 -1
  7. package/dist/commands/agenda/plan.js +18 -4
  8. package/dist/commands/agent/message/context.d.ts +2 -0
  9. package/dist/commands/agent/message/context.js +18 -3
  10. package/dist/commands/agent/message/list.d.ts +22 -0
  11. package/dist/commands/agent/message/list.js +66 -0
  12. package/dist/commands/agent/message/send.d.ts +1 -1
  13. package/dist/commands/agent/message/send.js +1 -3
  14. package/dist/commands/agent/message/show.d.ts +14 -0
  15. package/dist/commands/agent/message/show.js +39 -0
  16. package/dist/commands/agents/chat.d.ts +4 -0
  17. package/dist/commands/agents/chat.js +79 -17
  18. package/dist/commands/agents/eval/list.d.ts +4 -0
  19. package/dist/commands/agents/eval/list.js +33 -0
  20. package/dist/commands/agents/eval/show.d.ts +1 -0
  21. package/dist/commands/agents/eval/show.js +19 -0
  22. package/dist/commands/agents/intuitions/generate.js +1 -1
  23. package/dist/commands/agents/intuitions/list.js +1 -1
  24. package/dist/commands/agents/permissions/policy.js +25 -2
  25. package/dist/commands/agents/spawn.js +61 -24
  26. package/dist/commands/agents/triggers/fire.js +1 -1
  27. package/dist/commands/agents/triggers/runs.js +3 -0
  28. package/dist/commands/code/acp.js +1 -1
  29. package/dist/commands/code/handover.d.ts +3 -3
  30. package/dist/commands/code/handover.js +12 -12
  31. package/dist/commands/code/index.d.ts +3 -8
  32. package/dist/commands/code/index.js +15 -21
  33. package/dist/commands/code/jobs/approve.d.ts +1 -11
  34. package/dist/commands/code/jobs/approve.js +3 -15
  35. package/dist/commands/code/jobs/cancel.js +3 -2
  36. package/dist/commands/code/jobs/index.js +1 -1
  37. package/dist/commands/code/jobs/list.js +4 -11
  38. package/dist/commands/code/jobs/run.js +13 -7
  39. package/dist/commands/code/jobs/show.js +52 -6
  40. package/dist/commands/code/run.js +1 -1
  41. package/dist/commands/commands.d.ts +1 -0
  42. package/dist/commands/commands.js +5 -1
  43. package/dist/commands/context.d.ts +1 -0
  44. package/dist/commands/context.js +1 -0
  45. package/dist/commands/duties/catalog/add.d.ts +18 -0
  46. package/dist/commands/duties/catalog/add.js +52 -0
  47. package/dist/commands/duties/catalog/index.d.ts +18 -0
  48. package/dist/commands/duties/catalog/index.js +88 -0
  49. package/dist/commands/duties/receipt.js +56 -1
  50. package/dist/commands/goals/plan-now.d.ts +5 -3
  51. package/dist/commands/goals/plan-now.js +21 -16
  52. package/dist/commands/goals/planner-compare.js +5 -3
  53. package/dist/commands/instructions/discovery.d.ts +10 -0
  54. package/dist/commands/instructions/discovery.js +74 -0
  55. package/dist/commands/runs/admission.d.ts +12 -0
  56. package/dist/commands/runs/admission.js +66 -0
  57. package/dist/commands/runs/events.d.ts +16 -0
  58. package/dist/commands/runs/events.js +89 -0
  59. package/dist/commands/runs/list.d.ts +27 -0
  60. package/dist/commands/runs/list.js +151 -0
  61. package/dist/commands/runs/show.d.ts +14 -0
  62. package/dist/commands/runs/show.js +273 -0
  63. package/dist/commands/runs/stop.d.ts +15 -0
  64. package/dist/commands/runs/stop.js +105 -0
  65. package/dist/commands/runs/transcript.d.ts +19 -0
  66. package/dist/commands/runs/transcript.js +178 -0
  67. package/dist/commands/tasks/attachments/download.d.ts +1 -0
  68. package/dist/commands/tasks/attachments/download.js +6 -4
  69. package/dist/commands/tasks/attachments/source.d.ts +6 -0
  70. package/dist/commands/tasks/attachments/source.js +18 -0
  71. package/dist/commands/tasks/chat/exchange.d.ts +0 -14
  72. package/dist/commands/tasks/chat/exchange.js +8 -39
  73. package/dist/commands/tasks/chat/reply-run.d.ts +15 -0
  74. package/dist/commands/tasks/chat/reply-run.js +69 -0
  75. package/dist/commands/tasks/complete.js +1 -1
  76. package/dist/commands/tasks/lifecycle/transition.d.ts +1 -0
  77. package/dist/commands/tasks/lifecycle/transition.js +51 -13
  78. package/dist/commands/tasks/operations/show.js +5 -0
  79. package/dist/commands/tasks/result/submit.js +4 -2
  80. package/dist/commands/tasks/retry.js +25 -16
  81. package/dist/commands/tasks/runs.js +7 -0
  82. package/dist/commands/tasks/start-receipt.js +8 -8
  83. package/dist/commands/tasks/start.js +12 -1
  84. package/dist/commands/triggers/audit.js +3 -1
  85. package/dist/commands/triggers/fire-detail.js +4 -1
  86. package/dist/commands/triggers/fire.js +1 -1
  87. package/dist/commands/usage.d.ts +1 -0
  88. package/dist/commands/usage.js +1 -0
  89. package/dist/generated/agent-guides.json +350 -777
  90. package/dist/help.d.ts +2 -7
  91. package/dist/help.js +13 -7
  92. package/dist/hooks/init.js +10 -0
  93. package/dist/lib/agent-chat-queue.d.ts +2 -1
  94. package/dist/lib/agent-chat-queue.js +26 -21
  95. package/dist/lib/agent-evals.d.ts +1 -1
  96. package/dist/lib/agent-evals.js +13 -3
  97. package/dist/lib/agent-guides.d.ts +3 -5
  98. package/dist/lib/agent-guides.js +12 -13
  99. package/dist/lib/agent-runs.d.ts +101 -0
  100. package/dist/lib/agent-runs.js +350 -0
  101. package/dist/lib/agentic-stream.d.ts +13 -1
  102. package/dist/lib/agentic-stream.js +165 -81
  103. package/dist/lib/api-fetch.d.ts +4 -2
  104. package/dist/lib/api-fetch.js +11 -5
  105. package/dist/lib/code-handover.d.ts +2 -3
  106. package/dist/lib/code-handover.js +4 -6
  107. package/dist/lib/command-manifest.d.ts +1 -6
  108. package/dist/lib/command-manifest.js +86 -13
  109. package/dist/lib/communication-history.d.ts +27 -0
  110. package/dist/lib/communication-history.js +45 -0
  111. package/dist/lib/config.d.ts +2 -3
  112. package/dist/lib/config.js +2 -3
  113. package/dist/lib/duties.d.ts +5 -1
  114. package/dist/lib/duties.js +4 -0
  115. package/dist/lib/execution-history.d.ts +34 -0
  116. package/dist/lib/execution-history.js +7 -0
  117. package/dist/lib/first-party-harness-broker.d.ts +1 -1
  118. package/dist/lib/first-party-harness-broker.js +3 -5
  119. package/dist/lib/format.d.ts +1 -0
  120. package/dist/lib/format.js +18 -0
  121. package/dist/lib/guide-pointer.d.ts +5 -1
  122. package/dist/lib/guide-pointer.js +21 -2
  123. package/dist/lib/hosted-job-status.d.ts +4 -0
  124. package/dist/lib/hosted-job-status.js +19 -0
  125. package/dist/lib/inbound-messages.d.ts +2 -0
  126. package/dist/lib/inbound-messages.js +5 -0
  127. package/dist/lib/intuition-look.js +20 -4
  128. package/dist/lib/memory-history-session.d.ts +8 -4
  129. package/dist/lib/memory-history-session.js +30 -23
  130. package/dist/lib/roles.d.ts +2 -2
  131. package/dist/lib/schedule.d.ts +4 -0
  132. package/dist/lib/schedule.js +4 -3
  133. package/dist/lib/task-agent-run.d.ts +4 -0
  134. package/dist/lib/task-agent-run.js +15 -0
  135. package/dist/lib/task-execution.d.ts +1 -1
  136. package/dist/lib/task-execution.js +3 -19
  137. package/dist/lib/task-extras.d.ts +11 -1
  138. package/dist/lib/task-extras.js +15 -1
  139. package/dist/lib/task-transcript.js +3 -8
  140. package/dist/lib/triggers.d.ts +5 -36
  141. package/dist/lib/triggers.js +48 -33
  142. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/daemonWire.d.ts +9 -0
  143. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/daemonWire.js +40 -3
  144. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/harnessCommand.d.ts +37 -0
  145. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/harnessCommand.js +59 -0
  146. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/toolApprovalSignature.d.ts +62 -0
  147. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/toolApprovalSignature.js +56 -0
  148. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/daemonWire.d.ts +9 -0
  149. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/daemonWire.js +34 -3
  150. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/harnessCommand.d.ts +37 -0
  151. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/harnessCommand.js +57 -0
  152. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/toolApprovalSignature.d.ts +62 -0
  153. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/toolApprovalSignature.js +51 -0
  154. package/dist/node_modules/@skrr-ai/auth-core/package.json +10 -0
  155. package/dist/node_modules/@skrr-ai/data-provider/index.js +12259 -12160
  156. package/docs/v1/quickstart.md +18 -0
  157. package/oclif.manifest.json +3405 -2112
  158. package/package.json +6 -2
  159. package/skills/skrr/SKILL.md +14 -0
  160. package/dist/commands/triggers/runs.d.ts +0 -22
  161. package/dist/commands/triggers/runs.js +0 -58
@@ -38,6 +38,7 @@ const dpop_auth_1 = require("./dpop-auth");
38
38
  const SQUASH_RE = /\s+/g;
39
39
  const HANDLE_PERMISSION_RE = /^y(es)?$/i;
40
40
  const TO_WEB_SOCKET_ORIGIN_RE = /\/$/;
41
+ const CLOUD_STREAM_RESET_NOTICE = 'cloud-stream-reset';
41
42
  /**
42
43
  * Why a question was dismissed when no terminal exists to ask it on. It is the
43
44
  * REASON for a dismissal, never an answer: it travels as the value of the
@@ -694,7 +695,10 @@ function projectSessionNotices(envelopes) {
694
695
  const out = [];
695
696
  for (const envelope of envelopes) {
696
697
  const ev = envelope?.ev;
697
- if (ev?.t !== 'service' || typeof ev.notice !== 'string' || typeof ev.text !== 'string') {
698
+ if (ev?.t !== 'service' ||
699
+ typeof ev.notice !== 'string' ||
700
+ ev.notice === CLOUD_STREAM_RESET_NOTICE ||
701
+ typeof ev.text !== 'string') {
698
702
  continue;
699
703
  }
700
704
  out.push({ type: 'session.notice', notice: ev.notice, message: ev.text });
@@ -849,6 +853,8 @@ class AgenticStreamClient {
849
853
  // Envelope keys already applied, so a re-delivered `session:output` frame is
850
854
  // not appended twice (OSK-4834). Cleared on `execution:stream-reset`.
851
855
  seenEnvelopes = new Set();
856
+ /** Durable reset IDs observed on this response's exact session stream. */
857
+ canonicalResetIds = new Set();
852
858
  /**
853
859
  * Lifecycle events already emitted, by their own identity (OSK-7632/7689/7709).
854
860
  *
@@ -913,6 +919,7 @@ class AgenticStreamClient {
913
919
  /** Releases a connect wait still in flight; `close()` calls it. */
914
920
  abandonConnectWait = null;
915
921
  reconciling = false;
922
+ admittedResponseMessageId;
916
923
  responseMessageId;
917
924
  lastEvent;
918
925
  /**
@@ -939,6 +946,9 @@ class AgenticStreamClient {
939
946
  if (options.fixedCopilotProbe && (options.approveTools || options.input))
940
947
  throw new Error('Fixed Copilot probe cannot use blanket or terminal approval');
941
948
  this.options = options;
949
+ this.admittedResponseMessageId =
950
+ options.resumeRecordedResponseId || options.admittedResponseMessageId || undefined;
951
+ this.responseMessageId = this.admittedResponseMessageId;
942
952
  }
943
953
  async run() {
944
954
  const result = new Promise((resolve, reject) => {
@@ -946,8 +956,7 @@ class AgenticStreamClient {
946
956
  this.reject = reject;
947
957
  });
948
958
  if (this.options.resumeRecordedResponseId) {
949
- this.responseMessageId = this.options.resumeRecordedResponseId;
950
- const hasTerminal = await this.probeTerminal('inbound_replay');
959
+ const hasTerminal = await this.probeTerminal('idempotent_replay');
951
960
  if (hasTerminal || this.handover || this.closed)
952
961
  return result;
953
962
  }
@@ -1093,10 +1102,12 @@ class AgenticStreamClient {
1093
1102
  reconciledFrom: 'durable_record',
1094
1103
  reason,
1095
1104
  ...(terminal.error ? { message: terminal.error, error: terminal.error } : {}),
1105
+ ...(terminal.code ? { code: terminal.code } : {}),
1106
+ ...(terminal.errorType ? { errorType: terminal.errorType } : {}),
1096
1107
  ...(typeof terminal.text === 'string' ? { result: terminal.text } : {}),
1097
1108
  ...(terminal.publicProjection ? { publicProjection: terminal.publicProjection } : {}),
1098
1109
  };
1099
- if (reason === 'inbound_replay')
1110
+ if (reason === 'idempotent_replay')
1100
1111
  this.finishAfterReplay(terminal.status, event);
1101
1112
  else
1102
1113
  this.finish(terminal.status, event);
@@ -1573,6 +1584,46 @@ class AgenticStreamClient {
1573
1584
  answerText() {
1574
1585
  return (0, widgetTerminalText_1.widgetsAsText)(this.accumulated, { final: false });
1575
1586
  }
1587
+ matchesAdmittedResponse(messageId) {
1588
+ return (!this.admittedResponseMessageId ||
1589
+ typeof messageId !== 'string' ||
1590
+ !messageId ||
1591
+ messageId === this.admittedResponseMessageId);
1592
+ }
1593
+ /** Match the binding used by data-provider's canonical retry reducer. */
1594
+ canonicalResetId(event, value) {
1595
+ const env = value;
1596
+ const { sessionId } = this.options;
1597
+ const responseMessageId = this.admittedResponseMessageId;
1598
+ if (env?.ev?.t !== 'service' ||
1599
+ env.ev.notice !== CLOUD_STREAM_RESET_NOTICE ||
1600
+ !responseMessageId ||
1601
+ env.messageId !== responseMessageId ||
1602
+ (event.sessionId ?? env.sessionId) !== sessionId ||
1603
+ (env.sessionId != null && env.sessionId !== sessionId) ||
1604
+ env.role !== 'agent' ||
1605
+ env.subagent ||
1606
+ (env.agentId != null && (typeof env.agentId !== 'string' || !env.agentId)) ||
1607
+ (env.turn !== responseMessageId &&
1608
+ (env.sessionId !== sessionId || env.turn !== `${sessionId}:${responseMessageId}`)) ||
1609
+ typeof env.__seq !== 'number' ||
1610
+ !Number.isSafeInteger(env.__seq) ||
1611
+ env.__seq <= 0 ||
1612
+ typeof env.id !== 'string' ||
1613
+ !env.id)
1614
+ return undefined;
1615
+ return env.id;
1616
+ }
1617
+ resetAttemptOutput() {
1618
+ this.accumulated = '';
1619
+ this.chatReply = undefined;
1620
+ this.publicProjection = undefined;
1621
+ this.textJoiner.reset();
1622
+ this.renderedText = '';
1623
+ this.lastJsonlText = null;
1624
+ this.startedDaemonCalls.clear();
1625
+ this.orphanToolEnd = false;
1626
+ }
1576
1627
  applySessionOutput(event) {
1577
1628
  // The agent's words arrive HERE for agentic runs, inside `envelopes`, and
1578
1629
  // `event.text` is null. Normalising the frame without reading them meant
@@ -1585,73 +1636,102 @@ class AgenticStreamClient {
1585
1636
  // chatter in `response`.
1586
1637
  // Dedupe re-delivered envelopes (session room + user room + join replay):
1587
1638
  // append and reprint only the ones we have not applied yet (OSK-4834).
1588
- const rawEnvelopes = event.envelopes;
1589
- if (Array.isArray(rawEnvelopes) && rawEnvelopes.length > 0) {
1590
- const fresh = unseenEnvelopes(event, this.seenEnvelopes);
1591
- if (fresh.length === 0)
1592
- return; // a pure re-delivery — drop it whole
1593
- const scoped = { ...event, envelopes: fresh };
1594
- if (fresh.some((env) => env?.ev?.t === 'text' &&
1595
- env.ev?.publicProjection ===
1596
- 'lookback_answer_v1'))
1597
- this.publicProjection = 'lookback_answer_v1';
1598
- // Note what never arrived before folding this batch in (OSK-7631,
1599
- // OSK-13518). Checked against the FRESH set: a re-delivery carries old
1600
- // seqs and would read as a gap that never happened.
1601
- this.noteSeqGap(fresh);
1602
- this.noteDaemonToolEnvelopes(fresh);
1603
- // The machine's own turn-end is what the server repairs or settles the
1604
- // row on; seeing it relayed is the moment the record is about to move.
1605
- if (this.handover &&
1606
- fresh.some((env) => env?.ev?.t === 'turn-end')) {
1607
- this.requestHandoverRead();
1608
- }
1609
- for (const envelope of fresh) {
1610
- const { ev, messageId, subagent } = envelope;
1611
- if (ev?.t !== 'turn-end' ||
1612
- ev.status !== 'completed' ||
1613
- subagent ||
1614
- (messageId && this.responseMessageId && messageId !== this.responseMessageId))
1615
- continue;
1616
- const start = ev.chatReplyStart;
1617
- if (start === null || (typeof start === 'number' && Number.isSafeInteger(start) && start >= 0)) {
1618
- this.chatReply = {
1619
- start,
1620
- text: ev.responseText ?? '',
1621
- originalLength: ev.responseTextCut?.originalLength,
1622
- };
1623
- }
1624
- }
1625
- const envelopeText = envelopesText(scoped, this.textJoiner, this.accumulated);
1626
- if (envelopeText) {
1627
- this.accumulated += envelopeText;
1628
- this.emit({ ...scoped, type: 'text.delta', text: this.answerText() });
1629
- }
1630
- // A daemon-routed turn carries its tool calls HERE and nowhere else.
1631
- // Projecting them gives both execution paths one vocabulary (OSK-7730).
1632
- for (const projected of projectDaemonToolEvents(fresh, this.toolNamesByCall)) {
1633
- this.emitToolEvent({ ...projected, sessionId: this.options.sessionId });
1634
- }
1635
- // Notices meant for the person — a local harness that could not resume
1636
- // its previous session and started a fresh one (OSK-12131). A plain
1637
- // `service` line is diagnostic chatter and stays in the envelope; one
1638
- // marked `notice` is said out loud.
1639
- for (const notice of projectSessionNotices(fresh)) {
1640
- this.emit({ ...notice, sessionId: this.options.sessionId });
1641
- }
1642
- // Who decided each permission request — a person (and where), the
1643
- // mode, a policy — said beside the decision (OSK-12113).
1644
- for (const resolved of projectPermissionResolutions(fresh, this.toolNamesByPermission)) {
1645
- this.emit({ ...resolved, sessionId: this.options.sessionId });
1646
- }
1647
- this.emit({ ...scoped, type: 'session.output' });
1639
+ if (!Array.isArray(event.envelopes) || event.envelopes.length === 0) {
1640
+ this.emit({ ...event, type: 'session.output' });
1648
1641
  return;
1649
1642
  }
1650
- this.emit({ ...event, type: 'session.output' });
1643
+ const delivered = unseenEnvelopes(event, this.seenEnvelopes);
1644
+ if (delivered.length === 0)
1645
+ return;
1646
+ let from = 0;
1647
+ for (const [index, envelope] of delivered.entries()) {
1648
+ const resetId = this.canonicalResetId(event, envelope);
1649
+ if (!resetId)
1650
+ continue;
1651
+ this.applySessionEnvelopeBatch(event, delivered.slice(from, index));
1652
+ from = index + 1;
1653
+ if (this.canonicalResetIds.has(resetId))
1654
+ continue;
1655
+ // The marker replaces the answer at this sequence. Replay and raw
1656
+ // output still follow the same session cursor and envelope identities.
1657
+ this.noteSeqGap([envelope]);
1658
+ this.canonicalResetIds.add(resetId);
1659
+ this.resetAttemptOutput();
1660
+ this.emit({
1661
+ type: 'text.reset',
1662
+ sessionId: this.options.sessionId,
1663
+ responseMessageId: this.admittedResponseMessageId,
1664
+ resetId,
1665
+ });
1666
+ }
1667
+ this.applySessionEnvelopeBatch(event, from === 0 ? delivered : delivered.slice(from));
1668
+ this.emit({ ...event, envelopes: delivered, type: 'session.output' });
1669
+ }
1670
+ applySessionEnvelopeBatch(event, delivered) {
1671
+ if (delivered.length === 0)
1672
+ return;
1673
+ // The session's sequence and raw output include every turn. Use only
1674
+ // this Chat's server-stamped reply envelopes for its answer and tools.
1675
+ this.noteSeqGap(delivered);
1676
+ const fresh = delivered.filter((value) => {
1677
+ const env = value;
1678
+ return env?.role !== 'agent' || this.matchesAdmittedResponse(env.messageId);
1679
+ });
1680
+ const scoped = { ...event, envelopes: fresh };
1681
+ if (fresh.some((env) => env?.ev?.t === 'text' &&
1682
+ env.ev?.publicProjection ===
1683
+ 'lookback_answer_v1'))
1684
+ this.publicProjection = 'lookback_answer_v1';
1685
+ this.noteDaemonToolEnvelopes(fresh);
1686
+ // The machine's own turn-end is what the server repairs or settles the
1687
+ // row on; seeing it relayed is the moment the record is about to move.
1688
+ if (this.handover &&
1689
+ fresh.some((env) => env?.ev?.t === 'turn-end')) {
1690
+ this.requestHandoverRead();
1691
+ }
1692
+ for (const envelope of fresh) {
1693
+ const { ev, messageId, subagent } = envelope;
1694
+ if (ev?.t !== 'turn-end' ||
1695
+ ev.status !== 'completed' ||
1696
+ subagent ||
1697
+ (messageId && this.responseMessageId && messageId !== this.responseMessageId))
1698
+ continue;
1699
+ const start = ev.chatReplyStart;
1700
+ if (start === null || (typeof start === 'number' && Number.isSafeInteger(start) && start >= 0)) {
1701
+ this.chatReply = {
1702
+ start,
1703
+ text: ev.responseText ?? '',
1704
+ originalLength: ev.responseTextCut?.originalLength,
1705
+ };
1706
+ }
1707
+ }
1708
+ const envelopeText = envelopesText(scoped, this.textJoiner, this.accumulated);
1709
+ if (envelopeText) {
1710
+ this.accumulated += envelopeText;
1711
+ this.emit({ ...scoped, type: 'text.delta', text: this.answerText() });
1712
+ }
1713
+ // A daemon-routed turn carries its tool calls HERE and nowhere else.
1714
+ // Projecting them gives both execution paths one vocabulary (OSK-7730).
1715
+ for (const projected of projectDaemonToolEvents(fresh, this.toolNamesByCall)) {
1716
+ this.emitToolEvent({ ...projected, sessionId: this.options.sessionId });
1717
+ }
1718
+ // Notices meant for the person — a local harness that could not resume
1719
+ // its previous session and started a fresh one (OSK-12131). A plain
1720
+ // `service` line is diagnostic chatter and stays in the envelope; one
1721
+ // marked `notice` is said out loud.
1722
+ for (const notice of projectSessionNotices(fresh)) {
1723
+ this.emit({ ...notice, sessionId: this.options.sessionId });
1724
+ }
1725
+ // Who decided each permission request — a person (and where), the
1726
+ // mode, a policy — said beside the decision (OSK-12113).
1727
+ for (const resolved of projectPermissionResolutions(fresh, this.toolNamesByPermission)) {
1728
+ this.emit({ ...resolved, sessionId: this.options.sessionId });
1729
+ }
1651
1730
  }
1652
1731
  installHandlers() {
1653
1732
  const socket = this.socket;
1654
1733
  const match = (event) => !event.sessionId || event.sessionId === this.options.sessionId;
1734
+ const matchResponse = (event) => match(event) && this.matchesAdmittedResponse(event.responseMessageId);
1655
1735
  socket.on('connect', () => {
1656
1736
  socket.emit('session:join', this.sessionJoinPayload());
1657
1737
  this.emit({ type: 'transport.connected', sessionId: this.options.sessionId });
@@ -1694,7 +1774,7 @@ class AgenticStreamClient {
1694
1774
  this.emit({ ...event, type: 'run.started' });
1695
1775
  });
1696
1776
  socket.on('message:stream', (event) => {
1697
- if (!match(event))
1777
+ if (!match(event) || !this.matchesAdmittedResponse(event.messageId))
1698
1778
  return;
1699
1779
  if (event.publicProjection === 'lookback_answer_v1')
1700
1780
  this.publicProjection = event.publicProjection;
@@ -1704,7 +1784,7 @@ class AgenticStreamClient {
1704
1784
  this.accumulated = text;
1705
1785
  else if (delta)
1706
1786
  this.accumulated += delta;
1707
- if (typeof event.messageId === 'string')
1787
+ if (!this.admittedResponseMessageId && typeof event.messageId === 'string')
1708
1788
  this.responseMessageId = event.messageId;
1709
1789
  this.emit({ ...event, type: 'text.delta', text: this.answerText() });
1710
1790
  });
@@ -1730,21 +1810,20 @@ class AgenticStreamClient {
1730
1810
  this.emit({ ...event, type: 'run.queued' });
1731
1811
  });
1732
1812
  socket.on('execution:stream-reset', (event) => {
1733
- if (!match(event))
1813
+ if (!matchResponse(event))
1734
1814
  return;
1735
- this.accumulated = '';
1736
- this.chatReply = undefined;
1737
- this.publicProjection = undefined;
1738
- this.textJoiner.reset();
1739
- this.renderedText = '';
1815
+ if (event.sessionId === this.options.sessionId &&
1816
+ event.responseMessageId === this.admittedResponseMessageId &&
1817
+ typeof event.resetId === 'string' &&
1818
+ this.canonicalResetIds.has(event.resetId))
1819
+ return;
1820
+ this.resetAttemptOutput();
1740
1821
  // Seqs restart with the stream, so a fresh low seq is not a gap.
1741
1822
  this.highestSeq = 0;
1742
1823
  this.replayGeneration += 1;
1743
1824
  this.pendingEnvelopes.clear();
1744
1825
  this.reportedGap = false;
1745
1826
  this.lostRanges.length = 0;
1746
- this.startedDaemonCalls.clear();
1747
- this.orphanToolEnd = false;
1748
1827
  // A reset restarts the stream, so envelope seqs may repeat; forget the
1749
1828
  // seen keys or the fresh post-reset text would be deduped away (OSK-4834).
1750
1829
  this.seenEnvelopes.clear();
@@ -1752,7 +1831,7 @@ class AgenticStreamClient {
1752
1831
  this.emit({ ...event, type: 'text.reset' });
1753
1832
  });
1754
1833
  socket.on('message:stream-end', (event) => {
1755
- if (!match(event))
1834
+ if (!matchResponse(event))
1756
1835
  return;
1757
1836
  // Byte-identical repeats, including `endedAt` (OSK-7689). Key on the
1758
1837
  // message the stream ended for, falling back to the session.
@@ -1764,7 +1843,7 @@ class AgenticStreamClient {
1764
1843
  // hand-over failure through another room, or anything a later writer sends
1765
1844
  // — is a reason to read the record, not a verdict of its own (OSK-13543).
1766
1845
  socket.on('execution:complete', (event) => {
1767
- if (!match(event))
1846
+ if (!matchResponse(event))
1768
1847
  return;
1769
1848
  if (this.handover)
1770
1849
  this.requestHandoverRead();
@@ -1772,7 +1851,7 @@ class AgenticStreamClient {
1772
1851
  this.finish('completed', event);
1773
1852
  });
1774
1853
  socket.on('execution:aborted', (event) => {
1775
- if (!match(event))
1854
+ if (!matchResponse(event))
1776
1855
  return;
1777
1856
  if (typeof event.permissionEpoch === 'string' &&
1778
1857
  this.permissionEpochs.has(this.options.sessionId) &&
@@ -1784,7 +1863,7 @@ class AgenticStreamClient {
1784
1863
  this.finish('aborted', event);
1785
1864
  });
1786
1865
  socket.on('execution:cancelled', (event) => {
1787
- if (!match(event))
1866
+ if (!matchResponse(event))
1788
1867
  return;
1789
1868
  if (typeof event.permissionEpoch === 'string' &&
1790
1869
  this.permissionEpochs.has(this.options.sessionId) &&
@@ -1796,7 +1875,7 @@ class AgenticStreamClient {
1796
1875
  this.finish('aborted', event);
1797
1876
  });
1798
1877
  socket.on('execution:error', (event) => {
1799
- if (!match(event))
1878
+ if (!matchResponse(event))
1800
1879
  return;
1801
1880
  if (this.handover)
1802
1881
  this.requestHandoverRead();
@@ -2488,7 +2567,9 @@ class AgenticStreamClient {
2488
2567
  const previous = this.lastJsonlText;
2489
2568
  const text = event.text;
2490
2569
  this.lastJsonlText = text;
2491
- const appended = text.startsWith(previous) ? text.slice(previous.length) : undefined;
2570
+ const appended = previous !== null && text.startsWith(previous)
2571
+ ? text.slice(previous.length)
2572
+ : undefined;
2492
2573
  if (!this.options.incrementalText) {
2493
2574
  return appended === undefined ? event : { ...event, delta: appended };
2494
2575
  }
@@ -2560,6 +2641,9 @@ class AgenticStreamClient {
2560
2641
  // resolved to on that machine (OSK-12111).
2561
2642
  output.write(`[run] model: ${event.harnessModel} (reported by the harness)\n`);
2562
2643
  }
2644
+ else if (event.type === 'text.reset') {
2645
+ output.write('\n[retry] Discarding the previous attempt.\n');
2646
+ }
2563
2647
  else if (event.type === 'text.delta' && typeof event.text === 'string') {
2564
2648
  // Print what is NEW. See `renderableDelta` — the old `\r` repaint could
2565
2649
  // not rewind past a newline, so a multi-line answer was reprinted once
@@ -7,8 +7,10 @@ export interface ApiFetchOptions {
7
7
  singleAttempt?: boolean;
8
8
  /** Override credential resolution — useful for tests. */
9
9
  credential?: ResolvedCredential;
10
- /** Exact admitted-session Memory history GET; never uses owner credentials. */
11
- sessionRead?: 'memory-history-v1';
10
+ /** Exact history GET on the currently bound Agent session. */
11
+ sessionRead?: 'memory-history-v1' | 'agent-history-v1';
12
+ /** Read in personal scope regardless of the human CLI's ambient workspace. */
13
+ workspaceScope?: 'personal';
12
14
  /**
13
15
  * Extra request headers. Added for `X-Idempotency-Key` (OSK-2806): the
14
16
  * shared data-provider transport takes no per-call options, so a replayed
@@ -105,7 +105,7 @@ exports.ApiFetchError = ApiFetchError;
105
105
  */
106
106
  async function apiFetch(pathOrUrl, opts = {}) {
107
107
  const historyRead = opts.sessionRead
108
- ? (0, memory_history_session_1.bindMemoryHistoryRead)(pathOrUrl, opts.method ?? 'GET')
108
+ ? (0, memory_history_session_1.bindHistoryRead)(pathOrUrl, opts.method ?? 'GET', process.env, opts.sessionRead)
109
109
  : null;
110
110
  const sessionCredential = historyRead
111
111
  ? { token: historyRead.token, source: 'env-token', kind: (0, credential_resolver_1.kindOf)(historyRead.token) }
@@ -246,7 +246,12 @@ async function apiFetch(pathOrUrl, opts = {}) {
246
246
  OVERSKY_AUTONOMOUS_SESSION: '1',
247
247
  OVERSKY_SESSION_WORKSPACE_ID: process.env.OVERSKY_SESSION_WORKSPACE_ID,
248
248
  }
249
- : process.env), url, method);
249
+ : opts.workspaceScope === 'personal'
250
+ ? {
251
+ OVERSKY_AUTONOMOUS_SESSION: process.env.OVERSKY_AUTONOMOUS_SESSION,
252
+ OVERSKY_SESSION_WORKSPACE_ID: process.env.OVERSKY_SESSION_WORKSPACE_ID,
253
+ }
254
+ : process.env), url, method);
250
255
  // E6: a 429 on a GET or an idempotency-keyed write is retried (bounded,
251
256
  // jittered, honouring Retry-After). The last 429's wait is kept for the error.
252
257
  let fetched;
@@ -358,15 +363,16 @@ async function apiFetch(pathOrUrl, opts = {}) {
358
363
  catch {
359
364
  /* ignore body read failures */
360
365
  }
366
+ const historyName = opts.sessionRead === 'memory-history-v1' ? 'Memory' : 'Agent';
361
367
  const unsupportedHistory = historyRead &&
362
368
  res.status === 404 &&
363
369
  (!code || ['API_ROUTE_NOT_FOUND', 'ROUTE_NOT_FOUND'].includes(code));
364
370
  const error = new ApiFetchError(unsupportedHistory
365
- ? 'This server does not support session-scoped Memory history. Upgrade the server before retrying; owner-credential fallback is disabled.'
366
- : `HTTP ${res.status} ${res.statusText} — ${method} ${pathOrUrl}`, res.status, text, unsupportedHistory ? 'MEMORY_HISTORY_API_UNSUPPORTED' : code, method, res.headers.get('x-request-id') || undefined);
371
+ ? `This server does not support session-scoped ${historyName} history. Upgrade the server before retrying; owner-credential fallback is disabled.`
372
+ : `HTTP ${res.status} ${res.statusText} — ${method} ${pathOrUrl}`, res.status, text, unsupportedHistory ? `${historyName.toUpperCase()}_HISTORY_API_UNSUPPORTED` : code, method, res.headers.get('x-request-id') || undefined);
367
373
  if (historyRead && res.status === 401) {
368
374
  error.recoveryHint =
369
- 'Reconnect the managed Agent session and retry. If the refusal persists, check that this server supports session-scoped Memory history. Owner-credential fallback is disabled.';
375
+ `Reconnect the managed Agent session and retry. If the refusal persists, check that this server supports session-scoped ${historyName} history. Owner-credential fallback is disabled.`;
370
376
  }
371
377
  error.requestPath = (0, write_outcome_1.requestPathOf)(url);
372
378
  if (brokerFailure)
@@ -68,10 +68,9 @@ export interface EngineSessionExport {
68
68
  redactions?: unknown;
69
69
  }
70
70
  /**
71
- * Parse the export envelope, or null when the output is not the contract —
72
- * an engine that predates `session export` cannot produce `{version, messages[]}`.
71
+ * Only accept a contract envelope for the requested engine session.
73
72
  */
74
- export declare function parseSessionExportEnvelope(stdout: string): EngineSessionExport | null;
73
+ export declare function parseSessionExportEnvelope(stdout: string, sessionId: string): EngineSessionExport | null;
75
74
  export type SessionExportFailureKind = 'unsupported' | 'unknown-session';
76
75
  /**
77
76
  * Classify a failed `session export` spawn (an `execFileSync` throw).
@@ -88,10 +88,9 @@ function composeHandoverPrompt(input) {
88
88
  .join('\n');
89
89
  }
90
90
  /**
91
- * Parse the export envelope, or null when the output is not the contract —
92
- * an engine that predates `session export` cannot produce `{version, messages[]}`.
91
+ * Only accept a contract envelope for the requested engine session.
93
92
  */
94
- function parseSessionExportEnvelope(stdout) {
93
+ function parseSessionExportEnvelope(stdout, sessionId) {
95
94
  let parsed;
96
95
  try {
97
96
  parsed = JSON.parse(stdout);
@@ -102,9 +101,8 @@ function parseSessionExportEnvelope(stdout) {
102
101
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
103
102
  return null;
104
103
  const env = parsed;
105
- if (env.version === undefined || env.version === null)
106
- return null;
107
- if (!Array.isArray(env.messages))
104
+ if (env.version === undefined || env.version === null || env.sessionId !== sessionId ||
105
+ !Array.isArray(env.messages) || typeof env.truncated !== 'boolean')
108
106
  return null;
109
107
  return env;
110
108
  }
@@ -26,10 +26,5 @@ export declare function manifestPath(rootDir: string): string;
26
26
  export declare function loadCommandManifest(rootDir: string): CommandManifest;
27
27
  export declare function commandKey(command: string): string;
28
28
  export declare function visibleCommandEntries(manifest: CommandManifest): VisibleCommandEntry[];
29
- /**
30
- * Narrow a command catalog by every word the user supplied. A multi-word
31
- * discovery query such as "spaces templates" is a concept, not a request for
32
- * every command containing either generic word. Keeping the matching here
33
- * also makes the same semantics available to future catalog surfaces.
34
- */
29
+ /** Prefer command names and known intents. A match in an example ranks below either. */
35
30
  export declare function searchVisibleCommandEntries(entries: VisibleCommandEntry[], query: string | undefined): VisibleCommandEntry[];
@@ -43,7 +43,55 @@ const fs = __importStar(require("node:fs"));
43
43
  const path = __importStar(require("node:path"));
44
44
  const COMMAND_KEY_RE = /\s+/g;
45
45
  const VISIBLE_COMMAND_ENTRIES_RE = /:/g;
46
- const SEARCH_VISIBLE_COMMAND_ENTRIES_RE = /\s+/;
46
+ const SEARCH_WORDS = /[\p{L}\p{N}]+/gu;
47
+ const SEARCH_STOP_WORDS = new Set([
48
+ 'a',
49
+ 'an',
50
+ 'am',
51
+ 'for',
52
+ 'i',
53
+ 'in',
54
+ 'me',
55
+ 'my',
56
+ 'of',
57
+ 'on',
58
+ 'please',
59
+ 'the',
60
+ 'to',
61
+ ]);
62
+ const commandIntents = new Map([
63
+ ['context', ['check who I am', 'check write attribution', '检查身份']],
64
+ ['tasks:list', ['find a task', 'search tasks by title', 'look up existing tasks', '查找任务']],
65
+ ['tasks:show', ['read task details', 'inspect task state', '查看任务']],
66
+ [
67
+ 'tasks:complete',
68
+ [
69
+ 'finish a task',
70
+ 'close out a task',
71
+ 'submit for review',
72
+ 'submit for independent review',
73
+ 'submit result for review',
74
+ 'submit result for independent review',
75
+ 'send to independent review',
76
+ '完成任务',
77
+ '关闭任务',
78
+ '提交评审',
79
+ '提交审核',
80
+ '提交审阅',
81
+ '提交独立评审',
82
+ '交给独立评审',
83
+ '移交独立评审',
84
+ '送交独立评审',
85
+ ],
86
+ ],
87
+ ['tasks:result:submit', ['submit a result', 'record a result', '提交结果']],
88
+ [
89
+ 'tasks:review',
90
+ ['request changes', 'return result for changes', '退回补充证据', '要求补充证据'],
91
+ ],
92
+ ['tasks:updates:add', ['record verification', 'report task progress', '记录验证', '记录进展']],
93
+ ['agent:message:list', ['message history', 'previous owner messages', '沟通历史', '聊天记录']],
94
+ ]);
47
95
  let sourceManifest;
48
96
  /** The source launcher supplies the catalog generated from the same commands it runs. */
49
97
  function useSourceCommandManifest(root, manifest) {
@@ -77,20 +125,45 @@ function visibleCommandEntries(manifest) {
77
125
  examples: command.examples ?? [],
78
126
  }));
79
127
  }
80
- /**
81
- * Narrow a command catalog by every word the user supplied. A multi-word
82
- * discovery query such as "spaces templates" is a concept, not a request for
83
- * every command containing either generic word. Keeping the matching here
84
- * also makes the same semantics available to future catalog surfaces.
85
- */
128
+ function searchWords(text) {
129
+ return (text.normalize('NFKC').toLowerCase().match(SEARCH_WORDS) ?? [])
130
+ .filter((word) => !SEARCH_STOP_WORDS.has(word))
131
+ .map((word) => word.replace(/^(\w{3,}[^s])s$/, '$1'));
132
+ }
133
+ // Chinese requests often put the named action inside a longer unspaced phrase.
134
+ function includesChineseIntent(query, intent) {
135
+ return intent.length >= 4 && /\p{Script=Han}/u.test(intent) && query.includes(intent);
136
+ }
137
+ /** Prefer command names and known intents. A match in an example ranks below either. */
86
138
  function searchVisibleCommandEntries(entries, query) {
87
- const terms = query?.trim().toLowerCase().split(SEARCH_VISIBLE_COMMAND_ENTRIES_RE).filter(Boolean) ?? [];
88
- if (terms.length === 0)
139
+ if (!query?.trim())
89
140
  return entries;
90
- return entries.filter((entry) => {
141
+ const terms = searchWords(query);
142
+ if (!terms.length)
143
+ return [];
144
+ const exact = terms.join(' ');
145
+ const includesAll = (words) => terms.every((term) => words.includes(term));
146
+ const matches = entries.flatMap((entry) => {
91
147
  if (entry.id === 'commands')
92
- return false;
93
- const searchable = [entry.command, entry.description, ...entry.examples].join(' ').toLowerCase();
94
- return terms.every((term) => searchable.includes(term));
148
+ return [];
149
+ const names = [entry.command, ...entry.aliases].map(searchWords);
150
+ const intents = (commandIntents.get(entry.id) ?? []).map(searchWords);
151
+ const phrases = intents.map((words) => words.join(' '));
152
+ const name = names[0];
153
+ let rank = 0;
154
+ if (names.some((words) => words.join(' ') === exact))
155
+ rank = 5;
156
+ else if (phrases.includes(exact))
157
+ rank = 4;
158
+ else if (names.some(includesAll) ||
159
+ intents.some(includesAll) ||
160
+ phrases.some((phrase) => includesChineseIntent(exact, phrase)))
161
+ rank = 3;
162
+ else if (includesAll([...name, ...searchWords(entry.description)]))
163
+ rank = 2;
164
+ else if (entry.examples.some((example) => includesAll([...name, ...searchWords(example)])))
165
+ rank = 1;
166
+ return rank ? [{ entry, rank }] : [];
95
167
  });
168
+ return matches.sort((a, b) => b.rank - a.rank).map(({ entry }) => entry);
96
169
  }
@@ -0,0 +1,27 @@
1
+ import { type AgentSessionMessageContext } from './message-intent';
2
+ export declare function resolveHistorySession(requireHumanAuth: () => void): AgentSessionMessageContext | null;
3
+ export declare function readBoundAgentHistory<T>(sessionId: string, path: string, query: Record<string, string | number | undefined>): Promise<T>;
4
+ export declare const historyTimeFlags: {
5
+ from: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
6
+ to: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ since: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ timezone: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ };
10
+ export type CommunicationHistoryItem = {
11
+ messageId: string;
12
+ side: 'agent' | 'user';
13
+ source: string;
14
+ ownerAuthored?: boolean;
15
+ at: string;
16
+ kind?: string;
17
+ excerpt?: string;
18
+ retracted?: boolean;
19
+ };
20
+ export type CommunicationHistoryResult = {
21
+ items?: CommunicationHistoryItem[];
22
+ message?: CommunicationHistoryItem;
23
+ nextCursor?: string | null;
24
+ coverage: 'complete' | 'partial';
25
+ };
26
+ export declare function readCommunicationHistory(operation: 'list' | 'show' | 'outreach', agentId: string, session: AgentSessionMessageContext | null, query: Record<string, string | number | undefined>): Promise<CommunicationHistoryResult>;
27
+ export declare function formatCommunicationHistoryItem(item: CommunicationHistoryItem): string;