@snappedly-tools/shipyard 0.4.2 → 0.4.4-staging.35704989542

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/dist/main.js CHANGED
@@ -1,20 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import { CODEX_MODELS, withFriendlyErrors } from './chunk-VDHZO5PP.js';
3
- import { buildImage, removeImage } from './chunk-OCJKONZ7.js';
4
- import { SANDBOX_REPO_DIR, Display, InitError, PRODUCT_NAME, CONFIG_DIR, CLI_NAME, ClackDisplay, defaultImageName, ExecHostError, LOCKS_DIR, ConfigDirError } from './chunk-2GT3OPO5.js';
2
+ import { CODEX_MODELS, withFriendlyErrors, resolveEnv } from './chunk-EGYPJMLV.js';
3
+ import { buildImage, removeImage, validateExistingRepositoryRunner, RunnerLifecycleError, RUNNER_INSTALL_METADATA, removeRepositoryRunner, RUNNER_CONTROLLER_LOCK, recoverRepositoryRunner, REPOSITORY_RUNNER_OWNER_ENV, removeOwnedRepositoryRunnerContainers, RUNNER_WORK_DIR } from './chunk-KL3ASRFR.js';
4
+ import { SANDBOX_REPO_DIR, Display, InitError, ACTIVATION_LABEL, PRODUCT_NAME, CONFIG_DIR, CLI_NAME, ClackDisplay, RUNNER_DIR, RUNNER_SANDBOX_MASK_DIR, assertProtectedDirectoryIdentities, repositoryRunnerEnvironment, defaultImageName, ExecHostError, LOCKS_DIR, ConfigDirError } from './chunk-FDYOTN55.js';
5
5
  import './chunk-KMGNFXKN.js';
6
6
  import './chunk-WA7QPAXO.js';
7
- import { NodeContext, NodeRuntime } from '@effect/platform-node';
7
+ import { NodeContext, NodeRuntime, NodeFileSystem } from '@effect/platform-node';
8
8
  import { Effect, Layer, Option } from 'effect';
9
9
  import { Options, Command } from '@effect/cli';
10
10
  import * as clack from '@clack/prompts';
11
- import { execSync, spawn, execFileSync } from 'child_process';
12
- import { existsSync, statSync } from 'fs';
11
+ import { execFile, execSync, spawn, execFileSync } from 'child_process';
12
+ import { existsSync, constants, statSync } from 'fs';
13
13
  import { join, resolve, dirname } from 'path';
14
- import { styleText } from 'util';
14
+ import { promisify, styleText } from 'util';
15
15
  import { FileSystem } from '@effect/platform';
16
16
  import { fileURLToPath } from 'url';
17
- import { homedir } from 'os';
17
+ import { hostname, homedir } from 'os';
18
+ import { createHash } from 'crypto';
19
+ import { chmod, lstat, realpath, rm, mkdir, writeFile, readFile, access } from 'fs/promises';
18
20
  import 'module';
19
21
 
20
22
  var pathExists = (path) => Effect.gen(function* () {
@@ -262,7 +264,7 @@ var ISSUE_TRACKER_REGISTRY = [
262
264
  name: "github-issues",
263
265
  label: "GitHub Issues",
264
266
  templateArgs: {
265
- LIST_TASKS_COMMAND: `gh issue list --state open --label ${PRODUCT_NAME} --limit 100 --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'`,
267
+ LIST_TASKS_COMMAND: `gh issue list --state open --label ${ACTIVATION_LABEL} --limit 100 --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'`,
266
268
  VIEW_TASK_COMMAND: "gh issue view <ID>",
267
269
  CLOSE_TASK_COMMAND: `gh issue close <ID> --comment "Completed by ${PRODUCT_NAME}"`,
268
270
  ISSUE_TRACKER_TOOLS: GITHUB_CLI_TOOLS
@@ -270,7 +272,10 @@ var ISSUE_TRACKER_REGISTRY = [
270
272
  envExample: `# GitHub personal access token \u2014 the agent uses it to read and manage GitHub Issues
271
273
  # Create a fine-grained token: https://github.com/settings/personal-access-tokens/new
272
274
  # Required repository permissions: Issues (Read and write) and Metadata (Read)
273
- GH_TOKEN=`
275
+ # Or leave blank and run: GH_TOKEN="$(gh auth token)" npx shipyard run
276
+ GH_TOKEN=
277
+ # GitHub repository (owner/repository)
278
+ GH_REPO=`
274
279
  }
275
280
  ];
276
281
  var listIssueTrackers = () => ISSUE_TRACKER_REGISTRY;
@@ -286,69 +291,17 @@ var SANDBOX_PROVIDER_REGISTRY = [
286
291
  ];
287
292
  var listSandboxProviders = () => SANDBOX_PROVIDER_REGISTRY;
288
293
  var getSandboxProvider = (name) => SANDBOX_PROVIDER_REGISTRY.find((p) => p.name === name);
289
- function getNextStepsLines(template, mainFilename, agent, packageManager, codexAuth = "api-key") {
290
- const getAuthLines = (step) => {
291
- if (agent.name === "codex") {
292
- if (codexAuth === "chatgpt") {
293
- return [
294
- `${step}. Use your ChatGPT subscription with Codex: run \`codex login\` on the host and make sure \`~/.codex/auth.json\` exists`,
295
- ' If it does not exist, set `cli_auth_credentials_store = "file"` in `~/.codex/config.toml`, then run the login again',
296
- " Shipyard mounts this credential read-only; use this mode only with trusted repositories.",
297
- ` If subscription auth does not work, rerun init with \`--codex-auth api-key\` and set \`OPENAI_API_KEY\` in ${CONFIG_DIR}/.env instead.`,
298
- ` Also set any issue-tracker variables shown in ${CONFIG_DIR}/.env.example.`
299
- ];
300
- }
301
- return [
302
- `${step}. Use your ChatGPT subscription with Codex (recommended): run \`codex login\` on the host, then initialize with \`--codex-auth chatgpt\` so Shipyard can mount \`~/.codex/auth.json\` read-only`,
303
- ` If subscription auth does not work, use API-key billing instead by setting \`OPENAI_API_KEY\` in ${CONFIG_DIR}/.env (see ${CONFIG_DIR}/.env.example).`,
304
- ` Also set any issue-tracker variables shown in ${CONFIG_DIR}/.env.example.`
305
- ];
306
- }
307
- if (agent.name === "claude-code") {
308
- return [
309
- `${step}. Use your Claude subscription (recommended): run \`claude setup-token\` on the host and paste the result into \`CLAUDE_CODE_OAUTH_TOKEN\` in ${CONFIG_DIR}/.env`,
310
- ` If subscription auth does not work, use API-key billing instead by uncommenting \`ANTHROPIC_API_KEY\` in ${CONFIG_DIR}/.env and setting it to your key.`,
311
- ` Also set any issue-tracker variables shown in ${CONFIG_DIR}/.env.example.`
312
- ];
313
- }
314
- return [
315
- `${step}. Set the required env vars in ${CONFIG_DIR}/.env (see ${CONFIG_DIR}/.env.example)`
316
- ];
317
- };
318
- if (template === "blank") {
319
- const lines = ["Next steps:", ...getAuthLines(1)];
320
- lines.push(
321
- `2. Read and customize ${CONFIG_DIR}/prompt.md to describe what you want the agent to do`,
322
- `3. Customize ${CONFIG_DIR}/${mainFilename} \u2014 it uses the JS API (\`run()\`) to control how the agent runs`,
323
- `4. Run \`npx ${CLI_NAME} run\` to build the sandbox image and start the agent`
324
- );
325
- return lines;
326
- } else {
327
- const hasReviewer = template.includes("review");
328
- const usesPlanSchema = getTemplateDependencies(template).includes("zod");
329
- let step = 1;
330
- const lines = ["Next steps:", ...getAuthLines(step++)];
331
- lines.push(
332
- `${step++}. Templates use \`copyToWorktree: ["node_modules"]\` to copy your host node_modules into the sandbox for fast startup \u2014 the \`npm install\` in the onSandboxReady hook is a safety net for platform-specific binaries. Adjust both if you use a different package manager`
333
- );
334
- if (usesPlanSchema) {
335
- lines.push(
336
- `${step++}. Install a schema validator for the planner's \`<plan>\` output \u2014 the template uses Zod (\`${addDependencyCommand(packageManager, "zod")}\`), but Valibot, ArkType, or any Standard Schema library works (https://standardschema.dev)`
337
- );
338
- }
339
- lines.push(
340
- `${step++}. Read and customize the prompt files in ${CONFIG_DIR}/ \u2014 they shape what the agent does`
341
- );
342
- if (hasReviewer) {
343
- lines.push(
344
- `${step++}. Customize ${CONFIG_DIR}/CODING_STANDARDS.md with your project's standards \u2014 the reviewer agent loads it during review`
345
- );
346
- }
347
- lines.push(
348
- `${step++}. Run \`npx ${CLI_NAME} run\` to build the sandbox image and start the workflow`
349
- );
350
- return lines;
351
- }
294
+ function getNextStepsLines() {
295
+ return [
296
+ "Next steps:",
297
+ "1. Create your env file:",
298
+ ` cp ${CONFIG_DIR}/.env.example ${CONFIG_DIR}/.env`,
299
+ " Fill in the values you need.",
300
+ "2. If using a model subscription, sign in. For Codex:",
301
+ ` codex --config 'cli_auth_credentials_store="file"' login`,
302
+ " test -f ~/.codex/auth.json",
303
+ `3. Start with \`npx ${CLI_NAME} runner start\` (if installed) or \`npx ${CLI_NAME} run\``
304
+ ];
352
305
  }
353
306
  function getTemplatesDir() {
354
307
  const thisFile = fileURLToPath(import.meta.url);
@@ -425,27 +378,6 @@ var rewriteMainTs = (configDir, agent, model, sandboxProvider, mainFilename, cod
425
378
  content = content.replace(/\bdocker\b/g, sandboxProvider.name);
426
379
  yield* fs.writeFileString(mainTsPath, content).pipe(Effect.mapError((e) => new Error(e.message)));
427
380
  });
428
- var rewritePromptFiles = (configDir) => Effect.gen(function* () {
429
- const fs = yield* FileSystem.FileSystem;
430
- const files = yield* fs.readDirectory(configDir).pipe(Effect.mapError((e) => new Error(e.message)));
431
- const mdFiles = files.filter((f) => f.endsWith(".md"));
432
- yield* Effect.all(
433
- mdFiles.map(
434
- (f) => Effect.gen(function* () {
435
- const filePath = join(configDir, f);
436
- const content = yield* fs.readFileString(filePath).pipe(Effect.mapError((e) => new Error(e.message)));
437
- const updated = content.replace(
438
- new RegExp(` --label ${PRODUCT_NAME}`, "g"),
439
- ""
440
- );
441
- if (updated !== content) {
442
- yield* fs.writeFileString(filePath, updated).pipe(Effect.mapError((e) => new Error(e.message)));
443
- }
444
- })
445
- ),
446
- { concurrency: "unbounded" }
447
- );
448
- });
449
381
  var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
450
382
  ".md",
451
383
  ".txt",
@@ -504,7 +436,6 @@ var scaffold = (repoDir, options) => Effect.gen(function* () {
504
436
  agent,
505
437
  model,
506
438
  templateName = "blank",
507
- createLabel = true,
508
439
  issueTracker = ISSUE_TRACKER_REGISTRY[0],
509
440
  // default: github-issues
510
441
  sandboxProvider = SANDBOX_PROVIDER_REGISTRY[0],
@@ -552,9 +483,6 @@ var scaffold = (repoDir, options) => Effect.gen(function* () {
552
483
  codexAuth
553
484
  );
554
485
  yield* substituteTemplateArgs(configDir, issueTracker);
555
- if (!createLabel) {
556
- yield* rewritePromptFiles(configDir);
557
- }
558
486
  return { mainFilename };
559
487
  });
560
488
  var resolveCodexAuthMode = async (options) => {
@@ -633,7 +561,1636 @@ var ensureCodexChatGptAuth = (options) => {
633
561
  });
634
562
  }
635
563
  };
636
- var VERSION = "0.4.2" ;
564
+ var REPOSITORY_RUNNER_WORKFLOW_PATH = ".github/workflows/shipyard-wake.yml";
565
+ var REPOSITORY_RUNNER_WAKE_EXECUTABLE = "shipyard-wake";
566
+ var REPOSITORY_RUNNER_WORKFLOW = `name: Shipyard wake-up
567
+
568
+ on:
569
+ issues:
570
+ types: [labeled]
571
+ workflow_dispatch:
572
+
573
+ permissions: {}
574
+
575
+ jobs:
576
+ filter:
577
+ name: Check wake eligibility
578
+ runs-on: ubuntu-latest
579
+ outputs:
580
+ wake: \${{ steps.filter.outputs.wake }}
581
+ steps:
582
+ - name: Match the wake-up trigger
583
+ id: filter
584
+ shell: bash
585
+ env:
586
+ EVENT_NAME: \${{ github.event_name }}
587
+ LABEL_NAME: \${{ github.event.label.name }}
588
+ run: |
589
+ if [[ "$EVENT_NAME" == "workflow_dispatch" ]] || [[ "$EVENT_NAME" == "issues" && "$LABEL_NAME" == "shipyard" ]]; then
590
+ echo "wake=true" >> "$GITHUB_OUTPUT"
591
+ else
592
+ echo "wake=false" >> "$GITHUB_OUTPUT"
593
+ fi
594
+
595
+ wake:
596
+ name: Deliver wake-up
597
+ needs: filter
598
+ if: needs.filter.outputs.wake == 'true'
599
+ runs-on: [self-hosted, macOS, shipyard]
600
+ steps:
601
+ - name: Signal the foreground repository runner
602
+ shell: bash
603
+ run: '"$RUNNER_TEMP/../../shipyard-wake"'
604
+ `;
605
+ var REPOSITORY_RUNNER_WAKE_SCRIPT = `#!/bin/bash
606
+ set -euo pipefail
607
+
608
+ runner_dir="$(cd -- "$(dirname -- "$0")" && pwd)"
609
+ lock_path="$runner_dir/.shipyard-controller.lock"
610
+
611
+ if [[ ! -r "$lock_path" ]]; then
612
+ echo "::error::The Shipyard repository runner controller is unavailable. Start it with npx shipyard runner start."
613
+ exit 1
614
+ fi
615
+
616
+ controller_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p' "$lock_path" | head -n 1)"
617
+ controller_started_at="$(sed -n 's/.*"processStartedAt"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p' "$lock_path" | head -n 1)"
618
+ if [[ -z "$controller_pid" ]] || [[ -z "$controller_started_at" ]]; then
619
+ echo "::error::The Shipyard repository runner controller is unavailable. Start it with npx shipyard runner start."
620
+ exit 1
621
+ fi
622
+ current_started_at="$(ps -p "$controller_pid" -o lstart= 2>/dev/null | awk '{$1=$1; print}' || true)"
623
+ if [[ "$current_started_at" != "$controller_started_at" ]] || ! kill -0 "$controller_pid" 2>/dev/null; then
624
+ echo "::error::The Shipyard repository runner controller is unavailable. Start it with npx shipyard runner start."
625
+ exit 1
626
+ fi
627
+
628
+ if ! kill -USR1 "$controller_pid"; then
629
+ echo "::error::The Shipyard repository runner controller could not receive the wake-up."
630
+ exit 1
631
+ fi
632
+
633
+ echo "Wake-up delivered to the Shipyard repository runner controller."
634
+ `;
635
+ var RepositoryRunnerWakeError = class extends Error {
636
+ name = "RepositoryRunnerWakeError";
637
+ };
638
+ var workflowCollisionMessage = () => `Refusing to overwrite the differing workflow at ${REPOSITORY_RUNNER_WORKFLOW_PATH}. Replace it with the required Shipyard wake-only workflow, then retry:
639
+
640
+ ${REPOSITORY_RUNNER_WORKFLOW}`;
641
+ var assertRepositoryRunnerWorkflowCanBeInstalled = async (repoDir, adapters) => {
642
+ const workflowPath = join(repoDir, REPOSITORY_RUNNER_WORKFLOW_PATH);
643
+ if (!await adapters.exists(workflowPath)) return;
644
+ if (await adapters.readText(workflowPath) !== REPOSITORY_RUNNER_WORKFLOW) {
645
+ throw new RepositoryRunnerWakeError(workflowCollisionMessage());
646
+ }
647
+ };
648
+ var ensureDirectory = async (path, adapters) => {
649
+ if (!await adapters.exists(path)) await adapters.makeDirectory(path);
650
+ };
651
+ var installRepositoryRunnerWakeFiles = async (options, adapters) => {
652
+ await assertRepositoryRunnerWorkflowCanBeInstalled(options.repoDir, adapters);
653
+ const githubDir = join(options.repoDir, ".github");
654
+ const workflowsDir = join(githubDir, "workflows");
655
+ await ensureDirectory(githubDir, adapters);
656
+ await ensureDirectory(workflowsDir, adapters);
657
+ await adapters.writeText(
658
+ join(options.repoDir, REPOSITORY_RUNNER_WORKFLOW_PATH),
659
+ REPOSITORY_RUNNER_WORKFLOW
660
+ );
661
+ const wakeExecutable = join(
662
+ options.runnerDir,
663
+ REPOSITORY_RUNNER_WAKE_EXECUTABLE
664
+ );
665
+ await adapters.writeText(wakeExecutable, REPOSITORY_RUNNER_WAKE_SCRIPT);
666
+ await adapters.chmod(wakeExecutable, 448);
667
+ };
668
+ var requirePublishedRepositoryRunnerWorkflow = async (options, adapter) => {
669
+ let defaultBranch;
670
+ try {
671
+ const result = await adapter.run(
672
+ "gh",
673
+ ["api", `repos/${options.repository}`, "--jq", ".default_branch"],
674
+ { cwd: options.repoDir, env: options.environment }
675
+ );
676
+ defaultBranch = result.stdout.trim();
677
+ if (defaultBranch.length === 0) throw new Error("empty default branch");
678
+ } catch (error) {
679
+ throw new RepositoryRunnerWakeError(
680
+ `Could not determine the GitHub default branch for ${options.repository}: ${error instanceof Error ? error.message : String(error)}`
681
+ );
682
+ }
683
+ let publishedWorkflow;
684
+ try {
685
+ const result = await adapter.run(
686
+ "gh",
687
+ [
688
+ "api",
689
+ "--method",
690
+ "GET",
691
+ "-H",
692
+ "Accept: application/vnd.github.raw+json",
693
+ `repos/${options.repository}/contents/${REPOSITORY_RUNNER_WORKFLOW_PATH}?ref=${encodeURIComponent(defaultBranch)}`
694
+ ],
695
+ { cwd: options.repoDir, env: options.environment }
696
+ );
697
+ publishedWorkflow = result.stdout;
698
+ } catch (error) {
699
+ throw new RepositoryRunnerWakeError(
700
+ `The Shipyard wake workflow is not active for ${options.repository}. Commit and push ${REPOSITORY_RUNNER_WORKFLOW_PATH} to the default branch (${defaultBranch}), then start the runner again. GitHub reported: ${error instanceof Error ? error.message : String(error)}`
701
+ );
702
+ }
703
+ if (publishedWorkflow !== REPOSITORY_RUNNER_WORKFLOW) {
704
+ throw new RepositoryRunnerWakeError(
705
+ `The Shipyard wake workflow on the default branch (${defaultBranch}) does not match the required workflow. Update and push ${REPOSITORY_RUNNER_WORKFLOW_PATH}, then start the runner again.
706
+
707
+ ${REPOSITORY_RUNNER_WORKFLOW}`
708
+ );
709
+ }
710
+ };
711
+ var createRepositoryRunnerWakeSubscription = (subscribe = (listener) => {
712
+ process.on("SIGUSR1", listener);
713
+ return () => process.removeListener("SIGUSR1", listener);
714
+ }) => {
715
+ let pending = false;
716
+ let closed = false;
717
+ let resolveNext;
718
+ const unsubscribe = subscribe(() => {
719
+ if (closed || pending) return;
720
+ pending = true;
721
+ resolveNext?.();
722
+ resolveNext = void 0;
723
+ });
724
+ return {
725
+ next: async () => {
726
+ if (closed) return;
727
+ if (!pending) {
728
+ await new Promise((resolve2) => {
729
+ resolveNext = resolve2;
730
+ });
731
+ }
732
+ pending = false;
733
+ },
734
+ close: () => {
735
+ if (closed) return;
736
+ closed = true;
737
+ unsubscribe();
738
+ resolveNext?.();
739
+ resolveNext = void 0;
740
+ }
741
+ };
742
+ };
743
+
744
+ // src/RepositoryRunner.ts
745
+ var execFileAsync = promisify(execFile);
746
+ var RUNNER_ARCHIVE = "runner.tgz";
747
+ var RELEASES_API = "https://api.github.com/repos/actions/runner/releases/latest";
748
+ var RunnerInstallError = class extends Error {
749
+ name = "RunnerInstallError";
750
+ };
751
+ var defaultAdapters = {
752
+ platform: () => process.platform,
753
+ arch: () => process.arch,
754
+ hostname,
755
+ environment: () => process.env,
756
+ exists: async (path) => {
757
+ try {
758
+ await access(path, constants.F_OK);
759
+ return true;
760
+ } catch {
761
+ return false;
762
+ }
763
+ },
764
+ readText: (path) => readFile(path, "utf8"),
765
+ writeText: (path, content) => writeFile(path, content, { mode: 384 }),
766
+ writeBytes: (path, content) => writeFile(path, content, { mode: 384 }),
767
+ makeDirectory: (path) => mkdir(path, { recursive: false, mode: 448 }),
768
+ remove: (path) => rm(path, { recursive: true, force: true }),
769
+ chmod,
770
+ commandExists: async (command) => {
771
+ try {
772
+ await execFileAsync("which", [command]);
773
+ return true;
774
+ } catch {
775
+ return false;
776
+ }
777
+ },
778
+ inspectDirectory: async (path) => {
779
+ const [stat, resolved] = await Promise.all([lstat(path), realpath(path)]);
780
+ return {
781
+ realPath: resolved,
782
+ directory: stat.isDirectory(),
783
+ symbolicLink: stat.isSymbolicLink()
784
+ };
785
+ },
786
+ fetchJson: async (url) => {
787
+ const response = await fetch(url, {
788
+ headers: {
789
+ Accept: "application/vnd.github+json",
790
+ "User-Agent": "shipyard-runner-installer",
791
+ "X-GitHub-Api-Version": "2022-11-28"
792
+ }
793
+ });
794
+ if (!response.ok) {
795
+ throw new Error(`GitHub returned HTTP ${response.status}`);
796
+ }
797
+ return response.json();
798
+ },
799
+ fetchBytes: async (url) => {
800
+ const response = await fetch(url, {
801
+ headers: { "User-Agent": "shipyard-runner-installer" }
802
+ });
803
+ if (!response.ok) {
804
+ throw new Error(`GitHub returned HTTP ${response.status}`);
805
+ }
806
+ return new Uint8Array(await response.arrayBuffer());
807
+ },
808
+ run: async (command, args, options) => {
809
+ const result = await execFileAsync(command, [...args], {
810
+ cwd: options.cwd,
811
+ env: options.env,
812
+ maxBuffer: 10 * 1024 * 1024
813
+ });
814
+ return { stdout: result.stdout, stderr: result.stderr };
815
+ }
816
+ };
817
+ var parseGitHubRepository = (remote) => {
818
+ const trimmed = remote.trim();
819
+ const sshMatch = trimmed.match(
820
+ /^(?:git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?$/
821
+ );
822
+ const httpsMatch = trimmed.match(
823
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/
824
+ );
825
+ const match = sshMatch ?? httpsMatch;
826
+ if (!match) {
827
+ throw new RunnerInstallError(
828
+ "The origin remote must be a GitHub.com repository (github.com/owner/repository). GitHub Enterprise and other hosts are not supported yet."
829
+ );
830
+ }
831
+ return { owner: match[1], repository: match[2] };
832
+ };
833
+ var normalizeNamePart = (value) => {
834
+ const normalized = value.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-+/g, "-");
835
+ return normalized || "unknown";
836
+ };
837
+ var requireCommand = async (adapters, command, purpose) => {
838
+ if (!await adapters.commandExists(command)) {
839
+ throw new RunnerInstallError(
840
+ `Missing required command \`${command}\` (${purpose}). Install it and retry.`
841
+ );
842
+ }
843
+ };
844
+ var asRelease = (value) => {
845
+ if (typeof value !== "object" || value === null) {
846
+ throw new RunnerInstallError(
847
+ "GitHub returned invalid runner release metadata."
848
+ );
849
+ }
850
+ const release = value;
851
+ if (typeof release.tag_name !== "string" || !Array.isArray(release.assets)) {
852
+ throw new RunnerInstallError(
853
+ "GitHub returned invalid runner release metadata."
854
+ );
855
+ }
856
+ return release;
857
+ };
858
+ var selectArm64Asset = (release) => {
859
+ const asset = release.assets.find(
860
+ (candidate) => /^actions-runner-osx-arm64-[\d.]+\.tar\.gz$/.test(candidate.name)
861
+ );
862
+ if (!asset || !asset.browser_download_url.startsWith(
863
+ "https://github.com/actions/runner/releases/download/"
864
+ ) || !/^sha256:[a-f0-9]{64}$/i.test(asset.digest)) {
865
+ throw new RunnerInstallError(
866
+ "The latest official GitHub Actions runner release has no verifiable macOS ARM64 archive."
867
+ );
868
+ }
869
+ return asset;
870
+ };
871
+ var appendRunnerIgnores = async (gitignorePath, adapters) => {
872
+ const current = await adapters.exists(gitignorePath) ? await adapters.readText(gitignorePath) : "";
873
+ const lines = new Set(current.split(/\r?\n/));
874
+ const additions = [`${RUNNER_DIR}/`, `${RUNNER_SANDBOX_MASK_DIR}/`].filter(
875
+ (line) => !lines.has(line)
876
+ );
877
+ if (additions.length === 0) return;
878
+ const prefix = current.length === 0 || current.endsWith("\n") ? current : `${current}
879
+ `;
880
+ await adapters.writeText(gitignorePath, `${prefix}${additions.join("\n")}
881
+ `);
882
+ };
883
+ var commandFailure = (purpose, error) => new RunnerInstallError(
884
+ `${purpose} failed: ${error instanceof Error ? error.message : String(error)}`
885
+ );
886
+ var reportProgress = (options, current, total, message) => options.onProgress?.({ current, total, message });
887
+ var installRepositoryRunner = async (options, adapters = defaultAdapters) => {
888
+ if (adapters.platform() !== "darwin" || adapters.arch() !== "arm64") {
889
+ throw new RunnerInstallError(
890
+ "Repository runners currently require Apple Silicon macOS (darwin/arm64)."
891
+ );
892
+ }
893
+ const configDir = join(options.repoDir, CONFIG_DIR);
894
+ const runnerDir = join(configDir, RUNNER_DIR);
895
+ const maskDir = join(configDir, RUNNER_SANDBOX_MASK_DIR);
896
+ if (!await adapters.exists(configDir)) {
897
+ throw new RunnerInstallError(
898
+ `No ${CONFIG_DIR}/ found. Run \`shipyard init\` in this repository first.`
899
+ );
900
+ }
901
+ const runnerExists = await adapters.exists(runnerDir);
902
+ const progressTotal = runnerExists ? 3 : 8;
903
+ try {
904
+ await assertRepositoryRunnerWorkflowCanBeInstalled(
905
+ options.repoDir,
906
+ adapters
907
+ );
908
+ } catch (error) {
909
+ throw new RunnerInstallError(
910
+ error instanceof Error ? error.message : String(error)
911
+ );
912
+ }
913
+ await requireCommand(adapters, "git", "reading the repository remote");
914
+ if (!runnerExists) {
915
+ await requireCommand(adapters, "tar", "extracting the runner archive");
916
+ }
917
+ await requireCommand(adapters, "gh", "checking repository runner uniqueness");
918
+ const hostEnv = adapters.environment();
919
+ const gitRemote = await adapters.run("git", ["remote", "get-url", "origin"], {
920
+ cwd: options.repoDir,
921
+ env: hostEnv
922
+ }).catch((error) => {
923
+ throw commandFailure("Reading the origin remote", error);
924
+ });
925
+ const identity = parseGitHubRepository(gitRemote.stdout);
926
+ const repository = `${identity.owner}/${identity.repository}`;
927
+ const repoUrl = `https://github.com/${repository}`;
928
+ const runnerName = `shipyard-${normalizeNamePart(identity.repository)}-${normalizeNamePart(adapters.hostname())}`;
929
+ await adapters.run("gh", ["auth", "status", "--hostname", "github.com"], {
930
+ cwd: options.repoDir,
931
+ env: hostEnv
932
+ }).catch((error) => {
933
+ throw commandFailure(
934
+ "GitHub CLI authentication (repository administration is required)",
935
+ error
936
+ );
937
+ });
938
+ reportProgress(
939
+ options,
940
+ 1,
941
+ progressTotal,
942
+ "Validated repository and GitHub access"
943
+ );
944
+ if (runnerExists) {
945
+ let metadata;
946
+ try {
947
+ metadata = await validateExistingRepositoryRunner(
948
+ {
949
+ repoDir: options.repoDir,
950
+ runnerDir,
951
+ maskDir,
952
+ repository,
953
+ runnerName
954
+ },
955
+ adapters
956
+ );
957
+ } catch (error) {
958
+ throw new RunnerInstallError(
959
+ error instanceof RunnerLifecycleError ? error.message : `Validating the existing repository runner failed: ${error instanceof Error ? error.message : String(error)}`
960
+ );
961
+ }
962
+ await appendRunnerIgnores(join(configDir, ".gitignore"), adapters);
963
+ await adapters.chmod(runnerDir, 448);
964
+ await adapters.chmod(maskDir, 448);
965
+ await assertProtectedDirectoryIdentities(
966
+ runnerDir,
967
+ maskDir,
968
+ adapters.inspectDirectory
969
+ ).catch((error) => {
970
+ throw commandFailure("Validating protected runner directories", error);
971
+ });
972
+ reportProgress(options, 2, progressTotal, "Validated existing runner");
973
+ try {
974
+ await installRepositoryRunnerWakeFiles(
975
+ { repoDir: options.repoDir, runnerDir },
976
+ adapters
977
+ );
978
+ } catch (error) {
979
+ throw new RunnerInstallError(
980
+ `The existing runner is valid, but its wake-up files could not be refreshed: ${error instanceof Error ? error.message : String(error)}`
981
+ );
982
+ }
983
+ reportProgress(options, 3, progressTotal, "Refreshed wake-up workflow");
984
+ return {
985
+ name: metadata.name,
986
+ repository: metadata.repository,
987
+ version: metadata.version,
988
+ runnerDir
989
+ };
990
+ }
991
+ const existing = await adapters.run(
992
+ "gh",
993
+ [
994
+ "api",
995
+ "--paginate",
996
+ `repos/${repository}/actions/runners`,
997
+ "--jq",
998
+ `.runners[] | select(any(.labels[]; .name == "${ACTIVATION_LABEL}")) | .name`
999
+ ],
1000
+ { cwd: options.repoDir, env: hostEnv }
1001
+ ).catch((error) => {
1002
+ throw commandFailure(
1003
+ "Checking existing repository runners (repository administration is required)",
1004
+ error
1005
+ );
1006
+ });
1007
+ if (existing.stdout.trim().length > 0) {
1008
+ throw new RunnerInstallError(
1009
+ `A repository runner labeled \`${ACTIVATION_LABEL}\` is already registered for ${repository}. Remove it before installing another.`
1010
+ );
1011
+ }
1012
+ reportProgress(
1013
+ options,
1014
+ 2,
1015
+ progressTotal,
1016
+ "Checked for conflicting repository runners"
1017
+ );
1018
+ let registrationToken = options.registrationToken;
1019
+ if (!registrationToken) {
1020
+ const tokenResult = await adapters.run(
1021
+ "gh",
1022
+ [
1023
+ "api",
1024
+ "--method",
1025
+ "POST",
1026
+ `repos/${repository}/actions/runners/registration-token`
1027
+ ],
1028
+ { cwd: options.repoDir, env: hostEnv }
1029
+ ).catch((error) => {
1030
+ throw commandFailure(
1031
+ "Requesting a one-time runner registration token (repository administration is required)",
1032
+ error
1033
+ );
1034
+ });
1035
+ try {
1036
+ const parsed = JSON.parse(tokenResult.stdout);
1037
+ if (typeof parsed.token !== "string" || parsed.token.length === 0) {
1038
+ throw new Error("response did not contain a token");
1039
+ }
1040
+ registrationToken = parsed.token;
1041
+ } catch (error) {
1042
+ throw commandFailure("Reading the one-time registration token", error);
1043
+ }
1044
+ }
1045
+ reportProgress(
1046
+ options,
1047
+ 3,
1048
+ progressTotal,
1049
+ "Prepared runner registration token"
1050
+ );
1051
+ let release;
1052
+ try {
1053
+ release = asRelease(await adapters.fetchJson(RELEASES_API));
1054
+ } catch (error) {
1055
+ if (error instanceof RunnerInstallError) throw error;
1056
+ throw commandFailure("Fetching official runner release metadata", error);
1057
+ }
1058
+ const asset = selectArm64Asset(release);
1059
+ const version = release.tag_name.replace(/^v/, "");
1060
+ let archive;
1061
+ try {
1062
+ archive = await adapters.fetchBytes(asset.browser_download_url);
1063
+ } catch (error) {
1064
+ throw commandFailure("Downloading the official runner archive", error);
1065
+ }
1066
+ const actualDigest = createHash("sha256").update(archive).digest("hex");
1067
+ const expectedDigest = asset.digest.slice("sha256:".length).toLowerCase();
1068
+ if (actualDigest !== expectedDigest) {
1069
+ throw new RunnerInstallError(
1070
+ `Runner archive digest mismatch: expected ${expectedDigest}, received ${actualDigest}. Nothing was installed.`
1071
+ );
1072
+ }
1073
+ reportProgress(
1074
+ options,
1075
+ 4,
1076
+ progressTotal,
1077
+ "Downloaded and verified official runner archive"
1078
+ );
1079
+ await appendRunnerIgnores(join(configDir, ".gitignore"), adapters);
1080
+ await adapters.makeDirectory(runnerDir).catch((error) => {
1081
+ throw commandFailure("Creating the protected runner directory", error);
1082
+ });
1083
+ if (!await adapters.exists(maskDir)) {
1084
+ await adapters.makeDirectory(maskDir);
1085
+ }
1086
+ await assertProtectedDirectoryIdentities(
1087
+ runnerDir,
1088
+ maskDir,
1089
+ adapters.inspectDirectory
1090
+ ).catch((error) => {
1091
+ throw commandFailure("Validating protected runner directories", error);
1092
+ });
1093
+ await adapters.chmod(runnerDir, 448);
1094
+ await adapters.chmod(maskDir, 448);
1095
+ reportProgress(
1096
+ options,
1097
+ 5,
1098
+ progressTotal,
1099
+ "Prepared protected runner directories"
1100
+ );
1101
+ const archivePath = join(runnerDir, RUNNER_ARCHIVE);
1102
+ await adapters.writeBytes(archivePath, archive);
1103
+ try {
1104
+ await adapters.run("tar", ["-xzf", archivePath, "--directory", runnerDir], {
1105
+ cwd: options.repoDir,
1106
+ env: repositoryRunnerEnvironment(hostEnv)
1107
+ });
1108
+ } catch (error) {
1109
+ await adapters.remove(runnerDir);
1110
+ throw commandFailure("Extracting the verified runner archive", error);
1111
+ } finally {
1112
+ await adapters.remove(archivePath);
1113
+ }
1114
+ reportProgress(options, 6, progressTotal, "Extracted runner archive");
1115
+ try {
1116
+ await adapters.run(
1117
+ "./config.sh",
1118
+ [
1119
+ "--url",
1120
+ repoUrl,
1121
+ "--token",
1122
+ registrationToken,
1123
+ "--name",
1124
+ runnerName,
1125
+ "--labels",
1126
+ ACTIVATION_LABEL,
1127
+ "--work",
1128
+ "_work",
1129
+ "--unattended"
1130
+ ],
1131
+ { cwd: runnerDir, env: repositoryRunnerEnvironment(hostEnv) }
1132
+ );
1133
+ } catch {
1134
+ const cleanup = await Promise.allSettled([
1135
+ adapters.remove(runnerDir),
1136
+ adapters.remove(maskDir)
1137
+ ]);
1138
+ const cleanupSucceeded = cleanup.every(
1139
+ (result) => result.status === "fulfilled"
1140
+ );
1141
+ throw new RunnerInstallError(
1142
+ cleanupSucceeded ? `Registering ${runnerName} failed. Partial local runner files were removed so installation can be retried. Check GitHub Settings > Actions > Runners for an orphan registration; the one-time token was not stored.` : `Registering ${runnerName} failed and partial local runner files could not be fully removed. Remove only ${runnerDir} and ${maskDir}, check GitHub Settings > Actions > Runners for an orphan registration, then retry. The one-time token was not stored.`
1143
+ );
1144
+ }
1145
+ reportProgress(options, 7, progressTotal, "Registered runner with GitHub");
1146
+ await adapters.writeText(
1147
+ join(runnerDir, RUNNER_INSTALL_METADATA),
1148
+ `${JSON.stringify(
1149
+ {
1150
+ schemaVersion: 1,
1151
+ repository,
1152
+ repositoryUrl: repoUrl,
1153
+ name: runnerName,
1154
+ label: ACTIVATION_LABEL,
1155
+ version
1156
+ },
1157
+ null,
1158
+ 2
1159
+ )}
1160
+ `
1161
+ );
1162
+ try {
1163
+ await installRepositoryRunnerWakeFiles(
1164
+ { repoDir: options.repoDir, runnerDir },
1165
+ adapters
1166
+ );
1167
+ } catch (error) {
1168
+ throw new RunnerInstallError(
1169
+ `The runner was registered, but its wake-up files could not be installed. Runner files were retained at ${runnerDir}; fix the error and retry: ${error instanceof Error ? error.message : String(error)}`
1170
+ );
1171
+ }
1172
+ reportProgress(options, 8, progressTotal, "Installed wake-up workflow");
1173
+ return { name: runnerName, repository, version, runnerDir };
1174
+ };
1175
+
1176
+ // src/InitRepositoryRunner.ts
1177
+ var initializeRepositoryRunner = async (options) => {
1178
+ let shouldInstall = options.requested;
1179
+ if (shouldInstall === void 0) {
1180
+ shouldInstall = options.interactive ? await options.confirm({
1181
+ message: "Install a foreground repository runner for labelled GitHub issues?",
1182
+ initialValue: true
1183
+ }) : false;
1184
+ }
1185
+ if (!shouldInstall) return { status: "declined" };
1186
+ try {
1187
+ return { status: "installed", result: await options.install() };
1188
+ } catch (error) {
1189
+ return {
1190
+ status: "failed",
1191
+ message: error instanceof Error ? error.message : String(error)
1192
+ };
1193
+ }
1194
+ };
1195
+ var repositoryRunnerNextSteps = () => [
1196
+ `First, commit and push ${REPOSITORY_RUNNER_WORKFLOW_PATH} to the repository's default branch`,
1197
+ `Keep the foreground controller open with \`npx ${CLI_NAME} runner start\``,
1198
+ `Inspect it from another terminal with \`npx ${CLI_NAME} runner status\``,
1199
+ `Stop it with \`npx ${CLI_NAME} runner stop\``,
1200
+ `Unregister and delete its protected files with \`npx ${CLI_NAME} runner remove\``
1201
+ ];
1202
+ var execFileAsync2 = promisify(execFile);
1203
+ var CONTROLLER_STATE = ".shipyard-state.json";
1204
+ var LAST_FAILURE = ".shipyard-last-failure.json";
1205
+ var RunnerControlError = class extends Error {
1206
+ name = "RunnerControlError";
1207
+ };
1208
+ var retainedFailures = /* @__PURE__ */ new WeakSet();
1209
+ var spawnForegroundChild = (command, args, options) => {
1210
+ const child = spawn(command, [...args], {
1211
+ cwd: options.cwd,
1212
+ env: options.env,
1213
+ stdio: "inherit",
1214
+ detached: true
1215
+ });
1216
+ const pid = child.pid;
1217
+ if (pid === void 0) {
1218
+ throw new RunnerControlError(`Could not start ${command}.`);
1219
+ }
1220
+ const result = new Promise((resolve2, reject) => {
1221
+ child.once("error", reject);
1222
+ child.once("close", (code, signal) => resolve2({ code, signal }));
1223
+ });
1224
+ return {
1225
+ pid,
1226
+ wait: () => result,
1227
+ terminate: (signal) => {
1228
+ try {
1229
+ process.kill(-pid, signal);
1230
+ } catch {
1231
+ child.kill(signal);
1232
+ }
1233
+ }
1234
+ };
1235
+ };
1236
+ var registerRunnerShutdown = (handler) => {
1237
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
1238
+ let handling = false;
1239
+ const listeners = /* @__PURE__ */ new Map();
1240
+ const unregister = () => {
1241
+ for (const [signal, listener] of listeners) {
1242
+ process.removeListener(signal, listener);
1243
+ }
1244
+ listeners.clear();
1245
+ };
1246
+ for (const signal of signals) {
1247
+ const listener = () => {
1248
+ if (handling) return;
1249
+ handling = true;
1250
+ void handler().finally(() => {
1251
+ unregister();
1252
+ process.exit(
1253
+ signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129
1254
+ );
1255
+ });
1256
+ };
1257
+ listeners.set(signal, listener);
1258
+ process.once(signal, listener);
1259
+ }
1260
+ return unregister;
1261
+ };
1262
+ var defaultAdapters2 = {
1263
+ platform: () => process.platform,
1264
+ arch: () => process.arch,
1265
+ environment: () => process.env,
1266
+ currentPid: () => process.pid,
1267
+ processIdentity: async (pid) => {
1268
+ try {
1269
+ const result = await execFileAsync2("ps", [
1270
+ "-p",
1271
+ String(pid),
1272
+ "-o",
1273
+ "lstart="
1274
+ ]);
1275
+ const identity = result.stdout.trim().replace(/\s+/g, " ");
1276
+ return identity.length > 0 ? identity : void 0;
1277
+ } catch {
1278
+ return void 0;
1279
+ }
1280
+ },
1281
+ exists: async (path) => {
1282
+ try {
1283
+ await access(path, constants.F_OK);
1284
+ return true;
1285
+ } catch {
1286
+ return false;
1287
+ }
1288
+ },
1289
+ inspectDirectory: async (path) => {
1290
+ const [stat, resolved] = await Promise.all([lstat(path), realpath(path)]);
1291
+ return {
1292
+ realPath: resolved,
1293
+ directory: stat.isDirectory(),
1294
+ symbolicLink: stat.isSymbolicLink()
1295
+ };
1296
+ },
1297
+ readText: (path) => readFile(path, "utf8"),
1298
+ writeText: (path, content) => writeFile(path, content, { mode: 384 }),
1299
+ writeExclusive: (path, content) => writeFile(path, content, { encoding: "utf8", mode: 384, flag: "wx" }),
1300
+ remove: (path) => rm(path, { force: true }),
1301
+ makeDirectory: async (path) => {
1302
+ await mkdir(path, { recursive: true, mode: 448 });
1303
+ },
1304
+ removeTree: (path) => rm(path, { recursive: true, force: true }),
1305
+ commandExists: async (command) => {
1306
+ try {
1307
+ await execFileAsync2("which", [command]);
1308
+ return true;
1309
+ } catch {
1310
+ return false;
1311
+ }
1312
+ },
1313
+ resolveEnvironment: (repoDir) => Effect.runPromise(
1314
+ resolveEnv(repoDir).pipe(Effect.provide(NodeFileSystem.layer))
1315
+ ),
1316
+ run: async (command, args, options) => {
1317
+ const result = await execFileAsync2(command, [...args], {
1318
+ cwd: options.cwd,
1319
+ env: options.env,
1320
+ maxBuffer: 10 * 1024 * 1024
1321
+ });
1322
+ return { stdout: result.stdout, stderr: result.stderr };
1323
+ },
1324
+ spawn: spawnForegroundChild,
1325
+ isProcessRunning: (pid) => {
1326
+ try {
1327
+ process.kill(pid, 0);
1328
+ return true;
1329
+ } catch {
1330
+ return false;
1331
+ }
1332
+ },
1333
+ signalProcess: (pid, signal) => process.kill(pid, signal),
1334
+ onShutdown: registerRunnerShutdown,
1335
+ pause: (milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)),
1336
+ now: () => /* @__PURE__ */ new Date(),
1337
+ report: (message) => console.log(message)
1338
+ };
1339
+ var readJson = async (path, adapters) => {
1340
+ if (!await adapters.exists(path)) return void 0;
1341
+ try {
1342
+ return JSON.parse(await adapters.readText(path));
1343
+ } catch (error) {
1344
+ throw new RunnerControlError(
1345
+ `Could not read repository runner state at ${path}: ${error instanceof Error ? error.message : String(error)}`
1346
+ );
1347
+ }
1348
+ };
1349
+ var writeJson = (path, value, adapters) => adapters.writeText(path, `${JSON.stringify(value, null, 2)}
1350
+ `);
1351
+ var controlFailure = (purpose, error) => error instanceof RunnerControlError ? error : new RunnerControlError(
1352
+ `${purpose} failed: ${error instanceof Error ? error.message : String(error)}`
1353
+ );
1354
+ var runCommand = async (adapters, purpose, command, args, options) => {
1355
+ try {
1356
+ return await adapters.run(command, args, options);
1357
+ } catch (error) {
1358
+ throw controlFailure(purpose, error);
1359
+ }
1360
+ };
1361
+ var requireCommand2 = async (adapters, command, purpose) => {
1362
+ if (!await adapters.commandExists(command)) {
1363
+ throw new RunnerControlError(
1364
+ `Missing required command \`${command}\` (${purpose}). Install it and retry.`
1365
+ );
1366
+ }
1367
+ };
1368
+ var requireRunnerContext = async (repoDir, adapters) => {
1369
+ if (adapters.platform() !== "darwin" || adapters.arch() !== "arm64") {
1370
+ throw new RunnerControlError(
1371
+ "Repository runners currently require Apple Silicon macOS (darwin/arm64)."
1372
+ );
1373
+ }
1374
+ const configDir = join(repoDir, CONFIG_DIR);
1375
+ const runnerDir = join(configDir, RUNNER_DIR);
1376
+ const maskDir = join(configDir, RUNNER_SANDBOX_MASK_DIR);
1377
+ if (!await adapters.exists(configDir)) {
1378
+ throw new RunnerControlError(
1379
+ `No ${CONFIG_DIR}/ found. Run \`shipyard init\` in this repository first.`
1380
+ );
1381
+ }
1382
+ if (!await adapters.exists(runnerDir)) {
1383
+ throw new RunnerControlError(
1384
+ `No repository runner is installed at ${runnerDir}. Run \`shipyard runner install\` first.`
1385
+ );
1386
+ }
1387
+ if (adapters.inspectDirectory) {
1388
+ const runnerIdentity = await adapters.inspectDirectory(runnerDir).catch((error) => {
1389
+ throw controlFailure(
1390
+ "Inspecting the protected runner directory",
1391
+ error
1392
+ );
1393
+ });
1394
+ if (!runnerIdentity.directory || runnerIdentity.symbolicLink) {
1395
+ throw new RunnerControlError(
1396
+ `The protected repository runner path must be a real directory: ${runnerDir}`
1397
+ );
1398
+ }
1399
+ }
1400
+ const metadata = await readJson(
1401
+ join(runnerDir, RUNNER_INSTALL_METADATA),
1402
+ adapters
1403
+ );
1404
+ if (metadata?.schemaVersion !== 1 || typeof metadata.repository !== "string" || typeof metadata.name !== "string" || metadata.label !== ACTIVATION_LABEL) {
1405
+ throw new RunnerControlError(
1406
+ "The repository runner installation metadata is missing or invalid. Reinstall the repository runner."
1407
+ );
1408
+ }
1409
+ if (!await adapters.exists(join(runnerDir, "run.sh"))) {
1410
+ throw new RunnerControlError(
1411
+ "The official repository runner executable is missing. Reinstall the repository runner."
1412
+ );
1413
+ }
1414
+ for (const [command, purpose] of [
1415
+ ["git", "reading the repository remote"],
1416
+ ["npx", "running the local Shipyard package"],
1417
+ ["docker", "checking the Docker runtime"],
1418
+ ["gh", "checking GitHub access"]
1419
+ ]) {
1420
+ await requireCommand2(adapters, command, purpose);
1421
+ }
1422
+ const hostEnvironment = adapters.environment();
1423
+ const resolvedEnvironment = await adapters.resolveEnvironment(repoDir).catch((error) => {
1424
+ throw controlFailure("Resolving repository credentials", error);
1425
+ });
1426
+ const runtimeEnvironment = {
1427
+ ...hostEnvironment,
1428
+ ...resolvedEnvironment,
1429
+ [REPOSITORY_RUNNER_OWNER_ENV]: metadata.repository
1430
+ };
1431
+ const remote = await runCommand(
1432
+ adapters,
1433
+ "Reading the origin remote",
1434
+ "git",
1435
+ ["remote", "get-url", "origin"],
1436
+ { cwd: repoDir, env: runtimeEnvironment }
1437
+ );
1438
+ let identity;
1439
+ try {
1440
+ identity = parseGitHubRepository(remote.stdout);
1441
+ } catch (error) {
1442
+ throw new RunnerControlError(
1443
+ error instanceof Error ? error.message : String(error)
1444
+ );
1445
+ }
1446
+ const repository = `${identity.owner}/${identity.repository}`;
1447
+ if (repository !== metadata.repository) {
1448
+ throw new RunnerControlError(
1449
+ `The installed repository runner belongs to ${metadata.repository}, but this repository origin is ${repository}. Reinstall it for this repository.`
1450
+ );
1451
+ }
1452
+ await runCommand(
1453
+ adapters,
1454
+ "Checking the local Shipyard package",
1455
+ "npx",
1456
+ ["--no-install", "shipyard", "--version"],
1457
+ { cwd: repoDir, env: runtimeEnvironment }
1458
+ );
1459
+ await runCommand(
1460
+ adapters,
1461
+ "Checking Docker availability",
1462
+ "docker",
1463
+ ["info"],
1464
+ { cwd: repoDir, env: runtimeEnvironment }
1465
+ );
1466
+ await runCommand(
1467
+ adapters,
1468
+ "Checking GitHub authentication",
1469
+ "gh",
1470
+ ["auth", "status", "--hostname", "github.com"],
1471
+ { cwd: repoDir, env: runtimeEnvironment }
1472
+ );
1473
+ const label = await runCommand(
1474
+ adapters,
1475
+ "Checking the activation label",
1476
+ "gh",
1477
+ [
1478
+ "label",
1479
+ "list",
1480
+ "--repo",
1481
+ repository,
1482
+ "--json",
1483
+ "name",
1484
+ "--jq",
1485
+ `.[] | select(.name == "${ACTIVATION_LABEL}") | .name`
1486
+ ],
1487
+ { cwd: repoDir, env: runtimeEnvironment }
1488
+ );
1489
+ if (label.stdout.trim() !== ACTIVATION_LABEL) {
1490
+ await runCommand(
1491
+ adapters,
1492
+ "Creating the activation label",
1493
+ "gh",
1494
+ [
1495
+ "label",
1496
+ "create",
1497
+ ACTIVATION_LABEL,
1498
+ "--repo",
1499
+ repository,
1500
+ "--color",
1501
+ "1D76DB",
1502
+ "--description",
1503
+ "Tasks available to the Shipyard repository runner",
1504
+ "--force"
1505
+ ],
1506
+ { cwd: repoDir, env: runtimeEnvironment }
1507
+ );
1508
+ }
1509
+ await requirePublishedRepositoryRunnerWorkflow(
1510
+ {
1511
+ repoDir,
1512
+ repository,
1513
+ environment: runtimeEnvironment
1514
+ },
1515
+ adapters
1516
+ ).catch((error) => {
1517
+ throw new RunnerControlError(
1518
+ error instanceof Error ? error.message : String(error)
1519
+ );
1520
+ });
1521
+ return {
1522
+ runnerDir,
1523
+ maskDir,
1524
+ repository,
1525
+ metadata,
1526
+ hostEnvironment,
1527
+ runtimeEnvironment
1528
+ };
1529
+ };
1530
+ var childFailure = (command, result) => new RunnerControlError(
1531
+ result.signal === null ? `${command} exited with code ${result.code ?? "unknown"}.` : `${command} was terminated by ${result.signal}.`
1532
+ );
1533
+ var stopChildBounded = async (child, pause) => {
1534
+ child.terminate("SIGTERM");
1535
+ const stopped = await Promise.race([
1536
+ child.wait().then(() => true),
1537
+ pause(5e3).then(() => false)
1538
+ ]);
1539
+ if (stopped) return;
1540
+ child.terminate("SIGKILL");
1541
+ const killed = await Promise.race([
1542
+ child.wait().then(() => true),
1543
+ pause(1e3).then(() => false)
1544
+ ]);
1545
+ if (!killed) {
1546
+ throw new RunnerControlError(
1547
+ `Process ${child.pid} did not exit after SIGKILL.`
1548
+ );
1549
+ }
1550
+ };
1551
+ var lockOwnsProcess = async (lock, adapters) => lock !== void 0 && Number.isInteger(lock.pid) && typeof lock.processStartedAt === "string" && lock.processStartedAt.length > 0 && adapters.isProcessRunning(lock.pid) && await adapters.processIdentity(lock.pid) === lock.processStartedAt;
1552
+ var bestEffort = async (operation) => {
1553
+ try {
1554
+ await operation();
1555
+ } catch {
1556
+ }
1557
+ };
1558
+ var startRepositoryRunnerManaged = async (options, adapters = defaultAdapters2) => {
1559
+ const context = await requireRunnerContext(options.repoDir, adapters);
1560
+ const lifecycleAdapters = {
1561
+ environment: adapters.environment,
1562
+ exists: adapters.exists,
1563
+ readText: adapters.readText,
1564
+ makeDirectory: adapters.makeDirectory,
1565
+ inspectDirectory: adapters.inspectDirectory,
1566
+ remove: adapters.removeTree,
1567
+ run: adapters.run,
1568
+ isProcessRunning: adapters.isProcessRunning,
1569
+ signalProcess: adapters.signalProcess,
1570
+ pause: adapters.pause,
1571
+ processIdentity: adapters.processIdentity
1572
+ };
1573
+ await recoverRepositoryRunner(
1574
+ {
1575
+ repoDir: options.repoDir,
1576
+ runnerDir: context.runnerDir,
1577
+ maskDir: context.maskDir,
1578
+ metadata: context.metadata,
1579
+ runnerEnvironment: repositoryRunnerEnvironment(context.hostEnvironment),
1580
+ dockerEnvironment: context.runtimeEnvironment
1581
+ },
1582
+ lifecycleAdapters
1583
+ ).catch((error) => {
1584
+ throw new RunnerControlError(
1585
+ error instanceof RunnerLifecycleError ? error.message : `Repository runner recovery failed: ${error instanceof Error ? error.message : String(error)}`
1586
+ );
1587
+ });
1588
+ const lockPath = join(context.runnerDir, RUNNER_CONTROLLER_LOCK);
1589
+ const statePath = join(context.runnerDir, CONTROLLER_STATE);
1590
+ const failurePath = join(context.runnerDir, LAST_FAILURE);
1591
+ const existingLock = await readJson(lockPath, adapters);
1592
+ if (await lockOwnsProcess(existingLock, adapters)) {
1593
+ throw new RunnerControlError(
1594
+ `The repository runner is already running with process ${existingLock.pid}.`
1595
+ );
1596
+ }
1597
+ if (existingLock) {
1598
+ throw new RunnerControlError(
1599
+ "The repository runner has stale process state. Run it again after recovery or remove the stale installation."
1600
+ );
1601
+ }
1602
+ const controllerPid = adapters.currentPid();
1603
+ const processStartedAt = await adapters.processIdentity(controllerPid);
1604
+ if (!processStartedAt) {
1605
+ throw new RunnerControlError(
1606
+ "Could not establish the repository runner controller process identity."
1607
+ );
1608
+ }
1609
+ const lock = {
1610
+ schemaVersion: 1,
1611
+ pid: controllerPid,
1612
+ repository: context.repository,
1613
+ processStartedAt
1614
+ };
1615
+ try {
1616
+ await adapters.writeExclusive(lockPath, `${JSON.stringify(lock)}
1617
+ `);
1618
+ } catch (error) {
1619
+ throw controlFailure("Claiming the repository runner process", error);
1620
+ }
1621
+ let listenerChild;
1622
+ let shipyardChild;
1623
+ let stopping = false;
1624
+ let lastWake;
1625
+ let shutdownPromise;
1626
+ let primaryFailure;
1627
+ const saveState = async (state, lastOutcome) => {
1628
+ await writeJson(
1629
+ statePath,
1630
+ {
1631
+ schemaVersion: 1,
1632
+ repository: context.repository,
1633
+ state,
1634
+ lastOutcome,
1635
+ ...lastWake ? { lastWake } : {}
1636
+ },
1637
+ adapters
1638
+ );
1639
+ adapters.report(`[repository runner] ${state}: ${lastOutcome}`);
1640
+ };
1641
+ const removeTransientWork = () => adapters.removeTree(join(context.runnerDir, RUNNER_WORK_DIR));
1642
+ const removeOwnedContainers = () => removeOwnedRepositoryRunnerContainers(
1643
+ {
1644
+ repoDir: options.repoDir,
1645
+ repository: context.repository,
1646
+ environment: context.runtimeEnvironment
1647
+ },
1648
+ lifecycleAdapters
1649
+ );
1650
+ const attemptCleanup = async (failures, purpose, operation) => {
1651
+ try {
1652
+ await operation();
1653
+ } catch (error) {
1654
+ const message = `${purpose} failed: ${error instanceof Error ? error.message : String(error)}`;
1655
+ failures.push(message);
1656
+ adapters.report(`[repository runner] cleanup error: ${message}`);
1657
+ }
1658
+ };
1659
+ const persistCleanupFailures = async (failures) => {
1660
+ if (failures.length === 0) return;
1661
+ const cleanupMessage = `Repository runner cleanup failed: ${failures.join("; ")}`;
1662
+ const message = primaryFailure ? `${primaryFailure.message} ${cleanupMessage}` : cleanupMessage;
1663
+ await bestEffort(
1664
+ () => writeJson(
1665
+ failurePath,
1666
+ {
1667
+ schemaVersion: 1,
1668
+ repository: context.repository,
1669
+ message,
1670
+ recordedAt: adapters.now().toISOString()
1671
+ },
1672
+ adapters
1673
+ ).then(() => {
1674
+ if (primaryFailure) retainedFailures.add(primaryFailure);
1675
+ })
1676
+ );
1677
+ await bestEffort(() => saveState("stopped", cleanupMessage));
1678
+ };
1679
+ const shutdown = () => {
1680
+ if (shutdownPromise) return shutdownPromise;
1681
+ shutdownPromise = (async () => {
1682
+ stopping = true;
1683
+ const failures = [];
1684
+ const children = [listenerChild, shipyardChild].filter(
1685
+ (child) => child !== void 0
1686
+ );
1687
+ listenerChild = void 0;
1688
+ shipyardChild = void 0;
1689
+ await Promise.all(
1690
+ children.map(
1691
+ (child) => attemptCleanup(
1692
+ failures,
1693
+ `Stopping process ${child.pid}`,
1694
+ () => stopChildBounded(child, adapters.pause)
1695
+ )
1696
+ )
1697
+ );
1698
+ await attemptCleanup(
1699
+ failures,
1700
+ "Removing repository-runner containers",
1701
+ removeOwnedContainers
1702
+ );
1703
+ await attemptCleanup(
1704
+ failures,
1705
+ "Removing transient runner work",
1706
+ removeTransientWork
1707
+ );
1708
+ await attemptCleanup(
1709
+ failures,
1710
+ "Removing controller lock",
1711
+ () => adapters.remove(lockPath)
1712
+ );
1713
+ if (failures.length === 0) {
1714
+ try {
1715
+ await saveState("stopped", "Stopped by signal");
1716
+ } catch (error) {
1717
+ const message = `Persisting stopped state failed: ${error instanceof Error ? error.message : String(error)}`;
1718
+ failures.push(message);
1719
+ adapters.report(`[repository runner] cleanup error: ${message}`);
1720
+ }
1721
+ }
1722
+ await persistCleanupFailures(failures);
1723
+ })();
1724
+ return shutdownPromise;
1725
+ };
1726
+ const unregisterShutdown = adapters.onShutdown(shutdown);
1727
+ const wakeSubscription = createRepositoryRunnerWakeSubscription(
1728
+ adapters.onWake
1729
+ );
1730
+ let initialWorkFound = false;
1731
+ try {
1732
+ const listEligibleIssueNumbers = async () => {
1733
+ const issues = await runCommand(
1734
+ adapters,
1735
+ "Checking for eligible GitHub issues",
1736
+ "gh",
1737
+ [
1738
+ "api",
1739
+ "--method",
1740
+ "GET",
1741
+ "--paginate",
1742
+ `repos/${context.repository}/issues`,
1743
+ "-f",
1744
+ "state=open",
1745
+ "-f",
1746
+ `labels=${ACTIVATION_LABEL}`,
1747
+ "-f",
1748
+ "per_page=100",
1749
+ "--jq",
1750
+ ".[] | select(.pull_request == null) | .number"
1751
+ ],
1752
+ { cwd: options.repoDir, env: context.runtimeEnvironment }
1753
+ );
1754
+ return [...new Set(issues.stdout.split(/\s+/).filter(Boolean))].sort(
1755
+ (left, right) => Number(left) - Number(right)
1756
+ );
1757
+ };
1758
+ const sameIssueNumbers = (left, right) => left.length === right.length && left.every((issue, index) => issue === right[index]);
1759
+ const processEligibleWork = async () => {
1760
+ let issueNumbers = await listEligibleIssueNumbers();
1761
+ const workFound = issueNumbers.length > 0;
1762
+ while (!stopping && issueNumbers.length > 0) {
1763
+ await saveState("processing", "Shipyard is processing eligible issues");
1764
+ shipyardChild = adapters.spawn("npx", ["shipyard", "run"], {
1765
+ cwd: options.repoDir,
1766
+ env: context.runtimeEnvironment
1767
+ });
1768
+ const runResult = await shipyardChild.wait();
1769
+ shipyardChild = void 0;
1770
+ if (stopping) {
1771
+ await shutdownPromise;
1772
+ return workFound;
1773
+ }
1774
+ if (runResult.code !== 0) {
1775
+ const failure = childFailure("npx shipyard run", runResult);
1776
+ await writeJson(
1777
+ failurePath,
1778
+ {
1779
+ schemaVersion: 1,
1780
+ repository: context.repository,
1781
+ message: failure.message,
1782
+ recordedAt: adapters.now().toISOString()
1783
+ },
1784
+ adapters
1785
+ );
1786
+ await saveState("stopped", failure.message);
1787
+ throw failure;
1788
+ }
1789
+ const nextIssueNumbers = await listEligibleIssueNumbers();
1790
+ if (nextIssueNumbers.length === 0) {
1791
+ await saveState("idle", "Shipyard completed; no eligible issues");
1792
+ break;
1793
+ }
1794
+ if (sameIssueNumbers(issueNumbers, nextIssueNumbers)) {
1795
+ await saveState(
1796
+ "stalled",
1797
+ "Shipyard made no progress; eligible issues are unchanged"
1798
+ );
1799
+ break;
1800
+ }
1801
+ issueNumbers = nextIssueNumbers;
1802
+ }
1803
+ return workFound;
1804
+ };
1805
+ lastWake = {
1806
+ source: "startup",
1807
+ recordedAt: adapters.now().toISOString()
1808
+ };
1809
+ initialWorkFound = await processEligibleWork();
1810
+ if (stopping) {
1811
+ await shutdownPromise;
1812
+ return { repository: context.repository, initialWorkFound };
1813
+ }
1814
+ if (!initialWorkFound) {
1815
+ await saveState("idle", "No eligible issues; listening");
1816
+ }
1817
+ listenerChild = adapters.spawn("./run.sh", [], {
1818
+ cwd: context.runnerDir,
1819
+ env: repositoryRunnerEnvironment(context.hostEnvironment)
1820
+ });
1821
+ const listenerExit = listenerChild.wait().then((result) => ({
1822
+ type: "listener",
1823
+ result
1824
+ }));
1825
+ let listenerResult;
1826
+ while (!listenerResult && !stopping) {
1827
+ const event = await Promise.race([
1828
+ listenerExit,
1829
+ wakeSubscription.next().then(() => ({ type: "wake" }))
1830
+ ]);
1831
+ if (event.type === "listener") {
1832
+ listenerResult = event.result;
1833
+ listenerChild = void 0;
1834
+ break;
1835
+ }
1836
+ if (stopping) break;
1837
+ lastWake = {
1838
+ source: "signal",
1839
+ recordedAt: adapters.now().toISOString()
1840
+ };
1841
+ const workFound = await processEligibleWork();
1842
+ if (!workFound && !stopping) {
1843
+ await saveState("idle", "Wake-up delivered; no eligible issues");
1844
+ }
1845
+ }
1846
+ if (stopping) {
1847
+ await shutdownPromise;
1848
+ return { repository: context.repository, initialWorkFound };
1849
+ }
1850
+ if (!listenerResult) {
1851
+ throw new RunnerControlError(
1852
+ "The repository runner listener stopped without an exit result."
1853
+ );
1854
+ }
1855
+ if (listenerResult.code !== 0) {
1856
+ const failure = childFailure(
1857
+ "Repository runner listener",
1858
+ listenerResult
1859
+ );
1860
+ await writeJson(
1861
+ failurePath,
1862
+ {
1863
+ schemaVersion: 1,
1864
+ repository: context.repository,
1865
+ message: failure.message,
1866
+ recordedAt: adapters.now().toISOString()
1867
+ },
1868
+ adapters
1869
+ );
1870
+ await saveState("stopped", failure.message);
1871
+ throw failure;
1872
+ }
1873
+ await saveState("stopped", "Repository runner listener exited");
1874
+ return { repository: context.repository, initialWorkFound };
1875
+ } catch (error) {
1876
+ const failure = controlFailure("Repository runner controller", error);
1877
+ primaryFailure = failure;
1878
+ await bestEffort(
1879
+ () => writeJson(
1880
+ failurePath,
1881
+ {
1882
+ schemaVersion: 1,
1883
+ repository: context.repository,
1884
+ message: failure.message,
1885
+ recordedAt: adapters.now().toISOString()
1886
+ },
1887
+ adapters
1888
+ ).then(() => retainedFailures.add(failure))
1889
+ );
1890
+ await bestEffort(() => saveState("stopped", failure.message));
1891
+ throw failure;
1892
+ } finally {
1893
+ wakeSubscription.close();
1894
+ unregisterShutdown();
1895
+ if (shutdownPromise) {
1896
+ await shutdownPromise;
1897
+ } else {
1898
+ const failures = [];
1899
+ if (listenerChild) {
1900
+ await attemptCleanup(
1901
+ failures,
1902
+ `Stopping process ${listenerChild.pid}`,
1903
+ () => stopChildBounded(listenerChild, adapters.pause)
1904
+ );
1905
+ }
1906
+ if (shipyardChild) {
1907
+ await attemptCleanup(
1908
+ failures,
1909
+ `Stopping process ${shipyardChild.pid}`,
1910
+ () => stopChildBounded(shipyardChild, adapters.pause)
1911
+ );
1912
+ }
1913
+ await attemptCleanup(
1914
+ failures,
1915
+ "Removing repository-runner containers",
1916
+ removeOwnedContainers
1917
+ );
1918
+ await attemptCleanup(
1919
+ failures,
1920
+ "Removing transient runner work",
1921
+ removeTransientWork
1922
+ );
1923
+ await attemptCleanup(
1924
+ failures,
1925
+ "Removing controller lock",
1926
+ () => adapters.remove(lockPath)
1927
+ );
1928
+ await persistCleanupFailures(failures);
1929
+ }
1930
+ }
1931
+ };
1932
+ var startRepositoryRunner = async (options, adapters = defaultAdapters2) => {
1933
+ try {
1934
+ return await startRepositoryRunnerManaged(options, adapters);
1935
+ } catch (error) {
1936
+ const failure = controlFailure("Repository runner startup", error);
1937
+ if (retainedFailures.has(failure)) throw failure;
1938
+ const runnerDir = join(options.repoDir, CONFIG_DIR, RUNNER_DIR);
1939
+ if (await adapters.exists(runnerDir)) {
1940
+ const metadata = await readJson(
1941
+ join(runnerDir, RUNNER_INSTALL_METADATA),
1942
+ adapters
1943
+ ).catch(() => void 0);
1944
+ const repository = metadata?.repository ?? "unknown";
1945
+ for (const [purpose, operation] of [
1946
+ [
1947
+ "failure diagnostics",
1948
+ () => writeJson(
1949
+ join(runnerDir, LAST_FAILURE),
1950
+ {
1951
+ schemaVersion: 1,
1952
+ repository,
1953
+ message: failure.message,
1954
+ recordedAt: adapters.now().toISOString()
1955
+ },
1956
+ adapters
1957
+ )
1958
+ ],
1959
+ [
1960
+ "stopped state",
1961
+ () => writeJson(
1962
+ join(runnerDir, CONTROLLER_STATE),
1963
+ {
1964
+ schemaVersion: 1,
1965
+ repository,
1966
+ state: "stopped",
1967
+ lastOutcome: failure.message
1968
+ },
1969
+ adapters
1970
+ )
1971
+ ]
1972
+ ]) {
1973
+ try {
1974
+ await operation();
1975
+ } catch (persistenceError) {
1976
+ adapters.report(
1977
+ `[repository runner] Could not persist ${purpose}: ${persistenceError instanceof Error ? persistenceError.message : String(persistenceError)}`
1978
+ );
1979
+ }
1980
+ }
1981
+ }
1982
+ throw failure;
1983
+ }
1984
+ };
1985
+ var getRepositoryRunnerStatus = async (options, adapters = defaultAdapters2) => {
1986
+ const runnerDir = join(options.repoDir, CONFIG_DIR, RUNNER_DIR);
1987
+ const metadata = await readJson(
1988
+ join(runnerDir, RUNNER_INSTALL_METADATA),
1989
+ adapters
1990
+ );
1991
+ if (!metadata) {
1992
+ return {
1993
+ installed: false,
1994
+ running: false,
1995
+ github: "not-installed",
1996
+ state: "not-installed",
1997
+ lastOutcome: "Repository runner is not installed"
1998
+ };
1999
+ }
2000
+ const lock = await readJson(
2001
+ join(runnerDir, RUNNER_CONTROLLER_LOCK),
2002
+ adapters
2003
+ );
2004
+ const state = await readJson(
2005
+ join(runnerDir, CONTROLLER_STATE),
2006
+ adapters
2007
+ );
2008
+ const running = await lockOwnsProcess(lock, adapters);
2009
+ let github = "unreachable";
2010
+ try {
2011
+ const resolvedEnvironment = await adapters.resolveEnvironment(
2012
+ options.repoDir
2013
+ );
2014
+ const response = await adapters.run(
2015
+ "gh",
2016
+ [
2017
+ "api",
2018
+ `repos/${metadata.repository}/actions/runners`,
2019
+ "--jq",
2020
+ `.runners[] | select(.name == "${metadata.name}") | .status`
2021
+ ],
2022
+ {
2023
+ cwd: options.repoDir,
2024
+ env: { ...adapters.environment(), ...resolvedEnvironment }
2025
+ }
2026
+ );
2027
+ github = response.stdout.trim() === "online" ? "online" : "offline";
2028
+ } catch {
2029
+ github = "unreachable";
2030
+ }
2031
+ return {
2032
+ installed: true,
2033
+ running,
2034
+ ...lock ? { pid: lock.pid } : {},
2035
+ github,
2036
+ repository: metadata.repository,
2037
+ state: state?.state ?? (running ? "idle" : "stopped"),
2038
+ lastOutcome: state?.lastOutcome ?? "No repository runner outcome recorded",
2039
+ ...state?.lastWake ? { lastWake: state.lastWake } : {}
2040
+ };
2041
+ };
2042
+ var stopRepositoryRunner = async (options, adapters = defaultAdapters2) => {
2043
+ const lockPath = join(
2044
+ options.repoDir,
2045
+ CONFIG_DIR,
2046
+ RUNNER_DIR,
2047
+ RUNNER_CONTROLLER_LOCK
2048
+ );
2049
+ const lock = await readJson(lockPath, adapters);
2050
+ if (!lock || !Number.isInteger(lock.pid)) {
2051
+ throw new RunnerControlError("The repository runner is not running.");
2052
+ }
2053
+ if (!await lockOwnsProcess(lock, adapters)) {
2054
+ throw new RunnerControlError(
2055
+ `The repository runner process ${lock.pid} no longer matches the recorded controller identity; recovery is required.`
2056
+ );
2057
+ }
2058
+ try {
2059
+ adapters.signalProcess(lock.pid, "SIGTERM");
2060
+ } catch (error) {
2061
+ throw controlFailure("Stopping the repository runner", error);
2062
+ }
2063
+ return { pid: lock.pid };
2064
+ };
2065
+
2066
+ // src/RepositoryRunnerCommands.ts
2067
+ var registrationTokenOption = Options.text("registration-token").pipe(
2068
+ Options.withDescription(
2069
+ "one-time runner registration token (not stored; administrative gh access is still required for uniqueness checks)"
2070
+ ),
2071
+ Options.optional
2072
+ );
2073
+ var installRunnerCommand = Command.make(
2074
+ "install",
2075
+ { registrationToken: registrationTokenOption },
2076
+ ({ registrationToken }) => Effect.gen(function* () {
2077
+ const display = yield* Display;
2078
+ const result = yield* display.progress(
2079
+ "Installing repository runner",
2080
+ (report) => Effect.tryPromise({
2081
+ try: () => installRepositoryRunner({
2082
+ repoDir: process.cwd(),
2083
+ registrationToken: registrationToken._tag === "Some" ? registrationToken.value : void 0,
2084
+ onProgress: report
2085
+ }),
2086
+ catch: (error) => new InitError({
2087
+ message: error instanceof RunnerInstallError ? error.message : `Repository runner installation failed: ${error instanceof Error ? error.message : String(error)}`
2088
+ })
2089
+ })
2090
+ );
2091
+ yield* display.status(
2092
+ `Installed ${result.name} for ${result.repository}.`,
2093
+ "success"
2094
+ );
2095
+ })
2096
+ );
2097
+ var runnerControlEffect = (operation) => Effect.tryPromise({
2098
+ try: operation,
2099
+ catch: (error) => new InitError({
2100
+ message: error instanceof RunnerControlError || error instanceof RunnerLifecycleError ? error.message : `Repository runner operation failed: ${error instanceof Error ? error.message : String(error)}`
2101
+ })
2102
+ });
2103
+ var startRunnerCommand = Command.make(
2104
+ "start",
2105
+ {},
2106
+ () => Effect.gen(function* () {
2107
+ const display = yield* Display;
2108
+ const cwd = process.cwd();
2109
+ yield* display.status(
2110
+ "Starting the repository runner in this terminal...",
2111
+ "info"
2112
+ );
2113
+ const result = yield* runnerControlEffect(
2114
+ () => startRepositoryRunner({ repoDir: cwd })
2115
+ );
2116
+ yield* display.status(
2117
+ result.initialWorkFound ? `Repository runner for ${result.repository} stopped after processing startup work.` : `Repository runner for ${result.repository} stopped.`,
2118
+ "info"
2119
+ );
2120
+ })
2121
+ );
2122
+ var statusRunnerCommand = Command.make(
2123
+ "status",
2124
+ {},
2125
+ () => Effect.gen(function* () {
2126
+ const display = yield* Display;
2127
+ const status = yield* runnerControlEffect(
2128
+ () => getRepositoryRunnerStatus({ repoDir: process.cwd() })
2129
+ );
2130
+ yield* display.summary("Repository runner", {
2131
+ Installed: status.installed ? "yes" : "no",
2132
+ "Local process": status.running ? `running (PID ${status.pid ?? "unknown"})` : "stopped",
2133
+ GitHub: status.github,
2134
+ Repository: status.repository ?? "unknown",
2135
+ State: status.state,
2136
+ "Last outcome": status.lastOutcome,
2137
+ "Last wake": status.lastWake ? `${status.lastWake.source} at ${status.lastWake.recordedAt}` : "none recorded"
2138
+ });
2139
+ })
2140
+ );
2141
+ var stopRunnerCommand = Command.make(
2142
+ "stop",
2143
+ {},
2144
+ () => Effect.gen(function* () {
2145
+ const display = yield* Display;
2146
+ const result = yield* runnerControlEffect(
2147
+ () => stopRepositoryRunner({ repoDir: process.cwd() })
2148
+ );
2149
+ yield* display.status(
2150
+ `Stopping repository runner process ${result.pid}...`,
2151
+ "success"
2152
+ );
2153
+ })
2154
+ );
2155
+ var forceRemoveRunnerOption = Options.boolean("force").pipe(
2156
+ Options.withDescription(
2157
+ "delete local runner files if GitHub unregistration fails"
2158
+ )
2159
+ );
2160
+ var removeRunnerCommand = Command.make(
2161
+ "remove",
2162
+ { force: forceRemoveRunnerOption },
2163
+ ({ force }) => Effect.gen(function* () {
2164
+ const display = yield* Display;
2165
+ const result = yield* runnerControlEffect(
2166
+ () => removeRepositoryRunner({ repoDir: process.cwd(), force })
2167
+ );
2168
+ yield* display.status("Repository runner removed.", "success");
2169
+ if (result.manualCleanup) {
2170
+ yield* display.status(result.manualCleanup, "warn");
2171
+ }
2172
+ })
2173
+ );
2174
+ var runnerCommand = Command.make(
2175
+ "runner",
2176
+ {},
2177
+ () => Effect.gen(function* () {
2178
+ const display = yield* Display;
2179
+ yield* display.status(
2180
+ "Repository runner commands. Use --help to see available subcommands.",
2181
+ "info"
2182
+ );
2183
+ })
2184
+ ).pipe(
2185
+ Command.withSubcommands([
2186
+ installRunnerCommand,
2187
+ startRunnerCommand,
2188
+ statusRunnerCommand,
2189
+ stopRunnerCommand,
2190
+ removeRunnerCommand
2191
+ ])
2192
+ );
2193
+ var VERSION = "0.4.4-staging.35704989542" ;
637
2194
 
638
2195
  // src/cli.ts
639
2196
  var imageNameOption = Options.text("image-name").pipe(
@@ -737,7 +2294,7 @@ var executeEntrypoint = (cwd, entrypoint) => Effect.async((resume, signal) => {
737
2294
  );
738
2295
  });
739
2296
  });
740
- var runCommand = Command.make(
2297
+ var runCommand2 = Command.make(
741
2298
  "run",
742
2299
  {
743
2300
  imageName: imageNameOption,
@@ -810,25 +2367,25 @@ var issueTrackerOption = Options.text("issue-tracker").pipe(
810
2367
  Options.withDescription("Issue tracker to use (github-issues)"),
811
2368
  Options.optional
812
2369
  );
813
- var createLabelOption = Options.choice("create-label", [
2370
+ var buildImageOption = Options.choice("build-image", ["true", "false"]).pipe(
2371
+ Options.withDescription("Whether to build the sandbox image now"),
2372
+ Options.optional
2373
+ );
2374
+ var installTemplateDepsOption = Options.choice("install-template-deps", [
814
2375
  "true",
815
2376
  "false"
816
2377
  ]).pipe(
817
2378
  Options.withDescription(
818
- `Whether to create the "${PRODUCT_NAME}" GitHub label (only meaningful with --issue-tracker github-issues)`
2379
+ "Whether to install the template's host dependencies (e.g. zod for the planner templates)"
819
2380
  ),
820
2381
  Options.optional
821
2382
  );
822
- var buildImageOption = Options.choice("build-image", ["true", "false"]).pipe(
823
- Options.withDescription("Whether to build the sandbox image now"),
824
- Options.optional
825
- );
826
- var installTemplateDepsOption = Options.choice("install-template-deps", [
2383
+ var installRunnerOption = Options.choice("install-runner", [
827
2384
  "true",
828
2385
  "false"
829
2386
  ]).pipe(
830
2387
  Options.withDescription(
831
- "Whether to install the template's host dependencies (e.g. zod for the planner templates)"
2388
+ "Whether to install a foreground repository runner after scaffolding"
832
2389
  ),
833
2390
  Options.optional
834
2391
  );
@@ -843,9 +2400,9 @@ var initCommand = Command.make(
843
2400
  model: initModelOption,
844
2401
  sandbox: sandboxOption,
845
2402
  issueTracker: issueTrackerOption,
846
- createLabel: createLabelOption,
847
2403
  buildImage: buildImageOption,
848
- installTemplateDeps: installTemplateDepsOption
2404
+ installTemplateDeps: installTemplateDepsOption,
2405
+ installRunner: installRunnerOption
849
2406
  },
850
2407
  ({
851
2408
  imageName: imageNameFlag,
@@ -855,9 +2412,9 @@ var initCommand = Command.make(
855
2412
  model: modelFlag,
856
2413
  sandbox: sandboxFlag,
857
2414
  issueTracker: issueTrackerFlag,
858
- createLabel: createLabelFlag,
859
2415
  buildImage: buildImageFlag,
860
- installTemplateDeps: installTemplateDepsFlag
2416
+ installTemplateDeps: installTemplateDepsFlag,
2417
+ installRunner: installRunnerFlag
861
2418
  }) => Effect.gen(function* () {
862
2419
  const d = yield* Display;
863
2420
  const cwd = process.cwd();
@@ -896,11 +2453,11 @@ var initCommand = Command.make(
896
2453
  );
897
2454
  }
898
2455
  }
899
- const createLabelChoice = choiceToTriBool(createLabelFlag);
900
2456
  const buildImageChoice = choiceToTriBool(buildImageFlag);
901
2457
  const installTemplateDepsChoice = choiceToTriBool(
902
2458
  installTemplateDepsFlag
903
2459
  );
2460
+ const installRunnerChoice = choiceToTriBool(installRunnerFlag);
904
2461
  const isInteractive = process.stdin.isTTY === true;
905
2462
  const failIfNonInteractive = (flag) => Effect.fail(
906
2463
  new InitError({
@@ -1079,31 +2636,21 @@ var initCommand = Command.make(
1079
2636
  }
1080
2637
  selectedTemplate = selected;
1081
2638
  }
1082
- let shouldCreateLabel = false;
1083
2639
  if (selectedIssueTracker.name === "github-issues") {
1084
- shouldCreateLabel = yield* resolveConfirmFlag({
1085
- choice: createLabelChoice,
1086
- flag: "--create-label",
1087
- promptMessage: `Create a "${PRODUCT_NAME}" GitHub label? (Templates filter issues by this label)`,
1088
- cancelMessage: "Label selection cancelled."
1089
- });
1090
- if (shouldCreateLabel) {
1091
- yield* Effect.try({
1092
- try: () => execSync(
1093
- `gh label create "${PRODUCT_NAME}" --description "Issues for ${PRODUCT_NAME} to work on" --color "F9A825" 2>/dev/null`,
1094
- { cwd, stdio: "ignore" }
1095
- ),
1096
- catch: () => void 0
1097
- }).pipe(Effect.ignore);
1098
- }
2640
+ yield* Effect.try({
2641
+ try: () => execSync(
2642
+ `gh label create "${ACTIVATION_LABEL}" --description "Issues for ${PRODUCT_NAME} to work on" --color "F9A825" --force 2>/dev/null`,
2643
+ { cwd, stdio: "ignore" }
2644
+ ),
2645
+ catch: () => void 0
2646
+ }).pipe(Effect.ignore);
1099
2647
  }
1100
- const scaffoldResult = yield* d.spinner(
2648
+ yield* d.spinner(
1101
2649
  `Scaffolding ${CONFIG_DIR}/ config directory...`,
1102
2650
  scaffold(cwd, {
1103
2651
  agent: selectedAgent,
1104
2652
  model: selectedModel,
1105
2653
  templateName: selectedTemplate,
1106
- createLabel: shouldCreateLabel,
1107
2654
  issueTracker: selectedIssueTracker,
1108
2655
  sandboxProvider: selectedSandboxProvider,
1109
2656
  codexAuth: selectedCodexAuth
@@ -1157,20 +2704,66 @@ var initCommand = Command.make(
1157
2704
  buildArgs: defaultUidBuildArgs()
1158
2705
  })
1159
2706
  );
1160
- yield* d.status("Init complete! Image built successfully.", "success");
2707
+ yield* d.status("Image built successfully.", "success");
1161
2708
  } else {
1162
2709
  yield* d.status(
1163
- `Init complete! Run \`${CLI_NAME} ${selectedSandboxProvider.cliNamespace} build-image\` to build the ${providerLabel} image later.`,
2710
+ `Run \`${CLI_NAME} ${selectedSandboxProvider.cliNamespace} build-image\` to build the ${providerLabel} image later.`,
2711
+ "info"
2712
+ );
2713
+ }
2714
+ const runnerInit = yield* Effect.tryPromise({
2715
+ try: () => initializeRepositoryRunner({
2716
+ interactive: isInteractive,
2717
+ requested: installRunnerChoice._tag === "Some" ? installRunnerChoice.value : void 0,
2718
+ confirm: async ({ message, initialValue }) => {
2719
+ const confirmed = await clack.confirm({ message, initialValue });
2720
+ if (clack.isCancel(confirmed)) {
2721
+ throw new InitError({
2722
+ message: "Repository-runner installation selection cancelled."
2723
+ });
2724
+ }
2725
+ return confirmed === true;
2726
+ },
2727
+ install: () => Effect.runPromise(
2728
+ d.progress(
2729
+ "Installing repository runner",
2730
+ (report) => Effect.tryPromise({
2731
+ try: () => installRepositoryRunner({
2732
+ repoDir: cwd,
2733
+ onProgress: report
2734
+ }),
2735
+ catch: (error) => new InitError({
2736
+ message: error instanceof RunnerInstallError ? error.message : `Repository runner installation failed: ${error instanceof Error ? error.message : String(error)}`
2737
+ })
2738
+ })
2739
+ )
2740
+ )
2741
+ }),
2742
+ catch: (error) => error instanceof InitError ? error : new InitError({
2743
+ message: `Repository-runner setup failed: ${error instanceof Error ? error.message : String(error)}`
2744
+ })
2745
+ });
2746
+ if (runnerInit.status === "installed") {
2747
+ yield* d.status(
2748
+ `Installed ${runnerInit.result.name} for ${runnerInit.result.repository}.`,
1164
2749
  "success"
1165
2750
  );
2751
+ yield* d.text("Repository runner next steps:");
2752
+ for (const [index, line] of repositoryRunnerNextSteps().entries()) {
2753
+ yield* d.text(styleText("dim", `${index + 1}. ${line}`));
2754
+ }
2755
+ } else if (runnerInit.status === "failed") {
2756
+ yield* d.status(
2757
+ `Shipyard scaffolding is ready, but repository runner installation failed: ${runnerInit.message}`,
2758
+ "warn"
2759
+ );
2760
+ yield* d.status(
2761
+ `Retry from this repository with \`npx ${CLI_NAME} runner install\`.`,
2762
+ "warn"
2763
+ );
1166
2764
  }
1167
- const nextSteps = getNextStepsLines(
1168
- selectedTemplate,
1169
- scaffoldResult.mainFilename,
1170
- selectedAgent,
1171
- packageManager,
1172
- selectedCodexAuth
1173
- );
2765
+ yield* d.status("Init complete!", "success");
2766
+ const nextSteps = getNextStepsLines();
1174
2767
  for (const [i, line] of nextSteps.entries()) {
1175
2768
  yield* d.text(i === 0 ? line : styleText("dim", line));
1176
2769
  }
@@ -1242,7 +2835,12 @@ var rootCommand = Command.make(
1242
2835
  })
1243
2836
  );
1244
2837
  var shipyard = rootCommand.pipe(
1245
- Command.withSubcommands([initCommand, runCommand, dockerCommand])
2838
+ Command.withSubcommands([
2839
+ initCommand,
2840
+ runCommand2,
2841
+ dockerCommand,
2842
+ runnerCommand
2843
+ ])
1246
2844
  );
1247
2845
  var cli = Command.run(shipyard, {
1248
2846
  name: CLI_NAME,