@team-antioch/sc2-adjutant-host-macos 0.1.0 → 0.1.1

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
@@ -8,7 +8,10 @@ The macOS **Host Adapter** for [sc2-adjutant](https://github.com/TeamAntioch/sc2
8
8
  |---|---|
9
9
  | `editor.open`, `editor.checkClosed`, `editor.refresh` | Opens a Map Package in the Galaxy Editor, tells whether the Editor has it open, and closes a clean copy so a compile can rewrite it. It never saves or discards your changes. |
10
10
  | `editor.testDocument`, `editor.save` | Runs File > Test Document, and saves a throwaway copy of a map, through the Editor's menus. |
11
- | `editor.captureTour`, `editor.closeCaptureCopies`, `game.running` | Plays a capture map and screenshots each camera stop, then closes it unsaved. Captures run one at a time through the Editor Broker. |
11
+ | `game.banksDir` | The folder the game keeps its banks in; test_mission snapshots it around a test game. |
12
+ | `editor.captureTour`, `editor.closeCaptureCopies`, `game.running` | Plays a capture map and screenshots each camera stop, then closes it unsaved. Captures run one at a time through the Editor Broker. A capture quits only the game it started. |
13
+ | `game.logsFolder` | `~/Library/Application Support/Blizzard/StarCraft II/GameLogs`. |
14
+ | `game.list`, `game.quit` | Lists the running games with their start times, and quits one recorded game gracefully (Cmd+Option+Q, then Yes), killing it only after a timeout. |
12
15
  | `screen.capture` | Captures the game's window, else the Editor's. |
13
16
  | `tts.speak` | Speaks placeholder voice lines with macOS's `say`. |
14
17
  | `model.render`, `model.rendererKey`, `model.export`, `model.exportGltf` | Renders game and mod models to turntable thumbnails, and exports them as `.m3` or glTF, with the WhiteoutFlakes model viewer. |
@@ -21,7 +21,8 @@ import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/prom
21
21
  import os from "node:os";
22
22
  import path from "node:path";
23
23
  import { promisify } from "node:util";
24
- import { CAPTURE_MAPS_FOLDER } from "@team-antioch/sc2-adjutant/plugin-sdk";
24
+ import { CAPTURE_MAPS_FOLDER, ownedGame, quitOwnedGame, refuseForeignGame } from "@team-antioch/sc2-adjutant/plugin-sdk";
25
+ import { macSystem } from "./games.js";
25
26
  const run = promisify(execFile);
26
27
  const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
27
28
  const EDITOR = "StarCraft II Editor";
@@ -181,6 +182,25 @@ tell application "System Events" to tell process "${EDITOR}"
181
182
  end try
182
183
  end repeat
183
184
  end tell`;
185
+ /**
186
+ * The game window's size while recording, in points: 1280 wide, with a 16:9 picture under a 28-point
187
+ * title bar. Window capture gets no frames while the game window fills the display: macOS then
188
+ * hands it to the display without compositing it (2026-11-23: 27 s of nothing at 1728x1084, then
189
+ * steady frames from just after it was resized, with no gaps).
190
+ */
191
+ export const RECORD_WINDOW = { width: 1280, height: 748 };
192
+ /** How many times a recorder that exits before its first frame is started again in one tour. */
193
+ const RECORD_TRIES = 3;
194
+ /** resize-game <width> <height>: resizes the game's window; prints its size afterwards, "w, h", or nothing while the game doesn't answer (it doesn't while loading). */
195
+ const RESIZE_GAME = `on run argv
196
+ tell application "System Events" to tell process "SC2"
197
+ if (count of windows) is 0 then return ""
198
+ set size of window 1 to {(item 1 of argv) as integer, (item 2 of argv) as integer}
199
+ delay 0.3
200
+ set {w, h} to size of window 1
201
+ return (w as text) & ", " & (h as text)
202
+ end tell
203
+ end run`;
184
204
  const PRESS_SPACE = `
185
205
  tell application "System Events" to tell process "SC2" to set value of attribute "AXFrontmost" to true
186
206
  delay 0.3
@@ -266,6 +286,222 @@ guard let scaled = context.makeImage() else { exit(1) }
266
286
  CGImageDestinationAddImage(destination, scaled, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
267
287
  exit(CGImageDestinationFinalize(destination) ? 0 : 1)
268
288
  `;
289
+ /**
290
+ * record <window-id> <out.mp4> <width> <fps> <quality>: records one window as HEVC at <quality>
291
+ * (AVVideoQualityKey, 0-1), the 16:9 picture under its title bar, scaled to <width>. A covered window records; a minimized one doesn't. Frames come only
292
+ * when the window changes, so a still scene costs next to nothing. Prints "started <unix seconds>"
293
+ * at the first frame, which is the video's time 0; stops, finishing the file, when stdin closes
294
+ * (so a caller that dies doesn't leave it recording) or on SIGINT/SIGTERM.
295
+ */
296
+ const RECORD_SWIFT = `import AppKit
297
+ import AVFoundation
298
+ import CoreMedia
299
+ import Foundation
300
+ import ScreenCaptureKit
301
+
302
+ _ = NSApplication.shared // a command-line tool needs the window server connection ScreenCaptureKit uses
303
+ let args = CommandLine.arguments
304
+ guard args.count == 6, let windowID = UInt32(args[1]), let width = Int(args[3]), let fps = Int32(args[4]), let quality = Double(args[5]), quality > 0, quality <= 1 else {
305
+ FileHandle.standardError.write("usage: record <window-id> <out.mp4> <width> <fps> <quality 0-1>\\n".data(using: .utf8)!)
306
+ exit(2)
307
+ }
308
+ let outURL = URL(fileURLWithPath: args[2])
309
+ try? FileManager.default.removeItem(at: outURL)
310
+
311
+ final class Recorder: NSObject, SCStreamOutput, SCStreamDelegate {
312
+ let queue = DispatchQueue(label: "record")
313
+ var writer: AVAssetWriter?
314
+ var input: AVAssetWriterInput?
315
+ var started = false
316
+ var finishing = false
317
+ var counts: [Int: Int] = [:]
318
+ var lastReport = Date()
319
+
320
+ func setup(width: Int, height: Int, fps: Int32, quality: Double) throws {
321
+ let writer = try AVAssetWriter(outputURL: outURL, fileType: .mp4)
322
+ let input = AVAssetWriterInput(mediaType: .video, outputSettings: [
323
+ AVVideoCodecKey: AVVideoCodecType.hevc,
324
+ AVVideoWidthKey: width,
325
+ AVVideoHeightKey: height,
326
+ AVVideoCompressionPropertiesKey: [AVVideoQualityKey: quality, AVVideoExpectedSourceFrameRateKey: Int(fps)],
327
+ ])
328
+ input.expectsMediaDataInRealTime = true
329
+ writer.add(input)
330
+ writer.startWriting()
331
+ self.writer = writer
332
+ self.input = input
333
+ }
334
+
335
+ func stream(_ stream: SCStream, didOutputSampleBuffer buffer: CMSampleBuffer, of type: SCStreamOutputType) {
336
+ guard type == .screen, !finishing, let writer, let input else { return }
337
+ let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[SCStreamFrameInfo: Any]]
338
+ let status = attachments?.first?[.status] as? Int ?? -1
339
+ counts[status, default: 0] += 1
340
+ // Every 5 s, how many frames came by status (0 complete, 1 idle, 2 blank, 3 suspended, 4 started, 5 stopped), to stderr.
341
+ if Date().timeIntervalSince(lastReport) >= 5 {
342
+ lastReport = Date()
343
+ FileHandle.standardError.write("record: frames by status \\(counts.sorted { $0.key < $1.key })\\n".data(using: .utf8)!)
344
+ }
345
+ guard buffer.isValid, SCFrameStatus(rawValue: status) == .complete else { return }
346
+ if !started {
347
+ writer.startSession(atSourceTime: buffer.presentationTimeStamp)
348
+ started = true
349
+ print("started \\(Date().timeIntervalSince1970)")
350
+ fflush(stdout)
351
+ }
352
+ if input.isReadyForMoreMediaData { input.append(buffer) }
353
+ }
354
+
355
+ func stream(_ stream: SCStream, didStopWithError error: Error) {
356
+ FileHandle.standardError.write("record: the stream stopped: \\(error)\\n".data(using: .utf8)!)
357
+ finish(code: 1)
358
+ }
359
+
360
+ func finish(code: Int32) {
361
+ queue.async {
362
+ guard !self.finishing else { return }
363
+ self.finishing = true
364
+ guard let writer = self.writer, let input = self.input, self.started, writer.status == .writing else { exit(code) }
365
+ input.markAsFinished()
366
+ writer.finishWriting { exit(writer.status == .completed ? code : 1) }
367
+ }
368
+ }
369
+ }
370
+
371
+ let recorder = Recorder()
372
+ var stream: SCStream?
373
+ func stop() {
374
+ Task {
375
+ try? await stream?.stopCapture()
376
+ recorder.finish(code: 0)
377
+ }
378
+ }
379
+
380
+ Task {
381
+ do {
382
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
383
+ guard let window = content.windows.first(where: { $0.windowID == windowID }) else {
384
+ FileHandle.standardError.write("record: no window \\(windowID)\\n".data(using: .utf8)!)
385
+ exit(3)
386
+ }
387
+ // The 16:9 picture at the bottom of the window: what sits above it is the title bar.
388
+ let frame = window.frame
389
+ let pictureHeight = min(frame.height, frame.width * 9 / 16)
390
+ FileHandle.standardError.write("record: window \\(windowID) \\(window.owningApplication?.applicationName ?? "?") \\(Int(frame.width))x\\(Int(frame.height)) on screen: \\(window.isOnScreen)\\n".data(using: .utf8)!)
391
+ // A window on a display of 1 pixel a point has fewer pixels than the recording is wide: it is
392
+ // scaled up then, with no more detail than it had.
393
+ let filter = SCContentFilter(desktopIndependentWindow: window)
394
+ let scale = Double(SCShareableContent.info(for: filter).pointPixelScale)
395
+ FileHandle.standardError.write("record: \\(scale)x, recording \\(width) wide\\(Double(frame.width) * scale < Double(width) ? ", scaled up from \\(Int(Double(frame.width) * scale)) pixels: the window is on a display of fewer pixels a point" : "")\\n".data(using: .utf8)!)
396
+ let config = SCStreamConfiguration()
397
+ config.sourceRect = CGRect(x: 0, y: frame.height - pictureHeight, width: frame.width, height: pictureHeight)
398
+ config.width = width & ~1
399
+ config.height = Int((Double(width) * Double(pictureHeight / frame.width)).rounded()) & ~1
400
+ config.minimumFrameInterval = CMTime(value: 1, timescale: fps)
401
+ config.showsCursor = false
402
+ config.queueDepth = 8
403
+ try recorder.setup(width: config.width, height: config.height, fps: fps, quality: quality)
404
+ let started = SCStream(filter: filter, configuration: config, delegate: recorder)
405
+ try started.addStreamOutput(recorder, type: .screen, sampleHandlerQueue: recorder.queue)
406
+ try await started.startCapture()
407
+ stream = started
408
+ } catch {
409
+ FileHandle.standardError.write("record: \\(error)\\n".data(using: .utf8)!)
410
+ exit(1)
411
+ }
412
+ }
413
+
414
+ var signals: [DispatchSourceSignal] = []
415
+ for number in [SIGINT, SIGTERM] {
416
+ signal(number, SIG_IGN)
417
+ let source = DispatchSource.makeSignalSource(signal: number, queue: .main)
418
+ source.setEventHandler(handler: stop)
419
+ source.resume()
420
+ signals.append(source)
421
+ }
422
+ DispatchQueue.global().async {
423
+ while readLine() != nil {}
424
+ stop()
425
+ }
426
+ dispatchMain()
427
+ `;
428
+ /**
429
+ * The recorder's HEVC quality (AVVideoQualityKey) when a request doesn't give one. At 0.5 the
430
+ * hardware encoder made about 80 kbps of a 1280x720 tour, and smeared particles away.
431
+ */
432
+ export const DEFAULT_VIDEO_QUALITY = 0.9;
433
+ /** The recording's file names in a tour's output folder. */
434
+ export const VIDEO_FILE = "video.mp4";
435
+ export const VIDEO_STOPS_FILE = "video-stops.txt";
436
+ /**
437
+ * Starts recording `window` into `<outputDir>/video.mp4`. Each `mark` appends `<label> <seconds>` to
438
+ * video-stops.txt (a stop's number, or m<n> for the bank's "mark" key), the seconds into the video
439
+ * by the recorder's own first-frame clock; marks made before the first frame are timed from when it
440
+ * came. A failure to write the timeline is logged, not thrown, so it never stops a tour.
441
+ */
442
+ async function startRecording(context, window, outputDir, video, log) {
443
+ const bin = await swiftTool(context, "record", RECORD_SWIFT);
444
+ log(`recording window ${window}`);
445
+ const stopsFile = path.join(outputDir, VIDEO_STOPS_FILE);
446
+ await rm(stopsFile, { force: true });
447
+ const child = spawn(bin, [window, path.join(outputDir, VIDEO_FILE), String(video.width), String(video.fps), String(video.quality ?? DEFAULT_VIDEO_QUALITY)], { stdio: ["pipe", "pipe", "pipe"] });
448
+ let startedAt;
449
+ let gone = false;
450
+ const early = [];
451
+ const write = (stop, at) => appendFile(stopsFile, `${stop} ${Math.max(0, at - startedAt).toFixed(3)}\n`).catch((error) => log(`couldn't write ${VIDEO_STOPS_FILE}: ${error.message}`));
452
+ let pending = Promise.resolve();
453
+ // Read as whole lines: a chunk can end inside "started <seconds>".
454
+ let partial = "";
455
+ child.stdout.setEncoding("utf8").on("data", (text) => {
456
+ const lines = (partial + text).split("\n");
457
+ partial = lines.pop();
458
+ for (const line of lines) {
459
+ const match = /^started ([0-9.]+)$/.exec(line.trim());
460
+ if (!match || startedAt !== undefined)
461
+ continue;
462
+ startedAt = Number(match[1]);
463
+ pending = pending.then(async () => {
464
+ for (const { stop, at } of early.splice(0))
465
+ await write(stop, at);
466
+ });
467
+ }
468
+ });
469
+ child.stderr.setEncoding("utf8").on("data", (text) => log(text.trim()));
470
+ // A helper that can't start, or a pipe it has already closed, is logged, never thrown.
471
+ child.on("error", (error) => log(`record helper: ${error.message}`));
472
+ child.stdin.on("error", () => undefined);
473
+ const exited = new Promise((resolve) => {
474
+ child.on("exit", (code) => {
475
+ gone = true;
476
+ if (startedAt === undefined)
477
+ log(`record helper exited (${code ?? "killed"}) before its first frame`);
478
+ resolve();
479
+ });
480
+ child.on("error", () => {
481
+ gone = true;
482
+ resolve();
483
+ });
484
+ });
485
+ return {
486
+ mark: async (stop) => {
487
+ const at = Date.now() / 1000;
488
+ if (startedAt === undefined)
489
+ early.push({ stop, at });
490
+ else
491
+ pending = pending.then(() => write(stop, at));
492
+ await pending;
493
+ },
494
+ stop: async () => {
495
+ child.stdin.end();
496
+ // Finishing the file is quick; one that hangs is killed, losing only its unwritten tail.
497
+ const done = await Promise.race([exited.then(() => true), sleep(15).then(() => false)]);
498
+ if (!done)
499
+ child.kill("SIGKILL");
500
+ await pending;
501
+ },
502
+ failed: () => gone && startedAt === undefined,
503
+ };
504
+ }
269
505
  /** A Swift helper, compiled once into the cache folder. */
270
506
  async function swiftTool(context, name, source) {
271
507
  const folder = path.join(context.requirePath("cacheDir"), "host-macos", "bin");
@@ -285,15 +521,18 @@ async function swiftTool(context, name, source) {
285
521
  const osascript = async (script, args = [], language = "AppleScript") => (await run("osascript", ["-l", language, "-e", script, ...args])).stdout;
286
522
  const quietly = async (script, args = []) => osascript(script, args).catch(() => "");
287
523
  const windowList = (owner) => osascript(WINDOW_LIST, [owner], "JavaScript").catch(() => "");
288
- export async function gameRunning() {
289
- return run("pgrep", ["-f", "MacOS/SC2 "]).then(() => true, () => false);
524
+ /** The folder the game saves its banks in (`game.banksDir`). */
525
+ export async function banksDir() {
526
+ return BANKS;
290
527
  }
291
- async function quitGame() {
292
- await run("pkill", ["-f", "MacOS/SC2 "]).catch(() => undefined);
293
- await sleep(2);
294
- await run("pkill", ["-9", "-f", "MacOS/SC2 "]).catch(() => undefined);
295
- await sleep(1);
528
+ /** Whether any game runs: what attaching to the author's game and the broker's hold ask. */
529
+ export async function gameRunning() {
530
+ return (await macSystem.list()).length > 0;
296
531
  }
532
+ /** Every running game, with its start time. */
533
+ export const listGames = () => macSystem.list();
534
+ /** Quits this game and no other, gracefully, killing it only after a timeout (games.ts). */
535
+ export const quitGame = (request) => quitOwnedGame(request.game, macSystem, request.log ?? (() => undefined));
297
536
  /** The game's main window id, for `screencapture -l`. */
298
537
  async function gameWindow() {
299
538
  for (const line of (await windowList("SC2")).split("\n")) {
@@ -335,11 +574,14 @@ async function notify(title, message) {
335
574
  }
336
575
  /**
337
576
  * Closes, without saving, every capture copy the Editor has open (any document whose window title
338
- * shows a copy in <cacheDir>/capture/maps/), quitting the game first when one is open, since that game is
339
- * most likely testing it. The Editor Broker runs this as it starts and after a failed tour.
577
+ * shows a copy in <cacheDir>/capture/maps/), after quitting the games it is given: the capture's own,
578
+ * which the broker recorded. Another game is left running. The Editor Broker runs this as it starts and after a failed tour.
340
579
  */
341
580
  export async function closeCaptureCopies(request, context) {
342
581
  const log = request.log ?? (() => undefined);
582
+ // Only the games the broker recorded as a capture's; one it didn't is the author's to quit.
583
+ for (const game of request.games ?? [])
584
+ await quitGame({ game, log });
343
585
  const maps = path.join(context.requirePath("cacheDir"), CAPTURE_MAPS_FOLDER);
344
586
  const titles = (await quietly(AX_WINDOWS)) + "\n" + (await windowList(EDITOR));
345
587
  // Only this machine's capture folder: a copy under another cache's folder isn't this broker's to
@@ -349,10 +591,8 @@ export async function closeCaptureCopies(request, context) {
349
591
  const names = new Set(titledMapNames(titles).filter((name) => titles.includes(path.join(maps, name)) || (BROKER_COPY_NAME.test(name) && existsSync(path.join(maps, name)))));
350
592
  if (names.size === 0)
351
593
  return;
352
- if (await gameRunning()) {
353
- log("quitting the game a capture copy left running");
354
- await quitGame();
355
- }
594
+ if (!request.games?.length && (await gameRunning()))
595
+ log("a game is running that this tool didn't start: left running");
356
596
  for (const name of names) {
357
597
  log(`closing ${name}`);
358
598
  await closeMap(context, path.join(maps, name), log);
@@ -381,6 +621,9 @@ export async function captureTour(request, context) {
381
621
  "An Editor Broker it started inherits the permission, so stop a running broker too.");
382
622
  }
383
623
  const crop = await swiftTool(context, "crop", CROP_SWIFT);
624
+ // Compiled now, not in the watch loop, where a first build takes several seconds.
625
+ if (request.video)
626
+ await swiftTool(context, "record", RECORD_SWIFT);
384
627
  const bankFile = path.join(BANKS, `${request.bank}.SC2Bank`);
385
628
  await mkdir(request.outputDir, { recursive: true });
386
629
  // Keep the display awake for the whole run: a sleeping or locked screen stops every capture.
@@ -390,20 +633,29 @@ export async function captureTour(request, context) {
390
633
  // Set once this run may have opened the map or started the game; whatever ends the run then
391
634
  // quits the game and closes the map.
392
635
  let touchedEditor = false;
636
+ // The game this capture starts, once it appears: the only one it asks about or quits. Attaching, the author's game is watched and left alone.
637
+ const own = ownedGame(macSystem, request.onGameStarted);
638
+ const gameUp = request.attach ? gameRunning : () => own.running();
393
639
  const shrinking = [];
394
640
  // Attached to a game already running, the bank may still hold an earlier run's last stop (-1);
395
641
  // that content is ignored until the game saves the bank again.
396
642
  let leftover;
643
+ let recording;
644
+ // The last stop noted in the video: a stop whose screenshot failed is retried, but noted once.
645
+ let marked = 0;
646
+ let lastMark;
647
+ let lastResize = 0;
397
648
  try {
398
649
  stopIfCancelled();
399
650
  if (request.attach) {
400
- if (!(await gameRunning()))
651
+ if (!(await gameUp()))
401
652
  throw new Error("no game is running to watch");
402
653
  leftover = existsSync(bankFile) ? await readFile(bankFile, "utf8") : undefined;
403
654
  }
404
655
  else {
405
656
  await rm(bankFile, { force: true });
406
- await quitGame();
657
+ // Nothing is quit here: a game already running isn't this capture's.
658
+ await refuseForeignGame(macSystem);
407
659
  // A copy left open by an earlier run would be tested as it was: opening only brings it forward.
408
660
  if (await mapOpen(mapPath)) {
409
661
  log("closing a stale copy");
@@ -414,7 +666,8 @@ export async function captureTour(request, context) {
414
666
  stopIfCancelled();
415
667
  await request.writeMap?.();
416
668
  touchedEditor = true;
417
- await run("open", ["-g", "-a", context.requirePath("editorPath"), mapPath]);
669
+ // Through its component list, as the host's own open does: a folder can open as a packed document.
670
+ await run("open", ["-g", "-a", context.requirePath("editorPath"), path.join(mapPath, "ComponentList.SC2Components")]);
418
671
  const opened = await waitFor(300, 2, () => mapOpen(mapPath));
419
672
  stopIfCancelled();
420
673
  if (!opened) {
@@ -427,7 +680,7 @@ export async function captureTour(request, context) {
427
680
  if (clicked.includes("clicked"))
428
681
  log("Test Document clicked");
429
682
  restoredTerrain = clicked.includes("restored");
430
- const started = await waitFor(30, 2, gameRunning);
683
+ const started = await waitFor(30, 2, gameUp);
431
684
  stopIfCancelled();
432
685
  if (!started) {
433
686
  log("couldn't bring the Editor forward; trying again every 30 s, or waiting for File > Test Document (15 min)");
@@ -439,7 +692,7 @@ export async function captureTour(request, context) {
439
692
  let lastTry = Date.now();
440
693
  await waitFor(900, 2, async () => {
441
694
  compileErrors = (await windowList(EDITOR)).includes("Script Compile Errors");
442
- if (compileErrors || (await gameRunning()))
695
+ if (compileErrors || (await gameUp()))
443
696
  return true;
444
697
  if (Date.now() - lastTry >= RAISE_RETRY_MS) {
445
698
  lastTry = Date.now();
@@ -452,24 +705,55 @@ export async function captureTour(request, context) {
452
705
  return false;
453
706
  });
454
707
  stopIfCancelled();
455
- if (compileErrors && !(await gameRunning())) {
708
+ if (compileErrors && !(await gameUp())) {
456
709
  throw new Error(`the Editor shows script compile errors for ${path.basename(mapPath)}`);
457
710
  }
458
711
  }
459
- if (!(await gameRunning())) {
712
+ if (!(await gameUp())) {
460
713
  throw new Error("the game never started");
461
714
  }
462
715
  }
463
716
  log("game started; it can sit behind other windows now (don't minimize it)");
464
717
  let last = 0;
465
718
  let frames = 0;
466
- let idle = 0;
719
+ let watch = { since: Date.now(), lastPress: 0 };
467
720
  let warnedNoWindow = false;
468
721
  let end = "never started";
722
+ // Recording, the bank is read more often, so each stop's time in the video is closer.
723
+ const poll = request.video ? 0.1 : 0.5;
724
+ let polled = Date.now();
725
+ let resizeTries = 0;
726
+ let recordTries = 0;
469
727
  for (;;) {
470
- await sleep(0.5);
728
+ await sleep(poll);
729
+ // A watch loop this slow misses stops: say so, as a lead.
730
+ const took = (Date.now() - polled) / 1000;
731
+ if (took > 1.5)
732
+ log(`slow watch loop: ${took.toFixed(1)} s since the last poll`);
733
+ polled = Date.now();
471
734
  stopIfCancelled();
472
- if (!(await gameRunning())) {
735
+ // Recording waits until the game window is smaller than the display (RECORD_WINDOW), which
736
+ // the game allows only once it has loaded; tried once a second until then.
737
+ // A recorder that exited before its first frame is started again, up to RECORD_TRIES times.
738
+ if (recording?.failed()) {
739
+ recording = undefined;
740
+ if (recordTries >= RECORD_TRIES)
741
+ log(`no video: the recorder failed ${recordTries} times`);
742
+ }
743
+ if (request.video && !recording && recordTries < RECORD_TRIES && Date.now() - lastResize >= 1000) {
744
+ lastResize = Date.now();
745
+ const window = await gameWindow();
746
+ const size = window ? (await quietly(RESIZE_GAME, [String(RECORD_WINDOW.width), String(RECORD_WINDOW.height)])).trim() : "";
747
+ if (window && size === `${RECORD_WINDOW.width}, ${RECORD_WINDOW.height}`) {
748
+ recordTries++;
749
+ recording = await startRecording(context, window, request.outputDir, request.video, log);
750
+ log(`game window resized to ${size}; recording it to ${path.join(request.outputDir, VIDEO_FILE)}`);
751
+ }
752
+ else if (window && ++resizeTries % 10 === 0) {
753
+ log(`no recording yet: the game window is ${size || "not answering"}, and recording waits for ${RECORD_WINDOW.width}, ${RECORD_WINDOW.height}`);
754
+ }
755
+ }
756
+ if (!(await gameUp())) {
473
757
  log(`game exited at stop ${last}`);
474
758
  end = "game exited";
475
759
  break;
@@ -478,18 +762,25 @@ export async function captureTour(request, context) {
478
762
  if (leftover !== undefined && bank !== leftover)
479
763
  leftover = undefined;
480
764
  const stop = leftover === undefined ? bankValue(bank, "stop", "int") : undefined;
481
- if (stop === undefined) {
482
- idle++;
483
- if (idle >= request.pressSpaceAfterSeconds * 2 && idle % 20 === 0) {
484
- log("no stop yet; pressing Space in the game (takes focus)");
485
- await quietly(PRESS_SPACE);
486
- }
487
- if (idle > request.startSeconds * 2) {
488
- log("the tour never started");
489
- break;
490
- }
491
- continue;
765
+ // A tour that records may save an int key "mark" as well, just before something worth timing
766
+ // (the effect tour: each attach), noted in the video's timeline as m<mark>.
767
+ const mark = recording && leftover === undefined ? bankValue(bank, "mark", "int") : undefined;
768
+ if (recording && mark !== undefined && mark !== lastMark) {
769
+ lastMark = mark;
770
+ await recording.mark(`m${mark}`);
492
771
  }
772
+ const watched = watchStop(watch, stop, Date.now(), request);
773
+ watch = watched.watch;
774
+ if (watched.pressSpace) {
775
+ log("no stop yet; pressing Space in the game (takes focus)");
776
+ await quietly(PRESS_SPACE);
777
+ }
778
+ if (watched.neverStarted) {
779
+ log("the tour never started");
780
+ break;
781
+ }
782
+ if (stop === undefined)
783
+ continue;
493
784
  if (stop === "-1") {
494
785
  end = "done";
495
786
  log(`tour done (${frames} stops)`);
@@ -497,6 +788,10 @@ export async function captureTour(request, context) {
497
788
  }
498
789
  if (Number(stop) === last)
499
790
  continue;
791
+ if (recording && Number(stop) !== marked) {
792
+ marked = Number(stop);
793
+ await recording.mark(stop);
794
+ }
500
795
  const window = await gameWindow();
501
796
  if (!window) {
502
797
  if (!warnedNoWindow)
@@ -527,9 +822,15 @@ export async function captureTour(request, context) {
527
822
  return { frames, end };
528
823
  }
529
824
  finally {
825
+ // Whatever went wrong recording, the rest still runs: the shrinks, quitting the game, closing the map.
826
+ await recording?.stop().catch((error) => log(`couldn't finish the recording: ${error.message}`));
530
827
  await Promise.all(shrinking);
531
828
  if (touchedEditor) {
532
- await quitGame();
829
+ // A game that appeared since the last look is this capture's too.
830
+ await own.running().catch(() => false);
831
+ const game = own.game();
832
+ if (game)
833
+ await quitOwnedGame(game, macSystem, log).catch((error) => log(`couldn't quit the game: ${error.message}`));
533
834
  await closeMap(context, mapPath, log).catch((error) => log(`couldn't close ${path.basename(mapPath)}: ${error.message}`));
534
835
  if (restoredTerrain)
535
836
  await quietly(MINIMIZE_TERRAIN);
@@ -537,6 +838,24 @@ export async function captureTour(request, context) {
537
838
  awake.kill();
538
839
  }
539
840
  }
841
+ /**
842
+ * One poll of the bank, as the watch loop's clock sees it: whether to press Space, and whether the
843
+ * tour never started. Time without a stop counts from the last stop the bank held, not from the
844
+ * start of the tour, so a long tour whose bank is read mid-save keeps going. It is timed by the
845
+ * clock (`now`, in ms), not by counting polls: a recording's loop polls faster, and each pass costs
846
+ * more than its sleep.
847
+ */
848
+ export function watchStop(watch, stop, now, limits) {
849
+ if (stop !== undefined)
850
+ return { watch: { ...watch, since: now }, pressSpace: false, neverStarted: false };
851
+ const waited = (now - watch.since) / 1000;
852
+ const pressSpace = waited >= limits.pressSpaceAfterSeconds && now - watch.lastPress >= 10_000;
853
+ return {
854
+ watch: pressSpace ? { ...watch, lastPress: now } : watch,
855
+ pressSpace,
856
+ neverStarted: waited > limits.startSeconds,
857
+ };
858
+ }
540
859
  /** Polls `check` every `every` seconds for up to `seconds`; whether it came true. Gives up, false, once `signal` is aborted. */
541
860
  async function waitUntil(seconds, every, check, signal) {
542
861
  for (let waited = 0; waited < seconds; waited += every) {
package/dist/games.js ADDED
@@ -0,0 +1,49 @@
1
+ // Reading and driving the game's processes on the Mac, for the capture's game ownership (the
2
+ // logic, shared with the Windows adapter, is core's game-ownership.ts). Keys go to the game's own
3
+ // process through System Events, brought forward first.
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ const run = promisify(execFile);
7
+ /** The game processes in `ps -axww -o pid=,lstart=,command=` output: the start time is `lstart`'s, as printed, and only compared. */
8
+ export function parseGames(output) {
9
+ const games = [];
10
+ for (const line of output.split("\n")) {
11
+ const match = /^\s*(\d+)\s+(\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4})\s+(.*)$/.exec(line);
12
+ // The same test pgrep made: the game's executable inside its bundle, followed by its arguments.
13
+ if (match && match[3].includes("MacOS/SC2 "))
14
+ games.push({ pid: Number(match[1]), startedAt: match[2] });
15
+ }
16
+ return games;
17
+ }
18
+ /** Brings the game's process forward and sends it one key (an AppleScript key spec in argv). */
19
+ export const KEY_TO_GAME = `
20
+ on run argv
21
+ set p to (item 1 of argv) as integer
22
+ set k to item 2 of argv
23
+ tell application "System Events"
24
+ set proc to first process whose unix id is p
25
+ set frontmost of proc to true
26
+ delay 0.3
27
+ if not (frontmost of proc) then error "couldn't bring the game forward"
28
+ if k is "quit" then
29
+ keystroke "q" using {command down, option down}
30
+ else
31
+ keystroke k
32
+ end if
33
+ end tell
34
+ end run`;
35
+ /** The key that answers Yes in the game's Confirm Exit dialog. Needs a real run to confirm. */
36
+ export const YES_KEY = "y";
37
+ /** The real machine: `ps`, System Events keystrokes (Cmd+Option+Q, then Yes) to the game's process, and SIGKILL on its pid. */
38
+ export const macSystem = {
39
+ async list() {
40
+ const { stdout } = await run("ps", ["-axww", "-o", "pid=,lstart=,command="], { env: { ...process.env, LC_ALL: "C" }, maxBuffer: 16 * 1024 * 1024 });
41
+ return parseGames(stdout);
42
+ },
43
+ requestQuit: async (pid) => void (await run("osascript", ["-e", KEY_TO_GAME, String(pid), "quit"])),
44
+ confirmQuit: async (pid) => void (await run("osascript", ["-e", KEY_TO_GAME, String(pid), YES_KEY])),
45
+ async kill(pid) {
46
+ process.kill(pid, "SIGKILL");
47
+ },
48
+ sleep: (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000)),
49
+ };
package/dist/index.js CHANGED
@@ -16,13 +16,17 @@
16
16
  // The automation needs Accessibility permission for the app that runs the MCP server.
17
17
  import { execFile } from "node:child_process";
18
18
  import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
19
- import { tmpdir } from "node:os";
19
+ import os, { tmpdir } from "node:os";
20
20
  import path from "node:path";
21
21
  import { promisify } from "node:util";
22
22
  import { fragmentFor, refusalFor, windowState } from "./refresh.js";
23
- import { captureScreen, captureTour, closeCaptureCopies, gameRunning } from "./capture-tour.js";
23
+ import { banksDir, captureScreen, captureTour, closeCaptureCopies, gameRunning, listGames, quitGame } from "./capture-tour.js";
24
24
  import { exportModel, exportModelGltf, rendererKey, renderModel } from "./whiteoutflakes.js";
25
25
  const run = promisify(execFile);
26
+ /** game.logsFolder: where the game on the Mac writes its logs, under the user's Library. */
27
+ async function gameLogsFolder() {
28
+ return path.join(os.homedir(), "Library", "Application Support", "Blizzard", "StarCraft II", "GameLogs");
29
+ }
26
30
  /**
27
31
  * How long to wait for the Editor to show the map and for the game to start, in seconds, when the
28
32
  * caller gives no budget of its own. Together they stay under an MCP client's usual 60 s request
@@ -200,8 +204,7 @@ async function refreshEditor({ mapPath }) {
200
204
  /** The ids of the running game processes. */
201
205
  async function gamePids() {
202
206
  try {
203
- const { stdout } = await run("pgrep", ["-f", "MacOS/SC2 "]);
204
- return stdout.split("\n").filter(Boolean);
207
+ return (await listGames()).map((game) => String(game.pid));
205
208
  }
206
209
  catch {
207
210
  return [];
@@ -231,6 +234,10 @@ const plugin = {
231
234
  "editor.captureTour": captureTour,
232
235
  "editor.closeCaptureCopies": closeCaptureCopies,
233
236
  "game.running": gameRunning,
237
+ "game.banksDir": banksDir,
238
+ "game.list": listGames,
239
+ "game.quit": quitGame,
240
+ "game.logsFolder": gameLogsFolder,
234
241
  "screen.capture": captureScreen,
235
242
  "tts.speak": speak,
236
243
  "model.render": renderModel,
@@ -73,11 +73,13 @@ The adapter's AppleScript and Swift helpers are in `packages/plugin-host-macos/i
73
73
 
74
74
  ## The Editor Broker: one Editor job at a time
75
75
 
76
- There is one Editor, one menu bar and one frontmost window. Two captures at once click menus on each other's maps and capture each other's windows. A Test Document during a capture starts a second game, which the capture then quits. The Editor Broker (`packages/core/src/capture/editor-broker.ts`) is the one process that runs `editor.captureTour` and the other Editor actions that click menus, one job at a time, first come first served.
76
+ There is one Editor, one menu bar and one frontmost window. Two captures at once click menus on each other's maps and capture each other's windows. A Test Document during a capture starts a second game. The Editor Broker (`packages/core/src/capture/editor-broker.ts`) is the one process that runs `editor.captureTour` and the other Editor actions that click menus, one job at a time, first come first served.
77
77
 
78
78
  - **What goes through it.** Every `editor.captureTour` run: `capture_shots` and `npm run capture-shots`, `capture-exemplars`, `capture-sets` and `capture-edit`. Nothing else opens or closes capture copies. On a machine whose Host Adapter captures, `editor.open`, `editor.refresh`, `editor.testDocument` and `editor.save` go through it too (`runEditorAction` in `editor-broker-client.ts`), so `test_mission`, `compile_cutscene` with `play`, and the MapScript drift test take their turn in the same queue. `editor.checkClosed` only reads window titles and goes straight to the host. A host that can't capture has no broker, and runs those actions directly.
79
79
  - **`test_mission` doesn't wait.** Its whole call has to fit under the MCP client's 60 s request timeout, so its Test Document is refused at once while a capture runs or waits. The reply names the job ("The Editor is busy … capture job <id> of <map> is running, 2 more waiting") and tells the author to wait, not to click Test Document by hand. The drift test's save does wait its turn.
80
- - **A test game holds the queue.** A capture starts by quitting any game it finds. So after a Test Document that started a game, the broker starts nothing else until that game quits, checking `game.running` every 5 seconds. Meanwhile its status shows the Test Document job as running with `holding: true`, the log says `holding the queue until the test game quits`, and another `test_mission` is refused ("quit it first"). A game the author started from the Editor by hand isn't held for: a capture still quits it.
80
+ - **A test game holds the queue.** The broker records each game a job starts, by pid and start time (`game.list`; a pid is reused once its process exits, so a pid alone is never trusted). A Test Document's game is the author's to play: the broker starts nothing else until that game quits, checking every 5 seconds, and never quits it. Meanwhile its status shows the Test Document job as running with `holding: true` and the game under `games` as `owner: author`, the log says `holding the queue until the test game quits`, and another `test_mission` is refused ("quit it first"). A game the author started from the Editor by hand isn't recorded, and isn't held for, but no capture touches it either: a capture that isn't attaching refuses ("A game is running that this tool didn't start. Quit it, or capture with `attach`."), and `editor.closeCaptureCopies` quits only the games the broker hands it.
81
+ - **A capture quits only its own game, and gracefully.** The capture records the game its Test Document started (the first game to appear, since it refuses to start with one running), and the broker lists it under `games` as `owner: tool`. At the end of a run, and after a failed or cancelled one, `game.quit` quits that pid and no other (never `pkill -f`): it brings the game forward and presses Cmd+Option+Q through System Events, then `y` for Yes in the Confirm Exit dialog, so the game writes its logs on exit. If the process hasn't gone 20 seconds later it is killed with SIGKILL, after checking again that the pid still has the recorded start time. The log says which it was (`quit gracefully` or `killing it`). The key for Yes, and that the quit leaves complete logs, are checked on a real run (#57).
82
+ - **The capture copy opens by its component list.** The capture runs `open -g -a <Editor> <copy>/ComponentList.SC2Components`, as the host's own open does, since a folder can open as a packed document. It then waits for the Editor's window title to show the copy's name, as before; whether the title still matches when opened this way is checked on a real run.
81
83
  - **Merged tours.** Waiting tour jobs on the same map with the same capture options (lighting among them) run as one tour, and the frames are split back to each job, so the game starts once for all of them.
82
84
  - **Its socket and log.** It listens on `<cacheDir>/editor-broker.sock` (the machine config's `cacheDir`). When that path is longer than a Unix socket allows (103 bytes), it uses `$TMPDIR/sc2-adjutant-broker-<hash>.sock` instead. Its output goes to `<cacheDir>/editor-broker.log`. The first capture that finds no broker answering starts one, detached, with the same machine config. It exits after 10 minutes with no job and no client connected. The Editor stays open between jobs; only the capture copies open and close.
83
85
  - **Capture copies.** The broker writes each job's copy under its own name, `<map> <label>-<job id>.SC2Map` in `<cacheDir>/capture/maps/`, so a stale copy is never taken for a new one. It removes the copy once the tour is done, and keeps it when the tour stopped early, to open and debug.
@@ -100,9 +102,14 @@ For text with nothing to say ("...", say), `say` succeeds but writes no audio, a
100
102
  ## Watching the game
101
103
 
102
104
  - **Find the window.** Find the game window with `CGWindowListCopyWindowInfo` and `kCGWindowListOptionAll`, owner "SC2", name "StarCraft II", and capture it with `screencapture -l <id>`. With the Editor's Test Document window mode set to Windowed, a covered window still captures; a minimized one doesn't.
105
+ - **Recording video of the window.** A tour that asks for `video` gets the game window recorded with ScreenCaptureKit (a small Swift helper, `record`), as HEVC at the request's `quality` (`AVVideoQualityKey`, 0.9 when it gives none; at 0.5 particles smeared away) with a list of when each stop and mark happened. It logs the window's pixels per point, and warns when it has to scale the picture up to the asked width: a 1280-point window on a display of 1 pixel a point has only 1280 pixels. Like `screencapture -l`, it records a covered window. But it gets **no frames while the game window fills the display**: macOS then sends the window straight to the display without compositing it. On 2026-11-23, a 1728×1084 game window on a 1728×1117 display gave 27 s of nothing, then steady frames from 1.5 s after it was resized to 1280×800, with no gaps. Whole-screen recording (`screencapture -v`) still works then, but it films whatever is in front. So the host resizes the window to 1280×748 (a 16:9 picture under the title bar) before it starts recording, through System Events. The game ignores that until it has loaded, so the host tries once a second, and the effect tour waits 12 s before its first effect when recording. The game writes its window size to `Variables.txt` (`windowwidth`, `windowheight`, in pixels) when it quits, but setting a smaller size there while the game was closed didn't change the next Test Document window: it opened at full size and wrote that size back.
103
106
  - **Loading screens.** Some maps wait on a "press space" loading screen: send Space. Pressing it takes focus, so do it only after a long wait.
104
107
  - **Getting data out.** A map can report to the outside through `BankSave`. The bank appears at once at `~/Library/Application Support/Blizzard/StarCraft II/Banks/<name>.SC2Bank`. The `Text.txt` log stays empty. The ClientAPI on port 6119 also works ([game-testing.md §5](../../../docs/reference/game-testing.md#5-the-clientapi-http-server)).
105
108
 
109
+ ## The Banks folder
110
+
111
+ `game.banksDir` names the game's banks folder, `~/Library/Application Support/Blizzard/StarCraft II/Banks/`. The Editor Broker copies it into `<cacheDir>/banks/` before a Test Document and, once the test game quits, records which banks it added, changed or removed. `test_mission` and `bank_changes` report them, and `bank_changes` rolls back or keeps each bank when the author says so ([game-testing.md](../../../docs/reference/game-testing.md#what-a-test-game-does-to-the-banks-folder-issue-54)).
112
+
106
113
  ## Rendering a mod's models
107
114
 
108
115
  `model.render` draws with WhiteoutFlakes (`whiteoutflakes.ts`, through the plugin SDK's viewer driver, core's `src/host/whiteoutflakes.ts`, which the Windows Host Adapter shares). It reads a model and its textures straight from the game's CASC storage. Given a model by its file path, it reads each texture the model names (`Assets/Textures/x.dds`) from that path under the model's folder first, and never looks in a mod package. So when a request's `packages` hold the model (ADR-0017), the adapter copies the `.m3` into its work folder and renders the copy. Beside the copy it links just the textures the model names: it reads each material layer's image path from the `.m3`, and links that path to the file in the newest package that holds it. It also links a texture kept beside the model in its package beside the copy, where the viewer looks next. Textures the packages lack still come from the game. A render costs a few links however large the packages are, since it never links a package's other files (an asset mod can hold thousands, mostly sounds). A model whose textures can't be read, one that isn't an MD34, is copied with none. Nothing is written into the packages. Without the staging, a mod model whose textures are only in the mod draws untextured: flat grey or white, and the viewer logs nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@team-antioch/sc2-adjutant-host-macos",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The macOS Host Adapter Plugin for sc2-adjutant: opens the Galaxy Editor, runs Test Document, captures tours and the screen, speaks placeholder voices and renders game models.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -4,5 +4,5 @@
4
4
  "pluginApi": 2,
5
5
  "roles": ["host-adapter"],
6
6
  "entry": "./dist/index.js",
7
- "contributions": { "capabilities": ["editor.open", "editor.checkClosed", "editor.refresh","editor.testDocument", "editor.save", "editor.captureTour", "editor.closeCaptureCopies", "game.running", "screen.capture", "tts.speak", "model.render", "model.rendererKey", "model.export", "model.exportGltf"] }
7
+ "contributions": { "capabilities": ["editor.open", "editor.checkClosed", "editor.refresh","editor.testDocument", "editor.save", "editor.captureTour", "editor.closeCaptureCopies", "game.running", "game.banksDir", "game.list", "game.quit", "game.logsFolder", "screen.capture", "tts.speak", "model.render", "model.rendererKey", "model.export", "model.exportGltf"] }
8
8
  }