@aednzxy/smith-tui 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +160 -2
  2. package/dist/app/commands.js +58 -0
  3. package/dist/app/commands.js.map +1 -0
  4. package/dist/app/controller.js +5129 -0
  5. package/dist/app/controller.js.map +1 -0
  6. package/dist/app/state.js +266 -0
  7. package/dist/app/state.js.map +1 -0
  8. package/dist/cli.js +154 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/client/config.js +110 -0
  11. package/dist/client/config.js.map +1 -0
  12. package/dist/client/http.js +796 -0
  13. package/dist/client/http.js.map +1 -0
  14. package/dist/client/reducer.js +623 -0
  15. package/dist/client/reducer.js.map +1 -0
  16. package/dist/client/session-start.js +39 -0
  17. package/dist/client/session-start.js.map +1 -0
  18. package/dist/client/shell-ws.js +126 -0
  19. package/dist/client/shell-ws.js.map +1 -0
  20. package/dist/client/types.js +22 -0
  21. package/dist/client/types.js.map +1 -0
  22. package/dist/client/ws.js +233 -0
  23. package/dist/client/ws.js.map +1 -0
  24. package/dist/engine/color.js +142 -0
  25. package/dist/engine/color.js.map +1 -0
  26. package/dist/engine/editor.js +350 -0
  27. package/dist/engine/editor.js.map +1 -0
  28. package/dist/engine/input.js +351 -0
  29. package/dist/engine/input.js.map +1 -0
  30. package/dist/engine/screen.js +513 -0
  31. package/dist/engine/screen.js.map +1 -0
  32. package/dist/engine/terminal.js +163 -0
  33. package/dist/engine/terminal.js.map +1 -0
  34. package/dist/format/diff.js +85 -0
  35. package/dist/format/diff.js.map +1 -0
  36. package/dist/format/markdown.js +438 -0
  37. package/dist/format/markdown.js.map +1 -0
  38. package/dist/format/questions.js +78 -0
  39. package/dist/format/questions.js.map +1 -0
  40. package/dist/format/sessions.js +310 -0
  41. package/dist/format/sessions.js.map +1 -0
  42. package/dist/format/time.js +217 -0
  43. package/dist/format/time.js.map +1 -0
  44. package/dist/format/tools.js +169 -0
  45. package/dist/format/tools.js.map +1 -0
  46. package/dist/format/vt.js +233 -0
  47. package/dist/format/vt.js.map +1 -0
  48. package/dist/index.js +24 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/theme/palettes.js +1651 -0
  51. package/dist/theme/palettes.js.map +1 -0
  52. package/dist/views/activity-view.js +212 -0
  53. package/dist/views/activity-view.js.map +1 -0
  54. package/dist/views/auth-view.js +85 -0
  55. package/dist/views/auth-view.js.map +1 -0
  56. package/dist/views/boards-view.js +163 -0
  57. package/dist/views/boards-view.js.map +1 -0
  58. package/dist/views/chat-view.js +626 -0
  59. package/dist/views/chat-view.js.map +1 -0
  60. package/dist/views/compute-view.js +281 -0
  61. package/dist/views/compute-view.js.map +1 -0
  62. package/dist/views/files-skills-view.js +209 -0
  63. package/dist/views/files-skills-view.js.map +1 -0
  64. package/dist/views/fleet-view.js +282 -0
  65. package/dist/views/fleet-view.js.map +1 -0
  66. package/dist/views/inspector-view.js +612 -0
  67. package/dist/views/inspector-view.js.map +1 -0
  68. package/dist/views/memory-view.js +316 -0
  69. package/dist/views/memory-view.js.map +1 -0
  70. package/dist/views/modals-view.js +709 -0
  71. package/dist/views/modals-view.js.map +1 -0
  72. package/dist/views/notes-view.js +133 -0
  73. package/dist/views/notes-view.js.map +1 -0
  74. package/dist/views/select-agent-view.js +153 -0
  75. package/dist/views/select-agent-view.js.map +1 -0
  76. package/dist/views/settings-view.js +538 -0
  77. package/dist/views/settings-view.js.map +1 -0
  78. package/dist/views/shell-layout.js +802 -0
  79. package/dist/views/shell-layout.js.map +1 -0
  80. package/package.json +47 -4
@@ -0,0 +1,796 @@
1
+ // Complete authenticated HTTP client for Smith's gateway and worker passthrough routes.
2
+ // Implements ADR 122 bearer auth, 401 session-ended handling, 503 migration-pending detection,
3
+ // and ETag caching for GET /sessions.
4
+ import { hostname } from 'node:os';
5
+ import { gatewayHttpOrigin } from './config.js';
6
+ export class ApiError extends Error {
7
+ status;
8
+ code;
9
+ retryAfterSeconds;
10
+ constructor(message, status, code = null, retryAfterSeconds = null) {
11
+ super(message);
12
+ this.status = status;
13
+ this.code = code;
14
+ this.retryAfterSeconds = retryAfterSeconds;
15
+ this.name = 'ApiError';
16
+ }
17
+ }
18
+ const WORKER_PATH_RE = /^\/api\/agent\/([^/]+)\/worker(?:\/|$)/;
19
+ function encodePathSegments(path) {
20
+ return path.split('/').filter(Boolean).map(encodeURIComponent).join('/');
21
+ }
22
+ export class GatewayClient {
23
+ server;
24
+ token;
25
+ fetchImpl;
26
+ callbacks;
27
+ sessionsEtagCache = new Map();
28
+ constructor(server, token, callbacks = {}, fetchImpl = globalThis.fetch) {
29
+ this.server = server;
30
+ this.token = token;
31
+ this.callbacks = callbacks;
32
+ this.fetchImpl = fetchImpl;
33
+ }
34
+ setServer(server) {
35
+ this.server = server;
36
+ this.sessionsEtagCache.clear();
37
+ }
38
+ getServer() {
39
+ return this.server;
40
+ }
41
+ setToken(token) {
42
+ if (this.token !== token) {
43
+ this.token = token;
44
+ this.sessionsEtagCache.clear();
45
+ }
46
+ }
47
+ getToken() {
48
+ return this.token;
49
+ }
50
+ origin() {
51
+ return gatewayHttpOrigin(this.server);
52
+ }
53
+ workerUrl(dir, path) {
54
+ const clean = path.startsWith('/') ? path : `/${path}`;
55
+ return `${this.origin()}/api/agent/${encodeURIComponent(dir)}/worker${clean}`;
56
+ }
57
+ agentControlUrl(dir, path) {
58
+ const clean = path.startsWith('/') ? path.slice(1) : path;
59
+ return `${this.origin()}/api/agent/${encodeURIComponent(dir)}/${clean}`;
60
+ }
61
+ async rawFetch(url, init = {}, auth = true) {
62
+ const headers = new Headers(init.headers);
63
+ const usedToken = auth ? this.token : null;
64
+ if (usedToken && !headers.has('Authorization')) {
65
+ headers.set('Authorization', `Bearer ${usedToken}`);
66
+ }
67
+ let response;
68
+ try {
69
+ response = await this.fetchImpl(url, { ...init, headers });
70
+ }
71
+ catch (err) {
72
+ const msg = err instanceof Error ? err.message : 'Network error';
73
+ throw new ApiError(`Could not reach ${this.origin()}: ${msg}`, 0, 'unreachable');
74
+ }
75
+ if (auth && usedToken && response.status === 401 && this.token === usedToken) {
76
+ this.callbacks.onUnauthorized?.('Your session has ended. Sign in again.');
77
+ }
78
+ try {
79
+ const parsed = new URL(url);
80
+ const match = WORKER_PATH_RE.exec(parsed.pathname);
81
+ if (match) {
82
+ const dir = decodeURIComponent(match[1]);
83
+ if (response.status === 503) {
84
+ const clone = await response.clone().json().catch(() => null);
85
+ if (clone?.error === 'identity migration pending') {
86
+ this.callbacks.onMigrationPending?.(dir, true);
87
+ }
88
+ }
89
+ else {
90
+ this.callbacks.onMigrationPending?.(dir, false);
91
+ }
92
+ }
93
+ }
94
+ catch {
95
+ // ignore URL parsing errors
96
+ }
97
+ return response;
98
+ }
99
+ async requestJson(url, init = {}, auth = true) {
100
+ const response = await this.rawFetch(url, init, auth);
101
+ if (response.status === 204)
102
+ return undefined;
103
+ let body = null;
104
+ try {
105
+ body = await response.json();
106
+ }
107
+ catch {
108
+ body = null;
109
+ }
110
+ if (response.ok)
111
+ return body;
112
+ const obj = body && typeof body === 'object' ? body : {};
113
+ const code = typeof obj.code === 'string'
114
+ ? obj.code
115
+ : typeof obj.error === 'string'
116
+ ? obj.error
117
+ : null;
118
+ const retryHeader = response.headers.get('retry-after');
119
+ const retryAfter = retryHeader && Number.isFinite(Number(retryHeader)) ? Math.ceil(Number(retryHeader)) : null;
120
+ const message = (typeof obj.message === 'string' && obj.message) ||
121
+ (typeof obj.error === 'string' && obj.error) ||
122
+ `HTTP ${response.status} ${response.statusText}`.trim();
123
+ throw new ApiError(message, response.status, code, retryAfter);
124
+ }
125
+ jsonInit(method, body) {
126
+ return {
127
+ method,
128
+ headers: { 'Content-Type': 'application/json' },
129
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
130
+ };
131
+ }
132
+ // ── Auth ──────────────────────────────────────────────────────────────────
133
+ async probeGateway() {
134
+ try {
135
+ const res = await this.rawFetch(`${this.origin()}/api/auth/me`, { method: 'GET' }, false);
136
+ if (res.status === 401 || res.ok)
137
+ return 'reachable';
138
+ if (res.status === 404)
139
+ return 'outdated';
140
+ return 'reachable';
141
+ }
142
+ catch {
143
+ return 'unreachable';
144
+ }
145
+ }
146
+ async login(email, password) {
147
+ const hostLabel = hostname() || 'terminal';
148
+ const res = await this.rawFetch(`${this.origin()}/api/auth/login`, this.jsonInit('POST', {
149
+ email,
150
+ password,
151
+ device_name: `Smith TUI on ${hostLabel}`,
152
+ platform: process.platform,
153
+ }), false);
154
+ if (res.status === 404) {
155
+ throw new ApiError('Update Smith on the host to use this client.', 404, 'gateway_too_old');
156
+ }
157
+ if (res.status === 401) {
158
+ throw new ApiError('Wrong email or password.', 401, 'invalid_credentials');
159
+ }
160
+ if (res.status === 429) {
161
+ const retry = Number(res.headers.get('retry-after'));
162
+ const secs = Number.isFinite(retry) && retry > 0 ? Math.ceil(retry) : null;
163
+ throw new ApiError(secs ? `Too many attempts. Wait ${Math.ceil(secs / 60)} min and try again.` : 'Too many attempts. Try again later.', 429, 'rate_limited', secs);
164
+ }
165
+ const body = (await res.json().catch(() => null));
166
+ if (!res.ok || !body || typeof body.token !== 'string' || !body.user) {
167
+ throw new ApiError(body?.message ?? body?.error ?? `Sign-in failed (HTTP ${res.status})`, res.status);
168
+ }
169
+ return {
170
+ token: body.token,
171
+ user: body.user,
172
+ memberships: Array.isArray(body.memberships) ? body.memberships : [],
173
+ };
174
+ }
175
+ async fetchMe() {
176
+ const body = await this.requestJson(`${this.origin()}/api/auth/me`);
177
+ return {
178
+ user: body.user ?? null,
179
+ is_admin: body.is_admin === true,
180
+ shell_access: body.shell_access === true,
181
+ memberships: Array.isArray(body.memberships) ? body.memberships : [],
182
+ };
183
+ }
184
+ async updateTimeZone(timezone) {
185
+ const body = await this.requestJson(`${this.origin()}/api/auth/me`, this.jsonInit('PATCH', { timezone }));
186
+ return {
187
+ user: body.user ?? null,
188
+ is_admin: body.is_admin === true,
189
+ shell_access: body.shell_access === true,
190
+ memberships: Array.isArray(body.memberships) ? body.memberships : [],
191
+ };
192
+ }
193
+ async logout() {
194
+ try {
195
+ await this.rawFetch(`${this.origin()}/api/auth/logout`, { method: 'POST' });
196
+ }
197
+ catch {
198
+ // Clear local state regardless of transport failure
199
+ }
200
+ }
201
+ async changePassword(current, next) {
202
+ await this.requestJson(`${this.origin()}/api/auth/password`, this.jsonInit('POST', { current, new: next }));
203
+ }
204
+ async listDeviceSessions() {
205
+ const body = await this.requestJson(`${this.origin()}/api/auth/sessions`);
206
+ return Array.isArray(body.sessions) ? body.sessions : [];
207
+ }
208
+ async revokeDeviceSession(id) {
209
+ await this.requestJson(`${this.origin()}/api/auth/sessions/${id}`, { method: 'DELETE' });
210
+ }
211
+ // ── Directory & Fleet ─────────────────────────────────────────────────────
212
+ async fetchAgentDirectory() {
213
+ const body = await this.requestJson(`${this.origin()}/api/agents`);
214
+ return {
215
+ agents: Array.isArray(body.agents) ? body.agents : [],
216
+ memberScopedFleet: body.memberScopedFleet === true,
217
+ notificationBroker: typeof body.notificationBroker === 'number' ? body.notificationBroker : null,
218
+ };
219
+ }
220
+ fetchFleetSummary() {
221
+ return this.requestJson(`${this.origin()}/api/fleet/summary`);
222
+ }
223
+ fetchFleetAttention() {
224
+ return this.requestJson(`${this.origin()}/api/fleet/attention`);
225
+ }
226
+ dismissFleetAttention(item) {
227
+ return this.requestJson(`${this.origin()}/api/fleet/attention/dismiss`, this.jsonInit('POST', item));
228
+ }
229
+ undismissFleetAttention(key) {
230
+ return this.requestJson(`${this.origin()}/api/fleet/attention/undismiss`, this.jsonInit('POST', { key }));
231
+ }
232
+ fetchFleetCost(range = '30d') {
233
+ return this.requestJson(`${this.origin()}/api/fleet/cost?range=${range}`);
234
+ }
235
+ async fetchRunningJobs() {
236
+ const body = await this.requestJson(`${this.origin()}/api/jobs/running`);
237
+ return Array.isArray(body.jobs) ? body.jobs : [];
238
+ }
239
+ fetchFleetCredentialsUsage() {
240
+ return this.requestJson(`${this.origin()}/api/fleet/credentials-usage`);
241
+ }
242
+ fetchFleetStorage() {
243
+ return this.requestJson(`${this.origin()}/api/fleet/storage`);
244
+ }
245
+ fetchGlobalSearch(query, signal) {
246
+ return this.requestJson(`${this.origin()}/api/search?q=${encodeURIComponent(query)}&limit=60`, signal ? { signal } : {});
247
+ }
248
+ startAgent(dir) {
249
+ return this.requestJson(this.agentControlUrl(dir, 'start'), { method: 'POST' });
250
+ }
251
+ stopAgent(dir) {
252
+ return this.requestJson(this.agentControlUrl(dir, 'stop'), { method: 'POST' });
253
+ }
254
+ restartAgent(dir) {
255
+ return this.requestJson(this.agentControlUrl(dir, 'restart'), { method: 'POST' });
256
+ }
257
+ createAgent(body) {
258
+ return this.requestJson(`${this.origin()}/api/agents`, this.jsonInit('POST', body));
259
+ }
260
+ destroyAgent(dir, confirmName) {
261
+ return this.requestJson(`${this.origin()}/api/agent/${encodeURIComponent(dir)}`, this.jsonInit('DELETE', { confirmName }));
262
+ }
263
+ async fetchModels() {
264
+ const body = await this.requestJson(`${this.origin()}/api/models`);
265
+ return Array.isArray(body.models) ? body.models : [];
266
+ }
267
+ async fetchAgentModels(dir) {
268
+ try {
269
+ const body = await this.requestJson(this.agentControlUrl(dir, 'models'));
270
+ return Array.isArray(body.models) ? body.models : [];
271
+ }
272
+ catch {
273
+ return this.fetchModels();
274
+ }
275
+ }
276
+ // ── Conversations / Sessions (Worker Passthrough) ─────────────────────────
277
+ async fetchSessions(dir) {
278
+ const url = this.workerUrl(dir, '/sessions');
279
+ const cached = this.sessionsEtagCache.get(url);
280
+ const headers = {};
281
+ if (cached)
282
+ headers['If-None-Match'] = cached.etag;
283
+ const res = await this.rawFetch(url, { headers });
284
+ if (res.status === 304 && cached)
285
+ return cached.rows;
286
+ if (!res.ok)
287
+ throw new ApiError(`Failed to load sessions (HTTP ${res.status})`, res.status);
288
+ const rows = (await res.json());
289
+ const etag = res.headers.get('etag');
290
+ if (etag)
291
+ this.sessionsEtagCache.set(url, { etag, rows });
292
+ else
293
+ this.sessionsEtagCache.delete(url);
294
+ return Array.isArray(rows) ? rows : [];
295
+ }
296
+ fetchActiveSessions(dir) {
297
+ return this.requestJson(this.workerUrl(dir, '/active-sessions'));
298
+ }
299
+ fetchHistoryMessages(dir, sessionId) {
300
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/messages?format=history`));
301
+ }
302
+ fetchHistoryPage(dir, sessionId, before) {
303
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/messages?format=history&before=${before}`));
304
+ }
305
+ setSessionPinned(dir, sessionId, pinned) {
306
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}`), this.jsonInit('PATCH', { pinned }));
307
+ }
308
+ setSessionArchived(dir, sessionId, archived) {
309
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}`), this.jsonInit('PATCH', { archived }));
310
+ }
311
+ branchSession(dir, sessionId, messageId, mode) {
312
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/branch`), this.jsonInit('POST', { messageId, mode }));
313
+ }
314
+ editQueuedMessage(dir, sessionId, messageId, text) {
315
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/queued/${messageId}`), this.jsonInit('PATCH', { text }));
316
+ }
317
+ deleteQueuedMessage(dir, sessionId, messageId) {
318
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/queued/${messageId}`), { method: 'DELETE' });
319
+ }
320
+ sendQueuedMessageNow(dir, sessionId, messageId) {
321
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/queued/${messageId}/steer`), { method: 'POST' });
322
+ }
323
+ dismissSessionQuestion(dir, sessionId, observed) {
324
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/question/dismiss`), this.jsonInit('POST', observed));
325
+ }
326
+ wakeSessionNow(dir, sessionId) {
327
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/wake-now`), { method: 'POST' });
328
+ }
329
+ setSessionWake(dir, sessionId, wake) {
330
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/wake`), this.jsonInit('PUT', wake));
331
+ }
332
+ cancelSessionWake(dir, sessionId) {
333
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/wake`), { method: 'DELETE' });
334
+ }
335
+ postReadState(dir, sessionId, update) {
336
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/read-state`), this.jsonInit('POST', update));
337
+ }
338
+ fetchConversationParticipants(dir, sessionId) {
339
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/participants`));
340
+ }
341
+ setConversationParticipant(dir, sessionId, input) {
342
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/participants`), this.jsonInit('PATCH', input));
343
+ }
344
+ fetchConversationHierarchy(dir, sessionId) {
345
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/hierarchy`));
346
+ }
347
+ async fetchAttentionEvents(dir, open = true) {
348
+ try {
349
+ return await this.requestJson(this.workerUrl(dir, `/attention/events${open ? '?open=1' : ''}`));
350
+ }
351
+ catch (err) {
352
+ if (err instanceof ApiError && err.status === 404)
353
+ return null;
354
+ throw err;
355
+ }
356
+ }
357
+ dismissAttentionEvent(dir, id) {
358
+ return this.requestJson(this.workerUrl(dir, `/attention/events/${id}/dismiss`), { method: 'POST' });
359
+ }
360
+ // ── Following Inspector: Widgets, Notes, Subagents, Changes, PRs, Browser ─
361
+ async fetchSessionWidgets(dir, sessionId) {
362
+ const body = await this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/widgets`));
363
+ return Array.isArray(body.widgets) ? body.widgets : [];
364
+ }
365
+ stopBackgroundProcess(dir, sessionId, processId) {
366
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/background/${encodeURIComponent(processId)}/stop`), { method: 'POST' });
367
+ }
368
+ fetchSessionNote(dir, sessionId) {
369
+ return this.requestJson(this.agentControlUrl(dir, `sessions/${encodeURIComponent(sessionId)}/notes`));
370
+ }
371
+ saveSessionNote(dir, sessionId, text, version) {
372
+ return this.requestJson(this.agentControlUrl(dir, `sessions/${encodeURIComponent(sessionId)}/notes`), this.jsonInit('PUT', { text, version }));
373
+ }
374
+ fetchAgentSessions(dir, sessionId) {
375
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/agent-sessions?limit=200`));
376
+ }
377
+ fetchAgentSessionDetail(dir, id) {
378
+ return this.requestJson(this.workerUrl(dir, `/agent-sessions/${encodeURIComponent(id)}`));
379
+ }
380
+ fetchAgentSessionTranscript(dir, id) {
381
+ return this.requestJson(this.workerUrl(dir, `/agent-sessions/${encodeURIComponent(id)}/transcript`));
382
+ }
383
+ mutateAgentSession(dir, id, action, text) {
384
+ return this.requestJson(this.workerUrl(dir, `/agent-sessions/${encodeURIComponent(id)}/${action}`), action === 'stop' ? { method: 'POST' } : this.jsonInit('POST', { text: text ?? '' }));
385
+ }
386
+ fetchConversationChanges(dir, sessionId) {
387
+ return this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/changes`));
388
+ }
389
+ fetchWorktreeFileDiff(dir, agentSessionId, path) {
390
+ return this.requestJson(this.workerUrl(dir, `/agent-sessions/${encodeURIComponent(agentSessionId)}/diff?path=${encodeURIComponent(path)}`));
391
+ }
392
+ async fetchPullRequestStatuses(dir, urls) {
393
+ const body = await this.requestJson(this.workerUrl(dir, '/github/pull-request-status'), this.jsonInit('POST', { urls }));
394
+ return Array.isArray(body.results) ? body.results : [];
395
+ }
396
+ fetchPullRequestChanges(dir, url) {
397
+ return this.requestJson(this.workerUrl(dir, '/github/pull-request-changes'), this.jsonInit('POST', { url }));
398
+ }
399
+ async fetchBrowsers(dir, sessionId) {
400
+ const body = await this.requestJson(this.workerUrl(dir, `/sessions/${encodeURIComponent(sessionId)}/browser`));
401
+ return Array.isArray(body.browsers) ? body.browsers : [];
402
+ }
403
+ // ── Boards (ADR 143 / 146) ────────────────────────────────────────────────
404
+ async fetchBoards(dir) {
405
+ const body = await this.requestJson(this.workerUrl(dir, '/boards?archived=1'));
406
+ return Array.isArray(body.boards) ? body.boards : [];
407
+ }
408
+ fetchBoardDetail(dir, boardId, archivedCards = false) {
409
+ const q = archivedCards ? '?archivedCards=1' : '';
410
+ return this.requestJson(this.workerUrl(dir, `/boards/${encodeURIComponent(boardId)}${q}`));
411
+ }
412
+ fetchCardDetail(dir, boardId, cardId) {
413
+ return this.requestJson(this.workerUrl(dir, `/boards/${encodeURIComponent(boardId)}/cards/${encodeURIComponent(cardId)}`));
414
+ }
415
+ fetchBoardEvents(dir, boardId, cardId) {
416
+ const q = cardId ? `?cardId=${encodeURIComponent(cardId)}` : '';
417
+ return this.requestJson(this.workerUrl(dir, `/boards/${encodeURIComponent(boardId)}/events${q}`));
418
+ }
419
+ fetchBoardReactions(dir, boardId) {
420
+ return this.requestJson(this.workerUrl(dir, `/boards/${encodeURIComponent(boardId)}/reactions`));
421
+ }
422
+ postBoardOperation(dir, operation, requestId) {
423
+ return this.requestJson(this.workerUrl(dir, '/boards/ops'), this.jsonInit('POST', { operation, requestId }));
424
+ }
425
+ // ── Agent Notes (ADR 198) ─────────────────────────────────────────────────
426
+ fetchNotesList(dir, opts = {}) {
427
+ const params = new URLSearchParams({ sort: opts.sort ?? 'updated', offset: '0', limit: '100' });
428
+ if (opts.query?.trim())
429
+ params.set('q', opts.query.trim());
430
+ if (opts.view === 'pinned')
431
+ params.set('pinned', '1');
432
+ else if (opts.view === 'trash')
433
+ params.set('trashed', '1');
434
+ else if (opts.view === 'unfiled')
435
+ params.set('folderId', 'unfiled');
436
+ else if (opts.view && opts.view !== 'all')
437
+ params.set('folderId', opts.view);
438
+ return this.requestJson(this.workerUrl(dir, `/notes?${params.toString()}`));
439
+ }
440
+ async fetchNote(dir, noteId) {
441
+ const body = await this.requestJson(this.workerUrl(dir, `/notes/${encodeURIComponent(noteId)}`));
442
+ return body.note;
443
+ }
444
+ async fetchNoteVersions(dir, noteId) {
445
+ const body = await this.requestJson(this.workerUrl(dir, `/notes/${encodeURIComponent(noteId)}/versions`));
446
+ return Array.isArray(body.versions) ? body.versions : [];
447
+ }
448
+ async fetchNoteVersion(dir, noteId, revision) {
449
+ const body = await this.requestJson(this.workerUrl(dir, `/notes/${encodeURIComponent(noteId)}/versions/${revision}`));
450
+ return body.version;
451
+ }
452
+ postNoteOperation(dir, requestId, operation) {
453
+ return this.requestJson(this.workerUrl(dir, '/notes/ops'), this.jsonInit('POST', { requestId, operation }));
454
+ }
455
+ // ── Files & Skills (Gateway Control Plane) ────────────────────────────────
456
+ fetchAgentDirectoryTree(dir, path = '') {
457
+ const suffix = path ? `files/tree?path=${encodeURIComponent(path)}` : 'files/tree';
458
+ return this.requestJson(this.agentControlUrl(dir, suffix));
459
+ }
460
+ async readAgentTextFile(dir, path) {
461
+ const body = await this.requestJson(this.agentControlUrl(dir, `files/text/${encodePathSegments(path)}`));
462
+ if (body.encoding === 'utf-8') {
463
+ return { kind: 'text', content: body.content, mtimeMs: body.mtimeMs, sizeBytes: body.sizeBytes };
464
+ }
465
+ return { kind: body.encoding, mtimeMs: body.mtimeMs, sizeBytes: body.sizeBytes };
466
+ }
467
+ saveAgentTextFile(dir, path, content, ifMtimeMs) {
468
+ return this.requestJson(this.agentControlUrl(dir, `files/raw/${encodePathSegments(path)}`), this.jsonInit('PUT', { content, ifMtimeMs }));
469
+ }
470
+ createAgentPath(dir, path, kind) {
471
+ return this.requestJson(this.agentControlUrl(dir, `files/raw/${encodePathSegments(path)}?kind=${kind}`), { method: 'POST' });
472
+ }
473
+ deleteAgentPath(dir, path, recursive = false) {
474
+ return this.requestJson(this.agentControlUrl(dir, `files/raw/${encodePathSegments(path)}${recursive ? '?recursive=1' : ''}`), { method: 'DELETE' });
475
+ }
476
+ renameAgentPath(dir, path, newPath) {
477
+ return this.requestJson(this.agentControlUrl(dir, `files/raw/${encodePathSegments(path)}`), this.jsonInit('PATCH', { newPath }));
478
+ }
479
+ async fetchSkills(dir) {
480
+ const body = await this.requestJson(this.agentControlUrl(dir, 'skills'));
481
+ return Array.isArray(body.skills) ? body.skills : [];
482
+ }
483
+ createSkill(dir, skill) {
484
+ return this.requestJson(this.agentControlUrl(dir, 'skills'), this.jsonInit('POST', { skill }));
485
+ }
486
+ readSkillManifest(dir, skill) {
487
+ return this.requestJson(this.agentControlUrl(dir, `skills/${encodeURIComponent(skill)}`));
488
+ }
489
+ saveSkillManifest(dir, skill, content, ifMtimeMs) {
490
+ return this.requestJson(this.agentControlUrl(dir, `skills/${encodeURIComponent(skill)}`), this.jsonInit('PUT', { content, ifMtimeMs }));
491
+ }
492
+ deleteSkill(dir, skill) {
493
+ return this.requestJson(this.agentControlUrl(dir, `skills/${encodeURIComponent(skill)}`), { method: 'DELETE' });
494
+ }
495
+ async fetchSkillFiles(dir, skill) {
496
+ const body = await this.requestJson(this.agentControlUrl(dir, `skills/${encodeURIComponent(skill)}/files`));
497
+ return Array.isArray(body.files) ? body.files : [];
498
+ }
499
+ readSkillFile(dir, skill, subdir, name) {
500
+ return this.requestJson(this.agentControlUrl(dir, `skills/${encodeURIComponent(skill)}/files/${subdir}/${encodeURIComponent(name)}`));
501
+ }
502
+ // ── Memory ────────────────────────────────────────────────────────────────
503
+ fetchMemoryFiles(dir) {
504
+ return this.requestJson(this.workerUrl(dir, '/memory/files'));
505
+ }
506
+ fetchMemoryFile(dir, path) {
507
+ return this.requestJson(this.workerUrl(dir, `/memory/file?path=${encodeURIComponent(path)}`));
508
+ }
509
+ writeMemoryFile(dir, path, content, expectedHash) {
510
+ return this.requestJson(this.workerUrl(dir, `/memory/file?path=${encodeURIComponent(path)}`), this.jsonInit('PUT', expectedHash ? { content, expected_hash: expectedHash } : { content }));
511
+ }
512
+ deleteMemoryFile(dir, path, expectedHash) {
513
+ return this.requestJson(this.workerUrl(dir, `/memory/file?path=${encodeURIComponent(path)}`), this.jsonInit('DELETE', { expected_hash: expectedHash }));
514
+ }
515
+ async fetchBrainSnapshot(dir) {
516
+ const raw = await this.requestJson(this.workerUrl(dir, '/memory/brain'));
517
+ // Canonical worker v1 compact tuple format (packages/core/src/memory/graph/brain.ts)
518
+ if (raw && raw.version === 1 && Array.isArray(raw.entities) && Array.isArray(raw.types) && Array.isArray(raw.predicates)) {
519
+ const types = raw.types;
520
+ const predicates = raw.predicates;
521
+ const entityRows = raw.entities;
522
+ const edgeRows = Array.isArray(raw.edges) ? raw.edges : [];
523
+ const nodes = entityRows.map(([id, name, typeIdx, pinned, facts, degree]) => ({
524
+ id,
525
+ name,
526
+ type: types[typeIdx] ?? 'entity',
527
+ pinned: pinned === 1,
528
+ factCount: facts,
529
+ edgeCount: degree,
530
+ }));
531
+ // Sort pinned first, then highest degree/facts, then alphabetical
532
+ nodes.sort((a, b) => (a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1) || (b.edgeCount ?? 0) - (a.edgeCount ?? 0) || a.name.localeCompare(b.name));
533
+ const edges = edgeRows
534
+ .map(([srcIdx, dstIdx, predIdx]) => {
535
+ const src = entityRows[srcIdx]?.[0];
536
+ const dst = entityRows[dstIdx]?.[0];
537
+ if (!src || !dst)
538
+ return null;
539
+ return { src, dst, predicate: predicates[predIdx] ?? 'related_to' };
540
+ })
541
+ .filter((e) => e !== null);
542
+ return { nodes, edges };
543
+ }
544
+ // Fallback / fixture format `{ nodes, edges }`
545
+ return {
546
+ nodes: Array.isArray(raw?.nodes) ? raw.nodes : [],
547
+ edges: Array.isArray(raw?.edges) ? raw.edges : [],
548
+ generatedAt: typeof raw?.generatedAt === 'string' ? raw.generatedAt : undefined,
549
+ };
550
+ }
551
+ fetchEntityBrief(dir, entityId) {
552
+ return this.requestJson(this.workerUrl(dir, `/api/graph/entity/${encodeURIComponent(entityId)}`));
553
+ }
554
+ updateGraphEntity(dir, entityId, update) {
555
+ return this.requestJson(this.workerUrl(dir, `/api/graph/entity/${encodeURIComponent(entityId)}`), this.jsonInit('POST', update));
556
+ }
557
+ deleteGraphEntity(dir, entityId) {
558
+ return this.requestJson(this.workerUrl(dir, `/api/graph/entity/${encodeURIComponent(entityId)}`), { method: 'DELETE' });
559
+ }
560
+ closeGraphRow(dir, target, validTo) {
561
+ return this.requestJson(this.workerUrl(dir, '/api/graph/close'), this.jsonInit('POST', { ...target, validTo }));
562
+ }
563
+ async fetchMemorySubjects(dir) {
564
+ const body = await this.requestJson(this.workerUrl(dir, '/memory/subjects'));
565
+ return Array.isArray(body.subjects) ? body.subjects : [];
566
+ }
567
+ async fetchMemorySubject(dir, slug) {
568
+ const raw = await this.requestJson(this.workerUrl(dir, `/memory/subjects/${encodeURIComponent(slug)}`));
569
+ if (raw && typeof raw.subject === 'object' && raw.subject !== null) {
570
+ const sub = raw.subject;
571
+ return {
572
+ slug: typeof sub.slug === 'string' ? sub.slug : slug,
573
+ title: typeof sub.title === 'string' ? sub.title : slug,
574
+ content: typeof raw.content === 'string' ? raw.content : '',
575
+ status: typeof sub.status === 'string' ? sub.status : undefined,
576
+ version: typeof raw.version === 'number' ? raw.version : undefined,
577
+ updatedAt: typeof sub.updated === 'string' ? sub.updated : undefined,
578
+ conversations: Array.isArray(raw.conversations)
579
+ ? raw.conversations
580
+ : undefined,
581
+ };
582
+ }
583
+ return raw;
584
+ }
585
+ async fetchMemoryUpkeep(dir) {
586
+ const raw = await this.requestJson(this.workerUrl(dir, '/memory/upkeep'));
587
+ if (raw && typeof raw.passes === 'object' && raw.passes !== null) {
588
+ const passes = raw.passes;
589
+ const core = raw.coreMemory;
590
+ return {
591
+ enabled: raw.consolidationEnabled === true,
592
+ warnings: Array.isArray(raw.warnings) ? raw.warnings : [],
593
+ lastNightly: passes.nightly?.lastRun
594
+ ? { status: passes.nightly.lastRun.status, startedAt: passes.nightly.lastRun.startedAt, error: passes.nightly.lastRun.errorCode ?? null }
595
+ : null,
596
+ lastDeep: passes.deep?.lastRun
597
+ ? { status: passes.deep.lastRun.status, startedAt: passes.deep.lastRun.startedAt, error: passes.deep.lastRun.errorCode ?? null }
598
+ : null,
599
+ backlogCount: typeof raw.nightlyPendingMessages === 'number' ? raw.nightlyPendingMessages : 0,
600
+ coreMemoryBytes: typeof core?.chars === 'number' ? core.chars : undefined,
601
+ };
602
+ }
603
+ return raw;
604
+ }
605
+ async fetchMemoryMoments(dir, hours = 48) {
606
+ const body = await this.requestJson(this.workerUrl(dir, `/memory/moments?hours=${hours}`));
607
+ if (!Array.isArray(body.moments))
608
+ return [];
609
+ const whoMap = { consolidator: 'consolidation', agent: 'self-directed', dashboard: 'manual' };
610
+ return body.moments.map((m) => {
611
+ const id = typeof m.id === 'number' ? m.id : 0;
612
+ const kind = typeof m.kind === 'string' ? m.kind : undefined;
613
+ const createdAt = typeof m.createdAt === 'string' ? m.createdAt : typeof m.at === 'string' ? m.at : undefined;
614
+ const existingSummary = typeof m.summary === 'string' ? m.summary : undefined;
615
+ const who = typeof m.who === 'string' ? whoMap[m.who] ?? m.who : '';
616
+ const entityIds = Array.isArray(m.entityIds) ? m.entityIds : [];
617
+ const derived = existingSummary ??
618
+ (() => {
619
+ switch (kind) {
620
+ case 'fact_added':
621
+ return `learned about ${entityIds.length || 1} ${entityIds.length === 1 ? 'entity' : 'entities'}${who ? ` · ${who}` : ''}`;
622
+ case 'fact_reinforced':
623
+ return `reinforced a memory${who ? ` · ${who}` : ''}`;
624
+ case 'fact_closed':
625
+ case 'edge_closed':
626
+ return `let go of a memory${who ? ` · ${who}` : ''}`;
627
+ case 'entity_upsert':
628
+ return `updated its knowledge${who ? ` · ${who}` : ''}`;
629
+ case 'entity_merged':
630
+ return `merged duplicate memories${who ? ` · ${who}` : ''}`;
631
+ case 'pinned':
632
+ return `pinned a memory${who ? ` · ${who}` : ''}`;
633
+ case 'memory_md_changed':
634
+ return `revised its identity notes${who ? ` · ${who}` : ''}`;
635
+ case 'graph_changed':
636
+ return `reorganised its memory${who ? ` · ${who}` : ''}`;
637
+ default:
638
+ return `${kind ?? 'event'}${who ? ` · ${who}` : ''}`;
639
+ }
640
+ })();
641
+ return {
642
+ id,
643
+ kind,
644
+ summary: derived,
645
+ createdAt,
646
+ entityName: typeof m.entityName === 'string' ? m.entityName : undefined,
647
+ detail: typeof m.detail === 'string' ? m.detail : undefined,
648
+ };
649
+ });
650
+ }
651
+ searchMemory(dir, query) {
652
+ return this.requestJson(this.workerUrl(dir, `/memory/search?q=${encodeURIComponent(query)}&limit=30`));
653
+ }
654
+ async triggerConsolidation(dir, pass) {
655
+ const res = await this.rawFetch(this.workerUrl(dir, '/memory/consolidate'), this.jsonInit('POST', { pass }));
656
+ if (res.status === 202)
657
+ return 'Consolidation started.';
658
+ if (res.status === 409)
659
+ return 'Consolidation is already running.';
660
+ if (res.status === 503)
661
+ return 'Graph memory is not enabled for this agent.';
662
+ throw new ApiError(`Consolidation failed (HTTP ${res.status})`, res.status);
663
+ }
664
+ // ── Activity (Jobs, Logs, Stats) ──────────────────────────────────────────
665
+ async fetchJobRuns(dir, range = '24h', kind) {
666
+ const params = new URLSearchParams({ range, limit: '200' });
667
+ if (kind && kind !== 'all')
668
+ params.set('kind', kind);
669
+ const body = await this.requestJson(this.workerUrl(dir, `/jobs?${params.toString()}`));
670
+ return Array.isArray(body.rows) ? body.rows : [];
671
+ }
672
+ revertConsolidationRun(dir, runId) {
673
+ return this.requestJson(this.workerUrl(dir, '/api/graph/revert'), this.jsonInit('POST', { runId }));
674
+ }
675
+ async fetchAgentLogs(dir, opts = {}) {
676
+ const params = new URLSearchParams({ lines: String(opts.lines ?? 200) });
677
+ if (opts.cursor)
678
+ params.set('cursor', opts.cursor);
679
+ const body = await this.requestJson(this.workerUrl(dir, `/logs?${params.toString()}`));
680
+ return {
681
+ lines: Array.isArray(body.lines) ? body.lines : [],
682
+ cursor: typeof body.cursor === 'string' ? body.cursor : opts.cursor ?? '',
683
+ };
684
+ }
685
+ fetchAgentStats(dir, range = '7d') {
686
+ return this.requestJson(this.workerUrl(dir, `/stats?range=${range}`));
687
+ }
688
+ // ── Compute (ADR 126) ─────────────────────────────────────────────────────
689
+ fetchComputeSummary(agentDir) {
690
+ const q = agentDir ? `?agent=${encodeURIComponent(agentDir)}` : '';
691
+ return this.requestJson(`${this.origin()}/api/compute/summary${q}`);
692
+ }
693
+ fetchComputeNodes() {
694
+ return this.requestJson(`${this.origin()}/api/compute/nodes`);
695
+ }
696
+ fetchComputeWorkloads(query = {}) {
697
+ const params = new URLSearchParams();
698
+ if (query.limit)
699
+ params.set('limit', String(query.limit));
700
+ if (query.agentDir)
701
+ params.set('agent', query.agentDir);
702
+ if (query.state)
703
+ params.set('state', query.state);
704
+ if (query.sessionIncarnation !== undefined)
705
+ params.set('session', String(query.sessionIncarnation));
706
+ if (query.sessionNonce)
707
+ params.set('nonce', query.sessionNonce);
708
+ const s = params.toString();
709
+ return this.requestJson(`${this.origin()}/api/compute/workloads${s ? `?${s}` : ''}`);
710
+ }
711
+ fetchComputeWorkload(id) {
712
+ return this.requestJson(`${this.origin()}/api/compute/workloads/${id}`);
713
+ }
714
+ cancelComputeWorkload(id) {
715
+ return this.requestJson(`${this.origin()}/api/compute/workloads/${id}/cancel`, { method: 'POST' });
716
+ }
717
+ releaseComputeEnvironment(id) {
718
+ return this.requestJson(`${this.origin()}/api/compute/workloads/${id}/release`, { method: 'POST' });
719
+ }
720
+ disposeComputeOutputs(id) {
721
+ return this.requestJson(`${this.origin()}/api/compute/workloads/${id}/dispose-outputs`, this.jsonInit('POST', { confirm: true }));
722
+ }
723
+ async fetchComputeLogs(id, role = 'primary', service) {
724
+ const params = new URLSearchParams({ role });
725
+ if (service)
726
+ params.set('service', service);
727
+ const res = await this.rawFetch(`${this.origin()}/api/compute/workloads/${id}/logs?${params.toString()}`, {
728
+ headers: { Accept: 'text/plain' },
729
+ });
730
+ if (!res.ok)
731
+ throw new ApiError(`Logs unavailable (HTTP ${res.status})`, res.status);
732
+ return { text: await res.text(), truncated: res.headers.get('X-Smith-Log-Truncated') === '1' };
733
+ }
734
+ computeNodeAction(id, action, body) {
735
+ return this.requestJson(`${this.origin()}/api/compute/nodes/${id}/${action}`, body !== undefined ? this.jsonInit('POST', body) : { method: 'POST' });
736
+ }
737
+ // ── Settings: Config, Prompt, Credentials, Pi Engine, People, Users, Storage ─
738
+ fetchAgentConfig(dir) {
739
+ return this.requestJson(this.agentControlUrl(dir, 'config'));
740
+ }
741
+ saveAgentConfig(dir, payload) {
742
+ return this.requestJson(this.agentControlUrl(dir, 'config'), this.jsonInit('POST', payload));
743
+ }
744
+ fetchPromptCompose(dir, surface = 'tui') {
745
+ return this.requestJson(this.agentControlUrl(dir, `prompt?surface=${encodeURIComponent(surface)}`));
746
+ }
747
+ async fetchAgentCredentials(dir, withUsage = false) {
748
+ const body = await this.requestJson(this.agentControlUrl(dir, `credentials${withUsage ? '?usage=1' : ''}`));
749
+ return Array.isArray(body.credentials) ? body.credentials : [];
750
+ }
751
+ fetchPiEngine(dir) {
752
+ return this.requestJson(this.workerUrl(dir, '/pi/engine'));
753
+ }
754
+ reconcilePiProfiles(dir) {
755
+ return this.requestJson(this.workerUrl(dir, '/pi/profiles/reconcile'), { method: 'POST' });
756
+ }
757
+ async listAgentMembers(dir) {
758
+ const body = await this.requestJson(this.agentControlUrl(dir, 'members'));
759
+ return Array.isArray(body.members) ? body.members : [];
760
+ }
761
+ addAgentMember(dir, email, role) {
762
+ return this.requestJson(this.agentControlUrl(dir, 'members'), this.jsonInit('POST', { email, role }));
763
+ }
764
+ setAgentMemberRole(dir, userId, role) {
765
+ return this.requestJson(this.agentControlUrl(dir, `members/${userId}`), this.jsonInit('PATCH', { role }));
766
+ }
767
+ removeAgentMember(dir, userId) {
768
+ return this.requestJson(this.agentControlUrl(dir, `members/${userId}`), { method: 'DELETE' });
769
+ }
770
+ async listUsers() {
771
+ const body = await this.requestJson(`${this.origin()}/api/users`);
772
+ return Array.isArray(body.users) ? body.users : [];
773
+ }
774
+ createUser(input) {
775
+ return this.requestJson(`${this.origin()}/api/users`, this.jsonInit('POST', input));
776
+ }
777
+ patchUser(userId, patch) {
778
+ return this.requestJson(`${this.origin()}/api/users/${userId}`, this.jsonInit('PATCH', patch));
779
+ }
780
+ issuePasswordReset(userId) {
781
+ return this.requestJson(`${this.origin()}/api/users/${userId}/reset`, { method: 'POST' });
782
+ }
783
+ fetchAgentStorage(dir) {
784
+ return this.requestJson(this.agentControlUrl(dir, 'storage'));
785
+ }
786
+ requestStorageScan(dir) {
787
+ return this.requestJson(this.agentControlUrl(dir, 'storage/scan'), this.jsonInit('POST', {}));
788
+ }
789
+ fetchStorageTree(dir, root, path = '') {
790
+ const params = new URLSearchParams({ root });
791
+ if (path)
792
+ params.set('path', path);
793
+ return this.requestJson(this.agentControlUrl(dir, `storage/tree?${params.toString()}`));
794
+ }
795
+ }
796
+ //# sourceMappingURL=http.js.map