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