@quadient/skillshare 1.17.1 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -94,7 +100,7 @@ skillshare teams login
94
100
  skillshare teams status
95
101
  skillshare teams test
96
102
  skillshare teams watch
97
- skillshare teams access fullAccess
103
+ skillshare teams access limitedAccess # allow writes except editing/deleting messages
98
104
  skillshare teams upload ./report.pdf
99
105
  skillshare teams download '<file-webUrl-or-download-link>' --output ./report.pdf
100
106
  skillshare teams access readOnly
@@ -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_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';
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,22 @@ 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
+ 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');
30
32
  }
31
33
  export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPath) {
32
34
  const { start } = context;
33
- const sandbox = isSandboxed(start.configuration, context);
35
+ const sandbox = isSandboxed(start.configuration);
34
36
  const servers = start.mcpServers ?? [];
37
+ if (isLockedDown(start))
38
+ return claudeLockdownArgs(start, servers, mcpConfigPath, instructionsPath);
35
39
  // Replayed user messages tell when Claude Code took a message, which is how a steered message is known to have joined the turn.
36
40
  const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--replay-user-messages',
37
41
  ...(sandbox
38
42
  // A sandboxed session never prompts: anything outside the read-only allowlist is denied.
39
43
  ? ['--permission-mode', 'dontAsk', '--allowedTools', ...CLAUDE_SANDBOX_TOOLS, ...servers.map((server, index) => `mcp__${mcpServerName(server, index)}`)]
40
- : ['--dangerously-skip-permissions'])];
44
+ : !start.configuration.approvalMode || start.configuration.approvalMode === 'fullAccess' ? ['--dangerously-skip-permissions']
45
+ : ['--permission-mode', { supervised: 'default', autoEdits: 'acceptEdits', auto: 'auto' }[start.configuration.approvalMode], '--permission-prompt-tool', 'stdio'])];
41
46
  if (start.configuration.model !== DEFAULT)
42
47
  args.push('--model', start.configuration.model);
43
48
  if (start.configuration.reasoning !== DEFAULT)
@@ -50,8 +55,34 @@ export function claudeArgs(context, mcpConfigPath, instructionsPath, settingsPat
50
55
  args.push('--settings', settingsPath);
51
56
  if (start.resumeThreadId)
52
57
  args.push('--resume', start.resumeThreadId);
58
+ // A named profile may add tuning arguments, but cannot silently replace the session's selected permission mode.
59
+ if (start.configuration.approvalMode && (context.profile?.args ?? []).some(arg => /^--(?:permission-mode|dangerously-skip-permissions|allow-dangerously-skip-permissions)(?:=|$)/.test(arg)))
60
+ throw new Error('The local profile overrides permission flags. Remove those flags to use a session approval mode.');
61
+ if (start.configuration.approvalMode === 'fullAccess')
62
+ args.push('--permission-prompt-tool', 'stdio');
53
63
  return [...args, ...(context.profile?.args ?? [])];
54
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
+ }
55
86
  export function claudeMcpConfig(servers) {
56
87
  return JSON.stringify({
57
88
  mcpServers: Object.fromEntries(servers.map((server, index) => [mcpServerName(server, index),
@@ -138,18 +169,20 @@ class ClaudeDriver {
138
169
  early = [];
139
170
  costSoFar = 0;
140
171
  closing = false;
172
+ permissions = new Map();
141
173
  constructor(context, options) {
142
174
  this.context = context;
143
175
  this.options = options;
144
176
  }
145
177
  async open() {
178
+ await validateSessionWorkdir(this.context);
146
179
  const servers = this.context.start.mcpServers ?? [];
147
180
  const instructions = claudeInstructions(this.context);
148
181
  let mcpConfig;
149
182
  let instructionsFile;
150
183
  let settingsFile;
151
- const workdir = this.context.profile?.workdir ?? this.context.workdir;
152
- const shadowed = servers.length > 0 ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
184
+ const workdir = sessionWorkdir(this.context);
185
+ const shadowed = servers.length > 0 && !isLockedDown(this.context.start) ? shadowedMcpServers(claudeConfiguredMcpServers(workdir), servers) : [];
153
186
  if (servers.length > 0 || instructions)
154
187
  this.directory = await mkdtemp(join(tmpdir(), 'skillshare-session-'));
155
188
  if (servers.length > 0) {
@@ -173,7 +206,7 @@ class ClaudeDriver {
173
206
  // Claude Code holds suggestions back when the account nears a rate limit; the user can still turn them off with this variable.
174
207
  CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION: process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION ?? 'true',
175
208
  // 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' } : {}),
209
+ ...(isSandboxed(this.context.start.configuration) || isLockedDown(this.context.start) ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {}),
177
210
  },
178
211
  spawnAgent: this.options.spawnAgent,
179
212
  onLine: line => this.receive(line),
@@ -237,6 +270,7 @@ class ClaudeDriver {
237
270
  echo.steered?.(this.current ? 'steered' : 'nextTurn');
238
271
  }
239
272
  async interrupt() {
273
+ this.clearRequests();
240
274
  if (!this.current)
241
275
  return;
242
276
  this.current.interrupted = true;
@@ -244,6 +278,7 @@ class ClaudeDriver {
244
278
  }
245
279
  async close() {
246
280
  this.closing = true;
281
+ this.clearRequests();
247
282
  await this.process?.kill();
248
283
  if (this.directory)
249
284
  await rm(this.directory, { recursive: true, force: true }).catch(() => { });
@@ -290,9 +325,14 @@ class ClaudeDriver {
290
325
  return;
291
326
  }
292
327
  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.' } }));
328
+ this.permissionRequest(frame);
329
+ return;
330
+ case 'control_cancel_request':
331
+ for (const [id, pending] of this.permissions)
332
+ if (pending.nativeId === frame.request_id) {
333
+ this.permissions.delete(id);
334
+ this.context.requestResolved?.(id);
335
+ }
296
336
  return;
297
337
  case 'system':
298
338
  if (frame.subtype === 'init' && typeof frame.session_id === 'string')
@@ -313,6 +353,89 @@ class ClaudeDriver {
313
353
  return;
314
354
  }
315
355
  }
356
+ async permissionRequest(frame) {
357
+ const request = frame.request ?? {};
358
+ if (!this.context.request
359
+ || isSandboxed(this.context.start.configuration) && request.subtype === 'can_use_tool' && request.tool_name !== 'AskUserQuestion') {
360
+ this.process?.write(JSON.stringify({ type: 'control_response', response: {
361
+ subtype: 'error', request_id: frame.request_id, error: 'This agent request is not supported by the session.',
362
+ } }));
363
+ return;
364
+ }
365
+ const id = randomUUID();
366
+ const input = request.input ?? {};
367
+ const questions = request.tool_name === 'AskUserQuestion' && Array.isArray(input.questions) ? input.questions : undefined;
368
+ const kind = request.subtype === 'can_use_tool' ? 'tool' : request.subtype === 'elicitation' ? 'elicitation' : 'unsupported';
369
+ const pending = { nativeId: String(frame.request_id), input, questions, kind };
370
+ this.permissions.set(id, pending);
371
+ const schema = request.requested_schema ?? { type: 'object', properties: {} };
372
+ const form = kind === 'elicitation' && request.mode !== 'url' ? await nativeForm(schema) : undefined;
373
+ const empty = form && schema?.type === 'object' && Object.keys(schema.properties ?? {}).length === 0
374
+ && form.emptyValid;
375
+ const normalized = kind === 'unsupported' ? { id, kind: 'userInput', title: 'The agent needs attention',
376
+ adaptationWarning: `This native interaction (${String(request.subtype)}) is not supported yet. It remains waiting; no response has been sent.` }
377
+ : kind === 'elicitation' ? { id, kind: request.mode === 'url' || empty ? 'approval' : 'userInput', title: String(request.message ?? 'MCP server needs input'),
378
+ ...(request.mode === 'url' ? { detail: String(request.url ?? '') } : empty ? {} : { form: { schema, initialValue: form.initialValue }, adaptationWarning: form.warning }),
379
+ decisions: [{ id: 'accept', label: request.mode === 'url' || empty ? 'Approve' : 'Send response' }, { id: 'decline', label: 'Decline' }, { id: 'cancel', label: 'Cancel' }] }
380
+ : questions ? { id, kind: 'userInput', title: 'The agent needs your input', questions: questions.map((question, index) => ({
381
+ id: String(index), header: String(question.header ?? ''), question: String(question.question ?? ''),
382
+ options: question.options, multiSelect: question.multiSelect === true, secret: question.isSecret === true,
383
+ })) } : { id, kind: 'approval', title: `Allow ${String(request.tool_name ?? 'tool')}?`,
384
+ detail: [request.decision_reason?.reason, JSON.stringify(input, null, 2)].filter(Boolean).join('\n'),
385
+ scope: 'This tool invocation only', decisions: [{ id: 'accept', label: 'Approve once' }, { id: 'decline', label: 'Decline' }] };
386
+ normalized.originalRequest = JSON.stringify(request, null, 2);
387
+ const bounded = boundedSessionRequest(normalized);
388
+ if (this.closing || this.permissions.get(id) !== pending)
389
+ return;
390
+ Object.assign(pending, { form, schema, url: request.mode === 'url' });
391
+ this.context.request(bounded);
392
+ }
393
+ async respond(response) {
394
+ const pending = this.permissions.get(response.requestId);
395
+ if (!pending)
396
+ return;
397
+ if (pending.kind === 'unsupported')
398
+ return 'This native interaction has no supported response encoding. No response has been sent.';
399
+ let result;
400
+ if (pending.kind === 'elicitation') {
401
+ if (!['accept', 'decline', 'cancel'].includes(response.decision ?? ''))
402
+ return 'Choose a native MCP decision.';
403
+ if (response.decision !== 'accept' || pending.url)
404
+ result = { action: response.decision };
405
+ else {
406
+ const input = await nativeFormResponse(pending.schema, response.formData ?? '{}');
407
+ if (input.error)
408
+ return input.error;
409
+ result = { action: 'accept', content: input.value };
410
+ }
411
+ }
412
+ else {
413
+ if (!pending.questions && !['accept', 'decline'].includes(response.decision ?? ''))
414
+ return 'Choose whether to approve or decline the tool.';
415
+ if (pending.questions && !response.answers)
416
+ return 'Answer the agent questions before sending the response.';
417
+ const answers = pending.questions ? Object.fromEntries(pending.questions.map((question, index) => [String(question.question), (response.answers?.[String(index)] ?? []).join(', ')])) : undefined;
418
+ result = pending.questions || response.decision === 'accept'
419
+ ? { behavior: 'allow', updatedInput: { ...pending.input, ...(answers ? { answers } : {}) } }
420
+ : { behavior: 'deny', message: 'The user declined this action.' };
421
+ }
422
+ const serialized = JSON.stringify({ type: 'control_response', response: { subtype: 'success', request_id: pending.nativeId, response: result } });
423
+ if (this.context.responseAllowed?.(response.requestId) === false)
424
+ return;
425
+ if (await this.context.authorizeResponse?.(response) === false)
426
+ return;
427
+ if (this.closing || this.permissions.get(response.requestId) !== pending || this.context.responseAllowed?.(response.requestId) === false)
428
+ return;
429
+ if (!this.process?.write(serialized))
430
+ throw new Error('The agent is not accepting the response.');
431
+ this.permissions.delete(response.requestId);
432
+ this.context.requestResolved?.(response.requestId);
433
+ }
434
+ clearRequests() {
435
+ for (const id of this.permissions.keys())
436
+ this.context.requestResolved?.(id);
437
+ this.permissions.clear();
438
+ }
316
439
  /** Text arrives in deltas first; the complete assistant frame later replaces it under the same key. */
317
440
  streamEvent(event) {
318
441
  if (event.type === 'message_start' && typeof event.message?.id === 'string')
@@ -355,6 +478,7 @@ class ClaudeDriver {
355
478
  }
356
479
  }
357
480
  result(frame) {
481
+ this.clearRequests();
358
482
  if (typeof frame.session_id === 'string')
359
483
  this.adopt(frame.session_id);
360
484
  const current = this.current;
@@ -379,6 +503,7 @@ class ClaudeDriver {
379
503
  record({ status: 'failed', error: clip(detail, 2000), stats });
380
504
  }
381
505
  onExit(code) {
506
+ this.clearRequests();
382
507
  const reason = `Claude Code exited${code === null ? '' : ` with code ${code}`}${this.process?.stderrTail() ? `: ${this.process.stderrTail()}` : '.'}`;
383
508
  for (const waiter of this.controls.values())
384
509
  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, LOCKDOWN_NOTE, SANDBOX_NOTE, clip, isLockedDown, 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,30 @@ 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 ?? [];
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
+ }
49
63
  const instructions = [start.instructions?.trim(), sandbox ? SANDBOX_NOTE : undefined].filter(Boolean).join('\n\n');
50
64
  return {
51
- cwd: context.profile?.workdir ?? context.workdir,
65
+ cwd: sessionWorkdir(context),
52
66
  ...(start.configuration.model !== DEFAULT ? { model: start.configuration.model } : {}),
53
67
  // 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',
68
+ approvalPolicy: sandbox || !start.configuration.approvalMode || start.configuration.approvalMode === 'fullAccess' ? 'never'
69
+ : start.configuration.approvalMode === 'supervised' ? 'untrusted' : 'on-request',
70
+ sandbox: sandbox || start.configuration.approvalMode === 'supervised' ? 'read-only'
71
+ : start.configuration.approvalMode && start.configuration.approvalMode !== 'fullAccess' ? 'workspace-write' : 'danger-full-access',
72
+ ...(start.configuration.approvalMode ? { approvalsReviewer: start.configuration.approvalMode === 'auto' ? 'auto_review' : 'user' } : {}),
56
73
  ...(instructions ? { developerInstructions: instructions } : {}),
57
74
  config: {
58
75
  'tools.update_plan.enabled': true,
@@ -117,22 +134,25 @@ class CodexDriver {
117
134
  threadId = null;
118
135
  current = null;
119
136
  texts = new Map();
137
+ approvalItems = new Map();
120
138
  /** The last finished turn, the only one whose predicted next message is still worth showing. */
121
139
  lastTurnId = null;
122
140
  /** Cleared once Codex says it cannot predict, so later turns do not ask again. */
123
141
  predictions = true;
124
142
  closing = false;
143
+ requests = new Map();
125
144
  constructor(context, options) {
126
145
  this.context = context;
127
146
  this.options = options;
128
147
  }
129
148
  async open() {
149
+ await validateSessionWorkdir(this.context);
130
150
  const { start } = this.context;
131
151
  const servers = start.mcpServers ?? [];
132
152
  this.process = startAgentProcess({
133
153
  command: this.options.command ?? 'codex',
134
- args: ['app-server', ...codexConfigArgs(this.context.profile?.args ?? [])],
135
- cwd: this.context.profile?.workdir ?? this.context.workdir,
154
+ args: ['app-server', ...(isLockedDown(start) ? [] : codexConfigArgs(this.context.profile?.args ?? []))],
155
+ cwd: sessionWorkdir(this.context),
136
156
  env: { ...mcpTokenEnvironment(servers), SKILLSHARE_SESSION_ID: this.context.sessionId },
137
157
  spawnAgent: this.options.spawnAgent,
138
158
  onLine: line => this.receive(line),
@@ -144,7 +164,7 @@ class CodexDriver {
144
164
  capabilities: { experimentalApi: true, optOutNotificationMethods: ['turn/diff/updated', 'mcpServer/startupStatus/updated'] },
145
165
  });
146
166
  this.notify('initialized');
147
- const params = codexThreadParams(this.context, await this.shadowedServers(servers));
167
+ const params = codexThreadParams(this.context, isLockedDown(start) ? undefined : await this.shadowedServers(servers));
148
168
  const result = start.resumeThreadId
149
169
  ? await this.request('thread/resume', { threadId: start.resumeThreadId, ...params })
150
170
  : await this.request('thread/start', params);
@@ -159,7 +179,7 @@ class CodexDriver {
159
179
  if (servers.length === 0)
160
180
  return [];
161
181
  try {
162
- const result = await this.request('config/read', { cwd: this.context.profile?.workdir ?? this.context.workdir });
182
+ const result = await this.request('config/read', { cwd: sessionWorkdir(this.context) });
163
183
  return shadowedMcpServers(codexConfiguredMcpServers(result), servers);
164
184
  }
165
185
  catch {
@@ -168,10 +188,16 @@ class CodexDriver {
168
188
  }
169
189
  turn(message) {
170
190
  const { configuration } = this.context.start;
191
+ const policy = configuration.approvalMode ? codexThreadParams(this.context) : undefined;
171
192
  return new Promise((resolve, reject) => {
172
193
  this.current = { resolve, usage: { input: 0, cached: 0, cacheWrite: 0, output: 0 } };
173
194
  this.request('turn/start', {
174
195
  threadId: this.threadId, input: codexInput(message),
196
+ ...(policy ? {
197
+ approvalPolicy: policy.approvalPolicy,
198
+ approvalsReviewer: configuration.approvalMode === 'auto' && !isSandboxed(configuration) ? 'auto_review' : 'user',
199
+ sandboxPolicy: { type: { 'read-only': 'readOnly', 'workspace-write': 'workspaceWrite', 'danger-full-access': 'dangerFullAccess' }[policy.sandbox] },
200
+ } : {}),
175
201
  ...(configuration.reasoning !== DEFAULT ? { effort: configuration.reasoning } : {}),
176
202
  }).then(result => {
177
203
  if (this.current && typeof result?.turn?.id === 'string')
@@ -183,6 +209,7 @@ class CodexDriver {
183
209
  });
184
210
  }
185
211
  async interrupt() {
212
+ this.clearRequests();
186
213
  if (this.current?.id && this.threadId)
187
214
  await this.request('turn/interrupt', { threadId: this.threadId, turnId: this.current.id });
188
215
  }
@@ -201,6 +228,7 @@ class CodexDriver {
201
228
  }
202
229
  async close() {
203
230
  this.closing = true;
231
+ this.clearRequests();
204
232
  await this.process?.kill();
205
233
  }
206
234
  /** 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 +279,159 @@ class CodexDriver {
251
279
  if (typeof message.method === 'string')
252
280
  this.notification(message.method, message.params ?? {});
253
281
  }
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));
282
+ /** Native request ids may be reused after reconnect; our ids remain unique for the session. */
283
+ async answer(message) {
284
+ const params = message.params ?? {};
285
+ const item = this.approvalItems.get(String(params.itemId ?? ''));
286
+ const method = String(message.method);
287
+ if (!this.context.request || isSandboxed(this.context.start.configuration) && /requestApproval$/.test(method)) {
288
+ this.process?.write(JSON.stringify(/requestApproval$/.test(method) ? { id: message.id, result: { decision: 'decline' } }
289
+ : { id: message.id, error: { code: -32601, message: 'This request is not supported by the session.' } }));
290
+ return;
291
+ }
292
+ const id = randomUUID();
293
+ const decisions = new Map();
294
+ let kind = 'approval';
295
+ let form;
296
+ let questionIds;
297
+ const pending = { nativeId: message.id, kind, params, decisions };
298
+ this.requests.set(id, pending);
299
+ let request;
300
+ if (method === 'item/tool/requestUserInput') {
301
+ kind = 'userInput';
302
+ const questions = Array.isArray(params.questions) ? params.questions : [];
303
+ const counts = new Map();
304
+ for (const q of questions)
305
+ counts.set(String(q.id), (counts.get(String(q.id)) ?? 0) + 1);
306
+ questionIds = new Map();
307
+ request = { id, kind: 'userInput', title: 'The agent needs your input', questions: questions.map((q, index) => ({
308
+ id: String(q.id).length > 0 && String(q.id).length <= 100 && counts.get(String(q.id)) === 1
309
+ && !Object.hasOwn(Object.prototype, String(q.id)) ? String(q.id) : `${id}-${index}`,
310
+ header: String(q.header ?? ''), question: String(q.question ?? ''), options: q.options, multiSelect: q.multiSelect === true, secret: q.isSecret === true,
311
+ })) };
312
+ // Retain the local-to-native mapping even when the provider uses long or duplicate field ids.
313
+ request.questions.forEach((q, index) => questionIds.set(q.id, String(questions[index].id)));
314
+ }
315
+ else if (method === 'item/permissions/requestApproval') {
316
+ kind = 'permissions';
317
+ const scope = JSON.stringify(params.permissions ?? {}, null, 2);
318
+ decisions.set('accept', true);
319
+ decisions.set('decline', false);
320
+ request = { id, kind: 'approval', title: 'Allow additional permissions?', detail: params.reason, scope,
321
+ decisions: [{ id: 'accept', label: 'Approve for this turn', scope }, { id: 'decline', label: 'Decline' }] };
322
+ }
323
+ else if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
324
+ const available = Array.isArray(params.availableDecisions) ? params.availableDecisions : ['accept', 'decline', 'cancel'];
325
+ const command = typeof params.command === 'string' ? params.command : typeof item?.command === 'string' ? item.command : undefined;
326
+ // Permission grants must fit intact in the persisted scope, rather than being clipped out of the details.
327
+ const scope = params.additionalPermissions != null || params.networkApprovalContext != null
328
+ ? JSON.stringify({ command, cwd: params.cwd, grantRoot: params.grantRoot,
329
+ additionalPermissions: params.additionalPermissions, networkApprovalContext: params.networkApprovalContext }, null, 2)
330
+ : command ?? (typeof params.grantRoot === 'string' ? params.grantRoot : undefined);
331
+ for (const decision of available) {
332
+ const key = typeof decision === 'string' && decision.length > 0 && decision.length <= 100 ? decision : `decision-${decisions.size}`;
333
+ decisions.set(key, decision);
334
+ }
335
+ request = { id, kind: 'approval', title: method.includes('fileChange') ? 'Allow file changes?' : 'Allow command execution?',
336
+ detail: [params.reason, command, params.cwd && `Directory: ${params.cwd}`,
337
+ item?.type === 'fileChange' ? JSON.stringify(item.changes ?? [], null, 2) : undefined].filter(Boolean).join('\n'), scope,
338
+ decisions: [...decisions].map(([key, value]) => ({ id: key,
339
+ label: key === 'accept' ? 'Approve' : key === 'acceptForSession' ? 'Allow for this session' : key === 'cancel' ? 'Cancel turn' : key === 'decline' ? 'Decline'
340
+ : typeof value === 'object' && value !== null && 'acceptWithExecpolicyAmendment' in value ? 'Approve and save command policy'
341
+ : typeof value === 'object' && value !== null && 'applyNetworkPolicyAmendment' in value ? 'Apply persistent network policy' : `Native decision: ${key}`,
342
+ ...(key === 'acceptForSession' ? { scope: scope ?? 'The native session approval cache' }
343
+ : typeof value === 'object' ? { scope: JSON.stringify(value, null, 2) } : {}) })) };
344
+ }
345
+ else if (method === 'mcpServer/elicitation/request') {
346
+ kind = 'elicitation';
347
+ const schema = params.requestedSchema ?? { type: 'object', properties: {} };
348
+ form = params.mode === 'url' ? undefined : await nativeForm(schema);
349
+ const empty = params.mode !== 'url' && schema?.type === 'object' && Object.keys(schema.properties ?? {}).length === 0
350
+ && form.emptyValid;
351
+ request = { id, kind: params.mode === 'url' || empty ? 'approval' : 'userInput', title: String(params.message ?? 'MCP server needs input'),
352
+ ...(params.mode === 'url' ? { detail: String(params.url ?? '') } : empty ? {} : { form: { schema, initialValue: form.initialValue }, adaptationWarning: form.warning }),
353
+ decisions: [{ id: 'accept', label: params.mode === 'url' || empty ? 'Approve' : 'Send response' }, { id: 'decline', label: 'Decline' }, { id: 'cancel', label: 'Cancel' }] };
354
+ }
355
+ else {
356
+ kind = 'unsupported';
357
+ request = { id, kind: 'userInput', title: 'The agent needs attention',
358
+ adaptationWarning: `This native interaction (${method}) is not supported yet. It remains waiting; no response has been sent.` };
359
+ }
360
+ request.originalRequest = JSON.stringify({ method, params }, null, 2);
361
+ const bounded = boundedSessionRequest(request);
362
+ if (this.closing || this.requests.get(id) !== pending)
363
+ return;
364
+ Object.assign(pending, { kind, form, questionIds });
365
+ this.context.request(bounded);
366
+ }
367
+ async respond(response) {
368
+ const pending = this.requests.get(response.requestId);
369
+ if (!pending)
370
+ return;
371
+ if (pending.kind === 'unsupported')
372
+ return 'This native interaction has no supported response encoding. No response has been sent.';
373
+ let result;
374
+ if (pending.kind === 'userInput') {
375
+ if (!response.answers)
376
+ return 'Answer the agent questions before sending the response.';
377
+ result = { answers: Object.fromEntries([...(pending.questionIds ?? [])].map(([localId, nativeId]) => [nativeId, { answers: response.answers[localId] ?? [] }])) };
378
+ }
379
+ else if (pending.kind === 'elicitation') {
380
+ if (!['accept', 'decline', 'cancel'].includes(response.decision ?? ''))
381
+ return 'Choose a native MCP decision.';
382
+ if (response.decision !== 'accept' || pending.params.mode === 'url')
383
+ result = { action: response.decision };
384
+ else {
385
+ const schema = pending.params.requestedSchema ?? { type: 'object', properties: {} };
386
+ const input = await nativeFormResponse(schema, response.formData ?? '{}');
387
+ if (input.error)
388
+ return input.error;
389
+ result = { action: 'accept', content: input.value };
390
+ }
391
+ }
392
+ else {
393
+ if (!pending.decisions.has(response.decision ?? ''))
394
+ return 'Choose one of the native decisions shown in the request.';
395
+ result = pending.kind === 'permissions' ? { permissions: response.decision === 'accept' ? pending.params.permissions : {}, scope: 'turn' }
396
+ : { decision: pending.decisions.get(response.decision) };
397
+ }
398
+ const serialized = JSON.stringify({ id: pending.nativeId, 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.requests.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.requests.delete(response.requestId);
408
+ this.context.requestResolved?.(response.requestId);
409
+ }
410
+ clearRequests() {
411
+ for (const id of this.requests.keys())
412
+ this.context.requestResolved?.(id);
413
+ this.requests.clear();
259
414
  }
260
415
  notification(method, params) {
416
+ // Approvals and questions from child threads also belong to this connection's session.
417
+ if (method === 'serverRequest/resolved') {
418
+ for (const [id, request] of this.requests) {
419
+ if (request.nativeId !== params.requestId
420
+ || typeof params.threadId === 'string' && params.threadId !== (request.params.threadId ?? this.threadId))
421
+ continue;
422
+ this.requests.delete(id);
423
+ this.context.requestResolved?.(id);
424
+ }
425
+ return;
426
+ }
261
427
  // Subagent threads report on the same connection; only the session's own thread is transcribed.
262
428
  if (typeof params.threadId === 'string' && this.threadId && params.threadId !== this.threadId)
263
429
  return;
264
430
  switch (method) {
265
431
  case 'item/started':
266
432
  case 'item/completed': {
433
+ if (params.item?.id && ['fileChange', 'commandExecution'].includes(params.item.type))
434
+ this.approvalItems.set(String(params.item.id), params.item);
267
435
  const item = codexItem(params.item);
268
436
  if (!item)
269
437
  return;
@@ -320,6 +488,8 @@ class CodexDriver {
320
488
  const current = this.current;
321
489
  if (!current || current.id && turn.id && turn.id !== current.id)
322
490
  return;
491
+ this.clearRequests();
492
+ this.approvalItems.clear();
323
493
  this.current = null;
324
494
  const status = turn.status === 'completed' ? 'completed' : turn.status === 'interrupted' ? 'interrupted' : 'failed';
325
495
  const { usage } = current;
@@ -342,6 +512,7 @@ class CodexDriver {
342
512
  }
343
513
  }
344
514
  onExit(code) {
515
+ this.clearRequests();
345
516
  const reason = `Codex exited${code === null ? '' : ` with code ${code}`}${this.process?.stderrTail() ? `: ${this.process.stderrTail()}` : '.'}`;
346
517
  for (const pending of this.pending.values())
347
518
  pending.reject(new Error(reason));