@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.0

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