@optimuslabs/harness-map-staging 1.5.42 → 1.5.43

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.
@@ -90,6 +90,10 @@ export function getQuarantineDir() {
90
90
  export function getSkillBlockProcessesPath() {
91
91
  return join(getRemediationStateDir(), 'skill_block_processes.json');
92
92
  }
93
+ /** The blocked skills the user was already shown the quarantine window for, per server. */
94
+ export function getSkillBlockWindowsShownPath() {
95
+ return join(getRemediationStateDir(), 'skill_block_windows_shown.json');
96
+ }
93
97
  export function getDeferredVscdbApplyPath() {
94
98
  return join(getVscdbStateDir(), DEFERRED_VSCDB_APPLY_BASENAME);
95
99
  }
@@ -173,6 +177,7 @@ const APPROVAL_LISTS = [
173
177
  'skill_blocks',
174
178
  'skill_block_sessions',
175
179
  'skill_block_windows',
180
+ 'skill_block_group_window',
176
181
  'agent_access_windows',
177
182
  ];
178
183
  /** Each approval list from `file` when it names one, else the one on disk; absent ones left out. */
@@ -225,6 +230,10 @@ export function writeSkillBlocks(skill_blocks) {
225
230
  export function writeSkillBlockSessions(skill_block_sessions) {
226
231
  writeApprovalList({ skill_block_sessions });
227
232
  }
233
+ /** Replace only the window for several blocked skills at once, keeping everything else on disk. */
234
+ export function writeSkillBlockGroupWindow(skill_block_group_window) {
235
+ writeApprovalList({ skill_block_group_window });
236
+ }
228
237
  /** Replace only the skill block windows, keeping everything else on disk. */
229
238
  export function writeSkillBlockWindows(skill_block_windows) {
230
239
  writeApprovalList({ skill_block_windows });
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { executeBody } from '../../endpoint_client/http_transport.js';
5
5
  import { parseJsonWithJsoncFallback, parseTomlText, stringifyToml } from '../readers/file_readers.js';
6
6
  import { complianceRunnerDiag, hookRunLog, logRemediationApplyFailure } from './hook_logger.js';
7
- import { atomicWriteJson, getDeferredVscdbApplyPath, getFileCollectionVscdbContractPath, getRemediationInstructionsPath, readRemediationInstructionsFile, writeApprovedTenants, writeUnapprovedEmailDomains, writeAllowedEmailDomains, writeTeamEmailDomains, writeApprovedAgents, writeAgentAccessWindows, writeRemediationInstructionsFile, writeSkillBlockSessions, writeSkillBlockWindows, writeSkillBlocks, } from './management_storage.js';
7
+ import { atomicWriteJson, getDeferredVscdbApplyPath, getFileCollectionVscdbContractPath, getRemediationInstructionsPath, readRemediationInstructionsFile, writeApprovedTenants, writeUnapprovedEmailDomains, writeAllowedEmailDomains, writeTeamEmailDomains, writeApprovedAgents, writeAgentAccessWindows, writeRemediationInstructionsFile, writeSkillBlockSessions, writeSkillBlockGroupWindow, writeSkillBlockWindows, writeSkillBlocks, } from './management_storage.js';
8
8
  import { applySkillBlocks } from './skill_block.js';
9
9
  import { openQuarantineWindows } from './skill_block_sessions.js';
10
10
  import { readStoredAuthKey } from '../auth/auth_key_store.js';
@@ -1695,11 +1695,17 @@ function storeSkillBlockWindows(windows) {
1695
1695
  }
1696
1696
  writeSkillBlockWindows(kept);
1697
1697
  }
1698
+ /** Keep the server's window for several skills at once; null when nothing is blocked. */
1699
+ function storeSkillBlockGroupWindow(words) {
1700
+ if (words === undefined)
1701
+ return;
1702
+ writeSkillBlockGroupWindow(words && typeof words === 'object' && !Array.isArray(words) ? words : null);
1703
+ }
1698
1704
  /**
1699
1705
  * Store the server's skill blocks and make the folders on disk match them. An older server sends
1700
1706
  * no `skill_blocks`: the folders are then left as they are, never unlocked by mistake.
1701
1707
  */
1702
- function enforceSkillBlocks(syncResult) {
1708
+ function enforceSkillBlocks(syncResult, endpointBase) {
1703
1709
  const blocks = syncResult.skill_blocks;
1704
1710
  if (!Array.isArray(blocks))
1705
1711
  return;
@@ -1711,10 +1717,11 @@ function enforceSkillBlocks(syncResult) {
1711
1717
  writeSkillBlocks(entries);
1712
1718
  storeSkillBlockSessions(syncResult.skill_block_sessions);
1713
1719
  storeSkillBlockWindows(syncResult.skill_block_windows);
1720
+ storeSkillBlockGroupWindow(syncResult.skill_block_group_window);
1714
1721
  try {
1715
1722
  const outcome = applySkillBlocks(entries);
1716
1723
  // Tell the user when a skill is quarantined, whether or not a session of theirs loaded it.
1717
- openQuarantineWindows(outcome.quarantined, entries);
1724
+ openQuarantineWindows(outcome.quarantined, entries, endpointBase);
1718
1725
  }
1719
1726
  catch (err) {
1720
1727
  const msg = `skill_block_error: ${errorText(err)}`;
@@ -1857,7 +1864,7 @@ export async function syncRemediations(endpointBase, machineUuid) {
1857
1864
  return;
1858
1865
  applyClearApplyTrackingUuids(syncResult.clear_apply_tracking_uuids);
1859
1866
  storeApprovals(syncResult);
1860
- enforceSkillBlocks(syncResult);
1867
+ enforceSkillBlocks(syncResult, endpointBase);
1861
1868
  if (syncResult.status === 'unchanged') {
1862
1869
  await reconcileUnchanged(endpointBase, machineUuid, remediations, activeUuids);
1863
1870
  return;
@@ -11,9 +11,9 @@
11
11
  * of a process that ran a listed one. An unblock takes the sessions off the list.
12
12
  */
13
13
  import { execFileSync } from 'node:child_process';
14
- import { existsSync, readFileSync } from 'node:fs';
14
+ import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
15
15
  import { basename } from 'node:path';
16
- import { atomicWriteJson, getSkillBlockProcessesPath, readRemediationInstructionsFile, } from './management_storage.js';
16
+ import { atomicWriteJson, getSkillBlockProcessesPath, getSkillBlockWindowsShownPath, readRemediationInstructionsFile, } from './management_storage.js';
17
17
  import { launchAgentAccessWindow } from '../../agent_access/window_runner.js';
18
18
  import { quarantinedAt } from './skill_block.js';
19
19
  /**
@@ -162,9 +162,85 @@ function resourceUuidOf(skill) {
162
162
  /** The skills this run already opened the window for, so a prompt that quarantines a skill and is
163
163
  * refused for it opens one window, not two. */
164
164
  const windowsShown = new Set();
165
+ function readWindowsShown() {
166
+ try {
167
+ const path = getSkillBlockWindowsShownPath();
168
+ if (!existsSync(path))
169
+ return {};
170
+ const shown = JSON.parse(readFileSync(path, 'utf8'));
171
+ return shown && typeof shown === 'object' && !Array.isArray(shown) ? shown : {};
172
+ }
173
+ catch {
174
+ return {};
175
+ }
176
+ }
177
+ const lockWait = new Int32Array(new SharedArrayBuffer(4));
178
+ /** Try once to take the lock: 'held', 'busy' (another run holds it), or 'none' (it cannot be made). */
179
+ function takeWindowsLock(lock) {
180
+ try {
181
+ if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > 60_000)
182
+ unlinkSync(lock);
183
+ writeFileSync(lock, '', { flag: 'wx' });
184
+ return 'held';
185
+ }
186
+ catch (err) {
187
+ return err.code === 'EEXIST' ? 'busy' : 'none';
188
+ }
189
+ }
190
+ /**
191
+ * Run `decide` holding the lock on the remembered windows, so the gate and the runner of one prompt
192
+ * decide in turn and the second sees what the first opened. Waits up to two seconds while the other
193
+ * holds it; false, `decide` not run, when it still does. A lock a dead process left goes after a
194
+ * minute. When the lock cannot be made at all (no state folder), `decide` runs without it: a missing
195
+ * folder must not cost the user the window.
196
+ */
197
+ function withWindowsLock(decide) {
198
+ const lock = `${getSkillBlockWindowsShownPath()}.lock`;
199
+ let taken = takeWindowsLock(lock);
200
+ for (let attempt = 1; attempt < 20 && taken === 'busy'; attempt++) {
201
+ Atomics.wait(lockWait, 0, 0, 100);
202
+ taken = takeWindowsLock(lock);
203
+ }
204
+ if (taken === 'busy')
205
+ return false;
206
+ const held = taken === 'held';
207
+ try {
208
+ const state = readWindowsShown();
209
+ const before = JSON.stringify(state);
210
+ decide(state);
211
+ if (JSON.stringify(state) !== before)
212
+ atomicWriteJson(getSkillBlockWindowsShownPath(), state);
213
+ }
214
+ finally {
215
+ try {
216
+ if (held)
217
+ unlinkSync(lock);
218
+ }
219
+ catch {
220
+ // Already gone; the next run takes it again.
221
+ }
222
+ }
223
+ return true;
224
+ }
225
+ /**
226
+ * Open `words` as this prompt's one skill window: 'shown', 'taken' when this prompt (this run, or
227
+ * the other process of the same prompt) already opened one, or 'failed' when it could not open.
228
+ */
229
+ function openForPrompt(words, state) {
230
+ // The prompt's story id when the hook gave one (the gate and the runner share it), else this run.
231
+ const prompt = (process.env.OPTIMUS_STORY_ID || '').trim();
232
+ if (prompt ? state.prompt === prompt : windowsShown.size > 0)
233
+ return 'taken';
234
+ if (!launchAgentAccessWindow('claude', 'skill', words))
235
+ return 'failed';
236
+ if (prompt)
237
+ state.prompt = prompt;
238
+ return 'shown';
239
+ }
165
240
  /**
166
- * Open the window of one blocked skill, by resource uuid, once per run. True when it is open: just
167
- * started, or already started this run; false when the server sent no window for it.
241
+ * Open the window of one blocked skill, by resource uuid, beside a refusal. True when it is open:
242
+ * just started, or already started this run; false when the server sent no window for it, or this
243
+ * prompt already showed another skill's window (the hook then shows its one-line alert).
168
244
  */
169
245
  function openWindowOf(uuid) {
170
246
  if (!uuid)
@@ -174,22 +250,76 @@ function openWindowOf(uuid) {
174
250
  const words = readRemediationInstructionsFile().skill_block_windows?.[uuid];
175
251
  if (!words)
176
252
  return false;
177
- windowsShown.add(uuid);
178
- return launchAgentAccessWindow('claude', 'skill', words);
253
+ let open = false;
254
+ withWindowsLock((state) => {
255
+ open = openForPrompt(words, state) === 'shown';
256
+ });
257
+ if (open)
258
+ windowsShown.add(uuid);
259
+ return open;
179
260
  }
180
261
  /** Open the window beside the block of the skill named `skill` (a stopped session, a typed command). */
181
262
  export function openSkillBlockWindow(skill) {
182
263
  return openWindowOf(resourceUuidOf(skill));
183
264
  }
184
265
  /**
185
- * Open the window for each skill this sync moved into quarantine (`dirs`, the folders it moved), so
186
- * the user hears of it when it happens, even when no session of theirs is known to have loaded it
187
- * (a typed command whose turn made no tool call reaches the server as nothing). One window per
188
- * skill however many of its folders moved.
266
+ * The words for a window opened because the skills in `uuids` were newly blocked (at least one). It
267
+ * lists every skill the server blocks on this machine (`entries`), not only the new ones, so the
268
+ * user sees the whole list each time: the skill's own window when that is one skill, else the
269
+ * server's window for several, its red box listing each by name. An older server sends no window
270
+ * for several: the first new skill's own window then stands for them.
189
271
  */
190
- export function openQuarantineWindows(dirs, entries) {
272
+ function quarantineWords(uuids, entries) {
273
+ const file = readRemediationInstructionsFile();
274
+ const own = file.skill_block_windows ?? {};
275
+ const names = [...new Set(entries.map((e) => e.skill_name))];
276
+ const first = uuids.map((uuid) => own[uuid]).find(Boolean);
277
+ const group = file.skill_block_group_window;
278
+ if (names.length < 2 || !group)
279
+ return first;
280
+ const reason = (group.reason && typeof group.reason === 'object' ? group.reason : {});
281
+ const label = typeof group.group_skill_label === 'string' ? group.group_skill_label : '';
282
+ const findings = [...names].sort().map((name) => ({ severity: 'unknown', label, text: name }));
283
+ return { ...group, reason: { ...reason, findings } };
284
+ }
285
+ /**
286
+ * Open the window for the skills this sync moved into quarantine (`dirs`, the folders it moved), so
287
+ * the user hears of a block when it happens, even when no session of theirs is known to have loaded
288
+ * the skill (a typed command whose turn made no tool call reaches the server as nothing).
289
+ *
290
+ * One window per prompt, listing every skill blocked on the machine (the ones told about before
291
+ * too), and the gate and the runner of the same prompt open at most one between them. A window
292
+ * opens only when a skill is newly blocked, once per skill, by name: a
293
+ * blocked skill gains folders after its block (Claude Desktop copies its skills into a new folder
294
+ * for each session, one skill is in several agents' folders, and each version of a skill is a
295
+ * resource of its own, so `docx` can be several), and each new folder is quarantined by a later
296
+ * sync. The skills told about are remembered per `server` (resource uuids are the server's own,
297
+ * and a machine can sync with more than one), and forgotten once that server no longer blocks
298
+ * them, so a block after an unblock is told again. Skills newly blocked by the second sync of a
299
+ * prompt that already had its window are counted as told.
300
+ */
301
+ export function openQuarantineWindows(dirs, entries, server) {
191
302
  const moved = new Set(dirs);
192
- const uuids = new Set(entries.filter((e) => moved.has(e.skill_dir)).map((e) => e.resource_uuid));
193
- for (const uuid of uuids)
194
- openWindowOf(uuid);
303
+ withWindowsLock((state) => {
304
+ const nameOf = new Map(entries.map((e) => [e.resource_uuid, e.skill_name.toLowerCase()]));
305
+ const servers = state.servers ?? {};
306
+ const shown = Object.fromEntries(Object.entries(servers[server] ?? {}).filter(([uuid]) => nameOf.has(uuid)));
307
+ const toldNames = new Set(Object.keys(shown).map((uuid) => nameOf.get(uuid)));
308
+ const newly = [...new Set(entries.filter((e) => moved.has(e.skill_dir)).map((e) => e.resource_uuid))].filter((uuid) => !shown[uuid]);
309
+ const now = new Date().toISOString();
310
+ const fresh = newly.filter((uuid) => !toldNames.has(nameOf.get(uuid)));
311
+ // Another folder or version of a skill already told about: no window.
312
+ for (const uuid of newly)
313
+ if (!fresh.includes(uuid))
314
+ shown[uuid] = now;
315
+ const words = fresh.length > 0 ? quarantineWords(fresh, entries) : undefined;
316
+ const outcome = words ? openForPrompt(words, state) : 'failed';
317
+ // Told when this prompt's window shows them, or another one already did; not when none opened.
318
+ for (const uuid of outcome === 'failed' ? [] : fresh)
319
+ shown[uuid] = now;
320
+ if (outcome === 'shown')
321
+ fresh.forEach((uuid) => windowsShown.add(uuid));
322
+ servers[server] = shown;
323
+ state.servers = servers;
324
+ });
195
325
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optimuslabs/harness-map-staging",
3
- "version": "1.5.42",
3
+ "version": "1.5.43",
4
4
  "description": "CLI helpers for logging hardware UUIDs and posting startup payloads to Optimus Security.",
5
5
  "type": "module",
6
6
  "bin": {