@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.
package/README.md CHANGED
@@ -25,8 +25,10 @@ bun run index.ts install --skill-version-id 42 --target ./installed
25
25
  on this computer. Start a session under **Sessions** in Skillshare and keep talking to the agent
26
26
  there; Teams 👀 sessions go to the computer chosen under **Connected agents**. The listener
27
27
  reports the installed agents with their models and reasoning levels. Agents use the login you
28
- already have in `claude` and `codex`, and run with your full local permissions and configuration,
29
- without permission prompts.
28
+ already have in `claude` and `codex`. From CLI 1.18.0, configure Supervised, Auto-accept edits,
29
+ Auto or Full access in SkillShare. Approvals and questions appear in Sessions; only the owner can respond.
30
+ Auto is the default for new configurations and migrations; previous read-only listener/profile defaults migrate to Auto and remain editable in Skillshare.
31
+ Codex and Claude apply their native permissions, so their isolation differs.
30
32
 
31
33
  Codex runs as `codex app-server` and Claude Code with stream-json input and output. The agent
32
34
  keeps running between your messages and stops after 15 quiet minutes; the next message resumes
@@ -34,6 +36,11 @@ the same Codex thread or Claude Code session. Sessions need CLI 1.10.0 or newer.
34
36
  attached to messages reach the agent from CLI 1.10.2: the listener downloads them to a temp
35
37
  directory that it removes when the session closes.
36
38
 
39
+ Set defaults for each agent configuration on its listener card, then inherit or override them for a manual session,
40
+ source route or My work automation. Select one working folder at the point of use; it overrides the local profile/listener
41
+ folder and does not create a worktree automatically. Browser or Teams alerts can link directly to a pending request.
42
+ The listener reports supported permission modes from installed agent capabilities; unsupported modes fail explicitly.
43
+
37
44
  ```sh
38
45
  skillshare agents status
39
46
  skillshare agents listen --workdir ~/Research
@@ -62,13 +69,12 @@ working directory such as `--workdir ~\Projects`. The service is the scheduled t
62
69
  shims (`claude.cmd`, `codex.cmd`) are started through `cmd.exe` with every argument quoted;
63
70
  Claude Code gets the session instructions as a file.
64
71
 
65
- `--sandbox` keeps every agent read-only. Claude Code may only read files, search the web
66
- and use the Skillshare MCP; Codex runs in its read-only sandbox. A profile can do the same
67
- with `"sandbox": true`.
72
+ Legacy read-only settings migrate automatically to Auto, which uses each provider's automatic approvals and does not enforce permanent read-only access.
73
+ Already-created sessions retain their frozen permissions. Local `approvalMode` values seed defaults once; subsequent web changes take precedence.
68
74
 
69
75
  Optional named profiles in `~/.config/skillshare/agents.json` set a working directory and
70
76
  extra arguments. For Claude Code the arguments are added to `claude`; for Codex only
71
- configuration overrides (`-c`, `--config`, `--enable`, `--disable`) apply to `codex app-server`. Only the name, agent, model, reasoning and the working directory's last
77
+ configuration overrides (`-c`, `--config`, `--enable`, `--disable`) apply to `codex app-server`. Only the name, agent, model, reasoning, approval default and the working directory's last
72
78
  segment are sent to Skillshare.
73
79
 
74
80
  ```json
@@ -116,7 +122,7 @@ permissions, Microsoft session lifetime and file-tool differences in the hosted
116
122
 
117
123
  Starting with 1.9.0:
118
124
 
119
- - `agents listen` and `agents status` run Claude Code and Codex sessions from Skillshare on this computer (see [Connected agents](#connected-agents)); `--sandbox` keeps them read-only.
125
+ - `agents listen` and `agents status` run Claude Code and Codex sessions from Skillshare on this computer (see [Connected agents](#connected-agents)); choose approval modes in Skillshare.
120
126
  - Commands print readable text. Scripts that parsed JSON from `whoami`, `list`, `show`, `upload`, `pages list|show|runtime|upload|secrets` or `teams status|test|upload` must add `--json`; with `--json` progress goes to stderr and stdout contains only JSON.
121
127
  - `show` accepts a skill name as well as an id.
122
128
  - `pages upload` refuses build output folder names such as `dist` or `build` without `--slug`, says whether it creates or replaces a page, refuses pages owned by someone else unless you are an admin, and prints the page URL.
@@ -4,7 +4,8 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
4
4
  import { homedir, tmpdir } from 'node:os';
5
5
  import { dirname, join, resolve } from 'node:path';
6
6
  import { startAgentProcess } from './agents-process.js';
7
- import { CLAUDE_SANDBOX_TOOLS, DEFAULT, SANDBOX_NOTE, clip, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, } from './agents-session.js';
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
9
  /**
9
10
  * Claude Code in print mode with stream-json in both directions: the same protocol the Agent SDK speaks, but against the
10
11
  * user's own claude install, so their login and settings apply. MCP config and the session's instructions are passed per
@@ -26,18 +27,19 @@ export function claudeContent(message) {
26
27
  }
27
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. */
28
29
  export function claudeInstructions(context) {
29
- return [context.start.instructions?.trim(), isSandboxed(context.start.configuration, context) ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
30
+ return [context.start.instructions?.trim(), isSandboxed(context.start.configuration) ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
30
31
  }
31
32
  export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPath) {
32
33
  const { start } = context;
33
- const sandbox = isSandboxed(start.configuration, context);
34
+ const sandbox = isSandboxed(start.configuration);
34
35
  const servers = start.mcpServers ?? [];
35
36
  // Replayed user messages tell when Claude Code took a message, which is how a steered message is known to have joined the turn.
36
37
  const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--replay-user-messages',
37
38
  ...(sandbox
38
39
  // A sandboxed session never prompts: anything outside the read-only allowlist is denied.
39
40
  ? ['--permission-mode', 'dontAsk', '--allowedTools', ...CLAUDE_SANDBOX_TOOLS, ...servers.map((server, index) => `mcp__${mcpServerName(server, index)}`)]
40
- : ['--dangerously-skip-permissions'])];
41
+ : !start.configuration.approvalMode || start.configuration.approvalMode === 'fullAccess' ? ['--dangerously-skip-permissions']
42
+ : ['--permission-mode', { supervised: 'default', autoEdits: 'acceptEdits', auto: 'auto' }[start.configuration.approvalMode], '--permission-prompt-tool', 'stdio'])];
41
43
  if (start.configuration.model !== DEFAULT)
42
44
  args.push('--model', start.configuration.model);
43
45
  if (start.configuration.reasoning !== DEFAULT)
@@ -50,6 +52,11 @@ export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPat
50
52
  args.push('--settings', settingsPath);
51
53
  if (start.resumeThreadId)
52
54
  args.push('--resume', start.resumeThreadId);
55
+ // A named profile may add tuning arguments, but cannot silently replace the session's selected permission mode.
56
+ if (start.configuration.approvalMode && (context.profile?.args ?? []).some(arg => /^--(?:permission-mode|dangerously-skip-permissions|allow-dangerously-skip-permissions)(?:=|$)/.test(arg)))
57
+ throw new Error('The local profile overrides permission flags. Remove those flags to use a session approval mode.');
58
+ if (start.configuration.approvalMode === 'fullAccess')
59
+ args.push('--permission-prompt-tool', 'stdio');
53
60
  return [...args, ...(context.profile?.args ?? [])];
54
61
  }
55
62
  export function claudeMcpConfig(servers) {
@@ -138,17 +145,19 @@ class ClaudeDriver {
138
145
  early = [];
139
146
  costSoFar = 0;
140
147
  closing = false;
148
+ permissions = new Map();
141
149
  constructor(context, options) {
142
150
  this.context = context;
143
151
  this.options = options;
144
152
  }
145
153
  async open() {
154
+ await validateSessionWorkdir(this.context);
146
155
  const servers = this.context.start.mcpServers ?? [];
147
156
  const instructions = claudeInstructions(this.context);
148
157
  let mcpConfig;
149
158
  let instructionsFile;
150
159
  let settingsFile;
151
- const workdir = this.context.profile?.workdir ?? this.context.workdir;
160
+ const workdir = sessionWorkdir(this.context);
152
161
  const shadowed = servers.length > 0 ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
153
162
  if (servers.length > 0 || instructions)
154
163
  this.directory = await mkdtemp(join(tmpdir(), 'skillshare-session-'));
@@ -173,7 +182,7 @@ class ClaudeDriver {
173
182
  // Claude Code holds suggestions back when the account nears a rate limit; the user can still turn them off with this variable.
174
183
  CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION: process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION ?? 'true',
175
184
  // Claude Code lets auto-memory write to its own folder even under the read-only allowlist; a sandboxed session writes nothing.
176
- ...(isSandboxed(this.context.start.configuration, this.context) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
185
+ ...(isSandboxed(this.context.start.configuration) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
177
186
  },
178
187
  spawnAgent: this.options.spawnAgent,
179
188
  onLine: line => this.receive(line),
@@ -237,6 +246,7 @@ class ClaudeDriver {
237
246
  echo.steered?.(this.current ? 'steered' : 'nextTurn');
238
247
  }
239
248
  async interrupt() {
249
+ this.clearRequests();
240
250
  if (!this.current)
241
251
  return;
242
252
  this.current.interrupted = true;
@@ -244,6 +254,7 @@ class ClaudeDriver {
244
254
  }
245
255
  async close() {
246
256
  this.closing = true;
257
+ this.clearRequests();
247
258
  await this.process?.kill();
248
259
  if (this.directory)
249
260
  await rm(this.directory, { recursive: true, force: true }).catch(() => { });
@@ -290,9 +301,14 @@ class ClaudeDriver {
290
301
  return;
291
302
  }
292
303
  case 'control_request':
293
- // Permission prompts never reach a session: it runs without prompts or with a read-only allowlist.
294
- this.process?.write(JSON.stringify({ type: 'control_response',
295
- response: { subtype: 'error', request_id: frame.request_id, error: 'Skillshare sessions do not answer this request.' } }));
304
+ this.permissionRequest(frame);
305
+ return;
306
+ case 'control_cancel_request':
307
+ for (const [id, pending] of this.permissions)
308
+ if (pending.nativeId === frame.request_id) {
309
+ this.permissions.delete(id);
310
+ this.context.requestResolved?.(id);
311
+ }
296
312
  return;
297
313
  case 'system':
298
314
  if (frame.subtype === 'init' && typeof frame.session_id === 'string')
@@ -313,6 +329,89 @@ class ClaudeDriver {
313
329
  return;
314
330
  }
315
331
  }
332
+ async permissionRequest(frame) {
333
+ const request = frame.request ?? {};
334
+ if (!this.context.request
335
+ || isSandboxed(this.context.start.configuration) && request.subtype === 'can_use_tool' && request.tool_name !== 'AskUserQuestion') {
336
+ this.process?.write(JSON.stringify({ type: 'control_response', response: {
337
+ subtype: 'error', request_id: frame.request_id, error: 'This agent request is not supported by the session.',
338
+ } }));
339
+ return;
340
+ }
341
+ const id = randomUUID();
342
+ const input = request.input ?? {};
343
+ const questions = request.tool_name === 'AskUserQuestion' && Array.isArray(input.questions) ? input.questions : undefined;
344
+ const kind = request.subtype === 'can_use_tool' ? 'tool' : request.subtype === 'elicitation' ? 'elicitation' : 'unsupported';
345
+ const pending = { nativeId: String(frame.request_id), input, questions, kind };
346
+ this.permissions.set(id, pending);
347
+ const schema = request.requested_schema ?? { type: 'object', properties: {} };
348
+ const form = kind === 'elicitation' && request.mode !== 'url' ? await nativeForm(schema) : undefined;
349
+ const empty = form && schema?.type === 'object' && Object.keys(schema.properties ?? {}).length === 0
350
+ && form.emptyValid;
351
+ const normalized = kind === 'unsupported' ? { id, kind: 'userInput', title: 'The agent needs attention',
352
+ adaptationWarning: `This native interaction (${String(request.subtype)}) is not supported yet. It remains waiting; no response has been sent.` }
353
+ : kind === 'elicitation' ? { id, kind: request.mode === 'url' || empty ? 'approval' : 'userInput', title: String(request.message ?? 'MCP server needs input'),
354
+ ...(request.mode === 'url' ? { detail: String(request.url ?? '') } : empty ? {} : { form: { schema, initialValue: form.initialValue }, adaptationWarning: form.warning }),
355
+ decisions: [{ id: 'accept', label: request.mode === 'url' || empty ? 'Approve' : 'Send response' }, { id: 'decline', label: 'Decline' }, { id: 'cancel', label: 'Cancel' }] }
356
+ : questions ? { id, kind: 'userInput', title: 'The agent needs your input', questions: questions.map((question, index) => ({
357
+ id: String(index), header: String(question.header ?? ''), question: String(question.question ?? ''),
358
+ options: question.options, multiSelect: question.multiSelect === true, secret: question.isSecret === true,
359
+ })) } : { id, kind: 'approval', title: `Allow ${String(request.tool_name ?? 'tool')}?`,
360
+ detail: [request.decision_reason?.reason, JSON.stringify(input, null, 2)].filter(Boolean).join('\n'),
361
+ scope: 'This tool invocation only', decisions: [{ id: 'accept', label: 'Approve once' }, { id: 'decline', label: 'Decline' }] };
362
+ normalized.originalRequest = JSON.stringify(request, null, 2);
363
+ const bounded = boundedSessionRequest(normalized);
364
+ if (this.closing || this.permissions.get(id) !== pending)
365
+ return;
366
+ Object.assign(pending, { form, schema, url: request.mode === 'url' });
367
+ this.context.request(bounded);
368
+ }
369
+ async respond(response) {
370
+ const pending = this.permissions.get(response.requestId);
371
+ if (!pending)
372
+ return;
373
+ if (pending.kind === 'unsupported')
374
+ return 'This native interaction has no supported response encoding. No response has been sent.';
375
+ let result;
376
+ if (pending.kind === 'elicitation') {
377
+ if (!['accept', 'decline', 'cancel'].includes(response.decision ?? ''))
378
+ return 'Choose a native MCP decision.';
379
+ if (response.decision !== 'accept' || pending.url)
380
+ result = { action: response.decision };
381
+ else {
382
+ const input = await nativeFormResponse(pending.schema, response.formData ?? '{}');
383
+ if (input.error)
384
+ return input.error;
385
+ result = { action: 'accept', content: input.value };
386
+ }
387
+ }
388
+ else {
389
+ if (!pending.questions && !['accept', 'decline'].includes(response.decision ?? ''))
390
+ return 'Choose whether to approve or decline the tool.';
391
+ if (pending.questions && !response.answers)
392
+ return 'Answer the agent questions before sending the response.';
393
+ const answers = pending.questions ? Object.fromEntries(pending.questions.map((question, index) => [String(question.question), (response.answers?.[String(index)] ?? []).join(', ')])) : undefined;
394
+ result = pending.questions || response.decision === 'accept'
395
+ ? { behavior: 'allow', updatedInput: { ...pending.input, ...(answers ? { answers } : {}) } }
396
+ : { behavior: 'deny', message: 'The user declined this action.' };
397
+ }
398
+ const serialized = JSON.stringify({ type: 'control_response', response: { subtype: 'success', request_id: pending.nativeId, response: result } });
399
+ if (this.context.responseAllowed?.(response.requestId) === false)
400
+ return;
401
+ if (await this.context.authorizeResponse?.(response) === false)
402
+ return;
403
+ if (this.closing || this.permissions.get(response.requestId) !== pending || this.context.responseAllowed?.(response.requestId) === false)
404
+ return;
405
+ if (!this.process?.write(serialized))
406
+ throw new Error('The agent is not accepting the response.');
407
+ this.permissions.delete(response.requestId);
408
+ this.context.requestResolved?.(response.requestId);
409
+ }
410
+ clearRequests() {
411
+ for (const id of this.permissions.keys())
412
+ this.context.requestResolved?.(id);
413
+ this.permissions.clear();
414
+ }
316
415
  /** Text arrives in deltas first; the complete assistant frame later replaces it under the same key. */
317
416
  streamEvent(event) {
318
417
  if (event.type === 'message_start' && typeof event.message?.id === 'string')
@@ -355,6 +454,7 @@ class ClaudeDriver {
355
454
  }
356
455
  }
357
456
  result(frame) {
457
+ this.clearRequests();
358
458
  if (typeof frame.session_id === 'string')
359
459
  this.adopt(frame.session_id);
360
460
  const current = this.current;
@@ -379,6 +479,7 @@ class ClaudeDriver {
379
479
  record({ status: 'failed', error: clip(detail, 2000), stats });
380
480
  }
381
481
  onExit(code) {
482
+ this.clearRequests();
382
483
  const reason = `Claude Code exited${code === null ? '' : ` with code ${code}`}${this.process?.stderrTail() ? `: ${this.process.stderrTail()}` : '.'}`;
383
484
  for (const waiter of this.controls.values())
384
485
  waiter.reject(new Error(reason));
@@ -1,5 +1,7 @@
1
1
  import { startAgentProcess } from './agents-process.js';
2
- import { DEFAULT, SANDBOX_NOTE, clip, isSandboxed, mcpServerName, mcpTokenEnvironment, oneLine, shadowedMcpServers, } from './agents-session.js';
2
+ import { randomUUID } from 'node:crypto';
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';
3
5
  /** Profile arguments that make sense for a long-running app-server; anything else belongs to codex exec only. */
4
6
  export function codexConfigArgs(args) {
5
7
  const kept = [];
@@ -44,15 +46,18 @@ export function codexConfiguredMcpServers(result) {
44
46
  }
45
47
  export function codexThreadParams(context, shadowed) {
46
48
  const { start } = context;
47
- const sandbox = isSandboxed(start.configuration, context);
49
+ const sandbox = isSandboxed(start.configuration);
48
50
  const servers = start.mcpServers ?? [];
49
51
  const instructions = [start.instructions?.trim(), sandbox ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
50
52
  return {
51
- cwd: context.profile?.workdir ?? context.workdir,
53
+ cwd: sessionWorkdir(context),
52
54
  ...(start.configuration.model !== DEFAULT ? { model: start.configuration.model } : {}),
53
55
  // Nobody watches for approval prompts, so the agent never asks: full access, or a read-only sandbox.
54
- approvalPolicy: 'never',
55
- sandbox: sandbox ? 'read-only' : 'danger-full-access',
56
+ approvalPolicy: sandbox || !start.configuration.approvalMode || start.configuration.approvalMode === 'fullAccess' ? 'never'
57
+ : start.configuration.approvalMode === 'supervised' ? 'untrusted' : 'on-request',
58
+ sandbox: sandbox || start.configuration.approvalMode === 'supervised' ? 'read-only'
59
+ : start.configuration.approvalMode && start.configuration.approvalMode !== 'fullAccess' ? 'workspace-write' : 'danger-full-access',
60
+ ...(start.configuration.approvalMode ? { approvalsReviewer: start.configuration.approvalMode === 'auto' ? 'auto_review' : 'user' } : {}),
56
61
  ...(instructions ? { developerInstructions: instructions } : {}),
57
62
  config: {
58
63
  'tools.update_plan.enabled': true,
@@ -117,22 +122,25 @@ class CodexDriver {
117
122
  threadId = null;
118
123
  current = null;
119
124
  texts = new Map();
125
+ approvalItems = new Map();
120
126
  /** The last finished turn, the only one whose predicted next message is still worth showing. */
121
127
  lastTurnId = null;
122
128
  /** Cleared once Codex says it cannot predict, so later turns do not ask again. */
123
129
  predictions = true;
124
130
  closing = false;
131
+ requests = new Map();
125
132
  constructor(context, options) {
126
133
  this.context = context;
127
134
  this.options = options;
128
135
  }
129
136
  async open() {
137
+ await validateSessionWorkdir(this.context);
130
138
  const { start } = this.context;
131
139
  const servers = start.mcpServers ?? [];
132
140
  this.process = startAgentProcess({
133
141
  command: this.options.command ?? 'codex',
134
142
  args: ['app-server', ...codexConfigArgs(this.context.profile?.args ?? [])],
135
- cwd: this.context.profile?.workdir ?? this.context.workdir,
143
+ cwd: sessionWorkdir(this.context),
136
144
  env: { ...mcpTokenEnvironment(servers), SKILLSHARE_SESSION_ID: this.context.sessionId },
137
145
  spawnAgent: this.options.spawnAgent,
138
146
  onLine: line => this.receive(line),
@@ -159,7 +167,7 @@ class CodexDriver {
159
167
  if (servers.length === 0)
160
168
  return [];
161
169
  try {
162
- const result = await this.request('config/read', { cwd: this.context.profile?.workdir ?? this.context.workdir });
170
+ const result = await this.request('config/read', { cwd: sessionWorkdir(this.context) });
163
171
  return shadowedMcpServers(codexConfiguredMcpServers(result), servers);
164
172
  }
165
173
  catch {
@@ -168,10 +176,16 @@ class CodexDriver {
168
176
  }
169
177
  turn(message) {
170
178
  const { configuration } = this.context.start;
179
+ const policy = configuration.approvalMode ? codexThreadParams(this.context) : undefined;
171
180
  return new Promise((resolve, reject) => {
172
181
  this.current = { resolve, usage: { input: 0, cached: 0, cacheWrite: 0, output: 0 } };
173
182
  this.request('turn/start', {
174
183
  threadId: this.threadId, input: codexInput(message),
184
+ ...(policy ? {
185
+ approvalPolicy: policy.approvalPolicy,
186
+ approvalsReviewer: configuration.approvalMode === 'auto' && !isSandboxed(configuration) ? 'auto_review' : 'user',
187
+ sandboxPolicy: { type: { 'read-only': 'readOnly', 'workspace-write': 'workspaceWrite', 'danger-full-access': 'dangerFullAccess' }[policy.sandbox] },
188
+ } : {}),
175
189
  ...(configuration.reasoning !== DEFAULT ? { effort: configuration.reasoning } : {}),
176
190
  }).then(result => {
177
191
  if (this.current && typeof result?.turn?.id === 'string')
@@ -183,6 +197,7 @@ class CodexDriver {
183
197
  });
184
198
  }
185
199
  async interrupt() {
200
+ this.clearRequests();
186
201
  if (this.current?.id && this.threadId)
187
202
  await this.request('turn/interrupt', { threadId: this.threadId, turnId: this.current.id });
188
203
  }
@@ -201,6 +216,7 @@ class CodexDriver {
201
216
  }
202
217
  async close() {
203
218
  this.closing = true;
219
+ this.clearRequests();
204
220
  await this.process?.kill();
205
221
  }
206
222
  /** Asks for the user's likely next message; it arrives as thread/prediction/updated. Codex 0.162 declares the method but does not implement it yet. */
@@ -251,19 +267,159 @@ class CodexDriver {
251
267
  if (typeof message.method === 'string')
252
268
  this.notification(message.method, message.params ?? {});
253
269
  }
254
- /** Codex asks the client only for approvals and input, which a session never gives: the approval policy is never. */
255
- answer(message) {
256
- const reply = /requestApproval$/.test(message.method) ? { id: message.id, result: { decision: 'decline' } }
257
- : { id: message.id, error: { code: -32601, message: 'Skillshare sessions do not answer this request.' } };
258
- this.process?.write(JSON.stringify(reply));
270
+ /** Native request ids may be reused after reconnect; our ids remain unique for the session. */
271
+ async answer(message) {
272
+ const params = message.params ?? {};
273
+ const item = this.approvalItems.get(String(params.itemId ?? ''));
274
+ const method = String(message.method);
275
+ if (!this.context.request || isSandboxed(this.context.start.configuration) && /requestApproval$/.test(method)) {
276
+ this.process?.write(JSON.stringify(/requestApproval$/.test(method) ? { id: message.id, result: { decision: 'decline' } }
277
+ : { id: message.id, error: { code: -32601, message: 'This request is not supported by the session.' } }));
278
+ return;
279
+ }
280
+ const id = randomUUID();
281
+ const decisions = new Map();
282
+ let kind = 'approval';
283
+ let form;
284
+ let questionIds;
285
+ const pending = { nativeId: message.id, kind, params, decisions };
286
+ this.requests.set(id, pending);
287
+ let request;
288
+ if (method === 'item/tool/requestUserInput') {
289
+ kind = 'userInput';
290
+ const questions = Array.isArray(params.questions) ? params.questions : [];
291
+ const counts = new Map();
292
+ for (const q of questions)
293
+ counts.set(String(q.id), (counts.get(String(q.id)) ?? 0) + 1);
294
+ questionIds = new Map();
295
+ request = { id, kind: 'userInput', title: 'The agent needs your input', questions: questions.map((q, index) => ({
296
+ id: String(q.id).length > 0 && String(q.id).length <= 100 && counts.get(String(q.id)) === 1
297
+ && !Object.hasOwn(Object.prototype, String(q.id)) ? String(q.id) : `${id}-${index}`,
298
+ header: String(q.header ?? ''), question: String(q.question ?? ''), options: q.options, multiSelect: q.multiSelect === true, secret: q.isSecret === true,
299
+ })) };
300
+ // Retain the local-to-native mapping even when the provider uses long or duplicate field ids.
301
+ request.questions.forEach((q, index) => questionIds.set(q.id, String(questions[index].id)));
302
+ }
303
+ else if (method === 'item/permissions/requestApproval') {
304
+ kind = 'permissions';
305
+ const scope = JSON.stringify(params.permissions ?? {}, null, 2);
306
+ decisions.set('accept', true);
307
+ decisions.set('decline', false);
308
+ request = { id, kind: 'approval', title: 'Allow additional permissions?', detail: params.reason, scope,
309
+ decisions: [{ id: 'accept', label: 'Approve for this turn', scope }, { id: 'decline', label: 'Decline' }] };
310
+ }
311
+ else if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
312
+ const available = Array.isArray(params.availableDecisions) ? params.availableDecisions : ['accept', 'decline', 'cancel'];
313
+ const command = typeof params.command === 'string' ? params.command : typeof item?.command === 'string' ? item.command : undefined;
314
+ // Permission grants must fit intact in the persisted scope, rather than being clipped out of the details.
315
+ const scope = params.additionalPermissions != null || params.networkApprovalContext != null
316
+ ? JSON.stringify({ command, cwd: params.cwd, grantRoot: params.grantRoot,
317
+ additionalPermissions: params.additionalPermissions, networkApprovalContext: params.networkApprovalContext }, null, 2)
318
+ : command ?? (typeof params.grantRoot === 'string' ? params.grantRoot : undefined);
319
+ for (const decision of available) {
320
+ const key = typeof decision === 'string' && decision.length > 0 && decision.length <= 100 ? decision : `decision-${decisions.size}`;
321
+ decisions.set(key, decision);
322
+ }
323
+ request = { id, kind: 'approval', title: method.includes('fileChange') ? 'Allow file changes?' : 'Allow command execution?',
324
+ detail: [params.reason, command, params.cwd && `Directory: ${params.cwd}`,
325
+ item?.type === 'fileChange' ? JSON.stringify(item.changes ?? [], null, 2) : undefined].filter(Boolean).join('\n'), scope,
326
+ decisions: [...decisions].map(([key, value]) => ({ id: key,
327
+ label: key === 'accept' ? 'Approve' : key === 'acceptForSession' ? 'Allow for this session' : key === 'cancel' ? 'Cancel turn' : key === 'decline' ? 'Decline'
328
+ : typeof value === 'object' && value !== null && 'acceptWithExecpolicyAmendment' in value ? 'Approve and save command policy'
329
+ : typeof value === 'object' && value !== null && 'applyNetworkPolicyAmendment' in value ? 'Apply persistent network policy' : `Native decision: ${key}`,
330
+ ...(key === 'acceptForSession' ? { scope: scope ?? 'The native session approval cache' }
331
+ : typeof value === 'object' ? { scope: JSON.stringify(value, null, 2) } : {}) })) };
332
+ }
333
+ else if (method === 'mcpServer/elicitation/request') {
334
+ kind = 'elicitation';
335
+ const schema = params.requestedSchema ?? { type: 'object', properties: {} };
336
+ form = params.mode === 'url' ? undefined : await nativeForm(schema);
337
+ const empty = params.mode !== 'url' && schema?.type === 'object' && Object.keys(schema.properties ?? {}).length === 0
338
+ && form.emptyValid;
339
+ request = { id, kind: params.mode === 'url' || empty ? 'approval' : 'userInput', title: String(params.message ?? 'MCP server needs input'),
340
+ ...(params.mode === 'url' ? { detail: String(params.url ?? '') } : empty ? {} : { form: { schema, initialValue: form.initialValue }, adaptationWarning: form.warning }),
341
+ decisions: [{ id: 'accept', label: params.mode === 'url' || empty ? 'Approve' : 'Send response' }, { id: 'decline', label: 'Decline' }, { id: 'cancel', label: 'Cancel' }] };
342
+ }
343
+ else {
344
+ kind = 'unsupported';
345
+ request = { id, kind: 'userInput', title: 'The agent needs attention',
346
+ adaptationWarning: `This native interaction (${method}) is not supported yet. It remains waiting; no response has been sent.` };
347
+ }
348
+ request.originalRequest = JSON.stringify({ method, params }, null, 2);
349
+ const bounded = boundedSessionRequest(request);
350
+ if (this.closing || this.requests.get(id) !== pending)
351
+ return;
352
+ Object.assign(pending, { kind, form, questionIds });
353
+ this.context.request(bounded);
354
+ }
355
+ async respond(response) {
356
+ const pending = this.requests.get(response.requestId);
357
+ if (!pending)
358
+ return;
359
+ if (pending.kind === 'unsupported')
360
+ return 'This native interaction has no supported response encoding. No response has been sent.';
361
+ let result;
362
+ if (pending.kind === 'userInput') {
363
+ if (!response.answers)
364
+ return 'Answer the agent questions before sending the response.';
365
+ result = { answers: Object.fromEntries([...(pending.questionIds ?? [])].map(([localId, nativeId]) => [nativeId, { answers: response.answers[localId] ?? [] }])) };
366
+ }
367
+ else if (pending.kind === 'elicitation') {
368
+ if (!['accept', 'decline', 'cancel'].includes(response.decision ?? ''))
369
+ return 'Choose a native MCP decision.';
370
+ if (response.decision !== 'accept' || pending.params.mode === 'url')
371
+ result = { action: response.decision };
372
+ else {
373
+ const schema = pending.params.requestedSchema ?? { type: 'object', properties: {} };
374
+ const input = await nativeFormResponse(schema, response.formData ?? '{}');
375
+ if (input.error)
376
+ return input.error;
377
+ result = { action: 'accept', content: input.value };
378
+ }
379
+ }
380
+ else {
381
+ if (!pending.decisions.has(response.decision ?? ''))
382
+ return 'Choose one of the native decisions shown in the request.';
383
+ result = pending.kind === 'permissions' ? { permissions: response.decision === 'accept' ? pending.params.permissions : {}, scope: 'turn' }
384
+ : { decision: pending.decisions.get(response.decision) };
385
+ }
386
+ const serialized = JSON.stringify({ id: pending.nativeId, result });
387
+ if (this.context.responseAllowed?.(response.requestId) === false)
388
+ return;
389
+ if (await this.context.authorizeResponse?.(response) === false)
390
+ return;
391
+ if (this.closing || this.requests.get(response.requestId) !== pending || this.context.responseAllowed?.(response.requestId) === false)
392
+ return;
393
+ if (!this.process?.write(serialized))
394
+ throw new Error('The agent is not accepting the response.');
395
+ this.requests.delete(response.requestId);
396
+ this.context.requestResolved?.(response.requestId);
397
+ }
398
+ clearRequests() {
399
+ for (const id of this.requests.keys())
400
+ this.context.requestResolved?.(id);
401
+ this.requests.clear();
259
402
  }
260
403
  notification(method, params) {
404
+ // Approvals and questions from child threads also belong to this connection's session.
405
+ if (method === 'serverRequest/resolved') {
406
+ for (const [id, request] of this.requests) {
407
+ if (request.nativeId !== params.requestId
408
+ || typeof params.threadId === 'string' && params.threadId !== (request.params.threadId ?? this.threadId))
409
+ continue;
410
+ this.requests.delete(id);
411
+ this.context.requestResolved?.(id);
412
+ }
413
+ return;
414
+ }
261
415
  // Subagent threads report on the same connection; only the session's own thread is transcribed.
262
416
  if (typeof params.threadId === 'string' && this.threadId && params.threadId !== this.threadId)
263
417
  return;
264
418
  switch (method) {
265
419
  case 'item/started':
266
420
  case 'item/completed': {
421
+ if (params.item?.id && ['fileChange', 'commandExecution'].includes(params.item.type))
422
+ this.approvalItems.set(String(params.item.id), params.item);
267
423
  const item = codexItem(params.item);
268
424
  if (!item)
269
425
  return;
@@ -320,6 +476,8 @@ class CodexDriver {
320
476
  const current = this.current;
321
477
  if (!current || current.id && turn.id && turn.id !== current.id)
322
478
  return;
479
+ this.clearRequests();
480
+ this.approvalItems.clear();
323
481
  this.current = null;
324
482
  const status = turn.status === 'completed' ? 'completed' : turn.status === 'interrupted' ? 'interrupted' : 'failed';
325
483
  const { usage } = current;
@@ -342,6 +500,7 @@ class CodexDriver {
342
500
  }
343
501
  }
344
502
  onExit(code) {
503
+ this.clearRequests();
345
504
  const reason = `Codex exited${code === null ? '' : ` with code ${code}`}${this.process?.stderrTail() ? `: ${this.process.stderrTail()}` : '.'}`;
346
505
  for (const pending of this.pending.values())
347
506
  pending.reject(new Error(reason));