@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.
@@ -1,13 +1,52 @@
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 ' +
5
35
  'run commands that modify anything.';
36
+ export const LOCKDOWN_NOTE = 'This session is locked down: you have no files, shell, web access or other tools, only the tools of the ' +
37
+ 'provided MCP servers. Everything you need is in the instructions and the message.';
38
+ /** Claude Code built-in tools a locked-down session must never use; dontAsk already denies them, this states it explicitly. */
39
+ export const CLAUDE_LOCKDOWN_DENIED_TOOLS = ['Bash', 'BashOutput', 'KillShell', 'Edit', 'MultiEdit', 'Write', 'NotebookEdit', 'Read', 'Grep', 'Glob',
40
+ 'LS', 'WebFetch', 'WebSearch', 'Task', 'TodoWrite', 'SlashCommand', 'Skill', 'ExitPlanMode'];
6
41
  export const DEFAULT = 'default';
7
42
  const MAX_TEXT = 50_000;
8
43
  const MAX_SUGGESTION = 2_000;
9
- export function isSandboxed(configuration, options) {
10
- return options.sandbox === true || options.profile?.sandbox === true || configuration.sandbox === true;
44
+ export function isLockedDown(start) {
45
+ return start.lockdown === true;
46
+ }
47
+ /** Only frozen permissions of an already-created session may enforce the legacy read-only restriction. */
48
+ export function isSandboxed(configuration) {
49
+ return configuration.sandbox === true;
11
50
  }
12
51
  /** MCP server names become tool prefixes and config keys, so they are reduced to a safe alphabet. */
13
52
  export function mcpServerName(server, index) {
@@ -135,6 +174,14 @@ export class SessionRunner {
135
174
  idleTimer = null;
136
175
  closing = null;
137
176
  closedReported = false;
177
+ requests = new Set();
178
+ responding = new Set();
179
+ deliveredResponses = new Set();
180
+ leaseNow;
181
+ leaseDeadline;
182
+ leaseTimer = null;
183
+ requestEpoch = 0;
184
+ timeoutChanged;
138
185
  done;
139
186
  resolveDone;
140
187
  constructor(options) {
@@ -142,6 +189,8 @@ export class SessionRunner {
142
189
  this.sessionId = options.sessionId;
143
190
  this.leaseToken = options.leaseToken;
144
191
  this.now = options.now ?? Date.now;
192
+ this.leaseNow = options.leaseNow ?? (() => performance.now());
193
+ this.leaseDeadline = options.leaseDeadline ?? Number.POSITIVE_INFINITY;
145
194
  this.done = new Promise(resolve => { this.resolveDone = resolve; });
146
195
  // A rejected lease means the server moved on; the agent must stop without reporting anything more.
147
196
  this.events = new EventQueue(options.upload, options.flushIntervalMs, () => void this.stop());
@@ -159,16 +208,100 @@ export class SessionRunner {
159
208
  this.events.push({ type: 'suggestion', text: clip(text.trim(), MAX_SUGGESTION) });
160
209
  },
161
210
  exited: error => void this.finish(error ?? 'The agent stopped unexpectedly.'),
211
+ request: request => {
212
+ if (this.closing || this.requests.has(request.id))
213
+ return;
214
+ this.requests.add(request.id);
215
+ this.timeoutChanged?.();
216
+ this.events.push({ type: 'request', request });
217
+ },
218
+ requestResolved: requestId => this.resolveRequest(requestId),
219
+ responseAllowed: requestId => this.canRespond(requestId),
220
+ authorizeResponse: async (response) => {
221
+ const id = response.requestId, epoch = this.requestEpoch;
222
+ if (!this.canRespond(id) || this.deliveredResponses.has(id))
223
+ return false;
224
+ const authorized = this.options.authorizeResponse ? await this.options.authorizeResponse(response).catch(() => false) : true;
225
+ if (!authorized || epoch !== this.requestEpoch || !this.canRespond(id))
226
+ return false;
227
+ this.deliveredResponses.add(id);
228
+ return true;
229
+ },
162
230
  });
231
+ this.armLease();
163
232
  }
164
233
  get stopping() { return this.closing !== null; }
165
234
  /** A turn runs or a message waits for one; restarting the listener now would cut it off. */
166
235
  get busy() { return this.turnRunning || this.steering.size > 0 || this.pending.length > 0; }
236
+ async respond(response) {
237
+ const id = response.requestId, epoch = this.requestEpoch;
238
+ if (!this.canRespond(id) || this.responding.has(id) || this.deliveredResponses.has(id))
239
+ return;
240
+ this.responding.add(id);
241
+ try {
242
+ // The driver validates and serializes first, then asks the runner to authorize native delivery.
243
+ const error = await this.driver.respond?.(response);
244
+ if (typeof error === 'string' && epoch === this.requestEpoch && this.canRespond(id)) {
245
+ this.deliveredResponses.delete(id);
246
+ this.events.push({ type: 'requestInvalid', requestId: id, response: { requestId: id, revision: response.revision ?? 0 },
247
+ responseHash: responseFingerprint(response), error });
248
+ }
249
+ }
250
+ catch (error) {
251
+ // The native write may have happened before throwing; never replay an ambiguous operation.
252
+ await this.finish(`The agent response could not be delivered: ${errorMessage(error)}`);
253
+ }
254
+ finally {
255
+ this.responding.delete(id);
256
+ }
257
+ }
258
+ canRespond(id) {
259
+ if (!this.leaseLive())
260
+ return false;
261
+ return !this.closing && !this.interruptRequested && this.requests.has(id);
262
+ }
263
+ leaseLive() {
264
+ if (this.leaseNow() < this.leaseDeadline)
265
+ return !this.closing;
266
+ void this.stop();
267
+ return false;
268
+ }
269
+ /** A delayed poll cannot revive a locally expired lease. Deadlines are anchored before sending the poll. */
270
+ renewLease(deadline) {
271
+ if (!this.leaseLive())
272
+ return;
273
+ this.leaseDeadline = deadline;
274
+ this.armLease();
275
+ }
276
+ armLease() {
277
+ if (this.leaseTimer)
278
+ clearTimeout(this.leaseTimer);
279
+ this.leaseTimer = null;
280
+ if (!Number.isFinite(this.leaseDeadline))
281
+ return;
282
+ if (!this.leaseLive())
283
+ return;
284
+ this.leaseTimer = setTimeout(() => { if (this.leaseLive())
285
+ this.armLease(); }, Math.max(1, this.leaseDeadline - this.leaseNow()));
286
+ }
287
+ resolveRequest(requestId) {
288
+ if (!this.requests.delete(requestId))
289
+ return;
290
+ this.timeoutChanged?.();
291
+ this.events.push({ type: 'requestResolved', requestId });
292
+ }
293
+ clearRequests() {
294
+ this.requestEpoch++;
295
+ for (const requestId of this.requests)
296
+ this.resolveRequest(requestId);
297
+ }
167
298
  /**
168
299
  * Queues messages for the next turns, or steers them into the running turn; the server may send a message again, so
169
300
  * repeats are ignored.
170
301
  */
171
302
  send(messages) {
303
+ if (!this.leaseLive())
304
+ return;
172
305
  for (const message of messages) {
173
306
  if (this.seen.has(message.id))
174
307
  continue;
@@ -205,6 +338,7 @@ export class SessionRunner {
205
338
  if (!this.turnRunning || this.interruptRequested)
206
339
  return;
207
340
  this.interruptRequested = true;
341
+ this.clearRequests();
208
342
  await this.driver.interrupt().catch(() => { });
209
343
  }
210
344
  /** Stops the agent and reports the session as closed, so the server can resume it later or finish ending it. */
@@ -260,6 +394,7 @@ export class SessionRunner {
260
394
  }
261
395
  if (this.closing)
262
396
  return;
397
+ this.clearRequests();
263
398
  if (this.interruptRequested && outcome.status === 'failed' && !outcome.error)
264
399
  outcome = { ...outcome, status: 'interrupted' };
265
400
  this.events.push({ type: 'turnCompleted', status: outcome.status, error: outcome.error,
@@ -273,16 +408,31 @@ export class SessionRunner {
273
408
  const timeoutMs = Math.max(1, this.options.start.turnTimeoutSeconds) * 1000;
274
409
  let timer;
275
410
  let expired = false;
411
+ let remaining = timeoutMs;
412
+ let armedAt = 0;
276
413
  const timedOut = new Promise(resolve => {
277
- timer = setTimeout(async () => {
414
+ const expire = async () => {
278
415
  expired = true;
279
- await this.interrupt();
416
+ // A broken provider may never acknowledge interrupt; the stop grace period must still start immediately.
417
+ void this.interrupt();
280
418
  const stopped = await Promise.race([turn.then(() => true), delay(15_000).then(() => false)]);
281
419
  resolve(stopped ? { status: 'interrupted', error: `The turn did not finish within ${this.options.start.turnTimeoutSeconds} seconds.` }
282
420
  : { status: 'failed', error: `The agent did not stop after ${this.options.start.turnTimeoutSeconds} seconds.` });
283
421
  if (!stopped)
284
422
  void this.finish(`The agent did not stop after ${this.options.start.turnTimeoutSeconds} seconds.`);
285
- }, timeoutMs);
423
+ };
424
+ this.timeoutChanged = () => {
425
+ if (timer) {
426
+ remaining -= Math.max(0, this.now() - armedAt);
427
+ clearTimeout(timer);
428
+ timer = undefined;
429
+ }
430
+ if (!expired && this.requests.size === 0) {
431
+ armedAt = this.now();
432
+ timer = setTimeout(expire, Math.max(1, remaining));
433
+ }
434
+ };
435
+ this.timeoutChanged();
286
436
  });
287
437
  try {
288
438
  const outcome = await Promise.race([turn, timedOut]);
@@ -292,6 +442,7 @@ export class SessionRunner {
292
442
  }
293
443
  finally {
294
444
  clearTimeout(timer);
445
+ this.timeoutChanged = undefined;
295
446
  }
296
447
  }
297
448
  armIdle() {
@@ -308,6 +459,10 @@ export class SessionRunner {
308
459
  finish(error) {
309
460
  this.closing ??= (async () => {
310
461
  this.clearIdle();
462
+ if (this.leaseTimer)
463
+ clearTimeout(this.leaseTimer);
464
+ this.leaseTimer = null;
465
+ this.clearRequests();
311
466
  await this.driver.close().catch(() => { });
312
467
  if (this.turnRunning && !this.closedReported) {
313
468
  this.events.push({ type: 'turnCompleted', status: 'failed', error: error ?? 'The agent was stopped.' });
@@ -0,0 +1,133 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { link, lstat, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ export const APPROVAL_MODES = ['supervised', 'autoEdits', 'auto', 'fullAccess'];
5
+ export function withoutLegacySandboxArgs(args) {
6
+ return args.filter((arg, index) => !/^--sandbox(?:=(?:true|false))?$/.test(arg)
7
+ && !(args[index - 1] === '--sandbox' && (arg === 'true' || arg === 'false')));
8
+ }
9
+ /** Update only a regular file, retaining unknown fields and refusing concurrent changes. Never start on a failed migration. */
10
+ export async function updateAgentJson(path, transform) {
11
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
12
+ const lock = await open(`${path}.migration.lock`, 'wx', 0o600).catch(error => {
13
+ throw new Error(`Cannot acquire settings migration lock ${path}.migration.lock. Check for another listener or a lock left by an interrupted migration: ${error.message}`);
14
+ });
15
+ const temporary = `${path}.${randomUUID()}.tmp`;
16
+ const backup = `${path}.${randomUUID()}.migration-backup`;
17
+ let movedOriginal = false;
18
+ try {
19
+ const before = await lstat(path).catch(error => { if (error.code === 'ENOENT')
20
+ return null; throw error; });
21
+ if (before && (!before.isFile() || before.isSymbolicLink()))
22
+ throw new Error(`Cannot migrate non-regular agent settings: ${path}`);
23
+ const original = before ? await readFile(path, 'utf8') : null;
24
+ const value = original === null ? {} : JSON.parse(original);
25
+ if (!value || typeof value !== 'object' || Array.isArray(value))
26
+ throw new Error(`Agent settings must be an object: ${path}`);
27
+ const previous = JSON.stringify(value);
28
+ transform(value);
29
+ if (JSON.stringify(value) === previous)
30
+ return value;
31
+ await writeTemporary();
32
+ const current = await lstat(path).catch(error => { if (error.code === 'ENOENT')
33
+ return null; throw error; });
34
+ if (Boolean(current) !== Boolean(before) || current && (!current.isFile() || current.isSymbolicLink()
35
+ || current.ino !== before.ino || current.mtimeMs !== before.mtimeMs || await readFile(path, 'utf8') !== original))
36
+ throw new Error(`Agent settings changed during migration; retry: ${path}`);
37
+ if (before) {
38
+ // Move the actual original first: checking before a replacing rename cannot protect a last-moment user edit.
39
+ await rename(path, backup);
40
+ movedOriginal = true;
41
+ const moved = await lstat(backup);
42
+ if (!moved.isFile() || moved.isSymbolicLink() || moved.ino !== before.ino || moved.mtimeMs !== before.mtimeMs
43
+ || await readFile(backup, 'utf8') !== original)
44
+ throw new Error('Agent settings changed during migration.');
45
+ }
46
+ // Hard-link publication is create-if-absent: a concurrently created path is never overwritten.
47
+ await link(temporary, path);
48
+ // Keep the old inode available: an editor may still hold it open and write into it after publication.
49
+ return value;
50
+ async function writeTemporary() {
51
+ const file = await open(temporary, 'wx', before ? before.mode & 0o777 : 0o600);
52
+ try {
53
+ await file.writeFile(`${JSON.stringify(value, null, 2)}\n`);
54
+ await file.sync();
55
+ }
56
+ finally {
57
+ await file.close();
58
+ }
59
+ }
60
+ }
61
+ catch (error) {
62
+ let recovery = '';
63
+ if (movedOriginal) {
64
+ recovery = ` Original settings are preserved at ${backup}.`;
65
+ try {
66
+ await link(backup, path);
67
+ }
68
+ catch (restoreError) {
69
+ if (restoreError.code !== 'EEXIST')
70
+ recovery += ' Restore that file after resolving the filesystem error.';
71
+ }
72
+ }
73
+ throw new Error(`Could not load or migrate agent settings ${path}: ${error instanceof Error ? error.message : String(error)}${recovery}`);
74
+ }
75
+ finally {
76
+ await rm(temporary, { force: true });
77
+ await lock.close();
78
+ await rm(`${path}.migration.lock`, { force: true });
79
+ }
80
+ }
81
+ /** Local values seed web defaults once; they never constrain a session selected in Skillshare. */
82
+ export function migrateAgentSettings(value, legacySandbox = false) {
83
+ const migrate = (settings) => {
84
+ if (settings.sandbox !== undefined && typeof settings.sandbox !== 'boolean')
85
+ throw new Error('sandbox must be true or false.');
86
+ if (settings.sandbox === true)
87
+ settings.approvalMode = 'auto';
88
+ delete settings.sandbox;
89
+ if (settings.approvalMode !== undefined && !APPROVAL_MODES.includes(settings.approvalMode))
90
+ throw new Error('Invalid approvalMode.');
91
+ };
92
+ migrate(value);
93
+ if (legacySandbox && value.approvalMode === undefined)
94
+ value.approvalMode = 'auto';
95
+ if (Array.isArray(value.profiles))
96
+ value.profiles.forEach(profile => {
97
+ if (profile && typeof profile === 'object' && !Array.isArray(profile))
98
+ migrate(profile);
99
+ });
100
+ return value;
101
+ }
102
+ export async function loadAgentSettings(path, legacySandbox = false) {
103
+ const assertUnlocked = async () => {
104
+ if (await lstat(`${path}.migration.lock`).catch(error => { if (error.code === 'ENOENT')
105
+ return null; throw error; }))
106
+ throw new Error(`Agent settings migration is in progress or was interrupted. Check ${path}.migration.lock before retrying.`);
107
+ };
108
+ await assertUnlocked();
109
+ const file = await lstat(path).catch(error => { if (error.code === 'ENOENT')
110
+ return null; throw error; });
111
+ if (file && (!file.isFile() || file.isSymbolicLink()))
112
+ throw new Error(`Cannot migrate non-regular agent settings: ${path}`);
113
+ let value;
114
+ try {
115
+ value = file ? JSON.parse(await readFile(path, 'utf8')) : {};
116
+ await assertUnlocked();
117
+ const current = await lstat(path).catch(error => { if (error.code === 'ENOENT')
118
+ return null; throw error; });
119
+ if (Boolean(current) !== Boolean(file) || current && (!current.isFile() || current.isSymbolicLink()
120
+ || current.ino !== file.ino || current.mtimeMs !== file.mtimeMs))
121
+ throw new Error('Agent settings changed while reading; retry.');
122
+ if (!value || typeof value !== 'object' || Array.isArray(value))
123
+ throw new Error('Agent settings must be an object.');
124
+ const previous = JSON.stringify(value);
125
+ migrateAgentSettings(value, legacySandbox);
126
+ if (JSON.stringify(value) === previous)
127
+ return value;
128
+ }
129
+ catch (error) {
130
+ throw new Error(`Could not load or migrate agent settings ${path}: ${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ return updateAgentJson(path, settings => { migrateAgentSettings(settings, legacySandbox); });
133
+ }