@quadient/skillshare 1.19.0 → 1.19.2
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 +8 -0
- package/dist/agents-claude.js +33 -3
- package/dist/agents-codex.js +9 -1
- package/dist/agents-detect.js +200 -74
- package/dist/agents-executable.js +76 -0
- package/dist/agents-process.js +137 -28
- package/dist/agents-service.js +4 -2
- package/dist/agents.js +38 -11
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -69,6 +69,14 @@ working directory such as `--workdir ~\Projects`. The service is the scheduled t
|
|
|
69
69
|
shims (`claude.cmd`, `codex.cmd`) are started through `cmd.exe` with every argument quoted;
|
|
70
70
|
Claude Code gets the session instructions as a file.
|
|
71
71
|
|
|
72
|
+
From CLI 1.19.1, when Codex is missing from PATH on Windows, the listener finds the current
|
|
73
|
+
desktop CLI under `%LOCALAPPDATA%\OpenAI\Codex\bin`. It checks again for each new process,
|
|
74
|
+
so an app update can replace that directory without requiring a service reinstall or a PATH
|
|
75
|
+
edit. An existing Codex executable or shim on PATH takes precedence. Agent detection retries
|
|
76
|
+
a failed version check once and refreshes in the background while polling and session leases
|
|
77
|
+
continue. If refreshing capabilities throws an error, the last complete snapshot is retained
|
|
78
|
+
until retry; a completed check removes agents whose version command still fails.
|
|
79
|
+
|
|
72
80
|
Legacy read-only settings migrate automatically to Auto, which uses each provider's automatic approvals and does not enforce permanent read-only access.
|
|
73
81
|
Already-created sessions retain their frozen permissions. Local `approvalMode` values seed defaults once; subsequent web changes take precedence.
|
|
74
82
|
|
package/dist/agents-claude.js
CHANGED
|
@@ -169,13 +169,25 @@ class ClaudeDriver {
|
|
|
169
169
|
early = [];
|
|
170
170
|
costSoFar = 0;
|
|
171
171
|
closing = false;
|
|
172
|
+
startup = new AbortController();
|
|
172
173
|
permissions = new Map();
|
|
173
174
|
constructor(context, options) {
|
|
174
175
|
this.context = context;
|
|
175
176
|
this.options = options;
|
|
176
177
|
}
|
|
177
178
|
async open() {
|
|
179
|
+
try {
|
|
180
|
+
await this.openProcess();
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
await this.process?.kill();
|
|
184
|
+
await this.removeDirectory();
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async openProcess() {
|
|
178
189
|
await validateSessionWorkdir(this.context);
|
|
190
|
+
this.startup.signal.throwIfAborted();
|
|
179
191
|
const servers = this.context.start.mcpServers ?? [];
|
|
180
192
|
const instructions = claudeInstructions(this.context);
|
|
181
193
|
let mcpConfig;
|
|
@@ -185,19 +197,23 @@ class ClaudeDriver {
|
|
|
185
197
|
const shadowed = servers.length > 0 && !isLockedDown(this.context.start) ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
|
|
186
198
|
if (servers.length > 0 || instructions)
|
|
187
199
|
this.directory = await mkdtemp(join(tmpdir(), 'skillshare-session-'));
|
|
200
|
+
this.startup.signal.throwIfAborted();
|
|
188
201
|
if (servers.length > 0) {
|
|
189
202
|
mcpConfig = join(this.directory, 'mcp.json');
|
|
190
203
|
await writeFile(mcpConfig, claudeMcpConfig(servers), { mode: 0o600 });
|
|
204
|
+
this.startup.signal.throwIfAborted();
|
|
191
205
|
}
|
|
192
206
|
if (shadowed.length > 0) {
|
|
193
207
|
settingsFile = join(this.directory, 'settings.json');
|
|
194
208
|
await writeFile(settingsFile, claudeSettings(shadowed), { mode: 0o600 });
|
|
209
|
+
this.startup.signal.throwIfAborted();
|
|
195
210
|
}
|
|
196
211
|
if (instructions) {
|
|
197
212
|
instructionsFile = join(this.directory, 'instructions.md');
|
|
198
213
|
await writeFile(instructionsFile, instructions, { mode: 0o600 });
|
|
214
|
+
this.startup.signal.throwIfAborted();
|
|
199
215
|
}
|
|
200
|
-
this.process = startAgentProcess({
|
|
216
|
+
this.process = await startAgentProcess({
|
|
201
217
|
command: this.options.command ?? 'claude',
|
|
202
218
|
args: claudeArgs(this.context, mcpConfig, instructionsFile, settingsFile),
|
|
203
219
|
cwd: workdir,
|
|
@@ -209,8 +225,14 @@ class ClaudeDriver {
|
|
|
209
225
|
...(isSandboxed(this.context.start.configuration) || isLockedDown(this.context.start) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
|
|
210
226
|
},
|
|
211
227
|
spawnAgent: this.options.spawnAgent,
|
|
228
|
+
resolveCommand: this.options.resolveCommand,
|
|
229
|
+
signal: this.startup.signal,
|
|
212
230
|
onLine: line => this.receive(line),
|
|
213
231
|
});
|
|
232
|
+
if (this.closing) {
|
|
233
|
+
await this.process.kill();
|
|
234
|
+
this.startup.signal.throwIfAborted();
|
|
235
|
+
}
|
|
214
236
|
void this.process.exited.then(code => this.onExit(code));
|
|
215
237
|
// Claude Code answers initialize once it is ready, which turns a bad install or a bad flag into a clear start failure.
|
|
216
238
|
// Suggestions come after a turn's result; versions without them ignore the field.
|
|
@@ -278,10 +300,18 @@ class ClaudeDriver {
|
|
|
278
300
|
}
|
|
279
301
|
async close() {
|
|
280
302
|
this.closing = true;
|
|
303
|
+
this.startup.abort();
|
|
281
304
|
this.clearRequests();
|
|
282
305
|
await this.process?.kill();
|
|
283
|
-
|
|
284
|
-
|
|
306
|
+
await this.removeDirectory();
|
|
307
|
+
}
|
|
308
|
+
async removeDirectory() {
|
|
309
|
+
const directory = this.directory;
|
|
310
|
+
if (!directory)
|
|
311
|
+
return;
|
|
312
|
+
await rm(directory, { recursive: true, force: true }).catch(() => { });
|
|
313
|
+
if (this.directory === directory)
|
|
314
|
+
this.directory = null;
|
|
285
315
|
}
|
|
286
316
|
control(request) {
|
|
287
317
|
const requestId = randomUUID();
|
package/dist/agents-codex.js
CHANGED
|
@@ -140,6 +140,7 @@ class CodexDriver {
|
|
|
140
140
|
/** Cleared once Codex says it cannot predict, so later turns do not ask again. */
|
|
141
141
|
predictions = true;
|
|
142
142
|
closing = false;
|
|
143
|
+
startup = new AbortController();
|
|
143
144
|
requests = new Map();
|
|
144
145
|
constructor(context, options) {
|
|
145
146
|
this.context = context;
|
|
@@ -149,14 +150,20 @@ class CodexDriver {
|
|
|
149
150
|
await validateSessionWorkdir(this.context);
|
|
150
151
|
const { start } = this.context;
|
|
151
152
|
const servers = start.mcpServers ?? [];
|
|
152
|
-
this.process = startAgentProcess({
|
|
153
|
+
this.process = await startAgentProcess({
|
|
153
154
|
command: this.options.command ?? 'codex',
|
|
154
155
|
args: ['app-server', ...(isLockedDown(start) ? [] : codexConfigArgs(this.context.profile?.args ?? []))],
|
|
155
156
|
cwd: sessionWorkdir(this.context),
|
|
156
157
|
env: { ...mcpTokenEnvironment(servers), SKILLSHARE_SESSION_ID: this.context.sessionId },
|
|
157
158
|
spawnAgent: this.options.spawnAgent,
|
|
159
|
+
resolveCommand: this.options.resolveCommand,
|
|
160
|
+
signal: this.startup.signal,
|
|
158
161
|
onLine: line => this.receive(line),
|
|
159
162
|
});
|
|
163
|
+
if (this.closing) {
|
|
164
|
+
await this.process.kill();
|
|
165
|
+
this.startup.signal.throwIfAborted();
|
|
166
|
+
}
|
|
160
167
|
void this.process.exited.then(code => this.onExit(code));
|
|
161
168
|
await this.request('initialize', {
|
|
162
169
|
clientInfo: { name: 'skillshare', title: 'Skillshare', version: this.options.clientVersion ?? '0.0.0' },
|
|
@@ -228,6 +235,7 @@ class CodexDriver {
|
|
|
228
235
|
}
|
|
229
236
|
async close() {
|
|
230
237
|
this.closing = true;
|
|
238
|
+
this.startup.abort();
|
|
231
239
|
this.clearRequests();
|
|
232
240
|
await this.process?.kill();
|
|
233
241
|
}
|
package/dist/agents-detect.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
2
1
|
import { readFile, mkdtemp, readdir, rm } from 'node:fs/promises';
|
|
3
2
|
import { homedir, tmpdir } from 'node:os';
|
|
4
3
|
import { basename, isAbsolute, join, resolve } from 'node:path';
|
|
5
4
|
import { startAgentProcess } from './agents-process.js';
|
|
6
5
|
import { loadAgentSettings, migrateAgentSettings } from './agents-settings.js';
|
|
7
|
-
import
|
|
6
|
+
import { resolveAgentCommand } from './agents-executable.js';
|
|
8
7
|
/** Model aliases Claude Code resolves to the latest release; Claude Code itself has no command that lists models. */
|
|
9
8
|
export const CLAUDE_MODELS = ['fable', 'opus', 'sonnet', 'haiku'];
|
|
10
9
|
export const CLAUDE_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
@@ -21,12 +20,17 @@ export async function detectAgents(options = {}) {
|
|
|
21
20
|
const agents = [];
|
|
22
21
|
const problems = [];
|
|
23
22
|
const detectionFailures = [];
|
|
23
|
+
const commands = { claude: 'claude', codex: 'codex' };
|
|
24
24
|
const version = async (kind) => {
|
|
25
|
-
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
25
|
+
const injected = options.version ? await options.version(kind) : undefined;
|
|
26
|
+
const result = options.version ? { command: injected === null ? kind : await resolveAgentCommand(kind, env, { home, signal: options.signal }).catch(() => kind), output: injected ?? null }
|
|
27
|
+
: await detectAgentVersion(kind, env, { home, signal: options.signal });
|
|
28
|
+
options.signal?.throwIfAborted();
|
|
29
|
+
const { output } = result;
|
|
30
|
+
const failure = 'failure' in result ? result.failure : undefined;
|
|
31
|
+
commands[kind] = result.command;
|
|
32
|
+
if (failure)
|
|
33
|
+
problems.push(failure);
|
|
30
34
|
// Send only our bounded diagnostic, never stderr, the environment or the full local PATH.
|
|
31
35
|
if (output === null)
|
|
32
36
|
detectionFailures.push({ kind, message: failure ?? `${kind} --version could not be run. Check the executable and PATH.` });
|
|
@@ -38,8 +42,8 @@ export async function detectAgents(options = {}) {
|
|
|
38
42
|
const configured = Array.isArray(settings?.availableModels) ? settings.availableModels.filter((m) => typeof m === 'string') : [];
|
|
39
43
|
const models = [...new Set([...CLAUDE_MODELS, ...configured])].filter(id => NAME.test(id) && id !== 'default')
|
|
40
44
|
.map(id => ({ id, reasoningLevels: CLAUDE_EFFORT_LEVELS }));
|
|
41
|
-
const approvalModes = options.approvalModes ? await options.approvalModes('claude', claudeVersion)
|
|
42
|
-
: options.version ? undefined : await detectApprovalModes('claude', claudeVersion, env);
|
|
45
|
+
const approvalModes = options.approvalModes ? await options.approvalModes('claude', claudeVersion, commands.claude, env)
|
|
46
|
+
: options.version ? undefined : await detectApprovalModes('claude', claudeVersion, env, commands.claude, options.signal);
|
|
43
47
|
agents.push({ kind: 'claude', version: parseVersion(claudeVersion), models,
|
|
44
48
|
warnings: approvalModes?.length === 0 ? ['Could not verify approval modes. Check the installed Claude Code version and restart the listener after updating it.'] : [],
|
|
45
49
|
...(approvalModes ? { approvalModes } : {}) });
|
|
@@ -49,19 +53,21 @@ export async function detectAgents(options = {}) {
|
|
|
49
53
|
const codexHome = env.CODEX_HOME ?? join(home, '.codex');
|
|
50
54
|
const warnings = [];
|
|
51
55
|
// Codex's own model/list reflects the account; its cache file is the fallback when the app-server cannot be asked.
|
|
52
|
-
const listed = await (options.codexModels
|
|
56
|
+
const listed = await (options.codexModels ? options.codexModels(commands.codex, env) : codexModelList({ command: commands.codex, env, signal: options.signal })).catch(() => null);
|
|
57
|
+
options.signal?.throwIfAborted();
|
|
53
58
|
const models = listed ?? cachedCodexModels(parseJson(await read(join(codexHome, 'models_cache.json'))));
|
|
54
59
|
if (models.length === 0)
|
|
55
60
|
warnings.push('Codex did not list its models. Run codex once to sign in or refresh it; only the default model is offered.');
|
|
56
61
|
const configured = defaultCodexModel(await read(join(codexHome, 'config.toml')));
|
|
57
62
|
if (configured && models.length > 0 && !models.some(m => m.id === configured))
|
|
58
63
|
warnings.push(`The default model "${configured}" from config.toml is not in the Codex model list and may be rejected; pick a model explicitly.`);
|
|
59
|
-
const approvalModes = options.approvalModes ? await options.approvalModes('codex', codexVersion)
|
|
60
|
-
: options.version ? undefined : await detectApprovalModes('codex', codexVersion, env);
|
|
64
|
+
const approvalModes = options.approvalModes ? await options.approvalModes('codex', codexVersion, commands.codex, env)
|
|
65
|
+
: options.version ? undefined : await detectApprovalModes('codex', codexVersion, env, commands.codex, options.signal);
|
|
61
66
|
if (approvalModes?.length === 0)
|
|
62
67
|
warnings.push('Could not verify approval modes from Codex app-server schema. Update Codex and restart the listener.');
|
|
63
68
|
agents.push({ kind: 'codex', version: parseVersion(codexVersion), models, warnings, ...(approvalModes ? { approvalModes } : {}) });
|
|
64
69
|
}
|
|
70
|
+
options.signal?.throwIfAborted();
|
|
65
71
|
const settingsText = options.read ? await read(profilesPath(home)) : null;
|
|
66
72
|
const settings = options.read ? migrateAgentSettings(settingsText === null ? {} : JSON.parse(settingsText)) : await loadAgentSettings(profilesPath(home));
|
|
67
73
|
const profiles = parseProfiles(JSON.stringify({ ...settings, profiles: settings.profiles ?? [] }), home, problems);
|
|
@@ -102,44 +108,35 @@ export function claudeApprovalModesFromHelp(help) {
|
|
|
102
108
|
const choices = /choices?:\s*([^)]*)/i.exec(description)?.[1];
|
|
103
109
|
return choices ? approvalModesFromDescription('claude', choices) : [];
|
|
104
110
|
}
|
|
105
|
-
function detectApprovalModes(kind, version, env) {
|
|
106
|
-
const key = `${kind}\0${version}\0${env.PATH ?? env.Path ?? ''}`;
|
|
111
|
+
function detectApprovalModes(kind, version, env, command, signal) {
|
|
112
|
+
const key = `${kind}\0${version}\0${command}\0${env.PATH ?? env.Path ?? ''}`;
|
|
107
113
|
let cached = approvalModeCache.get(key);
|
|
108
114
|
if (!cached) {
|
|
109
115
|
cached = (async () => {
|
|
110
116
|
if (kind === 'claude') {
|
|
111
|
-
const help = await commandOutput(
|
|
117
|
+
const help = await commandOutput(command, ['--help'], env, signal);
|
|
112
118
|
return claudeApprovalModesFromHelp(help);
|
|
113
119
|
}
|
|
114
120
|
const directory = await mkdtemp(join(tmpdir(), 'skillshare-codex-schema-'));
|
|
115
121
|
try {
|
|
116
|
-
await commandOutput(
|
|
122
|
+
await commandOutput(command, ['app-server', 'generate-json-schema', '--out', directory, '--experimental'], env, signal);
|
|
117
123
|
const readSchemas = async (folder) => (await Promise.all((await readdir(folder, { withFileTypes: true })).map(async (entry) => entry.isDirectory() ? readSchemas(join(folder, entry.name)) : entry.name.endsWith('.json') ? [await readFile(join(folder, entry.name), 'utf8')] : []))).flat();
|
|
118
124
|
return approvalModesFromDescription(kind, (await readSchemas(directory)).join('\n'));
|
|
119
125
|
}
|
|
120
126
|
finally {
|
|
121
127
|
await rm(directory, { recursive: true, force: true });
|
|
122
128
|
}
|
|
123
|
-
})().catch(() => []);
|
|
129
|
+
})().catch(() => { approvalModeCache.delete(key); return []; });
|
|
124
130
|
approvalModeCache.set(key, cached);
|
|
125
131
|
}
|
|
126
132
|
return cached;
|
|
127
133
|
}
|
|
128
|
-
function commandOutput(command, args, env) {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
output += String(chunk);
|
|
135
|
-
if (output.length > 2 * 1024 * 1024) {
|
|
136
|
-
child.kill();
|
|
137
|
-
reject(new Error('Agent capability output is too large.'));
|
|
138
|
-
}
|
|
139
|
-
});
|
|
140
|
-
child.on('error', error => { clearTimeout(timer); reject(error); });
|
|
141
|
-
child.on('exit', code => { clearTimeout(timer); code === 0 ? resolvePromise(output) : reject(new Error('Agent capability detection failed.')); });
|
|
142
|
-
});
|
|
134
|
+
async function commandOutput(command, args, env, signal) {
|
|
135
|
+
const result = await captureCommand(command, args, env, { maxOutput: 2 * 1024 * 1024, signal });
|
|
136
|
+
if ('output' in result)
|
|
137
|
+
return result.output;
|
|
138
|
+
throw new Error(result.error === 'timeout' ? 'Agent capability detection timed out.'
|
|
139
|
+
: result.error === 'output' ? 'Agent capability output is too large.' : 'Agent capability detection failed.');
|
|
143
140
|
}
|
|
144
141
|
/** Keeps the list within what the server accepts: valid names, no "default", and bounded sizes. */
|
|
145
142
|
function codexModel(id, displayName, levels, fallback) {
|
|
@@ -164,41 +161,50 @@ function cachedCodexModels(cache) {
|
|
|
164
161
|
export async function codexModelList(options = {}) {
|
|
165
162
|
const pending = new Map();
|
|
166
163
|
let nextId = 0;
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
});
|
|
178
|
-
const request = (method, params) => new Promise((resolvePromise, reject) => {
|
|
179
|
-
const id = ++nextId;
|
|
180
|
-
pending.set(id, message => message.error ? reject(new Error(String(message.error.message))) : resolvePromise(message.result ?? {}));
|
|
181
|
-
if (!agent.write(JSON.stringify({ id, method, params })))
|
|
182
|
-
reject(new Error('Codex is not accepting input.'));
|
|
183
|
-
});
|
|
184
|
-
const ask = async () => {
|
|
185
|
-
await request('initialize', { clientInfo: { name: 'skillshare', title: 'Skillshare', version: '0.0.0' }, capabilities: { experimentalApi: true } });
|
|
186
|
-
agent.write(JSON.stringify({ method: 'initialized' }));
|
|
187
|
-
const data = [];
|
|
188
|
-
let cursor;
|
|
189
|
-
for (let page = 0; page < 10; page++) {
|
|
190
|
-
const result = await request('model/list', cursor ? { cursor } : {});
|
|
191
|
-
data.push(...(Array.isArray(result.data) ? result.data : []));
|
|
192
|
-
cursor = typeof result.nextCursor === 'string' && result.nextCursor ? result.nextCursor : undefined;
|
|
193
|
-
if (!cursor)
|
|
194
|
-
break;
|
|
195
|
-
}
|
|
196
|
-
return codexModelsFromList(data);
|
|
197
|
-
};
|
|
198
|
-
let timer;
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
166
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
167
|
+
if (options.signal?.aborted)
|
|
168
|
+
abort();
|
|
169
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
170
|
+
let resolveAbort;
|
|
171
|
+
const aborted = new Promise(resolvePromise => { resolveAbort = () => resolvePromise(null); });
|
|
172
|
+
controller.signal.addEventListener('abort', resolveAbort, { once: true });
|
|
173
|
+
let agent;
|
|
199
174
|
try {
|
|
200
|
-
|
|
201
|
-
|
|
175
|
+
agent = await startDetectionProcess({
|
|
176
|
+
command: options.command ?? 'codex', args: ['app-server'], cwd: homedir(), env: options.env ?? {}, spawnAgent: options.spawnAgent,
|
|
177
|
+
signal: controller.signal,
|
|
178
|
+
onLine: line => {
|
|
179
|
+
try {
|
|
180
|
+
const message = JSON.parse(line);
|
|
181
|
+
if (message.id !== undefined && message.method === undefined)
|
|
182
|
+
pending.get(message.id)?.(message);
|
|
183
|
+
}
|
|
184
|
+
catch { }
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
const request = (method, params) => new Promise((resolvePromise, reject) => {
|
|
188
|
+
const id = ++nextId;
|
|
189
|
+
pending.set(id, message => message.error ? reject(new Error(String(message.error.message))) : resolvePromise(message.result ?? {}));
|
|
190
|
+
if (!agent.write(JSON.stringify({ id, method, params })))
|
|
191
|
+
reject(new Error('Codex is not accepting input.'));
|
|
192
|
+
});
|
|
193
|
+
const ask = async () => {
|
|
194
|
+
await request('initialize', { clientInfo: { name: 'skillshare', title: 'Skillshare', version: '0.0.0' }, capabilities: { experimentalApi: true } });
|
|
195
|
+
agent.write(JSON.stringify({ method: 'initialized' }));
|
|
196
|
+
const data = [];
|
|
197
|
+
let cursor;
|
|
198
|
+
for (let page = 0; page < 10; page++) {
|
|
199
|
+
const result = await request('model/list', cursor ? { cursor } : {});
|
|
200
|
+
data.push(...(Array.isArray(result.data) ? result.data : []));
|
|
201
|
+
cursor = typeof result.nextCursor === 'string' && result.nextCursor ? result.nextCursor : undefined;
|
|
202
|
+
if (!cursor)
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
return codexModelsFromList(data);
|
|
206
|
+
};
|
|
207
|
+
const models = await Promise.race([ask(), agent.exited.then(() => null), aborted]);
|
|
202
208
|
return models && models.length > 0 ? models : null;
|
|
203
209
|
}
|
|
204
210
|
catch {
|
|
@@ -206,7 +212,9 @@ export async function codexModelList(options = {}) {
|
|
|
206
212
|
}
|
|
207
213
|
finally {
|
|
208
214
|
clearTimeout(timer);
|
|
209
|
-
|
|
215
|
+
options.signal?.removeEventListener('abort', abort);
|
|
216
|
+
controller.signal.removeEventListener('abort', resolveAbort);
|
|
217
|
+
await agent?.kill();
|
|
210
218
|
}
|
|
211
219
|
}
|
|
212
220
|
export function parseProfiles(text, home, problems = []) {
|
|
@@ -287,12 +295,130 @@ async function readOptional(path) {
|
|
|
287
295
|
return null;
|
|
288
296
|
}
|
|
289
297
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
298
|
+
/** Retry once to cover a desktop runtime being replaced; only the final, bounded diagnostic reaches the server. */
|
|
299
|
+
export async function detectAgentVersion(kind, env, options = {}) {
|
|
300
|
+
let command = kind;
|
|
301
|
+
let failure = { error: 'missing' };
|
|
302
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
303
|
+
options.signal?.throwIfAborted();
|
|
304
|
+
if (attempt)
|
|
305
|
+
await new Promise(resolvePromise => setTimeout(resolvePromise, options.retryDelayMs ?? 250));
|
|
306
|
+
let result;
|
|
307
|
+
try {
|
|
308
|
+
if (options.probe) {
|
|
309
|
+
command = await resolveAgentCommand(kind, env, { home: options.home, signal: options.signal }).catch(error => {
|
|
310
|
+
if (!options.signal?.aborted)
|
|
311
|
+
return kind;
|
|
312
|
+
throw error;
|
|
313
|
+
});
|
|
314
|
+
result = await options.probe(command, env);
|
|
315
|
+
}
|
|
316
|
+
else
|
|
317
|
+
result = await captureCommand(kind, ['--version'], env, { signal: options.signal, home: options.home,
|
|
318
|
+
maxOutput: 16_000, onCommand: resolved => { command = resolved; } });
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
result = probeStartFailure(error);
|
|
322
|
+
}
|
|
323
|
+
options.signal?.throwIfAborted();
|
|
324
|
+
if ('output' in result)
|
|
325
|
+
return { command, output: result.output };
|
|
326
|
+
failure = result;
|
|
327
|
+
}
|
|
328
|
+
const code = typeof failure.code === 'number' ? String(failure.code)
|
|
329
|
+
: typeof failure.code === 'string' && /^[A-Z0-9_]{1,30}$/.test(failure.code) ? failure.code : 'unknown error';
|
|
330
|
+
const reason = failure.error === 'missing' ? 'executable not found'
|
|
331
|
+
: failure.error === 'timeout' ? 'timed out after 15 seconds'
|
|
332
|
+
: failure.error === 'exit' ? `exit code ${code}`
|
|
333
|
+
: failure.error === 'output' ? 'version output exceeded the size limit' : `could not start: ${code}`;
|
|
334
|
+
return { command, output: null, failure: `${kind} --version failed (${reason}). Check the executable and PATH.` };
|
|
335
|
+
}
|
|
336
|
+
export function probeAgentVersion(command, env, options = {}) {
|
|
337
|
+
return captureCommand(command, ['--version'], env, { ...options, maxOutput: 16_000 });
|
|
338
|
+
}
|
|
339
|
+
function probeStartFailure(error) {
|
|
340
|
+
const code = error?.code;
|
|
341
|
+
return { error: code === 'ENOENT' ? 'missing' : 'start', code };
|
|
342
|
+
}
|
|
343
|
+
/** Bound lookup, startup and stdout together; kill the complete shim/agent tree before allowing a retry. */
|
|
344
|
+
async function captureCommand(command, args, env, options) {
|
|
345
|
+
const controller = new AbortController();
|
|
346
|
+
let timedOut = false;
|
|
347
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
348
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
349
|
+
if (options.signal?.aborted)
|
|
350
|
+
abort();
|
|
351
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, options.timeoutMs ?? 15_000);
|
|
352
|
+
try {
|
|
353
|
+
const agent = await startDetectionProcess({ command, args, cwd: homedir(), env, signal: controller.signal,
|
|
354
|
+
spawnAgent: options.spawnAgent, onLine: () => { },
|
|
355
|
+
resolveCommand: options.spawnAgent ? undefined : async (name, _environment, { signal } = {}) => {
|
|
356
|
+
const resolved = await resolveAgentCommand(name, env, { home: options.home, signal });
|
|
357
|
+
options.onCommand?.(resolved);
|
|
358
|
+
return resolved;
|
|
359
|
+
},
|
|
360
|
+
});
|
|
361
|
+
return await new Promise(resolvePromise => {
|
|
362
|
+
let output = '';
|
|
363
|
+
let finished = false;
|
|
364
|
+
const finish = async (result, kill = false) => {
|
|
365
|
+
if (finished)
|
|
366
|
+
return;
|
|
367
|
+
finished = true;
|
|
368
|
+
controller.signal.removeEventListener('abort', stopped);
|
|
369
|
+
if (kill)
|
|
370
|
+
await agent.kill().catch(() => { });
|
|
371
|
+
resolvePromise(result);
|
|
372
|
+
};
|
|
373
|
+
const stopped = () => { void finish(timedOut ? { error: 'timeout' } : { error: 'start', code: 'ABORT_ERR' }, true); };
|
|
374
|
+
controller.signal.addEventListener('abort', stopped, { once: true });
|
|
375
|
+
agent.child.stdout?.on('data', chunk => {
|
|
376
|
+
if (finished)
|
|
377
|
+
return;
|
|
378
|
+
const text = String(chunk);
|
|
379
|
+
if (output.length + text.length > options.maxOutput) {
|
|
380
|
+
agent.child.stdout?.pause();
|
|
381
|
+
void finish({ error: 'output' }, true);
|
|
382
|
+
}
|
|
383
|
+
else
|
|
384
|
+
output += text;
|
|
385
|
+
});
|
|
386
|
+
agent.child.once('error', error => { void finish(probeStartFailure(error), true); });
|
|
387
|
+
// `exit` can precede the final stdout chunks; only `close` confirms all captured output has drained.
|
|
388
|
+
void agent.closed.then(async () => {
|
|
389
|
+
const code = await agent.exited;
|
|
390
|
+
void finish(code === 0 ? { output } : { error: 'exit', code: code ?? undefined });
|
|
391
|
+
});
|
|
392
|
+
agent.child.stdin?.end();
|
|
393
|
+
if (controller.signal.aborted)
|
|
394
|
+
stopped();
|
|
296
395
|
});
|
|
297
|
-
}
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
return timedOut ? { error: 'timeout' } : probeStartFailure(error);
|
|
399
|
+
}
|
|
400
|
+
finally {
|
|
401
|
+
clearTimeout(timer);
|
|
402
|
+
options.signal?.removeEventListener('abort', abort);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/** Filesystem operations may finish late; the startup path checks cancellation again before it can spawn. */
|
|
406
|
+
async function startDetectionProcess(options) {
|
|
407
|
+
const { signal } = options;
|
|
408
|
+
signal?.throwIfAborted();
|
|
409
|
+
let abort;
|
|
410
|
+
const aborted = new Promise((_, reject) => { abort = () => reject(signal?.reason); });
|
|
411
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
412
|
+
try {
|
|
413
|
+
return await Promise.race([startAgentProcess(options).then(agent => {
|
|
414
|
+
if (signal?.aborted) {
|
|
415
|
+
void agent.kill();
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
}
|
|
418
|
+
return agent;
|
|
419
|
+
}), aborted]);
|
|
420
|
+
}
|
|
421
|
+
finally {
|
|
422
|
+
signal?.removeEventListener('abort', abort);
|
|
423
|
+
}
|
|
298
424
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import filesystem from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
function environmentValue(env, name) {
|
|
5
|
+
// Node's Windows spawn keeps the first case-insensitive key in lexicographic order.
|
|
6
|
+
const key = Object.keys(env).sort().find(key => key.toLowerCase() === name.toLowerCase());
|
|
7
|
+
return key === undefined ? undefined : env[key];
|
|
8
|
+
}
|
|
9
|
+
async function file(path, signal) {
|
|
10
|
+
signal?.throwIfAborted();
|
|
11
|
+
try {
|
|
12
|
+
const info = await filesystem.stat(path);
|
|
13
|
+
signal?.throwIfAborted();
|
|
14
|
+
return info.isFile();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Resolve afresh for every launch: the desktop app replaces its copied runtime directories during updates. */
|
|
22
|
+
export async function resolveAgentCommand(command, env = process.env, options = {}) {
|
|
23
|
+
const { signal } = options;
|
|
24
|
+
signal?.throwIfAborted();
|
|
25
|
+
if ((options.platform ?? process.platform) !== 'win32' || /[\\/:]/.test(command))
|
|
26
|
+
return command;
|
|
27
|
+
const configuredExtensions = (environmentValue(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(part => /^\.[a-z0-9]+$/i.test(part));
|
|
28
|
+
const extensions = command.includes('.') ? ['', ...configuredExtensions] : configuredExtensions;
|
|
29
|
+
const directories = (environmentValue(env, 'PATH') ?? '').split(';').map(part => part.trim().replace(/^"(.*)"$/, '$1'))
|
|
30
|
+
// Do not discover commands in the listener's working directory or in relative PATH entries.
|
|
31
|
+
.filter(part => part.length > 0 && isAbsolute(part));
|
|
32
|
+
// Match cross-spawn's extension lookup first, then its extensionless/shebang-wrapper fallback.
|
|
33
|
+
const paths = directories.flatMap(directory => extensions.map(extension => join(directory, command + extension)));
|
|
34
|
+
if (!extensions.includes(''))
|
|
35
|
+
paths.push(...directories.map(directory => join(directory, command)));
|
|
36
|
+
for (const path of paths) {
|
|
37
|
+
if (await file(path, signal)) {
|
|
38
|
+
signal?.throwIfAborted();
|
|
39
|
+
return path;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (/^codex(?:\.exe)?$/i.test(command)) {
|
|
43
|
+
const local = environmentValue(env, 'LOCALAPPDATA') ?? join(options.home ?? homedir(), 'AppData', 'Local');
|
|
44
|
+
const root = join(local, 'OpenAI', 'Codex', 'bin');
|
|
45
|
+
try {
|
|
46
|
+
const entries = await filesystem.readdir(root, { withFileTypes: true });
|
|
47
|
+
signal?.throwIfAborted();
|
|
48
|
+
const candidates = [];
|
|
49
|
+
for (const entry of entries.filter(entry => entry.isDirectory() && /^[0-9a-f]{16}$/i.test(entry.name))) {
|
|
50
|
+
const directory = join(root, entry.name);
|
|
51
|
+
const executable = join(directory, 'codex.exe');
|
|
52
|
+
try {
|
|
53
|
+
const binary = await filesystem.lstat(executable);
|
|
54
|
+
signal?.throwIfAborted();
|
|
55
|
+
if (!binary.isFile())
|
|
56
|
+
continue;
|
|
57
|
+
const folder = await filesystem.stat(directory);
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
candidates.push({ executable, modified: folder.mtimeMs });
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
candidates.sort((a, b) => b.modified - a.modified || a.executable.localeCompare(b.executable));
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
if (candidates[0])
|
|
68
|
+
return candidates[0].executable;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
signal?.throwIfAborted();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
signal?.throwIfAborted();
|
|
75
|
+
throw Object.assign(new Error('Agent executable was not found.'), { code: 'ENOENT' });
|
|
76
|
+
}
|
package/dist/agents-process.js
CHANGED
|
@@ -1,32 +1,77 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
2
4
|
import { createInterface } from 'node:readline';
|
|
3
|
-
import
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { resolveAgentCommand } from './agents-executable.js';
|
|
4
7
|
/**
|
|
5
8
|
* Starts an agent that speaks newline-delimited JSON on stdio. Tokens go through the environment only. A separate
|
|
6
9
|
* process group lets stopping the agent also stop the shell commands it runs.
|
|
7
10
|
*/
|
|
8
|
-
export function startAgentProcess(options) {
|
|
11
|
+
export async function startAgentProcess(options) {
|
|
9
12
|
const posix = process.platform !== 'win32';
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
const env = { ...process.env, ...options.env };
|
|
14
|
+
options.signal?.throwIfAborted();
|
|
15
|
+
// Resolve for every new process: desktop updates can replace Codex's directory while the listener stays running.
|
|
16
|
+
const resolveCommand = options.resolveCommand ?? (options.spawnAgent ? undefined : resolveAgentCommand);
|
|
17
|
+
let command = resolveCommand ? await resolveCommand(options.command, env, { signal: options.signal }) : options.command;
|
|
18
|
+
let args = options.args;
|
|
19
|
+
// Extensionless wrappers use an interpreter; resolve it asynchronously instead of cross-spawn's synchronous PATH walk.
|
|
20
|
+
if (!posix && !options.spawnAgent) {
|
|
21
|
+
for (let depth = 0; !/\.(?:exe|com|cmd|bat)$/i.test(command); depth++) {
|
|
22
|
+
if (depth === 4)
|
|
23
|
+
throw Object.assign(new Error('The agent interpreter could not be resolved.'), { code: 'ENOEXEC' });
|
|
24
|
+
const file = await open(command, 'r');
|
|
25
|
+
let firstLine;
|
|
26
|
+
try {
|
|
27
|
+
const buffer = Buffer.alloc(150);
|
|
28
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
29
|
+
firstLine = buffer.subarray(0, bytesRead).toString().split(/\r?\n/, 1)[0] ?? '';
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await file.close();
|
|
33
|
+
}
|
|
34
|
+
const parts = /^#!\s*(.+)$/.exec(firstLine)?.[1]?.trim().split(/\s+/);
|
|
35
|
+
let interpreter = parts?.shift()?.split(/[\\/]/).at(-1);
|
|
36
|
+
if (interpreter === 'env')
|
|
37
|
+
interpreter = parts?.shift();
|
|
38
|
+
if (!interpreter)
|
|
39
|
+
throw Object.assign(new Error('The agent executable has no supported interpreter.'), { code: 'ENOEXEC' });
|
|
40
|
+
args = [...parts ?? [], command, ...args];
|
|
41
|
+
command = await resolveAgentCommand(interpreter, env, { signal: options.signal });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
options.signal?.throwIfAborted();
|
|
45
|
+
// Batch shims need cmd, but no synchronous filesystem lookup or interpreter discovery belongs on the listener thread.
|
|
46
|
+
const batch = !posix && !options.spawnAgent && /\.(?:cmd|bat)$/i.test(command);
|
|
47
|
+
if (batch) {
|
|
48
|
+
const doubleEscape = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(command);
|
|
49
|
+
const shellCommand = [command.replace(BATCH_META, '^$1'), ...args.map(arg => batchArgument(arg, doubleEscape))].join(' ');
|
|
50
|
+
args = ['/d', '/s', '/v:off', '/c', `"${shellCommand}"`];
|
|
51
|
+
command = join(env.SystemRoot ?? env.SYSTEMROOT ?? 'C:\\Windows', 'System32', 'cmd.exe');
|
|
52
|
+
}
|
|
53
|
+
const child = (options.spawnAgent ?? spawn)(command, args, {
|
|
54
|
+
cwd: options.cwd, env, stdio: ['pipe', 'pipe', 'pipe'],
|
|
14
55
|
detached: posix, windowsHide: true,
|
|
56
|
+
...(batch ? { windowsVerbatimArguments: true } : {}),
|
|
15
57
|
});
|
|
16
58
|
let stderr = '';
|
|
17
59
|
child.stderr?.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
|
|
18
60
|
child.stdin?.on('error', () => { });
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
61
|
+
const lines = child.stdout ? createInterface({ input: child.stdout, crlfDelay: Infinity }) : undefined;
|
|
62
|
+
lines?.on('line', line => { if (line.trim())
|
|
63
|
+
options.onLine(line); });
|
|
64
|
+
let running = true;
|
|
22
65
|
const exited = new Promise(resolve => {
|
|
23
|
-
child.once('error', error => { stderr = (stderr + '\n' + error.message).slice(-4000); resolve(null); });
|
|
24
|
-
child.once('exit', code => resolve(code));
|
|
66
|
+
child.once('error', error => { running = false; stderr = (stderr + '\n' + error.message).slice(-4000); resolve(null); });
|
|
67
|
+
child.once('exit', code => { running = false; resolve(code); });
|
|
25
68
|
});
|
|
69
|
+
const closed = new Promise(resolve => child.once('close', () => resolve()));
|
|
26
70
|
let killing = null;
|
|
27
71
|
return {
|
|
28
72
|
child,
|
|
29
73
|
exited,
|
|
74
|
+
closed,
|
|
30
75
|
stderrTail: () => stderr.trim().split(/\r?\n/).filter(line => line.trim()).slice(-3).join(' ').slice(-300),
|
|
31
76
|
// write(false) signals backpressure, not rejection: the frame is already buffered and must not be resent.
|
|
32
77
|
write: line => {
|
|
@@ -42,26 +87,90 @@ export function startAgentProcess(options) {
|
|
|
42
87
|
},
|
|
43
88
|
kill() {
|
|
44
89
|
killing ??= (async () => {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
90
|
+
try {
|
|
91
|
+
if (posix) {
|
|
92
|
+
const signal = (sig) => {
|
|
93
|
+
try {
|
|
94
|
+
child.pid ? process.kill(-child.pid, sig) : child.kill(sig);
|
|
95
|
+
}
|
|
96
|
+
catch { }
|
|
97
|
+
};
|
|
98
|
+
child.stdin?.end();
|
|
99
|
+
signal('SIGTERM');
|
|
100
|
+
// The agent may exit while descendants are still flushing their data, even with no inherited stdio.
|
|
101
|
+
// Give the whole group the grace period; the parent's exit alone must not trigger SIGKILL.
|
|
102
|
+
const stopped = child.pid ? await waitForProcessGroupExit(child.pid) : await bounded(exited, 5000);
|
|
103
|
+
if (!stopped)
|
|
104
|
+
signal('SIGKILL');
|
|
105
|
+
}
|
|
106
|
+
else if (running && child.pid) {
|
|
107
|
+
// Kill the complete tree in one operation. Gracefully ending cmd first loses the descendant PIDs.
|
|
108
|
+
const killer = spawn(join(env.SystemRoot ?? env.SYSTEMROOT ?? 'C:\\Windows', 'System32', 'taskkill.exe'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
109
|
+
const killed = new Promise(resolve => { killer.once('error', () => resolve()); killer.once('close', () => resolve()); });
|
|
110
|
+
if (!await bounded(killed, 5000))
|
|
111
|
+
killer.kill();
|
|
112
|
+
}
|
|
113
|
+
if (running) {
|
|
114
|
+
try {
|
|
115
|
+
child.kill('SIGKILL');
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
54
118
|
}
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
119
|
+
await bounded(exited, 1000);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
lines?.close();
|
|
123
|
+
child.stdin?.destroy();
|
|
124
|
+
child.stdout?.destroy();
|
|
125
|
+
child.stderr?.destroy();
|
|
126
|
+
}
|
|
63
127
|
})();
|
|
64
128
|
return killing;
|
|
65
129
|
},
|
|
66
130
|
};
|
|
67
131
|
}
|
|
132
|
+
async function waitForProcessGroupExit(pid) {
|
|
133
|
+
const deadline = performance.now() + 5000;
|
|
134
|
+
while (true) {
|
|
135
|
+
try {
|
|
136
|
+
process.kill(-pid, 0);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (error.code === 'ESRCH')
|
|
140
|
+
return true;
|
|
141
|
+
// An inaccessible group is not proof that its processes have exited. Keep the wait bounded.
|
|
142
|
+
}
|
|
143
|
+
const remaining = deadline - performance.now();
|
|
144
|
+
if (remaining <= 0)
|
|
145
|
+
return false;
|
|
146
|
+
await delay(Math.min(50, remaining));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function bounded(promise, milliseconds) {
|
|
150
|
+
let timer;
|
|
151
|
+
try {
|
|
152
|
+
return await Promise.race([promise.then(() => true), new Promise(resolve => { timer = setTimeout(() => resolve(false), milliseconds); })]);
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/* Batch escaping adapted from cross-spawn 7.0.6, MIT License.
|
|
159
|
+
* Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
|
|
160
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
161
|
+
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
|
162
|
+
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
|
|
163
|
+
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
164
|
+
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
|
165
|
+
* the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
|
166
|
+
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
167
|
+
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
168
|
+
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
169
|
+
* OTHER DEALINGS IN THE SOFTWARE.
|
|
170
|
+
*/
|
|
171
|
+
const BATCH_META = /([()\][%!^"`<>&|;, *?])/g;
|
|
172
|
+
function batchArgument(argument, doubleEscape) {
|
|
173
|
+
const quoted = `"${argument.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"').replace(/(?=(\\+?)?)\1$/, '$1$1')}"`;
|
|
174
|
+
const escaped = quoted.replace(BATCH_META, '^$1');
|
|
175
|
+
return doubleEscape ? escaped.replace(BATCH_META, '^$1') : escaped;
|
|
176
|
+
}
|
package/dist/agents-service.js
CHANGED
|
@@ -317,9 +317,11 @@ export async function uninstallService(environment) {
|
|
|
317
317
|
await environment.run('systemctl', ['--user', 'daemon-reload']);
|
|
318
318
|
return existed || wasRunning;
|
|
319
319
|
}
|
|
320
|
-
export async function detectServiceAgents(appDir) {
|
|
320
|
+
export async function detectServiceAgents(appDir, signal) {
|
|
321
|
+
signal?.throwIfAborted();
|
|
321
322
|
const warnings = await refreshServicePath();
|
|
322
|
-
const detected = await detectAgents();
|
|
323
|
+
const detected = await detectAgents({ signal });
|
|
324
|
+
signal?.throwIfAborted();
|
|
323
325
|
detected.problems.unshift(...warnings);
|
|
324
326
|
const report = {
|
|
325
327
|
checkedAt: new Date().toISOString(), path: process.env.PATH ?? '',
|
package/dist/agents.js
CHANGED
|
@@ -143,7 +143,7 @@ export async function runAgentsCommand(client, args, flags, appDirectory, teamsW
|
|
|
143
143
|
try {
|
|
144
144
|
result = await listen({
|
|
145
145
|
client, listenerId, name: flags.name, workdir, maxConcurrency: max, signal: abort.signal, onProgress: console.log, service,
|
|
146
|
-
detect: service ?
|
|
146
|
+
detect: service ? signal => detectServiceAgents(appDirectory, signal) : undefined,
|
|
147
147
|
updater: worker ? { currentVersion: readCliVersion(), prepare: version => installVersion(appDirectory, version) } : undefined,
|
|
148
148
|
});
|
|
149
149
|
}
|
|
@@ -242,7 +242,9 @@ export function renderDetected(listenerId, server, detected) {
|
|
|
242
242
|
return lines.join('\n');
|
|
243
243
|
}
|
|
244
244
|
export async function listen(options) {
|
|
245
|
-
const
|
|
245
|
+
const detectionAbort = new AbortController();
|
|
246
|
+
const detectionSignal = AbortSignal.any([options.signal, detectionAbort.signal]);
|
|
247
|
+
const detect = () => options.detect ? options.detect(detectionSignal) : detectAgents({ signal: detectionSignal });
|
|
246
248
|
const codex = createCodexDriver({ clientVersion: readCliVersion() });
|
|
247
249
|
const claude = createClaudeDriver();
|
|
248
250
|
const driver = options.driver ?? (start => start.configuration.agent === 'codex' ? codex : claude);
|
|
@@ -257,7 +259,11 @@ export async function listen(options) {
|
|
|
257
259
|
const imageRoot = options.imageDirectory ?? join(tmpdir(), 'skillshare-agents');
|
|
258
260
|
let detected = await detect();
|
|
259
261
|
let registeredFingerprint = '';
|
|
260
|
-
|
|
262
|
+
const redetectMs = options.redetectMs ?? 5 * 60_000;
|
|
263
|
+
let nextDetectionAt = now() + redetectMs;
|
|
264
|
+
let detecting;
|
|
265
|
+
let pendingDetection;
|
|
266
|
+
let detectionActive = true;
|
|
261
267
|
let failures = 0;
|
|
262
268
|
// A downloaded update waits until no turn runs; a failed download is tried again later.
|
|
263
269
|
let updateReady = null;
|
|
@@ -265,6 +271,22 @@ export async function listen(options) {
|
|
|
265
271
|
let updateRetryAt = 0;
|
|
266
272
|
let updateMentioned = '';
|
|
267
273
|
let result = 'stopped';
|
|
274
|
+
function refreshDetection() {
|
|
275
|
+
if (detecting || now() < nextDetectionAt)
|
|
276
|
+
return;
|
|
277
|
+
// Detection can outlast the server's presence/lease timeout. Poll using the last complete snapshot meanwhile.
|
|
278
|
+
detecting = Promise.resolve().then(detect).then(next => {
|
|
279
|
+
if (!detectionActive || options.signal.aborted)
|
|
280
|
+
return;
|
|
281
|
+
pendingDetection = next;
|
|
282
|
+
nextDetectionAt = now() + redetectMs;
|
|
283
|
+
}).catch(() => {
|
|
284
|
+
if (!detectionActive || options.signal.aborted)
|
|
285
|
+
return;
|
|
286
|
+
nextDetectionAt = now() + Math.max(1000, Math.min(redetectMs, 5000));
|
|
287
|
+
log('! Agent detection failed. Keeping the last known capabilities and trying again shortly.');
|
|
288
|
+
}).finally(() => { detecting = undefined; });
|
|
289
|
+
}
|
|
268
290
|
function considerUpdate(version) {
|
|
269
291
|
const current = options.updater?.currentVersion ?? readCliVersion();
|
|
270
292
|
// Only a plain release number; npm would read anything else as a git, URL or file package spec.
|
|
@@ -290,13 +312,15 @@ export async function listen(options) {
|
|
|
290
312
|
}
|
|
291
313
|
const capabilities = () => ({ ...detected.capabilities, sessionApprovals: true, lockdown: true });
|
|
292
314
|
async function register() {
|
|
293
|
-
const
|
|
294
|
-
const
|
|
315
|
+
const snapshot = detected;
|
|
316
|
+
const registeredCapabilities = capabilities();
|
|
317
|
+
const fingerprint = JSON.stringify(registeredCapabilities);
|
|
318
|
+
const requiresApprovalDefaults = Boolean(registeredCapabilities.defaultApprovalMode || registeredCapabilities.profiles.some(profile => profile.defaultApprovalMode));
|
|
295
319
|
// A dedicated route rejects an older server before it can overwrite restrictions or dispatch queued work.
|
|
296
320
|
const path = `${root}/listeners/${options.listenerId}${requiresApprovalDefaults ? '/register' : ''}`;
|
|
297
321
|
const registered = await send(options.client, 'PUT', path, {
|
|
298
322
|
name: options.name ?? hostname(), host: hostname(), os: platform(), cliVersion: readCliVersion(), maxConcurrency: options.maxConcurrency,
|
|
299
|
-
capabilities:
|
|
323
|
+
capabilities: registeredCapabilities, service: options.service === true, autoUpdate: options.updater !== undefined,
|
|
300
324
|
}, options.signal).catch(error => {
|
|
301
325
|
if (requiresApprovalDefaults && error instanceof AgentsHttpError && error.status === 404)
|
|
302
326
|
throw new Error('Update Skillshare before connecting this listener; this server does not support safe approval-default registration.');
|
|
@@ -305,9 +329,9 @@ export async function listen(options) {
|
|
|
305
329
|
if (requiresApprovalDefaults && (registered?.approvalDefaultsVersion ?? 0) < 1)
|
|
306
330
|
throw new Error('Update Skillshare before using migrated approval defaults; this server cannot acknowledge them safely.');
|
|
307
331
|
registeredFingerprint = fingerprint;
|
|
308
|
-
for (const problem of
|
|
332
|
+
for (const problem of snapshot.problems)
|
|
309
333
|
log(`! ${problem}`);
|
|
310
|
-
log(`Listening as "${registered.name}" with ${registered.effectiveConcurrency} slot(s): ${describe(
|
|
334
|
+
log(`Listening as "${registered.name}" with ${registered.effectiveConcurrency} slot(s): ${describe(snapshot)}. Start sessions and choose routes under Connected agents on ${options.client.baseUrl}.`);
|
|
311
335
|
}
|
|
312
336
|
/** Posts a batch of session events: a rejected lease means the server moved on and the agent must stop. */
|
|
313
337
|
function uploader(sessionId, leaseToken) {
|
|
@@ -416,10 +440,11 @@ export async function listen(options) {
|
|
|
416
440
|
break;
|
|
417
441
|
}
|
|
418
442
|
try {
|
|
419
|
-
if (
|
|
420
|
-
detected =
|
|
421
|
-
|
|
443
|
+
if (pendingDetection) {
|
|
444
|
+
detected = pendingDetection;
|
|
445
|
+
pendingDetection = undefined;
|
|
422
446
|
}
|
|
447
|
+
refreshDetection();
|
|
423
448
|
if (registeredFingerprint !== JSON.stringify(capabilities()))
|
|
424
449
|
await register();
|
|
425
450
|
const polledAt = now();
|
|
@@ -461,6 +486,8 @@ export async function listen(options) {
|
|
|
461
486
|
}
|
|
462
487
|
}
|
|
463
488
|
finally {
|
|
489
|
+
detectionActive = false;
|
|
490
|
+
detectionAbort.abort();
|
|
464
491
|
// Closing reports each session as closed, so the server knows at once that the next message must resume it.
|
|
465
492
|
await Promise.all([...sessions.values()].map(runner => runner.close()));
|
|
466
493
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quadient/skillshare",
|
|
3
|
-
"version": "1.19.
|
|
3
|
+
"version": "1.19.2",
|
|
4
4
|
"description": "Skillshare CLI for installing and publishing Quadient skills",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && node -e \"require('node:fs').copyFileSync('page-browser-client.js', 'dist/page-browser-client.js')\"",
|
|
17
17
|
"start": "node ./dist/index.js",
|
|
18
18
|
"prepublishOnly": "npm run build",
|
|
19
|
-
"test": "tsx --test session-auth.test.ts cli-args.test.ts install-files.test.ts removed-skills.test.ts output.test.ts pages.test.ts page-links.test.ts pages-secrets.test.ts pages-comments.test.ts news.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-detection.test.ts agents-lockdown.test.ts agents-approvals.test.ts agents-native-forms.test.ts agents-delivery.test.ts agents-request-upload.test.ts agents-update.test.ts login-callback.test.ts"
|
|
19
|
+
"test": "tsx --test session-auth.test.ts cli-args.test.ts install-files.test.ts removed-skills.test.ts output.test.ts pages.test.ts page-links.test.ts pages-secrets.test.ts pages-comments.test.ts news.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-detection.test.ts agents-process.test.ts agents-probe.test.ts agents-lockdown.test.ts agents-approvals.test.ts agents-native-forms.test.ts agents-delivery.test.ts agents-request-upload.test.ts agents-update.test.ts login-callback.test.ts"
|
|
20
20
|
},
|
|
21
21
|
"publishConfig": {
|
|
22
22
|
"access": "public"
|