@runeditrun/rer 0.2.84 → 0.2.86
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 +156 -50
- package/cli/README.md +78 -2
- package/cli/agent-door.mjs +149 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/bounded.mjs +1 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +151 -0
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +29 -6
- package/cli/business/connect.mjs +20 -8
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +80 -30
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -6
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +97 -32
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/container-transfer.mjs +2 -2
- package/cli/contract.mjs +7 -7
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +6 -2
- package/cli/deploy-command.mjs +6 -4
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/deploy.mjs +9 -7
- package/cli/door-clauses.mjs +157 -0
- package/cli/errors.mjs +1 -1
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/human-error.mjs +20 -0
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +26 -6
- package/cli/main.mjs +2 -1
- package/cli/managed-data-schema.mjs +127 -0
- package/cli/managed-data-zip.mjs +116 -0
- package/cli/managed-data.mjs +110 -0
- package/cli/managed-server.mjs +25 -14
- package/cli/native-owner-entry.mjs +86 -0
- package/cli/output.mjs +3 -2
- package/cli/parse.mjs +2 -2
- package/cli/portability-empty.mjs +65 -0
- package/cli/portability-migrations.mjs +33 -9
- package/cli/portability-policy.mjs +5 -2
- package/cli/portability-worker.mjs +15 -6
- package/cli/portability.mjs +30 -8
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/cli/ready-summary.mjs +9 -0
- package/cli/run-transfers.mjs +37 -0
- package/cli/runtime-front-door.mjs +4 -4
- package/cli/server-proxy.mjs +4 -3
- package/cli/server-registry.mjs +13 -8
- package/cli/site.mjs +6 -1
- package/cli/transfers.mjs +17 -4
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +147 -25
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/module-closure.mjs +2 -16
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +218 -34
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/foundation/runtime/run-data.d.mts +1 -0
- package/foundation/runtime/run-data.mjs +2 -0
- package/global/CHANGELOG.md +126 -0
- package/global/README.md +156 -50
- package/global/cli/command.mjs +8 -2
- package/global/cli/install.mjs +4 -5
- package/global/cli/path-link.mjs +3 -2
- package/global/cli/repo-command.mjs +3 -7
- package/global/door/command.mjs +3 -1
- package/global/launch/dev.mjs +12 -2
- package/global/launch/facts.mjs +2 -2
- package/global/launch/render.mjs +16 -9
- package/global/launch/state.mjs +4 -4
- package/global/main.mjs +13 -8
- package/install.sh +17 -6
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit.mjs +66 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/invocation.mjs +32 -0
- package/modules/agent-door/conformance/journey.mjs +112 -0
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +21 -0
- package/modules/agent-door/conformance/negative.mjs +47 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +75 -0
- package/modules/agent-door/conformance/protocol.mjs +145 -0
- package/modules/agent-door/conformance/replay.mjs +38 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +33 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/surface.mjs +89 -0
- package/modules/agent-door/conformance/target.mjs +18 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +30 -0
- package/modules/container/README.md +6 -1
- package/modules/container/adapters/d1-limits.mjs +286 -0
- package/modules/container/adapters/d1-sqlite.mjs +95 -0
- package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
- package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
- package/modules/container/adapters/d1-workerd.mjs +5 -0
- package/modules/container/adapters/sqlite-worker.mjs +5 -3
- package/modules/container/build.mjs +1 -0
- package/modules/container/image-variables.mjs +14 -3
- package/modules/container/transfer.mjs +14 -4
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/build.mjs +1 -0
- package/modules/demo-host/native/prepare.mjs +2 -1
- package/modules/demo-host/native/sql.mjs +7 -2
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/deploy-kit/README.md +22 -2
- package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
- package/modules/deploy-kit/d1-import.mjs +17 -5
- package/modules/deploy-kit/diagnostics.mjs +29 -3
- package/modules/deploy-kit/owner-cli.mjs +20 -7
- package/modules/deploy-kit/provider-transport.mjs +19 -4
- package/modules/deploy-kit/provider.mjs +57 -22
- package/modules/deploy-kit/readiness-window.mjs +1 -1
- package/modules/deploy-kit/site.mjs +8 -3
- package/modules/deploy-kit/worker.mjs +4 -4
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/d1/README.md +23 -4
- package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
- package/modules/import-kit/src/d1/budget.ts +15 -7
- package/modules/import-kit/src/d1/column-layout.ts +5 -0
- package/modules/import-kit/src/d1/creation.ts +15 -8
- package/modules/import-kit/src/d1/database.ts +3 -3
- package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
- package/modules/import-kit/src/d1/erasure.ts +2 -2
- package/modules/import-kit/src/d1/jobs.ts +10 -6
- package/modules/import-kit/src/d1/plans.ts +14 -8
- package/modules/import-kit/src/d1/retirement.ts +2 -2
- package/modules/import-kit/src/d1/sets.ts +1 -3
- package/modules/import-kit/src/d1/staged-creation.ts +3 -3
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/limits.ts +1 -1
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +2 -1
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +138 -9
- package/modules/portability/backfills.mjs +9 -8
- package/modules/portability/bridge.mjs +32 -5
- package/modules/portability/catalogue.mjs +12 -5
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/files.mjs +4 -3
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/http.mjs +3 -3
- package/modules/portability/import.mjs +29 -13
- package/modules/portability/index.d.mts +4 -3
- package/modules/portability/index.mjs +1 -1
- package/modules/portability/ledgers.mjs +3 -2
- package/modules/portability/legacy-safety.mjs +11 -2
- package/modules/portability/migration-history.mjs +2 -2
- package/modules/portability/progress.mjs +1 -0
- package/modules/portability/restore-empty.mjs +12 -0
- package/modules/release/github-verify.mjs +11 -2
- package/onboarding/adapter.mjs +35 -6
- package/onboarding/app-fetch.mjs +6 -4
- package/onboarding/development-runtime.mjs +19 -0
- package/onboarding/local/operation.mjs +45 -27
- package/onboarding/loopback-fetch.mjs +16 -0
- package/onboarding/operator-installer.mjs +2 -4
- package/onboarding/process-diagnostics.mjs +6 -2
- package/onboarding/production-runtime.mjs +4 -2
- package/onboarding/readiness.mjs +1 -0
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/scripts/publish-check/public_hygiene.py +1 -1
- package/cli/business/opt-ins.mjs +0 -33
package/onboarding/adapter.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { dependencyEnvironment } from './dependency-environment.mjs';
|
|
|
11
11
|
import { labels } from './adapter-labels.mjs';
|
|
12
12
|
import { chooseOrigin, prepareSettings, readSettings } from './adapter-settings.mjs';
|
|
13
13
|
import {listenerPorts,listenerOwnership,inspectionContext} from './process-diagnostics.mjs';
|
|
14
|
-
import { appFetch } from './app-fetch.mjs';
|
|
14
|
+
import { appFetch, loopbackRequest } from './app-fetch.mjs';
|
|
15
15
|
import { owner, signIn } from './adapter-auth.mjs';
|
|
16
16
|
import { installerDevKey } from './dev-identity.mjs';
|
|
17
17
|
import { assertArchiveFree } from './archive-output.mjs';
|
|
@@ -208,26 +208,55 @@ async function start(context, hooks) {
|
|
|
208
208
|
const { store, onApp, signal } = context;
|
|
209
209
|
await store.step(labels.start);
|
|
210
210
|
const [[command, args = [], options = {}]] = await commandsFor(context, hooks.start);
|
|
211
|
-
const { health = '/health', ready, timeoutMs, softAfterMs, intervalMs, ...spawnOptions } = options;
|
|
211
|
+
const { health = '/health', ready, timeoutMs, softAfterMs, intervalMs, runtimePortHandshake, ...spawnOptions } = options;
|
|
212
212
|
if (hooks.guard) await hooks.guard(context);
|
|
213
213
|
let child;
|
|
214
214
|
try { child = store.spawn(labels.start, command, args, { cwd: context.root, signal, ...spawnOptions }); } catch (error) {
|
|
215
215
|
if (signal?.aborted) throw error;
|
|
216
216
|
throw installationFailure('command_failed', { step: 'start', diagnostic: error });
|
|
217
217
|
}
|
|
218
|
+
let announcement,detectedMismatch;
|
|
219
|
+
const mismatch=port=>({fatal:detectedMismatch=`the application listened on port ${port} but the CLI expected ${expectedPort}`});
|
|
220
|
+
const announced=message=>{if(message?.type==='rer-listening')announcement=message;};
|
|
221
|
+
if(runtimePortHandshake)child.on('message',announced);
|
|
218
222
|
context.app = child;
|
|
219
223
|
await onApp(child);
|
|
220
224
|
const url = new URL(health, context.origin).href;
|
|
221
|
-
|
|
222
|
-
const readinessLabel
|
|
225
|
+
let expectedPort=context.runtimePort??Number(new URL(context.origin).port||80);
|
|
226
|
+
const readinessLabel=runtimePortHandshake?`${labels.start} (waiting for the bound internal listener)`:`${labels.start} (expected internal port ${expectedPort})`;
|
|
223
227
|
const ownedPorts=async()=>{
|
|
224
228
|
try{return await listenerPorts(child.pid);}
|
|
225
229
|
catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
|
|
226
230
|
};
|
|
227
231
|
try {
|
|
228
|
-
await store.waitForReady(readinessLabel, child,
|
|
232
|
+
await store.waitForReady(readinessLabel, child, async probeSignal => {
|
|
233
|
+
if(runtimePortHandshake){
|
|
234
|
+
if(!announcement)return {ready:false,message:'Waiting for the application listener handshake'};
|
|
235
|
+
const {port,requestedPort}=announcement;
|
|
236
|
+
if(!Number.isInteger(port)||port<1||port>65535)return {fatal:'The application reported an invalid listener port.'};
|
|
237
|
+
if(requestedPort!==0)return mismatch(port);
|
|
238
|
+
if(context.runtimePort!==port){
|
|
239
|
+
const ownership=await listenerOwnership(child.pid,port,'127.0.0.1',inspectionContext({port,signal:probeSignal,budgetMs:3000}));
|
|
240
|
+
if(ownership.status!=='owned')return {fatal:'The application listener handshake did not identify an owned socket.'};
|
|
241
|
+
context.setRuntimePort(port);context.runtimePort=port;expectedPort=port;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const result=await (ready??hooks.health??defaultHealth)(url,probeSignal,context);
|
|
245
|
+
if(result===true||result?.ready===true)return result;
|
|
246
|
+
// Auxiliary runtime listeners are common. Only an owned listener serving the
|
|
247
|
+
// application's healthy response proves a mismatched application port.
|
|
248
|
+
const ports=await listenerPorts(child.pid,inspectionContext({signal:probeSignal,budgetMs:3000}));
|
|
249
|
+
if(!ports.includes(expectedPort))for(const port of ports){
|
|
250
|
+
try{
|
|
251
|
+
const reply=await loopbackRequest({port,path:health,headers:{host:new URL(url).host},signal:probeSignal,timeoutMs:1000});
|
|
252
|
+
if(reply.status===200&&JSON.parse(reply.body.toString()).status==='ok')return mismatch(port);
|
|
253
|
+
}catch(error){if(probeSignal.aborted)throw error;}
|
|
254
|
+
}
|
|
255
|
+
return result;
|
|
256
|
+
}, { signal, timeoutMs: Math.min(timeoutMs??60000,60000), ...(softAfterMs ? { softAfterMs } : {}), ...(intervalMs ? { intervalMs } : {}) });
|
|
229
257
|
} catch (error) {
|
|
230
258
|
if (signal?.aborted) throw error;
|
|
259
|
+
if(detectedMismatch)throw installationFailure('command_failed',{step:'start',diagnostic:error});
|
|
231
260
|
const ports=await ownedPorts();
|
|
232
261
|
if(ports.length){
|
|
233
262
|
let diagnosis;
|
|
@@ -237,7 +266,7 @@ async function start(context, hooks) {
|
|
|
237
266
|
store.report(message);const prior=approvedFailure(error);error=commandFailure(`${prior?.message??readinessLabel}\n${message}`,prior??{});
|
|
238
267
|
}
|
|
239
268
|
throw installationFailure('command_failed', { step: 'start', diagnostic: error });
|
|
240
|
-
}
|
|
269
|
+
} finally { if(runtimePortHandshake)child.removeListener('message',announced); }
|
|
241
270
|
// Another app can take the loopback port between the port check and the bind;
|
|
242
271
|
// its /health would pass. Claim and sign in only against the process this
|
|
243
272
|
// setup started.
|
package/onboarding/app-fetch.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Requests rer itself makes to a local app's own origin (health, sign-in,
|
|
2
|
-
// dev identity).
|
|
2
|
+
// dev identity). Direct loopback fetches close each connection. A front-door
|
|
3
3
|
// origin (http://NAME.localhost:PORT) is never resolved and never goes through
|
|
4
4
|
// the door: rer connects with node:http to that checkout's own proxy on
|
|
5
5
|
// 127.0.0.1, which keeps the Host header (fetch drops a Host override, and musl
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// whatever answers that name (the door, or a process that took its port) never
|
|
11
11
|
// receives rer's own requests, which can carry the checkout's dev key.
|
|
12
12
|
import http from 'node:http';
|
|
13
|
+
import { loopbackFetch } from './loopback-fetch.mjs';
|
|
13
14
|
import { basename, dirname } from 'node:path';
|
|
14
15
|
import { fileURLToPath } from 'node:url';
|
|
15
16
|
// The shared loopback predicate, beside this copy in Base or in a seed's scripts/.
|
|
@@ -32,7 +33,8 @@ export function loopbackRequest({ host = '127.0.0.1', port, path = '/', method =
|
|
|
32
33
|
response.on('end', () => resolve({ status: response.statusCode, statusText: response.statusMessage ?? '', rawHeaders: response.rawHeaders, body: Buffer.concat(chunks) }));
|
|
33
34
|
response.on('error', reject);
|
|
34
35
|
});
|
|
35
|
-
|
|
36
|
+
const timer=setTimeout(() => request.destroy(Object.assign(Error(`No answer from ${host}:${port} within ${timeoutMs / 1000} s.`), { code: 'ETIMEDOUT' })),timeoutMs);
|
|
37
|
+
request.once('close',()=>clearTimeout(timer));
|
|
36
38
|
request.on('error', reject);
|
|
37
39
|
request.end(body);
|
|
38
40
|
});
|
|
@@ -53,14 +55,14 @@ function unrouted(url) {
|
|
|
53
55
|
export async function appFetch(input, init = {}) {
|
|
54
56
|
let url = new URL(input instanceof Request ? input.url : String(input));
|
|
55
57
|
if (!routes.has(url.origin) && isLocalhostName(url.hostname)) throw unrouted(url);
|
|
56
|
-
if (!routes.has(url.origin)) return
|
|
58
|
+
if (!routes.has(url.origin)) return loopbackFetch(input, init);
|
|
57
59
|
let method = (init.method ?? 'GET').toUpperCase(), body = await bodyBytes(init.body);
|
|
58
60
|
const sent = Object.fromEntries(new Headers(init.headers ?? {}));
|
|
59
61
|
if (body !== undefined && init.body instanceof URLSearchParams && !sent['content-type']) sent['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
|
|
60
62
|
for (let hops = 0; ; hops++) {
|
|
61
63
|
const route = routes.get(url.origin);
|
|
62
64
|
if (!route && isLocalhostName(url.hostname)) throw unrouted(url);
|
|
63
|
-
if (!route) return
|
|
65
|
+
if (!route) return loopbackFetch(url, { ...init, method, body });
|
|
64
66
|
const reply = await loopbackRequest({ port: route.port, path: url.pathname + url.search, method, headers: { ...sent, ...route.headers, host: url.host, ...(body ? { 'content-length': String(body.length) } : {}) }, body, signal: init.signal });
|
|
65
67
|
const headers = new Headers();
|
|
66
68
|
for (let i = 0; i < reply.rawHeaders.length; i += 2) headers.append(reply.rawHeaders[i], reply.rawHeaders[i + 1]);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {createRequire} from 'node:module';
|
|
2
|
+
import {join} from 'node:path';
|
|
3
|
+
import {pathToFileURL} from 'node:url';
|
|
4
|
+
|
|
5
|
+
// Bind first, then announce the actual application listener over the private
|
|
6
|
+
// parent channel. No free-port probe is released before Vite binds.
|
|
7
|
+
const require=createRequire(join(process.cwd(),'package.json'));
|
|
8
|
+
const {createServer}=await import(pathToFileURL(require.resolve('vite')).href);
|
|
9
|
+
const args=process.argv.slice(2),port=Number(args[args.indexOf('--port')+1]);
|
|
10
|
+
const server=await createServer({server:{host:'127.0.0.1',port,strictPort:true}});
|
|
11
|
+
let stopping;
|
|
12
|
+
const stop=()=>stopping??=server.close().finally(()=>{if(process.connected)process.disconnect();});
|
|
13
|
+
process.on('SIGINT',()=>void stop());process.on('SIGTERM',()=>void stop());
|
|
14
|
+
try {
|
|
15
|
+
await server.listen();
|
|
16
|
+
const actual=server.httpServer.address().port;
|
|
17
|
+
process.send?.({type:'rer-listening',requestedPort:port,port:actual});
|
|
18
|
+
server.printUrls();
|
|
19
|
+
}catch(error){await stop();throw error;}
|
|
@@ -47,7 +47,12 @@ export async function localOperation(root, inheritedToken) {
|
|
|
47
47
|
try { await file.writeFile(JSON.stringify({ ...self, token })) } finally { await file.close() }
|
|
48
48
|
const acquired = await identity(path)
|
|
49
49
|
return { token, release: async () => {
|
|
50
|
-
|
|
50
|
+
let owner
|
|
51
|
+
try { owner = JSON.parse(await readFile(path, 'utf8')) } catch (error) {
|
|
52
|
+
if (error.code === 'ENOENT') return
|
|
53
|
+
throw error
|
|
54
|
+
}
|
|
55
|
+
if (owner.token === token && await identity(path) === acquired) await unlink(path).catch(missing)
|
|
51
56
|
} }
|
|
52
57
|
}
|
|
53
58
|
|
|
@@ -70,30 +75,36 @@ export async function ownerAlive(owner) {
|
|
|
70
75
|
// just created. Every starter that judged the same stale file competes for one
|
|
71
76
|
// exclusive guard named after that file's identity; only the guard holder may
|
|
72
77
|
// remove it, and only while the path still names that exact file. A new lock
|
|
73
|
-
// has a new identity
|
|
78
|
+
// has a new identity. Keep the judged descriptor open through the takeover:
|
|
79
|
+
// otherwise its deleted inode can be reused by a new lock while a delayed
|
|
80
|
+
// contender still holds the old identity. Filesystem timestamps do not make
|
|
81
|
+
// inode reuse an exclusive ownership primitive.
|
|
74
82
|
async function takeOver(path) {
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
if (
|
|
78
|
-
const
|
|
79
|
-
let guard
|
|
80
|
-
for (let attempt = 0; !guard; attempt++) {
|
|
81
|
-
try { guard = await open(guardPath, 'wx', 0o600) } catch (error) {
|
|
82
|
-
if (error.code !== 'EEXIST') throw error
|
|
83
|
-
// Another starter is taking over; it, or a faster starter, owns the lock.
|
|
84
|
-
// A guard whose owner was killed is removed once, after its grace.
|
|
85
|
-
if (attempt > 0 || !await removeAbandonedGuard(guardPath, path)) return false
|
|
86
|
-
}
|
|
87
|
-
}
|
|
83
|
+
const stale = await staleIdentity(path)
|
|
84
|
+
if (stale === undefined) return false
|
|
85
|
+
if (stale === null) return true // Already gone: retry the exclusive create.
|
|
86
|
+
const { handle, id: judged } = stale
|
|
88
87
|
try {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
88
|
+
const guardPath = `${path}.takeover-${judged}`
|
|
89
|
+
let guard
|
|
90
|
+
for (let attempt = 0; !guard; attempt++) {
|
|
91
|
+
try { guard = await open(guardPath, 'wx', 0o600) } catch (error) {
|
|
92
|
+
if (error.code !== 'EEXIST') throw error
|
|
93
|
+
// Another starter is taking over; it, or a faster starter, owns the lock.
|
|
94
|
+
// A guard whose owner was killed is removed once, after its grace.
|
|
95
|
+
if (attempt > 0 || !await removeAbandonedGuard(guardPath, path)) return false
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
await guard.writeFile(JSON.stringify(await currentProcess()))
|
|
100
|
+
const current = await identity(path)
|
|
101
|
+
if (current === judged) await unlink(path).catch(missing)
|
|
102
|
+
return true
|
|
103
|
+
} finally {
|
|
104
|
+
await guard.close()
|
|
105
|
+
await unlink(guardPath).catch(missing)
|
|
106
|
+
}
|
|
107
|
+
} finally { await handle.close() }
|
|
97
108
|
}
|
|
98
109
|
|
|
99
110
|
// Returns the identity of a stale lock, null when the lock is already gone, or
|
|
@@ -105,15 +116,22 @@ async function staleIdentity(path) {
|
|
|
105
116
|
if (error.code === 'ENOENT') return null
|
|
106
117
|
throw error
|
|
107
118
|
}
|
|
119
|
+
let retained = false
|
|
108
120
|
try {
|
|
109
121
|
const status = await handle.stat({ bigint: true })
|
|
110
122
|
const id = key(status)
|
|
111
123
|
try {
|
|
112
124
|
const owner = JSON.parse(await handle.readFile('utf8'))
|
|
113
|
-
if (Number.isSafeInteger(owner.pid) && owner.pid > 0)
|
|
125
|
+
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
126
|
+
if (await ownerAlive(owner)) return undefined
|
|
127
|
+
retained = true
|
|
128
|
+
return { handle, id }
|
|
129
|
+
}
|
|
114
130
|
} catch { /* Half-written or unreadable: judged by age below. */ }
|
|
115
|
-
|
|
116
|
-
|
|
131
|
+
if (Date.now() - Number(status.mtimeMs) <= graceMs) return undefined
|
|
132
|
+
retained = true
|
|
133
|
+
return { handle, id }
|
|
134
|
+
} finally { if (!retained) await handle.close() }
|
|
117
135
|
}
|
|
118
136
|
|
|
119
137
|
// A takeover guard left by a killed starter would otherwise block every later
|
|
@@ -162,7 +180,7 @@ async function identity(path) {
|
|
|
162
180
|
}
|
|
163
181
|
}
|
|
164
182
|
|
|
165
|
-
//
|
|
183
|
+
// Compare metadata while the judged inode remains pinned by its descriptor.
|
|
166
184
|
const key = (status) => `${status.dev}-${status.ino}-${status.ctimeNs}`
|
|
167
185
|
// A rename changes ctime, so a moved file is matched by its unchanged fields.
|
|
168
186
|
const movedKey = (status) => `${status.dev}-${status.ino}-${status.birthtimeNs}-${status.mtimeNs}`
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { basename, dirname } from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
|
|
4
|
+
const portable = basename(dirname(fileURLToPath(import.meta.url))) === 'base-onboarding';
|
|
5
|
+
const { isLoopbackHost } = await import(new URL(portable ? '../base-cli/modules/operator-auth/loopback.mjs' : '../modules/operator-auth/loopback.mjs', import.meta.url));
|
|
6
|
+
|
|
7
|
+
// Local harness servers may close idle sockets between readiness and a claim.
|
|
8
|
+
// Close each exchange instead of pooling a socket that can already be closed;
|
|
9
|
+
// never retry a request, particularly a POST with effects.
|
|
10
|
+
export function loopbackFetch(input, init = {}) {
|
|
11
|
+
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
12
|
+
if (!['http:', 'https:'].includes(url.protocol) || !isLoopbackHost(url.hostname)) return fetch(input, init);
|
|
13
|
+
const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
14
|
+
headers.set('connection', 'close');
|
|
15
|
+
return fetch(input, { ...init, headers });
|
|
16
|
+
}
|
|
@@ -5,7 +5,6 @@ import { selectLocalState, LocalStateSafetyError } from './local/state.mjs';
|
|
|
5
5
|
import {operatorPrerequisites} from './operator-prerequisites.mjs';
|
|
6
6
|
import { migrateOperator } from './operator-migrations.mjs';
|
|
7
7
|
import { installOperator } from './operator-install.mjs';
|
|
8
|
-
import { projectViteBinary } from './project-vite.mjs';
|
|
9
8
|
import { join, delimiter } from 'node:path';
|
|
10
9
|
|
|
11
10
|
export function operatorInstaller({ database, features, prepare, prepareData }) {
|
|
@@ -35,11 +34,10 @@ export function operatorInstaller({ database, features, prepare, prepareData })
|
|
|
35
34
|
// No runtime rer starts serves the Local Explorer: it reads and writes the store
|
|
36
35
|
// without the key. trafficProxy also refuses /cdn-cgi/* on the public listener.
|
|
37
36
|
const devBindings = devKey => devKey ? { RER_DEV_KEY: devKey, RER_DEV_IDENTITY: 'on' } : {};
|
|
38
|
-
const internalPort = port => { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('A local runtime requires the traffic proxy internal port.'); return String(port); };
|
|
39
37
|
const developmentEnvironment = () => { const { RER_MODELS_SERVICE, RER_MODELS_KEY, RER_DEMO, RER_DEMO_EXPIRES, RER_STATE_DIR, RER_DEMO_RUN_URL, ...env } = process.env; return env; };
|
|
40
38
|
// A demo's Vite persists to its own folder (the seed's vite.config reads RER_STATE_DIR)
|
|
41
39
|
// and its Worker sees RER_DEMO=1 and the demo's end (modules/demo).
|
|
42
40
|
const demoBindings = demo => demo ? { RER_DEMO: '1', RER_DEMO_EXPIRES: demo.ends, RER_STATE_DIR: demo.state, RER_DEMO_RUN_URL: demo.runUrl } : {};
|
|
43
|
-
export const developmentTarget = ({ root, origin,
|
|
41
|
+
export const developmentTarget = ({ root, origin, devKey, modelsLive, demo }) => [process.execPath, [fileURLToPath(new URL('./development-runtime.mjs',import.meta.url)), 'dev', '--host', '127.0.0.1', '--port', '0', '--strictPort'], { runtimePortHandshake: true, stdio: ['ignore','pipe','pipe','ipc'], env: { ...developmentEnvironment(), PATH: [process.env.PATH, join(root, 'node_modules', '.bin')].filter(value => value !== undefined).join(delimiter), RER_DEV_ORIGIN: origin, WRANGLER_SEND_METRICS: 'false', X_LOCAL_EXPLORER: 'false', ...devBindings(devKey), ...(modelsLive ? { RER_MODELS_SERVICE: modelsLive.baseUrl, RER_MODELS_KEY: modelsLive.apiKey } : {}), ...demoBindings(demo) } }];
|
|
44
42
|
|
|
45
|
-
export const previewTarget = ({ origin,
|
|
43
|
+
export const previewTarget = ({ origin, devKey, scheduled }) => [process.execPath, [fileURLToPath(new URL('./production-runtime.mjs', import.meta.url))], { runtimePortHandshake: true, stdio: ['ignore','pipe','pipe','ipc'], env: { ...process.env, RER_DEV_ORIGIN: origin, RER_RUNTIME_HOST: '127.0.0.1', RER_RUNTIME_PORT: '0', WRANGLER_SEND_METRICS: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false', X_LOCAL_EXPLORER: 'false', RER_RUNTIME_TRIGGERS: scheduled ? '1' : '0', ...(devKey ? { RER_DEV_KEY: devKey } : {}) } }];
|
|
@@ -158,9 +158,13 @@ async function descendants(pid,context){
|
|
|
158
158
|
const owned=new Set([pid]);for(let changed=true;changed;){changed=false;for(const [child,parent]of rows)if(owned.has(parent)&&!owned.has(child)){owned.add(child);changed=true;}}
|
|
159
159
|
return owned;
|
|
160
160
|
}
|
|
161
|
+
// The process's own listeners first, then its descendants', each in port order:
|
|
162
|
+
// a runtime's own application listener comes before the helper sockets its
|
|
163
|
+
// children open (Miniflare's workerd also answers the application's health).
|
|
161
164
|
export async function listenerPorts(pid,context=inspectionContext()){
|
|
162
|
-
const owned=await descendants(pid,context);
|
|
163
|
-
|
|
165
|
+
const owned=await descendants(pid,context),rows=(await listeners([...owned],context)).filter(row=>owned.has(row.pid));
|
|
166
|
+
const ports=group=>group.flatMap(row=>row.names.map(portOf)).filter(port=>Number.isInteger(port)&&port>0&&port<=65535).sort((a,b)=>a-b);
|
|
167
|
+
return [...new Set([...ports(rows.filter(row=>row.pid===pid)),...ports(rows.filter(row=>row.pid!==pid))])];
|
|
164
168
|
}
|
|
165
169
|
// An exact health address can use positive own-tree evidence. localhost can
|
|
166
170
|
// reach either loopback family, so it also needs a completed inspection with
|
|
@@ -9,7 +9,7 @@ import {watchProductionAssets} from './production-assets.mjs';
|
|
|
9
9
|
// only the pinned Miniflare, which owns one workerd and no bundler or
|
|
10
10
|
// source/config watcher. Built-asset changes refresh its manifest.
|
|
11
11
|
let planner,stopping,runtime,closeAssets;
|
|
12
|
-
const stop=()=>stopping??=(async()=>{planner?.kill('SIGTERM');await closeAssets?.();await runtime?.dispose();})();
|
|
12
|
+
const stop=()=>stopping??=(async()=>{planner?.kill('SIGTERM');await closeAssets?.();await runtime?.dispose();if(process.connected)process.disconnect();})();
|
|
13
13
|
process.on('SIGINT',()=>void stop());process.on('SIGTERM',()=>void stop());
|
|
14
14
|
async function plan(){
|
|
15
15
|
let text='';
|
|
@@ -27,7 +27,9 @@ try{
|
|
|
27
27
|
runtime=new Miniflare({...convertV4MiniflareOptions(options),resourcePersistencePath:resolve(process.cwd(),'.wrangler/state/v3')});
|
|
28
28
|
if(stopping)await runtime.dispose();
|
|
29
29
|
else {
|
|
30
|
-
await runtime.ready;
|
|
30
|
+
const address=await runtime.ready;
|
|
31
|
+
process.send?.({type:'rer-listening',requestedPort:options.port,port:Number(address.port)});
|
|
32
|
+
options.port=Number(address.port);
|
|
31
33
|
if (!stopping) closeAssets=watchProductionAssets(runtime,options,value=>({...convertV4MiniflareOptions(value),resourcePersistencePath:resolve(process.cwd(),'.wrangler/state/v3')}),error=>{process.stderr.write(`Preview asset refresh failed: ${error.message}\n`);process.exitCode=1;void stop();});
|
|
32
34
|
}
|
|
33
35
|
}
|
package/onboarding/readiness.mjs
CHANGED
|
@@ -48,6 +48,7 @@ export async function waitForReadiness(label, child, health, options, capture, r
|
|
|
48
48
|
if(stopped())return await drain();
|
|
49
49
|
if(signal?.aborted)return await fail('cancel');
|
|
50
50
|
if(now()-start>=timeoutMs)return await fail('deadline');
|
|
51
|
+
if(typeof result.value?.fatal==='string')throw failure(result.value.fatal,{reason:'mismatch'});
|
|
51
52
|
if(result.value===true||result.value?.ready===true)return result.value;
|
|
52
53
|
if(typeof result.value==='string')lastHealth=result.value;
|
|
53
54
|
else if(typeof result.value?.message==='string')lastHealth=result.value.message;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runeditrun/rer",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.86",
|
|
4
4
|
"description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -94,7 +94,9 @@
|
|
|
94
94
|
"./modules/dependencies": "./modules/dependencies/index.mjs",
|
|
95
95
|
"./internal/*": "./*",
|
|
96
96
|
"./package.json": "./package.json",
|
|
97
|
-
"./modules/import-kit/door": "./modules/import-kit/src/door/index.ts"
|
|
97
|
+
"./modules/import-kit/door": "./modules/import-kit/src/door/index.ts",
|
|
98
|
+
"./modules/import-kit/receipt": "./modules/import-kit/src/receipt/index.ts",
|
|
99
|
+
"./modules/import-kit/status": "./modules/import-kit/src/status/index.ts"
|
|
98
100
|
},
|
|
99
101
|
"engines": {
|
|
100
102
|
"node": ">=22"
|
|
@@ -34,7 +34,9 @@ def copy_pointers(document, read_regular):
|
|
|
34
34
|
value = read_regular(name)
|
|
35
35
|
if (value is None or value[1] != modes[name]
|
|
36
36
|
or hashlib.sha256(value[0]).hexdigest() != digest):
|
|
37
|
-
|
|
37
|
+
# An adapted or mismatched file does not invalidate its siblings'
|
|
38
|
+
# proofs. Its own digest and content remain ordinary scan inputs.
|
|
39
|
+
continue
|
|
38
40
|
pending.add(('copies', index, 'files', name))
|
|
39
41
|
else:
|
|
40
42
|
allowed.update(pending)
|
|
@@ -51,10 +51,35 @@ CONTEXT_URL = re.compile(r'(?i)(?<![A-Za-z])(?:' + REPOSITORY_CONTEXT + r')'
|
|
|
51
51
|
+ r'''[`*_~\[\]\s"']*(?:''' + URL.pattern.replace('(?i)', '') + ')')
|
|
52
52
|
LINK_URL = re.compile(r'(?i)\[(?P<label>[^]\n]+)\]\(\s*(?P<url>' + URL.pattern.replace('(?i)', '') + ')')
|
|
53
53
|
REPOSITORY_LABEL = re.compile(r'(?i)\b(?:' + REPOSITORY_CONTEXT + r')\b')
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
CODE_PREFIX = re.compile(r'(?i)(?<![A-Za-z])(?:origin|submodules?|repositories|repos|forks|clones)' + MARKUP + r'[ \t]*(?:[:=][ \t]*)?$')
|
|
55
|
+
CODE_SUFFIX = re.compile(r'(?i)[ \t]+(?:repositor(?:y|ies)|repos?)\b')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def markdown_repository_context(match, text):
|
|
59
|
+
"""A declaration or command must attach to the token, not nearby prose."""
|
|
60
|
+
if match['reference'] is None:
|
|
61
|
+
prefix = text[text.rfind('\n', 0, match.start()) + 1:match.start()]
|
|
62
|
+
return bool(CODE_PREFIX.search(prefix) or CODE_SUFFIX.match(text, match.end()))
|
|
63
|
+
separator = match['separator']
|
|
64
|
+
if '\n' in text[match.start():match.start('reference')] and not re.search(r'[:=]', separator):
|
|
65
|
+
return False
|
|
66
|
+
prefix = text[text.rfind('\n', 0, match.start()) + 1:match.start()]
|
|
67
|
+
if '|' in separator:
|
|
68
|
+
# A table label occupies a whole cell. The last word of an outcome
|
|
69
|
+
# such as "registered against a repository" cannot label the next cell.
|
|
70
|
+
return not prefix.rsplit('|', 1)[-1].strip(' \t`*_~[]')
|
|
71
|
+
if re.search(r'[:=]', separator):
|
|
72
|
+
return True
|
|
73
|
+
# A bare "source" is not a declaration: "source commit/tree" is prose.
|
|
74
|
+
if re.fullmatch(r'(?i)source', match['label']) and not re.search(
|
|
75
|
+
r'(?i)repository|repo', text[match.start():match.start('reference')]):
|
|
76
|
+
return False
|
|
77
|
+
command = re.match(r'(?i)github|gh\s|clone|fork', match['label'])
|
|
78
|
+
end = text.find('\n', match.end())
|
|
79
|
+
tail = text[match.end():end if end != -1 else len(text)]
|
|
80
|
+
declaration = (re.fullmatch(r'[ \t#>*_~`\[\]-]*(?:[0-9]+\.[ \t]+)?', prefix) and
|
|
81
|
+
re.fullmatch(r'[ \t\r`*_~\[\].,;:!)]*', tail))
|
|
82
|
+
return bool(match['markup'] or command or declaration)
|
|
58
83
|
|
|
59
84
|
|
|
60
85
|
def explicit_references(text, path):
|
|
@@ -109,7 +134,7 @@ def reference_sets(text, path, local_paths=frozenset(), project_identity=None):
|
|
|
109
134
|
markdown = URL.sub('', text)
|
|
110
135
|
markdown = re.sub(r'\]\((?![A-Za-z][A-Za-z0-9+.-]*://)[^)]*\)', ']()', markdown)
|
|
111
136
|
for match in MARKDOWN_REFERENCE.finditer(markdown):
|
|
112
|
-
explicit = match
|
|
137
|
+
explicit = markdown_repository_context(match, markdown)
|
|
113
138
|
value = re.split(r'[?#]', match['reference'] or match['code'], maxsplit=1)[0]
|
|
114
139
|
# Underscores are also legal slug characters; remove a closing
|
|
115
140
|
# emphasis marker only when the reference has its matching opener.
|
|
@@ -123,17 +148,11 @@ def reference_sets(text, path, local_paths=frozenset(), project_identity=None):
|
|
|
123
148
|
continue
|
|
124
149
|
# A plain multi-segment path is ambiguous; GitHub's repository
|
|
125
150
|
# routes, a labeled field or a GitHub command disambiguate it.
|
|
126
|
-
labeled = explicit and (re.search(r'[:=|]', match['separator']) or re.match(r'(?i)github|gh\s', match['label']))
|
|
151
|
+
labeled = explicit and match['reference'] is not None and (re.search(r'[:=|]', match['separator']) or re.match(r'(?i)github|gh\s', match['label']))
|
|
127
152
|
if REPOSITORY_ROUTE.match(suffix) or labeled:
|
|
128
153
|
found.add(normalize(repository))
|
|
129
154
|
elif not suffix:
|
|
130
|
-
if explicit
|
|
131
|
-
weak = re.fullmatch(r'(?i)source', match['label']) and not re.search(r'(?i)repository|repo', markdown[match.start():match.start('reference')])
|
|
132
|
-
else:
|
|
133
|
-
line_start = markdown.rfind('\n', 0, match.start()) + 1
|
|
134
|
-
around = markdown[max(line_start, match.start() - CONTEXT_WINDOW):match.end() + CONTEXT_WINDOW].split('\n', 1)[0]
|
|
135
|
-
weak = not NEARBY_CONTEXT.search(around)
|
|
136
|
-
(ambiguous if weak else found).add(normalize(repository))
|
|
155
|
+
(found if explicit else ambiguous).add(normalize(repository))
|
|
137
156
|
elif METADATA.search(path) or SOURCE.search(path):
|
|
138
157
|
if path.lower().endswith('.json'):
|
|
139
158
|
try:
|
|
@@ -18,7 +18,7 @@ SCHEME_CHARACTERS = frozenset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW
|
|
|
18
18
|
# acquire trailer privileges. Only the address span is omitted from email checks.
|
|
19
19
|
COAUTHOR = re.compile(
|
|
20
20
|
rb'^Co-Authored-By:[ \t]+(?=[^ \t])[^<>\r\n]*[^<>\s][ \t]+<(?P<address>'
|
|
21
|
-
rb'noreply@(?:anthropic|github)\.com|'
|
|
21
|
+
rb'noreply@(?:anthropic|openai|github)\.com|'
|
|
22
22
|
rb'[0-9]+\+[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}@users\.noreply\.github\.com'
|
|
23
23
|
rb')>[ \t]*\r?$', re.I | re.M)
|
|
24
24
|
|
package/cli/business/opt-ins.mjs
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { installService } from './service.mjs';
|
|
2
|
-
import { installPermissions } from './permissions.mjs';
|
|
3
|
-
import { saveState } from './state.mjs';
|
|
4
|
-
import { rerCommand } from './invocation.mjs';
|
|
5
|
-
|
|
6
|
-
// The server's field names stay internal; people see the browser's sentences.
|
|
7
|
-
export const optIns = {
|
|
8
|
-
installPermissions: 'Add rules so Claude Code never reads your secret files',
|
|
9
|
-
awakeConsent: 'Keep this computer awake while it works',
|
|
10
|
-
installService: 'Install the background service',
|
|
11
|
-
};
|
|
12
|
-
const optInNames = Object.keys(optIns);
|
|
13
|
-
|
|
14
|
-
export async function applyOptIns(api, state) {
|
|
15
|
-
let self;
|
|
16
|
-
// A server without this route answers a device credential with 403 (or 404):
|
|
17
|
-
// nothing is decided yet. This first authenticated request activates the computer.
|
|
18
|
-
try { self = await api.get('/api/business/executors/self'); }
|
|
19
|
-
catch (error) { if (![403, 404].includes(error.status)) throw error; }
|
|
20
|
-
const decisions = Object.fromEntries(optInNames.map(name => [name, self?.optIns?.[name] === true ? true : self?.optIns?.[name] === false ? false : null]));
|
|
21
|
-
if (decisions.installPermissions === true) await installPermissions({ consent: true });
|
|
22
|
-
state.awakeConsent = decisions.awakeConsent === true;
|
|
23
|
-
await saveState(state);
|
|
24
|
-
process.stdout.write(`This computer is connected to Business at ${state.origin}.\n`);
|
|
25
|
-
if (decisions.installService === true) {
|
|
26
|
-
await installService({ consent: true });
|
|
27
|
-
process.stdout.write('The background service is installed and works tasks after this chat ends.\n');
|
|
28
|
-
} else process.stdout.write(`Run ${rerCommand()} business run to work tasks.\n`);
|
|
29
|
-
const undecided = optInNames.filter(name => decisions[name] === null);
|
|
30
|
-
if (undecided.length) {
|
|
31
|
-
process.stdout.write(`The owner has not chosen yet:\n${undecided.map(name => ` - ${optIns[name]}\n`).join('')}Ask them to choose on this computer's row in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings, then run ${rerCommand()} business connect again to apply the choices.\n`);
|
|
32
|
-
}
|
|
33
|
-
}
|