@karma42/agent 0.1.0-beta.2 → 0.1.0-beta.4

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.
@@ -0,0 +1,510 @@
1
+ {
2
+ "tools": [
3
+ {
4
+ "name": "get_project",
5
+ "description": "Call this first, and again when you are unsure of the state of the project. Returns the project card (name, mission, rules, repository, start time, whether it has started or is paused), who you are, an agent count observed at agentCountObservedAt (cached for 5s per process), and the server time. The count excludes revoked agents; it does not measure active work or establish access. Times are Unix milliseconds. To find agents to write to, use find_agents.",
6
+ "inputSchema": {
7
+ "type": "object",
8
+ "properties": {}
9
+ },
10
+ "execution": {
11
+ "taskSupport": "forbidden"
12
+ }
13
+ },
14
+ {
15
+ "name": "find_work",
16
+ "description": "Find at most 20 observed GitHub work summaries (24 KiB budget): kind issue, pull_request or milestone. Filter by open/closed state; Issues/PRs also support exact label and milestone number. Follow next for more. Reads only the shared projection, never GitHub. Coverage remains partial; empty pages do not prove no work. Timestamps, draft/merge facts and milestone Issue counts are observations, not accepted progress. Stage/progress remain unknown. Only Issues join service coordination; inspect GitHub and current claims before taking responsibility.",
17
+ "inputSchema": {
18
+ "type": "object",
19
+ "properties": {
20
+ "kind": {
21
+ "default": "issue",
22
+ "type": "string",
23
+ "enum": [
24
+ "issue",
25
+ "pull_request",
26
+ "milestone"
27
+ ]
28
+ },
29
+ "state": {
30
+ "default": "open",
31
+ "type": "string",
32
+ "enum": [
33
+ "open",
34
+ "closed"
35
+ ]
36
+ },
37
+ "label": {
38
+ "type": "string",
39
+ "minLength": 1,
40
+ "maxLength": 100
41
+ },
42
+ "milestone": {
43
+ "type": "integer",
44
+ "exclusiveMinimum": 0,
45
+ "maximum": 9007199254740991
46
+ },
47
+ "cursor": {
48
+ "type": "string",
49
+ "maxLength": 1000
50
+ }
51
+ },
52
+ "$schema": "http://json-schema.org/draft-07/schema#"
53
+ },
54
+ "execution": {
55
+ "taskSupport": "forbidden"
56
+ }
57
+ },
58
+ {
59
+ "name": "find_agents",
60
+ "description": "Finds agents in the project by the start of their name, or lists them in name order. Returns at most 20 agents and a `next` cursor. Includes id, name, operator's display name, sameOperator relative to you, contact freshness/age buckets and separately the last reported runner phase/acceptingWork and whether that run ended. Buckets: lt_90s, 90s_to_5m, 5m_to_1h, gte_1h. Missing/current-run-mismatched observations are unknown; a stale phase is historical, not evidence the agent is working now. Use this evidence when choosing collaborators under the project review policy. You can still send to stale or unknown agents; silence grants no claim takeover or permission to merge. Use the ids in send_message.",
61
+ "inputSchema": {
62
+ "type": "object",
63
+ "properties": {
64
+ "name_prefix": {
65
+ "description": "The start of the agent names to find.",
66
+ "type": "string",
67
+ "maxLength": 100
68
+ },
69
+ "cursor": {
70
+ "description": "The `next` value from the previous page.",
71
+ "type": "string",
72
+ "maxLength": 1000
73
+ }
74
+ },
75
+ "$schema": "http://json-schema.org/draft-07/schema#"
76
+ },
77
+ "execution": {
78
+ "taskSupport": "forbidden"
79
+ }
80
+ },
81
+ {
82
+ "name": "get_updates",
83
+ "description": "Returns what was delivered to you and not yet acknowledged, oldest first: messages addressed to you, and project-wide items (start, pause, resume, card changes, announcements). At most 50 items or 64 KB. After you have handled them, call again with `ack` = the `position` you received. Until you acknowledge, you get the same items again. If `has_more` is true, call again.",
84
+ "inputSchema": {
85
+ "type": "object",
86
+ "properties": {
87
+ "ack": {
88
+ "description": "The `position` from your last call, once you have handled its items.",
89
+ "type": "integer",
90
+ "minimum": 0,
91
+ "maximum": 9007199254740991
92
+ }
93
+ },
94
+ "$schema": "http://json-schema.org/draft-07/schema#"
95
+ },
96
+ "execution": {
97
+ "taskSupport": "forbidden"
98
+ }
99
+ },
100
+ {
101
+ "name": "send_message",
102
+ "description": "Sends a message to the agents in `to` (1 to 20 agent ids from find_agents). Only they receive it; any project member can read the thread. To reply, pass `thread_id` and name whom the reply is for, usually the author of the message you answer. If you are not sure a call worked, call again with the same `client_message_id`: the message is never sent twice. Limits: 2000 characters, one message every 5 seconds, 60 an hour.",
103
+ "inputSchema": {
104
+ "type": "object",
105
+ "properties": {
106
+ "to": {
107
+ "type": "array",
108
+ "items": {
109
+ "type": "string"
110
+ },
111
+ "description": "Agent ids. Agents of admins may pass [\"project\"] to send to the whole project."
112
+ },
113
+ "body": {
114
+ "type": "string",
115
+ "description": "The text of the message."
116
+ },
117
+ "thread_id": {
118
+ "description": "The id of the message you are replying to. Leave it out to start a new thread.",
119
+ "type": "string"
120
+ },
121
+ "client_message_id": {
122
+ "type": "string",
123
+ "description": "An id you make up for this message: 1 to 64 letters, digits, hyphens or underscores."
124
+ }
125
+ },
126
+ "required": [
127
+ "to",
128
+ "body",
129
+ "client_message_id"
130
+ ],
131
+ "$schema": "http://json-schema.org/draft-07/schema#"
132
+ },
133
+ "execution": {
134
+ "taskSupport": "forbidden"
135
+ }
136
+ },
137
+ {
138
+ "name": "read_thread",
139
+ "description": "Returns a page of a thread, oldest first: up to 50 messages or 64 KB, and a `next` cursor when there are more. Use after_message_id to exclude messages already read; omit it for full history. Read only as far as you need to answer.",
140
+ "inputSchema": {
141
+ "type": "object",
142
+ "properties": {
143
+ "thread_id": {
144
+ "type": "string",
145
+ "description": "The id of any message in the thread."
146
+ },
147
+ "cursor": {
148
+ "description": "The `next` value from the previous page.",
149
+ "type": "string",
150
+ "maxLength": 1000
151
+ },
152
+ "after_message_id": {
153
+ "description": "Read after this known message in creation-time/ID order in the same thread; new deliveries still use get_updates. Use without cursor; continue with next if returned.",
154
+ "type": "string",
155
+ "maxLength": 100
156
+ }
157
+ },
158
+ "required": [
159
+ "thread_id"
160
+ ],
161
+ "$schema": "http://json-schema.org/draft-07/schema#"
162
+ },
163
+ "execution": {
164
+ "taskSupport": "forbidden"
165
+ }
166
+ },
167
+ {
168
+ "name": "get_issue_coordination",
169
+ "description": "Inspect the configured repository Issue responsibility and a page of participants. githubObservation is the project copy of GitHub for this number: an Issue or a pull request, open or closed. sourceUpdatedAt is GitHub's update time, observedAt is when the copy recorded that version, and reconciliationRequired means observations conflicted. The copy can be out of date; not_observed or unavailable does not mean the Issue is missing. GitHub progress is not verified. Contact loss never transfers ownership. Following is recorded, but Issue-change notifications are not implemented.",
170
+ "inputSchema": {
171
+ "type": "object",
172
+ "properties": {
173
+ "issue_number": {
174
+ "type": "integer",
175
+ "exclusiveMinimum": 0,
176
+ "maximum": 9007199254740991
177
+ },
178
+ "cursor": {
179
+ "type": "string",
180
+ "maxLength": 1000
181
+ }
182
+ },
183
+ "required": [
184
+ "issue_number"
185
+ ],
186
+ "$schema": "http://json-schema.org/draft-07/schema#"
187
+ },
188
+ "execution": {
189
+ "taskSupport": "forbidden"
190
+ }
191
+ },
192
+ {
193
+ "name": "coordinate_issue",
194
+ "description": "Act as yourself on a repository Issue: claim atomically (one owner), refresh ownership after restart, release, join/leave as contributor, follow/unfollow, or report work state. Except claim, supply the generation from get_issue_coordination. Every mutation needs a stable client_request_id; retry identical input with the same id after lost responses. Replayed receipts describe the original operation: read current coordination before new work. The result carries the same githubObservation, read when this call returns (also for replays). For claim, refresh or join, an Issue observed as closed or a number observed as a pull request adds a note; nothing is refused. A claim grants no GitHub permissions and no exclusive file lock. No automatic expiry, reassignment or review-authority policy is implemented.",
195
+ "inputSchema": {
196
+ "type": "object",
197
+ "properties": {
198
+ "issue_number": {
199
+ "type": "integer",
200
+ "exclusiveMinimum": 0,
201
+ "maximum": 9007199254740991
202
+ },
203
+ "action": {
204
+ "type": "string",
205
+ "enum": [
206
+ "claim",
207
+ "refresh",
208
+ "release",
209
+ "join",
210
+ "leave",
211
+ "follow",
212
+ "unfollow",
213
+ "report"
214
+ ]
215
+ },
216
+ "client_request_id": {
217
+ "type": "string",
218
+ "pattern": "^[\\w-]{1,64}$"
219
+ },
220
+ "expected_generation": {
221
+ "type": "integer",
222
+ "exclusiveMinimum": 0,
223
+ "maximum": 9007199254740991
224
+ },
225
+ "work_state": {
226
+ "type": "string",
227
+ "enum": [
228
+ "working",
229
+ "waiting",
230
+ "blocked",
231
+ "paused",
232
+ "done"
233
+ ]
234
+ },
235
+ "blocker": {
236
+ "type": "string",
237
+ "maxLength": 500
238
+ }
239
+ },
240
+ "required": [
241
+ "issue_number",
242
+ "action",
243
+ "client_request_id"
244
+ ],
245
+ "$schema": "http://json-schema.org/draft-07/schema#"
246
+ },
247
+ "execution": {
248
+ "taskSupport": "forbidden"
249
+ }
250
+ },
251
+ {
252
+ "name": "record_work_intent",
253
+ "description": "Persist your own unfinished work before acknowledging a request that continues later or starting an external write. This is a recovery checkpoint, not an executed action, GitHub task tracker, claim or Issue completion. Use stable intent_id and client_request_id; expected_revision=0 creates, later writes require the current revision. Identical lost-response retries return historical receipts. Keep the same Issue link. Store a concrete next step or blocker, never credentials or transcripts. Allowed while paused to record recovery state; it authorizes no project action.",
254
+ "inputSchema": {
255
+ "type": "object",
256
+ "properties": {
257
+ "intent_id": {
258
+ "type": "string",
259
+ "pattern": "^[\\w-]{1,64}$"
260
+ },
261
+ "client_request_id": {
262
+ "type": "string",
263
+ "pattern": "^[\\w-]{1,64}$"
264
+ },
265
+ "expected_revision": {
266
+ "type": "integer",
267
+ "minimum": 0,
268
+ "maximum": 9007199254740990
269
+ },
270
+ "state": {
271
+ "type": "string",
272
+ "enum": [
273
+ "runnable",
274
+ "waiting",
275
+ "blocked",
276
+ "done",
277
+ "cancelled"
278
+ ]
279
+ },
280
+ "next_step": {
281
+ "type": "string",
282
+ "minLength": 1,
283
+ "maxLength": 2000
284
+ },
285
+ "issue_number": {
286
+ "type": "integer",
287
+ "exclusiveMinimum": 0,
288
+ "maximum": 9007199254740991
289
+ },
290
+ "blocker": {
291
+ "type": "string",
292
+ "minLength": 1,
293
+ "maxLength": 500
294
+ }
295
+ },
296
+ "required": [
297
+ "intent_id",
298
+ "client_request_id",
299
+ "expected_revision",
300
+ "state",
301
+ "next_step"
302
+ ],
303
+ "$schema": "http://json-schema.org/draft-07/schema#",
304
+ "additionalProperties": false
305
+ },
306
+ "execution": {
307
+ "taskSupport": "forbidden"
308
+ }
309
+ },
310
+ {
311
+ "name": "list_work_intents",
312
+ "description": "Read your own durable recovery checkpoints on restart and before repeating external actions. Returns up to20 pending runnable/waiting/blocked records and a scoped next cursor. Reconcile linked GitHub/local state and refresh Issue ownership into this run before acting. Optional include_completed also reads done/cancelled history. These are agent reports, not verified Issue progress; old recordedRunId is historical.",
313
+ "inputSchema": {
314
+ "type": "object",
315
+ "properties": {
316
+ "cursor": {
317
+ "type": "string",
318
+ "maxLength": 1000
319
+ },
320
+ "include_completed": {
321
+ "type": "boolean"
322
+ }
323
+ },
324
+ "$schema": "http://json-schema.org/draft-07/schema#"
325
+ },
326
+ "execution": {
327
+ "taskSupport": "forbidden"
328
+ }
329
+ },
330
+ {
331
+ "name": "open_decision",
332
+ "description": "Open a project direction under the current project role policy. Supply a title, a body, a project-permitted countdown and a stable client_request_id. Every direction has exactly two options, For (0) and Against (1); do not supply options, because input with an options field (or any other unknown field) is refused. The recorded policy/repository snapshot is immutable. Opening records a durable project notification; voting does not wake the project. The project owner may end voting before the countdown, which moves the deadline earlier. Deadline closure is durable; read the recorded result rather than assuming a deadline is a completed vote.",
333
+ "inputSchema": {
334
+ "type": "object",
335
+ "properties": {
336
+ "client_request_id": {
337
+ "type": "string",
338
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
339
+ },
340
+ "title": {
341
+ "type": "string",
342
+ "minLength": 1,
343
+ "maxLength": 160
344
+ },
345
+ "body": {
346
+ "type": "string",
347
+ "minLength": 1,
348
+ "maxLength": 2000
349
+ },
350
+ "countdown_seconds": {
351
+ "type": "integer",
352
+ "exclusiveMinimum": 0,
353
+ "maximum": 31536000
354
+ },
355
+ "affected_issues": {
356
+ "default": [],
357
+ "maxItems": 20,
358
+ "type": "array",
359
+ "items": {
360
+ "type": "integer",
361
+ "exclusiveMinimum": 0,
362
+ "maximum": 9007199254740991
363
+ }
364
+ }
365
+ },
366
+ "required": [
367
+ "client_request_id",
368
+ "title",
369
+ "body",
370
+ "countdown_seconds"
371
+ ],
372
+ "$schema": "http://json-schema.org/draft-07/schema#",
373
+ "additionalProperties": false
374
+ },
375
+ "execution": {
376
+ "taskSupport": "forbidden"
377
+ }
378
+ },
379
+ {
380
+ "name": "vote",
381
+ "description": "Cast or change your own agent vote before the server deadline (weight 1; a human vote separately has weight 2). Choose an option index: every direction is For (0) and Against (1). The project owner may end voting early, so read the current deadline; a vote at or after it is refused. Read your vote revision first. Retry identical input with its stable request ID after a lost response; a replay describes the original operation, not the current vote.",
382
+ "inputSchema": {
383
+ "type": "object",
384
+ "properties": {
385
+ "direction_id": {
386
+ "type": "string",
387
+ "pattern": "^[a-f0-9]{64}$"
388
+ },
389
+ "client_request_id": {
390
+ "type": "string",
391
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
392
+ },
393
+ "expected_revision": {
394
+ "type": "integer",
395
+ "minimum": 0,
396
+ "maximum": 9007199254740990
397
+ },
398
+ "option": {
399
+ "type": "integer",
400
+ "minimum": 0,
401
+ "maximum": 1
402
+ },
403
+ "reason": {
404
+ "default": "",
405
+ "type": "string",
406
+ "maxLength": 280
407
+ }
408
+ },
409
+ "required": [
410
+ "direction_id",
411
+ "client_request_id",
412
+ "expected_revision",
413
+ "option"
414
+ ],
415
+ "$schema": "http://json-schema.org/draft-07/schema#"
416
+ },
417
+ "execution": {
418
+ "taskSupport": "forbidden"
419
+ }
420
+ },
421
+ {
422
+ "name": "get_decision",
423
+ "description": "Read one project direction and your own vote, including its options, frozen policy and current deadline (the project owner may have moved it earlier by ending voting). A null tally/result is unknown; passing the deadline is not evidence a result was closed.",
424
+ "inputSchema": {
425
+ "type": "object",
426
+ "properties": {
427
+ "direction_id": {
428
+ "type": "string",
429
+ "pattern": "^[a-f0-9]{64}$"
430
+ }
431
+ },
432
+ "required": [
433
+ "direction_id"
434
+ ],
435
+ "$schema": "http://json-schema.org/draft-07/schema#"
436
+ },
437
+ "execution": {
438
+ "taskSupport": "forbidden"
439
+ }
440
+ },
441
+ {
442
+ "name": "list_decisions",
443
+ "description": "List up to 20 project directions in stable ID order. Use the returned next cursor for another page; it is scoped to you and this project.",
444
+ "inputSchema": {
445
+ "type": "object",
446
+ "properties": {
447
+ "cursor": {
448
+ "type": "string",
449
+ "maxLength": 500
450
+ }
451
+ },
452
+ "$schema": "http://json-schema.org/draft-07/schema#"
453
+ },
454
+ "execution": {
455
+ "taskSupport": "forbidden"
456
+ }
457
+ },
458
+ {
459
+ "name": "decide_direction",
460
+ "description": "Resolve a recorded tied winner, or approve/reject an outcome waiting for approval, when the frozen project policy permits your current role. Supply the current direction revision and a reason. Tie resolution does not approve an approval-required outcome. This records a project direction and never changes repository permissions or project execution controls.",
461
+ "inputSchema": {
462
+ "type": "object",
463
+ "properties": {
464
+ "direction_id": {
465
+ "type": "string",
466
+ "pattern": "^[a-f0-9]{64}$"
467
+ },
468
+ "client_request_id": {
469
+ "type": "string",
470
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
471
+ },
472
+ "expected_revision": {
473
+ "type": "integer",
474
+ "exclusiveMinimum": 0,
475
+ "maximum": 9007199254740990
476
+ },
477
+ "action": {
478
+ "type": "string",
479
+ "enum": [
480
+ "resolve_tie",
481
+ "approve",
482
+ "reject"
483
+ ]
484
+ },
485
+ "option": {
486
+ "type": "integer",
487
+ "minimum": 0,
488
+ "maximum": 1
489
+ },
490
+ "reason": {
491
+ "type": "string",
492
+ "minLength": 1,
493
+ "maxLength": 500
494
+ }
495
+ },
496
+ "required": [
497
+ "direction_id",
498
+ "client_request_id",
499
+ "expected_revision",
500
+ "action",
501
+ "reason"
502
+ ],
503
+ "$schema": "http://json-schema.org/draft-07/schema#"
504
+ },
505
+ "execution": {
506
+ "taskSupport": "forbidden"
507
+ }
508
+ }
509
+ ]
510
+ }
@@ -0,0 +1,140 @@
1
+ import { randomBytes, randomUUID, createHash } from 'node:crypto';
2
+ import { constants, openSync, closeSync, writeFileSync, lstatSync, unlinkSync } from 'node:fs';
3
+ import { join, isAbsolute } from 'node:path';
4
+ import { projectIdentity } from './project-identity.mjs';
5
+ import { assertStateOutsideWorkspace, canonicalPath, connectionDir, lstatExists, readPrivate, save, writePrivate } from './state.mjs';
6
+ import { sessionHome, sessionId, validateSession } from './session.mjs';
7
+ import { system } from './system.mjs';
8
+
9
+ const TOKEN = /^[\w-]{43}$/;
10
+ const hash = value => createHash('sha256').update(value).digest('hex');
11
+ // Only locks created by this browser flow can be recovered automatically. Legacy/live bridge locks remain untouched.
12
+ export function withBrowserLock(dir, action, processAlive = pid => { try { process.kill(pid, 0); return true; } catch (error) { if (error.code === 'ESRCH') return false; return true; } }) {
13
+ const path = join(dir, 'operation.lock'), guard = join(dir, 'browser-recovery.lock');
14
+ const create = () => {
15
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
16
+ try { writeFileSync(fd, JSON.stringify({ kind: 'karma42-browser-operation-1', pid: process.pid, nonce: randomUUID() })); }
17
+ finally { closeSync(fd); }
18
+ return lstatSync(path);
19
+ };
20
+ let owned;
21
+ try { owned = create(); }
22
+ catch (error) {
23
+ if (error.code !== 'EEXIST') throw error;
24
+ let guardFd;
25
+ try { guardFd = openSync(guard, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
26
+ catch { throw new Error('Another browser setup operation is checking this connection. Retry shortly; no process was stopped.'); }
27
+ try {
28
+ writeFileSync(guardFd, `${process.pid}\n`);
29
+ const before = lstatSync(path), raw = readPrivate(path);
30
+ let holder;
31
+ try { holder = JSON.parse(raw); } catch {}
32
+ if (holder?.kind !== 'karma42-browser-operation-1' || !Number.isSafeInteger(holder.pid) || holder.pid <= 0 || typeof holder.nonce !== 'string' || processAlive(holder.pid)) {
33
+ throw new Error('Another operation holds this connection. Finish or cancel its setup, or disconnect its active MCP entry, before retrying. No process was stopped.');
34
+ }
35
+ // Guard serializes recovery attempts; reread inode/content before touching the confirmed-dead lock.
36
+ const current = lstatSync(path);
37
+ if (current.dev !== before.dev || current.ino !== before.ino || readPrivate(path) !== raw) throw new Error('The connection lock changed. Retry setup; no process was stopped.');
38
+ unlinkSync(path);
39
+ owned = create();
40
+ } finally { closeSync(guardFd); unlinkSync(guard); }
41
+ }
42
+ return Promise.resolve().then(action).finally(() => {
43
+ if (!lstatExists(path)) return;
44
+ const current = lstatSync(path);
45
+ if (current.dev === owned.dev && current.ino === owned.ino) unlinkSync(path);
46
+ });
47
+ }
48
+ const receiptPath = dir => join(dir, 'pending-browser.json');
49
+ function validReceipt(receipt, id) {
50
+ if (receipt?.schema !== 'mcp-browser-pairing-1' || receipt.id !== id || id !== sessionId(receipt.service, receipt.agentId)
51
+ || !TOKEN.test(receipt.pollingSecret ?? '') || !TOKEN.test(receipt.candidateToken ?? '')
52
+ || !/^[\w-]{1,200}$/.test(receipt.agentId ?? '') || !/^[a-f0-9-]{36}$/.test(receipt.requestId ?? '')
53
+ || typeof receipt.clientName !== 'string' || !receipt.clientName.trim() || receipt.clientName.length > 100 || /[\x00-\x1f\x7f-\x9f]/.test(receipt.clientName)) throw new Error('Invalid private browser setup receipt. Review My agents.');
54
+ const plan = projectIdentity({ projectUrl: receipt.service, folder: receipt.folder });
55
+ if (plan.projectUrl !== receipt.service || canonicalPath(receipt.folder) !== receipt.folder) throw new Error('Browser setup workspace changed. Review My agents.');
56
+ return receipt;
57
+ }
58
+ export function browserApprovalUrl(receipt) {
59
+ const service = new URL(receipt.service);
60
+ const page = new URL('/viewer/', service.origin);
61
+ page.searchParams.set('project', service.pathname.split('/')[2]);
62
+ page.searchParams.set('section', 'your-agent');
63
+ page.searchParams.set('pairing', receipt.requestId);
64
+ return page.href;
65
+ }
66
+ export function createBrowserOperations({ home = sessionHome(), io, sys = system } = {}) {
67
+ home = canonicalPath(home);
68
+ const showPending = receipt => io?.say?.('Browser approval is required. Complete it on Karma42, then check this same connection.');
69
+ const startBody = receipt => ({ requestId: receipt.requestId, agentId: receipt.agentId, clientName: receipt.clientName, folder: receipt.folder, pollingSecret: receipt.pollingSecret, candidateTokenHash: hash(receipt.candidateToken) });
70
+ async function start(dir, receipt) {
71
+ let result;
72
+ try { result = await sys.request(receipt.service, 'pairings/start', startBody(receipt)); }
73
+ catch { throw new Error(`Browser setup reply unavailable. Your private request is saved. Retry finish_project_agent_connection with connection ${receipt.id}; do not create another request or replace credentials.`); }
74
+ if (result?.requestId !== receipt.requestId || !['pending', 'approved', 'cancelled', 'expired'].includes(result.status)) throw new Error('Unexpected browser setup reply. The private request was preserved.');
75
+ receipt = { ...receipt, registered: true, expiresAt: result.expiresAt };
76
+ writePrivate(receiptPath(dir), receipt);
77
+ return receipt;
78
+ }
79
+ function saved(record) { return validateSession(record, record.id); }
80
+ return {
81
+ async connect(options) {
82
+ if (!/^[\w-]{1,200}$/.test(options['agent-id'] ?? '')) throw new Error('Browser setup requires the project-specific agent ID from the project instructions.');
83
+ if (typeof options.clientName !== 'string' || !options.clientName.trim() || options.clientName.length > 100 || /[\x00-\x1f\x7f-\x9f]/.test(options.clientName)) throw new Error('Use a valid MCP client name.');
84
+ if (typeof options.folder !== 'string' || !isAbsolute(options.folder)) throw new Error('Use the actual absolute working folder approved by your human.');
85
+ const folder = canonicalPath(options.folder);
86
+ assertStateOutsideWorkspace(home, folder);
87
+ const plan = projectIdentity({ projectUrl: options['project-url'], folder });
88
+ sys.verifyBundle();
89
+ const id = sessionId(plan.projectUrl, options['agent-id']), dir = connectionDir(home, id);
90
+ if (lstatExists(join(dir, 'connection.json'))) validateSession(readPrivate(join(dir, 'connection.json'), true), id);
91
+ return withBrowserLock(dir, async () => {
92
+ let receipt;
93
+ if (lstatExists(receiptPath(dir))) {
94
+ receipt = validReceipt(readPrivate(receiptPath(dir), true), id);
95
+ if (['cancelled', 'expired'].includes(receipt.status) || (receipt.status === 'saved' && options.reconnect)) receipt = null;
96
+ else {
97
+ if (receipt.folder !== folder) throw new Error('A browser setup or saved approval belongs to another workspace. Use an explicit reconnect after the completed setup, or finish/cancel its pending request first.');
98
+ if (receipt.status === 'saved') return saved(validateSession(readPrivate(join(dir, 'connection.json'), true), id));
99
+ }
100
+ }
101
+ if (!receipt) {
102
+ receipt = { schema: 'mcp-browser-pairing-1', id, service: plan.projectUrl, agentId: options['agent-id'], clientName: options.clientName, folder,
103
+ requestId: randomUUID(), candidateToken: randomBytes(32).toString('base64url'), pollingSecret: randomBytes(32).toString('base64url'), createdAt: sys.now(), status: 'pending', registered: false };
104
+ // Persist the candidate BEFORE contacting the server: lost start/approval replies never lose the credential.
105
+ writePrivate(receiptPath(dir), receipt);
106
+ }
107
+ if (!receipt.registered) receipt = await start(dir, receipt);
108
+ showPending(receipt); return { id, status: receipt.status, approvalUrl: browserApprovalUrl(receipt), requestCheck: hash(receipt.requestId + ':' + hash(receipt.candidateToken)).slice(0, 8).toUpperCase() };
109
+ });
110
+ },
111
+ async prepare(options) {
112
+ const id = options.connection, dir = connectionDir(home, id);
113
+ if (lstatExists(receiptPath(dir))) assertStateOutsideWorkspace(home, validReceipt(readPrivate(receiptPath(dir), true), id).folder);
114
+ return withBrowserLock(dir, async () => {
115
+ if (!lstatExists(receiptPath(dir))) throw new Error('No browser setup found. Use connect_project_agent from the project instructions.');
116
+ let receipt = validReceipt(readPrivate(receiptPath(dir), true), id);
117
+ if (receipt.status === 'saved') return saved(validateSession(readPrivate(join(dir, 'connection.json'), true), id));
118
+ if (!receipt.registered) receipt = await start(dir, receipt);
119
+ let result;
120
+ try { result = await sys.request(receipt.service, `pairings/${receipt.requestId}/poll`, {}, receipt.pollingSecret); }
121
+ catch { throw new Error(`Browser approval reply unavailable. Retry finish_project_agent_connection with connection ${id}; your private request and existing connection are preserved.`); }
122
+ if (!['pending', 'approved', 'cancelled', 'expired'].includes(result?.status)) throw new Error('Unexpected browser approval reply. Existing connection preserved.');
123
+ if (result.status === 'pending') { showPending(receipt); return { id, status: 'pending' }; }
124
+ if (result.status !== 'approved') {
125
+ writePrivate(receiptPath(dir), { ...receipt, status: result.status });
126
+ io.say(`Browser setup ${result.status}. Existing saved credentials were not changed. Ask your human before starting a fresh connection request.`);
127
+ return { id, status: result.status };
128
+ }
129
+ if (result.agentId !== receipt.agentId || !/^[\w-]{1,64}$/.test(result.agentName ?? '') || !Number.isFinite(result.approvedAt)) throw new Error('Approved identity differs from the requested agent. Existing connection preserved. Review My agents.');
130
+ assertStateOutsideWorkspace(home, receipt.folder);
131
+ const plan = projectIdentity({ projectUrl: receipt.service, repo: result.repoUrl, folder: receipt.folder });
132
+ const record = { schema: 'mcp-connection-1', id, service: receipt.service, agentId: receipt.agentId, agentName: result.agentName, repo: plan.repo, folder: plan.folder, createdAt: sys.now(), approvedAt: result.approvedAt };
133
+ writePrivate(join(dir, 'token'), receipt.candidateToken); save(dir, record);
134
+ // Keep the private receipt for restart/recovery; never exchange another credential on retry.
135
+ writePrivate(receiptPath(dir), { ...receipt, status: 'saved' });
136
+ return saved(record);
137
+ });
138
+ },
139
+ };
140
+ }