@tnunamak/dalan 0.0.0-stage → 0.6.0
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 +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/signal.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { writeAtomic } from './as-files.mjs';
|
|
5
|
+
|
|
6
|
+
// Public wake signal for hook-driven workers (built-in mode only). GET /signal/<token> answers {"work":true|false}: is a
|
|
7
|
+
// queued, live assignment waiting for the one worker the token belongs to. The token is its own 256-bit secret, never the MCP path secret.
|
|
8
|
+
// The response reveals one bit: no ids, titles or counts. Work is a queued job for the worker, or (resume wake, DALAN_RESUME_IDLE_MS)
|
|
9
|
+
// one of the worker's own claims that has gone idle.
|
|
10
|
+
const PREFIX = '/signal/';
|
|
11
|
+
const TOKEN = /^[a-f0-9]{64}$/;
|
|
12
|
+
const CACHE_MS = 10000;
|
|
13
|
+
const IP_BURST = 3, IP_REFILL_MS = 5000; // about one request per 5 s with a small burst
|
|
14
|
+
const GLOBAL_PER_MINUTE = 30;
|
|
15
|
+
const MAX_TRACKED_IPS = 4096;
|
|
16
|
+
const digest = value => createHash('sha256').update(value).digest();
|
|
17
|
+
|
|
18
|
+
export function createSignal({ dir, store, workerNames, publicUrl, log, now = Date.now }) {
|
|
19
|
+
// One secret per worker in signal-token.<worker>. A host from before per-worker tokens has a single signal-token file; it keeps
|
|
20
|
+
// answering for the one configured worker (so a hook already polling that URL survives) and is retired by that worker's rotation.
|
|
21
|
+
const legacyFile = path.join(dir, 'signal-token');
|
|
22
|
+
const fileFor = worker => path.join(dir, `signal-token.${worker}`);
|
|
23
|
+
const readToken = file => {
|
|
24
|
+
try {
|
|
25
|
+
const text = fs.readFileSync(file, 'utf8').trim();
|
|
26
|
+
return TOKEN.test(text) ? text : null;
|
|
27
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
28
|
+
};
|
|
29
|
+
const tokens = new Map(); // worker -> own token
|
|
30
|
+
const tokenOf = worker => {
|
|
31
|
+
if (!tokens.has(worker)) tokens.set(worker, readToken(fileFor(worker)));
|
|
32
|
+
const names = workerNames();
|
|
33
|
+
return tokens.get(worker) ?? (names.length === 1 && names[0] === worker ? readToken(legacyFile) : null);
|
|
34
|
+
};
|
|
35
|
+
const targetWorker = worker => {
|
|
36
|
+
const names = workerNames();
|
|
37
|
+
if (worker === undefined || worker === null) {
|
|
38
|
+
if (names.length === 1) return names[0];
|
|
39
|
+
throw new Error(`signal-token needs --worker NAME; configured: ${names.join(', ')}`);
|
|
40
|
+
}
|
|
41
|
+
if (!names.includes(worker)) throw new Error(`unknown worker "${worker}"; configured workers: ${names.join(', ')}`);
|
|
42
|
+
return worker;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Owner socket only. A new token replaces the worker's old one at once; the old URL answers 404 from this call on.
|
|
46
|
+
function tokenUrl({ worker, rotate = false } = {}) {
|
|
47
|
+
const name = targetWorker(worker);
|
|
48
|
+
let token = tokenOf(name);
|
|
49
|
+
if (rotate || !token) {
|
|
50
|
+
token = randomBytes(32).toString('hex');
|
|
51
|
+
writeAtomic(fileFor(name), `${token}\n`);
|
|
52
|
+
fs.chmodSync(fileFor(name), 0o600);
|
|
53
|
+
tokens.set(name, token);
|
|
54
|
+
if (workerNames().length === 1) fs.rmSync(legacyFile, { force: true }); // the pre-migration token must not outlive rotation
|
|
55
|
+
}
|
|
56
|
+
return { url: new URL(`${PREFIX}${token}`, publicUrl).href, worker: name, rotated: !!rotate };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const cached = new Map(); // worker -> { at, work }
|
|
60
|
+
const work = worker => {
|
|
61
|
+
const at = now(), hit = cached.get(worker);
|
|
62
|
+
if (hit && at >= hit.at && at - hit.at < CACHE_MS) return hit.work;
|
|
63
|
+
const fresh = { at, work: store.hasWakeFor(worker) };
|
|
64
|
+
cached.set(worker, fresh);
|
|
65
|
+
return fresh.work;
|
|
66
|
+
};
|
|
67
|
+
// Hash both sides so the compare takes the same time for any input length; a worker without a token matches nothing.
|
|
68
|
+
// Every configured worker is compared, so timing does not reveal which worker matched.
|
|
69
|
+
const workerFor = given => {
|
|
70
|
+
const wanted = digest(given);
|
|
71
|
+
let found = null;
|
|
72
|
+
for (const name of workerNames()) {
|
|
73
|
+
const token = tokenOf(name);
|
|
74
|
+
if (token !== null && timingSafeEqual(wanted, digest(token))) found = name;
|
|
75
|
+
}
|
|
76
|
+
return found;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const buckets = new Map(); // ip -> { tokens, at }
|
|
80
|
+
const recent = []; // times of admitted requests in the last minute
|
|
81
|
+
function admit(ip) {
|
|
82
|
+
const at = now();
|
|
83
|
+
while (recent.length && at - recent[0] >= 60000) recent.shift();
|
|
84
|
+
if (recent.length >= GLOBAL_PER_MINUTE) return Math.max(1, Math.ceil((60000 - (at - recent[0])) / 1000));
|
|
85
|
+
let bucket = buckets.get(ip);
|
|
86
|
+
if (!bucket) {
|
|
87
|
+
if (buckets.size >= MAX_TRACKED_IPS) for (const [key, b] of buckets) if (at - b.at >= IP_BURST * IP_REFILL_MS) buckets.delete(key);
|
|
88
|
+
if (buckets.size >= MAX_TRACKED_IPS) return 60; // table full of live buckets: refuse rather than grow
|
|
89
|
+
bucket = { tokens: IP_BURST, at };
|
|
90
|
+
buckets.set(ip, bucket);
|
|
91
|
+
}
|
|
92
|
+
bucket.tokens = Math.min(IP_BURST, bucket.tokens + (at - bucket.at) / IP_REFILL_MS);
|
|
93
|
+
bucket.at = at;
|
|
94
|
+
if (bucket.tokens < 1) return Math.max(1, Math.ceil((1 - bucket.tokens) * IP_REFILL_MS / 1000));
|
|
95
|
+
bucket.tokens -= 1;
|
|
96
|
+
recent.push(at);
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Returns true when the request was a signal request and has been answered.
|
|
101
|
+
function handle(req, res) {
|
|
102
|
+
const pathname = String(req.url).split('?')[0];
|
|
103
|
+
if (!pathname.startsWith(PREFIX)) return false;
|
|
104
|
+
const given = pathname.slice(PREFIX.length);
|
|
105
|
+
const worker = workerFor(given);
|
|
106
|
+
if (worker === null) { log({ kind: 'signal', status: 404 }); res.writeHead(404); res.end(); return true; }
|
|
107
|
+
if (req.method !== 'GET') { log({ kind: 'signal', status: 405 }); res.writeHead(405, { allow: 'GET' }); res.end(); return true; }
|
|
108
|
+
const wait = admit(req.socket.remoteAddress ?? 'unknown');
|
|
109
|
+
if (wait) { log({ kind: 'signal', status: 429 }); res.writeHead(429, { 'retry-after': String(wait), 'cache-control': 'no-store' }); res.end(); return true; }
|
|
110
|
+
const answer = work(worker);
|
|
111
|
+
const body = JSON.stringify({ work: answer });
|
|
112
|
+
log({ kind: 'signal', status: 200, work: answer });
|
|
113
|
+
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(body) });
|
|
114
|
+
res.end(body);
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { handle, tokenUrl };
|
|
119
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Worker reports are evidence of a suspected denial, not platform pause telemetry.
|
|
2
|
+
const denial = /auto-?review|guardian|denied|not approved|paused out of precaution/i;
|
|
3
|
+
const waiting = /auto.?stop|paused out of precaution|(?:resume|confirmation|approval).*(?:required|requested|needed)|(?:waiting|wait).*(?:guardian|confirmation|approval)/i;
|
|
4
|
+
|
|
5
|
+
export function statusEvidence(store) {
|
|
6
|
+
const observations = [
|
|
7
|
+
...store.db.prepare('SELECT request_id,id row_id,created_at at,note text FROM progress').all().map(row => ({ ...row, source: 'progress' })),
|
|
8
|
+
...store.db.prepare('SELECT request_id,rowid row_id,created_at at,summary text FROM reports').all().map(row => ({ ...row, source: 'report' })),
|
|
9
|
+
...store.db.prepare('SELECT request_id,rowid row_id,created_at at,summary text FROM late_evidence').all().map(row => ({ ...row, source: 'late_evidence' })),
|
|
10
|
+
];
|
|
11
|
+
const summarize = predicate => {
|
|
12
|
+
const matches = observations.filter(row => predicate(row.text)).sort((a, b) => b.at.localeCompare(a.at));
|
|
13
|
+
return {
|
|
14
|
+
count: new Set(matches.map(row => row.request_id)).size,
|
|
15
|
+
last_at: matches[0]?.at ?? null,
|
|
16
|
+
evidence: matches.slice(0, 20).map(({ request_id, row_id, at, source }) => ({ request_id, row_id, at, source })),
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
observed_at: store.stamp(),
|
|
21
|
+
denial_suspected: summarize(text => denial.test(text)),
|
|
22
|
+
worker_reported_guardian_wait: summarize(text => denial.test(text) && waiting.test(text)),
|
|
23
|
+
worker_pause: 'unknown',
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Calls and bytes against both windows always. The limits are estimates, not gates: name the ones reached (over_estimate).
|
|
28
|
+
const throttleToken = t => !t ? '' : (t.tool_calls_last_24h === undefined ? '' : ` calls=1h:${t.tool_calls_last_hour}/${t.max_tool_calls_per_hour},24h:${t.tool_calls_last_24h}/${t.max_tool_calls_per_24h}`) + (t.response_bytes_last_hour === undefined ? '' : ` bytes=1h:${t.response_bytes_last_hour}/${t.max_response_bytes_per_hour}${t.response_bytes_last_24h === undefined ? '' : `,24h:${t.response_bytes_last_24h}/${t.max_response_bytes_per_24h}`}`) +
|
|
29
|
+
(t.over_estimate?.length ? ` over_estimate=${t.over_estimate.join('+')}` : '') +
|
|
30
|
+
// Older bridges gated on these limits; keep explaining their responses.
|
|
31
|
+
(t.rewake_throttled || t.submit_throttled ? ` throttle=claims:${t.claims_last_hour}+queued:${t.queued}/${t.max_claims_per_hour},tool_calls:${t.tool_calls_last_hour}/${t.max_tool_calls_per_hour}${t.holding ? `,holding:submit[${t.holding.submit.join('+')}]rewake[${t.holding.rewake.join('+')}]${t.rewake_throttled && t.normal_rewake_throttled === false ? ' agent_work=passes' : ''}` : ''}` : '');
|
|
32
|
+
export function explainStatus(status) {
|
|
33
|
+
const queued = Array.isArray(status.counts) ? status.counts.find(row => row.status === 'queued')?.count ?? 0 : 'unknown';
|
|
34
|
+
const denialEvidence = status.denial_suspected;
|
|
35
|
+
const waitEvidence = status.worker_reported_guardian_wait;
|
|
36
|
+
const denialCount = Number.isInteger(denialEvidence?.count) ? denialEvidence.count : 'unavailable';
|
|
37
|
+
const denialLastAt = denialEvidence && Object.hasOwn(denialEvidence, 'last_at')
|
|
38
|
+
? denialEvidence.last_at ?? 'none'
|
|
39
|
+
: 'unknown';
|
|
40
|
+
const waitCount = Number.isInteger(waitEvidence?.count) ? waitEvidence.count : 'unavailable';
|
|
41
|
+
const lastClaim = status.last_claim_at ?? status.last_claim ?? status.subscription?.last_claim_at ?? 'none';
|
|
42
|
+
const priority=status.priority_counts??{};
|
|
43
|
+
const normal=`${priority.normal?.queued??'unknown'}/${priority.normal?.claimed??'unknown'}`;
|
|
44
|
+
const background=`${priority.background?.queued??'unknown'}/${priority.background?.claimed??'unknown'}`;
|
|
45
|
+
const d=status.dispatch, dispatch=d?` dispatch=${d.state}(free:${d.free_lanes},queued:${d.queued_live},oldest:${d.oldest_unclaimed_age_ms==null?'none':`${Math.round(d.oldest_unclaimed_age_ms/60000)}m`})`:'';
|
|
46
|
+
return `observed=${status.observed_at ?? 'unknown'}${dispatch} outer=${status.claimed_outer_count ?? 'unknown'}/${status.max_claimed_outer_assignments ?? 'unknown'} last_claim_at=${lastClaim} queued=${queued}${status.queued_expired?.count>0?` queued_expired=${status.queued_expired.count}`:''}${status.unclaimed_after_reannounce?.count>0?` unclaimed=${status.unclaimed_after_reannounce.count}`:''} normal=queued/claimed(${normal}) background=queued/claimed(${background}) background_max_in_flight=${status.background_max_in_flight??'unknown'} denial_suspected=${denialCount} denial_last_at=${denialLastAt} guardian_wait=worker_reported(${waitCount}) bridge_paused=${status.paused ?? 'unknown'} worker_pause=${status.worker_pause ?? 'unknown'}${status.worker_break?.active?` worker_break=since:${status.worker_break.since}(${status.worker_break.source})`:''}${throttleToken(status.throttle)}`;
|
|
47
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The short, plain `dalan status` output. Pure: it reads the /status document and returns text. `dalan status --json`
|
|
2
|
+
// prints the full document instead, so nothing here is a contract for scripts.
|
|
3
|
+
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { docsUrl } from './docs-url.mjs';
|
|
6
|
+
|
|
7
|
+
const CONNECT_URL = docsUrl('README.md', 'connect-your-own-worker');
|
|
8
|
+
|
|
9
|
+
export function age(ms) {
|
|
10
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
11
|
+
if (s < 90) return `${s} s`;
|
|
12
|
+
if (s < 5400) return `${Math.round(s / 60)} min`;
|
|
13
|
+
if (s < 172_800) return `${Math.round(s / 3600)} h`;
|
|
14
|
+
return `${Math.round(s / 86_400)} days`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
18
|
+
|
|
19
|
+
const countOf = (counts, status) => (counts ?? []).find(c => c.status === status)?.count ?? 0;
|
|
20
|
+
|
|
21
|
+
// The status document cannot tell which client made a worker's last call (after `dalan try` it is the demo worker), so
|
|
22
|
+
// the line reports when the worker last called, not whether "your" worker is connected.
|
|
23
|
+
function workerLine(name, w, { now, oldestMs }) {
|
|
24
|
+
const last = w.last_call_at ? Date.parse(w.last_call_at) : NaN;
|
|
25
|
+
const connection = [(w.subscriptions_active ?? 0) > 0 ? 'subscribed' : null, Number.isFinite(last) ? `last call ${age(now - last)} ago` : 'no calls yet'].filter(Boolean).join(', ');
|
|
26
|
+
const queued = countOf(w.counts, 'queued'), claimed = countOf(w.counts, 'claimed'), finished = countOf(w.counts, 'finished');
|
|
27
|
+
const others = (w.counts ?? []).filter(c => !['queued', 'claimed', 'finished'].includes(c.status) && c.count > 0).map(c => `${c.count} ${String(c.status).replaceAll('_', ' ')}`);
|
|
28
|
+
const parts = [connection, `${queued} queued${queued && oldestMs != null ? ` (oldest ${age(oldestMs)})` : ''}`,
|
|
29
|
+
...(claimed ? [`${claimed} in progress`] : []), ...others, `${finished} finished`];
|
|
30
|
+
return { text: `Worker ${name}: ${parts.join(' · ')}`, queued, total: (w.counts ?? []).reduce((n, c) => n + c.count, 0) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// status: the /status document. home: the bridge home. url: the bridge's public origin, or null. trial: a `dalan try` home.
|
|
34
|
+
// cli: how to name this CLI in the commands it prints (`dalan`, `npx @tnunamak/dalan` or node and a path).
|
|
35
|
+
export function formatStatusSummary(status, { home, url = null, trial = false, now = Date.now(), cli = 'dalan', envHome = null } = {}) {
|
|
36
|
+
const byWorker = Object.entries(status?.by_worker ?? {}).sort(([a], [b]) => a.localeCompare(b));
|
|
37
|
+
// The bridge reports the oldest queued age for all workers together, so it is shown only when one worker has queued work.
|
|
38
|
+
const queuedWorkers = byWorker.filter(([, w]) => countOf(w.counts, 'queued') > 0);
|
|
39
|
+
const oldestMs = queuedWorkers.length === 1 ? status?.oldest_queue_age_ms ?? null : null;
|
|
40
|
+
const workers = byWorker.map(([name, w]) => workerLine(name, w, { now, oldestMs: queuedWorkers[0]?.[0] === name ? oldestMs : null }));
|
|
41
|
+
const paused = status?.paused === true;
|
|
42
|
+
const lines = [`Bridge: ${paused ? 'running, paused' : 'running'}${url ? ` on ${url}` : ''} (${trial ? 'trial home' : 'home'} ${home})${paused && status.pause_reason ? `. Pause reason: ${status.pause_reason}` : ''}`,
|
|
43
|
+
...(workers.length ? workers.map(w => w.text) : ['Workers: none yet'])];
|
|
44
|
+
const total = workers.reduce((n, w) => n + w.total, 0) || (status?.counts ?? []).reduce((n, c) => n + c.count, 0);
|
|
45
|
+
const next = paused ? `resume handing out jobs: ${cli} resume`
|
|
46
|
+
: workers.some(w => w.queued) ? `send your worker the queued job (to connect a worker first, see ${CONNECT_URL}); list your jobs: ${cli} inbox --all`
|
|
47
|
+
: total ? `see what needs you: ${cli} inbox --all`
|
|
48
|
+
: `queue a job: ${cli} submit --help`;
|
|
49
|
+
// A trial home is never picked up without DALAN_HOME, and a status run as `DALAN_HOME=... dalan status` leaves the
|
|
50
|
+
// shell without it. A process cannot see its parent shell, so a trial summary always says how to select the home:
|
|
51
|
+
// a command, true in every shell. Other homes are chosen deliberately and get no line.
|
|
52
|
+
const select = trial && (!envHome || path.resolve(envHome) !== path.resolve(home)) ? [`In this shell, select this bridge home: export DALAN_HOME=${shellQuote(home)}`] : [];
|
|
53
|
+
return [...lines, ...select, `Next: ${next}`, `Full detail: ${cli} status --json`].join('\n');
|
|
54
|
+
}
|