@pulsehub/runner 0.1.4 → 0.1.6

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  Install with Node 20+: `npm install -g @pulsehub/runner`.
4
4
 
5
- To update an existing installation after a new release, run `npm update -g @pulsehub/runner`, then restart the background service with `pulse-runner service stop` followed by `pulse-runner service start`.
5
+ Before updating, stop the existing process with its installed `pulse-runner service stop` command (or Ctrl+C in its terminal). Then run `npm update -g @pulsehub/runner` and `pulse-runner service install`. This release replaces the old detached-process service with an OS-managed per-user service; install it once after upgrading. Service installation also starts it.
6
6
 
7
7
  Every push to `main` (including a merged pull request) runs the release workflow. It tests the Runner, increments the patch version, commits the version and a matching `vX.Y.Z` tag to `main`, then publishes that version to npm. The npm publisher uses GitHub Actions OIDC; no npm token is stored in GitHub. Development-channel releases can be added separately when a `dev` branch is introduced.
8
8
 
@@ -16,7 +16,7 @@ The Runner only uses local Git and provider sessions, creates disposable worktre
16
16
 
17
17
  ## QA review jobs
18
18
 
19
- An agent can use a dedicated Runner identity for QA. To run more than one agent on the same machine, give each instance its own `PULSE_RUNNER_HOME`; initialize each QA instance with `--agent-role qa`, and pair each one with its own agent and Runner credential, then run `pulse-runner start` with that same environment variable. Register the QA Runner in Pulse Settings using its generated signing public key, connect every repository that has a PR in the review, pair its one-time device credential, and select it on the QA agent. Review jobs call `pulse_next_review` and `pulse_get_review_context` through Pulse MCP, inspect every PR, and submit their verdict with `pulse_submit_review`. They do not publish source changes or create PRs.
19
+ An agent can use a dedicated Runner identity for QA. To run more than one agent on the same machine, give each instance its own `PULSE_RUNNER_HOME`; initialize each QA instance with `--agent-role qa`, and pair each one with its own agent and Runner credential, then run `pulse-runner start` with that same environment variable. Register the QA Runner in Pulse Settings using its generated signing public key, enable every repository that has a PR in the issue project, pair its one-time device credential, and select it on the QA agent. Review jobs call `pulse_next_review` and `pulse_get_review_context` through Pulse MCP, inspect every PR, and submit their verdict with `pulse_submit_review`. They do not publish source changes or create PRs.
20
20
 
21
21
  ## Preparation and preflight (TES-304)
22
22
 
@@ -39,3 +39,49 @@ Backend dispatch requires a recent heartbeat and readiness report, a matching id
39
39
  Rollout: upgrade the Runner and configure all Dev/QA identities before enabling the new backend preflight. Older Runners without readiness reports will be blocked with an actionable message. The frontend and backend changes are required together for the preparation panel. Manual UI and live provider verification remain part of TES-308.
40
40
 
41
41
  Authentication command references: [Codex CLI](https://developers.openai.com/codex/cli/reference), [Claude CLI](https://code.claude.com/docs/en/cli-reference).
42
+
43
+
44
+ ## Installation and background services (TES-286)
45
+
46
+ Install Node 20+, Git, the GitHub CLI and the provider CLI on macOS, Linux or Windows. Sign in locally with `gh auth login` and the provider's login command. No GitHub token needs to be entered in Pulse. Initialize with the public signing key shipped in this package, register the generated public key in Settings → Agentes → Pulse Runners and enable repositories in the issue project, then pair the one-time device credential on that machine. A signing **public** key is safe to install locally; never copy the backend's signing private key.
47
+
48
+ Run `pulse-runner diagnose`, then use `pulse-runner run --once` for one job or `pulse-runner start` for foreground operation. `service install` registers a LaunchAgent on macOS, a systemd user unit on Linux, or an on-logon Scheduled Task on Windows. `service start|stop|status|uninstall` manages that installation. Run these commands as the same OS user who owns the local provider and Git sessions. Linux background execution requires a working user systemd session; macOS requires a logged-in GUI user; the Windows task starts on user logon.
49
+
50
+ For multiple instances, use a separate `PULSE_RUNNER_HOME` for every Runner, including when running service commands. Service names derive from that directory, and the installed command retains it through `--home`. A shared lock prevents a daemon and `run --once` from using the same data directory concurrently. If a process died, the next invocation recovers its stale lock and cleans interrupted temporary work before polling.
51
+
52
+ ## Cancellation, recovery and repository scope
53
+
54
+ In Settings → Agentes → Pulse Runners → Actividad reciente, select **Cancelar** for an active job. Only the Runner owner or a workspace admin can cancel it. A queued job becomes canceled immediately. A delivered job shows **Cancelación solicitada**, revokes its ephemeral MCP access immediately, and retains its active capacity until the Runner stops the process and acknowledges cleanup. Refreshing that panel follows the acknowledgment automatically. A disconnected Runner cannot acknowledge until it reconnects; expired jobs are released by the existing sweeper.
55
+
56
+ While executing, the Runner sends an outbound heartbeat every two seconds with its active job ID. A cancellation, revocation, expired job or failed heartbeat stops the provider process tree. On Unix it sends SIGTERM, escalating after two seconds; Windows uses `taskkill /T /F`. Cancellation skips subsequent publication and removes per-job MCP configuration and worktrees before reporting `canceled`. It also checks cancellation before each push and PR creation. A push or PR that already finished cannot be undone by a later cancellation.
57
+
58
+ Ctrl+C or SIGTERM also cancels foreground work. A force-killed daemon recovers on its next start: its local journal stores only the job ID, cleans interrupted worktrees/MCP files, prunes Git registrations and reports the interrupted job canceled. Committed branches remain in the local mirror; uncommitted disposable worktree edits are removed. The source checkout remains untouched. On Windows, forcibly ending the daemon may defer cleanup until that restart.
59
+
60
+ Repository authorization comes from the issue project's enabled repositories, intersected with the workspace GitHub installation. Pairing and agent binding do not require a repository list. `repo add/remove` is deprecated for new jobs; configure repositories in Pulse's project settings. Existing local lists remain usable only for queued legacy jobs. Each project must explicitly declare its repositories; missing configuration blocks dispatch with a visible issue diagnostic.
61
+
62
+ Codex receives the ephemeral MCP Authorization header through a child-process environment variable, never command-line arguments. Claude receives a user-only temporary MCP configuration file, deleted after execution. Provider authentication is always discovered with native status commands; Pulse receives readiness booleans and sanitized lifecycle/results, not provider sessions.
63
+
64
+ ## Signing and rollout
65
+
66
+ Backend `RUNNER_JOB_SIGNING_PRIVATE_KEY` must already exist before deployment, be Ed25519, and match this release's `keys/runner-job-v1-public.pem` and `runner-job-v1` key ID. `contextRepos` is included in the signed envelope. Unknown keys, malformed/future/expired timestamps, invalid identities or unauthorized repositories are rejected before worktree creation. Older HMAC envelopes without algorithm/key ID are deliberately rejected; never reinterpret them locally. Project-scoped jobs use `protocolVersion: 2` and sign both that version and `projectId`. They retain the existing public key and `runner-job-v1` key ID. This Runner also validates queued legacy envelopes using their original payload, without rewriting signatures. Unknown protocol versions are rejected.
67
+
68
+ Upgrade with `pulse-runner service stop`, `npm install -g @pulsehub/runner@latest`, `pulse-runner service install`, then `pulse-runner diagnose`. Keep the existing data directory, pairing credential and signing key configuration. The heartbeat reports `jobProtocolVersion: 2`; the backend blocks older Runners before enqueue with these upgrade instructions. Publish and update the Runner before deploying the backend. No re-pairing or `repo add` is required.
69
+
70
+ Upgrade Runners before enabling the cancellation UI/backend. Older Runners do not observe cancellation requests while their CLI runs, even if the backend revokes MCP access. The backend transaction preserves a requested cancellation if a completion races it. This version retains the TES-304 readiness and Dev/QA identity requirements.
71
+
72
+ ## Verification
73
+
74
+ `npm test` runs native fixture CLIs for both providers against a loopback control plane and real temporary Git repositories. It covers native session detection, signed envelope rejection before checkout, multi-repo isolation, remote/local/revocation/expiry cancellation, process descendants, sanitized reports, temporary-file cleanup, lock exclusion, interrupted-job recovery and QA permissions. The CI matrix runs the suite and CLI smoke on macOS, Linux and Windows. Fixture tests do not prove live model execution or actual service installation in each OS session.
75
+
76
+ ## Local profiles
77
+
78
+ Profiles select local directories and an optional provider model; they do not grant repository access. The Runner checks that a directory is a repository root with a GitHub origin matching a signed job repository, then creates a disposable worktree. The source checkout and its uncommitted changes remain untouched. Cancellation and restart recovery prune these worktree registrations too.
79
+
80
+ ```sh
81
+ pulse-runner profile set --repo owner/repo --directory /absolute/repository/root
82
+ pulse-runner profile set --model MODEL_SUPPORTED_BY_YOUR_PROVIDER
83
+ pulse-runner profile list
84
+ pulse-runner profile remove --repo owner/repo
85
+ ```
86
+
87
+ Profiles are scoped by workspace and agent and saved locally with owner-only permissions. `--model` requires support in the installed provider CLI. Repository access probes run locally for the signed job context before checkout; no provider sessions are sent to Pulse.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pulsehub/runner",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Local, credential-safe Pulse Runner",
5
5
  "repository": {
6
6
  "type": "git",
package/src/config.js CHANGED
@@ -1,19 +1,19 @@
1
1
  import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
2
  import { homedir, platform } from 'node:os';
3
- import { join } from 'node:path';
3
+ import { join, resolve } from 'node:path';
4
4
 
5
5
  export function dataDir() {
6
- if (process.env.PULSE_RUNNER_HOME) return process.env.PULSE_RUNNER_HOME;
6
+ if (process.env.PULSE_RUNNER_HOME) return resolve(process.env.PULSE_RUNNER_HOME);
7
7
  if (platform() === 'darwin') return join(homedir(), 'Library', 'Application Support', 'pulse-runner');
8
8
  if (platform() === 'win32') return join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'pulse-runner');
9
9
  return join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'pulse-runner');
10
10
  }
11
11
 
12
- export const paths = () => ({ root: dataDir(), config: join(dataDir(), 'config.json'), credential: join(dataDir(), 'device-credential'), repos: join(dataDir(), 'repos'), worktrees: join(dataDir(), 'worktrees'), logs: join(dataDir(), 'logs') });
12
+ export const paths = () => ({ root: dataDir(), config: join(dataDir(), 'config.json'), profiles: join(dataDir(), 'agent-profiles.json'), credential: join(dataDir(), 'device-credential'), repos: join(dataDir(), 'repos'), worktrees: join(dataDir(), 'worktrees'), logs: join(dataDir(), 'logs') });
13
13
 
14
14
  export async function ensureDataDir() {
15
15
  const p = paths();
16
- await Promise.all(Object.values(p).filter((value) => value !== p.config && value !== p.credential).map((value) => mkdir(value, { recursive: true, mode: 0o700 })));
16
+ await Promise.all(Object.values(p).filter((value) => value !== p.config && value !== p.profiles && value !== p.credential).map((value) => mkdir(value, { recursive: true, mode: 0o700 })));
17
17
  return p;
18
18
  }
19
19
 
@@ -29,6 +29,17 @@ export async function writeConfig(config) {
29
29
  await chmod(p.config, 0o600);
30
30
  }
31
31
 
32
+ export async function readProfiles() {
33
+ try { return JSON.parse(await readFile(paths().profiles, 'utf8')); }
34
+ catch (error) { if (error.code === 'ENOENT') return {}; throw error; }
35
+ }
36
+
37
+ export async function writeProfiles(profiles) {
38
+ const p = await ensureDataDir();
39
+ await writeFile(p.profiles, `${JSON.stringify(profiles, null, 2)}\n`, { mode: 0o600 });
40
+ await chmod(p.profiles, 0o600);
41
+ }
42
+
32
43
  export async function readCredential() {
33
44
  try { return (await readFile(paths().credential, 'utf8')).trim(); }
34
45
  catch (error) { if (error.code === 'ENOENT') return null; throw error; }
package/src/index.js CHANGED
@@ -1,198 +1,39 @@
1
1
  #!/usr/bin/env node
2
- import { inspectReadiness, assertLocalReadiness, localIdentities } from './readiness.js';
2
+ import { inspectReadiness, localIdentities } from './readiness.js';
3
3
  import { generateKeyPairSync } from 'node:crypto';
4
- import { spawn } from 'node:child_process';
5
- import { appendFile, chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
6
- import { join } from 'node:path';
7
- import { platform } from 'node:os';
8
- import { ensureDataDir, paths, readConfig, readCredential, removeTemporary, writeConfig, writeCredential } from './config.js';
9
- import { validateJob, sanitize } from './job.js';
10
- import { command, runAgent } from './process.js';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { readConfig, readCredential, writeConfig, writeCredential } from './config.js';
6
+ import { sanitize } from './job.js';
7
+ import { service } from './service.js';
8
+ import { profileCommand } from './profile.js';
9
+
10
+ import { runOnce, recoverInterruptedWork, withRunnerLock, request } from './runtime.js';
11
11
 
12
12
  const DEFAULT_ENDPOINT = 'https://us-east4-pulse-app-93.cloudfunctions.net';
13
13
  const args = process.argv.slice(2);
14
+ const homeIndex = args.indexOf('--home');
15
+ if (homeIndex >= 0 && args[homeIndex + 1]) process.env.PULSE_RUNNER_HOME = args[homeIndex + 1];
16
+ let shutdownRequested = false;
17
+ let activeJobController;
18
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => {
19
+ shutdownRequested = true;
20
+ activeJobController?.abort();
21
+ });
14
22
  const value = (flag) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };
15
23
  const has = (flag) => args.includes(flag);
16
- const usage = () => console.log(`pulse-runner <init|pair|start|run|diagnose|identity|repo|service>\n\ninit --workspace WS --agent AGENT [--agent-kind codex|claude] [--agent-role dev|qa] --signing-public-key FILE --allow-autonomous [--endpoint URL] [--repo owner/repo]\npair --credential runner.secret\nidentity add|remove --agent ID --agent-kind codex|claude --agent-role dev|qa | identity list\nstart | run --once | diagnose | repo add|remove|list | service install|start|stop|status`);
17
-
18
- async function logEvent(event, details = {}) {
19
- try {
20
- const p = await ensureDataDir();
21
- const safeDetails = Object.fromEntries(Object.entries(details).map(([key, value]) => [
22
- key,
23
- typeof value === 'string' ? sanitize(value) : value,
24
- ]));
25
- const file = join(p.logs, 'runner.jsonl');
26
- await appendFile(file, `${JSON.stringify({ timestamp: new Date().toISOString(), event, ...safeDetails })}\n`, { mode: 0o600 });
27
- await chmod(file, 0o600);
28
- } catch {
29
- // Logging must not turn a successfully completed job into a failed one.
30
- }
31
- }
32
-
33
- async function request(config, path, body) {
34
- const credential = await readCredential();
35
- if (!credential) throw new Error('Runner is not paired. Run pulse-runner pair first.');
36
- const response = await fetch(`${config.endpoint}/${path}`, { method: 'POST', headers: { Authorization: `Bearer ${credential}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
37
- if (!response.ok) throw new Error(`Pulse endpoint rejected request (${response.status}).`);
38
- return response.json();
39
- }
24
+ const usage = () => console.log(`pulse-runner <init|pair|start|run|diagnose|identity|repo|profile|service>\n\ninit --workspace WS --agent AGENT [--agent-kind codex|claude] [--agent-role dev|qa] --signing-public-key FILE --allow-autonomous [--endpoint URL] \npair --credential runner.secret\nidentity add|remove --agent ID --agent-kind codex|claude --agent-role dev|qa | identity list\nprofile list|set|remove [--model MODEL] [--repo owner/repo --directory PATH]\nstart | run --once | diagnose | service install|start|stop|status|uninstall`);
40
25
 
41
- function repoPath(repo) { return repo.replace('/', '__'); }
42
- function failureDetail(output) {
43
- return sanitize(output).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-3).join(' | ').slice(-240);
44
- }
45
- function completionSummary(result, publication) {
46
- const entries = [{
47
- label: result.code === 0 ? 'Agent completed' : `Agent failed (exit ${result.code})`,
48
- detail: result.code === 0 ? '' : failureDetail(result.output),
49
- }];
50
- for (const published of publication.succeeded) entries.push({ label: 'Publication succeeded', detail: published });
51
- for (const failed of publication.failed) entries.push({
52
- label: `Publication failed for ${failed.repo} during ${failed.phase}`,
53
- detail: failureDetail(failed.error),
54
- });
55
- const detailCount = entries.filter((entry) => entry.detail).length;
56
- const prefixSize = entries.reduce((sum, entry) => sum + entry.label.length + (entry.detail ? 2 : 0), 0) + entries.length - 1;
57
- const detailBudget = detailCount ? Math.max(0, Math.floor((480 - prefixSize) / detailCount)) : 0;
58
- return entries.map(({ label, detail }) => detail && detailBudget ? `${label}: ${detail.slice(-detailBudget)}` : label).join('\n').slice(-500);
59
- }
60
- async function checkoutRepo(repo, worktree) {
61
- const p = paths(); const mirror = join(p.repos, `${repoPath(repo)}.git`);
62
- const existing = await command('git', ['--git-dir', mirror, 'rev-parse', '--git-dir']).catch(() => ({ code: 1, output: '' }));
63
- if (existing.code !== 0) {
64
- const cloned = await command('git', ['clone', '--mirror', `https://github.com/${repo}.git`, mirror]);
65
- if (cloned.code) throw new Error(sanitize(cloned.output));
66
- }
67
- const fetchResult = await command('git', ['--git-dir', mirror, 'fetch', '--prune', 'origin']); if (fetchResult.code) throw new Error(sanitize(fetchResult.output));
68
- const added = await command('git', ['--git-dir', mirror, 'worktree', 'add', '--detach', worktree, 'HEAD']); if (added.code) throw new Error(sanitize(added.output));
69
- const base = await command('git', ['-C', worktree, 'rev-parse', 'HEAD']);
70
- if (base.code) throw new Error(sanitize(base.output));
71
- return { repo, mirror, worktree, baseCommit: base.output.trim() };
72
- }
73
- async function checkout(job) {
74
- const root = join(paths().worktrees, job.id); const repos = [...new Set(job.contextRepos || [job.repoFullName])]; const checkouts = [];
75
- await mkdir(root, { recursive: true, mode: 0o700 });
76
- try {
77
- for (const repo of repos) {
78
- const checkout = await checkoutRepo(repo, join(root, repoPath(repo)));
79
- await writeFile(join(checkout.worktree, '.pulse-runner-job'), job.id, { mode: 0o600 });
80
- checkouts.push(checkout);
26
+ async function start(config) {
27
+ return withRunnerLock(async () => {
28
+ await recoverInterruptedWork(config);
29
+ let backoff = 5_000;
30
+ while (!shutdownRequested) {
31
+ try { activeJobController = new AbortController(); const ranJob = await runOnce((await readConfig()) || config, { signal: activeJobController.signal }); backoff = ranJob ? 1_000 : 5_000; }
32
+ catch (error) { console.error(sanitize(error.message)); backoff = Math.min(backoff * 2, 60_000); }
33
+ finally { activeJobController = undefined; }
34
+ if (!shutdownRequested) await new Promise((resolve) => setTimeout(resolve, backoff));
81
35
  }
82
- const primary = checkouts.find((checkout) => checkout.repo === job.repoFullName);
83
- if (!primary) throw new Error('Job context does not include its target repository.');
84
- return { primary, checkouts };
85
- } catch (error) { await cleanup(checkouts); await removeTemporary(root); throw error; }
86
- }
87
- async function cleanup(checkouts) {
88
- await Promise.all(checkouts.map(async ({ worktree, mirror }) => {
89
- await command('git', ['--git-dir', mirror, 'worktree', 'remove', '--force', worktree]).catch(() => {});
90
- await removeTemporary(worktree);
91
- }));
92
- }
93
- async function publishCheckout(checkout, jobId) {
94
- const branchResult = await command('git', ['-C', checkout.worktree, 'branch', '--show-current']);
95
- const branch = branchResult.output.trim();
96
- if (!branch || !branch.startsWith('pul/')) {
97
- await logEvent('publication.skipped', { jobId, repo: checkout.repo, reason: 'branch-not-pulse' });
98
- return '';
99
- }
100
- let phase = 'validate-commit';
101
- const status = await command('git', ['-C', checkout.worktree, 'status', '--porcelain']);
102
- const uncommitted = status.output.split('\n').filter((line) => line && !line.endsWith('.pulse-runner-job'));
103
- if (uncommitted.length > 0) throw Object.assign(new Error(`Uncommitted changes remain in ${checkout.repo}; the agent must commit every changed worktree.`), { phase });
104
- phase = 'inspect-commit';
105
- const head = await command('git', ['-C', checkout.worktree, 'rev-parse', 'HEAD']);
106
- if (head.code) throw Object.assign(new Error(sanitize(head.output)), { phase });
107
- if (head.output.trim() === checkout.baseCommit) {
108
- await logEvent('publication.skipped', { jobId, repo: checkout.repo, branch, reason: 'no-commits' });
109
- return '';
110
- }
111
- // Sólo se publica una rama de trabajo Pulse de un worktree firmado como
112
- // contexto de este job. El Runner no elige repos ni destinos externos.
113
- phase = 'push';
114
- await logEvent('publication.started', { jobId, repo: checkout.repo, branch, phase });
115
- const pushed = await command('git', ['-c', 'remote.origin.mirror=false', '--git-dir', checkout.mirror, 'push', 'origin', `refs/heads/${branch}:refs/heads/${branch}`]);
116
- if (pushed.code) throw Object.assign(new Error(sanitize(pushed.output)), { phase });
117
- await logEvent('publication.pushed', { jobId, repo: checkout.repo, branch, phase });
118
- phase = 'find-pull-request';
119
- const existing = await command('gh', ['pr', 'view', branch, '--repo', checkout.repo, '--json', 'url']);
120
- if (existing.code === 0) {
121
- await logEvent('publication.pull-request-exists', { jobId, repo: checkout.repo, branch });
122
- return `Published ${checkout.repo}:${branch}; existing PR detected.`;
123
- }
124
- if (!/no pull requests found/i.test(existing.output)) throw Object.assign(new Error(sanitize(existing.output)), { phase });
125
- phase = 'create-pull-request';
126
- const created = await command('gh', ['pr', 'create', '--repo', checkout.repo, '--base', 'main', '--head', branch, '--fill']);
127
- if (created.code) throw Object.assign(new Error(sanitize(created.output)), { phase });
128
- await logEvent('publication.pull-request-created', { jobId, repo: checkout.repo, branch, url: created.output.trim() });
129
- return `Published ${checkout.repo}:${branch}; ${created.output.trim()}`;
130
- }
131
- async function publish(checkouts, jobId) {
132
- const publications = { succeeded: [], failed: [] };
133
- for (const checkout of checkouts) {
134
- try {
135
- const published = await publishCheckout(checkout, jobId);
136
- if (published) publications.succeeded.push(published);
137
- } catch (error) {
138
- const failure = { repo: checkout.repo, phase: error.phase || 'prepare', error: sanitize(error.message) };
139
- publications.failed.push(failure);
140
- await logEvent('publication.failed', { jobId, ...failure });
141
- }
142
- }
143
- return publications;
144
- }
145
- let readinessCache;
146
- async function readinessFor(config, force = false) {
147
- const key = JSON.stringify([config.workspaceId, localIdentities(config), config.repos]);
148
- if (force || !readinessCache || readinessCache.key !== key || Date.now() - readinessCache.at > 60_000) readinessCache = { key, at: Date.now(), value: await inspectReadiness(config) };
149
- return readinessCache.value;
150
- }
151
- async function runOnce(config) {
152
- const readiness = await readinessFor(config);
153
- await request(config, 'pulseRunnerHeartbeat', { status: 'online', readiness });
154
- const delivery = await request(config, 'pulseRunnerPoll', {}); if (!delivery.job) return false;
155
- const job = delivery.job;
156
- await logEvent('job.received', { jobId: job.id, issueId: job.issueId, agentId: job.agentId, mode: job.mode, repo: job.repoFullName });
157
- let jobPhase = 'validate-job';
158
- try {
159
- const agent = delivery.agent || { kind: config.agentKind, role: job.agentId === config.agentId ? 'dev' : null };
160
- validateJob(job, config, agent);
161
- jobPhase = 'local-preflight';
162
- assertLocalReadiness(job, config, agent, await readinessFor(config, true));
163
- await logEvent('job.validated', { jobId: job.id, repoCount: (job.contextRepos || [job.repoFullName]).length });
164
- jobPhase = 'prepare-worktrees';
165
- await request(config, 'pulseRunnerHeartbeat', { status: 'busy' });
166
- const { primary, checkouts } = await checkout(job); const temp = join(paths().root, 'tmp', job.id);
167
- try {
168
- jobPhase = 'run-agent';
169
- await logEvent('agent.started', { jobId: job.id, repo: primary.repo, mode: job.mode });
170
- const result = await runAgent(agent.kind, job, primary.worktree, checkouts.filter((checkout) => checkout !== primary), config, delivery.mcpCredential, temp);
171
- const shouldPublish = result.code === 0 && job.mode !== 'review';
172
- await logEvent(result.code === 0 ? 'agent.completed' : 'agent.failed', {
173
- jobId: job.id,
174
- exitCode: result.code,
175
- ...(result.code === 0 ? {} : { error: failureDetail(result.output) }),
176
- });
177
- const publication = shouldPublish ? await publish(checkouts, job.id) : { succeeded: [], failed: [] };
178
- const outcome = result.code === 0 && publication.failed.length === 0 ? 'completed' : 'failed';
179
- const summary = completionSummary(result, publication);
180
- const failure = outcome === 'failed' ? { phase: result.code !== 0 ? 'run-agent' : publication.failed[0]?.phase || 'publication', category: 'execution', correlationId: job.id } : null;
181
- jobPhase = 'report-completion';
182
- await request(config, 'pulseRunnerComplete', { jobId: job.id, outcome, result: sanitize(summary), failure });
183
- await logEvent('job.completed', { jobId: job.id, outcome, publicationFailures: publication.failed.length });
184
- } finally { await removeTemporary(temp); await cleanup(checkouts); await removeTemporary(join(paths().worktrees, job.id)); }
185
- } catch (error) {
186
- const phase = error.phase || jobPhase;
187
- const message = error?.message || String(error);
188
- await logEvent('job.failed', { jobId: job.id, issueId: job.issueId, repo: job.repoFullName, phase, error: message });
189
- await request(config, 'pulseRunnerComplete', { jobId: job.id, outcome: 'failed', result: sanitize(`${phase}: ${message}`), failure: { phase, category: phase === 'validate-job' ? 'configuration' : ['local-preflight', 'prepare-worktrees'].includes(phase) ? 'local_preparation' : 'execution', correlationId: job.id } }).catch((completionError) => {
190
- logEvent('job.completion-report-failed', { jobId: job.id, error: completionError?.message || String(completionError) });
191
- });
192
- throw error;
193
- }
194
- finally { await request(config, 'pulseRunnerHeartbeat', { status: 'online' }).catch(() => {}); }
195
- return true;
36
+ });
196
37
  }
197
38
 
198
39
  async function init() {
@@ -201,13 +42,12 @@ async function init() {
201
42
  if (!['codex', 'claude'].includes(value('--agent-kind') || 'codex') || !['dev', 'qa'].includes(value('--agent-role') || 'dev')) throw new Error('init requires a valid --agent-kind codex|claude and --agent-role dev|qa.');
202
43
  const { publicKey } = generateKeyPairSync('ed25519'); const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
203
44
  const signingPublicKey = await readFile(publicKeyPath, 'utf8');
204
- await writeConfig({ version: 1, endpoint: value('--endpoint') || DEFAULT_ENDPOINT, workspaceId: value('--workspace'), agentId: value('--agent'), agentKind: value('--agent-kind') || 'codex', agentRole: value('--agent-role') || 'dev', signingKeyId: value('--signing-key-id') || 'runner-job-v1', signingPublicKey, repos: args.filter((item, index) => args[index - 1] === '--repo'), autonomousConfirmed: true });
45
+ await writeConfig({ version: 1, endpoint: value('--endpoint') || DEFAULT_ENDPOINT, workspaceId: value('--workspace'), agentId: value('--agent'), agentKind: value('--agent-kind') || 'codex', agentRole: value('--agent-role') || 'dev', signingKeyId: value('--signing-key-id') || 'runner-job-v1', signingPublicKey, repos: [], autonomousConfirmed: true });
205
46
  console.log(`Public key for pairing:\n${publicKeyPem}\n\nPaste it in Pulse Settings, then run: pulse-runner pair --credential <runner credential>`);
206
47
  }
207
- async function syncRepos(config) { await request(config, 'pulseRunnerConfigure', { connectedRepos: config.repos }); }
208
- async function repo(config) { const op = args[1]; const name = args[2]; if (op === 'list') return console.log(config.repos.join('\n')); if (!name || !/^[^/\s]+\/[^/\s]+$/.test(name)) throw new Error('Repository must be owner/repo.'); const repos = new Set(config.repos); op === 'add' ? repos.add(name) : repos.delete(name); const updated = { ...config, repos: [...repos].sort() }; await writeConfig(updated); await syncRepos(updated); }
48
+ async function repo() { throw new Error('Repository access comes from the issue project. pulse-runner repo is deprecated.'); }
209
49
  async function diagnose(config) {
210
- const readiness = await readinessFor(config, true);
50
+ const readiness = await inspectReadiness(config);
211
51
  console.log(JSON.stringify(readiness, null, 2));
212
52
  if (await readCredential()) await request(config, 'pulseRunnerHeartbeat', { status: 'online', readiness });
213
53
  const providers = localIdentities(config).map((identity) => readiness.providers[identity.kind]);
@@ -226,18 +66,10 @@ async function identity(config) {
226
66
  await writeConfig(updated);
227
67
  await diagnose(updated);
228
68
  }
229
- async function service(config) {
230
- const action = args[1]; const p = paths(); const definition = join(p.root, 'service-install.json'); const pidFile = join(p.root, 'service.pid');
231
- if (action === 'install') { await mkdir(p.logs, { recursive: true, mode: 0o700 }); await writeFile(definition, JSON.stringify({ command: process.execPath, args: [new URL('./index.js', import.meta.url).pathname, 'start'], platform: platform() }, null, 2), { mode: 0o600 }); return console.log(`Service definition prepared at ${definition}.`); }
232
- if (action === 'status') { try { const { pid } = JSON.parse(await readFile(pidFile, 'utf8')); process.kill(pid, 0); return console.log(`Pulse Runner is running (pid ${pid}).`); } catch { return console.log('Pulse Runner is stopped.'); } }
233
- if (action === 'start') { try { const { pid } = JSON.parse(await readFile(pidFile, 'utf8')); process.kill(pid, 0); return console.log(`Pulse Runner is already running (pid ${pid}).`); } catch {} const child = spawn(process.execPath, [new URL('./index.js', import.meta.url).pathname, 'start'], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env }); child.unref(); await writeFile(pidFile, JSON.stringify({ pid: child.pid }), { mode: 0o600 }); return console.log(`Pulse Runner started (pid ${child.pid}).`); }
234
- if (action === 'stop') { try { const { pid } = JSON.parse(await readFile(pidFile, 'utf8')); process.kill(pid, 'SIGTERM'); } catch {} await rm(pidFile, { force: true }); return console.log('Pulse Runner stopped.'); }
235
- throw new Error('Supported service commands: install, start, stop, status.');
236
- }
237
69
 
238
70
  try {
239
71
  if (!args.length || has('--help')) usage();
240
72
  else if (args[0] === 'init') await init();
241
- else if (args[0] === 'pair') { const credential = value('--credential'); const match = credential?.match(/^(runner-[A-Za-z0-9_-]{12})\.[A-Za-z0-9_-]{32,}$/); if (!match) throw new Error('Invalid Runner credential.'); const config = await readConfig(); if (!config) throw new Error('Run pulse-runner init before pairing.'); const paired = { ...config, runnerId: match[1] }; await writeCredential(credential); await writeConfig(paired); await syncRepos(paired); console.log(`Runner ${paired.runnerId} paired.`); }
242
- else { const config = await readConfig(); if (!config) throw new Error('Runner is not initialized.'); if (args[0] === 'identity') await identity(config); else if (args[0] === 'repo') await repo(config); else if (args[0] === 'diagnose') await diagnose(config); else if (args[0] === 'service') await service(config); else if (args[0] === 'run') await runOnce(config); else if (args[0] === 'start') { let backoff = 5_000; for (;;) { try { const ranJob = await runOnce((await readConfig()) || config); backoff = ranJob ? 1_000 : 5_000; } catch (error) { await logEvent('service.loop-failed', { error: error.message }); console.error(sanitize(error.message)); backoff = Math.min(backoff * 2, 60_000); } await new Promise((resolve) => setTimeout(resolve, backoff)); } } else usage(); }
73
+ else if (args[0] === 'pair') { const credential = value('--credential'); const match = credential?.match(/^(runner-[A-Za-z0-9_-]{12})\.[A-Za-z0-9_-]{32,}$/); if (!match) throw new Error('Invalid Runner credential.'); const config = await readConfig(); if (!config) throw new Error('Run pulse-runner init before pairing.'); const paired = { ...config, runnerId: match[1] }; await writeCredential(credential); await writeConfig(paired); console.log(`Runner ${paired.runnerId} paired.`); }
74
+ else { const config = await readConfig(); if (!config) throw new Error('Runner is not initialized.'); if (args[0] === 'identity') await identity(config); else if (args[0] === 'repo') await repo(); else if (args[0] === 'profile') await profileCommand(config, args); else if (args[0] === 'diagnose') await diagnose(config); else if (args[0] === 'service') await service(args[1]); else if (args[0] === 'run') { activeJobController = new AbortController(); try { await withRunnerLock(async () => { await recoverInterruptedWork(config); await runOnce(config, { signal: activeJobController.signal }); }); } finally { activeJobController = undefined; } } else if (args[0] === 'start') await start(config); else usage(); }
243
75
  } catch (error) { console.error(`pulse-runner: ${sanitize(error.message)}`); process.exitCode = 1; }
package/src/job.js CHANGED
@@ -3,22 +3,27 @@ import { verify } from 'node:crypto';
3
3
  const b64 = (value) => Buffer.from(value, 'base64url');
4
4
  export function jobPayload(job) {
5
5
  const contextRepos = [...new Set(job.contextRepos || [job.repoFullName])].sort().join(',');
6
- return [job.id, job.workspaceId, job.issueId, job.agentId, job.runnerId, job.repoFullName, contextRepos, job.mode, job.issuedAt, job.expiresAt, job.signatureAlgorithm, job.signingKeyId].join('.');
6
+ const fields = [job.id, job.workspaceId, job.issueId, job.agentId, job.runnerId, job.repoFullName, contextRepos, job.mode, job.issuedAt, job.expiresAt, job.signatureAlgorithm, job.signingKeyId];
7
+ return (job.protocolVersion === 2 ? [...fields, job.protocolVersion, job.projectId] : fields).join('.');
7
8
  }
8
9
 
9
10
  /** Reject an envelope before it can cause filesystem or process activity. */
10
11
  export function validateJob(job, config, agentOrNow = null, suppliedNow = Date.now()) {
11
12
  const agent = typeof agentOrNow === 'object' && agentOrNow !== null ? agentOrNow : null;
12
13
  const now = typeof agentOrNow === 'number' ? agentOrNow : suppliedNow;
13
- if (!job || job.signatureAlgorithm !== 'ed25519' || job.signingKeyId !== config.signingKeyId) throw new Error('Job signing key is not trusted.');
14
+ if (!job || typeof job.signature !== 'string' || job.signatureAlgorithm !== 'ed25519' || job.signingKeyId !== config.signingKeyId) throw new Error('Job signing key is not trusted.');
15
+ if (job.protocolVersion !== undefined && job.protocolVersion !== 2) throw new Error('Job protocol is not supported.');
16
+ if (job.protocolVersion === 2 && (typeof job.projectId !== 'string' || !/^[-A-Za-z0-9_]+$/.test(job.projectId))) throw new Error('Job project is invalid.');
14
17
  if (!config.signingPublicKey || !verify(null, Buffer.from(jobPayload(job)), config.signingPublicKey, b64(job.signature))) throw new Error('Job signature is invalid.');
15
- if (!job.id?.startsWith('rjob-') || new Date(job.expiresAt).getTime() <= now) throw new Error('Job is expired or malformed.');
18
+ const issuedAt = Date.parse(job.issuedAt);
19
+ const expiresAt = Date.parse(job.expiresAt);
20
+ if (!/^rjob-[A-Za-z0-9_-]+$/.test(job.id || '') || !Number.isFinite(issuedAt) || !Number.isFinite(expiresAt) || issuedAt > now || expiresAt <= now || expiresAt <= issuedAt || !['task', 'rework', 'review', 'handoff'].includes(job.mode)) throw new Error('Job is expired or malformed.');
16
21
  if (job.workspaceId !== config.workspaceId || job.runnerId !== config.runnerId) throw new Error('Job identity does not match this Runner.');
17
22
  const identity = (config.identities || [{ agentId: config.agentId, kind: config.agentKind, role: config.agentRole || 'dev' }]).find((entry) => entry.agentId === job.agentId);
18
23
  const role = job.mode === 'review' ? 'qa' : 'dev';
19
24
  if (!identity || identity.role !== role || (agent && (agent.kind !== identity.kind || agent.role !== role))) throw new Error('Job identity does not match this Runner provider/role.');
20
25
  const contextRepos = [...new Set(job.contextRepos || [job.repoFullName])];
21
- if (!contextRepos.includes(job.repoFullName) || contextRepos.some((repo) => !config.repos.includes(repo))) throw new Error('Job repository context is not allowed by this Runner.');
26
+ if (!contextRepos.includes(job.repoFullName) || contextRepos.some((repo) => typeof repo !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) || (job.protocolVersion !== 2 && !(config.repos || []).includes(repo)))) throw new Error('Job repository context is not allowed by this Runner.');
22
27
  return true;
23
28
  }
24
29
 
package/src/process.js CHANGED
@@ -3,14 +3,43 @@ import { existsSync } from 'node:fs';
3
3
  import { mkdir, writeFile, rm } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
 
6
- export function command(command, args, options = {}) {
6
+ export function command(executable, args, options = {}) {
7
7
  return new Promise((resolve, reject) => {
8
- const child = spawn(command, args, { cwd: options.cwd, env: options.env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
9
- const timer = options.timeout ? setTimeout(() => child.kill('SIGKILL'), options.timeout) : null;
8
+ if (options.signal?.aborted) { resolve({ code: null, output: '' }); return; }
9
+ // Node CLI entrypoints can be used directly on every supported OS.
10
+ const isScript = /\.(?:cjs|mjs|js)$/.test(executable);
11
+ const child = spawn(isScript ? process.execPath : executable, isScript ? [executable, ...args] : args, {
12
+ cwd: options.cwd, env: options.env, stdio: ['ignore', 'pipe', 'pipe'],
13
+ windowsHide: true, detached: process.platform !== 'win32',
14
+ });
15
+ let escalation;
16
+ const killTree = (signal) => {
17
+ try {
18
+ if (process.platform === 'win32') {
19
+ const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
20
+ killer.on('error', () => { try { child.kill(signal); } catch {} });
21
+ } else process.kill(-child.pid, signal);
22
+ } catch {}
23
+ };
24
+ const abort = () => {
25
+ killTree('SIGTERM');
26
+ escalation = setTimeout(() => killTree('SIGKILL'), 2000);
27
+ escalation.unref();
28
+ };
29
+ options.signal?.addEventListener('abort', abort, { once: true });
30
+ const timer = options.timeout ? setTimeout(abort, options.timeout) : null;
10
31
  let output = '';
11
32
  const append = (chunk) => { output = (output + chunk).slice(-(options.maxOutput || 1_000_000)); };
12
33
  child.stdout.on('data', append); child.stderr.on('data', append);
13
- child.on('error', (error) => { if (timer) clearTimeout(timer); reject(error); }); child.on('close', (code) => { if (timer) clearTimeout(timer); resolve({ code, output }); });
34
+ const cleanup = () => {
35
+ if (timer) clearTimeout(timer);
36
+ // Kill any descendants before releasing the process group on cancellation.
37
+ if (options.signal?.aborted || escalation) killTree('SIGKILL');
38
+ if (escalation) clearTimeout(escalation);
39
+ options.signal?.removeEventListener('abort', abort);
40
+ };
41
+ child.on('error', (error) => { cleanup(); reject(error); });
42
+ child.on('close', (code) => { cleanup(); resolve({ code, output }); });
14
43
  });
15
44
  }
16
45
 
@@ -36,6 +65,12 @@ export function agentPermissionArgs(kind, mode) {
36
65
  return [];
37
66
  }
38
67
 
68
+ export async function supportsModelOption(kind) {
69
+ if (!['codex', 'claude'].includes(kind)) return false;
70
+ const result = await command(resolveExecutable(kind), kind === 'codex' ? ['exec', '--help'] : ['--help'], { timeout: 10_000 }).catch(() => ({ code: 1, output: '' }));
71
+ return result.code === 0 && /(?:^|\s)--model(?:\s|[,=])/m.test(result.output);
72
+ }
73
+
39
74
  export function mcpEndpoint(endpoint) {
40
75
  return endpoint.replace(/\/(?:pulseRunner\w*|pulseMcp)\/?$/, '').replace(/\/$/, '') + '/pulseMcp';
41
76
  }
@@ -47,7 +82,19 @@ async function mcpConfig(dir, credential, endpoint) {
47
82
  return path;
48
83
  }
49
84
 
50
- export async function runAgent(kind, job, worktree, additionalWorktrees, config, credential, tempDir) {
85
+ export function providerInvocation(kind, worktree, additionalDirs, config, mcp, prompt, mode = 'task') {
86
+ if (kind === 'codex') return {
87
+ executable: resolveExecutable('codex'),
88
+ args: ['exec', '--ephemeral', ...agentPermissionArgs(kind, mode), '--cd', worktree, ...additionalDirs, '-c', `mcp_servers.pulse.url=${JSON.stringify(mcpEndpoint(config.endpoint))}`, '-c', 'mcp_servers.pulse.env_http_headers={Authorization="PULSE_RUNNER_MCP_CREDENTIAL"}', prompt],
89
+ };
90
+ if (kind === 'claude') return {
91
+ executable: resolveExecutable('claude'),
92
+ args: ['--print', '--no-session-persistence', ...agentPermissionArgs(kind, mode), ...additionalDirs, '--strict-mcp-config', '--mcp-config', mcp, prompt],
93
+ };
94
+ throw new Error(`Unsupported agent kind '${kind}'.`);
95
+ }
96
+
97
+ export async function runAgent(kind, job, worktree, additionalWorktrees, config, credential, tempDir, options = {}) {
51
98
  const context = additionalWorktrees.length
52
99
  ? job.mode === 'review'
53
100
  ? ` Additional review worktrees for inspection: ${additionalWorktrees.map(({ repo, worktree: path }) => `${repo} (${path})`).join('; ')}.`
@@ -59,14 +106,9 @@ export async function runAgent(kind, job, worktree, additionalWorktrees, config,
59
106
  const mcp = await mcpConfig(tempDir, credential, config.endpoint);
60
107
  const additionalDirs = additionalWorktrees.flatMap(({ worktree: path }) => ['--add-dir', path]);
61
108
  try {
62
- // `--approve-for-me` selects Codex's workspace-write sandbox itself.
63
- // Supplying both flags is rejected by current Codex releases.
64
- if (kind === 'codex') {
65
- return await command(resolveExecutable('codex'), ['exec', '--ephemeral', ...agentPermissionArgs(kind, job.mode), '--cd', worktree, ...additionalDirs, '-c', `mcp_servers.pulse.url="${mcpEndpoint(config.endpoint).replace(/\"/g, '\\\"')}"`, '-c', `mcp_servers.pulse.http_headers={Authorization="Bearer ${credential}"}`, prompt], { cwd: worktree });
66
- }
67
- if (kind === 'claude') {
68
- return await command(resolveExecutable('claude'), ['--print', '--no-session-persistence', ...agentPermissionArgs(kind, job.mode), ...additionalDirs, '--strict-mcp-config', '--mcp-config', mcp, prompt], { cwd: worktree });
69
- }
70
- throw new Error(`Unsupported agent kind '${kind}'.`);
109
+ const invocation = providerInvocation(kind, worktree, additionalDirs, config, mcp, prompt, job.mode);
110
+ if (options.profile?.model) invocation.args.splice(kind === 'codex' ? 1 : 0, 0, '--model', options.profile.model);
111
+ const env = kind === 'codex' ? { ...process.env, PULSE_RUNNER_MCP_CREDENTIAL: `Bearer ${credential}` } : process.env;
112
+ return await command(invocation.executable, invocation.args, { cwd: worktree, env, signal: options.signal });
71
113
  } finally { await rm(mcp, { force: true }); }
72
114
  }
package/src/profile.js ADDED
@@ -0,0 +1,63 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { readProfiles, writeProfiles } from './config.js';
4
+ import { command, supportsModelOption } from './process.js';
5
+ export const profileKey = (config) => `${config.workspaceId}:${config.agentId}`;
6
+ const validModel = (model) => typeof model === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(model);
7
+ function remoteRepo(remote) {
8
+ const match = String(remote || '').trim().match(/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/i);
9
+ return match?.[1]?.toLowerCase();
10
+ }
11
+ export async function validateLocalRepo(config, repo, directory, authorizedRepos) {
12
+ if (!repo || (authorizedRepos && !authorizedRepos.includes(repo))) throw new Error('Repository is not authorized by the signed project context.');
13
+ const path = await realpath(resolve(directory));
14
+ const rootResult = await command('git', ['-C', path, 'rev-parse', '--show-toplevel']);
15
+ if (rootResult.code) throw new Error('Selected directory is not an accessible Git repository.');
16
+ const root = await realpath(rootResult.output.trim());
17
+ if (path !== root) throw new Error('Select the repository root directory.');
18
+ const remoteResult = await command('git', ['-C', root, 'remote', 'get-url', 'origin']);
19
+ if (remoteResult.code || remoteRepo(remoteResult.output) !== repo.toLowerCase()) throw new Error('Selected directory origin does not match the allowed repository.');
20
+ return root;
21
+ }
22
+ export async function agentProfile(config) {
23
+ const profiles = await readProfiles();
24
+ return profiles[profileKey(config)] || {};
25
+ }
26
+ export async function resolveProfile(config, job) {
27
+ const profile = await agentProfile({ ...config, agentId: job.agentId });
28
+ if (profile.model && !validModel(profile.model)) throw new Error('Configured model name is invalid.');
29
+ if (profile.model && !(await supportsModelOption(config.agentKind))) throw new Error(`The installed ${config.agentKind} CLI does not support the --model option.`);
30
+ const directory = profile.directories?.[job.repoFullName];
31
+ if (!directory) return { ...profile, directory: undefined };
32
+ return { ...profile, directory: await validateLocalRepo(config, job.repoFullName, directory, job.contextRepos || [job.repoFullName]) };
33
+ }
34
+
35
+ export async function profileCommand(config, args) {
36
+ const value = (flag) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };
37
+ const op = args[1]; const profiles = await readProfiles(); const key = profileKey(config);
38
+ const current = profiles[key] || { directories: {} };
39
+ if (op === 'list') return console.log(JSON.stringify(current, null, 2));
40
+ if (op === 'set') {
41
+ const updated = { ...current, directories: { ...(current.directories || {}) } };
42
+ const model = value('--model'); const repo = value('--repo'); const directory = value('--directory');
43
+ if (!model && !directory) throw new Error('profile set requires --model and/or --directory.');
44
+ if (repo && !directory) throw new Error('--repo requires --directory when setting a profile.');
45
+ if (model) {
46
+ if (!validModel(model)) throw new Error('Model name is invalid; use letters, numbers, dot, underscore, colon, slash or hyphen.');
47
+ if (!(await supportsModelOption(config.agentKind))) throw new Error(`The installed ${config.agentKind} CLI does not support the --model option.`);
48
+ updated.model = model;
49
+ }
50
+ if (directory) {
51
+ if (!repo) throw new Error('--directory requires --repo owner/repo.');
52
+ updated.directories[repo] = await validateLocalRepo(config, repo, directory);
53
+ }
54
+ profiles[key] = updated; await writeProfiles(profiles); return console.log('Local agent profile saved.');
55
+ }
56
+ if (op === 'remove') {
57
+ const repo = value('--repo');
58
+ if (repo) { delete current.directories?.[repo]; if (current.model || Object.keys(current.directories || {}).length) profiles[key] = current; else delete profiles[key]; }
59
+ else delete profiles[key];
60
+ await writeProfiles(profiles); return console.log('Local agent profile updated.');
61
+ }
62
+ throw new Error('Supported profile commands: list, set, remove.');
63
+ }
package/src/readiness.js CHANGED
@@ -18,12 +18,12 @@ export async function inspectReadiness(config, run = command) {
18
18
  providers[kind] = { cli, session: !!session };
19
19
  }
20
20
  const repositories = [];
21
- for (const repo of config.repos) {
21
+ for (const repo of config.repos || []) {
22
22
  if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new Error('Invalid repository.');
23
23
  const accessible = await run('git', ['ls-remote', '--exit-code', `https://github.com/${repo}.git`, 'HEAD'], { env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, timeout: 10_000, maxOutput: 4096 }).then((result) => result.code === 0).catch(() => false);
24
24
  repositories.push({ repo, accessible });
25
25
  }
26
- return { workspaceId: config.workspaceId, identities: localIdentities(config), providers, repositories };
26
+ return { workspaceId: config.workspaceId, identities: localIdentities(config), providers, repositories, jobProtocolVersion: 2 };
27
27
  }
28
28
 
29
29
  export function assertLocalReadiness(job, config, agent, readiness) {