@tnunamak/dalan 0.8.1 → 0.8.3
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/CHANGELOG.md +61 -2
- package/CONTRIBUTING.md +2 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +121 -34
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +2 -1
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +77 -14
- package/docs/pull-workers.md +11 -1
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +4 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/test-suite-isolation.md +7 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +21 -7
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/cli-help.mjs +14 -3
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +44 -9
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +212 -7
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +503 -98
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +136 -21
- package/src/service-update.mjs +207 -51
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/store.mjs +876 -120
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +34 -7
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/src/gozar-routes.mjs
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
// The
|
|
2
|
-
// the shapes and the 21 error codes of that contract (tnunamak/gozar, contract/route-contract-c0 @ 91b41a1; the pinned fixture is
|
|
3
|
-
// src/test-support/gozar-contract.json). Dalan never names a provider, never validates or translates a route name, and never builds a
|
|
4
|
-
// command for a provider: a name from `--route` goes to Gozar as written.
|
|
5
|
-
//
|
|
6
|
-
// Every function takes the Gozar module as `gozar`, so tests inject a fake that is checked against the same fixture.
|
|
1
|
+
// The route boundary for Dalan: supply application requirements and render Gozar's current offers and observations.
|
|
7
2
|
import { createRequire } from 'node:module';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
8
4
|
import fs from 'node:fs';
|
|
9
5
|
import os from 'node:os';
|
|
10
6
|
import path from 'node:path';
|
|
7
|
+
import { routeSecretBackend, routeCustodyPath } from './route-custody.mjs';
|
|
11
8
|
import { safeDiagnostic } from './diagnostic.mjs';
|
|
12
9
|
import { readJournal, removeJournal, writeJournal, readRouteSetting, writeRouteSetting } from './route-setting.mjs';
|
|
13
10
|
|
|
@@ -15,9 +12,11 @@ export const OWNER = 'dalan';
|
|
|
15
12
|
export const SCHEMA_VERSION = 1;
|
|
16
13
|
export const FROZEN_CODES = Object.freeze(['invalid_input', 'requirements_unsatisfied', 'setup_required', 'consent_required', 'consent_unknown', 'consent_expired',
|
|
17
14
|
'consent_mismatch', 'candidate_stale', 'preference_conflict', 'route_not_found', 'route_conflict', 'address_changed', 'stopped_by_user', 'handing_back',
|
|
18
|
-
'verification_failed', 'provider_unavailable', 'cleanup_debt', 'unsupported', 'ambiguous_route', 'busy', 'internal_error'
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
'verification_failed', 'provider_unavailable', 'cleanup_debt', 'unsupported', 'ambiguous_route', 'busy', 'internal_error',
|
|
16
|
+
'configuration_stale', 'configuration_in_use', 'secret_in_use', 'secret_backend_locked', 'secret_backend_unavailable',
|
|
17
|
+
'host_policy_denied', 'artifact_integrity_failed', 'configuration_migration_required', 'proof_refresh_unsupported', 'operation_conflict']);
|
|
18
|
+
// Check the public exports before starting an install or trial.
|
|
19
|
+
export const REQUIRED_EXPORTS = Object.freeze(['catalogRoutes', 'ensureRoute', 'adoptRoute', 'expose', 'routeStatus', 'closeRoute', 'watchRoutes', 'inspectLegacyRoute', 'runSetupAction', 'readSetupOperation', 'cancelSetupOperation', 'createGozar', 'listRoutes', 'releaseRoute', 'confirmHandBack']);
|
|
21
20
|
|
|
22
21
|
export class RouteError extends Error {
|
|
23
22
|
constructor(code, message, { nextAction = null, cause } = {}) { super(message, cause ? { cause } : undefined); this.name = 'RouteError'; this.code = code; this.nextAction = nextAction; }
|
|
@@ -27,7 +26,7 @@ export class RouteError extends Error {
|
|
|
27
26
|
const require = createRequire(import.meta.url);
|
|
28
27
|
// The bundled package, resolved from Dalan's own install tree (not the working directory). An install without the contract's exports
|
|
29
28
|
// is reported as `runtime_missing` with the next step; nothing falls back to another executable.
|
|
30
|
-
export async function resolveGozar({ importer = () => import('@tnunamak/gozar'), resolvePackage = () => require.resolve('@tnunamak/gozar/package.json') } = {}) {
|
|
29
|
+
export async function resolveGozar({ env = process.env, home = gozarHomeFor(env), custody = routeCustodyPath({ HOME: os.homedir(), ...env }, home), importer = () => import('@tnunamak/gozar'), resolvePackage = () => require.resolve('@tnunamak/gozar/package.json') } = {}) {
|
|
31
30
|
let module;
|
|
32
31
|
try { module = await importer(); } catch (error) {
|
|
33
32
|
if (error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'MODULE_NOT_FOUND') throw new RouteError('runtime_missing', 'Gozar is not installed with this Dalan. Reinstall @tnunamak/dalan with its dependencies, then run this again.', { cause: error });
|
|
@@ -39,7 +38,12 @@ export async function resolveGozar({ importer = () => import('@tnunamak/gozar'),
|
|
|
39
38
|
try { version = JSON.parse(fs.readFileSync(resolvePackage(), 'utf8')).version ?? version; } catch { /* reported as unknown */ }
|
|
40
39
|
throw new RouteError('runtime_missing', `The installed Gozar (${version}) does not provide the route contract (missing ${missing.join(', ')}). Update @tnunamak/dalan to a release that bundles it.`);
|
|
41
40
|
}
|
|
42
|
-
|
|
41
|
+
const secretBackend = routeSecretBackend(custody);
|
|
42
|
+
const api = module.createGozar({ secretBackend, hostCapabilities: {
|
|
43
|
+
'secrets.backend': { known: true, value: true },
|
|
44
|
+
} });
|
|
45
|
+
// These standalone calls are public and take the same private state home explicitly.
|
|
46
|
+
return { ...api, releaseRoute: module.releaseRoute, confirmHandBack: module.confirmHandBack };
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
// Gozar's profile home for the real OS user. An explicit GOZAR_HOME selects a separate profile.
|
|
@@ -63,20 +67,23 @@ export const targetFor = port => `127.0.0.1:${port}`;
|
|
|
63
67
|
// ---- choosing and showing candidates (data only) ---------------------------------------------------------------------------------------
|
|
64
68
|
export const readyCandidates = catalog => [...catalog.candidates].filter(c => c.eligible && c.setup.state === 'ready' && typeof c.candidateToken === 'string').sort((a, b) => a.rank - b.rank);
|
|
65
69
|
export const pickCandidate = catalog => readyCandidates(catalog)[0] ?? null;
|
|
66
|
-
//
|
|
67
|
-
// type what the label says. The word is matched only against labels Gozar returned; no provider is named here. Returns the query to send and how to
|
|
68
|
-
// pick the candidate: an unnamed query lets Gozar offer every route, and `pick` chooses the matching one.
|
|
70
|
+
// Gozar accepts configured route names and exact catalog IDs. It validates both.
|
|
69
71
|
export async function resolveRouteWord({ gozar, query }) {
|
|
70
72
|
if (query.route === undefined) return { query, pick: pickCandidate };
|
|
71
|
-
try { await gozar.catalogRoutes(query); return { query, pick: pickCandidate }; }
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
73
|
+
try { await gozar.catalogRoutes(query); return { query, pick: pickCandidate }; }
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error?.code !== 'route_not_found') throw error;
|
|
76
|
+
const { route, ...request } = query;
|
|
77
|
+
const exact = { ...request, providerId: route };
|
|
78
|
+
try { await gozar.catalogRoutes(exact); }
|
|
79
|
+
catch (fallback) { if (fallback?.code === 'route_not_found') throw error; throw fallback; }
|
|
80
|
+
return { query: exact, pick: pickCandidate };
|
|
81
|
+
}
|
|
78
82
|
}
|
|
79
|
-
export const approvalFor = candidate => ({
|
|
83
|
+
export const approvalFor = candidate => ({
|
|
84
|
+
kind: 'route', candidateToken: candidate.candidateToken, disclosureRevision: candidate.disclosure.revision,
|
|
85
|
+
consentFactsDigest: candidate.consentFactsDigest,
|
|
86
|
+
});
|
|
80
87
|
|
|
81
88
|
const yesNo = value => value === true ? 'yes' : value === false ? 'no' : 'unknown';
|
|
82
89
|
// One block of lines per candidate, built only from what Gozar returned. Labels name a provider only as returned display data.
|
|
@@ -93,26 +100,36 @@ export function describeCandidate(candidate, index) {
|
|
|
93
100
|
}
|
|
94
101
|
export function describeDisclosure(candidate) {
|
|
95
102
|
const d = candidate.disclosure;
|
|
96
|
-
|
|
103
|
+
const cost = candidate.consent?.disclosures?.cost;
|
|
104
|
+
const costLine = cost?.summary && (cost.kind === 'paid'
|
|
105
|
+
? `Cost for this approval: ${cost.summary} (${cost.amount} ${cost.currency} per ${cost.period})`
|
|
106
|
+
: `Cost for this approval: ${cost.kind}, ${cost.summary}`);
|
|
107
|
+
return [...(costLine ? [costLine] : []), ...describeFacts(candidate.consent?.facts ?? []), d.text, ...d.links.map(l => `${l.label}: ${l.href}`)];
|
|
97
108
|
}
|
|
98
109
|
|
|
99
|
-
|
|
100
|
-
|
|
110
|
+
export const describeFacts = facts => facts.map(fact => `${fact.label}: ${fact.known ? String(fact.value) : `unknown (${fact.reason})`}`);
|
|
111
|
+
|
|
112
|
+
// Translate common route errors and display safe guidance returned by Gozar.
|
|
101
113
|
const EXPLAIN = {
|
|
102
114
|
invalid_input: 'Dalan sent Gozar a request it refused as invalid.', requirements_unsatisfied: 'No route satisfies what Dalan needs (an HTTPS address reachable from the internet).',
|
|
103
115
|
setup_required: 'A route needs one setup step first.', consent_required: 'This route needs your approval first.', consent_unknown: 'The approval was already used or is unknown. Ask for the choices again.',
|
|
104
116
|
consent_expired: 'The approval expired. Ask for the choices again.', consent_mismatch: 'The approval was for a different request. Ask for the choices again.', candidate_stale: 'The route choice changed while you decided. Ask again.',
|
|
105
117
|
preference_conflict: 'Your route preferences changed meanwhile. Try again.', route_not_found: 'Gozar has no route with that name.', route_conflict: 'Another owner or a newer route replaced this one; it was left untouched.',
|
|
106
118
|
address_changed: 'The public address changed.', stopped_by_user: 'This route was stopped by you; approve it again to start it.', handing_back: 'The route is being handed back to its previous owner.',
|
|
107
|
-
verification_failed: 'The route did not pass Gozar\'s check.', provider_unavailable: 'The route provider is unavailable right now.', cleanup_debt: '
|
|
119
|
+
verification_failed: 'The route did not pass Gozar\'s check.', provider_unavailable: 'The route provider is unavailable right now.', cleanup_debt: 'Gozar reports cleanup debt for this route.',
|
|
108
120
|
unsupported: 'This computer or request is not supported by any route.', ambiguous_route: 'Gozar cannot tell which existing route this is, so it changed nothing.',
|
|
109
121
|
busy: 'Gozar is busy. Wait a moment and try again.', internal_error: 'Gozar had an unexpected fault.', runtime_missing: 'Gozar is not available.',
|
|
122
|
+
configuration_stale: 'The route configuration changed. Ask for the current offer.', configuration_in_use: 'This configuration is still in use.',
|
|
123
|
+
secret_in_use: 'A setup or route still uses this credential.', secret_backend_locked: 'The credential store is locked.',
|
|
124
|
+
secret_backend_unavailable: 'The credential store could not be reached.', host_policy_denied: 'The host did not allow this effect.',
|
|
125
|
+
artifact_integrity_failed: 'The setup artifact failed its integrity check.', configuration_migration_required: 'Gozar requires a configuration migration.',
|
|
126
|
+
proof_refresh_unsupported: 'Gozar cannot refresh proof for this route.', operation_conflict: 'The saved operation belongs to a different route request.',
|
|
110
127
|
};
|
|
111
128
|
export function explainRouteError(error) {
|
|
112
129
|
const code = typeof error?.code === 'string' && (FROZEN_CODES.includes(error.code) || error.code === 'runtime_missing') ? error.code : null;
|
|
113
130
|
// Gozar's next step is shown as text for every code, including one Dalan does not know yet; Dalan never acts on it.
|
|
114
131
|
const action = error?.nextAction ?? null;
|
|
115
|
-
const fix = action ? [action.label, action.instructions, action.href].filter(value => typeof value === 'string' && value.length > 0).map(value => safeDiagnostic(value, 240)).join(' - ') || null : null;
|
|
132
|
+
const fix = action ? [action.label, action.instructions, !action.step?.browser && action.href].filter(value => typeof value === 'string' && value.length > 0).map(value => safeDiagnostic(value, 240)).join(' - ') || null : null;
|
|
116
133
|
if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix };
|
|
117
134
|
const detail = code === 'runtime_missing' ? error.message : `${EXPLAIN[code]}${error.message && !EXPLAIN[code].includes(error.message) ? ` (${safeDiagnostic(error.message, 160)})` : ''}`;
|
|
118
135
|
return { code, line: detail, fix };
|
|
@@ -120,73 +137,225 @@ export function explainRouteError(error) {
|
|
|
120
137
|
|
|
121
138
|
// ---- a session route (`dalan try --public`) --------------------------------------------------------------------------------------------
|
|
122
139
|
// `consent(candidate)` shows the disclosure and resolves true only on an explicit yes. The route lasts for the trial and is closed with it.
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
// `wait: 'allocated'` is for a trial whose bridge needs the address before it can answer Gozar's check: Dalan then runs its own readiness check.
|
|
126
|
-
export async function startSessionRoute({ gozar, query, consent, signal, wait = 'verified', pick = pickCandidate }) {
|
|
140
|
+
// An allocated origin can configure the local app. Only a current, published view can be handed off.
|
|
141
|
+
export async function startSessionRoute({ gozar, query, consent, signal, wait = 'verified', pick = pickCandidate, remember, setup, recovery }) {
|
|
127
142
|
signal?.throwIfAborted();
|
|
128
|
-
|
|
143
|
+
query = { ...query, operationId: recovery?.operationId ?? query.operationId ?? randomUUID() };
|
|
144
|
+
const { candidate, catalog } = await chooseRoute({ gozar, query, pick, setup });
|
|
129
145
|
signal?.throwIfAborted();
|
|
130
|
-
const candidate = pick(catalog);
|
|
131
|
-
if (!candidate) throw noCandidateError(catalog);
|
|
132
146
|
if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'No public route was started because consent was not given.'), { tryKind: 'consent' });
|
|
147
|
+
signal?.throwIfAborted();
|
|
148
|
+
const discard = async handle => {
|
|
149
|
+
if (remember || !handle) return;
|
|
150
|
+
const cleanup = await closeExactRoute(gozar, { home: query.home, handle });
|
|
151
|
+
if (!cleanup.removed) {
|
|
152
|
+
const debt = new RouteError('cleanup_debt', `Gozar could not confirm removal of ${safeDiagnostic(handle.kind, 24)} ${safeDiagnostic(handle.id, 160)} (generation ${handle.generation}). ${cleanup.detail}`);
|
|
153
|
+
throw Object.assign(debt, { handle });
|
|
154
|
+
}
|
|
155
|
+
};
|
|
133
156
|
let view;
|
|
134
|
-
try {
|
|
157
|
+
try {
|
|
158
|
+
view = await dispatchRouteOperation(query, recovery, remember,
|
|
159
|
+
request => gozar.expose({ ...request, approval: approvalFor(candidate), wait }));
|
|
160
|
+
} catch (error) {
|
|
161
|
+
await discard(error.route?.handle);
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
135
164
|
const handle = view?.handle;
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
165
|
+
let url; try { url = new URL(view?.origin); } catch { /* rejected below */ }
|
|
166
|
+
if (!handle || !url || url.protocol !== 'https:' || url.origin !== view.origin || (wait === 'verified' && !isPublished(view))) {
|
|
167
|
+
await discard(handle);
|
|
168
|
+
throw routeFailure(view, 'Gozar did not return a verified HTTPS origin for this route.');
|
|
169
|
+
}
|
|
170
|
+
if (signal?.aborted) { await discard(handle); signal.throwIfAborted(); }
|
|
171
|
+
const route = monitorRoute({ gozar, home: query.home, view, candidate });
|
|
172
|
+
if (wait === 'verified') void route.watchPublished();
|
|
173
|
+
return route;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export const isPublished = view => view?.state === 'usable' && typeof view.published === 'string' &&
|
|
177
|
+
view.origin === view.published && view.verification?.status === 'verified';
|
|
178
|
+
|
|
179
|
+
export function routeFailure(view, message) {
|
|
180
|
+
return new RouteError('verification_failed', message, { nextAction: view?.binding?.remedy ?? null });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function routeEnding(route, type, origin) {
|
|
184
|
+
if (route.state === 'address_changed' || (route.origin && route.origin !== origin) || (route.published && route.published !== origin)) return 'rotated';
|
|
185
|
+
// Gozar reports expiry using its own clock. A local wall-clock change cannot end the route.
|
|
186
|
+
if (type === 'terminal' || route.routeState === 'expired' ||
|
|
187
|
+
['lost', 'released', 'suspended', 'suspending', 'releasing', 'handing-back'].includes(route.state)) return 'lost';
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function waitForPublication({ gozar, home, handle, origin, signal, timeoutMs }) {
|
|
192
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
193
|
+
const watchSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
194
|
+
let latest;
|
|
195
|
+
for await (const { route, type } of gozar.watchRoutes({ home, handle, signal: watchSignal })) {
|
|
196
|
+
latest = route;
|
|
197
|
+
if (routeEnding(route, type, origin) || route.state === 'uncertain' || route.consentChange) break;
|
|
198
|
+
if (isPublished(route) && route.published === origin) return route;
|
|
199
|
+
}
|
|
200
|
+
signal?.throwIfAborted();
|
|
201
|
+
throw routeFailure(latest, 'Gozar could not prove that the route reaches this bridge.');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Only a durable host write before the dispatch fence proves the SDK was never called.
|
|
205
|
+
export const routeNotDispatched = ref => ref.phase === 'prepared' && !ref.handle;
|
|
206
|
+
|
|
207
|
+
export function reconcileRouteOperationId(retained, observed) {
|
|
208
|
+
const retainedId = typeof retained === 'string' && retained.length > 0 ? retained : undefined;
|
|
209
|
+
const observedId = typeof observed === 'string' && observed.length > 0 ? observed : undefined;
|
|
210
|
+
if (retainedId && observedId && retainedId !== observedId) {
|
|
211
|
+
throw new RouteError('route_conflict', 'Gozar returned a different operation for the retained route.');
|
|
141
212
|
}
|
|
142
|
-
|
|
143
|
-
if (signal?.aborted) { await closeNow(); throw abortError(signal); }
|
|
144
|
-
return sessionRoute({ gozar, home: query.home, view, candidate });
|
|
213
|
+
return retainedId ?? observedId;
|
|
145
214
|
}
|
|
146
215
|
|
|
147
|
-
function
|
|
216
|
+
export async function observeRetainedRoute(gozar, ref) {
|
|
217
|
+
const { home, operationId, handle } = ref;
|
|
218
|
+
if (handle) {
|
|
219
|
+
try {
|
|
220
|
+
const view = await gozar.routeStatus({ home, handle });
|
|
221
|
+
if (!sameRouteHandle(view.handle, handle)) throw new RouteError('route_conflict', 'Gozar returned a different route handle.');
|
|
222
|
+
reconcileRouteOperationId(operationId, view.operationId);
|
|
223
|
+
return { state: 'recorded', view };
|
|
224
|
+
} catch (error) { if (!operationId || error.code !== 'route_not_found') throw error; }
|
|
225
|
+
}
|
|
226
|
+
if (routeNotDispatched(ref)) return { state: 'not-started' };
|
|
227
|
+
const { routes } = await gozar.listRoutes({ home, owner: OWNER });
|
|
228
|
+
const matches = routes.filter(route => route.operationId === operationId);
|
|
229
|
+
if (matches.length > 1) throw new RouteError('route_conflict', 'More than one Gozar route matches the retained operation.');
|
|
230
|
+
if (!matches.length) {
|
|
231
|
+
if (handle) throw new RouteError('route_not_found', 'Gozar could not read the retained handle. Its reference was kept.');
|
|
232
|
+
return { state: 'unobserved' };
|
|
233
|
+
}
|
|
234
|
+
const [view] = matches;
|
|
235
|
+
if (handle && !sameRouteHandle(view.handle, handle)) {
|
|
236
|
+
throw new RouteError('route_conflict', 'The retained operation was observed at a different route generation.');
|
|
237
|
+
}
|
|
238
|
+
return { state: 'recorded', view };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const PRE_ALLOCATION_REFUSALS = new Set(['candidate_stale', 'consent_expired', 'consent_mismatch', 'consent_required', 'consent_unknown']);
|
|
242
|
+
|
|
243
|
+
async function dispatchRouteOperation(query, recovery, remember, dispatch) {
|
|
244
|
+
const { home, operationId } = query;
|
|
245
|
+
if (!remember || !operationId) return dispatch(query);
|
|
246
|
+
const ref = { home, operationId };
|
|
247
|
+
if (!recovery) remember({ ...ref, phase: 'prepared' });
|
|
248
|
+
remember({ ...ref, phase: 'dispatching' });
|
|
249
|
+
try {
|
|
250
|
+
const view = await dispatch(query);
|
|
251
|
+
if (view?.handle) remember({ ...ref, handle: view.handle });
|
|
252
|
+
return view;
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (error.route?.handle) remember({ ...ref, handle: error.route.handle });
|
|
255
|
+
else if (!recovery?.handle && PRE_ALLOCATION_REFUSALS.has(error.code)) {
|
|
256
|
+
// A refusal before reservation leaves a handle-less reference ready to retry.
|
|
257
|
+
// The SDK supplies the retained view for refusals after reservation.
|
|
258
|
+
remember({ ...ref, phase: 'prepared' });
|
|
259
|
+
}
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const sameRouteHandle = (left, right) => left?.kind === right.kind && left?.id === right.id && left?.generation === right.generation;
|
|
265
|
+
|
|
266
|
+
const removalConfirmed = view => view?.state === 'released' && view.published === null && view.cleanup?.state === 'confirmed';
|
|
267
|
+
|
|
268
|
+
export async function closeExactRoute(gozar, { home, operationId, handle }) {
|
|
269
|
+
try {
|
|
270
|
+
if (!handle) {
|
|
271
|
+
const observed = await observeRetainedRoute(gozar, { home, operationId });
|
|
272
|
+
if (observed.state !== 'recorded') return { removed: false, detail: 'Gozar has not confirmed whether the retained operation started.' };
|
|
273
|
+
const retained = observed.view;
|
|
274
|
+
if (removalConfirmed(retained)) return { removed: true };
|
|
275
|
+
handle = retained.handle;
|
|
276
|
+
}
|
|
277
|
+
const closed = await gozar.closeRoute({ home, handle, mode: 'remove' });
|
|
278
|
+
if (!sameRouteHandle(closed.handle, handle)) {
|
|
279
|
+
return { removed: false, detail: 'Gozar returned cleanup evidence for a different handle.' };
|
|
280
|
+
}
|
|
281
|
+
if (removalConfirmed(closed)) return { removed: true };
|
|
282
|
+
const remedy = closed.cleanup.nextAction ?? closed.binding?.remedy;
|
|
283
|
+
const explanation = explainRouteError({ code: 'cleanup_debt', message: closed.cleanup.message, nextAction: remedy });
|
|
284
|
+
return { removed: false, detail: [explanation.line, explanation.fix].filter(Boolean).join(' ') };
|
|
285
|
+
} catch (error) {
|
|
286
|
+
// Gozar has no route for this exact handle (given, or observed from the operation): nothing is left to remove.
|
|
287
|
+
// Callers keep their receipt while removed is false, so reporting it as unremoved would never let a retry finish.
|
|
288
|
+
if (handle && error?.code === 'route_not_found') return { removed: true, detail: 'Gozar no longer has this route; nothing was left to remove.' };
|
|
289
|
+
return { removed: false, detail: explainRouteError(error).line };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function monitorRoute({ gozar, home, view, candidate, remove = true }) {
|
|
148
294
|
const { handle, origin } = view;
|
|
149
295
|
const watch = new AbortController();
|
|
150
|
-
let reason = null, resolveEnded;
|
|
296
|
+
let reason = null, resolveEnded, handoffFailure = null;
|
|
151
297
|
const exited = new Promise(resolve => { resolveEnded = resolve; });
|
|
152
298
|
const end = why => { if (reason === null) reason = why; resolveEnded(reason); };
|
|
153
|
-
|
|
299
|
+
let watcher;
|
|
300
|
+
const watchPublished = (onProof = () => {}) => watcher ??= (async () => {
|
|
301
|
+
let published;
|
|
154
302
|
try {
|
|
155
|
-
for await (const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
if (
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
303
|
+
for await (const { route, type } of gozar.watchRoutes({ home, handle, signal: watch.signal })) {
|
|
304
|
+
if (watch.signal.aborted) return;
|
|
305
|
+
const ending = routeEnding(route, type, origin);
|
|
306
|
+
if (ending) { end(ending); return; }
|
|
307
|
+
const next = isPublished(route);
|
|
308
|
+
if (published !== next) {
|
|
309
|
+
published = next;
|
|
310
|
+
try { await onProof(next); }
|
|
311
|
+
catch (cause) {
|
|
312
|
+
handoffFailure = new Error('Could not update the trial connection handoff.', { cause });
|
|
313
|
+
end('handoff_failed');
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
165
317
|
}
|
|
166
318
|
if (!watch.signal.aborted) end('lost');
|
|
167
|
-
} catch
|
|
319
|
+
} catch { if (!watch.signal.aborted) end('lost'); }
|
|
168
320
|
})();
|
|
169
321
|
let stopped = null;
|
|
170
322
|
return {
|
|
171
|
-
origin, handle, view, candidate, exited, endedBecause: () => reason,
|
|
172
|
-
stop() {
|
|
323
|
+
origin, handle, view, candidate, exited, watchPublished, endedBecause: () => reason, handoffFailure: () => handoffFailure,
|
|
324
|
+
stop() {
|
|
173
325
|
stopped ??= (async () => {
|
|
174
|
-
watch.abort();
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (closed.cleanup?.state === 'debt') return { removed: false, detail: `Gozar reports cleanup debt for this route: ${safeDiagnostic(closed.cleanup.message ?? 'no detail', 200)}. Run \`dalan setup\` to review it.` };
|
|
178
|
-
return closed.state === 'released' ? { removed: true } : { removed: false, detail: `Gozar reports the route is ${closed.state}; its removal could not be confirmed.` };
|
|
179
|
-
} catch (error) {
|
|
180
|
-
if (error?.code === 'route_not_found') return { removed: true };
|
|
181
|
-
if (error?.code === 'route_conflict') return { removed: false, detail: 'Gozar reports a newer route replaced this one, so cleanup of this trial could not be confirmed. The replacement was left untouched.' };
|
|
182
|
-
return { removed: false, detail: `Gozar could not confirm the route removal (${explainRouteError(error).line}).` };
|
|
183
|
-
}
|
|
326
|
+
watch.abort();
|
|
327
|
+
await watcher;
|
|
328
|
+
return remove ? closeExactRoute(gozar, { home, handle }) : { removed: true };
|
|
184
329
|
})();
|
|
185
330
|
return stopped;
|
|
186
331
|
},
|
|
187
332
|
};
|
|
188
333
|
}
|
|
189
334
|
|
|
335
|
+
export async function chooseRoute({ gozar, query, pick = pickCandidate, setup, match }) {
|
|
336
|
+
const currentCatalog = async () => {
|
|
337
|
+
const catalog = await gozar.catalogRoutes(query);
|
|
338
|
+
if (!match) return catalog;
|
|
339
|
+
const candidates = catalog.candidates.filter(match);
|
|
340
|
+
if (!candidates.length) throw new RouteError('requirements_unsatisfied', 'Gozar offered no owner-managed route for this HTTPS origin and local listener.');
|
|
341
|
+
return { ...catalog, candidates };
|
|
342
|
+
};
|
|
343
|
+
let catalog = await currentCatalog();
|
|
344
|
+
let candidate = pick(catalog);
|
|
345
|
+
if (setup) {
|
|
346
|
+
const selected = candidate ?? catalog.candidates.filter(c => c.eligible && c.setup.state === 'action-required').sort((a, b) => a.rank - b.rank)[0];
|
|
347
|
+
if (selected) {
|
|
348
|
+
if (!await setup(selected)) throw new RouteError('setup_required', 'The current Gozar setup operation still needs attention.');
|
|
349
|
+
if (!candidate) {
|
|
350
|
+
catalog = await currentCatalog();
|
|
351
|
+
candidate = pick(catalog);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (!candidate) throw noCandidateError(catalog);
|
|
356
|
+
return { candidate, catalog };
|
|
357
|
+
}
|
|
358
|
+
|
|
190
359
|
function noCandidateError(catalog) {
|
|
191
360
|
const needsSetup = catalog.candidates.find(c => c.setup.state === 'action-required');
|
|
192
361
|
if (needsSetup) return new RouteError('setup_required', 'A route needs one setup step before it can start.', { nextAction: needsSetup.setup.actions[0] ?? null });
|
|
@@ -196,23 +365,34 @@ function noCandidateError(catalog) {
|
|
|
196
365
|
|
|
197
366
|
// ---- durable routes and external services ----------------------------------------------------------------------------------------------
|
|
198
367
|
// A durable route is never closed by an app exit. The first allocation asks once (the pin keeps the consent); a later call reuses it.
|
|
199
|
-
export async function ensureDurableRoute({ gozar, query, consent, reconsent = false, pick = pickCandidate }) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
368
|
+
export async function ensureDurableRoute({ gozar, query, consent, reconsent = false, pick = pickCandidate, setup, remember, recovery, external = false }) {
|
|
369
|
+
const options = reconsent ? { reconsent: true } : {};
|
|
370
|
+
if (!recovery && !external) {
|
|
371
|
+
try { return await gozar.ensureRoute({ ...query, ...options }); }
|
|
372
|
+
catch (error) { if (!['consent_required', 'setup_required'].includes(error?.code)) throw error; }
|
|
373
|
+
}
|
|
374
|
+
const match = external ? candidate => candidate.ownership === 'external-owned' &&
|
|
375
|
+
candidate.consent?.disclosures?.ownership === 'external-owned' &&
|
|
376
|
+
typeof query.origin === 'string' && candidate.consent.scope?.query?.expectedOrigin === query.origin &&
|
|
377
|
+
candidate.consent.scope.query.target === query.target : undefined;
|
|
378
|
+
const { candidate, catalog } = await chooseRoute({ gozar, query, pick, setup, match });
|
|
205
379
|
if (!await consent(candidate, catalog)) throw Object.assign(new RouteError('consent_required', 'The route was not started because consent was not given.'), { tryKind: 'consent' });
|
|
206
|
-
|
|
380
|
+
const operationId = recovery?.operationId ?? (remember ? randomUUID() : undefined);
|
|
381
|
+
const request = operationId ? { ...query, operationId } : query;
|
|
382
|
+
return dispatchRouteOperation(request, recovery, remember,
|
|
383
|
+
approved => gozar.ensureRoute({ ...approved, approval: approvalFor(candidate), ...options }));
|
|
207
384
|
}
|
|
208
385
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
386
|
+
export function requireExternalRoute(view, origin, target) {
|
|
387
|
+
const observedTarget = view?.hostConfiguration?.target;
|
|
388
|
+
const subject = view?.verification?.subject;
|
|
389
|
+
if (view?.ownership !== 'external-owned' || view.origin !== origin || !observedTarget?.known || observedTarget.value !== target) {
|
|
390
|
+
throw routeFailure(view, 'Gozar returned a route that does not match the requested existing address and listener.');
|
|
391
|
+
}
|
|
392
|
+
if (isPublished(view) && (subject?.origin !== origin || subject.target !== target ||
|
|
393
|
+
!view.handle || subject.handleGeneration !== view.handle.generation)) {
|
|
394
|
+
throw routeFailure(view, 'Gozar returned publication proof for a different address, listener or generation.');
|
|
395
|
+
}
|
|
216
396
|
}
|
|
217
397
|
|
|
218
398
|
// ---- the Host a bridge accepts -----------------------------------------------------------------------------------------------------------
|
|
@@ -240,13 +420,35 @@ export async function migrateLegacyRoute({
|
|
|
240
420
|
}) {
|
|
241
421
|
const hand = { from: `${OWNER}-legacy`, generation };
|
|
242
422
|
const q = (extra = {}) => buildQuery({ home: gozarHome, target, usage: { kind: 'durable', routeId }, route: routeName, origin, address: 'stable', ...extra });
|
|
243
|
-
const journal = phase => writeJournal({ phase, generation, origin, routeId }, env);
|
|
244
|
-
|
|
245
|
-
|
|
423
|
+
const journal = (phase, extra = {}) => writeJournal({ phase, generation, origin, routeId, ...extra }, env);
|
|
424
|
+
const adoptionUnknown = () => Object.assign(new Error('Route adoption outcome is unknown. The old route remains fenced and the recovery journal was kept. Rerun migration to reconcile the existing route; do not start a new adoption until the provider confirms its state.'), { code: 'migration_adoption_unknown' });
|
|
425
|
+
// Before adoption, lifting the fence leaves the old ingress and sign-in state as found.
|
|
426
|
+
const rollback = async () => {
|
|
427
|
+
try { await unfence(); }
|
|
428
|
+
catch (cause) {
|
|
429
|
+
// An incomplete unwind is not a clean refusal. Keep the journal for the next attempt.
|
|
430
|
+
throw Object.assign(new Error('Route migration rollback failed; recovery journal retained.', { cause }),
|
|
431
|
+
{ code: 'migration_rollback_failed' });
|
|
432
|
+
}
|
|
433
|
+
removeJournal(env);
|
|
434
|
+
};
|
|
435
|
+
const halt = async (reason, extra = {}) => {
|
|
436
|
+
await rollback();
|
|
437
|
+
return { migrated: false, reason, ...extra };
|
|
438
|
+
};
|
|
246
439
|
|
|
247
440
|
const existing = readJournal(env);
|
|
441
|
+
if (existing && (existing.routeId !== routeId || existing.origin !== origin)) {
|
|
442
|
+
throw new Error('A different route migration has a recovery journal. Finish that recovery first.');
|
|
443
|
+
}
|
|
248
444
|
if (existing?.phase === 'dalan-committed') { removeJournal(env); return { migrated: true, resumed: true }; }
|
|
249
|
-
|
|
445
|
+
if (existing?.transfer) {
|
|
446
|
+
await unfence();
|
|
447
|
+
await gozar.confirmHandBack({ routeId, transfer: existing.transfer, home: gozarHome });
|
|
448
|
+
removeJournal(env);
|
|
449
|
+
return { migrated: false, reason: 'the existing sign-in did not work through the new route; the old route was handed back' };
|
|
450
|
+
}
|
|
451
|
+
if (!existing) { journal('prepared'); crash('after-prepared'); }
|
|
250
452
|
|
|
251
453
|
// Already adopted by an earlier, interrupted run? An ensure without approval returns an existing pin and can never create one.
|
|
252
454
|
let adopted = null;
|
|
@@ -254,20 +456,37 @@ export async function migrateLegacyRoute({
|
|
|
254
456
|
try { const view = await gozar.ensureRoute(q()); if (view.origin === origin) adopted = view; }
|
|
255
457
|
catch (error) { if (error?.code !== 'consent_required' && error?.code !== 'route_not_found') throw error; }
|
|
256
458
|
}
|
|
459
|
+
if (!adopted && (existing?.adoptionDispatched === true || existing?.phase === 'gozar-adopted')) throw adoptionUnknown();
|
|
257
460
|
if (!adopted) {
|
|
258
461
|
// Gozar reads the old state where it was written: lift an earlier fence, inspect, then fence again.
|
|
259
462
|
await unfence();
|
|
463
|
+
if (existing) { journal('prepared'); crash('after-prepared'); }
|
|
260
464
|
const inspected = await gozar.inspectLegacyRoute({ home: gozarHome, owner: OWNER, source: { stateFiles: stateFiles() }, origin, target });
|
|
261
465
|
if (inspected.state !== 'adoptable') return halt(inspected.reasonCode ?? inspected.state, { nextAction: inspected.nextAction ?? null });
|
|
262
466
|
try { await fence(); } catch (error) { return halt(`the old exposure could not be fenced (${safeDiagnostic(error.message, 160)})`); }
|
|
263
467
|
crash('after-fence'); journal('old-owner-fenced'); crash('after-fence-journal');
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
468
|
+
let request;
|
|
469
|
+
try {
|
|
470
|
+
const intent = q({ intent: 'adopt', migrationRef: inspected.migrationRef });
|
|
471
|
+
const catalog = await gozar.catalogRoutes(intent);
|
|
472
|
+
const candidate = pickCandidate(catalog);
|
|
473
|
+
if (!candidate) return halt('Gozar offered no route to adopt this origin');
|
|
474
|
+
if (!await consent(candidate, catalog)) return halt('adoption was not approved');
|
|
475
|
+
request = { ...intent, origin, approval: approvalFor(candidate), handover: hand };
|
|
476
|
+
} catch (error) {
|
|
477
|
+
await rollback();
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
// Record the dispatch before it can reach the provider. Absence on a later
|
|
481
|
+
// read is not proof that a previously dispatched operation did not commit.
|
|
482
|
+
journal('old-owner-fenced', { adoptionDispatched: true });
|
|
483
|
+
try { adopted = await gozar.adoptRoute(request); }
|
|
484
|
+
catch (error) {
|
|
485
|
+
if (PRE_ALLOCATION_REFUSALS.has(error?.code) && !error?.view && !error?.handle) {
|
|
486
|
+
return halt(`Gozar did not adopt the route (${explainRouteError(error).line}); the old route is unchanged`);
|
|
487
|
+
}
|
|
488
|
+
throw adoptionUnknown();
|
|
489
|
+
}
|
|
271
490
|
crash('after-adopt');
|
|
272
491
|
}
|
|
273
492
|
journal('gozar-adopted'); crash('after-adopt-journal');
|