codex-overleaf-link 1.5.3 → 1.6.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
@@ -3,7 +3,7 @@
3
3
  <h1>Codex Overleaf Link</h1>
4
4
  <p><strong>Empower Overleaf with Codex.</strong></p>
5
5
  <p>
6
- <img src="https://img.shields.io/badge/version-1.5.3-blue" alt="version">
6
+ <img src="https://img.shields.io/badge/version-1.6.0-blue" alt="version">
7
7
  <img src="https://img.shields.io/badge/platform-macOS%20%2F%20Windows%20%2F%20Linux-lightgrey" alt="platform">
8
8
  <img src="https://img.shields.io/badge/chrome-MV3-green" alt="chrome manifest v3">
9
9
  <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="node version">
@@ -38,14 +38,14 @@ One command installs the native host **and** sets up the extension: the script r
38
38
  macOS / Linux:
39
39
 
40
40
  ```bash
41
- CODEX_OVERLEAF_REF=v1.5.3 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.5.3/install.sh)"
41
+ CODEX_OVERLEAF_REF=v1.6.0 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.6.0/install.sh)"
42
42
  ```
43
43
 
44
44
  Windows PowerShell:
45
45
 
46
46
  ```powershell
47
- iwr https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.5.3/install.ps1 -OutFile install.ps1
48
- $env:CODEX_OVERLEAF_REF='v1.5.3'
47
+ iwr https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.6.0/install.ps1 -OutFile install.ps1
48
+ $env:CODEX_OVERLEAF_REF='v1.6.0'
49
49
  powershell -ExecutionPolicy Bypass -File install.ps1
50
50
  ```
51
51
 
@@ -56,10 +56,10 @@ Then, in the `chrome://extensions` tab the script opened: enable **Developer mod
56
56
  `npm exec` installs and updates the **native host only** — it does not include the Chrome extension. Use it if you prefer a pinned npm package to a source checkout.
57
57
 
58
58
  ```bash
59
- npm exec --yes codex-overleaf-link@1.5.3 -- install-native
59
+ npm exec --yes codex-overleaf-link@1.6.0 -- install-native
60
60
  ```
61
61
 
62
- Then add the extension yourself: download `codex-overleaf-link-extension-v1.5.3.zip` from the [v1.5.3 GitHub Release](https://github.com/Ghqqqq/codex-overleaf-link/releases/tag/v1.5.3), unzip it to a stable folder, and in `chrome://extensions` enable **Developer mode**, click **Load unpacked**, and select that folder.
62
+ Then add the extension yourself: download `codex-overleaf-link-extension-v1.6.0.zip` from the [v1.6.0 GitHub Release](https://github.com/Ghqqqq/codex-overleaf-link/releases/tag/v1.6.0), unzip it to a stable folder, and in `chrome://extensions` enable **Developer mode**, click **Load unpacked**, and select that folder.
63
63
 
64
64
  ### Open Overleaf
65
65
 
@@ -86,9 +86,9 @@ npm installs, updates, uninstalls, and diagnoses the native host only. npm does
86
86
 
87
87
  | Action | Command |
88
88
  |--------|---------|
89
- | Install / update | `npm exec --yes codex-overleaf-link@1.5.3 -- install-native` |
90
- | Diagnose | `npm exec --yes codex-overleaf-link@1.5.3 -- doctor` |
91
- | Uninstall | `npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native` |
89
+ | Install / update | `npm exec --yes codex-overleaf-link@1.6.0 -- install-native` |
90
+ | Diagnose | `npm exec --yes codex-overleaf-link@1.6.0 -- doctor` |
91
+ | Uninstall | `npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native` |
92
92
 
93
93
  Use `--extension-id <chrome-extension-id>` only for a custom/dev unpacked extension id that differs from the official bundled id.
94
94
 
@@ -98,13 +98,13 @@ To update, re-run any of the [native host installers](#install) — they install
98
98
 
99
99
  ## GitHub Release Artifacts
100
100
 
101
- The v1.5.3 GitHub Release contains:
101
+ The v1.6.0 GitHub Release contains:
102
102
 
103
- - `codex-overleaf-link-extension-v1.5.3.zip`: loadable Chrome extension package for manual unpacked installation.
104
- - `codex-overleaf-native-host-v1.5.3.tar.gz`: native host runtime files used by the installer and release verification.
105
- - `codex-overleaf-link-1.5.3.tgz`: npm native host CLI package for pinned install, doctor, and uninstall flows.
106
- - `install.sh`: release-pinned macOS / Linux installer that defaults to `v1.5.3` when run directly from the release artifact.
107
- - `install.ps1`: release-pinned Windows PowerShell installer that defaults to `v1.5.3` when run directly from the release artifact.
103
+ - `codex-overleaf-link-extension-v1.6.0.zip`: loadable Chrome extension package for manual unpacked installation.
104
+ - `codex-overleaf-native-host-v1.6.0.tar.gz`: native host runtime files used by the installer and release verification.
105
+ - `codex-overleaf-link-1.6.0.tgz`: npm native host CLI package for pinned install, doctor, and uninstall flows.
106
+ - `install.sh`: release-pinned macOS / Linux installer that defaults to `v1.6.0` when run directly from the release artifact.
107
+ - `install.ps1`: release-pinned Windows PowerShell installer that defaults to `v1.6.0` when run directly from the release artifact.
108
108
  - `uninstall-native-host.mjs`: native host uninstaller that removes the Chrome Native Messaging manifest, bridge executable, and runtime copy.
109
109
  - `nativeHostPlatform.js`, `manifest.js`, `runtimeInstaller.js`: helper files required by the loose uninstaller asset.
110
110
  - `SHA256SUMS` and `release-manifest.json`: checksum and artifact metadata for release verification.
@@ -115,7 +115,7 @@ The v1.5.3 GitHub Release contains:
115
115
  Remove the native host (use `--browser chromium` on Linux Chromium):
116
116
 
117
117
  ```bash
118
- npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native
118
+ npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native
119
119
  ```
120
120
 
121
121
  The same command works on Windows PowerShell. If you installed from a manual checkout or source installer, you can also run `npm run uninstall:native` inside the repo, use `node ~/.codex-overleaf/source/scripts/uninstall-native-host.mjs` on macOS / Linux, or use `node $env:LOCALAPPDATA\CodexOverleaf\source\scripts\uninstall-native-host.mjs` on Windows PowerShell.
@@ -150,13 +150,13 @@ Then remove the extension from `chrome://extensions`. To delete local data: on m
150
150
  Linux Chromium install or update:
151
151
 
152
152
  ```bash
153
- CODEX_OVERLEAF_REF=v1.5.3 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.5.3/install.sh)" -- --browser chromium
153
+ CODEX_OVERLEAF_REF=v1.6.0 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.6.0/install.sh)" -- --browser chromium
154
154
  ```
155
155
 
156
156
  Linux Chromium uninstall:
157
157
 
158
158
  ```bash
159
- npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native --browser chromium
159
+ npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native --browser chromium
160
160
  ```
161
161
 
162
162
  ## Features
@@ -289,7 +289,7 @@ Composer attachments are turn-scoped Codex context. Limits are 8 attachments per
289
289
  Re-run any [native host installer](#install), reload the extension in `chrome://extensions`, then refresh the Overleaf tab. This also fixes extension/native version mismatch and native protocol mismatch.
290
290
 
291
291
  ```bash
292
- npm exec --yes codex-overleaf-link@1.5.3 -- install-native
292
+ npm exec --yes codex-overleaf-link@1.6.0 -- install-native
293
293
  ```
294
294
 
295
295
  **The Windows popup or panel shows a Bash recovery command**
@@ -338,8 +338,8 @@ Use this matrix for release-candidate signoff and compatibility reports. Record
338
338
  | Browser/channel/version | Google Chrome channel and version. | Google Chrome channel and version. | Google Chrome channel and version. | Chromium channel/package and version. |
339
339
  | Install mode | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout; native host installed with `--browser chromium`. |
340
340
  | Extension id | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. |
341
- | Installer/update command | `npm exec --yes codex-overleaf-link@1.5.3 -- install-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- install-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- install-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- install-native --browser chromium` |
342
- | Uninstall command | `npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.5.3 -- uninstall-native --browser chromium` |
341
+ | Installer/update command | `npm exec --yes codex-overleaf-link@1.6.0 -- install-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- install-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- install-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- install-native --browser chromium` |
342
+ | Uninstall command | `npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.6.0 -- uninstall-native --browser chromium` |
343
343
  | Manifest/registry path | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.codex.overleaf.json` | `HKCU\Software\Google\Chrome\NativeMessagingHosts\com.codex.overleaf` -> `%LOCALAPPDATA%\CodexOverleaf\native-host-runtime\com.codex.overleaf.json` | `~/.config/google-chrome/NativeMessagingHosts/com.codex.overleaf.json` | `~/.config/chromium/NativeMessagingHosts/com.codex.overleaf.json` |
344
344
  | Bridge/runtime/source path | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. | Bridge `%LOCALAPPDATA%\CodexOverleaf\codex-overleaf-bridge.cmd`; runtime `%LOCALAPPDATA%\CodexOverleaf\native-host-runtime`; source `%LOCALAPPDATA%\CodexOverleaf\source`. | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. |
345
345
  | Node/Git/Codex/TeX | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. |
@@ -135,6 +135,10 @@
135
135
  };
136
136
  }
137
137
 
138
+ if (type.indexOf('codex.subagent.') === 0) {
139
+ return mapSubagentEvent(event, type, locale);
140
+ }
141
+
138
142
  if (type === 'codex.exec.started') {
139
143
  return {
140
144
  kind: 'activity',
@@ -202,6 +206,81 @@
202
206
  };
203
207
  }
204
208
 
209
+ // Parallel-subagents lifecycle (v1.6): one human-readable line per state
210
+ // change; worker raw output never streams here (it lives in the queue's
211
+ // result files), so these lines plus the collapsed technical detail are the
212
+ // whole timeline footprint of a fan-out.
213
+ function mapSubagentEvent(event, type, locale) {
214
+ const detail = event.detail || {};
215
+ const label = String(event.title || detail.jobId || '').slice(0, 80);
216
+ const base = {
217
+ kind: 'activity',
218
+ visible: true,
219
+ technicalDetail: normalizeRawEvent(event)
220
+ };
221
+ if (type === 'codex.subagent.queued') {
222
+ return { ...base, status: 'running', title: textFor(locale, `↳ 子代理「${label}」已排队。`, `↳ Subagent "${label}" queued.`) };
223
+ }
224
+ if (type === 'codex.subagent.started') {
225
+ const active = Number(detail.activeWorkers) || 0;
226
+ const max = Number(detail.maxWorkers) || 0;
227
+ const slots = active && max ? `${active}/${max}` : '';
228
+ return {
229
+ ...base,
230
+ status: 'running',
231
+ title: slots
232
+ ? textFor(locale, `↳ 子代理「${label}」开始(${slots} 并行)。`, `↳ Subagent "${label}" started (${slots} parallel).`)
233
+ : textFor(locale, `↳ 子代理「${label}」开始。`, `↳ Subagent "${label}" started.`)
234
+ };
235
+ }
236
+ if (type === 'codex.subagent.completed') {
237
+ const seconds = Math.round((Number(detail.durationMs) || 0) / 1000);
238
+ return {
239
+ ...base,
240
+ status: 'completed',
241
+ title: seconds
242
+ ? textFor(locale, `↳ 子代理「${label}」完成(${seconds}s)。`, `↳ Subagent "${label}" completed (${seconds}s).`)
243
+ : textFor(locale, `↳ 子代理「${label}」完成。`, `↳ Subagent "${label}" completed.`)
244
+ };
245
+ }
246
+ if (type === 'codex.subagent.failed') {
247
+ const status = String(detail.status || 'failed');
248
+ const reason = String(detail.reason || '').slice(0, 120);
249
+ const zhStatus = status === 'timeout' ? '超时' : status === 'cancelled' ? '被取消' : '失败';
250
+ const enStatus = status === 'timeout' ? 'timed out' : status === 'cancelled' ? 'was cancelled' : 'failed';
251
+ return {
252
+ ...base,
253
+ status: 'warning',
254
+ title: reason
255
+ ? textFor(locale, `↳ 子代理「${label}」${zhStatus}:${reason}`, `↳ Subagent "${label}" ${enStatus}: ${reason}`)
256
+ : textFor(locale, `↳ 子代理「${label}」${zhStatus}。`, `↳ Subagent "${label}" ${enStatus}.`)
257
+ };
258
+ }
259
+ if (type === 'codex.subagent.rejected') {
260
+ const reason = String(detail.reason || 'rejected');
261
+ return {
262
+ ...base,
263
+ status: 'warning',
264
+ title: textFor(locale, `↳ 子代理任务「${label}」被拒绝(${reason})。`, `↳ Subagent job "${label}" was rejected (${reason}).`)
265
+ };
266
+ }
267
+ if (type === 'codex.subagent.violation') {
268
+ return {
269
+ ...base,
270
+ status: 'warning',
271
+ title: textFor(locale, `⚠ 子代理波次改动了未授权文件 ${label},该文件的改动将不会写回 Overleaf。`, `⚠ A subagent wave changed unowned file ${label}; its changes will NOT be written back to Overleaf.`)
272
+ };
273
+ }
274
+ if (type === 'codex.subagent.drained') {
275
+ return {
276
+ ...base,
277
+ status: 'completed',
278
+ title: textFor(locale, '↳ 子代理已全部收尾。', '↳ All subagents drained.')
279
+ };
280
+ }
281
+ return { ...base, status: event.status || 'running', title: label };
282
+ }
283
+
205
284
  function mapCodexSessionEvent(event, locale) {
206
285
  const method = String(event.detail?.method || event.title || '');
207
286
  const params = event.detail?.params || {};
@@ -12,7 +12,7 @@
12
12
  const MIN_NATIVE_VERSION = '1.0.0';
13
13
  const MIN_COMPATIBLE_NATIVE_VERSION = '1.0.0';
14
14
  const MIN_COMPATIBLE_EXTENSION_VERSION = '1.0.0';
15
- const BUILD_TARGET_VERSION = '1.5.3';
15
+ const BUILD_TARGET_VERSION = '1.6.0';
16
16
  const DEFAULT_CHROME_EXTENSION_ID = 'illdpneeeopfffmiepaejglgmhpmdhdc';
17
17
  const REQUIRED_CAPABILITIES = Object.freeze([
18
18
  'bridgePing',
@@ -852,6 +852,16 @@
852
852
  return compact;
853
853
  }
854
854
 
855
+ function compactCodexOverleafSkillsForStorage(skills) {
856
+ return (Array.isArray(skills) ? skills : [])
857
+ .slice(0, 32)
858
+ .map(skill => ({
859
+ id: String(skill?.id || '').trim().slice(0, 64),
860
+ name: String(skill?.name || '').trim().slice(0, 80)
861
+ }))
862
+ .filter(skill => skill.id);
863
+ }
864
+
855
865
  function compactPanelStateForStorage(input, limits) {
856
866
  const source = {
857
867
  ...DEFAULT_PANEL_STATE,
@@ -869,6 +879,11 @@
869
879
  const active = compactSessions.find(session => session.id === resolvedActiveId) || compactSessions[0] || null;
870
880
 
871
881
  return {
882
+ // The Codex-Overleaf skills catalog must survive reloads: the parallel-
883
+ // subagents broker gate reads it at run time, and before v1.6.1 it was
884
+ // stripped here — so the gate silently died after any reload until the
885
+ // Skills page was reopened.
886
+ codexOverleafSkills: compactCodexOverleafSkillsForStorage(source.codexOverleafSkills),
872
887
  mode: VALID_MODES.has(active?.mode) ? active.mode : normalizeMode(source.mode),
873
888
  model: normalizeTextField(active?.model || source.model || DEFAULT_PANEL_STATE.model, 80),
874
889
  reasoningEffort: VALID_REASONING.has(active?.reasoningEffort)
@@ -3,7 +3,7 @@
3
3
  const { spawn } = require('node:child_process');
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
- const { collectMirrorChangesDetailed, getProjectMirror, markMirrorDirty, syncOverleafToMirror } = require('./mirrorWorkspace');
6
+ const { SUBAGENT_QUEUE_DIR, collectMirrorChangesDetailed, getProjectMirror, markMirrorDirty, syncOverleafToMirror } = require('./mirrorWorkspace');
7
7
  const { computeLineDiff } = require('./diffEngine');
8
8
  const { computeTextPatches } = require('./textPatch');
9
9
  const { buildCodexHomeEnv } = require('./codexHome');
@@ -17,6 +17,9 @@ const {
17
17
  loadSelectedCodexOverleafSkill,
18
18
  loadSelectedProjectSkills
19
19
  } = require('./localSkills');
20
+ const { createSubagentBroker } = require('./subagentBroker');
21
+
22
+ const PARALLEL_SUBAGENTS_SKILL_ID = 'parallel-subagents';
20
23
 
21
24
  const TURN_ATTACHMENTS_DIR = '.codex-overleaf-attachments';
22
25
  const MAX_TURN_ATTACHMENT_BYTES = 12 * 1024 * 1024;
@@ -80,27 +83,92 @@ async function runCodexSession({ params = {}, env = process.env, emit = () => {}
80
83
  fs.mkdirSync(runnerWorkspacePath, { recursive: true });
81
84
  }
82
85
  const runner = executeCodex || runCodexAppServerSession;
83
- const runnerResult = await runner({
84
- workspacePath: runnerWorkspacePath,
85
- task: buildCodexTurnPrompt(params, mirror, projectLocalSkills, turnAttachments, codexSkillInvocationContext),
86
- userTask: String(params.task || ''),
87
- session: params.session || null,
88
- threadId: params.threadId || '',
89
- mode: params.mode || 'auto',
90
- model: params.model || '',
91
- reasoningEffort: params.reasoningEffort || '',
92
- speedTier: normalizeSpeedTier(params.speedTier),
93
- loadCodexLocalSkills: skillLoading.loadCodexLocalSkills,
94
- loadCodexOverleafSkills: skillLoading.loadCodexOverleafSkills,
95
- skillInvocation: effectiveSkillInvocation,
96
- installCodexOverleafSkillsTarget: skillInstallTurn,
97
- projectLocalSkills: null,
98
- sandboxMode: settings.sandboxMode,
99
- approvalPolicy: settings.approvalPolicy,
100
- env,
101
- emit,
102
- signal
103
- });
86
+ // Parallel-subagents broker (v1.6): activated solely by the official skill
87
+ // being enabled for this run. Workers are sibling Codex runs spawned by the
88
+ // host (fresh sandbox — never nested), confined to the same mirror; the
89
+ // broker enforces file ownership and wall-clock deadlines (spec §5-§7).
90
+ const subagentBroker = !skillInstallTurn
91
+ && skillLoading.loadCodexOverleafSkills !== false
92
+ && Array.isArray(params.enabledCodexOverleafSkillIds)
93
+ && params.enabledCodexOverleafSkillIds.includes(PARALLEL_SUBAGENTS_SKILL_ID)
94
+ ? createSubagentBroker({
95
+ workspacePath: mirror.workspacePath,
96
+ signal,
97
+ emit: (type, title, detail, status) => emitCodexEvent(emit, type, title, detail, status),
98
+ onMirrorDirty: () => markMirrorDirty({ projectId, rootDir, reason: 'subagent_run_cancelled' }),
99
+ runWorkerTask: ({ jobId, prompt, signal: workerSignal }) => runner({
100
+ workspacePath: mirror.workspacePath,
101
+ task: prompt,
102
+ userTask: `subagent:${jobId}`,
103
+ session: null,
104
+ threadId: '',
105
+ mode: params.mode || 'auto',
106
+ model: params.model || '',
107
+ reasoningEffort: params.reasoningEffort || '',
108
+ speedTier: normalizeSpeedTier(params.speedTier),
109
+ loadCodexLocalSkills: skillLoading.loadCodexLocalSkills,
110
+ loadCodexOverleafSkills: skillLoading.loadCodexOverleafSkills,
111
+ skillInvocation: null,
112
+ installCodexOverleafSkillsTarget: false,
113
+ projectLocalSkills: null,
114
+ // Recursion guard (spec S6): workers inherit skills EXCEPT the
115
+ // fan-out skill itself, stripped per worker app-server process.
116
+ disableCodexOverleafSkillIds: [PARALLEL_SUBAGENTS_SKILL_ID],
117
+ sandboxMode: settings.sandboxMode,
118
+ approvalPolicy: settings.approvalPolicy,
119
+ env,
120
+ // Worker raw events stay out of the parent timeline (spec §8);
121
+ // lifecycle events come from the broker, full text from result files.
122
+ emit: () => {},
123
+ signal: workerSignal
124
+ })
125
+ })
126
+ : null;
127
+ if (subagentBroker) {
128
+ subagentBroker.start();
129
+ } else if (!skillInstallTurn) {
130
+ // No broker this run: remove any stale queue from a previous brokered run
131
+ // so the model never reads a leftover closed handshake and reports the
132
+ // feature as half-available (v1.6.1 — observed in E2E).
133
+ fs.rmSync(path.join(mirror.workspacePath, SUBAGENT_QUEUE_DIR), { recursive: true, force: true });
134
+ }
135
+ let runnerResult;
136
+ try {
137
+ runnerResult = await runner({
138
+ workspacePath: runnerWorkspacePath,
139
+ task: buildCodexTurnPrompt(params, mirror, projectLocalSkills, turnAttachments, codexSkillInvocationContext),
140
+ userTask: String(params.task || ''),
141
+ session: params.session || null,
142
+ threadId: params.threadId || '',
143
+ mode: params.mode || 'auto',
144
+ model: params.model || '',
145
+ reasoningEffort: params.reasoningEffort || '',
146
+ speedTier: normalizeSpeedTier(params.speedTier),
147
+ loadCodexLocalSkills: skillLoading.loadCodexLocalSkills,
148
+ loadCodexOverleafSkills: skillLoading.loadCodexOverleafSkills,
149
+ skillInvocation: effectiveSkillInvocation,
150
+ installCodexOverleafSkillsTarget: skillInstallTurn,
151
+ projectLocalSkills: null,
152
+ sandboxMode: settings.sandboxMode,
153
+ approvalPolicy: settings.approvalPolicy,
154
+ env,
155
+ emit,
156
+ // While subagent workers are active, the parent idle watchdog resets
157
+ // instead of failing the run (spec P2-7 fix).
158
+ hasExternalActivity: subagentBroker ? () => subagentBroker.hasActiveWorkers() : undefined,
159
+ signal
160
+ });
161
+ } catch (error) {
162
+ if (subagentBroker) {
163
+ await subagentBroker.stop({ drain: false });
164
+ }
165
+ throw error;
166
+ }
167
+ // Parent turn finished: drain remaining workers so their edits are part of
168
+ // the single mirror diff below, then close the queue.
169
+ if (subagentBroker) {
170
+ await subagentBroker.stop({ drain: true });
171
+ }
104
172
  throwIfAborted(signal);
105
173
 
106
174
  if (skillInstallTurn) {
@@ -124,11 +192,27 @@ async function runCodexSession({ params = {}, env = process.env, emit = () => {}
124
192
  focusFiles: params.focusFiles || params.session?.focusFiles,
125
193
  restrictToFocusFiles: params.restrictToFocusFiles
126
194
  });
127
- const rawSyncChanges = filteredChanges.changes;
195
+ let rawSyncChanges = filteredChanges.changes;
128
196
  const unsupportedChanges = [
129
197
  ...(collected.unsupportedChanges || []),
130
198
  ...filteredChanges.unsupportedChanges
131
199
  ];
200
+ // Spec S8: ownership violations hard-block writeback. Changes on violated
201
+ // paths are demoted to unsupportedChanges (surfaced, never auto-applied) —
202
+ // this must hold even when requireReviewing is off and ordinary
203
+ // syncChanges would write directly.
204
+ const subagentViolationPaths = subagentBroker ? subagentBroker.getViolationPaths() : null;
205
+ if (subagentViolationPaths && subagentViolationPaths.size) {
206
+ const blocked = rawSyncChanges.filter(change => subagentViolationPaths.has(change.path));
207
+ rawSyncChanges = rawSyncChanges.filter(change => !subagentViolationPaths.has(change.path));
208
+ for (const change of blocked) {
209
+ unsupportedChanges.push({
210
+ type: 'unsupported-local-file',
211
+ path: change.path,
212
+ reason: 'subagent_unauthorized_edit'
213
+ });
214
+ }
215
+ }
132
216
  if (rawSyncChanges.length || unsupportedChanges.length) {
133
217
  markMirrorDirty({
134
218
  projectId,
@@ -548,6 +632,40 @@ async function applyCodexSkillIsolation({ input = {}, childEnv = process.env, re
548
632
  return { disabled };
549
633
  }
550
634
 
635
+ // Recursion guard (spec S6): disable specific Codex-Overleaf skills for one
636
+ // app-server child process — used to strip `parallel-subagents` from worker
637
+ // runs so an inheriting worker cannot discover the queue and fan out again.
638
+ // Skill directories are named by skill id (<root>/<id>/SKILL.md).
639
+ async function applyWorkerSkillStrip({ input = {}, request } = {}) {
640
+ const ids = Array.isArray(input.disableCodexOverleafSkillIds)
641
+ ? input.disableCodexOverleafSkillIds.filter(Boolean)
642
+ : [];
643
+ if (!ids.length || typeof request !== 'function') {
644
+ return { disabled: [] };
645
+ }
646
+ const listResult = await request('skills/list', {
647
+ cwd: input.workspacePath,
648
+ includeDisabled: true
649
+ });
650
+ const disabled = [];
651
+ for (const skill of flattenCodexSkillsList(listResult)) {
652
+ if (skill?.enabled === false) {
653
+ continue;
654
+ }
655
+ const skillDirName = path.basename(path.dirname(String(skill?.path || '')));
656
+ if (!ids.includes(skillDirName)) {
657
+ continue;
658
+ }
659
+ const params = buildSkillDisableParams(skill);
660
+ if (!params) {
661
+ continue;
662
+ }
663
+ await request('skills/config/write', params);
664
+ disabled.push(skillDirName);
665
+ }
666
+ return { disabled };
667
+ }
668
+
551
669
  function flattenCodexSkillsList(listResult = {}) {
552
670
  const data = Array.isArray(listResult?.data) ? listResult.data : [];
553
671
  return data.flatMap(entry => Array.isArray(entry?.skills) ? entry.skills : []);
@@ -692,6 +810,13 @@ function runCodexAppServerSession(input) {
692
810
  });
693
811
  const idleTimeoutMs = parseOptionalPositiveInteger(childEnv.CODEX_OVERLEAF_CODEX_IDLE_TIMEOUT_MS) || 600000;
694
812
  const idleWatchdog = createCodexIdleWatchdog(idleTimeoutMs, ms => {
813
+ // While the subagent broker reports active workers the parent may be
814
+ // legitimately quiet (waiting on results); reset instead of failing
815
+ // (spec P2-7). The broker's own wall-clock deadlines bound the wait.
816
+ if (input.hasExternalActivity?.()) {
817
+ idleWatchdog.reset();
818
+ return;
819
+ }
695
820
  fail(new Error(`Codex app-server produced no events for ${ms}ms (idle watchdog); the run was aborted to release the project lock.`));
696
821
  });
697
822
  const onAbort = () => {
@@ -740,6 +865,10 @@ function runCodexAppServerSession(input) {
740
865
  request,
741
866
  emit: input.emit
742
867
  });
868
+ await applyWorkerSkillStrip({
869
+ input,
870
+ request
871
+ });
743
872
 
744
873
  if (input.threadId) {
745
874
  try {
@@ -13,7 +13,7 @@ const MAX_SKILL_CONTENT_CHARS = MAX_SKILL_CONTENT_BYTES;
13
13
  const MAX_SKILL_PREVIEW_CHARS = 240;
14
14
  const PROJECT_SKILL_SCOPE = 'project';
15
15
  const CODEX_OVERLEAF_SKILL_SCOPE = 'codex-overleaf';
16
- const OFFICIAL_CODEX_OVERLEAF_SKILL_IDS = ['annotated-rewrite'];
16
+ const OFFICIAL_CODEX_OVERLEAF_SKILL_IDS = ['annotated-rewrite', 'parallel-subagents'];
17
17
 
18
18
  function listProjectSkills({ projectId, rootDir } = {}) {
19
19
  const skillsDir = getProjectSkillsDir(projectId, { rootDir });
@@ -11,6 +11,10 @@ const NATIVE_OUTPUT_LIMIT_BYTES = 1024 * 1024;
11
11
  const SAFE_INLINE_BINARY_CHANGE_BYTES = 512 * 1024;
12
12
  const SAFE_NATIVE_RESPONSE_PAYLOAD_BYTES = NATIVE_OUTPUT_LIMIT_BYTES - (64 * 1024);
13
13
  const TURN_ATTACHMENTS_DIR = '.codex-overleaf-attachments';
14
+ // Control plane for the parallel-subagents broker (v1.6). Lives inside the
15
+ // workspace so the sandboxed model can write jobs, but is excluded from the
16
+ // mirror scan so queue/result/log files can never enter Overleaf writeback.
17
+ const SUBAGENT_QUEUE_DIR = '.codex-overleaf-subagents';
14
18
 
15
19
  function getProjectMirror(projectId, options = {}) {
16
20
  const rootDir = path.resolve(options.rootDir || getDefaultMirrorRoot(options));
@@ -521,7 +525,7 @@ function listWorkspaceFiles(workspacePath) {
521
525
 
522
526
  function walk(dir, prefix) {
523
527
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
524
- if (entry.name === '.DS_Store' || entry.name === TURN_ATTACHMENTS_DIR) {
528
+ if (entry.name === '.DS_Store' || entry.name === TURN_ATTACHMENTS_DIR || entry.name === SUBAGENT_QUEUE_DIR) {
525
529
  continue;
526
530
  }
527
531
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
@@ -1004,6 +1008,7 @@ function verifyWorkspaceMatchesBaseline(workspacePath, baselineFiles = []) {
1004
1008
  }
1005
1009
 
1006
1010
  module.exports = {
1011
+ SUBAGENT_QUEUE_DIR,
1007
1012
  NATIVE_OUTPUT_LIMIT_BYTES,
1008
1013
  SAFE_INLINE_BINARY_CHANGE_BYTES,
1009
1014
  SAFE_NATIVE_RESPONSE_PAYLOAD_BYTES,
@@ -0,0 +1,99 @@
1
+ ---
2
+ name: parallel-subagents
3
+ description: >
4
+ When a task decomposes into independent work on two or more SEPARATE files
5
+ (polish chapters, per-section fixes), fan it out: write job files to the
6
+ subagent queue and the host runs real parallel Codex workers for you. Use
7
+ only when file ownership can be split cleanly; fall back to sequential work
8
+ for a single monolithic file.
9
+ ---
10
+
11
+ # Parallel Subagents
12
+
13
+ The native host can run parallel Codex workers for you. You cannot spawn
14
+ processes yourself (the sandbox forbids it) — instead you write **job files**
15
+ into a queue directory and poll for **result files**. Each worker is a full
16
+ Codex agent confined to the files you assign it.
17
+
18
+ ## 1. When to use
19
+
20
+ Use this when ALL of these hold:
21
+ - The task splits into ≥ 2 independent slices, each touching **different
22
+ files** (e.g. one chapter file per slice).
23
+ - Slices do not depend on each other's output.
24
+ - Each slice is small enough to finish in a few minutes.
25
+
26
+ Do NOT use it (work sequentially yourself instead) when:
27
+ - The project keeps everything in one monolithic file — never split one file
28
+ across jobs.
29
+ - Slices are deeply cross-referenced and must be edited together.
30
+ - There are fewer than 2 real slices.
31
+ - The handshake file below is missing or not `ready`.
32
+
33
+ ## 2. Handshake
34
+
35
+ Read `.codex-overleaf-subagents/broker.json`. If it is missing or its
36
+ `status` is not `ready`, the broker is off — do everything yourself. Respect
37
+ `maxWorkers`, `maxJobsPerRun`, and `perWorkerTimeoutMs` (size each job to
38
+ finish well inside it).
39
+
40
+ ## 3. Write jobs
41
+
42
+ One job per slice. Each job OWNS its `files` exclusively — no file may appear
43
+ in two jobs. Write atomically: create a temp file, then `mv` it to its final
44
+ `.json` name.
45
+
46
+ ```bash
47
+ cat > .codex-overleaf-subagents/jobs/.tmp-ch3 <<'JSON'
48
+ {
49
+ "id": "ch3",
50
+ "title": "Polish chapter 3",
51
+ "task": "Polish sections/ch3.tex for grammar, flow, and concision. Keep all math and citations intact. Follow the shared style notes: <paste the style guidance here>.",
52
+ "files": ["sections/ch3.tex"],
53
+ "readOnlyContext": ["main.tex", "macros.tex"]
54
+ }
55
+ JSON
56
+ mv .codex-overleaf-subagents/jobs/.tmp-ch3 .codex-overleaf-subagents/jobs/ch3.json
57
+ ```
58
+
59
+ Rules:
60
+ - `id`: lowercase letters/digits/hyphens, ≤ 32 chars, unique.
61
+ - `task`: complete, self-contained instructions — workers cannot ask
62
+ questions. Repeat shared style guidance in EVERY job.
63
+ - `files`: workspace-relative paths the job may edit. Keep ownership
64
+ disjoint across jobs.
65
+ - `readOnlyContext`: files the worker may read but must not edit.
66
+
67
+ ## 4. Poll for results
68
+
69
+ ```bash
70
+ while [ "$(ls .codex-overleaf-subagents/results/*.json 2>/dev/null | wc -l)" -lt <jobCount> ]; do
71
+ sleep 10
72
+ ls .codex-overleaf-subagents/results/ 2>/dev/null
73
+ done
74
+ ```
75
+
76
+ Then read each `results/<id>.json` (`status`: completed | failed | rejected |
77
+ timeout | cancelled; `summary`; `changedFiles`) and, when you need the full
78
+ close-out, `results/<id>.last-message.md`.
79
+
80
+ ## 5. Wave discipline (important)
81
+
82
+ While any job is queued or running, do **not** edit project files yourself —
83
+ write jobs, poll, wait. Do your own edits before the first job or after the
84
+ last result. Files changed during a wave that no job owns are reported as
85
+ ownership violations and **excluded from the Overleaf writeback**.
86
+
87
+ ## 6. Integrate
88
+
89
+ - For each `completed` job: read its summary, spot-check the owned files, and
90
+ smooth terminology/transitions ACROSS slice boundaries yourself.
91
+ - For each `failed` / `timeout` / `rejected` job: do that slice inline
92
+ yourself now (check `reason`; a `file_conflict` means you mis-partitioned).
93
+ - Mention any violations in your close-out so the user knows those edits were
94
+ withheld from writeback.
95
+
96
+ ## 7. Close out
97
+
98
+ End with a per-slice one-liner (job → what changed) plus an overall summary.
99
+ This becomes the run report the user reads.
@@ -0,0 +1,539 @@
1
+ 'use strict';
2
+
3
+ // Parallel-subagents broker (v1.6, spec: docs/superpowers/specs/
4
+ // 2026-06-10-v1.6-parallel-subagents-design.md).
5
+ //
6
+ // The sandboxed model cannot spawn processes (Seatbelt kills nested Codex at
7
+ // client init — verified empirically), but it CAN write workspace files. The
8
+ // broker runs in the native host (outside the sandbox), watches a file-based
9
+ // job queue inside the mirror workspace, and fans each accepted job out to a
10
+ // real sibling Codex run via an injected `runWorkerTask`. Ownership of files
11
+ // is disjoint by protocol; violations are attributed at wave level and the
12
+ // runner hard-blocks them from writeback (spec S5/S8).
13
+ //
14
+ // Everything time- or process-shaped is injectable so the unit suite can run
15
+ // with fake workers and millisecond limits.
16
+
17
+ const crypto = require('node:crypto');
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ const { SUBAGENT_QUEUE_DIR } = require('./mirrorWorkspace');
22
+
23
+ const PROTOCOL_VERSION = 1;
24
+ const JOB_ID_PATTERN = /^[a-z0-9-]{1,32}$/;
25
+ const MAX_JOB_FILE_BYTES = 32 * 1024;
26
+ const SUMMARY_LIMIT_CHARS = 2048;
27
+
28
+ const DEFAULT_LIMITS = Object.freeze({
29
+ maxWorkers: 3,
30
+ maxJobsPerRun: 8,
31
+ perWorkerTimeoutMs: 300000,
32
+ brokerBudgetMs: 900000,
33
+ pollIntervalMs: 500,
34
+ drainGraceMs: 30000
35
+ });
36
+
37
+ function createSubagentBroker(options = {}) {
38
+ const workspacePath = options.workspacePath;
39
+ if (!workspacePath) {
40
+ throw new Error('subagent broker requires a workspacePath');
41
+ }
42
+ const runWorkerTask = options.runWorkerTask;
43
+ if (typeof runWorkerTask !== 'function') {
44
+ throw new Error('subagent broker requires a runWorkerTask function');
45
+ }
46
+ const emit = typeof options.emit === 'function' ? options.emit : () => {};
47
+ const onMirrorDirty = typeof options.onMirrorDirty === 'function' ? options.onMirrorDirty : () => {};
48
+ const parentSignal = options.signal || null;
49
+ const limits = { ...DEFAULT_LIMITS, ...(options.limits || {}) };
50
+
51
+ const queueRoot = path.join(workspacePath, SUBAGENT_QUEUE_DIR);
52
+ const jobsDir = path.join(queueRoot, 'jobs');
53
+ const resultsDir = path.join(queueRoot, 'results');
54
+ const logsDir = path.join(queueRoot, 'logs');
55
+
56
+ const jobs = new Map(); // id -> { job, status, startedAt, ownedBefore }
57
+ const seenFiles = new Set();
58
+ const violations = [];
59
+ const violationPaths = new Set();
60
+ let queued = [];
61
+ let running = new Map(); // id -> { controller, deadlineTimer, promise }
62
+ let acceptedCount = 0;
63
+ let startedAt = 0;
64
+ let accepting = false;
65
+ let pollTimer = null;
66
+ let waveIndex = 0;
67
+ let waveSnapshot = null; // { hashes: Map(path->hash), ownedUnion: Set, jobIds: [] }
68
+ let anyWorkerStarted = false;
69
+ let cancelled = false;
70
+ let closed = false;
71
+
72
+ function start() {
73
+ // Stale queue dirs from a previous run carry old results/logs — clear
74
+ // them so the model never reads another run's state (spec S9).
75
+ fs.rmSync(queueRoot, { recursive: true, force: true });
76
+ fs.mkdirSync(jobsDir, { recursive: true });
77
+ fs.mkdirSync(resultsDir, { recursive: true });
78
+ fs.mkdirSync(logsDir, { recursive: true });
79
+ startedAt = Date.now();
80
+ accepting = true;
81
+ writeBrokerFile('ready');
82
+ pollTimer = setInterval(pollOnce, limits.pollIntervalMs);
83
+ if (parentSignal) {
84
+ parentSignal.addEventListener('abort', onParentAbort, { once: true });
85
+ }
86
+ }
87
+
88
+ function writeBrokerFile(status) {
89
+ const payload = {
90
+ protocolVersion: PROTOCOL_VERSION,
91
+ status,
92
+ maxWorkers: limits.maxWorkers,
93
+ maxJobsPerRun: limits.maxJobsPerRun,
94
+ perWorkerTimeoutMs: limits.perWorkerTimeoutMs,
95
+ brokerBudgetMs: limits.brokerBudgetMs,
96
+ acceptedUntil: new Date(startedAt + limits.brokerBudgetMs - limits.perWorkerTimeoutMs).toISOString()
97
+ };
98
+ atomicWrite(path.join(queueRoot, 'broker.json'), JSON.stringify(payload, null, 2));
99
+ }
100
+
101
+ function atomicWrite(target, text) {
102
+ const tmp = path.join(path.dirname(target), `.tmp-${crypto.randomUUID()}`);
103
+ fs.writeFileSync(tmp, text);
104
+ fs.renameSync(tmp, target);
105
+ }
106
+
107
+ function pollOnce() {
108
+ if (closed || cancelled) {
109
+ return;
110
+ }
111
+ try {
112
+ intakeJobs();
113
+ fillSlots();
114
+ } catch (_error) {
115
+ // The queue is adversarial model output; the broker never throws on it.
116
+ }
117
+ }
118
+
119
+ function intakeJobs() {
120
+ if (!accepting || !fs.existsSync(jobsDir)) {
121
+ return;
122
+ }
123
+ for (const name of fs.readdirSync(jobsDir).sort()) {
124
+ if (!name.endsWith('.json') || name.startsWith('.tmp-') || seenFiles.has(name)) {
125
+ continue;
126
+ }
127
+ seenFiles.add(name);
128
+ admitJobFile(name);
129
+ }
130
+ }
131
+
132
+ function admitJobFile(name) {
133
+ const filePath = path.join(jobsDir, name);
134
+ let stat;
135
+ try {
136
+ stat = fs.statSync(filePath);
137
+ } catch (_error) {
138
+ return;
139
+ }
140
+ if (stat.size > MAX_JOB_FILE_BYTES) {
141
+ return writeRejection({ id: idFromFileName(name), reason: 'job_too_large' });
142
+ }
143
+ let job;
144
+ try {
145
+ job = JSON.parse(fs.readFileSync(filePath, 'utf8'));
146
+ } catch (_error) {
147
+ return writeRejection({ id: idFromFileName(name), reason: 'invalid_json' });
148
+ }
149
+ const rejection = validateJob(job);
150
+ if (rejection) {
151
+ return writeRejection({ id: jobIdOrFallback(job, name), ...rejection });
152
+ }
153
+ acceptedCount += 1;
154
+ jobs.set(job.id, { job, status: 'queued' });
155
+ queued.push(job.id);
156
+ emit('codex.subagent.queued', job.title || job.id, { jobId: job.id, files: job.files }, 'running');
157
+ }
158
+
159
+ function idFromFileName(name) {
160
+ return name.replace(/\.json$/, '').slice(0, 32) || 'unknown';
161
+ }
162
+
163
+ function jobIdOrFallback(job, name) {
164
+ return typeof job?.id === 'string' && job.id ? job.id.slice(0, 32) : idFromFileName(name);
165
+ }
166
+
167
+ function validateJob(job) {
168
+ if (!job || typeof job !== 'object') {
169
+ return { reason: 'invalid_json' };
170
+ }
171
+ if (typeof job.id !== 'string' || !JOB_ID_PATTERN.test(job.id)) {
172
+ return { reason: 'invalid_id' };
173
+ }
174
+ if (jobs.has(job.id)) {
175
+ return { reason: 'duplicate_id' };
176
+ }
177
+ if (acceptedCount >= limits.maxJobsPerRun) {
178
+ return { reason: 'too_many_jobs' };
179
+ }
180
+ if (typeof job.task !== 'string' || !job.task.trim()) {
181
+ return { reason: 'missing_task' };
182
+ }
183
+ if (!Array.isArray(job.files) || !job.files.length) {
184
+ return { reason: 'missing_files' };
185
+ }
186
+ const owned = [];
187
+ for (const file of job.files) {
188
+ const safe = safeWorkspaceRelativePath(file);
189
+ if (!safe) {
190
+ return { reason: 'unsafe_path', path: String(file) };
191
+ }
192
+ if (!fs.existsSync(path.join(workspacePath, safe))) {
193
+ return { reason: 'missing_file', path: safe };
194
+ }
195
+ owned.push(safe);
196
+ }
197
+ for (const [otherId, entry] of jobs) {
198
+ if (entry.status === 'rejected') {
199
+ continue;
200
+ }
201
+ const overlap = entry.job.files.find(file => owned.includes(file));
202
+ if (overlap) {
203
+ return { reason: 'file_conflict', path: overlap, conflictsWith: otherId };
204
+ }
205
+ }
206
+ // Wave-aware admission: the parent turn has no default absolute deadline,
207
+ // so the broker enforces its own wall-clock envelope across ALL waves.
208
+ const projectedWaves = Math.ceil((queued.length + running.size + 1) / limits.maxWorkers);
209
+ if (Date.now() + projectedWaves * limits.perWorkerTimeoutMs > startedAt + limits.brokerBudgetMs) {
210
+ return { reason: 'insufficient_time' };
211
+ }
212
+ job.files = owned;
213
+ job.readOnlyContext = Array.isArray(job.readOnlyContext)
214
+ ? job.readOnlyContext.map(safeWorkspaceRelativePath).filter(Boolean)
215
+ : [];
216
+ return null;
217
+ }
218
+
219
+ function safeWorkspaceRelativePath(value) {
220
+ if (typeof value !== 'string' || !value.trim()) {
221
+ return null;
222
+ }
223
+ const normalized = value.trim().replace(/\\/g, '/').replace(/^\.\//, '');
224
+ if (!normalized || path.isAbsolute(normalized)) {
225
+ return null;
226
+ }
227
+ const segments = normalized.split('/');
228
+ if (segments.some(segment => segment === '..' || segment === '')) {
229
+ return null;
230
+ }
231
+ if (segments[0] === SUBAGENT_QUEUE_DIR) {
232
+ return null;
233
+ }
234
+ return segments.join('/');
235
+ }
236
+
237
+ function writeRejection(input) {
238
+ const result = {
239
+ id: input.id,
240
+ status: 'rejected',
241
+ reason: input.reason,
242
+ path: input.path,
243
+ conflictsWith: input.conflictsWith
244
+ };
245
+ writeResult(result);
246
+ emit('codex.subagent.rejected', input.id, result, 'warning');
247
+ }
248
+
249
+ function writeResult(result) {
250
+ atomicWrite(path.join(resultsDir, `${result.id}.json`), JSON.stringify(result, null, 2));
251
+ }
252
+
253
+ function fillSlots() {
254
+ while (accepting && !cancelled && queued.length && running.size < limits.maxWorkers) {
255
+ const jobId = queued.shift();
256
+ startWorker(jobs.get(jobId));
257
+ }
258
+ }
259
+
260
+ function startWorker(entry) {
261
+ const { job } = entry;
262
+ if (running.size === 0) {
263
+ beginWave();
264
+ }
265
+ anyWorkerStarted = true;
266
+ entry.status = 'running';
267
+ entry.startedAt = Date.now();
268
+ entry.wave = waveIndex;
269
+ entry.ownedBefore = hashPaths(job.files);
270
+ waveSnapshot.jobIds.push(job.id);
271
+ for (const file of job.files) {
272
+ waveSnapshot.ownedUnion.add(file);
273
+ }
274
+
275
+ const controller = new AbortController();
276
+ let timedOut = false;
277
+ const deadlineTimer = setTimeout(() => {
278
+ // Broker-owned wall-clock deadline (spec P1-5 fix): the runner's
279
+ // absolute timeout is an opt-in env override and the idle watchdog
280
+ // never fires on a chatty-but-stuck worker, so the broker is the only
281
+ // component positioned to bound worker wall-clock time.
282
+ timedOut = true;
283
+ controller.abort(new Error('subagent timeout'));
284
+ }, limits.perWorkerTimeoutMs);
285
+
286
+ emit('codex.subagent.started', job.title || job.id, {
287
+ jobId: job.id,
288
+ files: job.files,
289
+ activeWorkers: running.size + 1,
290
+ maxWorkers: limits.maxWorkers
291
+ }, 'running');
292
+
293
+ const promise = runWorkerTask({
294
+ jobId: job.id,
295
+ prompt: buildWorkerPrompt(job),
296
+ signal: controller.signal
297
+ }).then(workerResult => {
298
+ finishWorker(entry, {
299
+ status: 'completed',
300
+ summary: String(workerResult?.assistantMessage || '').slice(0, SUMMARY_LIMIT_CHARS),
301
+ tokensUsed: workerResult?.tokensUsed
302
+ }, workerResult);
303
+ }).catch(error => {
304
+ // Any broker-initiated abort that is not the wall-clock deadline
305
+ // (parent cancel, drain) reads as 'cancelled'; only genuine worker
306
+ // errors read as 'failed'.
307
+ const status = timedOut ? 'timeout' : controller.signal.aborted ? 'cancelled' : 'failed';
308
+ appendLog(job.id, `${status}: ${error?.stack || error?.message || String(error)}`);
309
+ finishWorker(entry, { status, reason: error?.message || String(error) });
310
+ }).finally(() => {
311
+ clearTimeout(deadlineTimer);
312
+ running.delete(job.id);
313
+ if (running.size === 0) {
314
+ endWave();
315
+ }
316
+ fillSlots();
317
+ });
318
+
319
+ running.set(job.id, { controller, deadlineTimer, promise });
320
+ }
321
+
322
+ function finishWorker(entry, resultFields, workerResult) {
323
+ const { job } = entry;
324
+ entry.status = resultFields.status;
325
+ const ownedAfter = hashPaths(job.files);
326
+ const changedFiles = job.files.filter(file => entry.ownedBefore.get(file) !== ownedAfter.get(file));
327
+ const result = {
328
+ id: job.id,
329
+ ...resultFields,
330
+ changedFiles,
331
+ durationMs: Date.now() - entry.startedAt
332
+ };
333
+ entry.result = result;
334
+ writeResult(result);
335
+ if (resultFields.status === 'completed' && workerResult?.assistantMessage) {
336
+ atomicWrite(path.join(resultsDir, `${job.id}.last-message.md`), String(workerResult.assistantMessage));
337
+ }
338
+ const eventType = resultFields.status === 'completed' ? 'codex.subagent.completed' : 'codex.subagent.failed';
339
+ emit(eventType, job.title || job.id, {
340
+ jobId: job.id,
341
+ status: resultFields.status,
342
+ reason: resultFields.reason,
343
+ changedFiles,
344
+ durationMs: result.durationMs
345
+ }, resultFields.status === 'completed' ? 'completed' : 'warning');
346
+ }
347
+
348
+ function appendLog(jobId, text) {
349
+ try {
350
+ fs.appendFileSync(path.join(logsDir, `${jobId}.log`), `${new Date().toISOString()} ${text}\n`);
351
+ } catch (_error) { /* logs are best-effort */ }
352
+ }
353
+
354
+ // ---- wave tracking (spec S5): owned attribution is per worker; unowned
355
+ // changes can only be attributed to the wave's set of suspects.
356
+ function beginWave() {
357
+ waveIndex += 1;
358
+ waveSnapshot = {
359
+ hashes: hashWorkspace(),
360
+ ownedUnion: new Set(),
361
+ jobIds: []
362
+ };
363
+ }
364
+
365
+ function endWave() {
366
+ if (!waveSnapshot) {
367
+ return;
368
+ }
369
+ const after = hashWorkspace();
370
+ const before = waveSnapshot.hashes;
371
+ const changed = new Set();
372
+ for (const [file, hash] of after) {
373
+ if (before.get(file) !== hash) {
374
+ changed.add(file);
375
+ }
376
+ }
377
+ for (const file of before.keys()) {
378
+ if (!after.has(file)) {
379
+ changed.add(file);
380
+ }
381
+ }
382
+ for (const file of changed) {
383
+ if (waveSnapshot.ownedUnion.has(file)) {
384
+ continue;
385
+ }
386
+ const violation = {
387
+ path: file,
388
+ wave: waveIndex,
389
+ suspects: [...waveSnapshot.jobIds, 'parent']
390
+ };
391
+ violations.push(violation);
392
+ violationPaths.add(file);
393
+ emit('codex.subagent.violation', file, violation, 'warning');
394
+ }
395
+ waveSnapshot = null;
396
+ }
397
+
398
+ function hashWorkspace() {
399
+ const hashes = new Map();
400
+ walk(workspacePath, '');
401
+ return hashes;
402
+
403
+ function walk(dir, prefix) {
404
+ let entries;
405
+ try {
406
+ entries = fs.readdirSync(dir, { withFileTypes: true });
407
+ } catch (_error) {
408
+ return;
409
+ }
410
+ for (const entry of entries) {
411
+ if (entry.name === '.DS_Store' || entry.name === SUBAGENT_QUEUE_DIR || entry.name === '.codex-overleaf-attachments') {
412
+ continue;
413
+ }
414
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
415
+ const absolute = path.join(dir, entry.name);
416
+ if (entry.isDirectory()) {
417
+ walk(absolute, relative);
418
+ } else if (entry.isFile()) {
419
+ hashes.set(relative, hashFile(absolute));
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ function hashPaths(files) {
426
+ const hashes = new Map();
427
+ for (const file of files) {
428
+ hashes.set(file, hashFile(path.join(workspacePath, file)));
429
+ }
430
+ return hashes;
431
+ }
432
+
433
+ function hashFile(absolute) {
434
+ try {
435
+ return crypto.createHash('sha1').update(fs.readFileSync(absolute)).digest('hex');
436
+ } catch (_error) {
437
+ return 'missing';
438
+ }
439
+ }
440
+
441
+ function buildWorkerPrompt(job) {
442
+ const readOnly = job.readOnlyContext.length
443
+ ? `- You may read these for context but must not modify them: ${job.readOnlyContext.join(', ')}.\n`
444
+ : '';
445
+ return [
446
+ 'You are a subagent working on one slice of a larger task.',
447
+ 'HARD CONSTRAINTS:',
448
+ `- You may modify ONLY these files: ${job.files.join(', ')}.`,
449
+ readOnly + '- Do not modify, create, or delete any other file. Do not touch .codex-overleaf-subagents/.',
450
+ '- Work fully autonomously; nobody can answer questions.',
451
+ '',
452
+ job.task
453
+ ].join('\n');
454
+ }
455
+
456
+ function onParentAbort() {
457
+ cancelled = true;
458
+ accepting = false;
459
+ for (const { controller } of running.values()) {
460
+ controller.abort(new Error('run cancelled'));
461
+ }
462
+ for (const jobId of queued.splice(0)) {
463
+ const entry = jobs.get(jobId);
464
+ entry.status = 'cancelled';
465
+ writeResult({ id: jobId, status: 'cancelled', reason: 'run cancelled' });
466
+ }
467
+ if (anyWorkerStarted) {
468
+ // Partial worker edits must be deterministically discarded: cancellation
469
+ // already skips writeback, and the dirty mark forces the next run's
470
+ // mirror sync to rebuild the workspace from Overleaf (spec P1-3 fix).
471
+ onMirrorDirty();
472
+ }
473
+ close();
474
+ }
475
+
476
+ async function stop({ drain = true } = {}) {
477
+ accepting = false;
478
+ if (drain && running.size) {
479
+ const grace = new Promise(resolve => {
480
+ setTimeout(resolve, limits.drainGraceMs);
481
+ });
482
+ await Promise.race([
483
+ Promise.allSettled([...running.values()].map(worker => worker.promise)),
484
+ grace
485
+ ]);
486
+ }
487
+ for (const { controller } of running.values()) {
488
+ controller.abort(new Error('broker drained'));
489
+ }
490
+ await Promise.allSettled([...running.values()].map(worker => worker.promise));
491
+ if (jobs.size) {
492
+ emit('codex.subagent.drained', 'subagents drained', {
493
+ jobs: jobs.size,
494
+ violations: violations.length
495
+ }, 'completed');
496
+ }
497
+ close();
498
+ }
499
+
500
+ function close() {
501
+ if (closed) {
502
+ return;
503
+ }
504
+ closed = true;
505
+ if (pollTimer) {
506
+ clearInterval(pollTimer);
507
+ }
508
+ parentSignal?.removeEventListener?.('abort', onParentAbort);
509
+ try {
510
+ writeBrokerFile('closed');
511
+ } catch (_error) { /* workspace may already be gone */ }
512
+ }
513
+
514
+ return {
515
+ start,
516
+ stop,
517
+ pollOnce,
518
+ hasActiveWorkers: () => running.size > 0,
519
+ hasAcceptedJobs: () => jobs.size > 0,
520
+ getViolationPaths: () => new Set(violationPaths),
521
+ getAuditSummary: () => ({
522
+ jobs: [...jobs.values()].map(entry => ({
523
+ id: entry.job?.id,
524
+ title: entry.job?.title,
525
+ files: entry.job?.files,
526
+ status: entry.status,
527
+ reason: entry.result?.reason,
528
+ durationMs: entry.result?.durationMs
529
+ })),
530
+ violations: violations.slice()
531
+ })
532
+ };
533
+ }
534
+
535
+ module.exports = {
536
+ createSubagentBroker,
537
+ SUBAGENT_QUEUE_DIR,
538
+ DEFAULT_SUBAGENT_LIMITS: DEFAULT_LIMITS
539
+ };
@@ -291,6 +291,12 @@ function handleSkillsList(request, env) {
291
291
  try {
292
292
  const { CODEX_OVERLEAF_SKILL_SCOPE, listCodexOverleafSkills, listProjectSkills } = require('./localSkills');
293
293
  if (request.params?.scope === CODEX_OVERLEAF_SKILL_SCOPE) {
294
+ // Install/restore official skills before listing so newly shipped ones
295
+ // (e.g. parallel-subagents) appear in the Skills UI right after a
296
+ // runtime update instead of only after the next codex run (v1.6.1).
297
+ try {
298
+ require('./codexHome').ensureDefaultCodexOverleafSkills({ env });
299
+ } catch (_error) { /* listing still proceeds */ }
294
300
  return okResponse(request.id, listCodexOverleafSkills({ env }));
295
301
  }
296
302
  return okResponse(request.id, listProjectSkills({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-overleaf-link",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "description": "Cross-platform Chrome bridge that connects Codex to the active Overleaf project.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",