xcodebug 1.2.2 → 1.2.3

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/GUIDE.md CHANGED
@@ -12,6 +12,18 @@ Enter these commands in the client's chat input. A bare `/xcodebug` (`$xcodebug`
12
12
  in Codex) builds as needed, installs, launches and starts capturing with defaults.
13
13
  Use `/xcodebug status` (`$xcodebug status` in Codex) to inspect current captures.
14
14
 
15
+ After installing the MCP server, run `xcodebug-setup-codex` once to register
16
+ the server when missing and set Codex's 4200-second tool timeout. From a
17
+ checkout, use `node bin/xcodebug-setup-codex.mjs`. This explicit command keeps
18
+ package installation from changing Codex configuration silently.
19
+
20
+ Native pi/omp `/xcodebug` dispatches directly to the loaded extension handler,
21
+ without skill/model selection for that dispatch. The package excludes its
22
+ bundled skill from native package discovery; Claude/Codex share `mcp/skills/xcodebug/SKILL.md`.
23
+ If a native host also discovers that user-level shared skill, it routes to the native tool
24
+ when available. Reading a skill alone never executes an action; model-selected
25
+ requests still require a tool call, while the native command runs its handler.
26
+
15
27
  Debug a real iOS device: build, install, launch, and read the app's console
16
28
  (stdout/stderr + os_log) inside the agent session. No jailbreak, no LLDB attach,
17
29
  no paid account.
@@ -89,6 +101,12 @@ for analysis.
89
101
  See [Claude Code live display](README.md#claude-code-live-display) for version
90
102
  requirements, upgrade/disable steps and missing-display troubleshooting.
91
103
 
104
+ For an optional footer in Codex CLI 0.171.0 or later, follow the
105
+ [Codex live display setup](README.md#codex-live-display-experimental). The
106
+ footer shows the current operation or one running capture and its
107
+ latest log line. It refreshes between tool calls and clears once no operation
108
+ or capture remains. Use `logs` or `wait` to bring log evidence into the conversation.
109
+
92
110
  ## Running a command alongside a capture
93
111
 
94
112
  ### What it is for
@@ -142,8 +160,12 @@ What happens after `command`:
142
160
  1. `/bin/sh -lc` runs the whole line, with the project root as the working
143
161
  directory (`pi.cwd` → `ctx.cwd` → process cwd).
144
162
  2. It waits for the process to exit.
145
- 3. It stops **the capture it targeted** — other apps' captures keep streaming.
146
- 4. It hands back the exit code, elapsed time, how many new lines arrived, the
163
+ 3. It stops **the capture it targeted** and cancels its queued reconnect — other
164
+ apps' captures keep streaming.
165
+ 4. When collecting exit diagnostics, it waits for the owned console-launch
166
+ result and matching crash-report collection independently of the stopped
167
+ capture; caller cancellation still interrupts that wait.
168
+ 5. It hands back the exit code, elapsed time, how many new lines arrived, the
147
169
  log path, and the `logs` call (with the right `since`) for the app side.
148
170
 
149
171
  **Quote the whole line.** `command="cd /repo && npm run test"`. Unquoted, the
@@ -249,6 +271,12 @@ A filtered read (`logs grep=`, `wait`) looks in those files for the lines memory
249
271
  has dropped and says in its reply that it did. Logs are deleted 30 days after
250
272
  their last write.
251
273
 
274
+ Console launch-result JSON is temporary metadata, not a log. Ordinary `stop`
275
+ preserves pending exit diagnostics; session exit instead cancels result reads
276
+ and bounds startup/result cleanup as well as log drainage. Incomplete cleanup
277
+ is reported. Ownership-checked stale-result reclamation and its conservative
278
+ exceptions are documented under [disk files](README.md#files).
279
+
252
280
  ## Three rules of use
253
281
 
254
282
  1. **Stop once the log has answered the question.** A capture left running keeps
package/README.md CHANGED
@@ -92,16 +92,29 @@ codex mcp list # xcodebug bun …
92
92
  claude mcp list # xcodebug: … ✔ Connected
93
93
  ```
94
94
 
95
- Set Codex's MCP timeout high enough for the stages your calls use. For example,
96
- 4200 seconds leaves room for the default 15-minute pod install, 15-minute build
97
- and 30-minute command budgets, plus device operations. Increase it if you pass
98
- larger timeouts; the client can still cancel before xcodebug's own deadline.
95
+ After installing the package, run the setup command once to register the MCP
96
+ server when missing and add the timeout without replacing an existing xcodebug
97
+
98
+ ```bash
99
+ xcodebug-setup-codex
100
+ ```
101
+
102
+ From a checkout, use `node bin/xcodebug-setup-codex.mjs`. The command uses the
103
+ Codex app-server config API. It registers xcodebug with Bun if it is missing,
104
+ then writes `tool_timeout_sec = 4200`. It does not run automatically during npm
105
+ install because package installation should not silently modify a user's Codex
106
+ configuration. The equivalent manual setting is:
99
107
 
100
108
  ```toml
101
109
  [mcp_servers.xcodebug]
102
110
  tool_timeout_sec = 4200
103
111
  ```
104
112
 
113
+ The timeout leaves room for the default 15-minute pod install, 15-minute build
114
+ and 30-minute command budgets, plus device operations. Increase it if you pass
115
+ larger timeouts. This does not change xcodebug's stage deadlines or Codex's
116
+ separate status-line resource read deadline.
117
+
105
118
  Claude Code needs no setting for this. Its default limit on a tool call is about
106
119
  28 hours. It also ends a call to a stdio server that has sent neither a reply
107
120
  nor a progress notification for 30 minutes; this server sends progress once a
@@ -116,13 +129,44 @@ until stdout closes or a write fails.
116
129
  To run `npm test` from a checkout, use Node.js 22.18 or later and put Bun on PATH
117
130
  for the stdio integration tests.
118
131
 
132
+ ### Codex live display (experimental)
133
+
134
+ With Codex CLI 0.171.0 or later, start Codex with
135
+ `codex --enable tui_extensions_statusline` and choose `xcodebug / xcodebug_ui`
136
+ under `/statusline`. Use a fresh Codex session after updating the xcodebug MCP
137
+ server. For persistent opt-in, set `features.tui_extensions_statusline = true`
138
+ in Codex's config (or set `tui_extensions_statusline = true` under `[features]`).
139
+ Codex 0.171.0 looks up status-line providers in the user configuration. If a
140
+ project config overrides the same MCP server name, remove the override or use
141
+ a distinct server name for the user registration.
142
+
143
+ The footer shows the current operation or capture and its latest log line. It
144
+ refreshes even between tool calls and clears when no operation or capture is
145
+ active. This is a display preview, not a log stream into the conversation; use
146
+ `action=logs` or `action=wait` for log evidence.
147
+ Long status text is shortened in the footer without changing the command or
148
+ its output.
149
+
119
150
  ### Install the manual entry point
120
151
 
121
152
  Connecting MCP makes the tool available to the model; it does not register a
122
153
  `/xcodebug` command in either client. The shared
123
- [xcodebug skill](skills/xcodebug/SKILL.md) adds an explicit entry point:
154
+ [xcodebug skill](mcp/skills/xcodebug/SKILL.md) adds an explicit entry point:
124
155
  `/xcodebug` in Claude Code, `$xcodebug` in Codex, or Codex's `/skills` picker.
125
156
 
157
+ Native pi/omp needs only the extension, not this skill or an MCP connection.
158
+ Both hosts register `extensions: ["./index.ts"]`; `pi.skills: []` disables pi's
159
+ package skill loading. The shared skill lives under `mcp/skills/`, outside the
160
+ root `skills/` directory that omp scans independently of manifest fields.
161
+ Native `/xcodebug` runs
162
+ the registered extension handler directly; it does not ask the model to select
163
+ a skill. A normal model tool call uses the registered native `xcodebug` tool.
164
+ If pi/omp also discovers the shared user-level skill through `.agents/skills`
165
+ or `.claude/skills`, its instructions select that native tool before MCP.
166
+ This shared-skill selection is model-driven, not a substitute for the native
167
+ command's deterministic dispatch. The extension must be installed, enabled and
168
+ loaded in the session; explicitly disabling it is not overridden.
169
+
126
170
  Both clients can read the same skill directory through user-level symlinks:
127
171
 
128
172
  ```bash
@@ -131,11 +175,12 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
131
175
  # XCODEBUG_DIR="$(npm root -g)/xcodebug"
132
176
 
133
177
  (
134
- source="$XCODEBUG_DIR/skills/xcodebug"
178
+ source="$XCODEBUG_DIR/mcp/skills/xcodebug"
179
+ legacy="$XCODEBUG_DIR/skills/xcodebug"
135
180
  test -f "$source/SKILL.md" || { printf 'Skill not found: %s\n' "$source/SKILL.md" >&2; exit 1; }
136
181
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
137
182
  if test -e "$dest" || test -L "$dest"; then
138
- if ! test -L "$dest" || ! test "$dest" -ef "$source"; then
183
+ if ! test -L "$dest" || { ! test "$dest" -ef "$source" && ! test "$(readlink "$dest")" = "$legacy"; }; then
139
184
  printf 'Existing skill path: %s; inspect it before installing.\n' "$dest" >&2
140
185
  exit 1
141
186
  fi
@@ -143,22 +188,29 @@ XCODEBUG_DIR="/absolute/path/to/xcodebug" # a checkout containing the skill
143
188
  done
144
189
  mkdir -p "$HOME/.agents/skills" "$HOME/.claude/skills" || exit 1
145
190
  for dest in "$HOME/.agents/skills/xcodebug" "$HOME/.claude/skills/xcodebug"; do
191
+ if test -L "$dest" && test "$(readlink "$dest")" = "$legacy"; then
192
+ rm "$dest" || exit 1
193
+ fi
146
194
  test -L "$dest" || ln -s "$source" "$dest" || exit 1
147
195
  done
148
196
  )
149
197
  ```
150
198
 
151
- If the installed package does not contain `skills/xcodebug/SKILL.md`, use a
199
+ If the installed package does not contain `mcp/skills/xcodebug/SKILL.md`, use a
152
200
  checkout that contains it. The commands check both target paths before installing,
153
- skip symlinks already pointing to this skill, and stop on other existing files,
154
- directories or symlinks, including broken links.
155
- Keep the checkout or npm package at the linked path. Updating that source updates
156
- the shared skill for both clients.
201
+ skip symlinks already pointing to this skill, and migrate links to this checkout's
202
+ old `skills/xcodebug` source. They stop on other existing files, directories or
203
+ symlinks, including unrelated broken links. After updating an older checkout or
204
+ upgrading an npm package that used the old root `skills/` path, rerun these
205
+ commands to relink both clients; npm upgrade alone does not migrate those links.
206
+ Keep the checkout or npm package at the linked path. Once relinked, updates to
207
+ the maintained source update the shared skill for both clients.
157
208
 
158
209
  Start a new Claude Code or Codex session after installing. The skill uses the
159
- MCP connection already configured above; it does not start a separate server or
160
- replace the native pi command. Both manual and model-selected invocation remain
161
- available. See the clients' [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
210
+ MCP connection already configured above in those clients; it does not start a
211
+ separate server. Native pi/omp uses its extension command and native tool instead.
212
+ Both manual and model-selected invocation remain available. See the clients'
213
+ [Claude Code skill documentation](https://code.claude.com/docs/en/skills)
162
214
  and [Codex skill documentation](https://learn.chatgpt.com/docs/build-skills).
163
215
 
164
216
  ### Use
@@ -364,15 +416,15 @@ remain available without the display.
364
416
  |---|---|---|
365
417
  | how the tool is exposed | registered in-process | MCP server process |
366
418
  | manual entry point | native `/xcodebug` | shared skill: `/xcodebug` in Claude, `$xcodebug` in Codex |
367
- | status line, widget | yes | Claude: optional live Mod above; otherwise request progress when rendered |
419
+ | status line, widget | yes | [Claude live Mod](#claude-code-live-display) or [Codex status line](#codex-live-display-experimental), both opt-in |
368
420
  | `push` | mirrors new lines into the session | `off` only; `context` and `wake` refused |
369
421
  | capture state | in the session | in the server process |
370
422
  | lifetime | the session | the client process |
371
423
 
372
424
  - **The adapter refuses `push=context` and `push=wake`.** It does not implement
373
425
  background log delivery into model context. Read with `action=logs` or
374
- `action=wait`; these pull reads are separate from the Claude Mod's user-visible
375
- display. Cursor reads exclude earlier indices, but a limited read can omit
426
+ `action=wait`; these pull reads are separate from both clients' live displays.
427
+ Cursor reads exclude earlier indices, but a limited read can omit
376
428
  lines; see [Reading logs from a cursor](#reading-logs-from-a-cursor).
377
429
  - **Captures end with the client.** The server is a child of Codex/Claude. When
378
430
  the client closes the connection, the server finishes the call in progress,
@@ -552,8 +604,8 @@ run. Set `installPods=false` to skip it deliberately.
552
604
  Detects the workspace from the current directory (walking up, so a nested cwd
553
605
  works), rebuilds when the tree changed, installs, launches, and starts capturing.
554
606
  Native pi/omp can push logs into the conversation; Claude Code and Codex use
555
- `logs`/`wait` pull reads through MCP. The optional Claude Mod displays a console
556
- tail to the user, not to the model. The phrase is a goal, not a log filter.
607
+ `logs`/`wait` pull reads through MCP. Both clients offer an optional live preview
608
+ for the user. The phrase is a goal, not a log filter.
557
609
 
558
610
  - **CocoaPods vs plain project** is decided by `Podfile`/`Podfile.lock`: a
559
611
  CocoaPods project uses its `.xcworkspace`, a plain project its `.xcodeproj`.
@@ -757,6 +809,9 @@ session.
757
809
  - **Do not stop while the user has not acted yet.** Silence there means nothing
758
810
  has been tried, not that the run is over: say what to do on the phone and keep
759
811
  listening.
812
+ - When the initial process-table query succeeds, a dual-channel launch runs
813
+ console app-PID discovery before connecting the syslog companion. An explicit
814
+ stop during that step does not leave a new companion running.
760
815
  - A console capture ends when the app process is confirmed gone, and its syslog
761
816
  companion is stopped too. It records why - `the app exited`, with the last
762
817
  line logged, which is devicectl's own `App terminated due to signal 9.` when
@@ -765,6 +820,28 @@ session.
765
820
  the log and its path is reported the same way. A standalone `syslog` capture
766
821
  is not bound to the app's lifetime and keeps reconnecting; stop it explicitly
767
822
  when finished.
823
+ - An interrupted `wait`, `await`, or `launch` with `command` joins the existing
824
+ exit-diagnostic job (launch identity and report collection) before replying.
825
+ A matching report supplies its
826
+ system termination namespace, code and explanation, plus its local path, in
827
+ the reply and follow-up details (`terminationReason`, `crashReport`). The
828
+ report search can add time after the line-wait or command deadline; caller
829
+ cancellation still interrupts it. A missing report or missing termination
830
+ data is reported as unavailable, not replaced with a guessed cause. A verified
831
+ App PID is required before a report can supply termination evidence; unknown
832
+ identity is reported explicitly without promoting another instance's candidate
833
+ report. Reattach-generation checks prevent an older search from overwriting
834
+ the newly launched instance's report.
835
+ Natural process exit registers that job before pipe/writer drain. Identity is
836
+ taken from this console launch's own `--json-output` result
837
+ (`result.process.processIdentifier`), not a late same-name process-table
838
+ snapshot. Each bridge start owns a fresh result file, removed after reading;
839
+ result identity and reattach-generation checks keep old jobs out of new runs.
840
+ A missing, malformed or unsuccessful launch result remains unverified; an
841
+ automatic reattach will not terminate an unverified running instance.
842
+ `wait` joins both identity and report collection. When a command exits, its
843
+ capture and queued reconnect are stopped before awaiting that independent job;
844
+ confirmed termination likewise cancels reconnect without cancelling collection.
768
845
  - A dropped console bridge whose app is still running is reattached, retrying
769
846
  for as long as it takes. devicectl attaches a console only by launching, so
770
847
  with the default `terminateExisting` **a reattach restarts the app** and its
@@ -786,9 +863,10 @@ session.
786
863
  e.g. `📖 xcodebug · capturing · 7895 lines · 42s · /xcodebug stop to end`, plus
787
864
  recent log lines and the number of streaming channels. Claude Code can instead
788
865
  load the [live display Mod](#claude-code-live-display).
866
+ Codex can enable the [experimental status line](#codex-live-display-experimental).
789
867
  - Native pushed log batches are **hidden from the transcript** (`display: false`)
790
868
  but delivered to the model, subject to the per-batch limit. MCP does not push
791
- batches; the Claude Mod's display does not add logs to model context.
869
+ batches; neither MCP live display adds logs to model context.
792
870
  - `/xcodebug stop` (or `action=stop`) without `captureId` closes **every running
793
871
  capture**. An ID scopes the stop to that target; a console primary's syslog
794
872
  companion is stopped too. Other apps' captures are unaffected by a targeted
@@ -922,6 +1000,20 @@ writes to drain. If they remain blocked, it destroys the streams, reports a
922
1000
  drain-timeout error in capture status, and completes shutdown; pending logs may
923
1001
  be truncated.
924
1002
 
1003
+ Console launches also own a private `.xcodebug-launch-*` directory containing
1004
+ `launch.json` and an `owner.json` marker with this extension's format, host PID
1005
+ and creation time. The directory is mode `0700`; the marker is mode `0600`.
1006
+ Result cleanup follows reading; raw metadata never enters the console log stream.
1007
+ Ordinary `stop` leaves a pending result read available to exit diagnostics.
1008
+ Session shutdown separately cancels those reads, blocks new bridge starts, and
1009
+ allows up to three seconds per capture for pending startup, result cleanup and
1010
+ log drainage, including older reattach results and captures evicted from visible
1011
+ history. Blocked filesystem work or failed deletion is reported as incomplete
1012
+ cleanup, including failures from captures already evicted from history.
1013
+ Once cleanup settles, the session retains only the warning text for shutdown,
1014
+ not the finished capture or its log buffer.
1015
+ Residual result files may remain; task settlement alone is not proof of deletion.
1016
+
925
1017
  The bundle id separates apps, and the timestamp includes milliseconds to
926
1018
  separate runs. Segment limits apply per capture. What xcodebug itself says while
927
1019
  a bridge is down - why the capture ended, each reattach - is appended to the same
@@ -931,8 +1023,13 @@ known, a report without that PID is not retained.
931
1023
 
932
1024
  Logs are kept for 30 days after their last write. The first `build`, `launch` or
933
1025
  `syslog` of a session deletes older `build-`, `console-`, `syslog-` and
934
- `pod-install-` logs and `crash-*.ips` reports from this directory, and nothing
935
- else in it.
1026
+ `pod-install-` logs and `crash-*.ips` reports from this directory. The same
1027
+ retention window applies to residual launch-result directories, but only when
1028
+ the ownership marker is valid, the host PID is definitely absent, and the
1029
+ directory and all known files are old. Active or uncertain owners, unmarked
1030
+ legacy directories, malformed markers, symlinks and extra entries are retained.
1031
+ Pruning removes only validated `owner.json` / `launch.json` files and an empty
1032
+ directory, never recursively deleting a directory based on its prefix.
936
1033
 
937
1034
  A successful build clears `<agentDir>/logs/xcodebug/archive/` first, so snapshots
938
1035
  from a previous binary cannot be mistaken for the run that is starting.
package/archive.ts CHANGED
@@ -14,7 +14,8 @@
14
14
  * device archive - os_log only (framework/system messages, errors)
15
15
  * MySDK-style NSLog lines appear only in the live channel.
16
16
  */
17
- import { mkdir, readdir, rm, stat } from "node:fs/promises";
17
+ import { constants, type Stats } from "node:fs";
18
+ import { lstat, mkdir, open, readdir, rm, rmdir, stat, unlink } from "node:fs/promises";
18
19
  import { dirname, join } from "node:path";
19
20
  import { runCommand, timestamp } from "./exec.ts";
20
21
 
@@ -64,12 +65,80 @@ export async function clearArchives(workDir: string): Promise<{ removed: number;
64
65
  /** The files this extension writes: build, capture and pod install logs, and pulled crash reports. */
65
66
  const OWN_LOG = /^(?:build|console|syslog|pod-install|crash)-.+\.(?:log(?:\.\d+)?|ips)$/;
66
67
 
68
+ /** Reclaim only expired, marked launch results whose owning process is definitely gone. */
69
+ async function pruneLaunchResult(path: string, cutoff: number): Promise<void> {
70
+ const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino
71
+ && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
72
+ const inspect = async (expectedDirectory?: Stats) => {
73
+ const directory = await lstat(path);
74
+ if (!directory.isDirectory() || (expectedDirectory
75
+ ? !same(directory, expectedDirectory) : !(directory.mtimeMs < cutoff))) return;
76
+ const names = (await readdir(path)).sort();
77
+ if (!names.includes("owner.json") || names.some(name => name !== "owner.json" && name !== "launch.json")) return;
78
+ const files: { name: string; info: Stats }[] = [];
79
+ for (const name of names) {
80
+ const info = await lstat(join(path, name));
81
+ if (!info.isFile() || !(info.mtimeMs < cutoff)) return;
82
+ files.push({ name, info });
83
+ }
84
+ const ownerInfo = files.find(file => file.name === "owner.json")!.info;
85
+ // Refuse links and oversized unknown content before reading an ownership marker.
86
+ if (ownerInfo.size > 1_024) return;
87
+ const handle = await open(join(path, "owner.json"), constants.O_RDONLY | constants.O_NOFOLLOW);
88
+ let ownerText: string;
89
+ try {
90
+ if (!same(await handle.stat(), ownerInfo)) return;
91
+ ownerText = await handle.readFile({ encoding: "utf8" });
92
+ if (!same(await handle.stat(), ownerInfo)) return;
93
+ } finally {
94
+ await handle.close();
95
+ }
96
+ const owner = JSON.parse(ownerText);
97
+ if (!owner || typeof owner !== "object" || Array.isArray(owner) || Object.keys(owner).length !== 4
98
+ || owner.kind !== "xcodebug.launch-result" || owner.version !== 1
99
+ || !Number.isSafeInteger(owner.pid) || owner.pid <= 0
100
+ || !Number.isSafeInteger(owner.createdAt) || owner.createdAt < 0 || !(owner.createdAt < cutoff)) return;
101
+ try {
102
+ process.kill(owner.pid, 0);
103
+ return;
104
+ } catch (error) {
105
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") return;
106
+ }
107
+ for (const file of files) {
108
+ if (!same(await lstat(join(path, file.name)), file.info)) return;
109
+ }
110
+ if (!same(await lstat(path), directory)) return;
111
+ return { directory, files, ownerText };
112
+ };
113
+
114
+ const initial = await inspect();
115
+ if (!initial) return;
116
+ let expectedDirectory = initial.directory;
117
+ let removed = 0;
118
+ // Sorted entries remove launch.json first, retaining proof of ownership if cleanup fails.
119
+ for (const file of initial.files) {
120
+ const current = await inspect(expectedDirectory);
121
+ if (!current || current.ownerText !== initial.ownerText || current.files.length !== initial.files.length - removed
122
+ || current.files.some((entry, index) => entry.name !== initial.files[index + removed].name
123
+ || !same(entry.info, initial.files[index + removed].info))) return;
124
+ await unlink(join(path, file.name));
125
+ removed++;
126
+ // Only our successful unlink may make an otherwise-expired directory fresh.
127
+ expectedDirectory = await lstat(path);
128
+ if (!expectedDirectory.isDirectory() || expectedDirectory.dev !== initial.directory.dev
129
+ || expectedDirectory.ino !== initial.directory.ino) return;
130
+ }
131
+ if ((await readdir(path)).length === 0 && same(await lstat(path), expectedDirectory)) await rmdir(path);
132
+ }
133
+
67
134
  /**
68
135
  * Delete this extension's logs that nothing has written to for `maxAgeMs`.
69
136
  *
70
137
  * Nothing else ever removes them, and they add up to hundreds of megabytes in
71
138
  * a few weeks. Age since the last write is the whole test: a capture still
72
139
  * running keeps its log fresh, and a file xcodebug did not name is left alone.
140
+ * Owned launch-result leftovers additionally require an expired marker and a
141
+ * definitely absent owner; unmarked or uncertain directories are left alone.
73
142
  */
74
143
  export async function pruneLogs(logDir: string, maxAgeMs: number): Promise<void> {
75
144
  let entries: string[];
@@ -80,12 +149,14 @@ export async function pruneLogs(logDir: string, maxAgeMs: number): Promise<void>
80
149
  }
81
150
  const cutoff = Date.now() - maxAgeMs;
82
151
  for (const name of entries) {
83
- if (!OWN_LOG.test(name)) continue;
152
+ const launchResult = name.startsWith(".xcodebug-launch-") && name.length > ".xcodebug-launch-".length;
153
+ if (!OWN_LOG.test(name) && !launchResult) continue;
84
154
  const path = join(logDir, name);
85
155
  try {
86
- if ((await stat(path)).mtimeMs < cutoff) await rm(path, { force: true });
156
+ if (launchResult) await pruneLaunchResult(path, cutoff);
157
+ else if ((await stat(path)).mtimeMs < cutoff) await rm(path, { force: true });
87
158
  } catch {
88
- // A log that cannot be removed is not worth failing a run over.
159
+ // A log or owned result that cannot be removed is not worth failing a run over.
89
160
  }
90
161
  }
91
162
  }
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createInterface } from "node:readline";
4
+ import { fileURLToPath } from "node:url";
5
+ import { dirname, join } from "node:path";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+
8
+ const TOOL_TIMEOUT_SECONDS = 4_200;
9
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
10
+ const serverPath = join(packageRoot, "mcp", "server.ts");
11
+ const codex = process.env.CODEX_BIN ?? "codex";
12
+ const runtime = process.env.XCODEBUG_MCP_RUNTIME ?? "bun";
13
+
14
+ function run(command, args) {
15
+ const result = spawnSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
16
+ if (result.error) throw result.error;
17
+ return result;
18
+ }
19
+
20
+ function ensureServerRegistration() {
21
+ const existing = run(codex, ["mcp", "get", "xcodebug"]);
22
+ if (existing.status === 0) return;
23
+
24
+ const runtimeCheck = run(runtime, ["--version"]);
25
+ if (runtimeCheck.status !== 0) {
26
+ throw new Error(`xcodebug is not registered and ${runtime} is unavailable; install Bun or set XCODEBUG_MCP_RUNTIME`);
27
+ }
28
+ const added = run(codex, ["mcp", "add", "xcodebug", "--", runtime, serverPath]);
29
+ if (added.status !== 0) {
30
+ throw new Error((added.stderr || added.stdout || "codex mcp add failed").trim());
31
+ }
32
+ }
33
+
34
+ function startAppServer() {
35
+ const child = spawn(codex, ["app-server", "--stdio"], { stdio: ["pipe", "pipe", "pipe"] });
36
+ let stderr = "";
37
+ child.stderr.setEncoding("utf8");
38
+ child.stderr.on("data", chunk => { stderr += chunk; });
39
+ const pending = new Map();
40
+ let nextId = 0;
41
+ const input = createInterface({ input: child.stdout });
42
+ input.on("line", line => {
43
+ let message;
44
+ try { message = JSON.parse(line); } catch { return; }
45
+ const request = pending.get(message.id);
46
+ if (!request) return;
47
+ pending.delete(message.id);
48
+ clearTimeout(request.timer);
49
+ if (message.error) request.reject(new Error(JSON.stringify(message.error)));
50
+ else request.resolve(message.result);
51
+ });
52
+ const request = (method, params) => new Promise((resolve, reject) => {
53
+ const id = ++nextId;
54
+ const timer = setTimeout(() => {
55
+ pending.delete(id);
56
+ reject(new Error(`codex app-server timed out during ${method}`));
57
+ }, 15_000);
58
+ pending.set(id, { resolve, reject, timer });
59
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
60
+ });
61
+ const close = async () => {
62
+ for (const { timer } of pending.values()) clearTimeout(timer);
63
+ input.close();
64
+ child.stdin.end();
65
+ await new Promise(resolve => {
66
+ const timer = setTimeout(() => { child.kill(); resolve(); }, 3_000);
67
+ child.once("exit", () => { clearTimeout(timer); resolve(); });
68
+ });
69
+ };
70
+ return { child, request, close, get stderr() { return stderr; } };
71
+ }
72
+
73
+ try {
74
+ ensureServerRegistration();
75
+ const app = startAppServer();
76
+ try {
77
+ await app.request("initialize", { clientInfo: { name: "xcodebug-setup-codex", version: "1" } });
78
+ app.child.stdin.write('{"jsonrpc":"2.0","method":"initialized"}\n');
79
+ const result = await app.request("config/value/write", {
80
+ keyPath: "mcp_servers.xcodebug.tool_timeout_sec",
81
+ value: TOOL_TIMEOUT_SECONDS,
82
+ mergeStrategy: "upsert",
83
+ });
84
+ if (result?.status !== "ok") throw new Error(`Codex rejected the config write: ${JSON.stringify(result)}`);
85
+ console.log(`Configured xcodebug MCP timeout: ${TOOL_TIMEOUT_SECONDS}s`);
86
+ } finally {
87
+ await app.close();
88
+ }
89
+ } catch (error) {
90
+ console.error(`xcodebug setup-codex failed: ${error instanceof Error ? error.message : String(error)}`);
91
+ process.exitCode = 1;
92
+ }