@karma42/agent 0.1.0-beta.11 → 0.1.0-beta.12
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/README.md +15 -13
- package/package.json +1 -1
- package/runtime/control-v2.mjs +6 -6
- package/runtime/manifest.json +2 -3
- package/runtime/project-tools.json +1 -1
- package/skills/karma42/SKILL.md +22 -4
- package/src/cli.mjs +3 -15
- package/src/layout.mjs +20 -0
- package/src/operation-lock.mjs +46 -0
- package/src/owner-client.mjs +143 -19
- package/src/reusable-stdio.mjs +77 -105
- package/src/system.mjs +19 -19
- package/src/version.mjs +3 -1
- package/src/worker-runtime.mjs +4 -2
- package/src/browser-batch.mjs +0 -130
- package/src/browser-pairing.mjs +0 -140
package/src/browser-pairing.mjs
DELETED
|
@@ -1,140 +0,0 @@
|
|
|
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('view', 'agent-connect');
|
|
63
|
-
page.searchParams.set('request', 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
|
-
}
|