@quadient/skillshare 1.18.1 → 1.19.1

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 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
 
@@ -100,7 +108,7 @@ skillshare teams login
100
108
  skillshare teams status
101
109
  skillshare teams test
102
110
  skillshare teams watch
103
- skillshare teams access fullAccess
111
+ skillshare teams access limitedAccess # allow writes except editing/deleting messages
104
112
  skillshare teams upload ./report.pdf
105
113
  skillshare teams download '<file-webUrl-or-download-link>' --output ./report.pdf
106
114
  skillshare teams access readOnly
@@ -5,7 +5,7 @@ import { homedir, tmpdir } from 'node:os';
5
5
  import { dirname, join, resolve } from 'node:path';
6
6
  import { startAgentProcess } from './agents-process.js';
7
7
  import { nativeForm, nativeFormResponse } from './agents-forms.js';
8
- import { CLAUDE_SANDBOX_TOOLS, DEFAULT, SANDBOX_NOTE, clip, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, boundedSessionRequest, sessionWorkdir, validateSessionWorkdir, } from './agents-session.js';
8
+ import { CLAUDE_LOCKDOWN_DENIED_TOOLS, CLAUDE_SANDBOX_TOOLS, DEFAULT, LOCKDOWN_NOTE, SANDBOX_NOTE, clip, isLockedDown, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, boundedSessionRequest, sessionWorkdir, validateSessionWorkdir, } from './agents-session.js';
9
9
  /**
10
10
  * Claude Code in print mode with stream-json in both directions: the same protocol the Agent SDK speaks, but against the
11
11
  * user's own claude install, so their login and settings apply. MCP config and the session's instructions are passed per
@@ -27,12 +27,15 @@ export function claudeContent(message) {
27
27
  }
28
28
  /** The session's instructions for Claude Code's system prompt; they go in a file, because newlines do not survive cmd.exe on Windows. */
29
29
  export function claudeInstructions(context) {
30
- return [context.start.instructions?.trim(), isSandboxed(context.start.configuration) ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
30
+ const note = isLockedDown(context.start) ? LOCKDOWN_NOTE : isSandboxed(context.start.configuration) ? SANDBOX_NOTE : undefined;
31
+ return [context.start.instructions?.trim(), note].filter(Boolean).join('\n\n');
31
32
  }
32
33
  export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPath) {
33
34
  const { start } = context;
34
35
  const sandbox = isSandboxed(start.configuration);
35
36
  const servers = start.mcpServers ?? [];
37
+ if (isLockedDown(start))
38
+ return claudeLockdownArgs(start, servers, mcpConfigPath, instructionsPath);
36
39
  // Replayed user messages tell when Claude Code took a message, which is how a steered message is known to have joined the turn.
37
40
  const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--replay-user-messages',
38
41
  ...(sandbox
@@ -59,6 +62,27 @@ export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPat
59
62
  args.push('--permission-prompt-tool', 'stdio');
60
63
  return [...args, ...(context.profile?.args ?? [])];
61
64
  }
65
+ /**
66
+ * Only the session's MCP servers (--strict-mcp-config ignores the user's own) and only their tools: dontAsk denies everything else
67
+ * without asking, and the built-in tools are denied by name as well. Local profiles and user settings files are not applied.
68
+ */
69
+ function claudeLockdownArgs(start, servers, mcpConfigPath, instructionsPath) {
70
+ const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--replay-user-messages',
71
+ '--permission-mode', 'dontAsk', '--strict-mcp-config',
72
+ '--allowedTools', ...servers.map((server, index) => `mcp__${mcpServerName(server, index)}`),
73
+ '--disallowedTools', ...CLAUDE_LOCKDOWN_DENIED_TOOLS];
74
+ if (start.configuration.model !== DEFAULT)
75
+ args.push('--model', start.configuration.model);
76
+ if (start.configuration.reasoning !== DEFAULT)
77
+ args.push('--effort', start.configuration.reasoning);
78
+ if (mcpConfigPath)
79
+ args.push('--mcp-config', mcpConfigPath);
80
+ if (instructionsPath)
81
+ args.push('--append-system-prompt-file', instructionsPath);
82
+ if (start.resumeThreadId)
83
+ args.push('--resume', start.resumeThreadId);
84
+ return args;
85
+ }
62
86
  export function claudeMcpConfig(servers) {
63
87
  return JSON.stringify({
64
88
  mcpServers: Object.fromEntries(servers.map((server, index) => [mcpServerName(server, index),
@@ -145,35 +169,51 @@ class ClaudeDriver {
145
169
  early = [];
146
170
  costSoFar = 0;
147
171
  closing = false;
172
+ startup = new AbortController();
148
173
  permissions = new Map();
149
174
  constructor(context, options) {
150
175
  this.context = context;
151
176
  this.options = options;
152
177
  }
153
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() {
154
189
  await validateSessionWorkdir(this.context);
190
+ this.startup.signal.throwIfAborted();
155
191
  const servers = this.context.start.mcpServers ?? [];
156
192
  const instructions = claudeInstructions(this.context);
157
193
  let mcpConfig;
158
194
  let instructionsFile;
159
195
  let settingsFile;
160
196
  const workdir = sessionWorkdir(this.context);
161
- const shadowed = servers.length > 0 ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
197
+ const shadowed = servers.length > 0 && !isLockedDown(this.context.start) ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
162
198
  if (servers.length > 0 || instructions)
163
199
  this.directory = await mkdtemp(join(tmpdir(), 'skillshare-session-'));
200
+ this.startup.signal.throwIfAborted();
164
201
  if (servers.length > 0) {
165
202
  mcpConfig = join(this.directory, 'mcp.json');
166
203
  await writeFile(mcpConfig, claudeMcpConfig(servers), { mode: 0o600 });
204
+ this.startup.signal.throwIfAborted();
167
205
  }
168
206
  if (shadowed.length > 0) {
169
207
  settingsFile = join(this.directory, 'settings.json');
170
208
  await writeFile(settingsFile, claudeSettings(shadowed), { mode: 0o600 });
209
+ this.startup.signal.throwIfAborted();
171
210
  }
172
211
  if (instructions) {
173
212
  instructionsFile = join(this.directory, 'instructions.md');
174
213
  await writeFile(instructionsFile, instructions, { mode: 0o600 });
214
+ this.startup.signal.throwIfAborted();
175
215
  }
176
- this.process = startAgentProcess({
216
+ this.process = await startAgentProcess({
177
217
  command: this.options.command ?? 'claude',
178
218
  args: claudeArgs(this.context, mcpConfig, instructionsFile, settingsFile),
179
219
  cwd: workdir,
@@ -182,11 +222,17 @@ class ClaudeDriver {
182
222
  // Claude Code holds suggestions back when the account nears a rate limit; the user can still turn them off with this variable.
183
223
  CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION: process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION ?? 'true',
184
224
  // Claude Code lets auto-memory write to its own folder even under the read-only allowlist; a sandboxed session writes nothing.
185
- ...(isSandboxed(this.context.start.configuration) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
225
+ ...(isSandboxed(this.context.start.configuration) || isLockedDown(this.context.start) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
186
226
  },
187
227
  spawnAgent: this.options.spawnAgent,
228
+ resolveCommand: this.options.resolveCommand,
229
+ signal: this.startup.signal,
188
230
  onLine: line => this.receive(line),
189
231
  });
232
+ if (this.closing) {
233
+ await this.process.kill();
234
+ this.startup.signal.throwIfAborted();
235
+ }
190
236
  void this.process.exited.then(code => this.onExit(code));
191
237
  // Claude Code answers initialize once it is ready, which turns a bad install or a bad flag into a clear start failure.
192
238
  // Suggestions come after a turn's result; versions without them ignore the field.
@@ -254,10 +300,18 @@ class ClaudeDriver {
254
300
  }
255
301
  async close() {
256
302
  this.closing = true;
303
+ this.startup.abort();
257
304
  this.clearRequests();
258
305
  await this.process?.kill();
259
- if (this.directory)
260
- await rm(this.directory, { recursive: true, force: true }).catch(() => { });
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;
261
315
  }
262
316
  control(request) {
263
317
  const requestId = randomUUID();
@@ -1,7 +1,7 @@
1
1
  import { startAgentProcess } from './agents-process.js';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { nativeForm, nativeFormResponse } from './agents-forms.js';
4
- import { DEFAULT, SANDBOX_NOTE, clip, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, boundedSessionRequest, sessionWorkdir, validateSessionWorkdir, } from './agents-session.js';
4
+ import { DEFAULT, LOCKDOWN_NOTE, SANDBOX_NOTE, clip, isLockedDown, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, boundedSessionRequest, sessionWorkdir, validateSessionWorkdir, } from './agents-session.js';
5
5
  /** Profile arguments that make sense for a long-running app-server; anything else belongs to codex exec only. */
6
6
  export function codexConfigArgs(args) {
7
7
  const kept = [];
@@ -48,6 +48,18 @@ export function codexThreadParams(context, shadowed) {
48
48
  const { start } = context;
49
49
  const sandbox = isSandboxed(start.configuration);
50
50
  const servers = start.mcpServers ?? [];
51
+ if (isLockedDown(start)) {
52
+ // Read-only and never asking; the session's servers replace the user's MCP table, and web search is off.
53
+ const instructions = [start.instructions?.trim(), LOCKDOWN_NOTE].filter(Boolean).join('\n\n');
54
+ return {
55
+ cwd: sessionWorkdir(context),
56
+ ...(start.configuration.model !== DEFAULT ? { model: start.configuration.model } : {}),
57
+ approvalPolicy: 'never',
58
+ sandbox: 'read-only',
59
+ developerInstructions: instructions,
60
+ config: { 'tools.web_search': false, 'tools.view_image': false, ...codexMcpConfig(servers, undefined) },
61
+ };
62
+ }
51
63
  const instructions = [start.instructions?.trim(), sandbox ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
52
64
  return {
53
65
  cwd: sessionWorkdir(context),
@@ -128,6 +140,7 @@ class CodexDriver {
128
140
  /** Cleared once Codex says it cannot predict, so later turns do not ask again. */
129
141
  predictions = true;
130
142
  closing = false;
143
+ startup = new AbortController();
131
144
  requests = new Map();
132
145
  constructor(context, options) {
133
146
  this.context = context;
@@ -137,14 +150,20 @@ class CodexDriver {
137
150
  await validateSessionWorkdir(this.context);
138
151
  const { start } = this.context;
139
152
  const servers = start.mcpServers ?? [];
140
- this.process = startAgentProcess({
153
+ this.process = await startAgentProcess({
141
154
  command: this.options.command ?? 'codex',
142
- args: ['app-server', ...codexConfigArgs(this.context.profile?.args ?? [])],
155
+ args: ['app-server', ...(isLockedDown(start) ? [] : codexConfigArgs(this.context.profile?.args ?? []))],
143
156
  cwd: sessionWorkdir(this.context),
144
157
  env: { ...mcpTokenEnvironment(servers), SKILLSHARE_SESSION_ID: this.context.sessionId },
145
158
  spawnAgent: this.options.spawnAgent,
159
+ resolveCommand: this.options.resolveCommand,
160
+ signal: this.startup.signal,
146
161
  onLine: line => this.receive(line),
147
162
  });
163
+ if (this.closing) {
164
+ await this.process.kill();
165
+ this.startup.signal.throwIfAborted();
166
+ }
148
167
  void this.process.exited.then(code => this.onExit(code));
149
168
  await this.request('initialize', {
150
169
  clientInfo: { name: 'skillshare', title: 'Skillshare', version: this.options.clientVersion ?? '0.0.0' },
@@ -152,7 +171,7 @@ class CodexDriver {
152
171
  capabilities: { experimentalApi: true, optOutNotificationMethods: ['turn/diff/updated', 'mcpServer/startupStatus/updated'] },
153
172
  });
154
173
  this.notify('initialized');
155
- const params = codexThreadParams(this.context, await this.shadowedServers(servers));
174
+ const params = codexThreadParams(this.context, isLockedDown(start) ? undefined : await this.shadowedServers(servers));
156
175
  const result = start.resumeThreadId
157
176
  ? await this.request('thread/resume', { threadId: start.resumeThreadId, ...params })
158
177
  : await this.request('thread/start', params);
@@ -216,6 +235,7 @@ class CodexDriver {
216
235
  }
217
236
  async close() {
218
237
  this.closing = true;
238
+ this.startup.abort();
219
239
  this.clearRequests();
220
240
  await this.process?.kill();
221
241
  }
@@ -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 crossSpawn from 'cross-spawn';
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'];
@@ -20,15 +19,31 @@ export async function detectAgents(options = {}) {
20
19
  const read = options.read ?? readOptional;
21
20
  const agents = [];
22
21
  const problems = [];
23
- const version = options.version ?? (command => commandVersion(command, env, problem => problems.push(problem)));
22
+ const detectionFailures = [];
23
+ const commands = { claude: 'claude', codex: 'codex' };
24
+ const version = async (kind) => {
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);
34
+ // Send only our bounded diagnostic, never stderr, the environment or the full local PATH.
35
+ if (output === null)
36
+ detectionFailures.push({ kind, message: failure ?? `${kind} --version could not be run. Check the executable and PATH.` });
37
+ return output;
38
+ };
24
39
  const claudeVersion = await version('claude');
25
40
  if (claudeVersion !== null) {
26
41
  const settings = parseJson(await read(join(env.CLAUDE_CONFIG_DIR ?? join(home, '.claude'), 'settings.json')));
27
42
  const configured = Array.isArray(settings?.availableModels) ? settings.availableModels.filter((m) => typeof m === 'string') : [];
28
43
  const models = [...new Set([...CLAUDE_MODELS, ...configured])].filter(id => NAME.test(id) && id !== 'default')
29
44
  .map(id => ({ id, reasoningLevels: CLAUDE_EFFORT_LEVELS }));
30
- const approvalModes = options.approvalModes ? await options.approvalModes('claude', claudeVersion)
31
- : 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);
32
47
  agents.push({ kind: 'claude', version: parseVersion(claudeVersion), models,
33
48
  warnings: approvalModes?.length === 0 ? ['Could not verify approval modes. Check the installed Claude Code version and restart the listener after updating it.'] : [],
34
49
  ...(approvalModes ? { approvalModes } : {}) });
@@ -38,19 +53,21 @@ export async function detectAgents(options = {}) {
38
53
  const codexHome = env.CODEX_HOME ?? join(home, '.codex');
39
54
  const warnings = [];
40
55
  // Codex's own model/list reflects the account; its cache file is the fallback when the app-server cannot be asked.
41
- const listed = await (options.codexModels ?? (() => codexModelList()))().catch(() => null);
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();
42
58
  const models = listed ?? cachedCodexModels(parseJson(await read(join(codexHome, 'models_cache.json'))));
43
59
  if (models.length === 0)
44
60
  warnings.push('Codex did not list its models. Run codex once to sign in or refresh it; only the default model is offered.');
45
61
  const configured = defaultCodexModel(await read(join(codexHome, 'config.toml')));
46
62
  if (configured && models.length > 0 && !models.some(m => m.id === configured))
47
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.`);
48
- const approvalModes = options.approvalModes ? await options.approvalModes('codex', codexVersion)
49
- : 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);
50
66
  if (approvalModes?.length === 0)
51
67
  warnings.push('Could not verify approval modes from Codex app-server schema. Update Codex and restart the listener.');
52
68
  agents.push({ kind: 'codex', version: parseVersion(codexVersion), models, warnings, ...(approvalModes ? { approvalModes } : {}) });
53
69
  }
70
+ options.signal?.throwIfAborted();
54
71
  const settingsText = options.read ? await read(profilesPath(home)) : null;
55
72
  const settings = options.read ? migrateAgentSettings(settingsText === null ? {} : JSON.parse(settingsText)) : await loadAgentSettings(profilesPath(home));
56
73
  const profiles = parseProfiles(JSON.stringify({ ...settings, profiles: settings.profiles ?? [] }), home, problems);
@@ -60,7 +77,7 @@ export async function detectAgents(options = {}) {
60
77
  if (agents.length === 0)
61
78
  problems.push(`Could not run claude --version or codex --version. Check that an agent is installed and runnable on PATH: ${env.PATH ?? env.Path ?? ''}. For a service, check skillshare agents service status and reinstall from a fresh terminal if needed.`);
62
79
  return {
63
- capabilities: { agents, ...(settings.approvalMode ? { defaultApprovalMode: settings.approvalMode } : {}),
80
+ capabilities: { agents, ...(detectionFailures.length ? { detectionFailures } : {}), ...(settings.approvalMode ? { defaultApprovalMode: settings.approvalMode } : {}),
64
81
  profiles: profiles.map(p => ({ name: p.name, agent: p.agent, model: p.model, reasoning: p.reasoning,
65
82
  workdir: p.workdir ? basename(p.workdir) : undefined, ...(p.defaultApprovalMode ? { defaultApprovalMode: p.defaultApprovalMode } : {}) })) },
66
83
  profiles,
@@ -91,44 +108,35 @@ export function claudeApprovalModesFromHelp(help) {
91
108
  const choices = /choices?:\s*([^)]*)/i.exec(description)?.[1];
92
109
  return choices ? approvalModesFromDescription('claude', choices) : [];
93
110
  }
94
- function detectApprovalModes(kind, version, env) {
95
- 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 ?? ''}`;
96
113
  let cached = approvalModeCache.get(key);
97
114
  if (!cached) {
98
115
  cached = (async () => {
99
116
  if (kind === 'claude') {
100
- const help = await commandOutput('claude', ['--help'], env);
117
+ const help = await commandOutput(command, ['--help'], env, signal);
101
118
  return claudeApprovalModesFromHelp(help);
102
119
  }
103
120
  const directory = await mkdtemp(join(tmpdir(), 'skillshare-codex-schema-'));
104
121
  try {
105
- await commandOutput('codex', ['app-server', 'generate-json-schema', '--out', directory, '--experimental'], env);
122
+ await commandOutput(command, ['app-server', 'generate-json-schema', '--out', directory, '--experimental'], env, signal);
106
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();
107
124
  return approvalModesFromDescription(kind, (await readSchemas(directory)).join('\n'));
108
125
  }
109
126
  finally {
110
127
  await rm(directory, { recursive: true, force: true });
111
128
  }
112
- })().catch(() => []);
129
+ })().catch(() => { approvalModeCache.delete(key); return []; });
113
130
  approvalModeCache.set(key, cached);
114
131
  }
115
132
  return cached;
116
133
  }
117
- function commandOutput(command, args, env) {
118
- return new Promise((resolvePromise, reject) => {
119
- const child = crossSpawn(command, args, { env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
120
- let output = '';
121
- const timer = setTimeout(() => { child.kill(); reject(new Error('Agent capability detection timed out.')); }, 15_000);
122
- child.stdout?.on('data', chunk => {
123
- output += String(chunk);
124
- if (output.length > 2 * 1024 * 1024) {
125
- child.kill();
126
- reject(new Error('Agent capability output is too large.'));
127
- }
128
- });
129
- child.on('error', error => { clearTimeout(timer); reject(error); });
130
- child.on('exit', code => { clearTimeout(timer); code === 0 ? resolvePromise(output) : reject(new Error('Agent capability detection failed.')); });
131
- });
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.');
132
140
  }
133
141
  /** Keeps the list within what the server accepts: valid names, no "default", and bounded sizes. */
134
142
  function codexModel(id, displayName, levels, fallback) {
@@ -153,41 +161,50 @@ function cachedCodexModels(cache) {
153
161
  export async function codexModelList(options = {}) {
154
162
  const pending = new Map();
155
163
  let nextId = 0;
156
- const agent = startAgentProcess({
157
- command: options.command ?? 'codex', args: ['app-server'], cwd: homedir(), env: {}, spawnAgent: options.spawnAgent,
158
- onLine: line => {
159
- try {
160
- const message = JSON.parse(line);
161
- if (message.id !== undefined && message.method === undefined)
162
- pending.get(message.id)?.(message);
163
- }
164
- catch { }
165
- },
166
- });
167
- const request = (method, params) => new Promise((resolvePromise, reject) => {
168
- const id = ++nextId;
169
- pending.set(id, message => message.error ? reject(new Error(String(message.error.message))) : resolvePromise(message.result ?? {}));
170
- if (!agent.write(JSON.stringify({ id, method, params })))
171
- reject(new Error('Codex is not accepting input.'));
172
- });
173
- const ask = async () => {
174
- await request('initialize', { clientInfo: { name: 'skillshare', title: 'Skillshare', version: '0.0.0' }, capabilities: { experimentalApi: true } });
175
- agent.write(JSON.stringify({ method: 'initialized' }));
176
- const data = [];
177
- let cursor;
178
- for (let page = 0; page < 10; page++) {
179
- const result = await request('model/list', cursor ? { cursor } : {});
180
- data.push(...(Array.isArray(result.data) ? result.data : []));
181
- cursor = typeof result.nextCursor === 'string' && result.nextCursor ? result.nextCursor : undefined;
182
- if (!cursor)
183
- break;
184
- }
185
- return codexModelsFromList(data);
186
- };
187
- 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;
188
174
  try {
189
- const models = await Promise.race([ask(), agent.exited.then(() => null),
190
- new Promise(resolvePromise => { timer = setTimeout(() => resolvePromise(null), options.timeoutMs ?? 20_000); })]);
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]);
191
208
  return models && models.length > 0 ? models : null;
192
209
  }
193
210
  catch {
@@ -195,7 +212,9 @@ export async function codexModelList(options = {}) {
195
212
  }
196
213
  finally {
197
214
  clearTimeout(timer);
198
- await agent.kill();
215
+ options.signal?.removeEventListener('abort', abort);
216
+ controller.signal.removeEventListener('abort', resolveAbort);
217
+ await agent?.kill();
199
218
  }
200
219
  }
201
220
  export function parseProfiles(text, home, problems = []) {
@@ -276,12 +295,130 @@ async function readOptional(path) {
276
295
  return null;
277
296
  }
278
297
  }
279
- function commandVersion(command, env, report) {
280
- return new Promise(resolvePromise => {
281
- execFile(command, ['--version'], { env, timeout: 15_000, windowsHide: true, shell: process.platform === 'win32' }, (error, stdout) => {
282
- if (error)
283
- report(`${command} --version failed (${error.killed ? 'timeout or terminated' : error.code ?? 'unknown error'}). Check the executable and PATH.`);
284
- resolvePromise(error ? null : stdout.toString());
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();
285
395
  });
286
- });
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
+ }
287
424
  }