@quadient/skillshare 1.17.1 → 1.18.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.
@@ -1,8 +1,10 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { readFile } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
2
+ import { readFile, mkdtemp, readdir, rm } from 'node:fs/promises';
3
+ import { homedir, tmpdir } from 'node:os';
4
4
  import { basename, isAbsolute, join, resolve } from 'node:path';
5
5
  import { startAgentProcess } from './agents-process.js';
6
+ import { loadAgentSettings, migrateAgentSettings } from './agents-settings.js';
7
+ import crossSpawn from 'cross-spawn';
6
8
  /** Model aliases Claude Code resolves to the latest release; Claude Code itself has no command that lists models. */
7
9
  export const CLAUDE_MODELS = ['fable', 'opus', 'sonnet', 'haiku'];
8
10
  export const CLAUDE_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
@@ -25,7 +27,11 @@ export async function detectAgents(options = {}) {
25
27
  const configured = Array.isArray(settings?.availableModels) ? settings.availableModels.filter((m) => typeof m === 'string') : [];
26
28
  const models = [...new Set([...CLAUDE_MODELS, ...configured])].filter(id => NAME.test(id) && id !== 'default')
27
29
  .map(id => ({ id, reasoningLevels: CLAUDE_EFFORT_LEVELS }));
28
- agents.push({ kind: 'claude', version: parseVersion(claudeVersion), models, warnings: [] });
30
+ const approvalModes = options.approvalModes ? await options.approvalModes('claude', claudeVersion)
31
+ : options.version ? undefined : await detectApprovalModes('claude', claudeVersion, env);
32
+ agents.push({ kind: 'claude', version: parseVersion(claudeVersion), models,
33
+ warnings: approvalModes?.length === 0 ? ['Could not verify approval modes. Check the installed Claude Code version and restart the listener after updating it.'] : [],
34
+ ...(approvalModes ? { approvalModes } : {}) });
29
35
  }
30
36
  const codexVersion = await version('codex');
31
37
  if (codexVersion !== null) {
@@ -39,21 +45,91 @@ export async function detectAgents(options = {}) {
39
45
  const configured = defaultCodexModel(await read(join(codexHome, 'config.toml')));
40
46
  if (configured && models.length > 0 && !models.some(m => m.id === configured))
41
47
  warnings.push(`The default model "${configured}" from config.toml is not in the Codex model list and may be rejected; pick a model explicitly.`);
42
- agents.push({ kind: 'codex', version: parseVersion(codexVersion), models, warnings });
48
+ const approvalModes = options.approvalModes ? await options.approvalModes('codex', codexVersion)
49
+ : options.version ? undefined : await detectApprovalModes('codex', codexVersion, env);
50
+ if (approvalModes?.length === 0)
51
+ warnings.push('Could not verify approval modes from Codex app-server schema. Update Codex and restart the listener.');
52
+ agents.push({ kind: 'codex', version: parseVersion(codexVersion), models, warnings, ...(approvalModes ? { approvalModes } : {}) });
43
53
  }
44
- const profiles = parseProfiles(await read(profilesPath(home)), home, problems);
54
+ const settingsText = options.read ? await read(profilesPath(home)) : null;
55
+ const settings = options.read ? migrateAgentSettings(settingsText === null ? {} : JSON.parse(settingsText)) : await loadAgentSettings(profilesPath(home));
56
+ const profiles = parseProfiles(JSON.stringify({ ...settings, profiles: settings.profiles ?? [] }), home, problems);
45
57
  for (const profile of profiles)
46
58
  if (!agents.some(agent => agent.kind === profile.agent))
47
59
  problems.push(`Profile "${profile.name}" uses ${profile.agent}, which is not installed.`);
48
60
  if (agents.length === 0)
49
61
  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.`);
50
62
  return {
51
- capabilities: { agents, profiles: profiles.map(p => ({ name: p.name, agent: p.agent, model: p.model, reasoning: p.reasoning,
52
- workdir: p.workdir ? basename(p.workdir) : undefined, ...(p.sandbox ? { sandbox: true } : {}) })) },
63
+ capabilities: { agents, ...(settings.approvalMode ? { defaultApprovalMode: settings.approvalMode } : {}),
64
+ profiles: profiles.map(p => ({ name: p.name, agent: p.agent, model: p.model, reasoning: p.reasoning,
65
+ workdir: p.workdir ? basename(p.workdir) : undefined, ...(p.defaultApprovalMode ? { defaultApprovalMode: p.defaultApprovalMode } : {}) })) },
53
66
  profiles,
54
67
  problems,
55
68
  };
56
69
  }
70
+ const approvalModeCache = new Map();
71
+ /** Pure capability interpretation is separately testable; unknown schemas never advertise automatic review. */
72
+ export function approvalModesFromDescription(kind, text) {
73
+ if (kind === 'claude') {
74
+ return [/\bdefault\b/.test(text) ? 'supervised' : null, /\bacceptEdits\b/.test(text) ? 'autoEdits' : null,
75
+ /\bauto\b/.test(text) ? 'auto' : null, /\bbypassPermissions\b/.test(text) ? 'fullAccess' : null].filter((v) => v !== null);
76
+ }
77
+ const policy = text.includes('approvalPolicy') && text.includes('sandbox');
78
+ return [policy && text.includes('untrusted') ? 'supervised' : null, policy && text.includes('on-request') ? 'autoEdits' : null,
79
+ policy && text.includes('approvalsReviewer') && text.includes('auto_review') ? 'auto' : null,
80
+ policy && text.includes('never') && text.includes('danger-full-access') ? 'fullAccess' : null].filter((v) => v !== null);
81
+ }
82
+ /** Commander wraps choices across lines at narrower terminal widths. Read only this option's explicit choices. */
83
+ export function claudeApprovalModesFromHelp(help) {
84
+ const lines = help.split(/\r?\n/);
85
+ const index = lines.findIndex(line => /--permission-mode\b/.test(line));
86
+ if (index < 0)
87
+ return [];
88
+ const remainder = lines.slice(index + 1);
89
+ const nextOption = remainder.findIndex(line => /^\s*(?:-{1,2}[A-Za-z?]|[A-Z][A-Za-z ]+:)/.test(line));
90
+ const description = [lines[index], ...remainder.slice(0, nextOption < 0 ? remainder.length : nextOption)].join('\n');
91
+ const choices = /choices?:\s*([^)]*)/i.exec(description)?.[1];
92
+ return choices ? approvalModesFromDescription('claude', choices) : [];
93
+ }
94
+ function detectApprovalModes(kind, version, env) {
95
+ const key = `${kind}\0${version}\0${env.PATH ?? env.Path ?? ''}`;
96
+ let cached = approvalModeCache.get(key);
97
+ if (!cached) {
98
+ cached = (async () => {
99
+ if (kind === 'claude') {
100
+ const help = await commandOutput('claude', ['--help'], env);
101
+ return claudeApprovalModesFromHelp(help);
102
+ }
103
+ const directory = await mkdtemp(join(tmpdir(), 'skillshare-codex-schema-'));
104
+ try {
105
+ await commandOutput('codex', ['app-server', 'generate-json-schema', '--out', directory, '--experimental'], env);
106
+ 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
+ return approvalModesFromDescription(kind, (await readSchemas(directory)).join('\n'));
108
+ }
109
+ finally {
110
+ await rm(directory, { recursive: true, force: true });
111
+ }
112
+ })().catch(() => []);
113
+ approvalModeCache.set(key, cached);
114
+ }
115
+ return cached;
116
+ }
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
+ });
132
+ }
57
133
  /** Keeps the list within what the server accepts: valid names, no "default", and bounded sizes. */
58
134
  function codexModel(id, displayName, levels, fallback) {
59
135
  if (typeof id !== 'string' || !NAME.test(id) || id === 'default')
@@ -150,17 +226,13 @@ export function parseProfiles(text, home, problems = []) {
150
226
  problems.push(`Profile "${name}" has an invalid model or reasoning.`);
151
227
  continue;
152
228
  }
153
- if (raw.sandbox !== undefined && typeof raw.sandbox !== 'boolean') {
154
- problems.push(`Profile "${name}" sandbox must be true or false.`);
155
- continue;
156
- }
157
229
  if (raw.args !== undefined && (!Array.isArray(raw.args) || raw.args.some(arg => typeof arg !== 'string'))) {
158
230
  problems.push(`Profile "${name}" args must be a list of strings.`);
159
231
  continue;
160
232
  }
161
233
  profiles.push({ name, agent: raw.agent, model: optional('model'), reasoning: optional('reasoning'),
162
234
  workdir: typeof raw.workdir === 'string' && raw.workdir.length > 0 ? expandHome(raw.workdir, home) : undefined,
163
- args: raw.args ?? [], ...(raw.sandbox === true ? { sandbox: true } : {}) });
235
+ args: raw.args ?? [], ...(raw.approvalMode ? { defaultApprovalMode: raw.approvalMode } : {}) });
164
236
  }
165
237
  return profiles.slice(0, 32);
166
238
  }
@@ -0,0 +1,33 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { Ajv } from 'ajv';
3
+ import { Ajv2019 } from 'ajv/dist/2019.js';
4
+ import { Ajv2020 } from 'ajv/dist/2020.js';
5
+ import addFormats from 'ajv-formats';
6
+ /** No reference loader, filesystem access or native agent writes enter this worker. */
7
+ export function validateNativeForm(schema, value) {
8
+ try {
9
+ const dialect = schema && typeof schema === 'object' && '$schema' in schema && typeof schema.$schema === 'string' ? schema.$schema : '';
10
+ const Constructor = dialect.includes('2020-12') ? Ajv2020 : dialect.includes('2019-09') ? Ajv2019 : Ajv;
11
+ const ajv = new Constructor({ strictSchema: true, strictTypes: false, strictTuples: false, strictRequired: false,
12
+ allErrors: false, ownProperties: true, coerceTypes: false, useDefaults: false, removeAdditional: false,
13
+ loopEnum: 32, loopRequired: 32, inlineRefs: false, logger: false });
14
+ addFormats.default(ajv);
15
+ ajv.addKeyword({ keyword: 'enumNames', schemaType: ['array', 'null'], valid: true });
16
+ const validate = ajv.compile(schema);
17
+ if ('$async' in validate && validate.$async)
18
+ return { warning: 'Asynchronous native form schemas are not supported. The request is still waiting; you can decline or cancel it.' };
19
+ if (validate(value))
20
+ return { value, valid: true };
21
+ const error = validate.errors?.[0];
22
+ return { valid: false, error: `The response does not match the native form schema at ${error?.instancePath || '/'} (${error?.keyword ?? 'validation'}).` };
23
+ }
24
+ catch (error) {
25
+ const message = error instanceof Error ? error.message : '';
26
+ const keyword = /unknown keyword: "([A-Za-z0-9_$-]+)"/.exec(message)?.[1];
27
+ const reason = keyword ? `unsupported schema keyword ${keyword}` : /can't resolve reference/.test(message) ? 'a schema reference is unavailable locally'
28
+ : /unknown format/.test(message) ? 'an unsupported value format' : 'invalid or unsupported schema';
29
+ return { warning: `The native form schema cannot be validated: ${reason}. The request is still waiting; you can decline or cancel it.` };
30
+ }
31
+ }
32
+ if (parentPort)
33
+ parentPort.postMessage(validateNativeForm(workerData.schema, workerData.value));
@@ -0,0 +1,79 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ const FORM_TIMEOUT_MS = 5_000;
3
+ let activeValidators = 0;
4
+ const waitingValidators = [];
5
+ async function acquireValidator() {
6
+ await new Promise(resolve => {
7
+ const enter = () => { activeValidators++; resolve(); };
8
+ if (activeValidators < 2)
9
+ enter();
10
+ else
11
+ waitingValidators.push(enter);
12
+ });
13
+ return () => { activeValidators--; waitingValidators.shift()?.(); };
14
+ }
15
+ /** Untrusted schema code and regular expressions cannot block the listener's lease/close timers. */
16
+ async function validateInWorker(schema, value) {
17
+ const release = await acquireValidator();
18
+ return new Promise(resolve => {
19
+ let worker;
20
+ let settled = false;
21
+ let timer;
22
+ const finish = (result) => {
23
+ if (settled)
24
+ return;
25
+ settled = true;
26
+ clearTimeout(timer);
27
+ const done = () => { release(); resolve(result); };
28
+ if (worker)
29
+ void worker.terminate().then(done, done);
30
+ else
31
+ done();
32
+ };
33
+ try {
34
+ worker = new Worker(new URL(import.meta.url.endsWith('.ts') ? './agents-form-worker.ts' : './agents-form-worker.js', import.meta.url), {
35
+ workerData: { schema, value }, resourceLimits: { maxOldGenerationSizeMb: 64, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 },
36
+ });
37
+ worker.once('message', (result) => finish(result));
38
+ worker.once('error', () => finish({ error: 'The native form validator could not complete. The request is still waiting; you can correct the response or cancel it.' }));
39
+ worker.once('exit', () => finish({ error: 'The native form validator stopped. The request is still waiting; you can try again or cancel it.' }));
40
+ timer = setTimeout(() => finish({ error: 'The native form validator exceeded its time limit. The request is still waiting; you can correct the response or cancel it.' }), FORM_TIMEOUT_MS);
41
+ }
42
+ catch {
43
+ finish({ error: 'The native form validator could not start. The request is still waiting; no response has been sent.' });
44
+ }
45
+ });
46
+ }
47
+ /** Compilation probes run in an isolated worker; original schemas remain intact for display. */
48
+ export async function nativeForm(schema) {
49
+ const root = schema && typeof schema === 'object' ? schema : undefined;
50
+ const initialValue = root?.type === 'string' ? '' : JSON.stringify(root?.default ?? (root?.type === 'array' ? [] : {}), null, 2);
51
+ const result = await validateInWorker(schema, {});
52
+ return { initialValue, emptyValid: result.valid === true, warning: result.warning ?? (result.valid === undefined ? result.error : undefined) };
53
+ }
54
+ /** Invalid input never consumes the request or becomes an automatic native decline. */
55
+ export async function nativeFormResponse(schema, text) {
56
+ if (text === undefined)
57
+ return { error: 'Enter a response to the native form.' };
58
+ let value = text;
59
+ if (schema && typeof schema === 'object' && schema.type === 'string') {
60
+ if (text.trimStart().startsWith('"')) {
61
+ try {
62
+ const parsed = JSON.parse(text);
63
+ if (typeof parsed === 'string')
64
+ value = parsed;
65
+ }
66
+ catch { }
67
+ }
68
+ }
69
+ else {
70
+ try {
71
+ value = JSON.parse(text);
72
+ }
73
+ catch {
74
+ return { error: 'Enter valid JSON matching the displayed native form schema.' };
75
+ }
76
+ }
77
+ const result = await validateInWorker(schema, value);
78
+ return result.warning ? { error: result.warning } : result;
79
+ }
@@ -28,7 +28,18 @@ export function startAgentProcess(options) {
28
28
  child,
29
29
  exited,
30
30
  stderrTail: () => stderr.trim().split(/\r?\n/).filter(line => line.trim()).slice(-3).join(' ').slice(-300),
31
- write: line => child.stdin?.writable ? child.stdin.write(line + '\n') : false,
31
+ // write(false) signals backpressure, not rejection: the frame is already buffered and must not be resent.
32
+ write: line => {
33
+ if (!child.stdin?.writable)
34
+ return false;
35
+ try {
36
+ child.stdin.write(line + '\n');
37
+ return true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ },
32
43
  kill() {
33
44
  killing ??= (async () => {
34
45
  const signal = (sig) => {
@@ -0,0 +1,55 @@
1
+ import { createHash } from 'node:crypto';
2
+ const EVENT_BYTES = 3 * 1024 * 1024;
3
+ const CHUNK_BYTES = 256 * 1024;
4
+ const MAX_REQUEST_BYTES = 32 * 1024 * 1024;
5
+ /** Preserve event order and native request content without increasing the ordinary events endpoint limit. */
6
+ export async function uploadSessionEvents(events, leaseToken, post, acknowledged = new WeakSet()) {
7
+ let batch = [];
8
+ let bytes = Buffer.byteLength(JSON.stringify({ leaseToken, events: [] }));
9
+ const flush = async () => {
10
+ if (!batch.length)
11
+ return;
12
+ await post('/events', { leaseToken, events: batch });
13
+ for (const event of batch)
14
+ acknowledged.add(event);
15
+ batch = [];
16
+ bytes = Buffer.byteLength(JSON.stringify({ leaseToken, events: [] }));
17
+ };
18
+ for (const event of events) {
19
+ // EventQueue retries its original snapshots after a partial upload. Successful prefixes must not replay.
20
+ if (acknowledged.has(event))
21
+ continue;
22
+ const eventBytes = Buffer.byteLength(JSON.stringify(event)) + 1;
23
+ if (event.type === 'request' && eventBytes > EVENT_BYTES / 2) {
24
+ await flush();
25
+ const data = Buffer.from(JSON.stringify(event.request), 'utf8');
26
+ const identity = { leaseToken, requestId: event.request.id, hash: createHash('sha256').update(data).digest('hex') };
27
+ const begin = await post('/request-uploads', { ...identity, operation: 'begin', size: data.length,
28
+ chunks: Math.ceil(data.length / CHUNK_BYTES), title: event.request.title.slice(0, 200) });
29
+ if (begin?.complete) {
30
+ acknowledged.add(event);
31
+ continue;
32
+ }
33
+ if (!begin?.success)
34
+ throw new Error(begin?.error ?? 'The full request upload is pending; no response has been sent.');
35
+ if (data.length > MAX_REQUEST_BYTES)
36
+ throw new Error('The request exceeds the upload limit and remains visible and pending.');
37
+ for (let offset = 0; offset < data.length; offset += CHUNK_BYTES) {
38
+ const chunk = await post('/request-uploads', { ...identity, operation: 'chunk', index: offset / CHUNK_BYTES,
39
+ data: data.subarray(offset, offset + CHUNK_BYTES).toString('base64') });
40
+ if (!chunk?.success)
41
+ throw new Error(chunk?.error ?? 'The request upload was interrupted; no response has been sent.');
42
+ }
43
+ const completed = await post('/request-uploads', { ...identity, operation: 'complete' });
44
+ if (!completed?.complete)
45
+ throw new Error(completed?.error ?? 'The full request upload is pending; no response has been sent.');
46
+ acknowledged.add(event);
47
+ continue;
48
+ }
49
+ if (bytes + eventBytes > EVENT_BYTES)
50
+ await flush();
51
+ batch.push(event);
52
+ bytes += eventBytes;
53
+ }
54
+ await flush();
55
+ }
@@ -0,0 +1,31 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Same length-prefixed UTF-8 protocol as AgentResponseFingerprint; never depend on JSON property order or escaping. */
3
+ export function responseFingerprint(response) {
4
+ const hash = createHash('sha256');
5
+ const integer = (value) => { const bytes = Buffer.allocUnsafe(4); bytes.writeInt32LE(value); hash.update(bytes); };
6
+ const text = (value) => {
7
+ if (value == null) {
8
+ integer(-1);
9
+ return;
10
+ }
11
+ const bytes = Buffer.from(value, 'utf8');
12
+ integer(bytes.length);
13
+ hash.update(bytes);
14
+ };
15
+ text('skillshare-response-v1');
16
+ text(response.requestId);
17
+ text(response.decision);
18
+ text(response.formData);
19
+ integer(response.revision ?? 0);
20
+ const answers = response.answers;
21
+ integer(answers == null ? -1 : Object.keys(answers).length);
22
+ if (answers != null)
23
+ for (const key of Object.keys(answers).sort()) {
24
+ text(key);
25
+ const values = answers[key];
26
+ integer(values.length);
27
+ for (const value of values)
28
+ text(value);
29
+ }
30
+ return hash.digest('hex');
31
+ }
@@ -1,4 +1,5 @@
1
- import { detectAgents } from './agents-detect.js';
1
+ import { detectAgents, profilesPath } from './agents-detect.js';
2
+ import { loadAgentSettings, updateAgentJson, withoutLegacySandboxArgs } from './agents-settings.js';
2
3
  import { refreshServicePath } from './agents-service-path.js';
3
4
  import { existsSync } from 'node:fs';
4
5
  import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
@@ -28,6 +29,21 @@ export function servicePaths(appDir) {
28
29
  windowsTask: join(appDir, 'agents-service-task.xml'),
29
30
  };
30
31
  }
32
+ /** Runs on the next service start, including with launchers written by older CLIs. Seed before removing the old argument. */
33
+ export async function migrateServiceApprovalOptions(appDir, settingsPath = profilesPath()) {
34
+ const path = servicePaths(appDir).config;
35
+ if (!existsSync(path))
36
+ return;
37
+ const stored = JSON.parse(await readFile(path, 'utf8'));
38
+ if (!stored.args?.some(arg => arg === '--sandbox' || arg === '--sandbox=true'))
39
+ return;
40
+ await loadAgentSettings(settingsPath, true);
41
+ await updateAgentJson(path, value => {
42
+ if (!Array.isArray(value.args) || value.args.some((arg) => typeof arg !== 'string'))
43
+ throw new Error('Service args must be a list of strings.');
44
+ value.args = withoutLegacySandboxArgs(value.args);
45
+ });
46
+ }
31
47
  /** Where the service manager keeps the service definition. */
32
48
  export function definitionPath(environment) {
33
49
  switch (environment.platform) {
@@ -1,4 +1,34 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
+ import { isAbsolute } from 'node:path';
3
+ import { stat } from 'node:fs/promises';
4
+ import { responseFingerprint } from './agents-response-hash.js';
5
+ /** UI dimensions never change a native decision, scope or answer. Unencodable interactions stay visible and pending. */
6
+ export function boundedSessionRequest(request) {
7
+ const validKey = (key) => typeof key === 'string' && key.length > 0;
8
+ const unique = (keys) => new Set(keys).size === keys.length;
9
+ const choices = request.decisions ?? [];
10
+ const questions = request.questions ?? [];
11
+ const valid = unique(choices.map(d => d.id)) && choices.every(d => validKey(d.id) && typeof d.label === 'string' && d.label.length > 0)
12
+ && unique(questions.map(q => q.id)) && questions.every(q => validKey(q.id) && typeof q.question === 'string' && q.question.length > 0
13
+ && (!q.options || q.options.every(o => typeof o.label === 'string' && o.label.length > 0)))
14
+ && (request.kind !== 'approval' || choices.length > 0)
15
+ && (request.kind !== 'userInput' || questions.length > 0 || request.form || request.adaptationWarning || request.originalRequest);
16
+ return valid ? { ...request, title: request.title.trim() || 'Agent request' } : {
17
+ id: request.id, kind: 'userInput', title: request.title.trim() || 'Agent request',
18
+ originalRequest: request.originalRequest ?? JSON.stringify(request, null, 2),
19
+ adaptationWarning: 'The native request cannot be encoded by this adapter. It remains pending; no response has been sent.',
20
+ };
21
+ }
22
+ /** A per-use directory takes precedence; it is a real local directory, never a shell fragment. */
23
+ export function sessionWorkdir(context) {
24
+ return context.start.configuration.workdir ?? context.profile?.workdir ?? context.workdir;
25
+ }
26
+ export async function validateSessionWorkdir(context) {
27
+ const path = sessionWorkdir(context);
28
+ if (!isAbsolute(path) || !(await stat(path)).isDirectory())
29
+ throw new Error('The working directory must be an existing absolute directory on this computer.');
30
+ return path;
31
+ }
2
32
  /** Read-only tools Claude Code may use in a sandboxed session; the session's MCP servers are added per server. */
3
33
  export const CLAUDE_SANDBOX_TOOLS = ['Read', 'Grep', 'Glob', 'WebSearch', 'WebFetch'];
4
34
  export const SANDBOX_NOTE = 'This session is sandboxed: you can read files, search and use the provided MCP tools, but you cannot change files or ' +
@@ -6,8 +36,9 @@ export const SANDBOX_NOTE = 'This session is sandboxed: you can read files, sear
6
36
  export const DEFAULT = 'default';
7
37
  const MAX_TEXT = 50_000;
8
38
  const MAX_SUGGESTION = 2_000;
9
- export function isSandboxed(configuration, options) {
10
- return options.sandbox === true || options.profile?.sandbox === true || configuration.sandbox === true;
39
+ /** Only frozen permissions of an already-created session may enforce the legacy read-only restriction. */
40
+ export function isSandboxed(configuration) {
41
+ return configuration.sandbox === true;
11
42
  }
12
43
  /** MCP server names become tool prefixes and config keys, so they are reduced to a safe alphabet. */
13
44
  export function mcpServerName(server, index) {
@@ -135,6 +166,14 @@ export class SessionRunner {
135
166
  idleTimer = null;
136
167
  closing = null;
137
168
  closedReported = false;
169
+ requests = new Set();
170
+ responding = new Set();
171
+ deliveredResponses = new Set();
172
+ leaseNow;
173
+ leaseDeadline;
174
+ leaseTimer = null;
175
+ requestEpoch = 0;
176
+ timeoutChanged;
138
177
  done;
139
178
  resolveDone;
140
179
  constructor(options) {
@@ -142,6 +181,8 @@ export class SessionRunner {
142
181
  this.sessionId = options.sessionId;
143
182
  this.leaseToken = options.leaseToken;
144
183
  this.now = options.now ?? Date.now;
184
+ this.leaseNow = options.leaseNow ?? (() => performance.now());
185
+ this.leaseDeadline = options.leaseDeadline ?? Number.POSITIVE_INFINITY;
145
186
  this.done = new Promise(resolve => { this.resolveDone = resolve; });
146
187
  // A rejected lease means the server moved on; the agent must stop without reporting anything more.
147
188
  this.events = new EventQueue(options.upload, options.flushIntervalMs, () => void this.stop());
@@ -159,16 +200,100 @@ export class SessionRunner {
159
200
  this.events.push({ type: 'suggestion', text: clip(text.trim(), MAX_SUGGESTION) });
160
201
  },
161
202
  exited: error => void this.finish(error ?? 'The agent stopped unexpectedly.'),
203
+ request: request => {
204
+ if (this.closing || this.requests.has(request.id))
205
+ return;
206
+ this.requests.add(request.id);
207
+ this.timeoutChanged?.();
208
+ this.events.push({ type: 'request', request });
209
+ },
210
+ requestResolved: requestId => this.resolveRequest(requestId),
211
+ responseAllowed: requestId => this.canRespond(requestId),
212
+ authorizeResponse: async (response) => {
213
+ const id = response.requestId, epoch = this.requestEpoch;
214
+ if (!this.canRespond(id) || this.deliveredResponses.has(id))
215
+ return false;
216
+ const authorized = this.options.authorizeResponse ? await this.options.authorizeResponse(response).catch(() => false) : true;
217
+ if (!authorized || epoch !== this.requestEpoch || !this.canRespond(id))
218
+ return false;
219
+ this.deliveredResponses.add(id);
220
+ return true;
221
+ },
162
222
  });
223
+ this.armLease();
163
224
  }
164
225
  get stopping() { return this.closing !== null; }
165
226
  /** A turn runs or a message waits for one; restarting the listener now would cut it off. */
166
227
  get busy() { return this.turnRunning || this.steering.size > 0 || this.pending.length > 0; }
228
+ async respond(response) {
229
+ const id = response.requestId, epoch = this.requestEpoch;
230
+ if (!this.canRespond(id) || this.responding.has(id) || this.deliveredResponses.has(id))
231
+ return;
232
+ this.responding.add(id);
233
+ try {
234
+ // The driver validates and serializes first, then asks the runner to authorize native delivery.
235
+ const error = await this.driver.respond?.(response);
236
+ if (typeof error === 'string' && epoch === this.requestEpoch && this.canRespond(id)) {
237
+ this.deliveredResponses.delete(id);
238
+ this.events.push({ type: 'requestInvalid', requestId: id, response: { requestId: id, revision: response.revision ?? 0 },
239
+ responseHash: responseFingerprint(response), error });
240
+ }
241
+ }
242
+ catch (error) {
243
+ // The native write may have happened before throwing; never replay an ambiguous operation.
244
+ await this.finish(`The agent response could not be delivered: ${errorMessage(error)}`);
245
+ }
246
+ finally {
247
+ this.responding.delete(id);
248
+ }
249
+ }
250
+ canRespond(id) {
251
+ if (!this.leaseLive())
252
+ return false;
253
+ return !this.closing && !this.interruptRequested && this.requests.has(id);
254
+ }
255
+ leaseLive() {
256
+ if (this.leaseNow() < this.leaseDeadline)
257
+ return !this.closing;
258
+ void this.stop();
259
+ return false;
260
+ }
261
+ /** A delayed poll cannot revive a locally expired lease. Deadlines are anchored before sending the poll. */
262
+ renewLease(deadline) {
263
+ if (!this.leaseLive())
264
+ return;
265
+ this.leaseDeadline = deadline;
266
+ this.armLease();
267
+ }
268
+ armLease() {
269
+ if (this.leaseTimer)
270
+ clearTimeout(this.leaseTimer);
271
+ this.leaseTimer = null;
272
+ if (!Number.isFinite(this.leaseDeadline))
273
+ return;
274
+ if (!this.leaseLive())
275
+ return;
276
+ this.leaseTimer = setTimeout(() => { if (this.leaseLive())
277
+ this.armLease(); }, Math.max(1, this.leaseDeadline - this.leaseNow()));
278
+ }
279
+ resolveRequest(requestId) {
280
+ if (!this.requests.delete(requestId))
281
+ return;
282
+ this.timeoutChanged?.();
283
+ this.events.push({ type: 'requestResolved', requestId });
284
+ }
285
+ clearRequests() {
286
+ this.requestEpoch++;
287
+ for (const requestId of this.requests)
288
+ this.resolveRequest(requestId);
289
+ }
167
290
  /**
168
291
  * Queues messages for the next turns, or steers them into the running turn; the server may send a message again, so
169
292
  * repeats are ignored.
170
293
  */
171
294
  send(messages) {
295
+ if (!this.leaseLive())
296
+ return;
172
297
  for (const message of messages) {
173
298
  if (this.seen.has(message.id))
174
299
  continue;
@@ -205,6 +330,7 @@ export class SessionRunner {
205
330
  if (!this.turnRunning || this.interruptRequested)
206
331
  return;
207
332
  this.interruptRequested = true;
333
+ this.clearRequests();
208
334
  await this.driver.interrupt().catch(() => { });
209
335
  }
210
336
  /** Stops the agent and reports the session as closed, so the server can resume it later or finish ending it. */
@@ -260,6 +386,7 @@ export class SessionRunner {
260
386
  }
261
387
  if (this.closing)
262
388
  return;
389
+ this.clearRequests();
263
390
  if (this.interruptRequested && outcome.status === 'failed' && !outcome.error)
264
391
  outcome = { ...outcome, status: 'interrupted' };
265
392
  this.events.push({ type: 'turnCompleted', status: outcome.status, error: outcome.error,
@@ -273,16 +400,31 @@ export class SessionRunner {
273
400
  const timeoutMs = Math.max(1, this.options.start.turnTimeoutSeconds) * 1000;
274
401
  let timer;
275
402
  let expired = false;
403
+ let remaining = timeoutMs;
404
+ let armedAt = 0;
276
405
  const timedOut = new Promise(resolve => {
277
- timer = setTimeout(async () => {
406
+ const expire = async () => {
278
407
  expired = true;
279
- await this.interrupt();
408
+ // A broken provider may never acknowledge interrupt; the stop grace period must still start immediately.
409
+ void this.interrupt();
280
410
  const stopped = await Promise.race([turn.then(() => true), delay(15_000).then(() => false)]);
281
411
  resolve(stopped ? { status: 'interrupted', error: `The turn did not finish within ${this.options.start.turnTimeoutSeconds} seconds.` }
282
412
  : { status: 'failed', error: `The agent did not stop after ${this.options.start.turnTimeoutSeconds} seconds.` });
283
413
  if (!stopped)
284
414
  void this.finish(`The agent did not stop after ${this.options.start.turnTimeoutSeconds} seconds.`);
285
- }, timeoutMs);
415
+ };
416
+ this.timeoutChanged = () => {
417
+ if (timer) {
418
+ remaining -= Math.max(0, this.now() - armedAt);
419
+ clearTimeout(timer);
420
+ timer = undefined;
421
+ }
422
+ if (!expired && this.requests.size === 0) {
423
+ armedAt = this.now();
424
+ timer = setTimeout(expire, Math.max(1, remaining));
425
+ }
426
+ };
427
+ this.timeoutChanged();
286
428
  });
287
429
  try {
288
430
  const outcome = await Promise.race([turn, timedOut]);
@@ -292,6 +434,7 @@ export class SessionRunner {
292
434
  }
293
435
  finally {
294
436
  clearTimeout(timer);
437
+ this.timeoutChanged = undefined;
295
438
  }
296
439
  }
297
440
  armIdle() {
@@ -308,6 +451,10 @@ export class SessionRunner {
308
451
  finish(error) {
309
452
  this.closing ??= (async () => {
310
453
  this.clearIdle();
454
+ if (this.leaseTimer)
455
+ clearTimeout(this.leaseTimer);
456
+ this.leaseTimer = null;
457
+ this.clearRequests();
311
458
  await this.driver.close().catch(() => { });
312
459
  if (this.turnRunning && !this.closedReported) {
313
460
  this.events.push({ type: 'turnCompleted', status: 'failed', error: error ?? 'The agent was stopped.' });