@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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.
Files changed (206) hide show
  1. package/GUIDE.md +975 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION.md +84 -0
  4. package/MIGRATION.zh.md +70 -0
  5. package/PROVIDERS.md +273 -0
  6. package/PROVIDERS.zh.md +234 -0
  7. package/README.md +334 -2
  8. package/dist/AgentClient.d.ts +312 -0
  9. package/dist/AgentClient.d.ts.map +1 -0
  10. package/dist/AgentClient.js +715 -0
  11. package/dist/AgentClient.js.map +1 -0
  12. package/dist/AgenticID.d.ts +823 -0
  13. package/dist/AgenticID.d.ts.map +1 -0
  14. package/dist/AgenticID.js +1188 -0
  15. package/dist/AgenticID.js.map +1 -0
  16. package/dist/AgenticIDClient.d.ts +68 -0
  17. package/dist/AgenticIDClient.d.ts.map +1 -0
  18. package/dist/AgenticIDClient.js +198 -0
  19. package/dist/AgenticIDClient.js.map +1 -0
  20. package/dist/AttestorClient.d.ts +465 -0
  21. package/dist/AttestorClient.d.ts.map +1 -0
  22. package/dist/AttestorClient.js +1030 -0
  23. package/dist/AttestorClient.js.map +1 -0
  24. package/dist/Providers.d.ts +72 -0
  25. package/dist/Providers.d.ts.map +1 -0
  26. package/dist/Providers.js +182 -0
  27. package/dist/Providers.js.map +1 -0
  28. package/dist/ReputationClient.d.ts +213 -0
  29. package/dist/ReputationClient.d.ts.map +1 -0
  30. package/dist/ReputationClient.js +708 -0
  31. package/dist/ReputationClient.js.map +1 -0
  32. package/dist/SandboxClient.d.ts +107 -0
  33. package/dist/SandboxClient.d.ts.map +1 -0
  34. package/dist/SandboxClient.js +200 -0
  35. package/dist/SandboxClient.js.map +1 -0
  36. package/dist/ServeProof.d.ts +161 -0
  37. package/dist/ServeProof.d.ts.map +1 -0
  38. package/dist/ServeProof.js +230 -0
  39. package/dist/ServeProof.js.map +1 -0
  40. package/dist/ServeSession.d.ts +180 -0
  41. package/dist/ServeSession.d.ts.map +1 -0
  42. package/dist/ServeSession.js +336 -0
  43. package/dist/ServeSession.js.map +1 -0
  44. package/dist/Settings.d.ts +179 -0
  45. package/dist/Settings.d.ts.map +1 -0
  46. package/dist/Settings.js +247 -0
  47. package/dist/Settings.js.map +1 -0
  48. package/dist/abi.d.ts +2216 -0
  49. package/dist/abi.d.ts.map +1 -0
  50. package/dist/abi.js +1248 -0
  51. package/dist/abi.js.map +1 -0
  52. package/dist/cli/commands/cells.d.ts +62 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +113 -0
  55. package/dist/cli/commands/cells.js.map +1 -0
  56. package/dist/cli/commands/doctor.d.ts +15 -0
  57. package/dist/cli/commands/doctor.d.ts.map +1 -0
  58. package/dist/cli/commands/doctor.js +236 -0
  59. package/dist/cli/commands/doctor.js.map +1 -0
  60. package/dist/cli/commands/interactive.d.ts +115 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3052 -0
  63. package/dist/cli/commands/interactive.js.map +1 -0
  64. package/dist/cli/commands/list.d.ts +31 -0
  65. package/dist/cli/commands/list.d.ts.map +1 -0
  66. package/dist/cli/commands/list.js +91 -0
  67. package/dist/cli/commands/list.js.map +1 -0
  68. package/dist/cli/commands/providers.d.ts +3 -0
  69. package/dist/cli/commands/providers.d.ts.map +1 -0
  70. package/dist/cli/commands/providers.js +21 -0
  71. package/dist/cli/commands/providers.js.map +1 -0
  72. package/dist/cli/commands/settings.d.ts +22 -0
  73. package/dist/cli/commands/settings.d.ts.map +1 -0
  74. package/dist/cli/commands/settings.js +188 -0
  75. package/dist/cli/commands/settings.js.map +1 -0
  76. package/dist/cli/commands/status.d.ts +16 -0
  77. package/dist/cli/commands/status.d.ts.map +1 -0
  78. package/dist/cli/commands/status.js +148 -0
  79. package/dist/cli/commands/status.js.map +1 -0
  80. package/dist/cli/commands/update.d.ts +21 -0
  81. package/dist/cli/commands/update.d.ts.map +1 -0
  82. package/dist/cli/commands/update.js +95 -0
  83. package/dist/cli/commands/update.js.map +1 -0
  84. package/dist/cli/config.d.ts +73 -0
  85. package/dist/cli/config.d.ts.map +1 -0
  86. package/dist/cli/config.js +239 -0
  87. package/dist/cli/config.js.map +1 -0
  88. package/dist/cli/env.d.ts +36 -0
  89. package/dist/cli/env.d.ts.map +1 -0
  90. package/dist/cli/env.js +74 -0
  91. package/dist/cli/env.js.map +1 -0
  92. package/dist/cli/envelope.d.ts +33 -0
  93. package/dist/cli/envelope.d.ts.map +1 -0
  94. package/dist/cli/envelope.js +62 -0
  95. package/dist/cli/envelope.js.map +1 -0
  96. package/dist/cli/errors.d.ts +48 -0
  97. package/dist/cli/errors.d.ts.map +1 -0
  98. package/dist/cli/errors.js +81 -0
  99. package/dist/cli/errors.js.map +1 -0
  100. package/dist/cli/inference.d.ts +21 -0
  101. package/dist/cli/inference.d.ts.map +1 -0
  102. package/dist/cli/inference.js +60 -0
  103. package/dist/cli/inference.js.map +1 -0
  104. package/dist/cli/logo.d.ts +21 -0
  105. package/dist/cli/logo.d.ts.map +1 -0
  106. package/dist/cli/logo.js +131 -0
  107. package/dist/cli/logo.js.map +1 -0
  108. package/dist/cli/main.d.ts +14 -0
  109. package/dist/cli/main.d.ts.map +1 -0
  110. package/dist/cli/main.js +223 -0
  111. package/dist/cli/main.js.map +1 -0
  112. package/dist/cli/proofs.d.ts +67 -0
  113. package/dist/cli/proofs.d.ts.map +1 -0
  114. package/dist/cli/proofs.js +133 -0
  115. package/dist/cli/proofs.js.map +1 -0
  116. package/dist/cli/ref.d.ts +39 -0
  117. package/dist/cli/ref.d.ts.map +1 -0
  118. package/dist/cli/ref.js +48 -0
  119. package/dist/cli/ref.js.map +1 -0
  120. package/dist/cli/sdk.d.ts +24 -0
  121. package/dist/cli/sdk.d.ts.map +1 -0
  122. package/dist/cli/sdk.js +65 -0
  123. package/dist/cli/sdk.js.map +1 -0
  124. package/dist/cli/settings.d.ts +66 -0
  125. package/dist/cli/settings.d.ts.map +1 -0
  126. package/dist/cli/settings.js +137 -0
  127. package/dist/cli/settings.js.map +1 -0
  128. package/dist/cli/tokenize.d.ts +61 -0
  129. package/dist/cli/tokenize.d.ts.map +1 -0
  130. package/dist/cli/tokenize.js +157 -0
  131. package/dist/cli/tokenize.js.map +1 -0
  132. package/dist/cli/types.d.ts +25 -0
  133. package/dist/cli/types.d.ts.map +1 -0
  134. package/dist/cli/types.js +8 -0
  135. package/dist/cli/types.js.map +1 -0
  136. package/dist/constants.d.ts +107 -0
  137. package/dist/constants.d.ts.map +1 -0
  138. package/dist/constants.js +74 -0
  139. package/dist/constants.js.map +1 -0
  140. package/dist/context.d.ts +108 -0
  141. package/dist/context.d.ts.map +1 -0
  142. package/dist/context.js +64 -0
  143. package/dist/context.js.map +1 -0
  144. package/dist/index.d.ts +45 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +118 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/provider-catalog.json +23 -0
  149. package/dist/seal.d.ts +47 -0
  150. package/dist/seal.d.ts.map +1 -0
  151. package/dist/seal.js +145 -0
  152. package/dist/seal.js.map +1 -0
  153. package/dist/secretEnv.d.ts +119 -0
  154. package/dist/secretEnv.d.ts.map +1 -0
  155. package/dist/secretEnv.js +199 -0
  156. package/dist/secretEnv.js.map +1 -0
  157. package/dist/taskHash.d.ts +39 -0
  158. package/dist/taskHash.d.ts.map +1 -0
  159. package/dist/taskHash.js +119 -0
  160. package/dist/taskHash.js.map +1 -0
  161. package/dist/types.d.ts +336 -0
  162. package/dist/types.d.ts.map +1 -0
  163. package/dist/types.js +19 -0
  164. package/dist/types.js.map +1 -0
  165. package/package.json +75 -4
  166. package/scripts/sync-providers.cjs +8 -0
  167. package/src/AgentClient.ts +897 -0
  168. package/src/AgenticID.ts +1382 -0
  169. package/src/AgenticIDClient.ts +238 -0
  170. package/src/AttestorClient.ts +1306 -0
  171. package/src/Providers.ts +176 -0
  172. package/src/ReputationClient.ts +821 -0
  173. package/src/SandboxClient.ts +227 -0
  174. package/src/ServeProof.ts +290 -0
  175. package/src/ServeSession.ts +421 -0
  176. package/src/Settings.ts +296 -0
  177. package/src/abi.ts +1282 -0
  178. package/src/cli/commands/cells.ts +107 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2738 -0
  181. package/src/cli/commands/list.ts +95 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
@@ -0,0 +1,2738 @@
1
+ /**
2
+ * @file interactive.ts
3
+ * @description The default action: a two-level interactive shell.
4
+ *
5
+ * L1 — manager REPL (`0g-agentdna>`): list your agents, link one, deploy a
6
+ * new one, configure the environment (attestor URL) and wallet.
7
+ * L2 — session REPL (`agent 286 ›`): chat with one agent. Esc / Ctrl-C
8
+ * interrupts a turn in flight; `/back` returns to L1; `/quit` exits.
9
+ *
10
+ * One readline drives both levels, so interrupt handling (a streaming turn's
11
+ * AbortController) is managed in one place. Owner-key checks are LAZY: L1 is
12
+ * reachable with only an attestor URL; `link`/`deploy` (signing operations)
13
+ * check for a key and point you at `login` if it's missing.
14
+ */
15
+
16
+ import * as readline from 'node:readline';
17
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { SDK_VERSION } from '../../constants';
20
+ import { parseEther, keccak256, isAddress, ContractFunctionRevertedError, type Address } from 'viem';
21
+ import type { AgenticID } from '../../AgenticID';
22
+ import type { AgentClient, ChatMessage } from '../../AgentClient';
23
+ import type { ServeProof, TaskReveal } from '../../types';
24
+ import { taskHashOf, requestUriCandidates } from '../../taskHash';
25
+ import { buildClient } from '../sdk';
26
+ import { saveProof, listProofs, removeProof, toServeProof, ticketDisposition, ticketRedeemable, type SavedProof } from '../proofs';
27
+ import { CliError } from '../errors';
28
+ import { requireAttestorUrl } from '../env';
29
+ import { loadKey, saveKey, normalizeKey, saveApiKey, loadConfig, saveConfig, configPaths } from '../config';
30
+ import { parseAgentRef, refMatchesSeal, type AgentRef } from '../ref';
31
+ import { applyAssignments, assertModelPresent, parseAssignments, renderSettings } from '../settings';
32
+ import { SettingsConflictError, THINKING_LEVELS, type SettingsDoc, type ThinkingLevel } from '../../Settings';
33
+ import { splitHead, tokenize } from '../tokenize';
34
+ import { pandaLines, svgPixelLines } from '../logo';
35
+ import { listInferenceProviders, type InferenceProvider, changesProvider } from '../../Providers';
36
+ import { configuredInferenceKey, requireConfiguredInferenceKey, agentInferenceProvider, requiresProviderReset, deployWithInference } from '../inference';
37
+
38
+ // Tab-completion candidates for the active REPL level (canonical names only —
39
+ // aliases like link//unuse still work typed out but don't clutter the list).
40
+ const L1_WORDS = ['list', 'use ', 'hello ', 'call ', 'rate ', 'deploy', 'start ', 'stop ', 'reset ', 'retry ', 'settings ', 'clone ', 'transfer ', 'authorizer ', 'grant ', 'revoke ', 'balance', 'deposit', 'withdraw', 'ack', 'login', 'whoami', 'help', 'quit'];
41
+ const L2_WORDS = ['/hello', '/balance', '/topup', '/start', '/stop', '/reset', '/settings', '/think', '/clear', '/compact', '/tasks', '/result', '/cancel', '/agentlog', '/startuplog', '/back', '/help', '/quit'];
42
+ let activeCompletions: string[] = L1_WORDS;
43
+ // First-argument completion per command (Tab after the command word).
44
+ // Static lists inline; AGENT resolves to the ids seen in the latest
45
+ // listing (banner / `list` / myRow refresh them as a side effect).
46
+ // This CLI process's identity for the agent's single-driver seat (WeChat
47
+ // semantics: entering a session claims the agent; a displaced window is told
48
+ // on its next message and re-enters to claim it back).
49
+ const clientInstanceId = (globalThis.crypto?.randomUUID?.() ?? `cli-${Date.now()}-${Math.floor(Math.random() * 1e9)}`);
50
+
51
+ /** The ONE money block both layers print (review: the two layers used to
52
+ * render different lines from different sources — same wallet, two answers).
53
+ * prepaid = the chain number; AVAILABLE = the provider's effective view and
54
+ * is ALWAYS shown ("couldn't check" ≠ "nothing owed"). */
55
+ type EffBalance = Awaited<ReturnType<AgenticID['getEffectiveBalance']>>;
56
+ function moneyBlock(prepaidWei: bigint | null, eff: EffBalance | null, effErr: string | null): void {
57
+ out(`prepaid balance : ${prepaidWei == null ? '(unreadable)' : og(prepaidWei)}\n`);
58
+ if (eff && eff.availableWei < eff.balanceWei) {
59
+ if (eff.outstandingDebtWei > 0n) out(`outstanding debt: ${og(eff.outstandingDebtWei)} (parked; settles from deposits first)\n`);
60
+ if (eff.pendingSettlementWei > 0n) out(`pending settles : ${og(eff.pendingSettlementWei)} (queued fees, deducted over the next cycles)\n`);
61
+ if (eff.reservedWei > 0n) out(`reserved : ${og(eff.reservedWei)}\n`);
62
+ out(`AVAILABLE : ${og(eff.availableWei)} ← what deploy/start can actually spend\n`);
63
+ } else if (eff) {
64
+ out(`AVAILABLE : ${og(eff.availableWei)} (nothing owed or queued off-chain)\n`);
65
+ } else {
66
+ out(`AVAILABLE : (couldn't reach the provider's effective view: ${effErr ?? 'unknown'} — the chain number above may be optimistic)\n`);
67
+ }
68
+ }
69
+
70
+ /** Once-a-day update hint, driven by the attestor's /config (cli_latest +
71
+ * cli_notes — operator-set per release). Deliberately minimal: no npm, no
72
+ * semver lib (numeric dot-compare), silent on any failure. */
73
+ // Deterministic latch for the update hint: Promise.race does NOT cancel the
74
+ // loser, so a fetch resolving just past the deadline could still print into
75
+ // the prompt. The banner closes the window; a late hint then stays silent.
76
+ let updateHintWindowOpen = false;
77
+
78
+ async function maybePrintUpdateHint(attestorUrl?: string): Promise<void> {
79
+ if (!attestorUrl) return;
80
+ updateHintWindowOpen = true;
81
+ {
82
+ try {
83
+ const cfg = (await (await fetch(`${attestorUrl}/config`, { signal: AbortSignal.timeout(4000) })).json()) as {
84
+ cli_latest?: string; cli_notes?: string;
85
+ };
86
+ const latest = cfg.cli_latest?.trim();
87
+ if (!latest) return;
88
+ const mine = SDK_VERSION;
89
+ if (compareVersions(mine, latest) >= 0) return;
90
+ // once per (day, latest)
91
+ const stamp = join(configPaths().dir, 'update-hint.json');
92
+ const today = new Date().toISOString().slice(0, 10);
93
+ try {
94
+ const prev = JSON.parse(readFileSync(stamp, 'utf8')) as { day?: string; latest?: string };
95
+ if (prev.day === today && prev.latest === latest) return;
96
+ } catch { /* first time */ }
97
+ if (!updateHintWindowOpen) return; // banner already closed — stay silent
98
+ // Create the config dir first: a user whose attestorUrl comes from
99
+ // AGENTIC_* env has never hit a write path, so the dir may not exist —
100
+ // without this the stamp write ENOENTs, the once-a-day guard never
101
+ // records, and the hint nags every start (review #170). Don't swallow
102
+ // silently either.
103
+ try {
104
+ mkdirSync(configPaths().dir, { recursive: true });
105
+ writeFileSync(stamp, JSON.stringify({ day: today, latest }));
106
+ } catch (e) { console.error(`(update-hint stamp unwritable: ${(e as Error).message} — the hint may repeat)`); }
107
+ out(`\n update available: ${mine} → ${latest} 0g-agentdna update\n`);
108
+ if (cfg.cli_notes?.trim()) out(` ${cfg.cli_notes.trim()}\n`);
109
+ } catch { /* a down attestor never blocks or complains here */ }
110
+ }
111
+ }
112
+
113
+ /** -1/0/1 numeric dot-compare ("0.1.9" < "0.1.10"). Exported for tests —
114
+ * a wrong compare either nags forever or never hints. */
115
+ export function compareVersions(a: string, b: string): number {
116
+ // parseInt tolerates suffixes ("7-rc1" → 7); anything unparsable is 0, so a
117
+ // malformed advertised version can never mis-trigger the hint.
118
+ const num = (x: string) => { const n = parseInt(x, 10); return Number.isFinite(n) ? n : 0; };
119
+ const as = a.split('.').map(num), bs = b.split('.').map(num);
120
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
121
+ const d = (as[i] ?? 0) - (bs[i] ?? 0);
122
+ if (d !== 0) return d < 0 ? -1 : 1;
123
+ }
124
+ return 0;
125
+ }
126
+
127
+
128
+ /** Short environment marker for prompts/errors: the attestor's hostname.
129
+ * Exported for tests. */
130
+ export function hostOf(url?: string): string {
131
+ if (!url) return 'unset';
132
+ try { return new URL(url).hostname; } catch { return url.slice(0, 24); }
133
+ }
134
+
135
+ /**
136
+ * A failure meaning the SEAT was taken (occupancy.go): HTTP 409 with
137
+ * 'displaced' or 'in use by another client' in the body. The seat gates the
138
+ * chat turn and the seat-gated POSTs (cancelTask, /clear, /compact, the
139
+ * interrupt brake) — all of them route through the displaced-seat prompt
140
+ * instead of surfacing the raw error. The status-check GETs (task()) are
141
+ * ungated today, so their routing is defensive: if the gate ever widens,
142
+ * those paths still do the right thing. Exported for the tests: this is the
143
+ * routing decision (which errors are seat events, not task errors).
144
+ */
145
+ export function displacedFailure(failure: string): boolean {
146
+ return /displaced|in use by another client/i.test(failure);
147
+ }
148
+
149
+ /**
150
+ * The Esc brake's failure line — a PURE function on purpose. The brake fires
151
+ * on an idle Esc, and at that moment the main loop is parked in its own
152
+ * ask() prompt; calling ask() from here (via the seat handler) would queue a
153
+ * second waiter, and ask hands lines out FIFO — the user's Enter would go to
154
+ * the wrong prompt (a bare-Enter status refresh instead of a reclaim), and
155
+ * their next chat message would be eaten as the prompt's non-empty answer.
156
+ * So a displaced 409 prints a NOTICE that points at the paths which CAN
157
+ * prompt (a chat turn, /cancel); every other failure keeps the old raw line.
158
+ * Taking no ask and returning a string is the guarantee — pinned by a test
159
+ * that drives the brake while a loop ask is pending.
160
+ */
161
+ /**
162
+ * The Esc brake: an idle Esc interrupts whatever the agent is still running
163
+ * in the background. A top-level factory so the test can drive the REAL
164
+ * handler (the 06d7a7d regression hid inside sessionRepl where no test could
165
+ * reach it): `seat` is passed in and must NEVER be invoked — the brake fires
166
+ * while the loop's ask() is pending, and any prompt from here is the FIFO
167
+ * bug. `seatPromptPending` keeps the brake quiet while displacedSeat's own
168
+ * prompt is on screen (firing then would print contradictory advice under a
169
+ * prompt that is waiting for an answer).
170
+ */
171
+ export function makeBrake(
172
+ // A GETTER, not the client: s.client is replaced mid-session (/start,
173
+ // /reset, the loop-top and bare-Enter reconnects, /stop) — capturing it
174
+ // here would pin the brake to a stale (or stopped) container for the rest
175
+ // of the session.
176
+ getClient: () => { interrupt?: () => Promise<{ aborted: boolean; note?: string }> } | null | undefined,
177
+ print: (line: string) => void,
178
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- passed so the test can assert it is never used
179
+ seat: (failure: string, reclaimedHint: string, leavesWhat?: string) => Promise<'reclaimed' | 'left' | null>,
180
+ seatPromptPending: () => boolean,
181
+ ): () => void {
182
+ let last = 0;
183
+ return () => {
184
+ const now = Date.now();
185
+ if (now - last < 2000) return;
186
+ last = now;
187
+ if (seatPromptPending()) return; // the seat prompt owns the screen — stay quiet
188
+ const client = getClient();
189
+ if (!client?.interrupt) { print('\n(this agent image has no interrupt endpoint — /reset is the only stop)\n'); return; }
190
+ client.interrupt().then(
191
+ (r) => print(r.aborted ? '\n⏹ stopped the running task\n' : '\n(nothing to stop, or: ' + (r.note ?? 'not supported') + ')\n'),
192
+ // NOT a prompt: the loop's ask() is pending right now — a notice only.
193
+ // The seat argument is deliberately NOT called from here.
194
+ (e) => print(brakeInterruptLine(e)),
195
+ );
196
+ };
197
+ }
198
+
199
+ export function brakeInterruptLine(e: unknown): string {
200
+ const msg = (e as Error)?.message ?? '';
201
+ if (displacedFailure(msg)) {
202
+ // "/cancel" is NOT advised: an idle Esc usually means nothing is running,
203
+ // and bare /cancel sends no POST then (no tasks / none in flight / status
204
+ // GETs failing), so the seat prompt would never appear. "Send a message"
205
+ // DOES work: the chat POST is seat-gated, gets the 409, and displacedSeat
206
+ // reclaims and resends.
207
+ return '\n⚠ this agent is now driven by another client — send a message to take the seat back\n';
208
+ }
209
+ return `\n(interrupt failed: ${msg})\n`;
210
+ }
211
+
212
+ /**
213
+ * The shared catch for a gated-POST failure: displaced → the seat handler
214
+ * (which prompts and may reclaim); anything else → the caller's raw line.
215
+ * `leavesWhat` for these paths is "leaves the seat with the other client" —
216
+ * unlike the chat turn, declining does NOT close this window. Exported for
217
+ * the tests: every task-path catch routes through here, so the routing
218
+ * behavior is pinned in one place.
219
+ */
220
+ export async function routeTaskFailure(
221
+ print: (line: string) => void,
222
+ seat: (failure: string, reclaimedHint: string, leavesWhat?: string) => Promise<'reclaimed' | 'left' | null>,
223
+ e: unknown,
224
+ rawLine: string,
225
+ seatHint: string,
226
+ ): Promise<'reclaimed' | 'left' | 'raw'> {
227
+ const d = await seat((e as Error)?.message ?? '', seatHint, 'leaves the seat with the other client');
228
+ if (d !== null) return d;
229
+ if (rawLine) print(rawLine);
230
+ return 'raw';
231
+ }
232
+
233
+ /**
234
+ * The tasks bare `/cancel` stops: everything still in flight, NEWEST FIRST
235
+ * (stopping only the newest would leave an older running turn alive; dsh/
236
+ * prime serialize turns, so a queued one is waiting on the running one).
237
+ * Statuses arrive live from the agent; "unknown" (evicted or agent
238
+ * restarted, 404) counts as not in flight — cancelling an unknown record
239
+ * would claim to stop something nobody can see. Exported for the tests:
240
+ * this is the re-attach story's decision core.
241
+ */
242
+ export function inFlightIds(rows: Array<{ id: string; status: string }>): string[] {
243
+ const out: string[] = [];
244
+ for (let i = rows.length - 1; i >= 0; i--) {
245
+ if (rows[i].status === 'queued' || rows[i].status === 'in_progress') out.push(rows[i].id);
246
+ }
247
+ return out;
248
+ }
249
+
250
+ let knownAgentIds: string[] = [];
251
+ const rememberAgentIds = (rows: Array<{ agentId?: unknown }>): void => {
252
+ const ids = rows.map((r) => String(r.agentId ?? '')).filter((x) => x && x !== 'undefined');
253
+ if (ids.length) knownAgentIds = [...new Set(ids)];
254
+ };
255
+ const AGENT = (): string[] => knownAgentIds;
256
+
257
+ // Model ids for `model=` completion. Filled once, best-effort, from the router
258
+ // catalog (chat models only — it also lists image/audio ones). Completion is
259
+ // synchronous, so this must be a plain cache: a fire-and-forget refresh on
260
+ // REPL entry populates it, and until it lands `model=<tab>` simply offers
261
+ // nothing rather than blocking on the network.
262
+ let chatModelIds: string[] = [];
263
+ let completionProvider = '0g-compute';
264
+ const providerModelIds: Record<string, string[]> = {};
265
+ let knownProviders: InferenceProvider[] = listInferenceProviders();
266
+ function prefetchModelIds(ag: AgenticID): void {
267
+ completionProvider = loadConfig().inferenceProvider ?? '0g-compute';
268
+ chatModelIds = providerModelIds[completionProvider] ?? [];
269
+ ag.agent.refreshProviders().then((providers) => {
270
+ knownProviders = providers;
271
+ for (const provider of providers) {
272
+ ag.agent.listModelCaps({ provider: provider.id }).then((caps) => {
273
+ providerModelIds[provider.id] = caps.filter((m) => m.chat).map((m) => m.id);
274
+ if (provider.id === completionProvider) chatModelIds = providerModelIds[provider.id];
275
+ }).catch(() => { /* completion must not block the prompt */ });
276
+ }
277
+ }).catch(() => { /* only completions; explicit operations refresh strictly */ });
278
+ }
279
+ const L1_ARGS: Record<string, string[] | (() => string[])> = {
280
+ use: AGENT, hello: AGENT, start: AGENT, stop: AGENT, reset: AGENT,
281
+ retry: AGENT, clone: AGENT, transfer: AGENT, call: AGENT, rate: AGENT,
282
+ grant: AGENT, revoke: AGENT, authorizer: AGENT, settings: AGENT,
283
+ list: ['--mine'],
284
+ };
285
+ const L2_ARGS: Record<string, string[] | (() => string[])> = {
286
+ '/think': ['low', 'high', 'max'],
287
+ '/reset': ['pick'],
288
+ '/settings': ['provider=', 'model=', 'thinking=', 'others='],
289
+ };
290
+ let activeArgs: Record<string, string[] | (() => string[])> = L1_ARGS;
291
+
292
+ // Commands whose LATER arguments also complete (the generic rule is "first
293
+ // argument only; the rest is free-form" — right for prompts and amounts,
294
+ // wrong for settings' k=v list, where the keys are a closed set the user
295
+ // should never have to remember).
296
+ const SETTING_KEYS = ['provider=', 'model=', 'thinking=', 'others='];
297
+ const TAIL_ARGS: Record<string, string[]> = {
298
+ 'settings': SETTING_KEYS, // L1: settings <agent> k=v k=v …
299
+ '/settings': SETTING_KEYS, // L2: /settings k=v k=v …
300
+ };
301
+
302
+ // completeTail finishes the word being typed in a k=v run: key names, and
303
+ // the value set for thinking=.
304
+ export function completeTail(cmd: string, word: string, models: string[], providers = knownProviders.map((p) => p.id)): string[] {
305
+ const keys = TAIL_ARGS[cmd];
306
+ if (!keys) return [];
307
+ // Value completion for the keys whose values are a known set. thinking is a
308
+ // fixed trio; model and provider suggestions come from the registry.
309
+ // others= is opaque JSON — nothing to suggest.
310
+ if (word.startsWith('thinking=')) {
311
+ return ['low', 'high', 'max'].map((v) => 'thinking=' + v).filter((c) => c.startsWith(word));
312
+ }
313
+ if (word.startsWith('model=')) {
314
+ const hits = models.map((id) => 'model=' + id).filter((c) => c.startsWith(word));
315
+ return hits.length ? hits : ['model='];
316
+ }
317
+ if (word.startsWith('provider=')) {
318
+ return providers.map((provider) => `provider=${provider}`).filter((candidate) => candidate.startsWith(word));
319
+ }
320
+ const hits = keys.filter((c) => c.startsWith(word));
321
+ return hits.length ? hits : keys;
322
+ }
323
+
324
+ // completeLine is the whole completer as a pure function, so the dispatch — the
325
+ // part that has now broken twice — is unit-testable without a tty. The live
326
+ // completer is a one-line adapter that hands it the mutable module state.
327
+ export function completeLine(
328
+ line: string,
329
+ state: { completions: string[]; args: Record<string, string[] | (() => string[])>; models: string[]; provider?: string; providerModels?: Record<string, string[]>; providers?: string[] },
330
+ ): [string[], string] {
331
+ const sp = line.indexOf(' ');
332
+ if (sp === -1) {
333
+ const hits = state.completions.filter((c) => c.startsWith(line));
334
+ return [hits.length ? hits : state.completions, line];
335
+ }
336
+ const cmd = line.slice(0, sp);
337
+ const rest = line.slice(sp + 1);
338
+ const word = rest.slice(rest.lastIndexOf(' ') + 1);
339
+ // k=v commands (settings / /settings) complete keys AND values at every
340
+ // position. The exception is L1 `settings <agent> …`, whose first token is
341
+ // the agent id; the in-session `/settings` has no agent token, so its first
342
+ // word is already k=v. This split is exactly what broke `/settings model=`.
343
+ const firstTokenIsAgent = cmd === 'settings' && !rest.includes(' ');
344
+ if (TAIL_ARGS[cmd] && !firstTokenIsAgent) {
345
+ const provider = rest.match(/(?:^|\s)provider=([^\s]+)/)?.[1] ?? state.provider ?? '0g-compute';
346
+ const models = state.providerModels?.[provider] ?? (provider === (state.provider ?? '0g-compute') ? state.models : []);
347
+ const hits = completeTail(cmd, word, models, state.providers);
348
+ return hits.length ? [hits, word] : [[], line];
349
+ }
350
+ const cand = state.args[cmd];
351
+ const list = typeof cand === 'function' ? cand() : (cand ?? []);
352
+ const hits = list.filter((c) => c.startsWith(rest));
353
+ return [hits.length ? hits : list, rest];
354
+ }
355
+
356
+ // The live readline interface — askSecret scrubs submitted secrets out of
357
+ // its history (display masking alone leaves the plaintext one ↑ away).
358
+ let activeRl: readline.Interface | null = null;
359
+ import type { CommandContext } from '../types';
360
+ import { cellText, cleanCell, ownerCellText, sealToAgentMap, shortAddr, trustedCell } from './cells';
361
+
362
+ /** Column widths of the REPL listing; its header and every row share them. */
363
+ const LIST_COLS = { id: 6, phase: 11, framework: 12, seal: 13, agentSeal: 13, owner: 24 } as const;
364
+
365
+ /** The REPL listing's header line, aligned with {@link renderListRow}. */
366
+ export function renderListHeader(): string {
367
+ const c = LIST_COLS;
368
+ return ` ${'ID'.padEnd(c.id)} ${'PHASE'.padEnd(c.phase)}${'FRAMEWORK'.padEnd(c.framework)}` +
369
+ `${'SEAL'.padEnd(c.seal)}${'AGENTSEAL'.padEnd(c.agentSeal)}${'OWNER'.padEnd(c.owner)}NAME\n`;
370
+ }
371
+
372
+ /**
373
+ * One row of the REPL's agent listing. Exported for the tests: this IS the
374
+ * renderer the interactive loop prints. Its cells go through ./cells, shared
375
+ * with `list`: a name cannot forge rows in this listing either, and an
376
+ * agent-owned agent reads the same way — its OWNER is another row's
377
+ * AGENTSEAL, annotated `⇄ #<agentId>` (`sealToAgent`, from the full listing).
378
+ * SEAL is the sealId PREFIX (`0x` + 10 hex), the form commands accept as a
379
+ * reference, so unminted rows stay referenceable without a 66-char column
380
+ * blowout (F12).
381
+ * AGENTSEAL is the agent's on-chain signing address.
382
+ */
383
+ export function renderListRow(
384
+ r: {
385
+ agentId: bigint | number | null; phase?: string | null; sealId: string; name?: string | null;
386
+ framework?: string | null; agentSeal?: string | null;
387
+ },
388
+ owner: string | null | undefined,
389
+ owned = ' ',
390
+ sealToAgent: ReadonlyMap<string, string> = new Map(),
391
+ ): string {
392
+ const c = LIST_COLS;
393
+ const seal = `0x${r.sealId.slice(2, 12)}`;
394
+ return `${owned} ${String(r.agentId ?? '?').padEnd(c.id)} ${cellText(r.phase ?? '?', c.phase)}` +
395
+ `${cellText(r.framework, c.framework)}${cellText(seal, c.seal)}${cellText(shortAddr(r.agentSeal), c.agentSeal)}` +
396
+ `${trustedCell(ownerCellText(owner, sealToAgent), c.owner)}${cleanCell(r.name)}\n`;
397
+ }
398
+
399
+ const sbid = (url: string): string | undefined => url.match(/8080-([^.]+)\./)?.[1];
400
+
401
+ /** Build a container URL from a sandbox id + proxy host, matching the
402
+ * attestor's build_agent_url scheme rule: a bare host (a TLS domain like
403
+ * art.0g.ai) is https; a host:port (dev IP behind plain-HTTP nginx) is
404
+ * http. Writing http:// for a bare domain hits :80, which prod nginx
405
+ * doesn't serve — "running but unreachable". Only used as a fallback when
406
+ * the attestor didn't hand back a `url`. */
407
+ function containerUrl(sandboxId: string, proxy: string): string {
408
+ return proxy.includes(':')
409
+ ? `http://8080-${sandboxId}.${proxy}`
410
+ : `https://8080-${sandboxId}.${proxy}`;
411
+ }
412
+ const og = (wei: bigint | null | undefined): string => (wei == null ? 'n/a' : `${(Number(wei) / 1e18).toFixed(6)} OG`);
413
+ const out = (s: string): void => void process.stdout.write(s);
414
+
415
+ interface Session {
416
+ ag: AgenticID;
417
+ attestorUrl: string;
418
+ sealId: `0x${string}`;
419
+ agentId: string;
420
+ agentSeal?: `0x${string}`; // for /topup; from deploy//hello, else read from chain on demand
421
+ /** Needed by /reset (which image) and the chat model selector. Not exposed
422
+ * by the attestor post-mint, so it is PICKED by the user when first
423
+ * needed (deploy knows it; use/attach does not). */
424
+ framework?: string;
425
+ phase: string;
426
+ // Connection half — absent until the agent is running (`use` enters the
427
+ // session in ANY phase; /start and /reset fill these in on success).
428
+ url?: string;
429
+ sandboxId?: string;
430
+ client?: AgentClient;
431
+ /** Tasks started from THIS session on the responses transport (newest
432
+ * last): lets /tasks list them and /result re-attach after a drop. The
433
+ * agent itself keeps the authoritative ring; this is just the ids. */
434
+ tasks?: Array<{ id: string; prompt: string; at: number }>;
435
+ /** The reasoning level /think last wrote to the settings document, mirrored
436
+ * here ONLY as the per-message override for frameworks whose bridge takes
437
+ * one (prime). The durable copy is the document; this is a session echo of
438
+ * it, set after a successful write and never on its own. */
439
+ thinking?: 'low' | 'high' | 'max';
440
+ /** Task id of the chat turn currently in flight (responses transport). */
441
+ currentTask?: string | null;
442
+ }
443
+
444
+ /** (Re)establish the connection half of a session from a running URL. */
445
+ async function connectSession(s: Session, url: string): Promise<void> {
446
+ s.url = url;
447
+ s.sandboxId = sbid(url);
448
+ // Pass the session's known agentId: the URL alone yields one only via
449
+ // /hello's proof envelope, which a container without VERIFIED_FEEDBACK_ADDR
450
+ // does not emit — and without it the handle would lose owner reauth.
451
+ const agentId = /^\d+$/.test(s.agentId) ? BigInt(s.agentId) : undefined;
452
+ s.client = await s.ag.agent.client(url, { instanceId: clientInstanceId, agentId });
453
+ s.phase = 'running';
454
+ // Take the single-driver seat (WeChat: the new login just wins; whoever
455
+ // held it is told on their next message). Best-effort — a pre-seat
456
+ // container 404s, and no seat is better than no session.
457
+ try {
458
+ await s.ag.agent.claimAgent(url, BigInt(s.agentId), clientInstanceId);
459
+ } catch { /* container predates the seat, or agentId unresolved — proceed */ }
460
+ if (!s.agentSeal) {
461
+ try {
462
+ const hello = (await (await fetch(`${url}/hello`)).json()) as { agent?: string };
463
+ if (hello.agent && /^0x[0-9a-fA-F]{40}$/.test(hello.agent)) s.agentSeal = hello.agent as `0x${string}`;
464
+ } catch { /* /topup will say it's unavailable */ }
465
+ }
466
+ }
467
+
468
+ /** /config's sandbox_proxy_addr, fetched once per attestor (used to construct
469
+ * container URLs — the detail endpoint has no url field). */
470
+ const proxyAddrCache = new Map<string, Promise<string | undefined>>();
471
+ function proxyAddrOf(attestorUrl: string): Promise<string | undefined> {
472
+ let p = proxyAddrCache.get(attestorUrl);
473
+ if (!p) {
474
+ p = fetch(`${attestorUrl}/config`)
475
+ .then((r) => r.json())
476
+ .then((c) => (c as { sandbox_proxy_addr?: string }).sandbox_proxy_addr)
477
+ .catch(() => undefined);
478
+ proxyAddrCache.set(attestorUrl, p);
479
+ }
480
+ return p;
481
+ }
482
+
483
+ /** Re-read the deployment row and resync the session, printing the result:
484
+ * phase always; the container URL as soon as a sandbox exists (the sealed
485
+ * runtime serves /log while still `deploying`); the chat client only when
486
+ * running (and dropped again when not, so a stale connection can't linger). */
487
+ async function refreshSession(s: Session, quiet = false): Promise<void> {
488
+ const before = s.phase;
489
+ const d = (await (await fetch(`${s.attestorUrl}/deployment/${s.sealId}`)).json()) as {
490
+ phase?: string; url?: string; sandbox_id?: string;
491
+ agent_card?: { url?: string };
492
+ container_stage?: { state?: string; reason?: string };
493
+ };
494
+ s.phase = d.phase ?? s.phase;
495
+ const proxy = await proxyAddrOf(s.attestorUrl);
496
+ // Prefer the attestor's own URL; some builds leave the top-level `url`
497
+ // empty but fill agent_card.url (already the correct https base) — use
498
+ // that (stripping the /hello path) before falling back to self-assembly.
499
+ const cardBase = d.agent_card?.url?.replace(/\/hello$/, '');
500
+ const url = d.url ?? cardBase ?? (d.sandbox_id && proxy ? containerUrl(d.sandbox_id, proxy) : undefined);
501
+ if (s.phase === 'running' && url) {
502
+ if (!s.client || s.url !== url) await connectSession(s, url);
503
+ } else {
504
+ s.url = url;
505
+ s.sandboxId = d.sandbox_id ?? s.sandboxId;
506
+ s.client = undefined;
507
+ }
508
+ if (quiet && s.phase === before) return; // background refresh: report only movement
509
+ out(` phase ${s.phase}\n`);
510
+ if (s.url) out(` url ${s.url}\n`);
511
+ const reason = d.container_stage?.state === 'failed' ? d.container_stage.reason : undefined;
512
+ if (reason) out(` last error: ${reason}\n`);
513
+ }
514
+
515
+ /**
516
+ * Wait for a deployment to reach `running` by polling the attestor's public
517
+ * /deployment/:sealId — and FAIL LOUD instead of hanging: a `failed`/`offline`
518
+ * phase (or a failed container_stage) surfaces its recorded reason
519
+ * immediately, and the timeout produces an error naming the last phase seen.
520
+ */
521
+ class WaitCancelled extends Error { constructor() { super('wait cancelled'); } }
522
+
523
+ async function pollRunning(attestorUrl: string, sealId: `0x${string}`, agentId: string, timeoutMs = 360000, signal?: AbortSignal): Promise<{ url: string }> {
524
+ const deadline = Date.now() + timeoutMs;
525
+ const t0 = Date.now();
526
+ let lastPhase = 'contacting attestor';
527
+ let lastShown = '';
528
+ // Transient progress line between phase changes — a deploy sits minutes in
529
+ // one phase with zero output otherwise. Repainted each second; phase-change
530
+ // lines and the final result overwrite it. TTY only.
531
+ const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧'];
532
+ let spin = 0;
533
+ let spinnerShown = false;
534
+ const clearSpinner = (): void => { if (spinnerShown) { out('\r\x1b[2K'); spinnerShown = false; } };
535
+ const ticker = process.stdout.isTTY
536
+ ? setInterval(() => {
537
+ if (signal?.aborted) return;
538
+ spin = (spin + 1) % SPIN.length;
539
+ out(`\r\x1b[2K ${SPIN[spin]} ${lastPhase}… (${Math.floor((Date.now() - t0) / 1000)}s · esc stops waiting, not the deploy)`);
540
+ spinnerShown = true;
541
+ }, 1000)
542
+ : null;
543
+ try {
544
+ // The DETAIL endpoint carries no `url` field (only the listing does), so a
545
+ // running agent's URL is constructed from its sandbox_id + the sandbox
546
+ // proxy address the attestor /config advertises.
547
+ const cfg = (await (await fetch(`${attestorUrl}/config`)).json().catch(() => ({}))) as { sandbox_proxy_addr?: string };
548
+ for (;;) {
549
+ try {
550
+ const d = (await (await fetch(`${attestorUrl}/deployment/${sealId}`)).json()) as {
551
+ phase?: string; url?: string; sandbox_id?: string;
552
+ agent_card?: { url?: string };
553
+ container_stage?: { state?: string; reason?: string };
554
+ };
555
+ lastPhase = d.phase ?? lastPhase;
556
+ if (lastPhase !== lastShown) { clearSpinner(); out(` … ${lastPhase}\n`); lastShown = lastPhase; }
557
+ const cardBase = d.agent_card?.url?.replace(/\/hello$/, '');
558
+ const url = d.url ?? cardBase ?? (d.sandbox_id && cfg.sandbox_proxy_addr ? containerUrl(d.sandbox_id, cfg.sandbox_proxy_addr) : undefined);
559
+ if (d.phase === 'running' && url) return { url };
560
+ const reason = d.container_stage?.state === 'failed' ? d.container_stage?.reason : undefined;
561
+ if (d.phase === 'failed' || reason) {
562
+ throw new CliError('UNKNOWN', `agent ${agentId} did not start: ${reason ?? `phase=${d.phase}`}`, {
563
+ remedy: `run \`reset ${agentId}\` to recreate the container once the cause is fixed`,
564
+ });
565
+ }
566
+ } catch (e) {
567
+ if (e instanceof CliError) throw e;
568
+ // transient fetch error — keep polling until the deadline
569
+ }
570
+ if (Date.now() > deadline) {
571
+ throw new CliError('UNKNOWN', `timed out after ${Math.round(timeoutMs / 1000)}s waiting for agent ${agentId} (last phase: ${lastPhase})`, {
572
+ remedy: 'check `status` — provisioning can lag; retry the command when the phase moves',
573
+ });
574
+ }
575
+ if (signal?.aborted) throw new WaitCancelled();
576
+ await new Promise((r) => setTimeout(r, 4000));
577
+ if (signal?.aborted) throw new WaitCancelled();
578
+ }
579
+ } finally {
580
+ if (ticker) clearInterval(ticker);
581
+ clearSpinner();
582
+ }
583
+ }
584
+
585
+ /** pollRunning wired to the Esc/Ctrl-C interrupt: cancelling abandons the
586
+ * WAIT only — the lifecycle operation keeps going server-side. */
587
+ async function waitRunningInterruptible(irq: Interrupt, attestorUrl: string, sealId: `0x${string}`, agentId: string): Promise<{ url: string } | null> {
588
+ const ac = new AbortController();
589
+ irq.streaming = ac;
590
+ try {
591
+ return await pollRunning(attestorUrl, sealId, agentId, 360000, ac.signal);
592
+ } catch (e) {
593
+ if (e instanceof WaitCancelled || ac.signal.aborted) {
594
+ out('\n(wait cancelled — the operation continues server-side; check with `list` or re-enter with `use`)\n');
595
+ return null;
596
+ }
597
+ throw e;
598
+ } finally {
599
+ irq.streaming = null;
600
+ }
601
+ }
602
+
603
+ /** Shared interrupt state: set while an L2 turn streams; Esc/Ctrl-C abort it.
604
+ * `brake` is the server-side stop for the CURRENT session's agent — wired
605
+ * while inside an L2 session so Esc at an idle prompt can still stop a task
606
+ * running in the background (e.g. an orphaned turn whose stream died). */
607
+ interface Interrupt {
608
+ streaming: AbortController | null;
609
+ brake: (() => void) | null;
610
+ }
611
+
612
+ export async function run(ctx: CommandContext): Promise<void> {
613
+ if (ctx.json) {
614
+ throw new CliError('BAD_FLAG', 'interactive mode has no --json output', {
615
+ remedy: 'use `status`/`list --json` for machine-readable output',
616
+ });
617
+ }
618
+
619
+ const rl = readline.createInterface({
620
+ input: process.stdin,
621
+ output: process.stdout,
622
+ // TTY features only on an actual TTY. Hardcoding true broke every piped
623
+ // use at once: readline echoed raw input back to stdout (INCLUDING the
624
+ // login private key — the exact leak the no---private-key-flag rule
625
+ // exists to prevent), emitted cursor control sequences that NO_COLOR
626
+ // can't suppress, and its line editor raced the async banner for early
627
+ // input. (feedback.md F11/F6/F5)
628
+ terminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
629
+ // Tab completion on the command word. One readline serves both levels,
630
+ // so the candidate set is swapped by whichever REPL loop is active
631
+ // (activeCompletions); empty line + Tab lists everything.
632
+ completer: (line: string): [string[], string] =>
633
+ completeLine(line, { completions: activeCompletions, args: activeArgs, models: chatModelIds, provider: completionProvider, providerModels: providerModelIds }),
634
+ });
635
+ // `ask` is a line QUEUE, not rl.question: lines that arrive while no
636
+ // question is pending (piped input racing the ~4s async banner) used to be
637
+ // consumed by readline with no listener and silently dropped — commands
638
+ // vanished with exit 0 (feedback.md F5). Buffer them instead.
639
+ const pendingLines: string[] = [];
640
+ const waiters: Array<{ res: (s: string) => void; rej: (e: Error) => void }> = [];
641
+ rl.on('line', (l) => {
642
+ const w = waiters.shift();
643
+ if (w) w.res(l);
644
+ else pendingLines.push(l);
645
+ });
646
+ activeRl = rl;
647
+ let stdinClosed = false;
648
+ rl.on('close', () => {
649
+ // EOF while a question is pending — surface the same code rl.question
650
+ // would, which run() already treats as a normal way to leave.
651
+ stdinClosed = true;
652
+ for (const w of waiters.splice(0)) {
653
+ w.rej(Object.assign(new Error('stdin closed'), { code: 'ERR_USE_AFTER_CLOSE' }));
654
+ }
655
+ });
656
+ const ask = (q: string): Promise<string> => {
657
+ const buffered = pendingLines.shift();
658
+ if (buffered !== undefined) {
659
+ out(`${q}${buffered}\n`); // keep the transcript readable in pipes/logs
660
+ return Promise.resolve(buffered);
661
+ }
662
+ if (stdinClosed) {
663
+ return Promise.reject(Object.assign(new Error('stdin closed'), { code: 'ERR_USE_AFTER_CLOSE' }));
664
+ }
665
+ rl.setPrompt(q);
666
+ rl.prompt();
667
+ return new Promise((res, rej) => waiters.push({ res, rej }));
668
+ };
669
+ const irq: Interrupt = { streaming: null, brake: null };
670
+
671
+ let lastSigint = 0;
672
+ rl.on('SIGINT', () => {
673
+ if (irq.streaming) { irq.streaming.abort(); return; } // interrupt the turn, stay in the REPL
674
+ const now = Date.now();
675
+ if (now - lastSigint < 2000) { rl.close(); process.exit(0); }
676
+ lastSigint = now;
677
+ out('\n(press Ctrl-C again to exit)\n');
678
+ rl.prompt();
679
+ });
680
+ readline.emitKeypressEvents(process.stdin, rl);
681
+ process.stdin.on('keypress', (_s, key) => {
682
+ if (key?.name !== 'escape') return;
683
+ if (irq.streaming) { irq.streaming.abort(); return; }
684
+ irq.brake?.(); // idle Esc in a session: stop a background/orphaned task
685
+ });
686
+
687
+ try {
688
+ // Shortcut: `0g-agentdna <agent>` links straight into L2, then drops to L1.
689
+ if (ctx.positionals[0]) {
690
+ // Validate the argument BEFORE demanding a wallet: a typo'd agent ref
691
+ // must exit 2 (BAD_AGENT_REF) per the --help EXIT CODES contract, not
692
+ // masquerade as a missing-wallet error. (feedback.md F1)
693
+ parseAgentRef(ctx.positionals[0]);
694
+ const ag = await withWallet(ctx);
695
+ const s = await attach(ag, requireAttestorUrl(ctx.env), ctx.positionals[0], ask);
696
+ await sessionRepl(s, ask, irq, ctx);
697
+ }
698
+ await managerRepl(ctx, ask, irq);
699
+ } catch (e) {
700
+ // stdin EOF (piped input, Ctrl-D) closes readline while a question is
701
+ // pending — that's a normal way to leave, not an error.
702
+ if ((e as { code?: string }).code !== 'ERR_USE_AFTER_CLOSE') throw e;
703
+ } finally {
704
+ rl.close();
705
+ }
706
+ }
707
+
708
+ /** Resolve an agent ref to this wallet's deployment row (owner listing —
709
+ * lifecycle verbs need sandboxId, which the public listing withholds). */
710
+ async function myRow(ag: AgenticID, refInput: string): Promise<{ sealId: `0x${string}`; agentId: string; phase: string; sandboxId?: string; framework?: string | null }> {
711
+ const ref = parseAgentRef(refInput);
712
+ const rows = await ag.agent.listMyDeployments();
713
+ rememberAgentIds(rows);
714
+ const row = pickRow(ref, refInput, rows);
715
+ if (!row) {
716
+ // Say WHICH of the two things went wrong: the agent doesn't exist here,
717
+ // or it exists but belongs to another wallet (owner-only action).
718
+ const pub = await ag.agent.listDeployments().catch(() => []);
719
+ const exists = !!pickRow(ref, refInput, pub);
720
+ throw new CliError(
721
+ 'AGENT_NOT_FOUND',
722
+ exists
723
+ ? `agent ${refInput} is not yours`
724
+ : `agent ${refInput} does not exist`,
725
+ { remedy: exists ? 'check `whoami` — are you on the right wallet? `list` marks yours with *' : 'check `list` for the agents that exist here' },
726
+ );
727
+ }
728
+ return { sealId: row.sealId, agentId: String(row.agentId ?? '?'), phase: row.phase ?? 'unknown', sandboxId: (row as { sandboxId?: string | null }).sandboxId ?? undefined, framework: (row as { framework?: string | null }).framework ?? null };
729
+ }
730
+
731
+ // ── L1: manager REPL ─────────────────────────────────────────────────────────
732
+
733
+ const L1_HELP =
734
+ 'commands: list · use <id> · hello <id> · call <id> · rate <id> · deploy · start/stop/reset <id> · settings <id> · balance · deposit · withdraw · ack · login · whoami · help · quit';
735
+
736
+ const L1_HELP_FULL = `manager commands
737
+ list agents on this attestor (* = owned by your wallet)
738
+ use <agentId|sealId> enter YOUR agent's session — works in ANY phase
739
+ hello <agentId|sealId> any agent's public /hello: identity, services,
740
+ routes, serve-proof verification (with a wallet
741
+ configured it also banks a rating ticket, see rate)
742
+ call <id> [path [body]] use an agent's public service as a client; the
743
+ response banks a rating ticket (bare call = list
744
+ its services)
745
+ rate <id> [score] [/ep] rate an agent on-chain (canonical 8004 + TEE mark).
746
+ Spends a ticket banked by call/hello (<1h) — no
747
+ interaction, no rating; picks among multiple
748
+ tickets; owners cannot rate their own agents
749
+ deploy new-agent wizard (framework + model), then chat
750
+ start <id> start a stopped agent
751
+ stop <id> stop a running agent
752
+ reset <id> recreate an agent's container (uses the recorded
753
+ framework — 'reset <id> pick' to change; uses the
754
+ stored key from \`login\`)
755
+ retry <id|sealId> resume a FAILED deploy/clone under the same identity
756
+ (re-runs the failed on-chain stages; reset after)
757
+ settings <id> [k=v …] show the agent's configuration document (which model
758
+ it thinks with, and how hard); with assignments —
759
+ model=… provider=… thinking=low|high|max
760
+ others=<json> — merge and write it (owner-signed)
761
+ clone <id> [to] clone an agent. Yours: mints to you (or <to>).
762
+ Someone else's: goes through its fork policy — works
763
+ iff the seller granted YOUR wallet. Lands offline
764
+ transfer <id> <to> transfer YOUR agent to another wallet (irreversible;
765
+ new owner acks + resets to take over the runtime)
766
+ authorizer <id> [a|off] show the agent's fork policy; owner sets a policy
767
+ contract address to open fork sales, off to close
768
+ ('standard' = the official policy from /config)
769
+ grant <id> <buyer> seller: allow <buyer> to fork this agent (standard
770
+ policy only; a switch — revoke closes it again)
771
+ revoke <id> <buyer> seller: close the door for <buyer>
772
+ balance prepaid sandbox balance, burn rate, runway
773
+ deposit [og] fund the prepaid balance (default 1 OG)
774
+ withdraw [og] get prepaid funds back: shows balance + pending,
775
+ offers to claim matured refunds, then asks how
776
+ much (more) to withdraw (time-locked)
777
+ ack acknowledge the TEE trust root (deploy/start/reset
778
+ do this implicitly; re-run after an attestor upgrade)
779
+ login [provider] setup: attestor URL, owner key, provider, inference key
780
+ (Enter keeps the current value; secrets echo *)
781
+ whoami show attestor / wallet / api-key / ack status
782
+ help this text
783
+ quit exit (Ctrl-C twice also works)`;
784
+
785
+ async function managerRepl(ctx: CommandContext, ask: (q: string) => Promise<string>, irq: Interrupt): Promise<void> {
786
+ // The environment marker in every prompt: cross-environment mistakes (a
787
+ // config.json pointing at prod while working on dev) are silent otherwise —
788
+ // the banner scrolls away, and a wrong-attestor error reads like a missing
789
+ // agent. Recomputed per prompt, NOT frozen once: `login` can change the
790
+ // attestor mid-session, and a stale label then disagrees with the real
791
+ // backend (the exact confusion this marker exists to prevent).
792
+ const key = ctx.env.privateKey ?? loadKey() ?? undefined;
793
+ const hasApiKey = !!configuredInferenceKey(loadConfig().inferenceProvider ?? '0g-compute');
794
+ const wallet = key ? await addressOf(key).catch(() => '(malformed key — run `login`)') : null;
795
+ const short = (a: string) => `${a.slice(0, 6)}…${a.slice(-4)}`;
796
+ // Pixel splash (the avatar generator's panda) when the terminal can show
797
+ // it; the plain box otherwise (pipes, NO_COLOR, dumb terminals).
798
+ if (process.stdout.isTTY && !process.env.NO_COLOR) {
799
+ const art = pandaLines();
800
+ const caption = ['', '', '', ' \x1b[1m0G AgentDNA\x1b[0m', ' interactive shell', '', '', ''];
801
+ out('\n');
802
+ art.forEach((l, i) => out(` ${l}${caption[i] ?? ''}\n`));
803
+ out('\n');
804
+ } else {
805
+ out('\n╭──────────────────────────────────────╮\n');
806
+ out(`│${' 0G AgentDNA — interactive shell'.padEnd(38)}│\n`);
807
+ out('╰──────────────────────────────────────╯\n\n');
808
+ }
809
+ // Ack read and the update hint both hit the attestor; they start before the
810
+ // first await and share ONE wall-clock ceiling (sequential races cost 8s on
811
+ // a hanging attestor). The hint keeps its OWN /config fetch by design — it
812
+ // must work for a keyless user too, where no wallet client exists to share
813
+ // one. A hanging (vs refusing) attestor must not stall the banner.
814
+ let ack = '';
815
+ out(` attestor ${ctx.env.attestorUrl ?? '(unset)'}\n`);
816
+ {
817
+ const started = Date.now();
818
+ const readAck = key && ctx.env.attestorUrl
819
+ ? withWallet(ctx)
820
+ .then((ag) => ag.ackStatus())
821
+ .then(({ allAcked }) => (allAcked ? 'ok' : 'MISSING — run `ack`'))
822
+ .catch(() => '(unreachable)')
823
+ : Promise.resolve('');
824
+ // The hint is NOT key-gated: a pre-login user with an attestor configured
825
+ // is exactly who may need the newer CLI.
826
+ const hintDone = maybePrintUpdateHint(ctx.env.attestorUrl).catch(() => {});
827
+ ack = await Promise.race([readAck, new Promise<string>((r) => setTimeout(() => r('(unreachable)'), 4000).unref())]);
828
+ const left = Math.max(0, 4000 - (Date.now() - started));
829
+ await Promise.race([hintDone, new Promise<void>((r) => setTimeout(r, left).unref())]);
830
+ updateHintWindowOpen = false; // a losing fetch that resolves later stays silent
831
+ }
832
+ out(` wallet ${wallet ? (wallet.startsWith('0x') ? short(wallet) : wallet) : '(none)'}\n`);
833
+ out(` api key ${hasApiKey ? 'set' : '(none)'}\n`);
834
+ if (ack) out(` ack ${ack}\n`);
835
+ out('\n');
836
+ if (!ctx.env.attestorUrl || !key) {
837
+ out(' first run? type `login` — one guided setup for the attestor + keys\n\n');
838
+ } else if (!hasApiKey) {
839
+ // API key is only needed for deploy/reset — don't re-onboard a
840
+ // configured user over an optional item (feedback.md F8).
841
+ out(' `help` commands · `use <id>` chat · (no inference API key — `login` adds one when you deploy)\n\n');
842
+ } else {
843
+ out(' `help` commands · `use <id>` chat · Esc interrupts a turn\n\n');
844
+ }
845
+ // Prefill the completion id cache in the background: without it, `use
846
+ // <Tab>` is dead until the first list/balance/agent op of the session.
847
+ // Fire-and-forget — a slow attestor costs the completions, never the prompt.
848
+ if (key && ctx.env.attestorUrl) {
849
+ withWallet(ctx).then((ag) => {
850
+ ag.agent.listMyDeployments().then(rememberAgentIds).catch(() => { /* completions only */ });
851
+ prefetchModelIds(ag); // so `model=<Tab>` has the catalog ready
852
+ }).catch(() => { /* completions only */ });
853
+ }
854
+ for (;;) {
855
+ activeCompletions = L1_WORDS;
856
+ activeArgs = L1_ARGS;
857
+ const line = (await ask(`\n0g-agentdna [${hostOf(ctx.env.attestorUrl)}]> `)).trim();
858
+ // Bare Enter refreshes the account status — the L1 analog of L2's
859
+ // bare-Enter agent refresh.
860
+ // Quote-aware, so a value with a space in it (`settings 286
861
+ // others='{"a": 1}'`) survives the way it does in a real shell.
862
+ const [cmd, ...args] = line ? tokenize(line) : ['whoami'];
863
+ try {
864
+ if (cmd === 'quit' || cmd === 'exit') return;
865
+ if (cmd === 'help') { out(`${L1_HELP_FULL}\n`); continue; }
866
+
867
+ if (cmd === 'login' || cmd === 'config') {
868
+ // Guided setup — attestor URL, owner key, provider, inference key. Enter
869
+ // keeps the current value; a typed value replaces it. Secrets masked.
870
+ const url = (await ask(`attestor URL [${ctx.env.attestorUrl ?? 'unset'}]: `)).trim();
871
+ if (url) { saveConfig({ attestorUrl: url.replace(/\/$/, '') }); ctx.env.attestorUrl = url.replace(/\/$/, ''); }
872
+
873
+ const hasKey = !!(ctx.env.privateKey ?? loadKey());
874
+ const key = (await askSecret(ask, `owner private key [${hasKey ? 'set — Enter to keep' : 'unset'}]: `)).trim();
875
+ if (key) {
876
+ // Cache what was SAVED, not what was typed — saveKey normalizes
877
+ // (0x prefix optional), and a raw un-prefixed value in ctx.env
878
+ // makes every later command see a "malformed" key until restart.
879
+ try { saveKey(key); ctx.env.privateKey = normalizeKey(key)!; ctx.env.privateKeySource = 'file'; }
880
+ catch (e) { out(`private key not saved: ${(e as Error).message}\n`); }
881
+ }
882
+
883
+ if (ctx.env.attestorUrl) {
884
+ const client = await buildClient(ctx.env);
885
+ knownProviders = await client.agent.refreshProviders();
886
+ } else { knownProviders = listInferenceProviders(); }
887
+ const selected = args[0] ?? await pickInferenceProvider(ask, loadConfig().inferenceProvider ?? '0g-compute');
888
+ if (!knownProviders.some((provider) => provider.id === selected)) throw new CliError('BAD_FLAG', `unknown inference provider: ${selected}`);
889
+ saveConfig({ inferenceProvider: selected });
890
+ const hasApi = !!configuredInferenceKey(selected);
891
+ const api = (await askSecret(ask, `${selected} API key [${hasApi ? 'set — Enter to keep' : 'unset'}]: `)).trim();
892
+ if (api) saveApiKey(selected, api);
893
+ out(`saved to ${configPaths().dir} (credentials chmod 600)\n`);
894
+ // Re-seed the startup-time caches that were filled from the OLD
895
+ // attestor or wallet: without this, Tab completion keeps offering the
896
+ // previous environment's (or wallet's — listMyDeployments is
897
+ // per-wallet) agent ids and model names until the next `list` (same
898
+ // root cause as the prompt marker — a login mid-session leaves
899
+ // startup-seeded state stale). Best-effort, completion-only.
900
+ if (ctx.env.privateKey) {
901
+ withWallet(ctx).then((ag) => {
902
+ ag.agent.listMyDeployments().then(rememberAgentIds).catch(() => { /* completions only */ });
903
+ prefetchModelIds(ag);
904
+ }).catch(() => { /* completions only */ });
905
+ }
906
+ continue;
907
+ }
908
+
909
+ if (cmd === 'balance') {
910
+ // Account-level view: prepaid sandbox balance, the burn rate implied
911
+ // by how many of this wallet's agents are running, and the runway.
912
+ const ag = await withWallet(ctx);
913
+ let effErr: string | null = null;
914
+ const [est, rows, detail, eff] = await Promise.all([
915
+ ag.agent.estimateCosts(),
916
+ ag.agent.listMyDeployments(),
917
+ ag.getBalanceDetail().catch(() => null),
918
+ ag.getEffectiveBalance().catch((e: Error) => { effErr = e.message; return null; }),
919
+ ]);
920
+ rememberAgentIds(rows);
921
+ const running = rows.filter((r) => r.phase === 'running').length;
922
+ const burnPerMin = est.costPerMinWei * BigInt(running);
923
+ const runway = burnPerMin > 0n && est.prepaidBalanceWei != null ? Number(est.prepaidBalanceWei / burnPerMin) : null;
924
+ moneyBlock(est.prepaidBalanceWei, eff, effErr);
925
+ if (detail && detail.pendingRefund > 0n) {
926
+ out(`pending refund : ${og(detail.pendingRefund)} (unlocks ${new Date(Number(detail.refundUnlockAt) * 1000).toLocaleString()} — claim with \`withdraw\`)\n`);
927
+ }
928
+ out(`running agents : ${running} (× ${og(est.costPerMinWei)}/min each)\n`);
929
+ out(`burn rate : ${og(burnPerMin)}/min\n`);
930
+ out(`runway : ${runway == null ? (running === 0 ? '∞ (nothing running)' : 'n/a') : `~${runway} min`}\n`);
931
+ out('add funds with `deposit [amount OG]` · withdraw with `withdraw [amount OG]`\n');
932
+ continue;
933
+ }
934
+
935
+ if (cmd === 'deposit') {
936
+ const ag = await withWallet(ctx);
937
+ const amt = args[0] || (await ask('amount OG [1]: ')).trim() || '1';
938
+ const tx = await ag.deposit({ amountWei: parseEther(amt) });
939
+ await ag.waitForTransaction(tx);
940
+ out(`deposited ${amt} OG to the prepaid sandbox balance (tx ${tx})\n`);
941
+ continue;
942
+ }
943
+
944
+ if (cmd === 'withdraw') {
945
+ // Two-step by contract design: requestRefund moves funds into a
946
+ // time-locked pending pot; withdrawRefund claims it after the lock.
947
+ // `withdraw <og>` starts one, bare `withdraw` claims (or reports the
948
+ // lock) — the pending state decides which step the user is on.
949
+ const ag = await withWallet(ctx);
950
+ const d = await ag.getBalanceDetail();
951
+ const unlockMs = Number(d.refundUnlockAt) * 1000;
952
+ let pending = d.pendingRefund;
953
+ // Status first: spendable, the pending pot (one per provider — the
954
+ // contract holds a single pot, not a list) and its lock state.
955
+ out(`spendable : ${og(d.balance)}\n`);
956
+ out(`pending : ${pending > 0n ? `${og(pending)} ${Date.now() >= unlockMs ? '(unlocked — claimable now)' : `(locked until ${new Date(unlockMs).toLocaleString()})`}` : '(none)'}\n`);
957
+ // Matured funds are offered FIRST: requestRefund re-absorbs the pot
958
+ // and re-locks it, so requesting before claiming would freeze money
959
+ // that was already free.
960
+ if (pending > 0n && Date.now() >= unlockMs) {
961
+ const yn = (await ask(`claim ${og(pending)} to your wallet now? [Y/n]: `)).trim().toLowerCase();
962
+ if (!yn || yn === 'y' || yn === 'yes') {
963
+ const tx = await ag.withdrawRefund();
964
+ await ag.waitForTransaction(tx);
965
+ out(`withdrew ${og(pending)} to your wallet (tx ${tx})\n`);
966
+ pending = 0n;
967
+ }
968
+ }
969
+ // Then the request. The amount asked is the INCREMENT, drawn from the
970
+ // spendable balance — the contract itself only takes a new total
971
+ // (re-absorbing the pot, restarting the lock), so we submit
972
+ // pending + amount on the user's behalf.
973
+ const more = pending > 0n ? ` more (joins the pending ${og(pending)}; lock restarts)` : '';
974
+ const amt = args[0] || (await ask(`withdraw how much${more}? [max ${og(d.balance)}, empty to skip]: `)).trim();
975
+ if (!amt) continue;
976
+ const amountWei = parseEther(amt);
977
+ if (amountWei > d.balance) { out(`only ${og(d.balance)} spendable — cannot withdraw ${amt} OG\n`); continue; }
978
+ const tx = await ag.requestRefund({ amountWei: amountWei + pending });
979
+ await ag.waitForTransaction(tx);
980
+ const after = await ag.getBalanceDetail();
981
+ if (pending > 0n) out(`pending refund: ${og(pending)} → ${og(after.pendingRefund)} (lock restarted)\n`);
982
+ else out(`${amt} OG moved to pending refund (tx ${tx})\n`);
983
+ out(`unlocks ${new Date(Number(after.refundUnlockAt) * 1000).toLocaleString()} — claim then with a bare \`withdraw\`\n`);
984
+ continue;
985
+ }
986
+
987
+
988
+ if (cmd === 'whoami') {
989
+ out(`attestor: ${ctx.env.attestorUrl ?? '(unset)'}\n`);
990
+ const key = ctx.env.privateKey ?? loadKey() ?? undefined;
991
+ out(`wallet : ${key ? await addressOf(key).catch(() => '(malformed key — run `login`)') : '(no key — run `login`)'}\n`);
992
+ out(`provider: ${loadConfig().inferenceProvider ?? '0g-compute'} (default for deploy/login)\n`);
993
+ for (const provider of knownProviders) out(`key ${provider.id}: ${configuredInferenceKey(provider.id) ? 'set' : '(not registered)'}\n`);
994
+ if (key && ctx.env.attestorUrl) {
995
+ // The three status reads are independent — fetch them in parallel
996
+ // (they were serial: 2.9s measured; parallel is bounded by the
997
+ // slowest, ~1.5s).
998
+ const ag2 = await withWallet(ctx);
999
+ const [ackRes, dRes, eff] = await Promise.all([
1000
+ ag2.ackStatus().then((r) => ({ ok: true as const, r })).catch((e: Error) => ({ ok: false as const, e })),
1001
+ ag2.getBalanceDetail().then((r) => ({ ok: true as const, r })).catch((e: Error) => ({ ok: false as const, e })),
1002
+ ag2.getEffectiveBalance().catch(() => null),
1003
+ ]);
1004
+ if (ackRes.ok) {
1005
+ const { allAcked, missing } = ackRes.r;
1006
+ out(`ack : ${allAcked ? 'ok (trust root acknowledged)' : `missing ${missing.join(', ')} — run \`ack\``}\n`);
1007
+ } else {
1008
+ out(`ack : (unreadable: ${ackRes.e.message})\n`);
1009
+ }
1010
+ try {
1011
+ if (!dRes.ok) throw dRes.e;
1012
+ const d = dRes.r;
1013
+ const effNote = eff && eff.availableWei < eff.balanceWei
1014
+ ? ` — AVAILABLE ${og(eff.availableWei)} (${og(eff.outstandingDebtWei + eff.pendingSettlementWei + eff.reservedWei)} owed/queued off-chain)`
1015
+ : '';
1016
+ out(`balance : ${og(d.balance)} prepaid${d.pendingRefund > 0n ? ` (+${og(d.pendingRefund)} pending refund)` : ''}${effNote}\n`);
1017
+ } catch { /* serving not configured — skip the line */ }
1018
+ } else {
1019
+ // Degrade like the other lines instead of silently omitting the
1020
+ // fourth one (feedback.md F7).
1021
+ out(`ack : ${key ? '(needs an attestor URL — run `login`)' : '(needs a wallet — run `login`)'}\n`);
1022
+ }
1023
+ continue;
1024
+ }
1025
+
1026
+ if (cmd === 'ack') {
1027
+ // Manual trust-root acknowledgment. deploy/start/reset all run this
1028
+ // implicitly, but the attestor's ackVersion can bump under you (e.g.
1029
+ // a redeploy) — this is the explicit re-ack.
1030
+ const ag = await withWallet(ctx);
1031
+ const { allAcked, missing } = await ag.ackStatus();
1032
+ if (allAcked) { out('trust root already acknowledged — nothing to do\n'); continue; }
1033
+ out(`acknowledging: ${missing.join(', ')}\n`);
1034
+ const tx = await ag.ack();
1035
+ if (tx) { out(`ack() → ${tx} (waiting…)\n`); await ag.waitForTransaction(tx); }
1036
+ out('acknowledged\n');
1037
+ continue;
1038
+ }
1039
+
1040
+ if (cmd === 'list') {
1041
+ // Public listing — no wallet needed. Minted rows carry owner (chain-
1042
+ // public via ownerOf); "mine" marks still come from the owner-signed
1043
+ // listing so unminted rows attribute correctly too.
1044
+ let key = ctx.env.privateKey ?? loadKey() ?? undefined;
1045
+ let ag: AgenticID;
1046
+ try {
1047
+ ag = key ? await withWallet(ctx) : await clientFor(ctx, false);
1048
+ } catch (e) {
1049
+ // Malformed key must not block a PUBLIC listing — warn, go walletless.
1050
+ out(`warning: ${(e as CliError).message} — listing without ownership marks\n`);
1051
+ key = undefined;
1052
+ ag = await clientFor(ctx, false);
1053
+ }
1054
+ const mineOnly = args.includes('--mine') || args.includes('mine');
1055
+ if (mineOnly && !key) { out('list --mine needs a wallet — run `login` first\n'); continue; }
1056
+ // The two listings are independent — fetch them in parallel. The
1057
+ // owner-signed rows carry `owner` for UNMINTED rows too (the public
1058
+ // tier shows it only once minted); keyed by sealId for the table.
1059
+ const [rows, myRows] = await Promise.all([
1060
+ ag.agent.listDeployments(),
1061
+ key
1062
+ ? ag.agent.listMyDeployments().catch(() => null)
1063
+ : Promise.resolve(null),
1064
+ ]);
1065
+ const mine = myRows ? new Map(myRows.map((r) => [r.sealId, r])) : null;
1066
+ // A failed owner listing must not read as an empty wallet (F2): with
1067
+ // --mine it aborts with the reason; without, fall back unmarked.
1068
+ if (key && !mine) {
1069
+ if (mineOnly) { out('could not fetch your owner-signed listing — try again or check the attestor\n'); continue; }
1070
+ out('warning: owner listing unavailable — showing unmarked rows\n');
1071
+ }
1072
+ const shown = mineOnly ? rows.filter((r) => mine?.has(r.sealId)) : rows;
1073
+ if (!shown.length) { out(mineOnly ? 'no agents owned by this wallet here\n' : 'no agents on this attestor\n'); continue; }
1074
+ // From the full public listing, as in `list`: a --mine view must not
1075
+ // strip the annotation off a child whose parent it hides.
1076
+ const sealToAgent = sealToAgentMap(rows);
1077
+ out(renderListHeader());
1078
+ for (const r of shown) {
1079
+ const own = mine?.get(r.sealId);
1080
+ // The owner tier carries owner and agentSeal for UNMINTED rows too.
1081
+ out(renderListRow({ ...r, agentSeal: own?.agentSeal ?? r.agentSeal }, own?.owner ?? r.owner, own ? '*' : ' ', sealToAgent));
1082
+ }
1083
+ if (mine && !mineOnly) out('(* = owned by your wallet · `list --mine` filters to them)\n');
1084
+ if (shown.some((r) => r.agentId == null)) out("('?' rows have no agentId yet — reference them by sealId prefix, e.g. retry 0x" + shown.find((r) => r.agentId == null)!.sealId.slice(2, 12) + ')\n');
1085
+ continue;
1086
+ }
1087
+
1088
+ if (cmd === 'stop' || cmd === 'start' || cmd === 'reset') {
1089
+ // Manager-level lifecycle: act and stay at L1 (enter with `use` to chat).
1090
+ if (!args[0]) { out(`usage: ${cmd} <agentId|sealId>\n`); continue; }
1091
+ const ag = await withWallet(ctx);
1092
+ const attestorUrl = requireAttestorUrl(ctx.env);
1093
+ const row = await myRow(ag, args[0]);
1094
+ if (cmd === 'stop') {
1095
+ if (row.phase !== 'running' || !row.sandboxId) { out(`agent ${row.agentId} is ${row.phase} — nothing to stop\n`); continue; }
1096
+ await ag.agent.stop(row.sealId, row.sandboxId);
1097
+ out(`agent ${row.agentId} stopped\n`);
1098
+ continue;
1099
+ }
1100
+ if (cmd === 'start') {
1101
+ if (row.phase === 'running') { out(`agent ${row.agentId} is already running\n`); continue; }
1102
+ if (row.phase !== 'stopped' || !row.sandboxId) { out(`agent ${row.agentId} is ${row.phase} — a plain start cannot revive it; run: reset ${row.agentId}\n`); continue; }
1103
+ if (!(await ensureOwnerReady(ag, ask))) { out('start cancelled — prepaid balance too low\n'); continue; }
1104
+ out(`starting agent ${row.agentId}… (Esc cancels the wait)\n`);
1105
+ await ag.agent.start(row.sealId, row.sandboxId);
1106
+ const r = await waitRunningInterruptible(irq, attestorUrl, row.sealId, row.agentId);
1107
+ if (r) out(`running at ${r.url} — enter with: use ${row.agentId}\n`);
1108
+ continue;
1109
+ }
1110
+ // reset — the row remembers its framework; ask only when unknown
1111
+ // (legacy rows). `reset <id> pick` forces the menu to change harness.
1112
+ const forcePick = args[1] === 'pick';
1113
+ let framework: string;
1114
+ if (row.framework && !forcePick) {
1115
+ framework = row.framework;
1116
+ out(`framework: ${framework} (recorded — \`reset ${args[0]} pick\` to change)\n`);
1117
+ } else {
1118
+ framework = await pickFramework(attestorUrl, ask, row.framework ?? undefined);
1119
+ }
1120
+ const provider = await agentInferenceProvider(ag, row.sealId);
1121
+ await ag.agent.assertProviderSupported(provider, { sealId: row.sealId, framework });
1122
+ const apiKey = await inferenceKey(ctx, ask, provider);
1123
+ if (!(await ensureOwnerReady(ag, ask))) { out('reset cancelled — prepaid balance too low\n'); continue; }
1124
+ out(`resetting agent ${row.agentId} as ${framework}… (Esc cancels the wait)\n`);
1125
+ await ag.agent.reset(row.sealId, { provider, framework, apiKey });
1126
+ const r = await waitRunningInterruptible(irq, attestorUrl, row.sealId, row.agentId);
1127
+ if (r) out(`running at ${r.url} — enter with: use ${row.agentId}\n`);
1128
+ continue;
1129
+ }
1130
+
1131
+ if (cmd === 'retry') {
1132
+ // Resume a FAILED deploy/clone under the SAME identity (sealId) —
1133
+ // the attestor re-runs the failed idempotent stages (storage, mint,
1134
+ // setAgentURI). Never redeploy a failed row: that would orphan the
1135
+ // identity. Container work isn't retried here — once minted, use
1136
+ // `reset <id>` to bring the agent up.
1137
+ if (!args[0]) { out('usage: retry <agentId|sealId>\n'); continue; }
1138
+ const ag = await withWallet(ctx);
1139
+ const row = await findAgentRow(ag, args[0]);
1140
+ if (!row) { out(`no agent matching ${args[0]} on this attestor\n`); continue; }
1141
+ if (row.phase !== 'failed') { out(`agent ${row.agentId ?? row.sealId} is ${row.phase} — retry only applies to failed rows\n`); continue; }
1142
+ out(`retrying seal ${row.sealId} — re-running the failed stages… (Esc-proof; may take a minute)\n`);
1143
+ await ag.agent.retry(row.sealId);
1144
+ try {
1145
+ const agentId = await ag.agent.waitForMint(row.sealId);
1146
+ out(`recovered: agent ${agentId} minted under the same seal\n`);
1147
+ out(`it lands offline — bring it up with: reset ${agentId}\n`);
1148
+ } catch (e) {
1149
+ out(`still failing: ${(e as Error).message}\n`);
1150
+ }
1151
+ continue;
1152
+ }
1153
+
1154
+ if (cmd === 'settings') {
1155
+ // The document is the owner's in both directions — reading it is
1156
+ // owner-signed too — so the wallet is needed even for a bare show.
1157
+ if (!args[0]) { out('usage: settings <agentId|sealId> [model=… thinking=low|high|max provider=… others=<json>]\n'); continue; }
1158
+ const ag = await withWallet(ctx);
1159
+ const row = await findAgentRow(ag, args[0]);
1160
+ if (!row) { out(`no agent matching ${args[0]} on this attestor\n`); continue; }
1161
+ await settingsOp(ag, row.sealId, args.slice(1), row.phase === 'running' && row.url ? row.url : undefined);
1162
+ continue;
1163
+ }
1164
+
1165
+ if (cmd === 'authorizer') {
1166
+ // Extra args are ambiguous (`authorizer <id> <addr> off` — set or
1167
+ // clear?) — refuse rather than silently act on a guess.
1168
+ if (!args[0] || args.length > 2) { out('usage: authorizer <agentId|sealId> [address|off]\n'); continue; }
1169
+ if (!args[1]) {
1170
+ // Read-only: anyone can inspect any agent's fork policy.
1171
+ const ag = await clientFor(ctx, false);
1172
+ const id = await mintedTokenId(ag, args[0]);
1173
+ const a = await ag.agent.cloneAuthorizerOf(id);
1174
+ out(a === ZERO_ADDR
1175
+ ? `agent ${id}: fork sales closed (no effective policy)\n`
1176
+ : `agent ${id}: fork policy ${a}\n`);
1177
+ continue;
1178
+ }
1179
+ const ag = await withWallet(ctx);
1180
+ const id = await mintedTokenId(ag, args[0]);
1181
+ let target = args[1].toLowerCase() === 'off' ? ZERO_ADDR : args[1];
1182
+ if (target.toLowerCase() === 'standard') {
1183
+ // Resolve the OFFICIAL stock policy from the attestor /config so
1184
+ // publishers don't hand-copy addresses out of DEPLOYMENT.md.
1185
+ const cfg = await (await fetch(`${requireAttestorUrl(ctx.env)}/config`)).json() as { standard_clone_authorizer_addr?: string };
1186
+ if (!cfg.standard_clone_authorizer_addr) {
1187
+ out('this attestor does not advertise a standard clone policy (standard_clone_authorizer_addr missing from /config) — pass the policy address explicitly\n');
1188
+ continue;
1189
+ }
1190
+ target = cfg.standard_clone_authorizer_addr;
1191
+ out(`standard policy: ${target}\n`);
1192
+ }
1193
+ if (target !== ZERO_ADDR && !isAddress(target)) { out('authorizer must be an address, `standard`, or `off`\n'); continue; }
1194
+ const tx = await ag.agent.setCloneAuthorizer(id, target as Address);
1195
+ await ag.agent.waitForTransaction(tx);
1196
+ out(target === ZERO_ADDR
1197
+ ? `agent ${id}: fork sales closed\n`
1198
+ : `agent ${id}: fork policy set to ${target}\n allow buyers with: grant ${id} <buyer>\n`);
1199
+ continue;
1200
+ }
1201
+
1202
+ if (cmd === 'grant' || cmd === 'revoke') {
1203
+ if (!args[0] || !args[1]) {
1204
+ out(`usage: ${cmd} <agentId|sealId> <buyer>\n`);
1205
+ continue;
1206
+ }
1207
+ if (!isAddress(args[1])) { out('buyer must be a 0x address\n'); continue; }
1208
+ const ag = await withWallet(ctx);
1209
+ const id = await mintedTokenId(ag, args[0]);
1210
+ const tx = cmd === 'grant'
1211
+ ? await ag.agent.grantClone(id, args[1] as Address)
1212
+ : await ag.agent.revokeClone(id, args[1] as Address);
1213
+ await ag.agent.waitForTransaction(tx);
1214
+ out(cmd === 'grant'
1215
+ ? `${args[1]} may now fork agent ${id}\n they clone with: clone ${id}\n`
1216
+ : `${args[1]} may no longer fork agent ${id}\n`);
1217
+ continue;
1218
+ }
1219
+
1220
+ if (cmd === 'transfer') {
1221
+ if (!args[0] || !args[1]) { out('usage: transfer <agentId|sealId> <to>\n'); continue; }
1222
+ if (!isAddress(args[1])) { out('to must be a 0x address\n'); continue; }
1223
+ const ag = await withWallet(ctx);
1224
+ const id = await mintedTokenId(ag, args[0]);
1225
+ const from = await ag.agent.ownerOf(id);
1226
+ const yn = (await ask(`transfer agent ${id} to ${args[1]} — IRREVERSIBLE. proceed? [y/N]: `)).trim().toLowerCase();
1227
+ if (yn !== 'y' && yn !== 'yes') { out('transfer cancelled\n'); continue; }
1228
+ const tx = await ag.agent.transferFrom(from, args[1] as Address, id);
1229
+ await ag.agent.waitForTransaction(tx);
1230
+ out(`agent ${id} transferred to ${args[1]}\n`);
1231
+ out('the new owner acks + resets to take over the runtime; any fork policy you set is now dormant\n');
1232
+ continue;
1233
+ }
1234
+
1235
+ if (cmd === 'clone') {
1236
+ if (!args[0]) { out('usage: clone <agentId|sealId> [to]\n'); continue; }
1237
+ const ag = await withWallet(ctx);
1238
+ const id = await mintedTokenId(ag, args[0]);
1239
+ const key = ctx.env.privateKey ?? loadKey();
1240
+ const me = (await addressOf(key as `0x${string}`)) as Address;
1241
+ // Route by identity: the source's owner clones directly (owner mode,
1242
+ // optional recipient); anyone else can only go through the token's
1243
+ // fork policy (the seller must have granted THIS wallet).
1244
+ const sourceOwner = await ag.agent.ownerOf(id);
1245
+ let params: Parameters<typeof ag.agent.clone>[0];
1246
+ if (sourceOwner.toLowerCase() === me.toLowerCase()) {
1247
+ const to = args[1] ?? me;
1248
+ if (!isAddress(to)) { out('to must be a 0x address\n'); continue; }
1249
+ params = { sourceAgentId: id, targetOwner: to as Address };
1250
+ } else {
1251
+ if (args[1]) { out('policy clones always mint to YOUR wallet — drop the <to> argument\n'); continue; }
1252
+ params = { sourceAgentId: id, targetOwner: me, authorization: { authData: '0x' } };
1253
+ }
1254
+ if (!(await ensureOwnerReady(ag, ask))) { out('clone cancelled — prepaid balance too low\n'); continue; }
1255
+ out(`cloning agent ${id}… (TEE re-seal + on-chain mint, may take a minute)\n`);
1256
+ const r = await ag.agent.clone(params, { wait: 'minted' });
1257
+ out(`cloned: new agent ${r.agentId} → ${params.targetOwner}\n`);
1258
+ out(`it lands offline — its owner brings it up with: reset ${r.agentId}\n`);
1259
+ continue;
1260
+ }
1261
+
1262
+ if (cmd === 'hello') {
1263
+ // Public inspection of ANY agent (yours or not) — no wallet needed.
1264
+ if (!args[0]) { out('usage: hello <agentId|sealId>\n'); continue; }
1265
+ const ag = await clientFor(ctx, false);
1266
+ const ref = parseAgentRef(args[0]);
1267
+ const rows = await ag.agent.listDeployments();
1268
+ rememberAgentIds(rows);
1269
+ const row = pickRow(ref, args[0], rows);
1270
+ if (!row) { out(`agent ${args[0]} does not exist\n`); continue; }
1271
+ if (row.phase !== 'running' || !row.url) { out(`agent ${args[0]} is ${row.phase ?? 'unknown'} — not reachable\n`); continue; }
1272
+ // With a wallet configured, declare it as the proof's redeemer so this
1273
+ // visit banks a rating ticket (see `rate`). Still no signing involved.
1274
+ const helloKey = ctx.env.privateKey ?? loadKey() ?? undefined;
1275
+ const helloAddr = helloKey ? ((await addressOf(helloKey)) as `0x${string}`) : undefined;
1276
+ await showHello(ag, row.url, helloAddr);
1277
+ continue;
1278
+ }
1279
+
1280
+ if (cmd === 'call') {
1281
+ // Use an agent's public service as a client — the experience that
1282
+ // earns the right to rate. The response banks a rating ticket bound
1283
+ // to your wallet; `call <id>` alone lists the services.
1284
+ if (!args[0]) { out('usage: call <agentId|sealId> [</path> [json-body]]\n'); continue; }
1285
+ const ag = await withWallet(ctx);
1286
+ const my = (await addressOf(ctx.env.privateKey!)) as `0x${string}`;
1287
+ const row = await findAgentRow(ag, args[0]);
1288
+ if (!row) { out(`agent ${args[0]} does not exist\n`); continue; }
1289
+ if (row.phase !== 'running' || !row.url) { out(`agent ${args[0]} is ${row.phase ?? 'unknown'} — not reachable\n`); continue; }
1290
+ // Service table for method resolution (no client address — this lookup
1291
+ // is not the interaction being rated, so it must not bank a ticket).
1292
+ const services = await servicesOf(row.url);
1293
+ if (!args[1]) {
1294
+ if (!services.length) { out('this agent registers no public services (only /hello)\n'); continue; }
1295
+ out('services:\n');
1296
+ for (const sv of services) out(` ${sv.method.padEnd(4)} ${sv.path.padEnd(24)} ${sv.transport === 'mcp' ? '[mcp] ' : ''}${sv.description ?? ''}${sv.skill ? ` [skill: ${sv.skill}]` : ''}\n`);
1297
+ out(`call one with: call ${args[0]} <path> [json-body]${services.some((sv) => sv.transport === 'mcp') ? '\n[mcp] entries speak MCP (JSON-RPC over POST) — mount the path in an MCP client; a plain call posts raw JSON' : ''}\n`);
1298
+ continue;
1299
+ }
1300
+ const path = args[1];
1301
+ if (!path.startsWith('/')) { out('path must start with /\n'); continue; }
1302
+ // The body is free-form — take it VERBATIM from the line. Running it
1303
+ // through the shell-style splitter and re-joining the pieces eats the
1304
+ // quote characters a JSON body is made of (`{"a":1}` → `{a:1}`, POSTed
1305
+ // as garbage) and rewrites its spacing; the tail after `call <id>
1306
+ // <path>` is the body exactly as typed, which is what the agent parses.
1307
+ const body = splitHead(line, 3).rest || undefined;
1308
+ const registered = services.find((sv) => sv.path === path);
1309
+ const method = registered?.method ?? (body ? 'POST' : 'GET');
1310
+ if (!registered && path !== '/hello') out(`note: ${path} is not in the agent's service table — calling anyway\n`);
1311
+
1312
+ const started = Date.now();
1313
+ const t = await callAgentWithTicket(ag, row.url, path, method, body, my);
1314
+ out(`${method} ${path} → ${t.res.status} (${((Date.now() - started) / 1000).toFixed(1)}s)\n`);
1315
+ // Display only — hashing above used the full raw bytes.
1316
+ let pretty = t.bodyText;
1317
+ try { pretty = JSON.stringify(JSON.parse(t.bodyText), null, 2); } catch { /* not JSON */ }
1318
+ out(pretty.length > 4096 ? `${pretty.slice(0, 4096)}\n… (${pretty.length} chars total)\n` : `${pretty}\n`);
1319
+ if (t.banked) out(`ticket : banked (${method} ${path}) — spend with \`rate ${row.agentId}\` within ~60 min\n`);
1320
+ else if (t.proof) out('ticket : NOT banked — the signed taskHash does not match the transcript as sent from here ' +
1321
+ '(something between here and the agent re-encoded the request URI or a body)\n');
1322
+ else out('ticket : NOT banked — no serve-proof on the response\n');
1323
+ continue;
1324
+ }
1325
+
1326
+ if (cmd === 'rate') {
1327
+ // Rate an agent you have INTERACTED with: spends a banked serve-proof
1328
+ // ticket (from `call`/`hello` within the last hour), then submits
1329
+ // canonical 8004 feedback + the TEE verification mark — atomically
1330
+ // (EIP-7702) when the environment has a feedbackBatcher. No ticket,
1331
+ // no rating: experiencing the agent is what earns the right to rate.
1332
+ if (!args[0]) { out('usage: rate <agentId|sealId> [score] [</endpoint>]\n'); continue; }
1333
+ const ag = await withWallet(ctx);
1334
+ const my = (await addressOf(ctx.env.privateKey!)) as `0x${string}`;
1335
+ const row = await findAgentRow(ag, args[0]);
1336
+ if (!row) { out(`agent ${args[0]} does not exist\n`); continue; }
1337
+ if (row.agentId == null) { out(`agent ${args[0]} is not minted yet — nothing to rate\n`); continue; }
1338
+ const agentId = BigInt(row.agentId);
1339
+ // The chain would reject this at the attest step (self-feedback); say it upfront.
1340
+ const agentOwner = await ag.agent.ownerOf(agentId);
1341
+ if (agentOwner.toLowerCase() === my.toLowerCase()) { out(`agent ${row.agentId} is yours — owners cannot rate their own agent\n`); continue; }
1342
+
1343
+ // `rate <id> [score] [endpoint]` — either trailing arg order works.
1344
+ let rawScore = '';
1345
+ let endpointFilter = '';
1346
+ for (const a of args.slice(1)) {
1347
+ if (a.startsWith('/')) endpointFilter = a;
1348
+ else rawScore = a;
1349
+ }
1350
+
1351
+ // Tickets come ONLY from real interactions (call/hello). Newest first.
1352
+ let tickets = listProofs(agentId, my);
1353
+ if (endpointFilter) tickets = tickets.filter((e) => e.task.uri === endpointFilter);
1354
+ if (tickets.length === 0) {
1355
+ out(`you hold no unexpired ticket for agent ${row.agentId}${endpointFilter ? ` on ${endpointFilter}` : ''} (tickets live ~1h)\n` +
1356
+ ` → experience it first: \`call ${row.agentId}\` lists its services, \`call ${row.agentId} <path>\` uses one, then rate promptly\n`);
1357
+ continue;
1358
+ }
1359
+ let ticket: SavedProof;
1360
+ if (tickets.length === 1) {
1361
+ ticket = tickets[0];
1362
+ } else {
1363
+ out(`you hold ${tickets.length} tickets for agent ${row.agentId}:\n`);
1364
+ tickets.forEach((e, i) => {
1365
+ const at = new Date(e.capturedAt * 1000).toLocaleTimeString();
1366
+ const exp = new Date(e.deadline * 1000).toLocaleTimeString();
1367
+ out(` ${i + 1}. ${e.task.method.padEnd(4)} ${e.task.uri.padEnd(24)} ${at} (expires ${exp})\n`);
1368
+ });
1369
+ const pick = (await ask('which interaction are you rating? [1]: ')).trim() || '1';
1370
+ const n = Number(pick);
1371
+ if (!Number.isInteger(n) || n < 1 || n > tickets.length) { out('invalid choice\n'); continue; }
1372
+ ticket = tickets[n - 1];
1373
+ }
1374
+ out(`rating the ${ticket.task.method} ${ticket.task.uri} interaction from ${new Date(ticket.capturedAt * 1000).toLocaleTimeString()}\n`);
1375
+ const proof = toServeProof(ticket);
1376
+
1377
+ // Free pre-check before spending gas, on the fields the registry
1378
+ // checks (ticketRedeemable) — not on dataOnChain, which it doesn't.
1379
+ const v = await ag.reputation.verifyProof(proof);
1380
+ if (!ticketRedeemable(v)) {
1381
+ // Burn only on a defect of the ticket itself; keep it when the
1382
+ // failure is this side's registry configuration (ticketDisposition).
1383
+ if (ticketDisposition(v) === 'burn') {
1384
+ removeProof(ticket.proof.signature);
1385
+ out(`serve-proof failed verification (${v.reasons.join(', ')}) — ticket discarded\n`);
1386
+ } else {
1387
+ out(`serve-proof not verifiable in this environment (${v.reasons.join(', ')}) — ticket kept\n` +
1388
+ ` → check the attestor's verified_feedback_addr / AGENTIC_VERIFIED_FEEDBACK_ADDR\n`);
1389
+ }
1390
+ continue;
1391
+ }
1392
+ if (!v.dataOnChain) {
1393
+ out(`note: the agent has committed new state since this interaction (a dataHash in the ticket is no longer current) — ` +
1394
+ `the ticket still redeems, and the rating records the version that served you\n`);
1395
+ }
1396
+
1397
+ if (!rawScore) rawScore = (await ask('score [1-5]: ')).trim();
1398
+ if (!/^-?\d+$/.test(rawScore)) { out('score must be an integer\n'); continue; }
1399
+ out('submitting: canonical 8004 feedback + TEE attestation…\n');
1400
+ const fb = await ag.reputation.giveFeedback({
1401
+ agentId, value: BigInt(rawScore), serveProof: proof, endpoint: ticket.endpoint, task: ticket.task,
1402
+ });
1403
+ await ag.reputation.waitForTransaction(fb.attestTx);
1404
+ removeProof(ticket.proof.signature);
1405
+ const atomic = fb.feedbackTx === fb.attestTx;
1406
+ out(`rated agent ${row.agentId}: ${rawScore} — canonical index ${fb.feedbackIndex}, TEE-verified (endpoint ${ticket.task.uri})${atomic ? ', atomic' : ''} (tx ${fb.attestTx})\n`);
1407
+ continue;
1408
+ }
1409
+
1410
+ if (cmd === 'use' || cmd === 'link') {
1411
+ if (!args[0]) { out('usage: use <agentId|sealId>\n'); continue; }
1412
+ const ag = await withWallet(ctx);
1413
+ const s = await attach(ag, requireAttestorUrl(ctx.env), args[0], ask);
1414
+ await sessionRepl(s, ask, irq, ctx);
1415
+ continue;
1416
+ }
1417
+
1418
+ if (cmd === 'deploy') {
1419
+ const ag = await withWallet(ctx);
1420
+ const s = await deployWizard(ag, requireAttestorUrl(ctx.env), ask, ctx, irq);
1421
+ if (!s) { out('wait cancelled — the deploy continues in the background; watch it with `list`, enter later with `use <id>`\n'); continue; }
1422
+ await sessionRepl(s, ask, irq, ctx);
1423
+ continue;
1424
+ }
1425
+
1426
+ out(`unknown command: ${cmd}\n${L1_HELP}\n`);
1427
+ } catch (e) {
1428
+ // Keep the REPL alive on operational errors; show the remedy if present.
1429
+ const ce = e as CliError;
1430
+ out(`error: ${friendlyChainError(e) ?? ce.message}${ce.remedy ? `\n → ${ce.remedy}` : ''}\n`);
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ /**
1436
+ * Translate the custom contract errors our commands can hit into one human
1437
+ * sentence, instead of viem's raw revert dump (signature + arg tuple + call
1438
+ * frame). Returns undefined for anything unrecognized — caller falls back to
1439
+ * the error's own message.
1440
+ */
1441
+ function friendlyChainError(e: unknown): string | undefined {
1442
+ const revert = (e as { walk?: (fn: (x: unknown) => boolean) => unknown }).walk?.(
1443
+ (x) => x instanceof ContractFunctionRevertedError,
1444
+ ) as ContractFunctionRevertedError | undefined;
1445
+ const d = revert?.data;
1446
+ if (!d?.errorName) return undefined;
1447
+ const a = (d.args ?? []) as readonly unknown[];
1448
+ switch (d.errorName) {
1449
+ case 'CloneGateNotTokenOwner':
1450
+ return `agent ${a[1]} is not yours — its owner is ${a[2]} (you signed as ${a[0]})`;
1451
+ case 'StdCloneAuthNotSeller':
1452
+ return `only agent ${a[1]}'s owner (${a[2]}) can manage its fork grants — you signed as ${a[0]}`;
1453
+ case 'CloneGateDenied':
1454
+ return a[1] === ZERO_ADDR
1455
+ ? `agent ${a[0]} has no fork policy configured — its owner opens sales with: authorizer ${a[0]} <policy>`
1456
+ : `agent ${a[0]}'s fork policy (${a[1]}) declined — ask the seller to: grant ${a[0]} <your wallet>`;
1457
+ case 'CloneGateNotTrustedAttestor':
1458
+ return 'cloneFrom may only be submitted by a trusted attestor — use the attestor /clone flow, not a direct tx';
1459
+ default:
1460
+ return `${d.errorName}(${a.map(String).join(', ')})`;
1461
+ }
1462
+ }
1463
+
1464
+ /** One client per (attestor,key) pair, cached across REPL commands —
1465
+ * rebuilding the SDK (a /config fetch + viem clients) on EVERY command is
1466
+ * what made the REPL feel slow. login/env changes invalidate naturally
1467
+ * because the cache key changes. */
1468
+ let cachedClient: { key: string; ag: AgenticID } | null = null;
1469
+ /**
1470
+ * Show, or merge-and-write, an agent's settings document — the owner's
1471
+ * configuration (which model it thinks with, and how hard). Shared by L1
1472
+ * `settings <id>`, L2 `/settings` and L2 `/think`, so the grammar, the
1473
+ * refusals and the conflict handling are the same in all three.
1474
+ *
1475
+ * A bare call shows; `key=value` args merge onto the stored document and
1476
+ * write it back, owner-signed — reading is owner-signed too, so `ag` must
1477
+ * carry a wallet either way. The catalog check inside setSettings warns
1478
+ * before signing and never blocks — the container is the gate.
1479
+ *
1480
+ * Returns the document now in force (unchanged on a bare show), so a caller
1481
+ * like /think can report the level that actually landed.
1482
+ */
1483
+ async function settingsOp(ag: AgenticID, sealId: `0x${string}`, args: string[], serveBase?: string): Promise<SettingsDoc | null> {
1484
+ const assignments = parseAssignments(args); // throws CliError on a bad key/level
1485
+ const { settings: current, version } = await ag.agent.getSettings(sealId);
1486
+ if (!assignments.length) {
1487
+ for (const l of renderSettings(current)) out(` ${l}\n`);
1488
+ out(' change with: model=<id> · thinking=low|high|max · provider=<name> · others=\'<json>\' (quote it)\n');
1489
+ return current;
1490
+ }
1491
+ const next = applyAssignments(current, assignments);
1492
+ // A document with no model is the one the container hard-fails on and
1493
+ // last-known-good cannot cover — refuse before signing, and say so.
1494
+ assertModelPresent(next, current !== null);
1495
+ const providerChanged = changesProvider(current, next);
1496
+ if (providerChanged) requireConfiguredInferenceKey(next.provider ?? '0g-compute');
1497
+ try {
1498
+ const { version: written } = await ag.agent.setSettings(sealId, next, {
1499
+ baseVersion: version,
1500
+ onWarn: (w) => out(`⚠ ${w}\n`),
1501
+ });
1502
+ for (const l of renderSettings(next)) out(` ${l}\n`);
1503
+ if (providerChanged) {
1504
+ out(`written — version ${written}; provider change pending — run reset with the ${next.provider} key\n`);
1505
+ completionProvider = next.provider ?? '0g-compute';
1506
+ chatModelIds = providerModelIds[completionProvider] ?? [];
1507
+ return next;
1508
+ }
1509
+ // Push to the running container so a change made mid-conversation takes
1510
+ // effect NOW, not at the next boot. Best-effort: the write above is
1511
+ // durable, so a push failure is a note, never an error. The command-line
1512
+ // `settings` already did this; the in-session /settings and /think — the
1513
+ // likeliest place to retune an agent you are talking to — used to defer to
1514
+ // a reset (found live: /settings thinking=high said "next boot" while the
1515
+ // agent was running).
1516
+ if (serveBase) {
1517
+ try {
1518
+ const agentId = await ag.agent.getAgentIdBySealId(sealId);
1519
+ const r = await ag.agent.pushSettingsToContainer(serveBase, agentId, next);
1520
+ out(`written — version ${written}; ${r.note ?? 'applied to the running container'}\n`);
1521
+ } catch (e2) {
1522
+ const msg = (e2 as Error).message;
1523
+ if (requiresProviderReset(e2)) {
1524
+ out(`written — version ${written}; provider change pending — run reset with the ${next.provider} key\n`);
1525
+ return next;
1526
+ }
1527
+ // A container that ANSWERED and refused (HTTP status) will refuse the
1528
+ // same document on the next boot too and fall back to last-known-good;
1529
+ // only an UNREACHABLE container (no HTTP status) applies it next boot.
1530
+ if (/HTTP \d/.test(msg)) {
1531
+ out(`written — version ${written}; stored, but the running container REFUSED it (${msg}) — a refused document does not boot, so the agent keeps its current configuration until you store one it accepts\n`);
1532
+ } else {
1533
+ out(`written — version ${written}; stored, but the running container was unreachable (${msg}) — it applies on the next boot\n`);
1534
+ }
1535
+ }
1536
+ } else {
1537
+ out(`written — version ${written}; the container applies it at its next boot (reset applies it now)\n`);
1538
+ }
1539
+ return next;
1540
+ } catch (e) {
1541
+ if (!(e instanceof SettingsConflictError)) throw e;
1542
+ // Someone else edited this agent between the read and the write. Show
1543
+ // what is there now and let the owner decide — a quiet retry here would
1544
+ // be this REPL choosing to discard the other change.
1545
+ out(`⚠ ${e.message}\n the document now stored (version ${e.currentVersion}):\n`);
1546
+ for (const l of renderSettings(e.current)) out(` ${l}\n`);
1547
+ out(' nothing was written — repeat your command to apply it on top of that\n');
1548
+ return e.current;
1549
+ }
1550
+ }
1551
+
1552
+ async function clientFor(ctx: CommandContext, withWalletOpt: boolean): Promise<AgenticID> {
1553
+ const cacheKey = `${ctx.env.attestorUrl}|${withWalletOpt ? ctx.env.privateKey ?? '' : ''}`;
1554
+ if (cachedClient?.key === cacheKey) return cachedClient.ag;
1555
+ const ag = await buildClient(ctx.env, withWalletOpt ? { withWallet: true } : {});
1556
+ cachedClient = { key: cacheKey, ag };
1557
+ return ag;
1558
+ }
1559
+
1560
+ /** The agent's avatar as terminal art. Source of truth is the CARD's stored
1561
+ * image (agent_card.image, frozen at mint — the exact image the dashboard
1562
+ * shows), so the CLI can never drift from other surfaces; the attestor's
1563
+ * live /avatar/:sealId derivation is only the fallback for cards without
1564
+ * one. */
1565
+ async function fetchAvatarLines(attestorUrl: string, sealId: string): Promise<string[] | null> {
1566
+ const B64 = 'data:image/svg+xml;base64,';
1567
+ try {
1568
+ const d = (await (await fetch(`${attestorUrl}/deployment/${sealId}`, { signal: AbortSignal.timeout(3000) })).json()) as { agent_card?: { image?: string } };
1569
+ const img = d.agent_card?.image;
1570
+ if (img?.startsWith(B64)) {
1571
+ const lines = svgPixelLines(Buffer.from(img.slice(B64.length), 'base64').toString('utf8'));
1572
+ if (lines) return lines;
1573
+ }
1574
+ } catch { /* fall through to the live derivation */ }
1575
+ try {
1576
+ const r = await fetch(`${attestorUrl}/avatar/${sealId}.svg`, { signal: AbortSignal.timeout(3000) });
1577
+ return r.ok ? svgPixelLines(await r.text()) : null;
1578
+ } catch {
1579
+ return null;
1580
+ }
1581
+ }
1582
+
1583
+
1584
+ /** Call one of an agent's endpoints, capturing the serve-proof AND its
1585
+ * task-receipt materials. With `clientAddr` the request declares
1586
+ * X-Client-Address, so the proof is redeemable by that wallet — and gets
1587
+ * banked in the proof jar as a rating ticket (only when the locally
1588
+ * recomputed taskHash matches the signed one, so a mangled transcript never
1589
+ * banks an unusable reveal). Non-2xx responses bank too: a failed
1590
+ * interaction is still an interaction — arguably the one you most want to
1591
+ * rate. */
1592
+ async function callAgentWithTicket(
1593
+ ag: AgenticID,
1594
+ url: string,
1595
+ path: string,
1596
+ method: string,
1597
+ body: string | undefined,
1598
+ clientAddr?: `0x${string}`,
1599
+ ): Promise<{ res: Response; bodyText: string; proof: ServeProof | null; task: TaskReveal | null; banked: boolean }> {
1600
+ const target = `${url}${path}`;
1601
+ const bodyBytes = body ? new TextEncoder().encode(body) : new Uint8Array(0);
1602
+ const res = await fetch(target, {
1603
+ method,
1604
+ headers: {
1605
+ ...(clientAddr ? { 'X-Client-Address': clientAddr } : {}),
1606
+ ...(body ? { 'content-type': 'application/json' } : {}),
1607
+ },
1608
+ ...(body ? { body } : {}),
1609
+ });
1610
+ const raw = new Uint8Array(await res.arrayBuffer());
1611
+ const bodyText = new TextDecoder().decode(raw);
1612
+ const proof = ag.reputation.proofFromResponse(res);
1613
+ let task: TaskReveal | null = null;
1614
+ let banked = false;
1615
+ if (proof) {
1616
+ // The uri is Go's r.URL.RequestURI() of what was sent (requestUriCandidates
1617
+ // covers the forms a client may put on the wire).
1618
+ for (const uri of requestUriCandidates(target)) {
1619
+ const candidate: TaskReveal = {
1620
+ method,
1621
+ uri,
1622
+ reqBodyHash: keccak256(bodyBytes),
1623
+ respBodyHash: keccak256(raw),
1624
+ statusCode: res.status,
1625
+ };
1626
+ if (taskHashOf(candidate) === proof.taskHash) { task = candidate; break; }
1627
+ }
1628
+ if (clientAddr && proof.submitter.toLowerCase() === clientAddr.toLowerCase() && task) {
1629
+ saveProof(proof, task, target);
1630
+ banked = true;
1631
+ }
1632
+ }
1633
+ return { res, bodyText, proof, task, banked };
1634
+ }
1635
+
1636
+ async function helloWithTicket(
1637
+ ag: AgenticID,
1638
+ url: string,
1639
+ clientAddr?: `0x${string}`,
1640
+ ): Promise<{ res: Response; bodyText: string; proof: ServeProof | null; task: TaskReveal | null; banked: boolean }> {
1641
+ return callAgentWithTicket(ag, url, '/hello', 'GET', undefined, clientAddr);
1642
+ }
1643
+
1644
+ /** Public-listing row for an agentId/sealId(/unique-prefix) reference, or undefined. */
1645
+ async function findAgentRow(ag: AgenticID, refInput: string): Promise<Awaited<ReturnType<AgenticID['agent']['listDeployments']>>[number] | undefined> {
1646
+ const ref = parseAgentRef(refInput);
1647
+ const rows = await ag.agent.listDeployments();
1648
+ return pickRow(ref, refInput, rows);
1649
+ }
1650
+
1651
+ /** Match rows against a ref; a sealId PREFIX must be unique (ambiguity throws). */
1652
+ function pickRow<T extends { agentId?: unknown; sealId?: string }>(
1653
+ ref: AgentRef,
1654
+ refInput: string,
1655
+ rows: T[],
1656
+ ): T | undefined {
1657
+ const hits = rows.filter((r) =>
1658
+ ref.kind === 'agentId'
1659
+ ? String(r.agentId ?? '') === String(ref.agentId)
1660
+ : !!r.sealId && refMatchesSeal(ref, r.sealId));
1661
+ if (ref.kind === 'sealPrefix' && hits.length > 1) {
1662
+ throw new CliError('BAD_AGENT_REF', `"${refInput}" matches ${hits.length} agents — add more hex chars`, {
1663
+ remedy: 'use `list` and copy a longer prefix (or the full sealId)',
1664
+ });
1665
+ }
1666
+ return hits[0];
1667
+ }
1668
+
1669
+ /** The agent's registered service table (from its /hello; empty on failure). */
1670
+ async function servicesOf(url: string): Promise<Array<{ path: string; method: string; description?: string; skill?: string; transport?: string }>> {
1671
+ try {
1672
+ const b = (await (await fetch(`${url}/hello`)).json()) as {
1673
+ services?: Array<{ path: string; method: string; description?: string; skill?: string; transport?: string }>;
1674
+ };
1675
+ // entry #0 is /hello itself — callable but not a business service; keep it out of the picker
1676
+ return (b.services ?? []).filter((sv) => sv.path !== '/hello');
1677
+ } catch {
1678
+ return [];
1679
+ }
1680
+ }
1681
+
1682
+ /** Fetch and print an agent's signed /hello: identity, proof verification,
1683
+ * and its two capability tables — services (agent-registered endpoints,
1684
+ * entry #0 is /hello itself) and routes (framework-declared prefixes).
1685
+ * The public way to inspect ANY agent (L1 `hello <id>` and L2 /hello).
1686
+ * With `clientAddr`, the serve-proof is banked as a rating ticket. */
1687
+ async function showHello(ag: AgenticID, url: string, clientAddr?: `0x${string}`): Promise<void> {
1688
+ const { proof, bodyText, banked } = await helloWithTicket(ag, url, clientAddr);
1689
+ let body: {
1690
+ agent?: string; owner?: string; message?: string;
1691
+ services?: { path: string; method: string; description?: string; skill?: string }[];
1692
+ routes?: { prefix: string; kind?: string; auth?: string; signed: boolean; description?: string }[];
1693
+ } = {};
1694
+ try { body = JSON.parse(bodyText); } catch { /* body printed fields stay empty */ }
1695
+ const valid = proof ? await ag.reputation.verifyProof(proof) : null;
1696
+ const proofLine = valid
1697
+ ? `${JSON.stringify(valid.ok)}${valid.ok ? '' : ` (${valid.reasons.join('; ')})`}`
1698
+ : '(no proof header)';
1699
+ out(`agent : ${body.agent}\nowner : ${body.owner}\nproof ok: ${proofLine}\n`);
1700
+ if (banked) out(`ticket : banked (GET /hello) — spend with \`rate\` within ~60 min\n`);
1701
+ if (body.services?.length) {
1702
+ out('services:\n');
1703
+ for (const sv of body.services) {
1704
+ out(` ${sv.method.padEnd(4)} ${sv.path.padEnd(24)} ${sv.description ?? ''}${sv.skill ? ` [skill: ${sv.skill}]` : ''}\n`);
1705
+ }
1706
+ }
1707
+ if (body.routes?.length) {
1708
+ out('routes:\n');
1709
+ for (const rt of body.routes) {
1710
+ const tags = [rt.kind, rt.auth ? `auth=${rt.auth}` : '', rt.signed ? 'signed' : ''].filter(Boolean).join(' · ');
1711
+ out(` ${rt.prefix.padEnd(29)} ${tags}${rt.description ? ` — ${rt.description}` : ''}\n`);
1712
+ }
1713
+ }
1714
+ }
1715
+
1716
+ /** Build a wallet-backed client, turning a missing key into a `login` nudge. */
1717
+ async function withWallet(ctx: CommandContext): Promise<AgenticID> {
1718
+ if (!ctx.env.privateKey) {
1719
+ const k = loadKey();
1720
+ if (k) ctx.env.privateKey = k;
1721
+ }
1722
+ if (!ctx.env.privateKey) {
1723
+ throw new CliError('WALLET_REQUIRED', 'this needs your owner wallet, and none is configured', {
1724
+ remedy: 'run `login` here (stored 0600), or set AGENTIC_PRIVATE_KEY',
1725
+ });
1726
+ }
1727
+ return clientFor(ctx, true);
1728
+ }
1729
+
1730
+ /** Prompt for a secret with the typed characters not echoed. readline has no
1731
+ * native masking, so suppress stdout echo for the duration of the question. */
1732
+ function askSecret(ask: (q: string) => Promise<string>, prompt: string): Promise<string> {
1733
+ return new Promise((res, rej) => {
1734
+ const stdout = process.stdout as unknown as { write: (s: string) => boolean };
1735
+ const orig = stdout.write.bind(stdout);
1736
+ // Echo the typed/pasted characters as `*` so there IS visible feedback
1737
+ // (an all-silent prompt reads as a hang). Masking must survive readline's
1738
+ // LINE REDRAWS: Backspace/Del/arrows arrive as ONE chunk
1739
+ // "ESC[2K ESC[1G <prompt> <typed secret>" — so escape sequences and the
1740
+ // prompt are preserved but every other printable character is masked
1741
+ // (passing ESC-prefixed or prompt-bearing chunks through raw leaked the
1742
+ // full secret on the first edit keystroke).
1743
+ stdout.write = (s: string): boolean => {
1744
+ if (!s || s === '\r\n' || s === '\n') return orig(s);
1745
+ const masked = s
1746
+ .split(/(\x1b\[[0-9;?]*[A-Za-z~]|\x1b.)/) // capture ANSI escape sequences
1747
+ .map((seg, i) => {
1748
+ if (i % 2 === 1 || !seg) return seg; // an escape sequence — keep
1749
+ return seg.split(prompt).map((part) => part.replace(/[^\r\n]/g, '*')).join(prompt);
1750
+ })
1751
+ .join('');
1752
+ return orig(masked);
1753
+ };
1754
+ void ask(prompt).then(
1755
+ (ans) => {
1756
+ stdout.write = orig;
1757
+ // Masking only covers the SCREEN — readline also recorded the line in
1758
+ // its history, where ↑ at any later prompt replays the secret in
1759
+ // plaintext. Scrub every matching entry.
1760
+ const hist = (activeRl as unknown as { history?: string[] } | null)?.history;
1761
+ if (hist && ans) {
1762
+ for (let i = hist.length - 1; i >= 0; i--) {
1763
+ if (hist[i] === ans) hist.splice(i, 1);
1764
+ }
1765
+ }
1766
+ process.stdout.write('\n');
1767
+ res(ans);
1768
+ },
1769
+ // stdin EOF mid-prompt: restore the write hook BEFORE surfacing, or
1770
+ // every later line stays masked.
1771
+ (err) => {
1772
+ stdout.write = orig;
1773
+ rej(err);
1774
+ },
1775
+ );
1776
+ });
1777
+ }
1778
+
1779
+ const ZERO_ADDR = '0x0000000000000000000000000000000000000000';
1780
+
1781
+ /** Resolve an agent ref to its minted tokenId (works on ANY agent, not just mine). */
1782
+ async function mintedTokenId(ag: AgenticID, refInput: string): Promise<bigint> {
1783
+ const row = await findAgentRow(ag, refInput);
1784
+ if (!row) throw new CliError('UNKNOWN', `no agent matching ${refInput} on this attestor`);
1785
+ if (row.agentId == null) throw new CliError('UNKNOWN', `agent ${refInput} is not minted yet — nothing on-chain to act on`);
1786
+ return BigInt(row.agentId);
1787
+ }
1788
+
1789
+ async function addressOf(key: `0x${string}`): Promise<string> {
1790
+ const { privateKeyToAccount } = await import('viem/accounts');
1791
+ return privateKeyToAccount(key).address;
1792
+ }
1793
+
1794
+ // ── deploy / attach (from the former chat command) ───────────────────────────
1795
+
1796
+ async function pickInferenceProvider(ask: (q: string) => Promise<string>, preferred: string): Promise<string> {
1797
+ const providers = knownProviders;
1798
+ const fallback = Math.max(0, providers.findIndex((provider) => provider.id === preferred));
1799
+ out('providers:\n');
1800
+ providers.forEach((provider, index) => out(` ${index}. ${provider.id} (${provider.name})${index === fallback ? ' (default)' : ''}\n`));
1801
+ const input = (await ask(`provider [${fallback}]: `)).trim();
1802
+ const chosen = !input ? providers[fallback] : providers.find((provider) => provider.id === input) ?? providers[Number(input)];
1803
+ if (!chosen) throw new CliError('BAD_FLAG', `unknown inference provider: ${input}`);
1804
+ return chosen.id;
1805
+ }
1806
+
1807
+ async function inferenceKey(ctx: CommandContext, ask: (q: string) => Promise<string>, provider = '0g-compute'): Promise<string> {
1808
+ const configured = configuredInferenceKey(provider);
1809
+ if (configured) return configured;
1810
+ const typed = (await askSecret(ask, `${provider} inference API key (saved to credentials): `)).trim();
1811
+ if (typed) { saveApiKey(provider, typed); return typed; }
1812
+ // No key anywhere: deploying anyway would provision a container that 401s
1813
+ // on every turn minutes later — fail HERE with the fix instead.
1814
+ throw new CliError('INFERENCE_KEY_REQUIRED', `no API key registered for ${provider}`, {
1815
+ remedy: `run login and register the ${provider} key`,
1816
+ });
1817
+ }
1818
+
1819
+ /** Trust-root ack (once per owner) + a prepaid-balance gate that ASKS before
1820
+ * spending: under 0.1 OG, report the shortfall and offer to deposit now.
1821
+ * Gates every balance-spending action (deploy/start/reset). Returns false
1822
+ * when the user declines (caller should abort the action). */
1823
+ async function ensureOwnerReady(ag: AgenticID, ask: (q: string) => Promise<string>): Promise<boolean> {
1824
+ // ack (may send a tx) and the effective-balance read are independent —
1825
+ // overlap them; the balance gate below still waits for both.
1826
+ const effPromise = ag.getEffectiveBalance().catch(() => null);
1827
+ const ackTx = await ag.ack();
1828
+ if (ackTx) { out(`ack() → ${ackTx} (waiting…)\n`); await ag.agent.waitForTransaction(ackTx); }
1829
+ // Gate on the provider's EFFECTIVE balance (on-chain minus outstanding
1830
+ // off-chain debt) when reachable — that's what its create gate enforces;
1831
+ // the raw chain read is the fallback.
1832
+ const eff = await effPromise;
1833
+ const bal = eff ? eff.availableWei : await ag.getBalance();
1834
+ if (bal < parseEther('0.1')) {
1835
+ if (eff && eff.availableWei < eff.balanceWei) {
1836
+ const owed = eff.outstandingDebtWei + eff.pendingSettlementWei + eff.reservedWei;
1837
+ out(`available balance is ${og(bal)} — on-chain ${og(eff.balanceWei)} minus ${og(owed)} owed/queued off-chain. Deposits settle those first.\n`);
1838
+ } else {
1839
+ out(`prepaid sandbox balance is ${og(bal)} — deploy/run needs ≥ 0.1 OG.\n`);
1840
+ }
1841
+ // What the wallet can actually afford: native balance minus a gas
1842
+ // reserve. A deposit's principal + fee both come out of native, so
1843
+ // suggesting more than this guarantees an "insufficient funds" revert.
1844
+ const native = await ag.nativeBalance().catch(() => null);
1845
+ const shortfallWei = parseEther('0.1') - (bal < 0n ? 0n : bal);
1846
+ const GAS_RESERVE = parseEther('0.05');
1847
+ const affordableWei = native != null && native > GAS_RESERVE ? native - GAS_RESERVE : 0n;
1848
+ if (native != null && affordableWei < shortfallWei) {
1849
+ out(`wallet has only ${og(native)} native gas — not enough to cover a ${og(shortfallWei)} deposit plus fees. Fund the wallet, or use one with more OG.\n`);
1850
+ return false;
1851
+ }
1852
+ // Suggest the shortfall (no arbitrary padding), capped at what's affordable.
1853
+ let suggestWei = shortfallWei > 0n ? shortfallWei : parseEther('0.1');
1854
+ if (affordableWei > 0n && suggestWei > affordableWei) suggestWei = affordableWei;
1855
+ const suggest = og(suggestWei).replace(/ OG$/, '');
1856
+ // Empty = cancel (as the prompt says). To deposit the suggested amount,
1857
+ // the user types it — no silent default that contradicts "empty to cancel".
1858
+ // Typing the amount IS the confirmation — the prompt already says empty
1859
+ // cancels; a second [Y/n] was pure friction (review of the topup flows).
1860
+ const amt = (await ask(`deposit how much OG now? (e.g. ${suggest}, empty to cancel): `)).trim();
1861
+ if (!amt) { out('cancelled — deposit later with `deposit`.\n'); return false; }
1862
+ const tx = await ag.deposit({ amountWei: parseEther(amt) });
1863
+ out(`deposit ${amt} OG (tx ${tx}, waiting…)\n`);
1864
+ await ag.waitForTransaction(tx);
1865
+ }
1866
+ return true;
1867
+ }
1868
+
1869
+ async function deployWizard(ag: AgenticID, attestorUrl: string, ask: (q: string) => Promise<string>, ctx: CommandContext, irq: Interrupt): Promise<Session | null> {
1870
+ const cfg = (await fetch(`${attestorUrl}/config`, { signal: AbortSignal.timeout(10_000) })
1871
+ .then((r) => r.json())
1872
+ .catch(() => ({}))) as { frameworks?: { name: string }[] };
1873
+ const fws = (cfg.frameworks ?? []).map((f) => f.name);
1874
+ let framework = 'openclaw';
1875
+ if (fws.length) {
1876
+ const di = Math.max(0, fws.indexOf('openclaw'));
1877
+ out('\nframeworks:\n');
1878
+ fws.forEach((n, i) => out(` ${i}. ${n}${i === di ? ' (default)' : ''}\n`));
1879
+ const raw = (await ask(`framework [${di}]: `)).trim();
1880
+ const i = Number(raw);
1881
+ framework = !raw ? fws[di] : Number.isInteger(i) && fws[i] ? fws[i] : fws.includes(raw) ? raw : fws[di];
1882
+ }
1883
+
1884
+ // Only offer models the chosen framework can actually run: chatbots only
1885
+ // (the router also lists image/audio models), and function-calling models
1886
+ // for the tool-driven frameworks — a chat-only model deploys "successfully"
1887
+ // and then fails EVERY turn, with no way to fix it in-CLI (feedback.md F14).
1888
+ knownProviders = await ag.agent.refreshProviders();
1889
+ const provider = await pickInferenceProvider(ask, loadConfig().inferenceProvider ?? '0g-compute');
1890
+ const definition = knownProviders.find((entry) => entry.id === provider)!;
1891
+ await ag.agent.assertProviderSupported(provider, { framework });
1892
+ const NEEDS_TOOLS = new Set(['openclaw', 'dsh', 'prime-agent']);
1893
+ const caps = await ag.agent.listModelCaps({ provider });
1894
+ const models = caps.filter((model) => model.chat)
1895
+ .filter((model) => !NEEDS_TOOLS.has(framework) || model.tools)
1896
+ .filter((model) => framework !== 'hermes' || definition.native || model.formats.includes('openai') || (!model.formats.length && !model.id.startsWith('claude')))
1897
+ .map((model) => model.id);
1898
+ let model: string;
1899
+ if (!models.length && !definition.modelCatalog) {
1900
+ model = (await ask(`${provider} model id (required): `)).trim();
1901
+ if (!model) throw new CliError('BAD_FLAG', 'model is required');
1902
+ } else {
1903
+ if (!models.length) throw new CliError('UNKNOWN', `no compatible models advertised for ${framework} on ${provider}`);
1904
+ out('\nmodels:\n');
1905
+ models.forEach((id, index) => out(` ${index}. ${id}\n`));
1906
+ model = models[Number((await ask('model [0]: ')).trim()) || 0] ?? models[0];
1907
+ }
1908
+
1909
+ const name = (await ask(`name [chat-${framework}]: `)).trim() || `chat-${framework}`;
1910
+
1911
+ // Mint-only: register the agent on chain without spinning up (or paying
1912
+ // for) a container. It lands Offline; `reset`/`start` brings it online
1913
+ // later. The prepaid-balance gate and the inference key only matter when a
1914
+ // container is actually provisioned, so skip both in mint-only mode.
1915
+ const provision = !(await ask('bring it online now (start a container)? [Y/n]: ')).trim().toLowerCase().startsWith('n');
1916
+
1917
+ const apiKey = provision ? await inferenceKey(ctx, ask, provider) : undefined;
1918
+ if (provision && !(await ensureOwnerReady(ag, ask))) throw new CliError('WALLET_REQUIRED', 'deploy cancelled — prepaid balance too low', { remedy: 'run `deposit`, then `deploy` again' });
1919
+ out(`\ndeploying ${name} (${framework} · ${model})${provision ? '' : ' — mint only, no container'}…\n`);
1920
+ const { deployment: dep, agentId } = await deployWithInference(ag, { name, framework, provider, model, provision, apiKey });
1921
+ if (!provision) {
1922
+ out(`minted agentId ${agentId} — offline (no container). Bring it online with: reset ${agentId}\n`);
1923
+ return null;
1924
+ }
1925
+ out(`minted agentId ${agentId} — waiting for the container (can take minutes; Esc stops waiting, not the deploy)…\n`);
1926
+ const r = await waitRunningInterruptible(irq, attestorUrl, dep.sealId, agentId);
1927
+ if (!r) return null; // Esc: the attestor keeps deploying — only the wait ends
1928
+ // Enter through attach so a fresh deploy gets the same entry card
1929
+ // (avatar / gas / status) as `use`; only the wizard knows the framework.
1930
+ const s = await attach(ag, attestorUrl, agentId, ask);
1931
+ s.framework = framework;
1932
+ if (!s.agentSeal) s.agentSeal = dep.agentSealAddr;
1933
+ return s;
1934
+ }
1935
+
1936
+ async function attach(ag: AgenticID, attestorUrl: string, refInput: string, ask: (q: string) => Promise<string>): Promise<Session> {
1937
+ const ref = parseAgentRef(refInput);
1938
+ const rows = await ag.agent.listDeployments();
1939
+ const row = pickRow(ref, refInput, rows as { agentId?: unknown; sealId?: string }[]) as
1940
+ { sealId: `0x${string}`; agentId?: unknown; phase?: string; url?: string; name?: string | null; framework?: string | null } | undefined;
1941
+ if (!row) {
1942
+ throw new CliError('AGENT_NOT_FOUND', `no deployment matches ${refInput} on this attestor`, {
1943
+ remedy: 'use `list` to see the agents this wallet owns here',
1944
+ });
1945
+ }
1946
+ const agentId = String(row.agentId ?? '?');
1947
+
1948
+ // `use` selects the agent in ANY phase — lifecycle stays explicit inside
1949
+ // the session (/start, /reset). Only a running agent gets a connection.
1950
+ const s: Session = {
1951
+ ag, attestorUrl, sealId: row.sealId, agentId,
1952
+ phase: row.phase ?? 'unknown',
1953
+ sandboxId: row.url ? sbid(row.url) : undefined,
1954
+ // The attestor row remembers which harness this agent runs (deploy-time
1955
+ // iData binding) — nobody should have to. Feeds the chat model selector
1956
+ // and the reset default; legacy rows (pre-column) come through null and
1957
+ // fall back to the old ask-once flow.
1958
+ framework: row.framework ?? undefined,
1959
+ };
1960
+ if (row.phase === 'running' && row.url) await connectSession(s, row.url);
1961
+ // Entry status card: the agent's own pixel avatar (the attestor renders
1962
+ // it from the sealId — the exact image its AgentCard carries) beside
1963
+ // phase / url / sealId / agentSeal gas. Avatar + gas fetch in parallel
1964
+ // and each degrades to absence on failure.
1965
+ const wantArt = !!process.stdout.isTTY && !process.env.NO_COLOR;
1966
+ const [art, gasWei, mine] = await Promise.all([
1967
+ wantArt ? fetchAvatarLines(attestorUrl, row.sealId) : Promise.resolve(null),
1968
+ /^\d+$/.test(agentId)
1969
+ ? ag.agent.runtimeCosts(BigInt(agentId)).then((rc) => rc.sealGasWei).catch(() => null)
1970
+ : Promise.resolve(null),
1971
+ // Ownership up front, so owner-only commands can refuse plainly instead
1972
+ // of failing phase checks or bouncing off the attestor's auth later.
1973
+ ag.agent.listMyDeployments().then((rs) => rs.some((r) => r.sealId === row.sealId)).catch(() => undefined),
1974
+ ]);
1975
+ // The session is the owner's cockpit — a foreign agent's public surface is
1976
+ // L1 `hello <id>`. Undetermined ownership (listing fetch failed) enters
1977
+ // anyway; the attestor's auth still guards every owner action.
1978
+ if (mine === false) {
1979
+ throw new CliError('AGENT_NOT_FOUND', `agent ${agentId} is not yours`, {
1980
+ remedy: `talk to its public surface with: hello ${agentId}`,
1981
+ });
1982
+ }
1983
+ const fields: string[] = [];
1984
+ fields.push(`agent ${agentId}${row.name ? ` · ${row.name}` : ''}`);
1985
+ fields.push(`phase ${s.phase}`);
1986
+ if (s.url) fields.push(`url ${s.url}`);
1987
+ fields.push(`sealId ${row.sealId.slice(0, 10)}…${row.sealId.slice(-6)}`);
1988
+ if (gasWei != null) fields.push(`gas ${og(gasWei)} (agentSeal — fund with /topup)`);
1989
+ if (s.phase === 'running' && s.url) {
1990
+ fields.push('type to chat · /help for commands · Esc interrupts a turn');
1991
+ } else {
1992
+ const reason = await failureReasonOf(attestorUrl, row.sealId);
1993
+ if (reason) fields.push(`last error: ${reason}`);
1994
+ fields.push(s.phase === 'stopped' ? '→ /start to bring it back' : '→ /reset to recreate its container');
1995
+ }
1996
+ out('\n');
1997
+ if (art) {
1998
+ for (let i = 0; i < Math.max(art.length, fields.length); i++) {
1999
+ out(` ${art[i] ?? ' '.repeat(16)} ${fields[i] ?? ''}\n`);
2000
+ }
2001
+ } else {
2002
+ for (const f of fields) out(` ${f}\n`);
2003
+ }
2004
+ out('\n');
2005
+ return s;
2006
+ }
2007
+
2008
+ /** The last recorded container failure reason, if any (public detail). */
2009
+ async function failureReasonOf(attestorUrl: string, sealId: `0x${string}`): Promise<string | undefined> {
2010
+ try {
2011
+ const d = (await (await fetch(`${attestorUrl}/deployment/${sealId}`)).json()) as {
2012
+ container_stage?: { state?: string; reason?: string };
2013
+ };
2014
+ return d.container_stage?.state === 'failed' ? d.container_stage?.reason : undefined;
2015
+ } catch {
2016
+ return undefined;
2017
+ }
2018
+ }
2019
+
2020
+ /** Numbered framework picker from /config — the user chooses; never guess.
2021
+ * (The deployment row records the framework post-#154; this picker is the fallback for legacy rows and explicit switches.) */
2022
+ async function pickFramework(attestorUrl: string, ask: (q: string) => Promise<string>, current?: string): Promise<string> {
2023
+ const cfg = (await fetch(`${attestorUrl}/config`, { signal: AbortSignal.timeout(10_000) })
2024
+ .then((r) => r.json())
2025
+ .catch(() => ({}))) as { frameworks?: { name: string }[] };
2026
+ const fws = (cfg.frameworks ?? []).map((f) => f.name);
2027
+ if (!fws.length) return current ?? 'openclaw';
2028
+ const di = Math.max(0, current ? fws.indexOf(current) : 0);
2029
+ out('frameworks:\n');
2030
+ fws.forEach((n, i) => out(` ${i}. ${n}${i === di ? ' (default)' : ''}\n`));
2031
+ const raw = (await ask(`framework [${di}]: `)).trim();
2032
+ const i = Number(raw);
2033
+ return !raw ? fws[di] : Number.isInteger(i) && fws[i] ? fws[i] : fws.includes(raw) ? raw : fws[di];
2034
+ }
2035
+
2036
+ // ── L2: session REPL ─────────────────────────────────────────────────────────
2037
+
2038
+ const L2_HELP =
2039
+ 'chat, or: /hello /balance /topup /stop /start /reset /settings /think /clear /compact /tasks /result /cancel /agentlog /startuplog /back /quit — Esc interrupts a turn (help: /help)';
2040
+
2041
+ const L2_HELP_FULL = `session commands
2042
+ <anything else> chat with the agent — Esc or Ctrl-C interrupts the
2043
+ turn in flight (the runtime cancels server-side)
2044
+ (bare Enter) refresh this agent's phase/url from the attestor
2045
+ /hello identity, routes/services, serve-proof verification
2046
+ /balance this agent's agentSeal gas + the account prepaid
2047
+ /topup [og] fund this agent's agentSeal gas (default 0.1 OG)
2048
+ /start start (only from stopped)
2049
+ /stop stop the running container
2050
+ /reset recreate the container (uses the recorded framework;
2051
+ /reset pick to choose another; asks the key; also
2052
+ clears the local chat history)
2053
+ /settings [k=v …] the owner's configuration document: which model
2054
+ this agent thinks with, and how hard. Bare shows it;
2055
+ model=… provider=… thinking=low|high|max
2056
+ others=<json> merge into it and write it back
2057
+ (owner-signed). Applies at the next boot — /reset
2058
+ applies it now
2059
+ /think [low|high|max] reasoning depth for thinking models (glm etc.) —
2060
+ shorthand for /settings thinking=…, so it is written
2061
+ to the owner's document (owner-signed) and applies at
2062
+ the agent's next boot; /reset applies it now. prime
2063
+ also takes it per message, from the next one on.
2064
+ No arg shows the level currently stored
2065
+ /clear wipe the agent's conversation and start fresh —
2066
+ chain-tracked memory (what the agent chose to keep)
2067
+ is untouched; that is the difference from /reset
2068
+ /compact compact the agent's conversation in place — older
2069
+ history becomes a summary, the newest part stays
2070
+ as it is (openclaw ~20K tokens, dsh its newest
2071
+ item), and the conversation goes on (unlike
2072
+ /clear). One or more model calls; can take
2073
+ minutes. dsh, and openclaw 2026.7.1 or later
2074
+ /tasks this session's long tasks with live status — on
2075
+ agents with the responses transport a chat turn
2076
+ survives dropped connections and keeps running
2077
+ /result [id] re-attach to a task (default: latest): prints a
2078
+ finished one, follows a running one live
2079
+ /cancel [id] stop tasks — the brake for orphaned turns: Esc only
2080
+ cancels a turn THIS connection started (on dsh/prime
2081
+ it interrupts the bridge-wide current turn), so after
2082
+ a dropped stream /cancel is the way to stop what
2083
+ survived. Bare form stops everything this session
2084
+ knows to be in flight (newest first); with an id,
2085
+ just that one — /result <id> adopts an id into the
2086
+ session first. Session memory starts empty after a
2087
+ CLI restart or /back + use
2088
+ /agentlog [n] agent process log, last n lines (owner-only)
2089
+ /startuplog [n] sealed runtime startup log, last n lines
2090
+ /back (or /unuse) return to the manager
2091
+ /quit exit`;
2092
+
2093
+ async function sessionRepl(s: Session, ask: (q: string) => Promise<string>, irq: Interrupt, ctx: CommandContext): Promise<void> {
2094
+ out(`\nagent ${s.agentId} session — ${s.phase} · ${hostOf(s.attestorUrl)} · type to chat · Tab completes /commands · /help for details\n`);
2095
+ // Low-gas heads-up WITH the entry card. It used to run detached and could
2096
+ // land mid-turn, reading like the agent said it (feedback.md F17) — so wait
2097
+ // for it, but bounded: advisory reads must not hold the prompt hostage.
2098
+ // A losing (slow) read must NOT print later mid-turn — that's the original
2099
+ // F17 symptom through the back door (review F-A): gate on a window flag.
2100
+ let advisoryWindowOpen = true;
2101
+ await Promise.race([
2102
+ s.ag.agent.runtimeCosts(BigInt(s.agentId)).then((rc) => {
2103
+ if (advisoryWindowOpen && rc.sealGasWei < parseEther('0.005')) {
2104
+ out(`⚠ agentSeal gas is ${og(rc.sealGasWei)} — evolution commits may fail; fund with /topup [og]\n`);
2105
+ }
2106
+ }),
2107
+ new Promise<void>((r) => setTimeout(r, 2500).unref()),
2108
+ ]).catch(() => { /* advisory only */ });
2109
+ advisoryWindowOpen = false;
2110
+ // Esc at the idle prompt = stop whatever this agent is doing server-side.
2111
+ // Throttled: hammering Esc must not queue N interrupts.
2112
+ // Displaced seat (occupancy.go): WeChat semantics — this window bows
2113
+ // out; Enter claims the seat back. Defined at session scope (the Esc brake
2114
+ // below, the command dispatch, and the chat turn all share it). `leavesWhat`
2115
+ // distinguishes the chat turn ("leaves the session" — it returns) from the
2116
+ // task paths ("leaves the seat with the other client" — this window stays
2117
+ // open, it just stops driving the agent).
2118
+ // A seat prompt pending flag: while displacedSeat's ask() is on screen,
2119
+ // the brake must stay quiet — firing it then would print "send a message
2120
+ // to take the seat back" UNDER a prompt that is already waiting, and
2121
+ // following that advice would answer the prompt instead of sending.
2122
+ let seatPromptPending = false;
2123
+ const displacedSeat = async (
2124
+ failure: string,
2125
+ reclaimedHint: string,
2126
+ leavesWhat = 'leaves the session',
2127
+ ): Promise<'reclaimed' | 'left' | null> => {
2128
+ if (!displacedFailure(failure)) return null;
2129
+ seatPromptPending = true;
2130
+ try {
2131
+ out(`\n⚠ this agent is now driven by another client\n`);
2132
+ const takeBack = (await ask(`press Enter to take the seat back (anything else ${leavesWhat}): `)).trim();
2133
+ if (takeBack === '') {
2134
+ try {
2135
+ if (s.url) { await s.ag.agent.claimAgent(s.url, BigInt(s.agentId), clientInstanceId); out(`seat reclaimed — ${reclaimedHint}\n`); return 'reclaimed'; }
2136
+ } catch (e) {
2137
+ out(`reclaim failed: ${(e as Error).message}\n`);
2138
+ }
2139
+ }
2140
+ out(`no live connection to reclaim — \`use ${s.agentId}\` re-enters\n`);
2141
+ return 'left';
2142
+ } finally {
2143
+ seatPromptPending = false;
2144
+ }
2145
+ };
2146
+
2147
+ irq.brake = makeBrake(() => s.client, out, displacedSeat, () => seatPromptPending);
2148
+ // A friendly message that hides WHICH failure happened costs a whole
2149
+ // debugging round trip: "no headers ever arrived" and "the stream was cut
2150
+ // mid-way" have different causes and used to print identically. Append the
2151
+ // transport in use and the runtime's own error identity.
2152
+ const failureDetail = (e: unknown, transport: string): string => {
2153
+ const err = e as { name?: string; message?: string; cause?: { code?: string; message?: string; name?: string } };
2154
+ const code = err?.cause?.code ?? err?.cause?.name ?? err?.name ?? '';
2155
+ const msg = err?.cause?.message ?? err?.message ?? '';
2156
+ return ` [${transport}${code ? ` · ${code}` : ''}${msg && msg !== code ? ` · ${msg.slice(0, 80)}` : ''}]`;
2157
+ };
2158
+ const messages: ChatMessage[] = [];
2159
+ try {
2160
+ for (;;) {
2161
+ activeCompletions = L2_WORDS;
2162
+ activeArgs = L2_ARGS;
2163
+ // While not connected (deploying/stopped/offline) the phase is in flux —
2164
+ // auto-refresh before every prompt, printing only when it moves (and
2165
+ // connecting the moment it reaches running). Once connected, skip: no
2166
+ // per-chat-line attestor round-trip; bare Enter stays the manual refresh.
2167
+ if (!s.client) { try { await refreshSession(s, true); } catch { /* prompt anyway */ } }
2168
+ const line = (await ask(`\nagent ${s.agentId} › `)).trim();
2169
+ if (!line) {
2170
+ // Bare Enter = live status refresh (phase moves on its own during
2171
+ // deploying/provisioning; the entry card only showed the initial one).
2172
+ try { await refreshSession(s); } catch { out(` phase ${s.phase} (refresh failed — attestor unreachable)\n`); }
2173
+ continue;
2174
+ }
2175
+ if (line === '/back' || line === '/unuse') { out('← back to manager\n'); return; }
2176
+ if (line === '/quit' || line === '/exit') { process.exit(0); }
2177
+ if (line === '/help') { out(`${L2_HELP_FULL}\n`); continue; }
2178
+
2179
+ try {
2180
+ if (line === '/hello') {
2181
+ if (s.phase !== 'running' || !s.url) { out(`agent is ${s.phase} — not reachable; /start or /reset first\n`); continue; }
2182
+ await showHello(s.ag, s.url);
2183
+ continue;
2184
+ }
2185
+ if (line === '/balance') {
2186
+ // Agent-focused: this agent's own evolution-gas (agentSeal) balance,
2187
+ // with the account-level prepaid alongside for context. The provider's
2188
+ // effective view (debt/queued fees) rides along when it says less is
2189
+ // spendable than the chain shows — same lines as the L1 `balance`.
2190
+ let effErr: string | null = null;
2191
+ const [rc, eff] = await Promise.all([
2192
+ s.ag.agent.runtimeCosts(BigInt(s.agentId)),
2193
+ s.ag.getEffectiveBalance().catch((e: Error) => { effErr = e.message; return null; }),
2194
+ ]);
2195
+ out(`agentSeal gas : ${og(rc.sealGasWei)} (${s.agentSeal ?? '?'})\n`);
2196
+ moneyBlock(rc.prepaidBalanceWei, eff, effErr);
2197
+ out('top up this agent with /topup [amount OG] · account-level details: `balance` in the manager\n');
2198
+ continue;
2199
+ }
2200
+ if (line === '/topup' || line.startsWith('/topup ')) {
2201
+ if (!s.agentSeal) {
2202
+ // Not learned from deploy//hello yet — the chain has it regardless
2203
+ // of phase (set-once at mint), so a stopped agent tops up fine.
2204
+ try {
2205
+ const sealAddr = await s.ag.agent.getAgentSeal(BigInt(s.agentId));
2206
+ if (!sealAddr || /^0x0{40}$/.test(sealAddr)) throw new Error('zero');
2207
+ s.agentSeal = sealAddr;
2208
+ } catch {
2209
+ out(`cannot resolve agent ${s.agentId}'s agentSeal from chain — is the mint complete?\n`);
2210
+ continue;
2211
+ }
2212
+ }
2213
+ const amt = line.split(/\s+/)[1] || (await ask(' amount OG [0.1]: ')).trim() || '0.1';
2214
+ const tx = await s.ag.agent.topUpAgentSeal(s.agentSeal, parseEther(amt));
2215
+ out(`topUpAgentSeal(${s.agentSeal}, ${amt} OG) → ${tx} (waiting…)\n`);
2216
+ // Parity with L1 `deposit`: return only once the chain agrees, so an
2217
+ // immediate /balance shows the new number (feedback.md S2).
2218
+ await s.ag.agent.waitForTransaction(tx);
2219
+ const rc = await s.ag.agent.runtimeCosts(BigInt(s.agentId)).catch(() => null);
2220
+ out(rc ? `confirmed — agentSeal gas now ${og(rc.sealGasWei)}\n` : 'confirmed\n');
2221
+ continue;
2222
+ }
2223
+ if (line === '/stop') {
2224
+ if (s.phase !== 'running' || !s.sandboxId) { out(`agent is ${s.phase} — nothing to stop\n`); continue; }
2225
+ out('stopping…\n'); await s.ag.agent.stop(s.sealId, s.sandboxId);
2226
+ s.phase = 'stopped'; s.url = undefined; s.client = undefined;
2227
+ // Stop is async server-side: until the attestor row flips, the
2228
+ // loop-top auto-refresh would happily reconnect to the dying
2229
+ // container (typed text then "chats" into the void) and a bare-Enter
2230
+ // refresh would contradict the 'stopped.' we just printed
2231
+ // (feedback.md F16/F17). Wait for the row, bounded.
2232
+ const deadline = Date.now() + 45_000;
2233
+ while (Date.now() < deadline) {
2234
+ try {
2235
+ const d = (await (await fetch(`${s.attestorUrl}/deployment/${s.sealId}`, { signal: AbortSignal.timeout(10_000) })).json()) as { phase?: string };
2236
+ if (d.phase && d.phase !== 'running') { s.phase = d.phase; break; }
2237
+ } catch { /* transient — keep waiting */ }
2238
+ await new Promise((r) => setTimeout(r, 2000));
2239
+ }
2240
+ out('stopped. /start brings it back.\n');
2241
+ continue;
2242
+ }
2243
+ if (line === '/start') {
2244
+ if (s.phase === 'running') { out('already running\n'); continue; }
2245
+ if (s.phase !== 'stopped' || !s.sandboxId) { out(`agent is ${s.phase} — a plain start cannot revive it; use /reset\n`); continue; }
2246
+ if (!(await ensureOwnerReady(s.ag, ask))) { out('start cancelled — prepaid balance too low\n'); continue; }
2247
+ out('starting… (Esc cancels the wait)\n'); await s.ag.agent.start(s.sealId, s.sandboxId);
2248
+ const r = await waitRunningInterruptible(irq, s.attestorUrl, s.sealId, s.agentId);
2249
+ if (!r) continue;
2250
+ await connectSession(s, r.url);
2251
+ out(`running at ${s.url}\n`); continue;
2252
+ }
2253
+ if (line === '/reset' || line === '/reset pick') {
2254
+ // Known framework (the attestor row remembers it, or this session
2255
+ // already picked one): use it without asking — changing harness on
2256
+ // reset is the rare case, and '/reset pick' forces the menu for it.
2257
+ // Unknown (legacy rows): menu as before.
2258
+ if (s.framework && line !== '/reset pick') {
2259
+ out(`framework: ${s.framework} (recorded — use /reset pick to change)\n`);
2260
+ } else {
2261
+ s.framework = await pickFramework(s.attestorUrl, ask, s.framework);
2262
+ }
2263
+ const provider = await agentInferenceProvider(s.ag, s.sealId);
2264
+ await s.ag.agent.assertProviderSupported(provider, { sealId: s.sealId, framework: s.framework });
2265
+ const apiKey = await inferenceKey(ctx, ask, provider);
2266
+ if (!(await ensureOwnerReady(s.ag, ask))) { out('reset cancelled — prepaid balance too low\n'); continue; }
2267
+ out(`resetting as ${s.framework}… (Esc cancels the wait)\n`);
2268
+ await s.ag.agent.reset(s.sealId, { provider, framework: s.framework, apiKey });
2269
+ const r = await waitRunningInterruptible(irq, s.attestorUrl, s.sealId, s.agentId);
2270
+ if (!r) continue;
2271
+ await connectSession(s, r.url);
2272
+ messages.length = 0; out(`back up at ${s.url}\n`); continue;
2273
+ }
2274
+ if (line === '/clear') {
2275
+ // Wipe the agent's persisted conversation (server-side) and this
2276
+ // window's local echo of it. Chain-tracked memory is untouched — that
2277
+ // is the difference between /clear and /reset. Frameworks whose
2278
+ // history is client-held answer 501; then clearing the local array IS
2279
+ // the clear.
2280
+ if (!s.url) { out(`agent is ${s.phase} — nothing to clear\n`); continue; }
2281
+ try {
2282
+ const r = await s.ag.agent.clearConversation(s.url, BigInt(s.agentId), clientInstanceId);
2283
+ messages.length = 0;
2284
+ out(`${r.note ?? 'conversation cleared'}\n`);
2285
+ } catch (e) {
2286
+ // clear is a seat-gated POST — a displaced 409 is a seat event here too
2287
+ if (await routeTaskFailure(out, displacedSeat, e, '', 'retry /clear') !== 'raw') continue;
2288
+ const msg = (e as Error).message;
2289
+ if (/HTTP 501/.test(msg)) { messages.length = 0; out('history is client-held for this framework — local history cleared\n'); }
2290
+ else out(`clear failed: ${msg}\n`);
2291
+ }
2292
+ continue;
2293
+ }
2294
+ if (line === '/compact') {
2295
+ // Compact the agent's persisted conversation in place: older history
2296
+ // becomes a summary, the newest part stays verbatim, and the
2297
+ // conversation goes on (unlike /clear). The summary takes one or more
2298
+ // model calls — minutes on a long history — and the agent finishes it
2299
+ // even if this connection drops; the runtime log has the outcome. The
2300
+ // local echo is left alone: the server-side history is the one
2301
+ // compacted.
2302
+ if (!s.url) { out(`agent is ${s.phase} — nothing to compact\n`); continue; }
2303
+ out('compacting the conversation (one or more model calls; can take a few minutes)…\n');
2304
+ try {
2305
+ const r = await s.ag.agent.compactConversation(s.url, BigInt(s.agentId), clientInstanceId);
2306
+ out(`${r.note ?? 'conversation compacted'}\n`);
2307
+ } catch (e) {
2308
+ // compact is a seat-gated POST — a displaced 409 is a seat event;
2309
+ // every other 409 (e.g. "compact refused") stays a compact error
2310
+ if (await routeTaskFailure(out, displacedSeat, e, '', 'retry /compact') !== 'raw') continue;
2311
+ const msg = (e as Error).message;
2312
+ const status = Number(msg.match(/^compactConversation: HTTP (\d+):/)?.[1] ?? 0);
2313
+ const cause = (e as { cause?: { code?: string } }).cause?.code ?? '';
2314
+ // The agent's own 500 ("compact failed: …") is a final outcome.
2315
+ const failed = msg.match(/^compactConversation: HTTP 500: (compact failed: [\s\S]*)$/);
2316
+ // A 501 that names a reason (an older framework version) shows it.
2317
+ const why = msg.match(/^compactConversation: HTTP 501: [^(]*\(([\s\S]*)\)\s*$/)?.[1]?.split(': ').pop()?.trim();
2318
+ // Sent, but no answer: this side gave up waiting (Node's fetch, after
2319
+ // 300s: UND_ERR_HEADERS_TIMEOUT), the connection dropped, or a
2320
+ // gateway on the way gave up (the agent's own route never answers
2321
+ // 502/504). The agent goes on compacting regardless — unlike a
2322
+ // connection that never opened, where nothing started.
2323
+ const unanswered = status === 502 || status === 504 ||
2324
+ ['UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET', 'ECONNRESET'].includes(cause);
2325
+ if (status === 501) out(`this agent's framework${s.framework ? ` (${s.framework})` : ''} does not support /compact${why ? ` (${why})` : ' yet'} — /clear starts fresh instead\n`);
2326
+ else if (status === 409) out(`compact refused: ${msg.replace(/^compactConversation: HTTP 409: /, '').trim()}\n`);
2327
+ else if (failed) out(`${failed[1].trim()}\n`);
2328
+ else if (unanswered) out(`no answer yet (${status ? `HTTP ${status} from a gateway on the way` : cause}); the agent may still be compacting — /startuplog shows the outcome (a "compact:" line). Wait for it before sending /compact again.\n`);
2329
+ else out(`compact failed: ${msg}${cause ? ` (${cause})` : ''}\n`);
2330
+ }
2331
+ continue;
2332
+ }
2333
+ if (line === '/agentlog' || line.startsWith('/agentlog ')) {
2334
+ if (!s.client?.logs) { out(s.client ? '(logs unavailable — owner key needed)' : `agent is ${s.phase} — /start or /reset first`); out('\n'); continue; }
2335
+ const n = Number(line.split(/\s+/)[1]) || 200;
2336
+ out(`${await s.client.logs({ tail: n })}\n`); continue;
2337
+ }
2338
+ if (line === '/startuplog' || line.startsWith('/startuplog ')) {
2339
+ // The sealed runtime serves /log from early boot — mid-`deploying` is
2340
+ // exactly when this log matters, so resolve the container URL now.
2341
+ if (!s.url) { try { await refreshSession(s); } catch { /* gate below reports */ } }
2342
+ if (!s.url) { out(`no container yet (${s.phase}) — nothing to read; /start or /reset creates one\n`); continue; }
2343
+ const n = Number(line.split(/\s+/)[1]) || 200;
2344
+ const res = await fetch(`${s.url}/log`, { signal: AbortSignal.timeout(10_000) });
2345
+ out(res.ok
2346
+ ? `${(await res.text()).split('\n').slice(-n).join('\n')}\n`
2347
+ : `container refused /log (HTTP ${res.status}) — agent is ${s.phase}; /agentlog has the runtime log once it's up\n`);
2348
+ continue;
2349
+ }
2350
+ if (line === '/settings' || line.startsWith('/settings ')) {
2351
+ // The owner's configuration document: which model this agent thinks
2352
+ // with, and how hard. Bare shows it; key=value writes it (merged).
2353
+ // Owner-signed in both directions, so it needs the wallet client and
2354
+ // not the session's (possibly keyless) one.
2355
+ await settingsOp(await withWallet(ctx), s.sealId, tokenize(line).slice(1), s.client && s.url ? s.url : undefined);
2356
+ continue;
2357
+ }
2358
+ if (line === '/think' || line.startsWith('/think ')) {
2359
+ // /think is `/settings thinking=…` with a shorter name: it writes the
2360
+ // owner's document, which is the only place a reasoning level lives
2361
+ // now. (It used to set a session variable that rode a container
2362
+ // environment variable on the next /reset — nothing reads that any
2363
+ // more, so the command announced a change it was not making.)
2364
+ const arg = tokenize(line)[1];
2365
+ const ag = await withWallet(ctx);
2366
+ if (!arg) {
2367
+ const doc = await ag.agent.getSettings(s.sealId);
2368
+ out(`thinking level: ${(doc.settings?.thinking as string | undefined) ?? '(unset — the platform bounds thinking models at low)'}\n`);
2369
+ continue;
2370
+ }
2371
+ if (!(THINKING_LEVELS as readonly string[]).includes(arg)) { out(`usage: /think ${THINKING_LEVELS.join('|')}\n`); continue; }
2372
+ if (arg === 'max') out('⚠ max is measured-risky here: thinking can exceed the router\'s ~10min single-request limit and the turn dies empty. Your call.\n');
2373
+ const written = await settingsOp(ag, s.sealId, [`thinking=${arg}`], s.client && s.url ? s.url : undefined);
2374
+ // Only mirror it into this session once the write actually landed —
2375
+ // a refused or conflicted write must not leave the per-message
2376
+ // override claiming a level the agent was never given.
2377
+ if (written?.thinking === arg) {
2378
+ s.thinking = arg as ThinkingLevel;
2379
+ out(s.framework === 'prime-agent'
2380
+ ? ' this framework also takes it per message, so your next message uses it already\n'
2381
+ : ' /reset applies it now; otherwise it lands at the agent\'s next boot\n');
2382
+ }
2383
+ continue;
2384
+ }
2385
+ if (line === '/tasks') {
2386
+ // Long-task surface (responses transport). The list is this session's
2387
+ // memory of submitted ids; status is fetched live from the agent.
2388
+ if (!s.client?.task) { out('(this agent has no task surface — chat turns are connection-bound here)\n'); continue; }
2389
+ if (!s.tasks?.length) { out('no tasks started from this session yet — every chat turn on this agent is one; /result <id> also re-attaches by id\n'); continue; }
2390
+ let displacedFromTasks: string | null = null;
2391
+ const rows = await Promise.all(s.tasks.map(async (t) => {
2392
+ const snap = await s.client!.task!(t.id).catch((e: Error) => {
2393
+ // DEFENSIVE: task() is an ungated GET today (the seat gates only
2394
+ // POST /v1/*), so this leg cannot fire on current images — but if
2395
+ // the gate ever widens, a 409 displaced is a seat event and routes
2396
+ // to the same prompt instead of "unknown (evicted…)".
2397
+ if (displacedFailure(e.message ?? '')) displacedFromTasks = e.message;
2398
+ return null;
2399
+ });
2400
+ return { ...t, status: snap?.status ?? 'unknown (evicted or agent restarted)' };
2401
+ }));
2402
+ if (displacedFromTasks && (await displacedSeat(displacedFromTasks, 'retry /tasks')) !== null) continue;
2403
+ for (const t of rows.reverse()) {
2404
+ out(` ${t.id} ${t.status.padEnd(12)} ${Math.round((Date.now() - t.at) / 1000)}s ago ${t.prompt}\n`);
2405
+ }
2406
+ out('re-attach with /result [id] (default: latest)\n');
2407
+ continue;
2408
+ }
2409
+ if (line === '/result' || line.startsWith('/result ')) {
2410
+ if (!s.client?.task || !s.client.followTask) { out('(this agent has no task surface)\n'); continue; }
2411
+ const id = line.split(/\s+/)[1] ?? s.tasks?.[s.tasks.length - 1]?.id;
2412
+ if (!id) { out('no task to show — /result <id>, or start one by chatting\n'); continue; }
2413
+ // Adopt an explicitly-named id into this session's task memory: the
2414
+ // id may come from another window, a /tasks listing before a restart,
2415
+ // or a dropped-connection message — once /result shows it, /cancel
2416
+ // (bare form) can stop it without re-typing the id.
2417
+ if (line.split(/\s+/)[1] && !s.tasks?.some((t) => t.id === id)) {
2418
+ (s.tasks ??= []).push({ id, prompt: '(adopted by /result)', at: Date.now() });
2419
+ }
2420
+ const snap = await s.client.task(id).catch(async (e: Error) => {
2421
+ // DEFENSIVE: ungated GET (see /tasks) — routed in case the gate widens
2422
+ if ((await displacedSeat(e.message ?? '', `retry /result ${id}`)) !== null) return null;
2423
+ out(`(${e.message})\n`);
2424
+ return null;
2425
+ });
2426
+ if (!snap) continue;
2427
+ if (snap.status === 'completed' || snap.status === 'cancelled' || snap.status === 'failed') {
2428
+ out(`task ${id} — ${snap.status}\n`);
2429
+ if (snap.output_text) out(`${snap.output_text}\n`);
2430
+ if (snap.error) out(`error: ${snap.error.message}\n`);
2431
+ continue;
2432
+ }
2433
+ // Still running: re-attach live. Text so far arrives via the replay
2434
+ // (followTask starts at sequence 0), so don't pre-print the snapshot.
2435
+ // Esc here stops WATCHING only (the deliberate stop stays on the chat
2436
+ // turn's Esc / the task's cancel).
2437
+ out(`task ${id} — ${snap.status}; following (esc stops watching, not the task; then /cancel ${id} stops it)\nagent> `);
2438
+ const ac = new AbortController();
2439
+ irq.streaming = ac;
2440
+ try {
2441
+ for await (const delta of s.client.followTask(id, { signal: ac.signal })) out(delta);
2442
+ out('\n');
2443
+ } catch (e) {
2444
+ out(ac.signal.aborted
2445
+ ? `\n(stopped watching — the task continues; /result re-attaches, then /cancel ${id} stops it)\n`
2446
+ : `\n(${(e as Error).message})\n`);
2447
+ } finally {
2448
+ irq.streaming = null;
2449
+ }
2450
+ continue;
2451
+ }
2452
+ if (line === '/cancel' || line.startsWith('/cancel ')) {
2453
+ if (!s.client) { out(`agent is ${s.phase} — /start or /reset to connect; /cancel needs a live connection (a task to cancel, if any, keeps running server-side)\n`); continue; }
2454
+ // The re-attach gap: Esc only cancels a turn THIS connection started
2455
+ // (s.currentTask); after a dropped stream the id is gone while the
2456
+ // turn keeps running server-side (on the responses transport that
2457
+ // survival is the feature). /cancel is the explicit brake: by id, or
2458
+ // everything in flight this session knows.
2459
+ let id = line.split(/\s+/)[1];
2460
+ if (!id && s.client?.task) {
2461
+ if (!s.tasks?.length) { out('no task id given and none started from this session — /cancel <id>, or /tasks to list (after a CLI restart or /back+use, this session starts empty)\n'); continue; }
2462
+ // Fetch live statuses; a fetch FAILURE is not "not in flight" —
2463
+ // only a 404 means the record is gone. Anything else (network
2464
+ // error, 5xx, 401, 409) means we could not CHECK, and the honest
2465
+ // answer is to say so, not to claim nothing is running.
2466
+ const rows: Array<{ id: string; status: string }> = [];
2467
+ let displacedDuringCheck: string | null = null;
2468
+ const unreachable: string[] = [];
2469
+ for (const t of s.tasks) {
2470
+ try {
2471
+ const snap = await s.client!.task!(t.id);
2472
+ rows.push({ id: t.id, status: snap.status });
2473
+ } catch (e) {
2474
+ const msg = (e as Error).message ?? '';
2475
+ // DEFENSIVE: ungated GET (see /tasks) — routed in case the gate widens
2476
+ if (displacedFailure(msg)) { displacedDuringCheck = msg; break; }
2477
+ if (msg.includes('HTTP 404')) rows.push({ id: t.id, status: 'unknown' });
2478
+ else unreachable.push(t.id);
2479
+ }
2480
+ }
2481
+ if (displacedDuringCheck && (await displacedSeat(displacedDuringCheck, 'retry /cancel')) !== null) continue;
2482
+ if (unreachable.length) {
2483
+ out(`could not reach the agent to check: ${unreachable.join(', ')} — the tasks may still be running; retry /cancel, or /cancel <id> directly\n`);
2484
+ continue;
2485
+ }
2486
+ // A brake stops everything in flight, newest first — stopping only
2487
+ // the newest would leave an older running turn alive (dsh/prime
2488
+ // serialize turns, so a queued one is waiting on the running one).
2489
+ const inFlight = inFlightIds(rows);
2490
+ if (!inFlight.length) { out('nothing in flight from this session — /tasks to list; a finished task cannot be cancelled\n'); continue; }
2491
+ if (s.client?.cancelTask) {
2492
+ let seatGone = false;
2493
+ for (const tid of inFlight) {
2494
+ // Retry the SAME id after a reclaim — the 409 killed this
2495
+ // cancel, not the task; every other in-flight id still needs
2496
+ // its own brake.
2497
+ for (;;) {
2498
+ try {
2499
+ const t = await s.client.cancelTask(tid);
2500
+ out(`⏹ cancel ${tid} — ${t.status === 'completed' ? 'already finished' : t.status}\n`);
2501
+ break;
2502
+ } catch (e) {
2503
+ const d = await routeTaskFailure(out, displacedSeat, e, `(cancel ${tid} failed: ${(e as Error).message})\n`, `retry /cancel ${tid}`);
2504
+ if (d === 'reclaimed') continue; // seat is back — retry this id
2505
+ if (d === 'left') { out(`(cancel ${tid} skipped — the seat is held by another client)\n`); seatGone = true; }
2506
+ break;
2507
+ }
2508
+ }
2509
+ if (seatGone) break; // every further POST would 409 the same way
2510
+ }
2511
+ continue;
2512
+ }
2513
+ }
2514
+ if (id && s.client?.cancelTask) {
2515
+ for (;;) {
2516
+ try {
2517
+ const t = await s.client.cancelTask(id);
2518
+ out(`⏹ cancel ${id} — ${t.status === 'completed' ? 'already finished' : t.status}\n`);
2519
+ break;
2520
+ } catch (e) {
2521
+ const d = await routeTaskFailure(out, displacedSeat, e, `(cancel failed: ${(e as Error).message})\n`, `retry /cancel ${id}`);
2522
+ if (d === 'reclaimed') continue; // seat is back — retry
2523
+ break;
2524
+ }
2525
+ }
2526
+ continue;
2527
+ }
2528
+ if (id && !s.client?.cancelTask) {
2529
+ // An id was asked for but this image has no task-level cancel: do
2530
+ // NOT silently interrupt "whatever is running" instead — but on
2531
+ // dsh/prime the bridge-wide interrupt DOES stop the running turn,
2532
+ // so point there instead of claiming nothing can be done.
2533
+ out(s.client?.interrupt
2534
+ ? '(this agent image has no per-task cancel — the bridge interrupt stops the current running turn; try /cancel with no id)\n'
2535
+ : '(this agent image has no task-level cancel — on agents without the task surface turns stop when the connection drops)\n');
2536
+ continue;
2537
+ }
2538
+ // Bare /cancel on an image without the task surface: same brake as
2539
+ // Esc at the idle prompt.
2540
+ if (!s.client?.interrupt) { out('(this agent image has no cancel path — /stop stops the whole container)\n'); continue; }
2541
+ const r = await s.client.interrupt().catch(async (e) => {
2542
+ // gated POST, same as the Esc brake
2543
+ if (await routeTaskFailure(out, displacedSeat, e, `(interrupt failed: ${(e as Error).message})\n`, 'retry the interrupt') !== 'raw') return null;
2544
+ return null;
2545
+ });
2546
+ if (r) out(r.aborted ? '⏹ stopped the running turn\n' : `(nothing to stop, or: ${r.note ?? 'not supported'})\n`);
2547
+ continue;
2548
+ }
2549
+ if (line.startsWith('/')) { out(`unknown command ${line}\n${L2_HELP}\n`); continue; }
2550
+ } catch (e) {
2551
+ // Show the remedy too: an error whose whole point is "do this instead"
2552
+ // (a refused settings write, a missing wallet) is useless without it.
2553
+ const ce = e as CliError;
2554
+ out(`error: ${ce.message}${ce.remedy ? `\n → ${ce.remedy}` : ''}\n`); continue;
2555
+ }
2556
+
2557
+ // a chat turn (interruptible)
2558
+ if (!s.client) { out(`agent is ${s.phase} — /start or /reset before chatting\n`); continue; }
2559
+ if (!s.client.chatStream) { out('(chat unavailable on this agent)\n'); continue; }
2560
+ messages.push({ role: 'user', content: line });
2561
+ // `model` is a per-framework selector some gateways require (openclaw
2562
+ // does; the dsh/prime bridges ignore it). Send it when known, omit it
2563
+ // otherwise — and only if the framework rejects that, ask once and retry.
2564
+ let retriedWithPick = false;
2565
+ for (;;) {
2566
+ const ac = new AbortController();
2567
+ irq.streaming = ac;
2568
+ out('agent> ');
2569
+ let reply = '';
2570
+ let interrupted = false;
2571
+ let failure: string | null = null;
2572
+ // ── Live status line (CC-style) ────────────────────────────────────
2573
+ // An agent turn spends most of its time producing NOTHING visible —
2574
+ // model thinking, tools running. One transient line keeps the wait
2575
+ // legible: a spinner, what it's doing (last activity label, or
2576
+ // "thinking" as the default guess), elapsed seconds, and the way out.
2577
+ // ⠹ tool/call bash… (14s · esc to interrupt)
2578
+ // Repainted once a second; any real output erases it. TTY only —
2579
+ // pipes get the clean payload.
2580
+ const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧'];
2581
+ const turnT0 = Date.now();
2582
+ let spin = 0;
2583
+ let status = 'thinking';
2584
+ let statusShown = false;
2585
+ let sawToolActivity = false;
2586
+ const clearActivity = (): void => {
2587
+ if (statusShown) { out('\r\x1b[2K'); statusShown = false; }
2588
+ };
2589
+ const paintStatus = (): void => {
2590
+ if (!process.stdout.isTTY || ac.signal.aborted) return;
2591
+ // Never overwrite the agent's own partial line — break to a fresh
2592
+ // one first (the visual break marks where the status began).
2593
+ if (!statusShown && reply && !reply.endsWith('\n')) out('\n');
2594
+ const secs = Math.floor((Date.now() - turnT0) / 1000);
2595
+ spin = (spin + 1) % SPIN.length;
2596
+ out(`\r\x1b[2K ${SPIN[spin]} ${status}… (${secs}s · esc to interrupt)`);
2597
+ statusShown = true;
2598
+ };
2599
+ const onActivity = process.stdout.isTTY
2600
+ ? (label: string): void => {
2601
+ // "did work this turn" detector, across bridges' label dialects:
2602
+ // dsh "tool/call bash", prime "tool_execution_start — bash" /
2603
+ // "bash_command_start", hermes "tool/call web_search". Thinking
2604
+ // alone doesn't count — a think-only turn with no output is still
2605
+ // a failure worth reporting.
2606
+ if (/tool|bash|subagent|rlm_child/i.test(label) && label !== 'thinking') sawToolActivity = true;
2607
+ if (label.startsWith('turn/end')) { clearActivity(); return; }
2608
+ status = label;
2609
+ paintStatus();
2610
+ }
2611
+ : undefined;
2612
+ // Ticker: repaint elapsed/spinner during silence. Starts after a short
2613
+ // grace (instant replies never see it), stops at first delta unless the
2614
+ // agent goes silent again mid-turn (tools) — then the last label keeps
2615
+ // counting.
2616
+ let lastOutputAt = Date.now();
2617
+ const ticker = process.stdout.isTTY
2618
+ ? setInterval(() => {
2619
+ if (ac.signal.aborted) return;
2620
+ if (Date.now() - lastOutputAt >= 2000) paintStatus();
2621
+ }, 1000)
2622
+ : null;
2623
+ try {
2624
+ const opts = {
2625
+ ...(s.framework ? { model: s.framework } : {}),
2626
+ ...(s.thinking ? { thinking: s.thinking } : {}),
2627
+ signal: ac.signal,
2628
+ ...(onActivity ? { onActivity } : {}),
2629
+ // Responses transport only: remember the server-side task id, so
2630
+ // Esc cancels THIS task and /tasks//result can re-attach to it.
2631
+ onTask: (id: string): void => {
2632
+ s.currentTask = id;
2633
+ (s.tasks ??= []).push({ id, prompt: line.slice(0, 60), at: Date.now() });
2634
+ },
2635
+ };
2636
+ for await (const delta of s.client.chatStream(messages, opts)) {
2637
+ clearActivity();
2638
+ out(delta); reply += delta;
2639
+ lastOutputAt = Date.now();
2640
+ status = 'writing';
2641
+ }
2642
+ clearActivity();
2643
+ } catch (e) {
2644
+ clearActivity();
2645
+ if ((e as Error).name === 'AbortError' || ac.signal.aborted) {
2646
+ interrupted = true;
2647
+ // Esc means "stop the TASK", not "stop watching": tearing down the
2648
+ // HTTP stream alone leaves the turn running server-side (on the
2649
+ // responses transport that survival is the FEATURE). Cancel by task
2650
+ // id when we have one (works on all four frameworks), else fall
2651
+ // back to the bridge-wide /v1/interrupt.
2652
+ const stopped: { aborted: boolean; note?: string } | null | undefined =
2653
+ s.currentTask && s.client.cancelTask
2654
+ ? await s.client.cancelTask(s.currentTask).then(
2655
+ (t) => ({ aborted: t.status === 'cancelled' || t.status === 'completed' }),
2656
+ () => null,
2657
+ )
2658
+ : await s.client.interrupt?.().catch(() => null);
2659
+ // No /v1/interrupt endpoint (openclaw/hermes serve their own /v1
2660
+ // directly): both stop the turn on client disconnect — openclaw via
2661
+ // watchClientDisconnect→AbortController, hermes via its abandoned-SSE
2662
+ // hard-interrupt + reap — so the disconnect Esc just did IS the stop.
2663
+ out(stopped?.aborted || (stopped && /disconnects/.test(stopped.note ?? ''))
2664
+ ? '\n⏹ interrupted — the task stopped (already-executed actions are not rolled back)'
2665
+ : `\n(interrupted the stream — but the task may still be running${stopped?.note ? `: ${stopped.note}` : ''}; /cancel stops it${s.client?.cancelTask ? '' : ' (bare form — this image has no per-id cancel)'})`);
2666
+ } else if (/lost the agent while following/.test((e as Error).message)) {
2667
+ // Responses transport: the SDK already auto-resumed through drops
2668
+ // and only gives up after repeated reconnect failures — the agent
2669
+ // (or the network to it) is down, but the task itself may well
2670
+ // still be running inside the container.
2671
+ out(`\n(lost the connection after ${Math.round((Date.now() - turnT0) / 1000)}s of retrying — the task likely CONTINUES on the agent. /result re-attaches when it's reachable again; /tasks lists this session's tasks)${failureDetail(e, s.client?.task ? 'responses' : 'chat')}\n`);
2672
+ messages.push({ role: 'assistant', content: `${reply} [connection lost mid-turn — task continued server-side]` });
2673
+ break;
2674
+ } else if (/fetch failed|terminated|ECONNRESET|socket|network|aborted by the server|other side closed/i.test((e as Error).message)) {
2675
+ // Connection dropped WITHOUT the user asking (proxy duration caps,
2676
+ // network blips, sleep). The bridges deliberately keep the turn
2677
+ // running through disconnects (only /v1/interrupt stops work), so
2678
+ // this is a lost window, not a failed task — say so instead of
2679
+ // crying failure, and route the user to the reattach paths.
2680
+ // The hint must match the transport: on the responses transport
2681
+ // the task survives and /result re-attaches; on plain chat/
2682
+ // completions (no task surface) the turn dies with the connection
2683
+ // and the old advice — send a message to see if the agent answers —
2684
+ // was the working one.
2685
+ const hint = s.client?.task
2686
+ ? `Re-attach with /result${s.currentTask ? ` ${s.currentTask}` : ''}; /agentlog shows its log; /cancel${s.currentTask ? ` ${s.currentTask}` : ''} stops it`
2687
+ : 'the turn stopped with it (no task surface on this image) — send a message to see if the agent answers; /agentlog shows its log';
2688
+ out(`\n(connection dropped after ${Math.round((Date.now() - turnT0) / 1000)}s — ${s.client?.task ? `the task CONTINUES on the agent${s.currentTask ? ` as ${s.currentTask}` : ''}. ${hint}` : hint})${failureDetail(e, s.client?.task ? 'responses' : 'chat')}\n`);
2689
+ messages.push({ role: 'assistant', content: `${reply} [connection dropped mid-turn — task continued server-side]` });
2690
+ break;
2691
+ } else {
2692
+ failure = (e as Error).message;
2693
+ }
2694
+ } finally {
2695
+ if (ticker) clearInterval(ticker);
2696
+ clearActivity();
2697
+ irq.streaming = null;
2698
+ s.currentTask = null;
2699
+ }
2700
+ if (failure && !s.framework && !retriedWithPick) {
2701
+ out(`\n(chat failed: ${failure})\nthis framework may need a model selector — pick it:\n`);
2702
+ s.framework = await pickFramework(s.attestorUrl, ask);
2703
+ retriedWithPick = true;
2704
+ continue; // retry the same user message once with the selector
2705
+ }
2706
+ // A turn that ran tools but produced no text is WORK, not failure —
2707
+ // dsh agents legitimately end tool-only turns silently. Say what
2708
+ // happened instead of crying wolf (the true-failure path — no deltas,
2709
+ // no activity — still reports as an error).
2710
+ // Displaced by another window (occupancy.go): WeChat semantics — this
2711
+ // window bows out to the manager (same exit as /back; the try/finally
2712
+ // still releases the Esc brake). Entering the session again claims the
2713
+ // seat back.
2714
+ if (failure) {
2715
+ const d = await displacedSeat(failure, 'continue chatting', 'leaves the session');
2716
+ if (d === 'reclaimed') continue;
2717
+ if (d === 'left') return;
2718
+ }
2719
+ if (failure && sawToolActivity && /without any output/.test(failure)) {
2720
+ out('\n(the agent ran tools this turn but wrote no reply — /agentlog shows what it did)');
2721
+ failure = null;
2722
+ }
2723
+ // The catch-all failure — a model the backend rejects (e.g. a catalog
2724
+ // max_tokens over the model's real cap), a bad key, an upstream 400 —
2725
+ // arrives here as the gateway's terse transcript ("LLM request failed"),
2726
+ // while the actual cause (the 400 body) is only in the container log. A
2727
+ // turn that fails EVERY time is usually the model or config it was just
2728
+ // given, so point at the log the way the connection-drop branches do.
2729
+ if (failure) out(`\n(chat failed: ${failure}) — /agentlog has the agent's full error (a turn that fails every time usually means the model or config just set)`);
2730
+ out('\n');
2731
+ messages.push({ role: 'assistant', content: interrupted ? `${reply} [interrupted]` : reply });
2732
+ break;
2733
+ }
2734
+ }
2735
+ } finally {
2736
+ irq.brake = null; // leaving the session: idle-Esc no longer targets this agent
2737
+ }
2738
+ }