dsh-plugin-agentdeck 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.
package/lib/index.js ADDED
@@ -0,0 +1,366 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import {
4
+ AWAKE_MODES,
5
+ controlAgentDeckDaemon,
6
+ getAgentDeckStatus,
7
+ runAgentDeckSetup,
8
+ setAgentDeckAwake,
9
+ syncAgentDeckModels,
10
+ } from './setup.js';
11
+
12
+ export const name = 'agentdeck';
13
+ export const inject = ['webServer'];
14
+
15
+ const STATUS_PATH = '/api/agentdeck/status';
16
+ const SETUP_PATH = '/api/agentdeck/setup';
17
+ const DAEMON_PATH = '/api/agentdeck/daemon';
18
+ const AWAKE_PATH = '/api/agentdeck/awake';
19
+ const SYNC_MODELS_PATH = '/api/agentdeck/sync-models';
20
+ const MAX_BODY_BYTES = 16 * 1024;
21
+
22
+ function sendJson(res, statusCode, payload) {
23
+ const body = JSON.stringify(payload);
24
+ res.statusCode = statusCode;
25
+ res.setHeader('content-type', 'application/json; charset=utf-8');
26
+ res.setHeader('cache-control', 'no-store');
27
+ res.end(body);
28
+ }
29
+
30
+ function sendMethodNotAllowed(res, allow) {
31
+ res.statusCode = 405;
32
+ res.setHeader('allow', allow);
33
+ res.setHeader('cache-control', 'no-store');
34
+ res.end();
35
+ }
36
+
37
+ function readBoundedBody(req, maxBytes = MAX_BODY_BYTES) {
38
+ return new Promise((resolve, reject) => {
39
+ const chunks = [];
40
+ let size = 0;
41
+ let exceeded = false;
42
+ req.on('data', (chunk) => {
43
+ size += chunk.length;
44
+ if (size > maxBytes) {
45
+ exceeded = true;
46
+ return;
47
+ }
48
+ chunks.push(chunk);
49
+ });
50
+ req.on('end', () => {
51
+ if (exceeded) {
52
+ resolve(null);
53
+ return;
54
+ }
55
+ resolve(Buffer.concat(chunks).toString('utf8'));
56
+ });
57
+ req.on('error', reject);
58
+ });
59
+ }
60
+
61
+ async function parseJsonRequest(req, res) {
62
+ const contentType = String(req.headers['content-type'] || '')
63
+ .split(';', 1)[0]
64
+ .trim()
65
+ .toLowerCase();
66
+ if (contentType !== 'application/json') {
67
+ sendJson(res, 415, {
68
+ ok: false,
69
+ error: 'content-type must be application/json',
70
+ });
71
+ return null;
72
+ }
73
+
74
+ let rawBody = '';
75
+ try {
76
+ rawBody = await readBoundedBody(req);
77
+ } catch {
78
+ sendJson(res, 400, { ok: false, error: 'request body unreadable' });
79
+ return null;
80
+ }
81
+ if (rawBody === null) {
82
+ sendJson(res, 413, { ok: false, error: 'request body too large' });
83
+ return null;
84
+ }
85
+
86
+ if (!rawBody.trim()) return {};
87
+ try {
88
+ return JSON.parse(rawBody);
89
+ } catch {
90
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
91
+ return null;
92
+ }
93
+ }
94
+
95
+ function getProfileInfo(ctx) {
96
+ const profile = ctx.get?.('profileContext');
97
+ const dshHome =
98
+ profile?.home || process.env.DSH_HOME || join(homedir(), '.dsh');
99
+ const profileName = profile?.name || 'web';
100
+ const sourcePatchPath =
101
+ profile?.patchPath ||
102
+ join(dshHome, 'profiles', profileName, 'cordis.patch.yml');
103
+ const packageManager = profile?.packageManager || null;
104
+ return { dshHome, profileName, sourcePatchPath, packageManager };
105
+ }
106
+
107
+ export function apply(ctx) {
108
+ let opInFlight = null;
109
+ let disposed = false;
110
+ let provisioning = { state: 'idle', error: null };
111
+
112
+ const startAutoProvision = ({ forceStartDaemon = false } = {}) => {
113
+ if (opInFlight || disposed) return opInFlight;
114
+ const info = getProfileInfo(ctx);
115
+ provisioning = { state: 'running', error: null };
116
+ const task = (async () => {
117
+ try {
118
+ const current = await getAgentDeckStatus(info);
119
+ const needsSetup =
120
+ !current.acpPlugin.installed ||
121
+ !current.customAgent.configured ||
122
+ current.models.acpNeedsProviderPin ||
123
+ !current.daemon.installed ||
124
+ (!current.daemon.running &&
125
+ (forceStartDaemon || !current.daemon.pairedReady));
126
+ if (!needsSetup || disposed) {
127
+ provisioning = { state: 'idle', error: null };
128
+ return { ok: true, status: current };
129
+ }
130
+ const result = await runAgentDeckSetup({
131
+ ...info,
132
+ syncModels: false,
133
+ startDaemon: forceStartDaemon || !current.daemon.pairedReady || !current.customAgent.configured,
134
+ });
135
+ provisioning = { state: 'idle', error: null };
136
+ return result;
137
+ } catch (err) {
138
+ const message = err instanceof Error ? err.message : String(err);
139
+ provisioning = { state: 'error', error: message };
140
+ throw err;
141
+ } finally {
142
+ if (opInFlight === task) opInFlight = null;
143
+ }
144
+ })();
145
+ opInFlight = task;
146
+ return task;
147
+ };
148
+
149
+ // Automatically provision ACP, custom_agents.json, and agentdeckd in the
150
+ // background when the plugin activates so the QR code is ready without clicks.
151
+ ctx.effect(() => {
152
+ disposed = false;
153
+ startAutoProvision().catch(() => {
154
+ // Error is captured in `provisioning` and surfaced in the Settings UI
155
+ });
156
+ return () => {
157
+ disposed = true;
158
+ };
159
+ }, 'agentdeck: auto-provision');
160
+
161
+ const isRejected = (req, res) => {
162
+ const connection = ctx.get?.('connection') ?? Reflect.get(ctx, 'connection');
163
+ const rejection = connection?.requestRejection?.(req);
164
+ if (rejection === undefined) return false;
165
+ res.statusCode = rejection;
166
+ res.end();
167
+ return true;
168
+ };
169
+
170
+ const buildStatusPayload = async () => {
171
+ const info = getProfileInfo(ctx);
172
+ const status = await getAgentDeckStatus(info);
173
+ return { ...status, provisioning };
174
+ };
175
+
176
+ ctx.effect(
177
+ () =>
178
+ ctx.webServer.register({
179
+ kind: 'exact',
180
+ path: STATUS_PATH,
181
+ handler: async (req, res) => {
182
+ if (isRejected(req, res)) return;
183
+ if (req.method !== 'GET') {
184
+ sendMethodNotAllowed(res, 'GET');
185
+ return;
186
+ }
187
+ try {
188
+ sendJson(res, 200, await buildStatusPayload());
189
+ } catch (err) {
190
+ sendJson(res, 500, {
191
+ ok: false,
192
+ error: err instanceof Error ? err.message : String(err),
193
+ });
194
+ }
195
+ },
196
+ }),
197
+ `agentdeck: GET ${STATUS_PATH}`,
198
+ );
199
+
200
+ // Retry/repair endpoint if auto-provisioning failed or user wants to re-run
201
+ ctx.effect(
202
+ () =>
203
+ ctx.webServer.register({
204
+ kind: 'exact',
205
+ path: SETUP_PATH,
206
+ handler: async (req, res) => {
207
+ if (isRejected(req, res)) return;
208
+ if (req.method !== 'POST') {
209
+ sendMethodNotAllowed(res, 'POST');
210
+ return;
211
+ }
212
+ const parsed = await parseJsonRequest(req, res);
213
+ if (parsed === null) return;
214
+
215
+ if (opInFlight) {
216
+ sendJson(res, 202, {
217
+ ok: true,
218
+ status: await buildStatusPayload(),
219
+ });
220
+ return;
221
+ }
222
+
223
+ try {
224
+ const result = await startAutoProvision({ forceStartDaemon: true });
225
+ sendJson(res, 200, {
226
+ ok: true,
227
+ status: { ...result.status, provisioning },
228
+ });
229
+ } catch (err) {
230
+ sendJson(res, 500, {
231
+ ok: false,
232
+ error: err instanceof Error ? err.message : String(err),
233
+ status: await buildStatusPayload(),
234
+ });
235
+ }
236
+ },
237
+ }),
238
+ `agentdeck: POST ${SETUP_PATH}`,
239
+ );
240
+
241
+ ctx.effect(
242
+ () =>
243
+ ctx.webServer.register({
244
+ kind: 'exact',
245
+ path: DAEMON_PATH,
246
+ handler: async (req, res) => {
247
+ if (isRejected(req, res)) return;
248
+ if (req.method !== 'POST') {
249
+ sendMethodNotAllowed(res, 'POST');
250
+ return;
251
+ }
252
+ const parsed = await parseJsonRequest(req, res);
253
+ if (parsed === null) return;
254
+
255
+ const action = parsed?.action;
256
+ if (!['start', 'stop', 'restart'].includes(action)) {
257
+ sendJson(res, 400, {
258
+ ok: false,
259
+ error: 'action must be "start", "stop", or "restart"',
260
+ });
261
+ return;
262
+ }
263
+
264
+ if (opInFlight) {
265
+ sendJson(res, 409, {
266
+ ok: false,
267
+ error: 'Another AgentDeck operation is already in progress',
268
+ });
269
+ return;
270
+ }
271
+
272
+ const info = getProfileInfo(ctx);
273
+ const task = controlAgentDeckDaemon({ ...info, action });
274
+ opInFlight = task;
275
+ try {
276
+ const result = await task;
277
+ sendJson(res, 200, {
278
+ ok: true,
279
+ status: { ...result.status, provisioning },
280
+ });
281
+ } catch (err) {
282
+ sendJson(res, 500, {
283
+ ok: false,
284
+ error: err instanceof Error ? err.message : String(err),
285
+ });
286
+ } finally {
287
+ if (opInFlight === task) opInFlight = null;
288
+ }
289
+ },
290
+ }),
291
+ `agentdeck: POST ${DAEMON_PATH}`,
292
+ );
293
+
294
+ ctx.effect(
295
+ () =>
296
+ ctx.webServer.register({
297
+ kind: 'exact',
298
+ path: AWAKE_PATH,
299
+ handler: async (req, res) => {
300
+ if (isRejected(req, res)) return;
301
+ if (req.method !== 'POST') {
302
+ sendMethodNotAllowed(res, 'POST');
303
+ return;
304
+ }
305
+ const parsed = await parseJsonRequest(req, res);
306
+ if (parsed === null) return;
307
+
308
+ const mode = parsed?.mode;
309
+ if (!AWAKE_MODES.includes(mode)) {
310
+ sendJson(res, 400, {
311
+ ok: false,
312
+ error: `mode must be one of: ${AWAKE_MODES.join(', ')}`,
313
+ });
314
+ return;
315
+ }
316
+
317
+ try {
318
+ const info = getProfileInfo(ctx);
319
+ const result = await setAgentDeckAwake({ ...info, mode });
320
+ sendJson(res, 200, {
321
+ ok: true,
322
+ status: { ...result.status, provisioning },
323
+ });
324
+ } catch (err) {
325
+ sendJson(res, 500, {
326
+ ok: false,
327
+ error: err instanceof Error ? err.message : String(err),
328
+ });
329
+ }
330
+ },
331
+ }),
332
+ `agentdeck: POST ${AWAKE_PATH}`,
333
+ );
334
+
335
+ ctx.effect(
336
+ () =>
337
+ ctx.webServer.register({
338
+ kind: 'exact',
339
+ path: SYNC_MODELS_PATH,
340
+ handler: async (req, res) => {
341
+ if (isRejected(req, res)) return;
342
+ if (req.method !== 'POST') {
343
+ sendMethodNotAllowed(res, 'POST');
344
+ return;
345
+ }
346
+ const parsed = await parseJsonRequest(req, res);
347
+ if (parsed === null) return;
348
+
349
+ try {
350
+ const info = getProfileInfo(ctx);
351
+ const result = await syncAgentDeckModels(info);
352
+ sendJson(res, 200, {
353
+ ok: true,
354
+ status: { ...result.status, provisioning },
355
+ });
356
+ } catch (err) {
357
+ sendJson(res, 500, {
358
+ ok: false,
359
+ error: err instanceof Error ? err.message : String(err),
360
+ });
361
+ }
362
+ },
363
+ }),
364
+ `agentdeck: POST ${SYNC_MODELS_PATH}`,
365
+ );
366
+ }