@runeditrun/rer 0.2.98 → 0.2.99

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
@@ -501,7 +501,7 @@ agent and OS (including WSL) for the owner to recognise.
501
501
  For older Business pages, `rer business connect --code ABCD-1234 --origin URL`
502
502
  keeps the browser-created code and six-digit confirmation-number flow unchanged
503
503
  in 0.2.98. It cannot be combined with `--business` or `--timeout`. Removal is
504
- planned for 0.2.99 after the production rollback target uses device pairing.
504
+ planned for a later release after the production rollback target uses device pairing.
505
505
  The install.sh form still passes either connect command through unchanged.
506
506
 
507
507
  The owner chooses three things on the computer's row in the browser: "Add rules
@@ -14,11 +14,12 @@ export function originUrl(value = 'https://app.runeditrun.com') {
14
14
  // The server's own reason travels with its status: platform errors answer
15
15
  // {error, requestId}. It is shown as one bounded line of text, never as markup.
16
16
  export class ApiError extends Error {
17
- constructor(status, reason = null, requestId = null, code = null) {
17
+ constructor(status, reason = null, requestId = null, code = null, { state, link } = {}) {
18
18
  const said = reason ? ` The server said: ${reason}${/[.!?]$/.test(reason) ? '' : '.'}` : '';
19
19
  const reference = requestId ? ` Reference ${requestId}.` : '';
20
20
  super((status === 401 ? 'Business pairing was revoked or expired. Reconnect in your browser.' : `Business server refused the request (HTTP ${status}).`) + said + reference);
21
21
  this.status = status; this.reason = reason; this.requestId = requestId; this.code = code;
22
+ this.state = state; this.link = link;
22
23
  }
23
24
  }
24
25
 
@@ -33,7 +34,8 @@ async function refusal(response, quiet = false) {
33
34
  const code = typeof body?.code === 'string' && /^[a-z][a-z0-9_]{0,79}$/.test(body.code) ? body.code : null;
34
35
  // Pairing responses can echo secrets, including the short user code. Only
35
36
  // the bounded machine code is needed by that flow, never server prose.
36
- return new ApiError(response.status, quiet ? null : reason, quiet ? null : requestId, code);
37
+ return new ApiError(response.status, quiet ? null : reason, quiet ? null : requestId, code,
38
+ quiet ? {} : { state: body?.state === 'waiting_for_owner' ? body.state : undefined, link: line(body?.link) });
37
39
  }
38
40
 
39
41
  const network = {
@@ -47,6 +47,12 @@ In an agent sandbox that writes only inside its working folder, use RER_BUSINESS
47
47
  `;
48
48
 
49
49
  const verbHelp = {
50
+ run: `Usage: rer business run [--once]
51
+ Work this computer's tasks and check in every 25 seconds until stopped.
52
+ When Business needs the owner's catch-up approval or export details,
53
+ print the owner step and keep waiting between check-ins. --once returns then.
54
+ Exits 0 completed, idle or waiting for the owner; 1 failed; 2 usage.
55
+ `,
50
56
  connect: `Usage: rer business connect --business ID [--origin URL] [--timeout SECONDS]
51
57
  Pair this computer with a Business. Prints a code and a link: the owner opens the
52
58
  link in a signed-in browser, checks the code and approves. Waits for that (up to
@@ -87,8 +93,9 @@ export async function businessCommand(argv) {
87
93
  }
88
94
  try {
89
95
  if (options.business !== undefined) identifier(options.business);
90
- if (options.origin !== undefined && options.code === undefined) originUrl(options.origin);
96
+ if (options.origin !== undefined && options.business !== undefined) originUrl(options.origin);
91
97
  } catch { return invalid(); }
98
+ if (options.origin !== undefined && options.code === undefined && options.business === undefined) originUrl(options.origin);
92
99
  await connect(options);
93
100
  } else if (verb === 'vendor-key' && args.length === 2) await vendorKey(...args);
94
101
  else if (verb === 'answer' && [3, 4].includes(args.length)) await answer(...args);
@@ -1,7 +1,7 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { Api, originUrl, identifier, pause } from './api.mjs';
4
- import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
4
+ import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable, lockPairing } from './state.mjs';
5
5
  import { createCredentialStore } from './keychain.mjs';
6
6
  import { applyChoices } from './choices.mjs';
7
7
  import { rerCommand, businessCommand } from './invocation.mjs';
@@ -24,16 +24,17 @@ const nothingSent = 'Nothing was sent, so the pairing code still works.';
24
24
  * computer is active: its credential is stored and the server has seen it.
25
25
  */
26
26
  export async function connect(options = {}) {
27
+ if (options.business !== undefined) return connectDevice(options);
27
28
  const pending = await loadPending();
28
29
  // Approval can outlive the original code deadline. A legacy command must
29
30
  // not discard a device pairing that is still within its collection window.
30
31
  if (pending?.flow === 'device' && options.code !== undefined && Date.parse(pending.keep_until) > Date.now()) throw Error('Business is already waiting for a device pairing. Resume that command, or run business disconnect before using another code.');
31
- if (options.business !== undefined || pending?.flow === 'device' && options.code === undefined) return connectDevice(options);
32
+ if (pending?.flow === 'device' && options.code === undefined) return connectDevice(options);
32
33
  return connectLegacy(options);
33
34
  }
34
35
 
35
- // Compatibility with browser-created codes is retained through 0.2.98 and
36
- // removed in 0.2.99, once the production rollback target uses device pairing.
36
+ // Removal of the browser-created --code flow is planned for a later release,
37
+ // once the production rollback target uses device pairing.
37
38
  async function connectLegacy({ code, origin } = {}) {
38
39
  const stored = await loadState();
39
40
  let pending = await loadPending();
@@ -140,45 +141,47 @@ const terminalPairing = new Map([
140
141
 
141
142
  function validateDevicePairing(value, origin, businessId) {
142
143
  const uri = `${origin}/business/${encodeURIComponent(businessId)}/pair`;
143
- if (!value || !secretValid(value.device_code, 'bz_pairing_') || !shortCode.test(value.user_code)
144
+ if (!value || !secretValid(value.device_code, 'bz_pairing_') || typeof value.user_code !== 'string' || !shortCode.test(value.user_code)
144
145
  || value.verification_uri !== uri || value.business_id !== businessId
145
146
  || value.verification_uri_complete !== undefined && value.verification_uri_complete !== `${uri}#${value.user_code}`
146
147
  || !intervalValid(value.interval) || !timestampValid(value.expires_at)) throw Error('Business server returned an invalid device pairing response.');
147
148
  }
148
149
 
149
150
  async function connectDevice({ business, origin, timeout } = {}) {
150
- const stored = await loadState();
151
- let pending = await loadPending();
152
- origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
153
- business = identifier(business ?? pending?.businessId);
154
- if (stored) {
155
- if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}`);
156
- if (stored.origin !== origin || stored.businessId !== business) throw Error(`This state folder is connected to Business ${identifier(stored.businessId)} at ${originUrl(stored.origin)}. Run disconnect, or use another RER_BUSINESS_STATE_DIR.`);
157
- const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
158
- if (!credential) throw Error('This computer\'s Business credential is missing from OS credential storage. Run disconnect, then connect again.');
159
- return connected(new Api(origin, credential), stored, { reconnecting: true });
160
- }
161
- if (pending && Date.parse(pending.flow === 'device' ? pending.keep_until : pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
162
- if (pending && (pending.flow !== 'device' || pending.origin !== origin || pending.businessId !== business)) throw Error('Business is already waiting for another pairing. Resume that command, or run business disconnect before joining another Business.');
163
- if (pending) {
164
- validateDevicePairing({ ...pending, business_id: pending.businessId }, origin, business);
165
- if (!timestampValid(pending.keep_until) || Date.parse(pending.keep_until) > Date.parse(pending.expires_at) + approvalWindow) throw Error('The saved Business pairing is invalid. Run business disconnect, then connect again.');
166
- }
167
- // Both probes precede even the unauthenticated start. Keychain / Secret
168
- // Service handling and the device credential's account are unchanged.
169
- await checkStateWritable();
170
- const store = createCredentialStore();
171
- const resume = `${rerCommand()} business connect --business ${business} --origin ${origin}${timeout === undefined ? '' : ` --timeout ${timeout}`}`;
172
- try { await store.check(); }
173
- catch (error) {
174
- const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${resume}. Every other business command runs inside the sandbox.` : '';
175
- throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept.' : 'Nothing was sent; no pairing was started.'}`);
176
- }
177
151
  const stop = new AbortController();
178
152
  const interrupt = () => stop.abort('SIGINT'), terminate = () => stop.abort('SIGTERM');
179
153
  process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
180
- let timer;
154
+ let pending, resume, timer, unlock;
181
155
  try {
156
+ await checkStateWritable({ codeExists: false });
157
+ unlock = await lockPairing(stop.signal);
158
+ const stored = await loadState();
159
+ pending = await loadPending();
160
+ origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
161
+ business = identifier(business ?? pending?.businessId);
162
+ if (stored) {
163
+ if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}`);
164
+ if (stored.origin !== origin || stored.businessId !== business) throw Error(`This state folder is connected to Business ${identifier(stored.businessId)} at ${originUrl(stored.origin)}. Run disconnect, or use another RER_BUSINESS_STATE_DIR.`);
165
+ const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
166
+ if (!credential) throw Error('This computer\'s Business credential is missing from OS credential storage. Run disconnect, then connect again.');
167
+ await unlock(); unlock = undefined;
168
+ return await connected(new Api(origin, credential), stored, { reconnecting: true });
169
+ }
170
+ if (pending && Date.parse(pending.flow === 'device' ? pending.keep_until : pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
171
+ if (pending && (pending.flow !== 'device' || pending.origin !== origin || pending.businessId !== business)) throw Error('Business is already waiting for another pairing. Resume that command, or run business disconnect before joining another Business.');
172
+ if (pending) {
173
+ validateDevicePairing({ ...pending, business_id: pending.businessId }, origin, business);
174
+ if (!timestampValid(pending.keep_until) || Date.parse(pending.keep_until) > Date.parse(pending.expires_at) + approvalWindow) throw Error('The saved Business pairing is invalid. Run business disconnect, then connect again.');
175
+ }
176
+ // Both probes precede even the unauthenticated start. Keychain / Secret
177
+ // Service handling and the device credential's account are unchanged.
178
+ const store = createCredentialStore();
179
+ resume = `${rerCommand()} business connect --business ${business} --origin ${origin}${timeout === undefined ? '' : ` --timeout ${timeout}`}`;
180
+ try { await store.check(); }
181
+ catch (error) {
182
+ const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${resume}. Every other business command runs inside the sandbox.` : '';
183
+ throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept.' : 'Nothing was sent; no pairing was started.'}`);
184
+ }
182
185
  const api = new Api(origin);
183
186
  if (!pending) {
184
187
  const name = deviceName(), folder = workingFolder();
@@ -195,6 +198,7 @@ async function connectDevice({ business, origin, timeout } = {}) {
195
198
  keep_until: new Date(Date.parse(result.expires_at) + approvalWindow).toISOString(), next_poll_at: Date.now() + result.interval * 1000 };
196
199
  await savePending(pending);
197
200
  }
201
+ await unlock(); unlock = undefined;
198
202
  // One write puts the fixed lines first, even without a TTY. Never echo the
199
203
  // code elsewhere in prose or errors; the fragment is not sent to a server.
200
204
  process.stdout.write(`Code: ${pending.user_code}\nApprove at: ${pending.verification_uri}#${pending.user_code}\nOpen the link signed in as an owner, check the code, then approve.\nWaiting until ${clock(pending.expires_at)}. Keep this command running.\nRun this same command again to keep waiting (same code).\n`);
@@ -233,7 +237,9 @@ async function connectDevice({ business, origin, timeout } = {}) {
233
237
  } finally {
234
238
  clearTimeout(timer);
235
239
  process.off('SIGINT', interrupt); process.off('SIGTERM', terminate);
240
+ await unlock?.();
236
241
  }
242
+ if (!pending) throw new Stopped('Stopped before starting a Business pairing. Run connect again.', stop.signal.reason === 'SIGTERM' ? 143 : 130);
237
243
  if (stop.signal.reason === 'timeout') throw new Stopped(`Still waiting for approval until ${clock(pending.expires_at)}. Run this same command again to keep waiting (same code).`, 75);
238
244
  throw new Stopped(`Stopped waiting for approval. The pairing is saved: run ${resume} to resume it.`, stop.signal.reason === 'SIGTERM' ? 143 : 130);
239
245
  }
@@ -122,7 +122,7 @@ export async function next() {
122
122
  if (!item) {
123
123
  // Nothing to answer here; say whether run has work, or what it waits for.
124
124
  const work = tasks.find(task => Object.hasOwn(runWork, task.kind) && task.state === 'ready');
125
- if (work) { process.stdout.write(`Ready for run: ${runWork[work.kind]}. Start it with: ${businessCommand('run')}\n`); return; }
125
+ if (work) { process.stdout.write(`Ready for run: ${runWork[work.kind]}. Start it with: ${businessCommand('run --once')}\n`); return; }
126
126
  process.stdout.write(`${waitingFor(state)}\nNothing yet.\n`); return;
127
127
  }
128
128
  const id = identifier(item.task_id);
@@ -142,7 +142,7 @@ export async function next() {
142
142
  + (vendor && !keyed(vendor) ? `Vendor key: none; ${name} is read from its public page, with no key.\n`
143
143
  : stored ? `Vendor key: the owner's read-only ${name} key is stored in this computer's OS credential storage. To replace it, ${keyStep(vendor)}\n`
144
144
  : `Vendor key: ${keyStep(vendor)}${vendor ? '' : `\n where <vendor> is the tool this step reads: ${Object.keys(vendorNames).filter(keyed).join(' | ')}`}\n`)
145
- + `Then run: ${businessCommand('run')}\n`);
145
+ + `Then run: ${businessCommand('run --once')}\n`);
146
146
  return;
147
147
  }
148
148
  const { toolId, vendorId, vendors } = classification(item);
@@ -3,6 +3,7 @@ import { readFileSync, unlinkSync } from 'node:fs';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
+ import { setTimeout as delay } from 'node:timers/promises';
6
7
  import { localCause } from './errors.mjs';
7
8
 
8
9
  // RER_BUSINESS_STATE_DIR names the folder itself, for agent sandboxes that may write only
@@ -61,7 +62,7 @@ async function saveJson(name, value) {
61
62
  * Folders made only for the check are removed again, so a refused connect
62
63
  * leaves nothing behind.
63
64
  */
64
- export async function checkStateWritable() {
65
+ export async function checkStateWritable({ codeExists = true } = {}) {
65
66
  const directory = stateDirectory(), probe = join(directory, `${randomUUID()}.tmp`), created = [];
66
67
  for (let path = directory; path !== dirname(path); path = dirname(path)) {
67
68
  try { await lstat(path); break; } catch (error) { if (error.code !== 'ENOENT') break; created.push(path); }
@@ -77,7 +78,7 @@ export async function checkStateWritable() {
77
78
  const fix = chosenStateDirectory()
78
79
  ? 'Allow writes to that folder in this session, or set RER_BUSINESS_STATE_DIR to a folder this session can write'
79
80
  : 'Allow writes to that folder, or set RER_BUSINESS_STATE_DIR to a folder this session can write (in Codex, one inside the working folder, such as RER_BUSINESS_STATE_DIR="$PWD/.rer-business")';
80
- throw Error(`Business cannot save its state in ${directory}: ${localCause(error) ?? error.message}. Nothing was sent, so the pairing code still works. ${fix}, then run connect again.`);
81
+ throw Error(`Business cannot save its state in ${directory}: ${localCause(error) ?? error.message}. ${codeExists ? 'Nothing was sent, so the pairing code still works.' : 'Nothing was sent.'} ${fix}, then run connect again.`);
81
82
  } finally {
82
83
  for (const path of created) await rmdir(path).catch(() => {});
83
84
  }
@@ -85,7 +86,7 @@ export async function checkStateWritable() {
85
86
 
86
87
  // Files this CLI writes in its state folder. A folder named by RER_BUSINESS_STATE_DIR
87
88
  // may hold other things, so only these are removed from it.
88
- const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|export-[0-9a-f]{32}\.bundle|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
89
+ const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|(?:run|pairing)\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|export-[0-9a-f]{32}\.bundle|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
89
90
  /** After a revocation whose local cleanup was refused, keep only what a later
90
91
  * disconnect needs to finish: the state and the receipts of what remains. */
91
92
  export async function removeWorkFiles(keep = ['state.json', 'permissions.json', 'service.json']) {
@@ -153,3 +154,44 @@ export async function lockSupervisor() {
153
154
  }
154
155
  throw Error('Could not acquire Business supervisor lock.');
155
156
  }
157
+
158
+ /** Serialize the pending read, start and save. Contenders wait, then resume
159
+ * the saved pairing; the lock never covers the foreground approval wait. */
160
+ export async function lockPairing(signal) {
161
+ const directory = stateDirectory(), path = join(directory, 'pairing.lock'), created = [];
162
+ for (let parent = directory; parent !== dirname(parent); parent = dirname(parent)) {
163
+ try { await lstat(parent); break; } catch (error) { if (error.code !== 'ENOENT') break; created.push(parent); }
164
+ }
165
+ const cleanDirectories = async () => { for (const parent of created) await rmdir(parent).catch(() => {}); };
166
+ let file;
167
+ try {
168
+ while (true) {
169
+ signal?.throwIfAborted();
170
+ await mkdir(directory, { recursive: true, mode: 0o700 });
171
+ try { file = await open(path, 'wx', 0o600); }
172
+ catch (error) {
173
+ if (error.code === 'ENOENT') continue; // A failed starter removed its empty folder.
174
+ if (error.code !== 'EEXIST') throw error;
175
+ if (await liveSupervisor(path)) await delay(50, undefined, { signal });
176
+ else await unlink(path).catch(error => { if (error.code !== 'ENOENT') throw error; });
177
+ continue;
178
+ }
179
+ try { await file.writeFile(String(process.pid)); } finally { await file.close(); }
180
+ const refresh = setInterval(() => { const now = new Date(); utimes(path, now, now).catch(() => {}); }, 30_000);
181
+ refresh.unref();
182
+ const exit = () => { try { if (readFileSync(path, 'utf8') === String(process.pid)) unlinkSync(path); } catch { /* Already gone. */ } };
183
+ process.once('exit', exit);
184
+ let released = false;
185
+ return async () => {
186
+ if (released) return;
187
+ released = true;
188
+ clearInterval(refresh); process.off('exit', exit); exit();
189
+ await cleanDirectories();
190
+ };
191
+ }
192
+ } catch (error) {
193
+ if (file) await unlink(path).catch(() => {});
194
+ await cleanDirectories();
195
+ throw error;
196
+ }
197
+ }
@@ -11,7 +11,7 @@ import { Lease } from './lease.mjs';
11
11
  import { runDiscovery } from './discovery-task.mjs';
12
12
  import { applyChoices } from './choices.mjs';
13
13
  import { businessCommand } from './invocation.mjs';
14
- import { ExportWaiting, vendorHandle } from './vendor-door.mjs';
14
+ import { ExportWaiting, vendorHandle, titledVendor } from './vendor-door.mjs';
15
15
  import { runExport } from './export-task.mjs';
16
16
  import { runCatchup } from './catchup-task.mjs';
17
17
  import { runArchive } from './archive-task.mjs';
@@ -22,6 +22,27 @@ const kinds = new Set(['discover.local', ...Object.keys(vendorWork)]);
22
22
  export function supportsTaskKind(kind) { return kinds.has(kind); }
23
23
  const checkIn = 25_000;
24
24
 
25
+ // Only these platform refusals hand work to the owner. Catch-up completion
26
+ // has already surrendered its lease; an export-input wait never claims one.
27
+ function ownerWait(error, state, task) {
28
+ if (error.status !== 409) return null;
29
+ const catchup = error.code === 'business_catchup_approval_required';
30
+ if (!catchup && !(error.code === 'business_export_inputs_required' && error.state === 'waiting_for_owner')) return null;
31
+ let link = ownerLink(state);
32
+ if (catchup && typeof error.link === 'string') {
33
+ try {
34
+ const url = new URL(error.link, state.origin);
35
+ if (url.origin === state.origin && !url.username && !url.password && !url.search && !url.hash
36
+ && url.pathname.startsWith(new URL(link).pathname + '/moves/')) link = url.href;
37
+ } catch { /* The Business page is where the owner can find this step. */ }
38
+ }
39
+ const vendor = task && titledVendor(task.kind, task.title);
40
+ const step = catchup ? 'approve this catch-up' : vendor === 'sorry' ? 'confirm the address'
41
+ : ['sentry', 'pagerduty'].includes(vendor) ? 'confirm the export details' : null;
42
+ if (!step) return `${error.reason ?? "Waiting for the owner's export inputs."}\nIn Business: ${link}`;
43
+ return `${error.reason ? error.reason + '\n' : ''}Waiting for the owner to ${step} in Business: ${link}`;
44
+ }
45
+
25
46
  /** Work this computer's tasks. It says what it is doing and what it waits
26
47
  * for, applies the owner's choices at every check-in, and removes run.lock on
27
48
  * every exit, including Ctrl-C, SIGTERM and a closed terminal (SIGHUP). */
@@ -29,7 +50,7 @@ export async function run({ once = false } = {}) {
29
50
  const { state, credential } = await paired(), api = new Api(state.origin, credential), directory = stateDirectory();
30
51
  // Tasks this run handed back as paused, with what each waits for. An export
31
52
  // waiting only for the owner's vendor key is picked up again once it is stored.
32
- const parked = new Map(), unlock = await lockSupervisor(), stop = new AbortController();
53
+ const parked = new Map(), ownerWaits = new Map(), unlock = await lockSupervisor(), stop = new AbortController();
33
54
  // A terminal's Ctrl-C reaches npx and this process together, and npx then
34
55
  // forwards another SIGINT, which can arrive at any moment until this process
35
56
  // has exited. So the handlers stay for the rest of the process: a repeated
@@ -42,7 +63,7 @@ export async function run({ once = false } = {}) {
42
63
  let progress, stopCarry, said = '', held = null, summaries = [];
43
64
  const say = text => { if (text !== said) { said = text; process.stdout.write(text + '\n'); } };
44
65
  // An agent step that waits is said in its own words, never as "Nothing yet".
45
- const waits = () => [...new Set([...summaries.filter(task => parked.has(task.task_id)).map(task => parked.get(task.task_id).message), ...agentWaiting(summaries)])];
66
+ const waits = () => [...new Set([...ownerWaits.values()].concat(summaries.filter(task => parked.has(task.task_id)).map(task => parked.get(task.task_id).message), agentWaiting(summaries)))];
46
67
  // With no agent step waiting, a move's owner step (freeze, rollback, cancellation) is named with its link.
47
68
  const idle = () => { const owner = ownerWaiting(summaries, state); return owner.length ? owner.join('\n') : waitingFor(state); };
48
69
  try {
@@ -60,6 +81,9 @@ export async function run({ once = false } = {}) {
60
81
  }
61
82
  if (!progress.pendingClaim) {
62
83
  summaries = await nextQuestions(api, stop.signal);
84
+ // A wait belongs only to a task Business still lists as needing input.
85
+ // Cancellation, completion or another computer taking it clears the line.
86
+ for (const id of ownerWaits.keys()) if (!summaries.some(task => task.task_id === id && ['needs_input', 'waiting_for_owner'].includes(task.state))) ownerWaits.delete(id);
63
87
  const handles = (await loadState())?.vendorHandles ?? [];
64
88
  for (const [id, wait] of parked) if (wait.keyMissing && handles.includes(vendorHandle(wait.keyMissing))) parked.delete(id);
65
89
  const selected = summaries.find(task => kinds.has(task.kind) && ['ready','leased'].includes(task.state) && !parked.has(task.task_id));
@@ -76,9 +100,18 @@ export async function run({ once = false } = {}) {
76
100
  let claimed;
77
101
  try { claimed = await api.post('/api/business/executors/claim', { ...progress.pendingClaim, wait_seconds: 25 }, { signal: stop.signal }); }
78
102
  catch (error) {
79
- if (error.status !== 409) throw error;
103
+ const waiting = ownerWait(error, state, summaries.find(task => task.task_id === progress.pendingClaim.task_id));
104
+ if (!waiting) {
105
+ if (error.status !== 409) throw error;
106
+ progress = {}; await saveProgress(progress);
107
+ held = null;
108
+ if (once) throw error;
109
+ await pause(checkIn, stop.signal); continue;
110
+ }
111
+ ownerWaits.set(progress.pendingClaim.task_id, waiting); say(waiting);
80
112
  progress = {}; await saveProgress(progress);
81
- if (once) throw error;
113
+ held = null;
114
+ if (once) return;
82
115
  await pause(checkIn, stop.signal); continue;
83
116
  }
84
117
  if (!claimed.task || claimed.task.state !== 'leased' || claimed.task.fence !== claimed.fence || Date.parse(claimed.lease_expires_at) <= Date.now()) {
@@ -130,14 +163,20 @@ export async function run({ once = false } = {}) {
130
163
  }
131
164
  } catch (error) { failure = lease.signal.aborted ? lease.signal.reason : error; }
132
165
  finally {
133
- if (!finished && failure?.status !== 401) {
166
+ if (!finished && failure?.status !== 401 && !ownerWait(failure ?? {}, state)) {
134
167
  try { await lease.release(stop.signal.aborted ? 'handover' : parked.has(claimed.task.id) ? 'paused' : 'failed'); released = true; }
135
168
  catch (error) { if (error.status === 401) failure = error; }
136
169
  }
137
170
  await lease.close();
138
- if (finished || released) { progress = {}; await saveProgress(progress); }
171
+ if (finished || released || ownerWait(failure ?? {}, state)) { progress = {}; await saveProgress(progress); }
139
172
  }
140
173
  if (failure) {
174
+ const waiting = ownerWait(failure, state);
175
+ if (waiting && !stop.signal.aborted) {
176
+ ownerWaits.set(claimed.task.id, waiting); say(waiting); held = null;
177
+ if (once) return;
178
+ await pause(checkIn, stop.signal); continue;
179
+ }
141
180
  if (failure.status === 401 || once || !parked.has(claimed.task.id)) throw failure;
142
181
  process.stderr.write(failure.message + '\n');
143
182
  }
@@ -89,8 +89,9 @@ function destination(task, grant) {
89
89
  function adapterInputs(vendor, task) {
90
90
  const inputs = exportInputs(vendor, task);
91
91
  if (inputs) return inputs;
92
- const needs = vendor === 'calendly' ? 'an import door that takes its folder of files' : `${inputNeeds[vendor]}, which this task does not carry yet`;
93
- throw new ExportWaiting(`Business vendor export for ${vendorNames[vendor]} needs ${needs}. Task released as paused.`, 'configuration_required');
92
+ const message = vendor === 'calendly' ? 'Waiting for the owner: this tool needs its folder of files shared with Business.'
93
+ : `Waiting for the owner to confirm ${inputNeeds[vendor]} in Business.`;
94
+ throw new ExportWaiting(message, 'configuration_required');
94
95
  }
95
96
 
96
97
  /** One RER-signed import grant for one door request. `review` asks for a
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.99
4
+
5
+ ### Agents wait for the owner instead of failing
6
+
7
+ - `rer business run` now waits when a catch-up needs the owner's approval, or when an export needs an input the owner has not confirmed yet. It prints the platform's message and where the owner acts in Business (for a catch-up, the approval; for an export, the vendor's step, such as confirming the address or the export details), and it does not hand the task back.
8
+ - `rer business run --once` exits 0 when it stops at one of these waits. A continuous `rer business run` keeps running, checks in again every 25 seconds, and picks the work up after the owner acts. A wait clears once Business no longer lists the task as waiting (cancelled, completed or taken by another computer).
9
+ - Every other refusal behaves as before: a 403, a 500 and any other 409 fail or retry exactly as before.
10
+
11
+ ### Plainer words
12
+
13
+ - A vendor export that is missing an input now says it is waiting for the owner (it used to say the task was released as paused) and names the right thing per vendor: Sentry's organization and export window, PagerDuty's export window, Sorry's status page address, and for Calendly that its folder of files needs to be shared with Business. The owner step printed by `rer business run` follows the vendor too: confirm the address for Sorry, the export details for Sentry and PagerDuty.
14
+ - `rer business next` now tells you to run `rer business run --once` when there is work ready, and after a vendor key step.
15
+
16
+ ### Small connect fixes
17
+
18
+ - A pairing response whose code is not text is refused.
19
+ - Two `rer business connect --business ID` runs in the same state folder can no longer start two pairings: the second waits, then resumes the saved pairing.
20
+ - A failure before a pairing starts no longer says the pairing code still works when no code exists yet; the `--code` flow keeps that line.
21
+ - `rer business connect --origin URL` with an origin that is not https, and without `--code`, names the origin rule again.
22
+ - The README and the code comment no longer promise a date for removing `--code`; it is planned for a later release. Nothing in 0.2.99 changes the `--code` path.
23
+
3
24
  ## 0.2.98
4
25
 
5
26
  ### Connecting a computer to a Business
package/global/README.md CHANGED
@@ -501,7 +501,7 @@ agent and OS (including WSL) for the owner to recognise.
501
501
  For older Business pages, `rer business connect --code ABCD-1234 --origin URL`
502
502
  keeps the browser-created code and six-digit confirmation-number flow unchanged
503
503
  in 0.2.98. It cannot be combined with `--business` or `--timeout`. Removal is
504
- planned for 0.2.99 after the production rollback target uses device pairing.
504
+ planned for a later release after the production rollback target uses device pairing.
505
505
  The install.sh form still passes either connect command through unchanged.
506
506
 
507
507
  The owner chooses three things on the computer's row in the browser: "Add rules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.98",
3
+ "version": "0.2.99",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",