@ignitionai/cogitator 0.5.1 → 0.6.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/CHANGELOG.md +86 -0
- package/LICENSE +21 -0
- package/README.md +81 -56
- package/dist/extensions/index.js +66 -29
- package/dist/src/app-updates.js +15 -0
- package/dist/src/auth-cli.js +18 -8
- package/dist/src/auth-http.js +13 -3
- package/dist/src/auth-state.js +41 -6
- package/dist/src/board.js +3 -1
- package/dist/src/browser-http.js +146 -0
- package/dist/src/classic-configuration.js +12 -4
- package/dist/src/cli.js +29 -2
- package/dist/src/config.js +10 -0
- package/dist/src/cron.js +91 -15
- package/dist/src/db.js +55 -3
- package/dist/src/durable/approvals.js +17 -2
- package/dist/src/durable/effect-gateway.js +23 -16
- package/dist/src/durable/manager.js +13 -4
- package/dist/src/durable/mission-runtime.js +204 -46
- package/dist/src/durable/recovery.js +37 -0
- package/dist/src/durable/workers.js +22 -14
- package/dist/src/execution/confinement.js +2 -1
- package/dist/src/execution/worker-supervisor.js +222 -0
- package/dist/src/git-import.js +187 -0
- package/dist/src/github-login.js +101 -0
- package/dist/src/history.js +6 -1
- package/dist/src/host-pi.js +9 -6
- package/dist/src/json-files.js +7 -4
- package/dist/src/machine-metrics.js +49 -0
- package/dist/src/machine-types.js +1 -0
- package/dist/src/mcp-cli.js +63 -0
- package/dist/src/mcp-http.js +164 -0
- package/dist/src/mcp-oauth.js +502 -0
- package/dist/src/mcp-server.js +6 -136
- package/dist/src/mcp-tokens.js +104 -0
- package/dist/src/mcp-tools.js +264 -0
- package/dist/src/native-auth.js +9 -2
- package/dist/src/packages.js +190 -0
- package/dist/src/paths.js +1 -0
- package/dist/src/pi-child.js +180 -0
- package/dist/src/pi-rpc-wrap.js +84 -0
- package/dist/src/pool.js +58 -7
- package/dist/src/project-setup.js +63 -0
- package/dist/src/provider-login.js +72 -13
- package/dist/src/reap-orphans.js +138 -0
- package/dist/src/registry.js +66 -43
- package/dist/src/schemas.js +19 -4
- package/dist/src/server-compat.js +173 -0
- package/dist/src/server-identity.js +69 -0
- package/dist/src/server.js +597 -41
- package/dist/src/shared-browser.js +357 -0
- package/dist/src/skills-import.js +13 -4
- package/dist/src/skills-upload.js +68 -0
- package/dist/src/spawner.js +20 -4
- package/dist/src/subagents.js +242 -0
- package/dist/src/team-queue.js +262 -0
- package/dist/src/terminal-assist.js +96 -0
- package/dist/src/terminal-http.js +167 -0
- package/dist/src/terminal.js +171 -0
- package/package.json +13 -3
- package/web/dist/assets/{BrandLogo3D-BvZPXohP.js → BrandLogo3D-4IJEcixt.js} +1 -1
- package/web/dist/assets/addon-fit-DIOBYJe3.js +1 -0
- package/web/dist/assets/index-Bi_Aag-u.js +85 -0
- package/web/dist/assets/index-DQsw9iul.css +1 -0
- package/web/dist/assets/xterm-ScmBfeDI.js +16 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-7Dyl-4v7.css +0 -1
- package/web/dist/assets/index-CdqzcBU-.js +0 -83
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { chromium } from 'playwright-core';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, existsSync, chmodSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { readJson, atomicWriteJson } from './json-files.js';
|
|
7
|
+
import { checkRequestAuthorization } from './request-authorization.js';
|
|
8
|
+
export const profileInput = z.object({ name: z.string().trim().min(1).max(60), agentIds: z.array(z.string().uuid()).max(50).default([]) }).strict();
|
|
9
|
+
export const browserAction = z.object({
|
|
10
|
+
action: z.enum(['tabs', 'open', 'navigate', 'read', 'screenshot', 'click', 'fill', 'press', 'scroll', 'back', 'forward', 'reload', 'close']),
|
|
11
|
+
tabId: z.string().uuid().optional(), url: z.string().max(4096).optional(),
|
|
12
|
+
selector: z.string().min(1).max(500).optional(), text: z.string().max(16000).optional(),
|
|
13
|
+
key: z.string().max(80).optional(), x: z.number().min(0).max(1).optional(), y: z.number().min(0).max(1).optional(),
|
|
14
|
+
delta: z.number().min(-2000).max(2000).optional(),
|
|
15
|
+
}).strict();
|
|
16
|
+
export class BrowserProblem extends Error {
|
|
17
|
+
}
|
|
18
|
+
/** Profiles contain credentials on disk. No profile bytes, cookies or CDP endpoints leave this service. */
|
|
19
|
+
export class SharedBrowser {
|
|
20
|
+
db;
|
|
21
|
+
controllerOrigin;
|
|
22
|
+
profiles;
|
|
23
|
+
directory;
|
|
24
|
+
running = new Map();
|
|
25
|
+
launching = new Map();
|
|
26
|
+
queues = new Map();
|
|
27
|
+
human = new Set();
|
|
28
|
+
epochs = new Map();
|
|
29
|
+
closing = false;
|
|
30
|
+
constructor(home, db, controllerOrigin) {
|
|
31
|
+
this.db = db;
|
|
32
|
+
this.controllerOrigin = controllerOrigin;
|
|
33
|
+
this.directory = join(home, 'browsers');
|
|
34
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
35
|
+
chmodSync(this.directory, 0o700);
|
|
36
|
+
const stored = readJson(join(this.directory, 'profiles.json'), []);
|
|
37
|
+
this.profiles = z.array(profileInput.extend({ id: z.string().uuid() })).parse(stored);
|
|
38
|
+
// Restart never silently returns a signed-in browser to automation.
|
|
39
|
+
for (const p of this.profiles)
|
|
40
|
+
this.human.add(p.id);
|
|
41
|
+
}
|
|
42
|
+
list() { return this.profiles.map(p => ({ ...p, humanControl: this.human.has(p.id), running: this.running.has(p.id) })); }
|
|
43
|
+
profile(id) { const p = this.profiles.find(p => p.id === id); if (!p)
|
|
44
|
+
throw new BrowserProblem('BROWSER_PROFILE_NOT_FOUND'); return p; }
|
|
45
|
+
save() { atomicWriteJson(join(this.directory, 'profiles.json'), this.profiles, 0o600); chmodSync(join(this.directory, 'profiles.json'), 0o600); }
|
|
46
|
+
create(input) {
|
|
47
|
+
const data = profileInput.parse(input);
|
|
48
|
+
this.validateAgents(data.agentIds);
|
|
49
|
+
if (this.profiles.length >= 20)
|
|
50
|
+
throw new BrowserProblem('BROWSER_PROFILE_LIMIT');
|
|
51
|
+
if (this.profiles.some(p => p.name === data.name))
|
|
52
|
+
throw new BrowserProblem('BROWSER_NAME_EXISTS');
|
|
53
|
+
const profile = { id: randomUUID(), ...data };
|
|
54
|
+
checkRequestAuthorization();
|
|
55
|
+
this.profiles.push(profile);
|
|
56
|
+
this.human.add(profile.id);
|
|
57
|
+
this.save();
|
|
58
|
+
return profile;
|
|
59
|
+
}
|
|
60
|
+
update(id, input) {
|
|
61
|
+
const data = profileInput.parse(input);
|
|
62
|
+
this.validateAgents(data.agentIds);
|
|
63
|
+
const profile = this.profile(id);
|
|
64
|
+
checkRequestAuthorization();
|
|
65
|
+
this.bump(id);
|
|
66
|
+
Object.assign(profile, data);
|
|
67
|
+
this.save();
|
|
68
|
+
return profile;
|
|
69
|
+
}
|
|
70
|
+
validateAgents(ids) { for (const id of ids)
|
|
71
|
+
if (!this.db.prepare('SELECT id FROM agent_preset WHERE id=?').get(id))
|
|
72
|
+
throw new BrowserProblem('BROWSER_AGENT_NOT_FOUND'); }
|
|
73
|
+
bump(id) { this.epochs.set(id, (this.epochs.get(id) ?? 0) + 1); }
|
|
74
|
+
async control(id, human) {
|
|
75
|
+
this.profile(id);
|
|
76
|
+
checkRequestAuthorization();
|
|
77
|
+
this.bump(id);
|
|
78
|
+
if (human)
|
|
79
|
+
this.human.add(id);
|
|
80
|
+
else
|
|
81
|
+
this.human.delete(id);
|
|
82
|
+
// Drain commands already sent before acknowledging takeover. New agent calls fail immediately.
|
|
83
|
+
await this.queues.get(id)?.catch(() => undefined);
|
|
84
|
+
checkRequestAuthorization();
|
|
85
|
+
return { humanControl: this.human.has(id) };
|
|
86
|
+
}
|
|
87
|
+
agentProfiles(conversationId) {
|
|
88
|
+
const row = this.db.prepare('SELECT agent_id FROM conversation WHERE id=?').get(conversationId);
|
|
89
|
+
if (!row?.agent_id)
|
|
90
|
+
throw new BrowserProblem('BROWSER_CONVERSATION_REQUIRED');
|
|
91
|
+
return this.list().filter(p => p.agentIds.includes(row.agent_id));
|
|
92
|
+
}
|
|
93
|
+
agentCheck(id, conversationId) {
|
|
94
|
+
if (!this.agentProfiles(conversationId).some(p => p.id === id))
|
|
95
|
+
throw new BrowserProblem('BROWSER_ACCESS_DENIED');
|
|
96
|
+
if (this.human.has(id))
|
|
97
|
+
throw new BrowserProblem('BROWSER_HUMAN_CONTROL');
|
|
98
|
+
}
|
|
99
|
+
validUrl(raw) {
|
|
100
|
+
let url;
|
|
101
|
+
try {
|
|
102
|
+
url = new URL(raw);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new BrowserProblem('BROWSER_URL_INVALID');
|
|
106
|
+
}
|
|
107
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || this.blocked(url))
|
|
108
|
+
throw new BrowserProblem('BROWSER_URL_DENIED');
|
|
109
|
+
return url.href;
|
|
110
|
+
}
|
|
111
|
+
blocked(url) {
|
|
112
|
+
// Never let the managed browser open its own controller/owner API.
|
|
113
|
+
return url.port === (process.env.COGITATOR_PORT ?? '5320') || (!!this.controllerOrigin && url.origin === this.controllerOrigin);
|
|
114
|
+
}
|
|
115
|
+
async launch(id) {
|
|
116
|
+
this.profile(id);
|
|
117
|
+
if (this.closing)
|
|
118
|
+
throw new BrowserProblem('BROWSER_STOPPING');
|
|
119
|
+
const active = this.running.get(id);
|
|
120
|
+
if (active)
|
|
121
|
+
return active;
|
|
122
|
+
const pending = this.launching.get(id);
|
|
123
|
+
if (pending)
|
|
124
|
+
return pending;
|
|
125
|
+
if (this.running.size + this.launching.size >= 2)
|
|
126
|
+
throw new BrowserProblem('BROWSER_RUNNING_LIMIT');
|
|
127
|
+
const task = (async () => {
|
|
128
|
+
const dir = join(this.directory, id);
|
|
129
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
130
|
+
let context;
|
|
131
|
+
try {
|
|
132
|
+
context = await chromium.launchPersistentContext(dir, {
|
|
133
|
+
headless: true, chromiumSandbox: true, viewport: { width: 1280, height: 800 },
|
|
134
|
+
acceptDownloads: false, serviceWorkers: 'block', timeout: 20000,
|
|
135
|
+
...(process.env.COGITATOR_BROWSER_EXECUTABLE ? { executablePath: process.env.COGITATOR_BROWSER_EXECUTABLE } : {}),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw new BrowserProblem('BROWSER_START_FAILED');
|
|
140
|
+
}
|
|
141
|
+
context.setDefaultTimeout(3000);
|
|
142
|
+
context.setDefaultNavigationTimeout(15000);
|
|
143
|
+
const run = { context, pages: new Map() };
|
|
144
|
+
await context.route('**/*', route => {
|
|
145
|
+
const url = new URL(route.request().url());
|
|
146
|
+
return this.blocked(url) ? route.abort() : route.continue();
|
|
147
|
+
});
|
|
148
|
+
await context.routeWebSocket('**/*', socket => {
|
|
149
|
+
const url = new URL(socket.url());
|
|
150
|
+
url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
|
|
151
|
+
if (this.blocked(url))
|
|
152
|
+
socket.close();
|
|
153
|
+
else
|
|
154
|
+
socket.connectToServer();
|
|
155
|
+
});
|
|
156
|
+
const register = (page) => {
|
|
157
|
+
if (run.pages.size >= 8) {
|
|
158
|
+
void page.close();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const tabId = randomUUID();
|
|
162
|
+
run.pages.set(tabId, page);
|
|
163
|
+
page.on('close', () => run.pages.delete(tabId));
|
|
164
|
+
page.on('dialog', dialog => { void dialog.dismiss().catch(() => undefined); });
|
|
165
|
+
};
|
|
166
|
+
context.pages().forEach(register);
|
|
167
|
+
context.on('page', register);
|
|
168
|
+
context.on('close', () => { this.running.delete(id); this.human.add(id); this.bump(id); });
|
|
169
|
+
this.running.set(id, run);
|
|
170
|
+
return run;
|
|
171
|
+
})();
|
|
172
|
+
this.launching.set(id, task);
|
|
173
|
+
try {
|
|
174
|
+
return await task;
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
this.launching.delete(id);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async serial(id, work) {
|
|
181
|
+
const next = (this.queues.get(id) ?? Promise.resolve()).catch(() => undefined).then(work);
|
|
182
|
+
this.queues.set(id, next);
|
|
183
|
+
try {
|
|
184
|
+
return await next;
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
if (this.queues.get(id) === next)
|
|
188
|
+
this.queues.delete(id);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async tabs(id) {
|
|
192
|
+
this.profile(id);
|
|
193
|
+
const run = this.running.get(id);
|
|
194
|
+
return Promise.all([...(run?.pages ?? [])].map(async ([id, page]) => ({ id, url: page.url(), title: await page.title().catch(() => '') })));
|
|
195
|
+
}
|
|
196
|
+
async act(id, raw, conversationId) {
|
|
197
|
+
const input = browserAction.parse(raw);
|
|
198
|
+
this.profile(id);
|
|
199
|
+
const epoch = this.epochs.get(id) ?? 0;
|
|
200
|
+
const check = () => {
|
|
201
|
+
checkRequestAuthorization();
|
|
202
|
+
if ((this.epochs.get(id) ?? 0) !== epoch)
|
|
203
|
+
throw new BrowserProblem('BROWSER_CONTROL_CHANGED');
|
|
204
|
+
if (conversationId)
|
|
205
|
+
this.agentCheck(id, conversationId);
|
|
206
|
+
else if (!this.human.has(id))
|
|
207
|
+
throw new BrowserProblem('BROWSER_TAKE_CONTROL');
|
|
208
|
+
};
|
|
209
|
+
check();
|
|
210
|
+
return this.serial(id, async () => {
|
|
211
|
+
check();
|
|
212
|
+
if (input.action === 'tabs')
|
|
213
|
+
return { tabs: await this.tabs(id) };
|
|
214
|
+
const run = await this.launch(id);
|
|
215
|
+
check();
|
|
216
|
+
let page = input.tabId ? run.pages.get(input.tabId) : undefined;
|
|
217
|
+
if (input.action === 'open') {
|
|
218
|
+
const url = this.validUrl(input.url ?? '');
|
|
219
|
+
check();
|
|
220
|
+
if (run.pages.size >= 8)
|
|
221
|
+
throw new BrowserProblem('BROWSER_TAB_LIMIT');
|
|
222
|
+
page = [...run.pages.values()].find(p => p.url() === "about:blank") ?? await run.context.newPage();
|
|
223
|
+
check();
|
|
224
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
if (!page || page.isClosed())
|
|
228
|
+
throw new BrowserProblem('BROWSER_TAB_NOT_FOUND');
|
|
229
|
+
const locator = input.selector ? page.locator(input.selector) : undefined;
|
|
230
|
+
switch (input.action) {
|
|
231
|
+
case 'navigate':
|
|
232
|
+
await page.goto(this.validUrl(input.url ?? ''), { waitUntil: 'domcontentloaded' });
|
|
233
|
+
break;
|
|
234
|
+
case 'back':
|
|
235
|
+
await page.goBack({ waitUntil: 'domcontentloaded' });
|
|
236
|
+
break;
|
|
237
|
+
case 'forward':
|
|
238
|
+
await page.goForward({ waitUntil: 'domcontentloaded' });
|
|
239
|
+
break;
|
|
240
|
+
case 'reload':
|
|
241
|
+
await page.reload({ waitUntil: 'domcontentloaded' });
|
|
242
|
+
break;
|
|
243
|
+
case 'close':
|
|
244
|
+
await page.close();
|
|
245
|
+
break;
|
|
246
|
+
case 'read': {
|
|
247
|
+
const text = await page.locator('body').ariaSnapshot({ timeout: 3000 });
|
|
248
|
+
check();
|
|
249
|
+
return { text: text.slice(0, 24000) };
|
|
250
|
+
}
|
|
251
|
+
case 'screenshot': {
|
|
252
|
+
const bytes = await page.screenshot({ type: 'jpeg', quality: 65, timeout: 5000 });
|
|
253
|
+
check();
|
|
254
|
+
return { image: bytes.toString('base64'), mimeType: 'image/jpeg' };
|
|
255
|
+
}
|
|
256
|
+
case 'click':
|
|
257
|
+
if (locator)
|
|
258
|
+
await locator.click({ timeout: 2000 });
|
|
259
|
+
else if (input.x !== undefined && input.y !== undefined)
|
|
260
|
+
await page.mouse.click(input.x * 1280, input.y * 800);
|
|
261
|
+
else
|
|
262
|
+
throw new BrowserProblem('BROWSER_TARGET_REQUIRED');
|
|
263
|
+
break;
|
|
264
|
+
case 'fill':
|
|
265
|
+
if (!locator || input.text === undefined)
|
|
266
|
+
throw new BrowserProblem('BROWSER_TARGET_REQUIRED');
|
|
267
|
+
// Credentials are entered by the human through takeover, never as agent tool arguments.
|
|
268
|
+
if (conversationId && await locator.getAttribute('type') === 'password')
|
|
269
|
+
throw new BrowserProblem('BROWSER_SECRET_TAKEOVER');
|
|
270
|
+
check();
|
|
271
|
+
await locator.fill(input.text);
|
|
272
|
+
break;
|
|
273
|
+
case 'press':
|
|
274
|
+
if (!input.key || !/^[A-Za-z0-9+_. -]{1,80}$/.test(input.key))
|
|
275
|
+
throw new BrowserProblem('BROWSER_KEY_INVALID');
|
|
276
|
+
await page.keyboard.press(input.key);
|
|
277
|
+
break;
|
|
278
|
+
case 'scroll':
|
|
279
|
+
await page.mouse.wheel(0, input.delta ?? 500);
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
check();
|
|
284
|
+
return { tabs: await this.tabs(id) };
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/** Human input only; never available as an agent tool. */
|
|
288
|
+
async type(id, tabId, text) {
|
|
289
|
+
if (text.length > 16000)
|
|
290
|
+
throw new BrowserProblem('BROWSER_TEXT_LIMIT');
|
|
291
|
+
return this.serial(id, async () => {
|
|
292
|
+
checkRequestAuthorization();
|
|
293
|
+
if (!this.human.has(id))
|
|
294
|
+
throw new BrowserProblem('BROWSER_TAKE_CONTROL');
|
|
295
|
+
const page = this.running.get(id)?.pages.get(tabId);
|
|
296
|
+
if (!page)
|
|
297
|
+
throw new BrowserProblem('BROWSER_TAB_NOT_FOUND');
|
|
298
|
+
await page.keyboard.insertText(text);
|
|
299
|
+
return {};
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
async watch(id, tabId, send, check) {
|
|
303
|
+
this.profile(id);
|
|
304
|
+
check();
|
|
305
|
+
const page = this.running.get(id)?.pages.get(tabId);
|
|
306
|
+
if (!page)
|
|
307
|
+
throw new BrowserProblem('BROWSER_TAB_NOT_FOUND');
|
|
308
|
+
const session = await page.context().newCDPSession(page);
|
|
309
|
+
check();
|
|
310
|
+
let stopped = false;
|
|
311
|
+
let latest;
|
|
312
|
+
const timer = setInterval(() => {
|
|
313
|
+
if (!latest || stopped)
|
|
314
|
+
return;
|
|
315
|
+
try {
|
|
316
|
+
check();
|
|
317
|
+
send(latest);
|
|
318
|
+
latest = undefined;
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
void stop();
|
|
322
|
+
}
|
|
323
|
+
}, 100);
|
|
324
|
+
session.on('Page.screencastFrame', event => {
|
|
325
|
+
if (stopped)
|
|
326
|
+
return;
|
|
327
|
+
void session.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => undefined);
|
|
328
|
+
try {
|
|
329
|
+
check();
|
|
330
|
+
latest = Buffer.from(event.data, 'base64');
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
void stop();
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
const stop = async () => { if (stopped)
|
|
337
|
+
return; stopped = true; clearInterval(timer); latest = undefined; await session.detach().catch(() => undefined); };
|
|
338
|
+
try {
|
|
339
|
+
await session.send('Page.startScreencast', { format: 'jpeg', quality: 65, maxWidth: 1280, maxHeight: 800, everyNthFrame: 1 });
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
await stop();
|
|
343
|
+
throw err;
|
|
344
|
+
}
|
|
345
|
+
return stop;
|
|
346
|
+
}
|
|
347
|
+
async stop(id) {
|
|
348
|
+
this.profile(id);
|
|
349
|
+
this.human.add(id);
|
|
350
|
+
this.bump(id);
|
|
351
|
+
await this.queues.get(id)?.catch(() => undefined);
|
|
352
|
+
await this.running.get(id)?.context.close();
|
|
353
|
+
return {};
|
|
354
|
+
}
|
|
355
|
+
async dispose() { this.closing = true; await Promise.allSettled(this.launching.values()); await Promise.allSettled([...this.running.values()].map(r => r.context.close())); }
|
|
356
|
+
installed() { return existsSync(process.env.COGITATOR_BROWSER_EXECUTABLE ?? chromium.executablePath()); }
|
|
357
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { checkRequestAuthorization } from "./request-authorization.js";
|
|
2
2
|
import { AuthError } from "./native-auth.js";
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
|
-
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync, realpathSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
|
-
import { basename, join } from "node:path";
|
|
6
|
+
import { basename, join, resolve, sep } from "node:path";
|
|
7
7
|
/** Bornes de l'exploration et des transferts (une source hostile ne doit pas saturer le disque). */
|
|
8
8
|
const SCAN_MAX_DEPTH = 2;
|
|
9
9
|
const SCAN_MAX_SKILLS = 50;
|
|
@@ -50,12 +50,21 @@ export function importFromDir(srcDir, destRoot, overwrite = false) {
|
|
|
50
50
|
for (const dir of skills) {
|
|
51
51
|
const name = sanitizeSkillName(basename(dir));
|
|
52
52
|
const target = join(destRoot, name);
|
|
53
|
+
if (existsSync(target) && realpathSync(target) === realpathSync(dir)) {
|
|
54
|
+
result.skipped.push(name);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (resolve(target).startsWith(realpathSync(dir) + sep))
|
|
58
|
+
throw new Error("La destination ne peut pas être à l’intérieur du skill source.");
|
|
53
59
|
if (existsSync(target) && !overwrite) {
|
|
54
60
|
result.skipped.push(name);
|
|
55
61
|
continue;
|
|
56
62
|
}
|
|
57
|
-
|
|
58
|
-
cpSync(dir,
|
|
63
|
+
const stage = mkdtempSync(join(destRoot, ".import-"));
|
|
64
|
+
cpSync(dir, stage, { recursive: true });
|
|
65
|
+
if (existsSync(target))
|
|
66
|
+
renameSync(target, `${stage}.previous-${name}`);
|
|
67
|
+
renameSync(stage, target);
|
|
59
68
|
result.imported.push(name);
|
|
60
69
|
}
|
|
61
70
|
if (skills.length === 0)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, renameSync, writeFileSync, lstatSync } from "node:fs";
|
|
2
|
+
import { dirname, join, posix } from "node:path";
|
|
3
|
+
import { checkRequestAuthorization } from "./request-authorization.js";
|
|
4
|
+
/** Browser directory uploads contain relative paths, never server paths or archives. */
|
|
5
|
+
export function importSkillUpload(input, dest) {
|
|
6
|
+
if (!Array.isArray(input) || !input.length || input.length > 500)
|
|
7
|
+
throw new Error("Choisis entre 1 et 500 fichiers (6 Mo maximum).");
|
|
8
|
+
let bytes = 0;
|
|
9
|
+
const files = new Map();
|
|
10
|
+
for (const item of input) {
|
|
11
|
+
if (!item || typeof item.path !== "string" || typeof item.content !== "string")
|
|
12
|
+
throw new Error("Fichier invalide.");
|
|
13
|
+
const parts = item.path.split("/");
|
|
14
|
+
if (item.path.length > 500 || parts.length > 12 || parts.some(p => !p || p.startsWith(".") || p === "node_modules" || /[\\:\x00-\x1f]/.test(p)))
|
|
15
|
+
throw new Error("Chemin de fichier refusé.");
|
|
16
|
+
if (files.has(item.path) || item.content.length > 8 * 1024 * 1024 || !/^[A-Za-z0-9+/]*={0,2}$/.test(item.content))
|
|
17
|
+
throw new Error("Fichier dupliqué ou encodage invalide.");
|
|
18
|
+
const data = Buffer.from(item.content, "base64");
|
|
19
|
+
if (data.toString("base64") !== item.content)
|
|
20
|
+
throw new Error("Encodage invalide.");
|
|
21
|
+
bytes += data.length;
|
|
22
|
+
if (bytes > 6 * 1024 * 1024)
|
|
23
|
+
throw new Error("Le dossier dépasse 6 Mo.");
|
|
24
|
+
files.set(item.path, data);
|
|
25
|
+
}
|
|
26
|
+
const roots = [...files.keys()].filter(p => posix.basename(p) === "SKILL.md").map(p => posix.dirname(p));
|
|
27
|
+
if (!roots.length || roots.length > 50)
|
|
28
|
+
throw new Error("Le dossier doit contenir entre 1 et 50 skills avec un SKILL.md.");
|
|
29
|
+
const names = new Set();
|
|
30
|
+
for (const root of roots) {
|
|
31
|
+
const name = posix.basename(root);
|
|
32
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name) || names.has(name) || roots.some(r => r !== root && root.startsWith(r + "/")))
|
|
33
|
+
throw new Error("Noms de skills en conflit ou dossiers imbriqués.");
|
|
34
|
+
names.add(name);
|
|
35
|
+
const skill = files.get(root + "/SKILL.md").toString("utf8");
|
|
36
|
+
if (!/^---\r?\n/.test(skill) || !/^name:\s*\S/m.test(skill) || !/^description:\s*\S/m.test(skill))
|
|
37
|
+
throw new Error(`SKILL.md incomplet : ${name}`);
|
|
38
|
+
}
|
|
39
|
+
// Validate everything before writing. Existing skills are preserved, never overwritten.
|
|
40
|
+
checkRequestAuthorization();
|
|
41
|
+
mkdirSync(dest, { recursive: true, mode: 0o700 });
|
|
42
|
+
if (lstatSync(dest).isSymbolicLink())
|
|
43
|
+
throw new Error("Destination symbolique refusée.");
|
|
44
|
+
const imported = [], skipped = [];
|
|
45
|
+
for (const root of roots) {
|
|
46
|
+
const name = posix.basename(root), target = join(dest, name);
|
|
47
|
+
if (existsSync(target)) {
|
|
48
|
+
skipped.push(name);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const stage = mkdtempSync(join(dest, ".import-"));
|
|
52
|
+
for (const [path, data] of files) {
|
|
53
|
+
if (!path.startsWith(root + "/"))
|
|
54
|
+
continue;
|
|
55
|
+
const output = join(stage, path.slice(root.length + 1));
|
|
56
|
+
mkdirSync(dirname(output), { recursive: true, mode: 0o700 });
|
|
57
|
+
writeFileSync(output, data, { flag: "wx", mode: 0o600 });
|
|
58
|
+
}
|
|
59
|
+
checkRequestAuthorization();
|
|
60
|
+
if (existsSync(target)) {
|
|
61
|
+
skipped.push(name);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
renameSync(stage, target);
|
|
65
|
+
imported.push(name);
|
|
66
|
+
}
|
|
67
|
+
return { imported, skipped };
|
|
68
|
+
}
|
package/dist/src/spawner.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { currentMcpServers, resourceInstructions, runtimeIntegration } from "./project-setup.js";
|
|
2
|
+
import { githubEnv, githubConfigured } from "./github-login.js";
|
|
1
3
|
import { checkRequestAuthorization } from "./request-authorization.js";
|
|
2
4
|
import { reconcileConfiguration } from "./classic-configuration.js";
|
|
3
5
|
import { mkdirSync } from "node:fs";
|
|
@@ -6,9 +8,10 @@ import { join } from "node:path";
|
|
|
6
8
|
import { getConversation, setConversationSession } from "./conversations.js";
|
|
7
9
|
import { UI_INSTRUCTIONS, UI_PRESENTATION_POLICY } from "./generative-ui.js";
|
|
8
10
|
import { MCP_ENV_VAR, encodeMcpEnv } from "./mcp-env.js";
|
|
11
|
+
import { OWNED_PI_ENV, ownedPiMarker } from "./reap-orphans.js";
|
|
9
12
|
import { buildArgs } from "./spawn.js";
|
|
10
13
|
/** Identité d'environnement : l'agent sait qu'il tourne dans le web UI, pas dans le TUI pi. */
|
|
11
|
-
const ENVIRONMENT_NOTICE = "Environnement : tu t'exécutes dans Cogitator, un panneau de contrôle web pour pi. L'utilisateur interagit depuis un navigateur : ne lui demande jamais de changer de mode, d'appuyer sur une touche ou d'utiliser le TUI pi —
|
|
14
|
+
const ENVIRONMENT_NOTICE = "Environnement : tu t'exécutes dans Cogitator, un panneau de contrôle web pour pi. L'utilisateur interagit depuis un navigateur : ne lui demande jamais de changer de mode, d'appuyer sur une touche ou d'utiliser le TUI pi — vérifie tes outils réellement disponibles et signale les capacités manquantes avant toute action qui en dépend.";
|
|
12
15
|
/** Fabrique unique du mécanisme de spawn, partagé par le serveur HTTP et le CronService. */
|
|
13
16
|
export function makeSpawner(opts) {
|
|
14
17
|
const { db, pool, paths } = opts;
|
|
@@ -29,14 +32,27 @@ export function makeSpawner(opts) {
|
|
|
29
32
|
throw new Error("conversation durable : aucun processus pi classic (runtime.ts)");
|
|
30
33
|
}
|
|
31
34
|
const spawn = JSON.parse(conv.spawn_args || "{}");
|
|
32
|
-
const mcpEnv = encodeMcpEnv(spawn.mcpServers ?? []);
|
|
35
|
+
const mcpEnv = encodeMcpEnv(currentMcpServers(spawn.mcpServers ?? []));
|
|
36
|
+
const env = {
|
|
37
|
+
...(githubConfigured(paths) ? { GH_CONFIG_DIR: githubEnv(paths).GH_CONFIG_DIR, GH_TOKEN: "", GITHUB_TOKEN: "", GH_ENTERPRISE_TOKEN: "", GITHUB_ENTERPRISE_TOKEN: "" } : {}),
|
|
38
|
+
COGITATOR_HOME: paths.home,
|
|
39
|
+
PI_CODING_AGENT_DIR: paths.piAgentDir,
|
|
40
|
+
COGITATOR_CONVERSATION_ID: conv.id,
|
|
41
|
+
};
|
|
42
|
+
const marker = ownedPiMarker();
|
|
43
|
+
if (marker)
|
|
44
|
+
env[OWNED_PI_ENV] = marker;
|
|
45
|
+
if (process.env.COGITATOR_URL)
|
|
46
|
+
env.COGITATOR_URL = process.env.COGITATOR_URL;
|
|
47
|
+
if (mcpEnv)
|
|
48
|
+
env[MCP_ENV_VAR] = mcpEnv;
|
|
33
49
|
const result = await pool.ensure(conv.id, {
|
|
34
50
|
cwd: conv.workspace_dir ?? homedir(),
|
|
35
51
|
// Host presentation capability: also available to legacy sessions, without rewriting their snapshot.
|
|
36
|
-
args: buildArgs({ ...spawn, uiInstructions: `${spawn.uiInstructions ?? UI_INSTRUCTIONS}\n\n${UI_PRESENTATION_POLICY}\n\n${ENVIRONMENT_NOTICE}` }, tmpDir, conv.id),
|
|
52
|
+
args: ["--extension", runtimeIntegration().extension, ...buildArgs({ ...spawn, uiInstructions: `${spawn.uiInstructions ?? UI_INSTRUCTIONS}\n\n${UI_PRESENTATION_POLICY}\n\n${ENVIRONMENT_NOTICE}\n\n${resourceInstructions(db, paths, conv.workspace_dir ?? paths.home)}` }, tmpDir, conv.id)],
|
|
37
53
|
resumeSessionFile: conv.session_file,
|
|
38
54
|
initialize: client => reconcileConfiguration(db, pool, conv.id, client),
|
|
39
|
-
env
|
|
55
|
+
env,
|
|
40
56
|
});
|
|
41
57
|
try {
|
|
42
58
|
checkRequestAuthorization();
|