@tnunamak/dalan 0.8.0 → 0.8.2
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 +70 -1
- package/CONTRIBUTING.md +2 -0
- package/PROTOCOL.md +6 -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 +215 -40
- 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 +3 -2
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +78 -14
- package/docs/pull-workers.md +11 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +6 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/t3-wake-fence-r4.md +1 -1
- package/docs/test-suite-isolation.md +8 -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 +35 -9
- 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/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +29 -10
- 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/inbox.mjs +13 -3
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +104 -11
- 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 +285 -19
- 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 +619 -88
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +64 -19
- package/src/service-update.mjs +193 -48
- 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/status-summary.mjs +3 -0
- package/src/store.mjs +1086 -127
- 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 +49 -4
- 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/as-store.mjs
CHANGED
|
@@ -55,6 +55,8 @@ export class AsStore {
|
|
|
55
55
|
CREATE INDEX IF NOT EXISTS oidc_expiry ON oidc(expires_at) WHERE expires_at IS NOT NULL;
|
|
56
56
|
CREATE TABLE IF NOT EXISTS refresh_receipts(
|
|
57
57
|
grant_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, deadline INTEGER NOT NULL, payload TEXT NOT NULL) WITHOUT ROWID;
|
|
58
|
+
CREATE TABLE IF NOT EXISTS refresh_heads(
|
|
59
|
+
grant_id TEXT PRIMARY KEY, payload TEXT NOT NULL, prev_id TEXT, rotated_at INTEGER) WITHOUT ROWID;
|
|
58
60
|
CREATE TABLE IF NOT EXISTS static_clients(client_id TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
59
61
|
CREATE TABLE IF NOT EXISTS connections(
|
|
60
62
|
connection_id TEXT PRIMARY KEY, worker TEXT NOT NULL, grant_id TEXT NOT NULL UNIQUE, client_id TEXT NOT NULL,
|
|
@@ -71,6 +73,9 @@ export class AsStore {
|
|
|
71
73
|
const columns = this.db.prepare('PRAGMA table_info(windows)').all().map(c => c.name);
|
|
72
74
|
if (!columns.includes('registrations')) this.db.exec('ALTER TABLE windows ADD COLUMN registrations INTEGER NOT NULL DEFAULT 0');
|
|
73
75
|
if (!columns.includes('generation')) this.db.exec('ALTER TABLE windows ADD COLUMN generation TEXT');
|
|
76
|
+
const headColumns = this.db.prepare('PRAGMA table_info(refresh_heads)').all().map(c => c.name);
|
|
77
|
+
if (!headColumns.includes('prev_id')) this.db.exec('ALTER TABLE refresh_heads ADD COLUMN prev_id TEXT');
|
|
78
|
+
if (!headColumns.includes('rotated_at')) this.db.exec('ALTER TABLE refresh_heads ADD COLUMN rotated_at INTEGER');
|
|
74
79
|
try { this.#initializeCodec(); } catch { this.db.close(); throw new Error('as: encrypted storage could not be opened'); }
|
|
75
80
|
this.onGrantRevoked = () => {};
|
|
76
81
|
const self = this;
|
|
@@ -196,6 +201,34 @@ export class AsStore {
|
|
|
196
201
|
if (!row || row.deadline <= this.now()) return undefined;
|
|
197
202
|
return { ...row, value: JSON.parse(this.#open(row.payload, `refresh-receipt:${row.grant_id}`)) };
|
|
198
203
|
}
|
|
204
|
+
// The grant's current head refresh token, sealed, with the id of the one token rotated away to make it. Only that token,
|
|
205
|
+
// presented within windowMs of the rotation (never before it: a clock step back is refused), is answered with the head.
|
|
206
|
+
reuseHead(grantId, tokenValue, windowMs) {
|
|
207
|
+
const row = this.db.prepare('SELECT payload,prev_id,rotated_at FROM refresh_heads WHERE grant_id=?').get(grantId);
|
|
208
|
+
if (!row || row.rotated_at === null) return undefined;
|
|
209
|
+
const age = this.now() - row.rotated_at;
|
|
210
|
+
if (age < 0 || age > windowMs || row.prev_id !== this.#id('RefreshToken', tokenValue)) return undefined;
|
|
211
|
+
return { head: this.#open(row.payload, `refresh-head:${grantId}`), age };
|
|
212
|
+
}
|
|
213
|
+
// Commit-time fence for a tolerated reuse, like commitRefresh: nothing it read may have changed, the connection must still be
|
|
214
|
+
// live, and the head must still be the one served. Only then are the staged access-token writes stored.
|
|
215
|
+
commitReuse(exchange, grantId, clientId, head, windowMs) {
|
|
216
|
+
this.tx(() => {
|
|
217
|
+
for (const [model, id, original] of exchange.reads) {
|
|
218
|
+
if (JSON.stringify(this.find(model, id)) !== original) throw new errors.InvalidGrant('refresh state changed');
|
|
219
|
+
}
|
|
220
|
+
const connection = this.connectionByGrant(grantId);
|
|
221
|
+
const grant = this.find('Grant', grantId);
|
|
222
|
+
if (!connection || connection.revoked_at !== null || connection.client_id !== clientId || !grant || grant.clientId !== clientId) throw new errors.InvalidGrant('grant inactive');
|
|
223
|
+
const row = this.db.prepare('SELECT payload,rotated_at FROM refresh_heads WHERE grant_id=?').get(grantId);
|
|
224
|
+
const age = row?.rotated_at == null ? -1 : this.now() - row.rotated_at;
|
|
225
|
+
if (!row || age < 0 || age > windowMs || this.#open(row.payload, `refresh-head:${grantId}`) !== head) throw new errors.InvalidGrant('refresh state changed');
|
|
226
|
+
for (const [op, model, id, payload, ttl] of exchange.writes) {
|
|
227
|
+
if (op !== 'upsert' || model !== 'AccessToken') throw new errors.InvalidGrant('refresh state changed');
|
|
228
|
+
this.upsert(model, id, payload, ttl);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
199
232
|
refreshValid(grantId, clientId, successor) {
|
|
200
233
|
const connection = this.connectionByGrant(grantId);
|
|
201
234
|
const grant = this.find('Grant', grantId);
|
|
@@ -226,6 +259,11 @@ export class AsStore {
|
|
|
226
259
|
this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=? OR grant_id=?').run(this.now(), grantId);
|
|
227
260
|
this.db.prepare('INSERT INTO refresh_receipts VALUES(?,?,?,?)').run(grantId, this.#id('RefreshToken', token), deadline,
|
|
228
261
|
this.#seal(JSON.stringify({ clientId, params, response }), `refresh-receipt:${grantId}`));
|
|
262
|
+
// No rotated token in the response means no head to serve; a stale head must not outlive it.
|
|
263
|
+
if (typeof response?.refresh_token === 'string') {
|
|
264
|
+
this.db.prepare('INSERT INTO refresh_heads VALUES(?,?,?,?) ON CONFLICT(grant_id) DO UPDATE SET payload=excluded.payload,prev_id=excluded.prev_id,rotated_at=excluded.rotated_at')
|
|
265
|
+
.run(grantId, this.#seal(response.refresh_token, `refresh-head:${grantId}`), this.#id('RefreshToken', token), this.now());
|
|
266
|
+
} else this.db.prepare('DELETE FROM refresh_heads WHERE grant_id=?').run(grantId);
|
|
229
267
|
});
|
|
230
268
|
}
|
|
231
269
|
|
|
@@ -268,6 +306,7 @@ export class AsStore {
|
|
|
268
306
|
#revokeGrantRows(grantId, reason, now = this.now()) {
|
|
269
307
|
this.db.prepare('DELETE FROM oidc WHERE grant_id=?').run(grantId);
|
|
270
308
|
this.db.prepare("DELETE FROM oidc WHERE model='Grant' AND id=?").run(grantId);
|
|
309
|
+
this.db.prepare('DELETE FROM refresh_heads WHERE grant_id=?').run(grantId);
|
|
271
310
|
this.db.prepare('UPDATE connections SET revoked_at=?,revoked_reason=? WHERE grant_id=? AND revoked_at IS NULL').run(now, reason, grantId);
|
|
272
311
|
}
|
|
273
312
|
// The one revocation path: tokens, codes and the Grant record go, and the connection row is marked. Idempotent.
|
|
@@ -311,6 +350,7 @@ export class AsStore {
|
|
|
311
350
|
purge() {
|
|
312
351
|
const now = this.now();
|
|
313
352
|
this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=?').run(now);
|
|
353
|
+
this.db.prepare('DELETE FROM refresh_heads WHERE grant_id NOT IN (SELECT grant_id FROM connections WHERE revoked_at IS NULL)').run();
|
|
314
354
|
const expired = this.db.prepare('DELETE FROM oidc WHERE expires_at IS NOT NULL AND expires_at<=?').run(now).changes;
|
|
315
355
|
// Registered clients that never got a connection are dropped after a day: anonymous registration must not grow without bound.
|
|
316
356
|
const stale = this.db.prepare(`DELETE FROM oidc WHERE model='Client' AND created_at<? AND id NOT IN (SELECT client_id FROM static_clients) AND id NOT IN (SELECT client_id FROM connections)
|
|
@@ -322,12 +362,14 @@ export class AsStore {
|
|
|
322
362
|
|
|
323
363
|
// ---- pairing window --------------------------------------------------------------------------------------------
|
|
324
364
|
openWindow(worker, minutes) {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
.
|
|
330
|
-
|
|
365
|
+
return this.tx(() => {
|
|
366
|
+
const now = this.now(), open = this.window();
|
|
367
|
+
if (open && open.worker !== worker) throw new Error(`a pairing window for ${open.worker} is open until ${new Date(open.expires_at).toISOString()}; stop it first`);
|
|
368
|
+
if (open) this.db.prepare('UPDATE windows SET expires_at=? WHERE id=1').run(now + minutes * 60000);
|
|
369
|
+
else this.db.prepare('INSERT INTO windows(id,worker,opened_at,expires_at,registrations,generation) VALUES(1,?,?,?,0,?) ON CONFLICT(id) DO UPDATE SET worker=excluded.worker,opened_at=excluded.opened_at,expires_at=excluded.expires_at,registrations=0,generation=excluded.generation')
|
|
370
|
+
.run(worker, now, now + minutes * 60000, randomUUID());
|
|
371
|
+
return this.window();
|
|
372
|
+
});
|
|
331
373
|
}
|
|
332
374
|
window() {
|
|
333
375
|
const row = this.db.prepare('SELECT * FROM windows WHERE id=1').get();
|
|
@@ -414,6 +456,9 @@ export class AsStore {
|
|
|
414
456
|
commitApproval({ code, worker, grantId, snapshot, replace }) {
|
|
415
457
|
return this.tx(() => {
|
|
416
458
|
const now = this.now();
|
|
459
|
+
const reserved = this.db.prepare("SELECT expires_at FROM pairings WHERE code=? AND state='approving'").get(code);
|
|
460
|
+
if (!reserved) throw new Error('pairing is no longer being approved');
|
|
461
|
+
if (!Number.isFinite(reserved.expires_at) || reserved.expires_at <= now) throw new Error('pairing approval expired');
|
|
417
462
|
// Removal and approval serialize here, so a delayed approval cannot recreate a connection after client removal.
|
|
418
463
|
if (!this.db.prepare("SELECT 1 FROM oidc WHERE model='Client' AND id=?").get(snapshot.client_id)) throw new Error('client was removed');
|
|
419
464
|
let replaced = null;
|
package/src/as.mjs
CHANGED
|
@@ -3,7 +3,7 @@ const GRANT_TYPES = ['authorization_code', 'refresh_token', 'client_credentials'
|
|
|
3
3
|
const TOKEN_PARAMS = ['grant_type', 'code', 'redirect_uri', 'client_id', 'client_secret', 'code_verifier', 'refresh_token', 'scope', 'resource', 'client_assertion', 'client_assertion_type'];
|
|
4
4
|
import { Provider, errors } from 'oidc-provider';
|
|
5
5
|
import { ACCEPTED_SCOPES, ADVERTISED_SCOPES, canonicalScopes } from './scopes.mjs';
|
|
6
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
7
|
import { performance } from 'node:perf_hooks';
|
|
8
8
|
import { acquireAsOwner, asFiles, LIFETIMES, PAIRING_MINUTES, loadAsConfig, loadKeys, isLoopbackCallback, matchesCallback, parseAsConfig, parseCallbackPattern, parseNativeLoopback, saveAsCallbacks, untrusted } from './as-files.mjs';
|
|
9
9
|
import { AsStore, LIMITS, normalizeCode, showCode } from './as-store.mjs';
|
|
@@ -16,6 +16,10 @@ import { approvalFacts, approvalRecord, describeClient } from './client-approval
|
|
|
16
16
|
export const SCOPES = ADVERTISED_SCOPES;
|
|
17
17
|
export const ACCOUNT = 'owner';
|
|
18
18
|
const ACCESS_TOKEN_TTL = 3600;
|
|
19
|
+
// The token rotated away one step ago, presented this soon after, is a concurrent holder of the connection, not a replay
|
|
20
|
+
// (Okta rotation grace period, Auth0 rotation overlap). Measured need: stale holders arrived 38 s and 175 s late; Okta allows 0-60 s.
|
|
21
|
+
// DALAN_REFRESH_REUSE_WINDOW_MS overrides it (clamped to 1 s .. 1 h) so tests can cross the window quickly.
|
|
22
|
+
export const REUSE_WINDOW_MS = Math.min(3600000, Math.max(1000, Number(process.env.DALAN_REFRESH_REUSE_WINDOW_MS) || 5 * 60 * 1000));
|
|
19
23
|
const OFF = Object.freeze({ enabled: false });
|
|
20
24
|
const html = text => String(text).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
21
25
|
export { untrusted };
|
|
@@ -107,7 +111,8 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
107
111
|
scopes: [...ACCEPTED_SCOPES],
|
|
108
112
|
pkce: { required: () => true }, // S256 is the only method the library supports
|
|
109
113
|
ttl: { AuthorizationCode: 600, AccessToken: ACCESS_TOKEN_TTL, RefreshToken: 30 * 86400, Grant: 90 * 86400, Interaction: LIFETIMES.interaction, Session: LIFETIMES.session, IdToken: LIFETIMES.idToken, ClientCredentials: 600, DeviceCode: 600 },
|
|
110
|
-
|
|
114
|
+
// A reuse inside the window answers with the current head and must not rotate it again.
|
|
115
|
+
rotateRefreshToken: async ctx => !ctx.dalanReuseHead,
|
|
111
116
|
// A connection is the owner's approval, not a browser login: its tokens must not die with the pairing session.
|
|
112
117
|
// oidc-provider's default binds them to the session unless the client asks for offline_access. Revocation stays per connection.
|
|
113
118
|
expiresWithSession: async () => false,
|
|
@@ -171,7 +176,22 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
171
176
|
const receipt = source.consumed && store.refreshReceipt(tokenValue);
|
|
172
177
|
const retry = receipt && receipt.grant_id === source.grantId && receipt.value.clientId === clientId &&
|
|
173
178
|
receipt.value.params === fingerprint && store.refreshValid(source.grantId, clientId, receipt.value.response.refresh_token);
|
|
174
|
-
if (source.consumed && !retry)
|
|
179
|
+
if (source.consumed && !retry) {
|
|
180
|
+
// A concurrent holder of the same connection may present the one token that was rotated away moments ago. Inside the
|
|
181
|
+
// window, answer with a fresh access token and the current head, without rotating. Anything else the provider revokes.
|
|
182
|
+
const reuse = source.clientId === clientId && source.exp * 1000 > Date.now() ? store.reuseHead(source.grantId, tokenValue, REUSE_WINDOW_MS) : undefined;
|
|
183
|
+
if (reuse && store.refreshValid(source.grantId, clientId, reuse.head)) {
|
|
184
|
+
ctx.dalanReuseHead = reuse.head;
|
|
185
|
+
ctx.oidc.params.refresh_token = reuse.head;
|
|
186
|
+
// Staged like an ordinary refresh: nothing is stored or returned unless the commit-time checks still hold.
|
|
187
|
+
const staged = { reads: [], writes: [], retryToken: undefined };
|
|
188
|
+
await store.refreshExchange.run(staged, () => handler(ctx));
|
|
189
|
+
store.commitReuse(staged, source.grantId, clientId, reuse.head, REUSE_WINDOW_MS);
|
|
190
|
+
log({ kind: 'as_refresh_reuse_tolerated', age_ms: reuse.age });
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
return await handler(ctx);
|
|
194
|
+
}
|
|
175
195
|
const exchange = { reads: [], writes: [], retryToken: retry ? tokenValue : undefined };
|
|
176
196
|
try { await store.refreshExchange.run(exchange, () => handler(ctx)); }
|
|
177
197
|
catch (error) {
|
|
@@ -206,7 +226,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
206
226
|
if (!store.reserveRegistration()) return reject(429, 'temporarily_unavailable', 'Registration limit reached. Reuse the client this worker already registered. If you cannot, ask the owner to run dalan connect reset, then retry.');
|
|
207
227
|
if (Number(ctx.get('content-length')) > 8192) return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
|
|
208
228
|
const normalized = await normalizeRegistration(ctx.req);
|
|
209
|
-
if (normalized === 'too_large')
|
|
229
|
+
if (normalized === 'too_large') return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
|
|
210
230
|
if (normalized === 'invalid') return reject(400, 'invalid_request', 'The registration body must be a UTF-8 JSON object.');
|
|
211
231
|
let bytes = 0;
|
|
212
232
|
const count = chunk => { bytes += chunk.length; if (bytes > 8192) ctx.req.destroy(); };
|
|
@@ -391,11 +411,13 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
391
411
|
// The owner CLI never prints the bridge path secret (approve output checks this), so show the resource's origin and shape only.
|
|
392
412
|
const shownResource = resource => `${new URL(resource).origin}/<secret>/mcp`;
|
|
393
413
|
const shownIssuer = `${publicUrl.origin}/<secret>/oauth`; // the issuer carries the secret path prefix too
|
|
414
|
+
const fingerprint = value => createHash('sha256').update(value).digest('base64url');
|
|
394
415
|
const pendingView = pairing => {
|
|
395
416
|
const shown = describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: '', scopes: [] });
|
|
396
417
|
return {
|
|
397
418
|
code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
|
|
398
419
|
native: isLoopbackCallback(new URL(pairing.redirect_uri)),
|
|
420
|
+
interaction_fingerprint: fingerprint(pairing.uid),
|
|
399
421
|
redirect_uri: pairing.redirect_uri, redirect_host: shown.redirect_host, redirect_origin: shown.redirect_origin, redirect_punycode: shown.redirect_punycode, known_client: shown.known_client,
|
|
400
422
|
resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
|
|
401
423
|
expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
|
|
@@ -443,7 +465,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
443
465
|
stop() { return { closed: store.closeWindow() }; },
|
|
444
466
|
pending() {
|
|
445
467
|
const window = store.window();
|
|
446
|
-
return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, pending: window ? supersede(store.pendingPairings().filter(p => p.worker === window.worker).map(pendingView)) : [] };
|
|
468
|
+
return { authorization_endpoint_fingerprint: fingerprint(issuer + '/auth'), window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, pending: window ? supersede(store.pendingPairings().filter(p => p.worker === window.worker).map(pendingView)) : [] };
|
|
447
469
|
},
|
|
448
470
|
async approve({ code, worker, replace = false, confirm_redirect: confirmRedirect }) {
|
|
449
471
|
if (typeof code !== 'string' || normalizeCode(code).length !== 8) throw new Error('invalid pairing code');
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Catalog preflight only. Stop writers before using this snapshot to switch catalogs.
|
|
3
|
+
// It neither changes catalogs nor settles answers.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
8
|
+
import { journalPath, readJournal } from './answer-journal.mjs';
|
|
9
|
+
|
|
10
|
+
function unknownSends(receiptsDir) {
|
|
11
|
+
let directories;
|
|
12
|
+
try { directories = fs.readdirSync(receiptsDir, { withFileTypes: true }); }
|
|
13
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
14
|
+
const sends = [];
|
|
15
|
+
// src/answer-journal.mjs#journalPath: <job>.answers/<encoded question>.json.
|
|
16
|
+
for (const directory of directories.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
17
|
+
if (!directory.name.endsWith('.answers')) continue;
|
|
18
|
+
if (!directory.isDirectory()) throw new Error('answer journal directory is not a regular directory');
|
|
19
|
+
const job = directory.name.slice(0, -'.answers'.length);
|
|
20
|
+
const dir = path.join(receiptsDir, directory.name);
|
|
21
|
+
for (const file of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
22
|
+
if (!file.name.endsWith('.json')) continue; // Unpublished stage files are not journal entries.
|
|
23
|
+
if (!file.isFile()) throw new Error('answer journal is not a regular file');
|
|
24
|
+
const questionId = decodeURIComponent(file.name.slice(0, -'.json'.length));
|
|
25
|
+
const filename = path.join(dir, file.name);
|
|
26
|
+
if (journalPath(receiptsDir, job, questionId) !== filename) throw new Error('noncanonical answer journal filename');
|
|
27
|
+
// Validate the complete envelope, but never expose answer text or command envelopes.
|
|
28
|
+
const entry = readJournal(filename, job, questionId);
|
|
29
|
+
if (!entry) throw new Error('answer journal disappeared during inventory; retry with writers stopped');
|
|
30
|
+
if (entry.state !== 'committed') {
|
|
31
|
+
sends.push({ job: entry.job, question_id: entry.question_id, state: entry.state });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return sends;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function inventory({ dataRoot, receiptsDir = path.join(dataRoot, 'receipts') }) {
|
|
39
|
+
// src/restore-check.mjs#db: readOnly prevents creation and Store migrations.
|
|
40
|
+
const db = new DatabaseSync(path.join(dataRoot, 'bridge.db'), { readOnly: true });
|
|
41
|
+
try {
|
|
42
|
+
db.exec('BEGIN');
|
|
43
|
+
// src/store.mjs#Store.constructor creates assignments.
|
|
44
|
+
// src/store.mjs#Store.answerQuestionInTransaction treats finished/cancelled as terminal.
|
|
45
|
+
const open_jobs = db.prepare("SELECT request_id,status FROM assignments WHERE status NOT IN ('finished','cancelled') ORDER BY request_id").all().map(row => ({ ...row }));
|
|
46
|
+
// src/store.mjs#Store.migrate creates job_questions.
|
|
47
|
+
// src/store.mjs#Store.answerQuestionInTransaction saves answer/answered_at together.
|
|
48
|
+
// Include unanswered audit questions on finished jobs; do not silently discard them.
|
|
49
|
+
const open_questions = db.prepare('SELECT request_id AS job,question_id FROM job_questions WHERE answer IS NULL ORDER BY request_id,question_id').all().map(row => ({ ...row }));
|
|
50
|
+
// src/store.mjs#Store.assertRegrantReady: terminal jobs can still own host effects.
|
|
51
|
+
const open_checks = db.prepare("SELECT id,request_id AS job,check_id,status,stop_verified FROM check_jobs WHERE status='running' OR stop_verified IS NOT 1 ORDER BY request_id,id").all().map(row => ({ ...row }));
|
|
52
|
+
// src/store.mjs#Store.finishOnce enqueues result delivery after marking a job finished.
|
|
53
|
+
const pending_deliveries = db.prepare("SELECT id,request_id AS job,kind,state FROM notifications WHERE state IN ('pending','sending','failed','uncertain','uncertain_terminal') AND kind IN ('t3','blocker','watch') ORDER BY request_id,id").all().map(row => ({ ...row }));
|
|
54
|
+
const unknown_sends = unknownSends(receiptsDir);
|
|
55
|
+
db.exec('COMMIT');
|
|
56
|
+
return { open_jobs, open_questions, open_checks, pending_deliveries, unknown_sends, safe_to_switch: !open_jobs.length && !open_questions.length && !open_checks.length && !pending_deliveries.length && !unknown_sends.length };
|
|
57
|
+
} finally { db.close(); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
61
|
+
const [dataRoot, extra] = process.argv.slice(2);
|
|
62
|
+
try {
|
|
63
|
+
if (!dataRoot || extra !== undefined) throw new Error('usage: node src/catalog-switch-inventory.mjs DATA_ROOT');
|
|
64
|
+
process.stdout.write(JSON.stringify(inventory({ dataRoot })) + '\n');
|
|
65
|
+
} catch {
|
|
66
|
+
// Fail closed. No success-shaped JSON and no answer content on an unreadable input.
|
|
67
|
+
process.stderr.write('catalog-switch-inventory: inventory unavailable; check arguments, database and answer journals. Nothing was changed.\n');
|
|
68
|
+
process.exitCode = 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
package/src/check-response.mjs
CHANGED
|
@@ -5,8 +5,11 @@ export async function checkResponse(work, running, {
|
|
|
5
5
|
schedule = setTimeout,
|
|
6
6
|
cancel = clearTimeout,
|
|
7
7
|
} = {}) {
|
|
8
|
-
if (!Number.isFinite(responseMs) || responseMs < 0)
|
|
8
|
+
if (!Number.isFinite(responseMs) || responseMs < 0) {
|
|
9
|
+
// Observe rejected work even when the response budget is invalid.
|
|
10
|
+
Promise.resolve(work).catch(() => {});
|
|
9
11
|
throw new TypeError('responseMs must be a non-negative finite number');
|
|
12
|
+
}
|
|
10
13
|
let timer;
|
|
11
14
|
try {
|
|
12
15
|
return await Promise.race([
|
|
@@ -27,7 +27,7 @@ export function createClaimCommands({db,authorize,clock=Date.now,maxLeaseMs=3600
|
|
|
27
27
|
if(result.changes!==1)fail('revision_conflict');
|
|
28
28
|
return expected+1;
|
|
29
29
|
}
|
|
30
|
-
function execute(command,mutate) {
|
|
30
|
+
function execute(command,mutate,{leaseCapMs=maxLeaseMs}={}) {
|
|
31
31
|
tx();
|
|
32
32
|
const {job,subject,worker,claim,epoch,operation,key,expectedRevision,args}=command;
|
|
33
33
|
if(![job,subject,worker,claim,operation,key].every(str)||!nat(epoch)||epoch<1||!nat(expectedRevision)||typeof mutate!=='function')fail('invalid_command');
|
|
@@ -38,7 +38,8 @@ export function createClaimCommands({db,authorize,clock=Date.now,maxLeaseMs=3600
|
|
|
38
38
|
const old=db.prepare('SELECT identity,result FROM claim_command_receipts WHERE job=? AND command_key=?').get(job,key);
|
|
39
39
|
if(old){if(old.identity!==identity)fail('command_conflict');return JSON.parse(old.result);}
|
|
40
40
|
const decision=decide({revision:revision(job)},{expectedRevision,operation,args},{now,maxLeaseMs});
|
|
41
|
-
|
|
41
|
+
// Keep the requested duration in command identity while applying owner policy to the deadline.
|
|
42
|
+
const leaseUntil=decision.leaseUntil===undefined?undefined:Math.min(decision.leaseUntil,now+leaseCapMs);
|
|
42
43
|
// No arbitrary worker callback: parent injects the trusted Store mutation.
|
|
43
44
|
const nextRevision=advance(job,decision.effects[0].expectedRevision);
|
|
44
45
|
const value=mutate({command,now,revision:nextRevision,...(leaseUntil===undefined?{}:{leaseUntil})});
|
package/src/cli-help.mjs
CHANGED
|
@@ -6,6 +6,10 @@ import { docsUrl } from './docs-url.mjs';
|
|
|
6
6
|
// commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
|
|
7
7
|
// `dalan help --internal`. Every command runs and has its own help either way.
|
|
8
8
|
export const COMMANDS = [
|
|
9
|
+
{ name: 'jobs', summary: 'Read a versioned page of jobs', usage: 'dalan jobs --json [--worker W] [--status S] [--since T] [--kind K] [--source S] [--limit N] [--cursor C]', detail: ['Reads local state without changing it. Default page size 100, maximum 1000. Pass next_cursor to --cursor for the next page. --since filters creation time (Nh, Nd, RFC3339, or all). See docs/operations.md#stable-read-interface for fields and compatibility.'] },
|
|
10
|
+
{ name: 'events', summary: 'Read a versioned page of lifecycle events', usage: 'dalan events --json [--since T] [--worker W] [--type TYPE] [--limit N] [--cursor C]', detail: ['Reads retained lifecycle events in ID order without changing state. Default page size 100, maximum 1000. --since takes Nh, Nd, RFC3339, or all. Pass next_cursor to --cursor for the next page. See docs/operations.md#stable-read-interface.'] },
|
|
11
|
+
{ name: 'relationships', group: 'operator', summary: 'List or end relationships', usage: 'dalan relationships list | end RELATIONSHIP_ID [--json]', detail: ['Ending a relationship blocks new work; existing jobs and grants remain.'] },
|
|
12
|
+
{ name: 'grants', group: 'operator', summary: 'List authority held by each enforcer', usage: 'dalan grants [--json]', detail: ['Shows relationship and grant lifetimes independently.'] },
|
|
9
13
|
{ name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--route NAME]] [--home DIR] [--port N] [--callback PATTERN]...',
|
|
10
14
|
detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client (the default) or this computer only. For a hosted client, Dalan asks Gozar for a public HTTPS route, shows what Gozar says about it (who can read the traffic, whether the address is stable, what it costs), and asks for consent before anything is exposed.',
|
|
11
15
|
'Dalan checks the original public address and ends the trial when it detects a change or route loss. A temporary route lasts for the trial, 3 hours at most; Ctrl-C stops the run and Dalan asks Gozar to remove the route. If cleanup cannot be confirmed, it reports this. A route you saved with `dalan setup` is durable: ending the run never removes it. Keep private work out of a temporary demo.',
|
|
@@ -14,12 +18,12 @@ export const COMMANDS = [
|
|
|
14
18
|
' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
|
|
15
19
|
' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
|
|
16
20
|
'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a temporary public trial creates a new home, and a saved stable route uses ~/.local/share/dalan-hosted. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
|
|
17
|
-
{ name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME]',
|
|
21
|
+
{ name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME | --cancel OPERATION_ID]',
|
|
18
22
|
detail: ['Asks Gozar which routes can serve Dalan, shows what it returned, and saves your choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in.',
|
|
19
23
|
'With --route NAME, asks Gozar for the route with that name. Afterwards `dalan try --public` uses the saved route.', '', 'Example: dalan setup'] },
|
|
20
24
|
{ name: 'service', group: 'operator', summary: 'Install, update or inspect a long-running bridge service', usage: 'dalan service install|migrate-workers|update|auto-update|status [options]',
|
|
21
25
|
detail: ['Install the bridge as a background service that starts on its own, and publish it through a Gozar route.', '',
|
|
22
|
-
'Install: dalan service install --worker NAME --route NAME [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update] [--write-units-only]',
|
|
26
|
+
'Install: dalan service install --worker NAME [--route NAME] [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update] [--write-units-only]',
|
|
23
27
|
'With --route alone, Gozar supplies the public address and Dalan picks a loopback port. To use an HTTPS origin you already run, pass --public-url https://HOST --port N --target HOST:PORT instead, with optional [--lan-port N] [--verify-cmd COMMAND].',
|
|
24
28
|
'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
|
|
25
29
|
'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
|
|
@@ -40,6 +44,7 @@ export const COMMANDS = [
|
|
|
40
44
|
{ name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
|
|
41
45
|
detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
|
|
42
46
|
' approve CODE --worker NAME approve only the attempt with this code', ' [--confirm-redirect URI] required for a native client: the redirect you expect', ' [--replace] replace an existing connection for the worker',
|
|
47
|
+
' complete URL --worker NAME [--replace] [--json]', ' approve and finish a local loopback sign-in without a browser;', ' URL is the authorization URL the local client printed',
|
|
43
48
|
' list [--json] show connected workers', ' revoke NAME disconnect a worker', ' stop close the pairing window', ' reset clear pairing state',
|
|
44
49
|
' add-client --redirect-uri URI [--name NAME] [--json] register an OAuth client', ' clients [--json] list OAuth clients', ' remove-client CLIENT_ID [--json] remove an OAuth client',
|
|
45
50
|
' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
|
|
@@ -53,11 +58,16 @@ export const COMMANDS = [
|
|
|
53
58
|
' --queue-anyway queue even when the bridge would defer or warn', ' --refuse-defer fail instead of deferring',
|
|
54
59
|
' --allow-scope-prune when submit rejects the brief for naming files outside scope_paths, let it fix scope_paths and retry once',
|
|
55
60
|
' --execution none|worker|host execution capability for the job (default: the profile\'s default_execution, none for a new profile)',
|
|
56
|
-
' --require-capability LIST comma-separated backend capabilities the job needs (default: none)',
|
|
61
|
+
' --require-capability LIST comma-separated backend capabilities the job needs (default: none)',
|
|
62
|
+
' --revises REQUEST_ID this job corrects that job (one you submitted). It cancels nothing: a worker still on it is told, and its result can no longer be accepted or applied. Send a new --revision', ' --json print JSON', '',
|
|
57
63
|
'Examples (the first job):',
|
|
58
64
|
' dalan submit --worker local --execution none --deliver none --file first-job.json --json', ' dalan wait REQUEST_ID', ' dalan get REQUEST_ID', ' dalan decide REQUEST_ID accepted',
|
|
59
65
|
'', 'Example (a question that needs no files):', ' dalan submit --worker local --brief "What does a database index do?"', '',
|
|
60
66
|
'Replace REQUEST_ID with the request_id that submit prints. Read the report before you accept it.', `first-job.json and the full walk-through: ${docsUrl('docs/manual-setup.md', 'submit-finish-and-read-the-result')}`] },
|
|
67
|
+
{ name: 'forecast', summary: 'Preview a job’s admission without queuing it', usage: 'dalan forecast (--file PATH | --stdin | --brief TEXT) [options]',
|
|
68
|
+
detail: ['Runs the same admission checks as dalan submit --dry-run. Nothing is queued or reserved.', 'Use submit input and worker options. --json prints the admission report.'] },
|
|
69
|
+
{ name: 'correct', summary: 'Submit a corrected version of a job', usage: 'dalan correct REQUEST_ID (--file PATH | --stdin | --brief TEXT) [options]',
|
|
70
|
+
detail: ['Runs dalan submit --revises REQUEST_ID with the remaining submit arguments. It does not cancel the earlier job.'] },
|
|
61
71
|
{ name: 'status', group: 'everyday', summary: 'Show the bridge, queue and worker state', usage: 'dalan status [--explain] [--json]',
|
|
62
72
|
detail: ['Prints the bridge state.', '', 'Options:', ' --explain describe the state and recent metrics in plain words', ' --json print JSON', '', 'Example: dalan status, then dalan inbox --all'] },
|
|
63
73
|
{ name: 'get', group: 'everyday', summary: 'Show one job (or message) by ID', usage: 'dalan get ID [--json]',
|
|
@@ -68,11 +78,13 @@ export const COMMANDS = [
|
|
|
68
78
|
'--drained needs --producer-thread ID unless the command runs inside a Claude Code or Codex session, which supplies it.', '',
|
|
69
79
|
'Exit status for a job: 0 finished, 3 blocker or question, 4 cancelled, 5 the worker is on a usage break, 124 timeout (the job is still open), 1 error.', '', 'Example: dalan wait REQUEST_ID --timeout 3600, then dalan get REQUEST_ID.', 'Exit 124 leaves the job open; inspect it with dalan get before waiting again.'] },
|
|
70
80
|
{ name: 'inbox', group: 'everyday', summary: 'List jobs and messages that need you', usage: 'dalan inbox [--all | --producer ID] [--since RFC3339] [--json] | dalan inbox --mark-read [ID...] [--before RFC3339]',
|
|
71
|
-
detail: ['Lists what needs you. A producer is the shell or agent session that submitted the job. Inside a Claude Code or Codex session, plain dalan inbox lists that session\'s jobs.', 'Outside a Claude Code or Codex session, plain dalan inbox lists every producer\'s jobs on this bridge home.', '--all lists every producer anywhere; --producer ID lists one.', '', 'Options:', ' --since, --before an RFC3339 time or a duration such as 72h or 3d', '', 'Default window: jobs updated in the last 72 hours. Questions are always listed. To see older results: dalan inbox --all --since all', '', 'Example: dalan inbox --all, then dalan get REQUEST_ID'] },
|
|
81
|
+
detail: ['Lists what needs you. A producer is the shell or agent session that submitted the job. Inside a Claude Code or Codex session, plain dalan inbox lists that session\'s jobs.', 'Outside a Claude Code or Codex session, plain dalan inbox lists every producer\'s jobs on this bridge home.', '--all lists every producer anywhere; --producer ID lists one.', '', 'Options:', ' --since, --before an RFC3339 time or a duration such as 72h or 3d', '', 'Default window: jobs updated in the last 72 hours. Questions are always listed. To see older results: dalan inbox --all --since all', '', 'A line marked "wake held: parent_stopped" is a result or question that did not reach your T3 thread because the thread\'s latest run was stopped. It stays queued and sends when the thread runs again; read it now with dalan get.', '', 'Example: dalan inbox --all, then dalan get REQUEST_ID'] },
|
|
72
82
|
{ name: 'decide', group: 'everyday', summary: 'Record your decision on a finished job', usage: 'dalan decide ID WORD [--note TEXT]',
|
|
73
83
|
detail: ['Records your decision on a finished job. Review the report or patch first.', '', 'WORD is one of: accepted, applied, useful_no_change, useful_negative, not_useful.', 'Example: dalan decide REQUEST_ID accepted'] },
|
|
74
|
-
{ name: '
|
|
75
|
-
detail: ['
|
|
84
|
+
{ name: 'materialize', summary: 'Publish a finished job\'s patch as a draft pull request, or preview the decision', usage: 'dalan materialize ID (--dry-run | [--approve] [--dir PATH]) [--json]',
|
|
85
|
+
detail: ['Reads a current finished job and the owner grant in ~/.config/dot-bridge/materialize.json.', 'With --dry-run it prints the decision and the patch files, and changes nothing.', 'Otherwise, when the grant covers the repository (or asks for approval and you pass --approve), it commits the patch at the job\'s base commit in a temporary worktree of the clone in --dir (default: the current directory), pushes a new branch dalan/ID and opens a draft pull request.', 'It never replaces an existing branch, never merges and records no decision.'] },
|
|
86
|
+
{ name: 'apply', group: 'everyday', summary: 'Apply a finished job\'s patch to a directory', usage: 'dalan apply ID [--dir PATH] [--release]',
|
|
87
|
+
detail: ['Applies the patch from a finished job to a directory (default: the current directory) and records the decision "applied" for you, after the patch is written.', 'There is no need to accept the job first.', 'If the write fails, the files are put back and the job stays not applied. If the process dies before the bridge confirms, `dalan get` shows the apply as uncertain; run apply again to resolve it. If the checkout was left partly changed, the error names the files and the recovery steps; "dalan apply ID --release" gives up the uncertain apply on purpose and touches no file.'] },
|
|
76
88
|
{ name: 'mcp', group: 'everyday', summary: 'Serve submit, wait, result and status as local MCP tools over stdio', usage: 'dalan mcp',
|
|
77
89
|
detail: ['Runs a local MCP server on standard input and output for an agent on this computer (Claude Code, Codex).', 'Tools: dalan_submit, dalan_wait, dalan_result, dalan_status. They run the same CLI commands, with the same access to the admin socket.', 'Only protocol messages go to standard output; logs go to standard error. See docs/local-agent-mcp.md.'] },
|
|
78
90
|
{ name: 'worker', group: 'operator', summary: 'Choose which repositories a worker may use', usage: 'dalan worker allow|deny NAME OWNER/REPO [--json] | worker list [NAME] [--json] | worker migrate-repos [--json]',
|
|
@@ -85,9 +97,14 @@ export const COMMANDS = [
|
|
|
85
97
|
{ name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
|
|
86
98
|
{ name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },
|
|
87
99
|
// Reachable, but not on the first screen.
|
|
100
|
+
{ name: 'quiesce', summary: 'Hold new effectful calls for a restart', usage: 'dalan quiesce on|off|status [--json]',
|
|
101
|
+
detail: ['Closes (on) or reopens (off) the admission gate so the service can restart without waiting for worker leases. While on, every call that changes state is refused with a retryable message; reads still answer and no lease changes.', '', 'status prints on, admitted_in_flight, delivery_in_flight, host_checks_unverified and live_leases. The mode is in memory only: a restart reopens the gate.'] },
|
|
88
102
|
{ name: 'artifact', summary: 'Download a job artifact', usage: 'dalan artifact ID --output PATH' },
|
|
89
|
-
{ name: 'cancel', summary: 'Cancel a job', usage: 'dalan cancel ID [--reason TEXT]'
|
|
90
|
-
|
|
103
|
+
{ name: 'cancel', summary: 'Cancel a job', usage: 'dalan cancel ID [--reason TEXT]',
|
|
104
|
+
detail: ['Withdraws a job.', '', 'Scope controlled: the job. Its authority is withdrawn, so a result sent after this is kept as audit evidence and is not accepted.', 'Not controlled: worker compute. A worker that already holds the job may still run and report late. Nothing here proves it stopped (compute_stopped stays false until a stop is verified).', '',
|
|
105
|
+
'The output carries a scope block that states both, and the lifecycle log records a withdraw_work event with the job as its scope.', 'Example: dalan cancel REQUEST_ID --reason "no longer needed"'] },
|
|
106
|
+
{ name: 'cancel-if-queued', summary: 'Cancel a job only if it has not started', usage: 'dalan cancel-if-queued ID',
|
|
107
|
+
detail: ['Withdraws a job only while it is still queued. A claimed job keeps running and nothing is revoked.', '', 'Scope controlled: the queued job. Not controlled: worker compute (none was running when the job was withdrawn).', 'Example: dalan cancel-if-queued REQUEST_ID'] },
|
|
91
108
|
{ name: 'accept', summary: 'same as: dalan decide REQUEST_ID accepted', usage: 'dalan accept ID [--note TEXT]' },
|
|
92
109
|
{ name: 'reject', summary: 'same as: dalan decide REQUEST_ID not_useful', usage: 'dalan reject ID [--note TEXT]' },
|
|
93
110
|
{ name: 'note', summary: 'Add a note to a job', usage: 'dalan note ID TEXT [--json]' },
|
|
@@ -97,7 +114,9 @@ export const COMMANDS = [
|
|
|
97
114
|
{ name: 'untell', summary: 'Withdraw a message', usage: 'dalan untell MESSAGE_ID [--worker NAME] [--json]' },
|
|
98
115
|
{ name: 'audit', summary: 'Show the audit trail', usage: 'dalan audit [--since RFC3339]' },
|
|
99
116
|
{ name: 'claims', summary: 'List active worker claims', usage: 'dalan claims [--json]' },
|
|
100
|
-
{ name: 'abandon', summary: 'Release a stuck claim', usage: 'dalan abandon ID [--reason TEXT]'
|
|
117
|
+
{ name: 'abandon', summary: 'Release a stuck claim', usage: 'dalan abandon ID [--reason TEXT]',
|
|
118
|
+
detail: ['Releases the active claim on a job and queues the job again.', '', 'Scope controlled: the claim. It is released and its claim id stops working.', 'Not controlled: the worker session. It is not stopped, and it may keep running until it sees that the claim is gone.', '',
|
|
119
|
+
'The output carries a scope block that states both, and the lifecycle log records a detach event with the claim as its scope.', 'Example: dalan abandon REQUEST_ID --reason "worker stuck"'] },
|
|
101
120
|
{ name: 'reconcile', internal: true, summary: 'Reconcile one job record with the bridge', usage: 'dalan reconcile ID [--adopt]' },
|
|
102
121
|
{ name: 'verify-stops', internal: true, summary: 'Re-check host stop evidence for a job whose claim reports claim_effects_unverified', usage: 'dalan verify-stops [ID] [--json]' },
|
|
103
122
|
{ name: 'integrate', summary: 'Mark a job as integrated', usage: 'dalan integrate ID [--reason TEXT]' },
|
|
@@ -110,7 +129,7 @@ export const COMMANDS = [
|
|
|
110
129
|
{ name: 'break-usage-backfill', internal: true, summary: 'Backfill usage for a capacity break', usage: 'dalan break-usage-backfill --id N [--log PATH] [--json]' },
|
|
111
130
|
{ name: 'as-init', internal: true, summary: 'Create built-in authorization server files (older form of init)', usage: 'dalan as-init --public-url https://HOST [--json]' },
|
|
112
131
|
{ name: 'as-rotate-keys', summary: 'Rotate the authorization server keys', usage: 'dalan as-rotate-keys [--jwks-only|--cookies-only] [--json] (stop the bridge first)' },
|
|
113
|
-
{ name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]' },
|
|
132
|
+
{ name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--go|--pnpm] [--json] [--replace-invalid] | dalan prepare-deps --prune [--keep N]' },
|
|
114
133
|
];
|
|
115
134
|
|
|
116
135
|
const GROUPS = [['start', 'Getting started'], ['everyday', 'Everyday'], ['operator', 'Operator']];
|
package/src/cli-name.mjs
CHANGED
|
@@ -10,7 +10,19 @@ const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
|
10
10
|
export function cliCommand(argv1, env = process.env) {
|
|
11
11
|
const real = p => { try { return fs.realpathSync(p); } catch { return null; } };
|
|
12
12
|
const self = real(path.resolve(argv1 ?? defaultBin));
|
|
13
|
-
|
|
13
|
+
let firstOnPath = null;
|
|
14
|
+
for (const dir of env.PATH == null ? [] : env.PATH.split(path.delimiter)) {
|
|
15
|
+
const candidate = path.join(dir || '.', 'dalan');
|
|
16
|
+
try {
|
|
17
|
+
if (!fs.statSync(candidate).isFile()) continue;
|
|
18
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
19
|
+
} catch {
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
firstOnPath = real(candidate);
|
|
23
|
+
if (firstOnPath !== null) break;
|
|
24
|
+
}
|
|
25
|
+
const onPath = self && firstOnPath === self;
|
|
14
26
|
if (onPath) return env.npm_command === 'exec' ? 'npx @tnunamak/dalan' : 'dalan';
|
|
15
27
|
return `node ${shellQuote(self ?? path.resolve(argv1 ?? defaultBin))}`;
|
|
16
28
|
}
|