@tnunamak/dalan 0.0.0-stage → 0.5.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 +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -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 +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -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 +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -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 +65 -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/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 +412 -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 +497 -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/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -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-slot.mjs +53 -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 +70 -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/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/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/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 +1340 -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 +3057 -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 +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -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 +622 -0
- package/src/workspace.mjs +1058 -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/cli-help.mjs
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Help text and command lookup for the `dalan` CLI. Its only I/O is reading the package version for docs links, so `bin/dalan.mjs` can answer help
|
|
2
|
+
// requests before it loads the rest of the CLI.
|
|
3
|
+
import { docsUrl } from './docs-url.mjs';
|
|
4
|
+
|
|
5
|
+
// Order matters: it is the order of the help screens. `group` is where a command shows on the short screen;
|
|
6
|
+
// commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
|
|
7
|
+
// `dalan help --internal`. Every command runs and has its own help either way.
|
|
8
|
+
export const COMMANDS = [
|
|
9
|
+
{ name: 'try', group: 'start', summary: 'Run a private trial bridge and finish a first job', usage: 'dalan try [--home DIR] [--port N] [--callback PATTERN]...',
|
|
10
|
+
detail: ['Starts a bridge and a built-in demo worker in a private trial home and runs a self-check: the demo worker finishes one job,',
|
|
11
|
+
'and a repository grant is tested. In an interactive terminal it then waits for you to connect your own worker; press Ctrl-C to stop.',
|
|
12
|
+
'With standard input closed (dalan try < /dev/null) it stops after the self-check. Nothing outside the trial home is touched.', '',
|
|
13
|
+
'Options:', ' --home DIR trial home (default: DALAN_HOME if set, else ~/.local/share/dalan-trial)', ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN allow one more OAuth callback pattern; repeatable', '',
|
|
14
|
+
'Example: dalan try', `Then connect your worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
|
|
15
|
+
{ name: 'init', group: 'start', summary: 'Create a bridge home and its first worker profile', usage: 'dalan init --public-url URL (--worker NAME | --legacy) [--json]',
|
|
16
|
+
detail: ['Writes the built-in authorization server files and the first worker profile into the bridge home (DALAN_HOME).', 'It needs no running bridge.', '',
|
|
17
|
+
'Options:', ' --public-url URL the address clients will use to reach the bridge: https://HOST, or',
|
|
18
|
+
' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
|
|
19
|
+
'Example (a bridge on this computer only):', ' export DALAN_HOME="$HOME/.local/share/dalan-manual-trial"', ' export DALAN_LOOPBACK=1', ' dalan init --worker local --public-url http://127.0.0.1:8799'] },
|
|
20
|
+
{ name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
|
|
21
|
+
detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
|
|
22
|
+
' 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',
|
|
23
|
+
' list [--json] show connected workers', ' revoke NAME disconnect a worker', ' stop close the pairing window', ' reset clear pairing state',
|
|
24
|
+
' 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',
|
|
25
|
+
' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
|
|
26
|
+
'Examples (pair a worker named local):', ' dalan connect start --worker local', ' dalan connect pending', ' dalan connect approve CODE --worker local --confirm-redirect URI',
|
|
27
|
+
'Replace CODE with the code that pending and the browser page both show, and URI with the', 'redirect that pending shows.'] },
|
|
28
|
+
{ name: 'submit', group: 'everyday', summary: 'Queue a job for a worker', usage: 'dalan submit (--file PATH | --stdin | --brief TEXT) [options]',
|
|
29
|
+
detail: ['Queues a job. Give it a JSON assignment (request_id, inputs, brief, ...) or, with --brief, plain text for a question that needs no files.', 'Prints the request ID.', '',
|
|
30
|
+
'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
|
|
31
|
+
' --thread ID deliver the result to a T3 Code thread (optional integration)', ' --deliver none|t3:ID delivery target (default: none; not with --thread)', ' --review ask for a review of work already done',
|
|
32
|
+
' --wait wait for the result before returning', ' --timeout S with --wait: seconds to wait, 1 to 3600 (default: 300)', ' --dry-run check the assignment and store nothing',
|
|
33
|
+
' --queue-anyway queue even when the bridge would defer or warn', ' --refuse-defer fail instead of deferring',
|
|
34
|
+
' --allow-scope-prune when submit rejects the brief for naming files outside scope_paths, let it fix scope_paths and retry once',
|
|
35
|
+
' --execution none|worker|host execution capability for the job (default: the profile\'s default_execution, none for a new profile)',
|
|
36
|
+
' --require-capability LIST comma-separated backend capabilities the job needs (default: none)', ' --json print JSON', '',
|
|
37
|
+
'Examples (the first job):',
|
|
38
|
+
' 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',
|
|
39
|
+
'', 'Example (a question that needs no files):', ' dalan submit --worker local --brief "What does a database index do?"', '',
|
|
40
|
+
'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')}`] },
|
|
41
|
+
{ name: 'status', group: 'everyday', summary: 'Show the bridge, queue and worker state', usage: 'dalan status [--explain] [--json]',
|
|
42
|
+
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'] },
|
|
43
|
+
{ name: 'get', group: 'everyday', summary: 'Show one job (or message) by ID', usage: 'dalan get ID [--json]',
|
|
44
|
+
detail: ['Prints the job\'s state, progress, report and artifacts, and marks a finished result as read.', 'On a terminal it prints a short view; piped, or with --json, it prints the full JSON record.', '', 'Example: dalan get REQUEST_ID'] },
|
|
45
|
+
{ name: 'wait', group: 'everyday', summary: 'Wait for a job to finish', usage: 'dalan wait ID [--timeout S] | wait --drained --producer-thread ID [--max-claimed N] [--max-queued N] [--timeout S]',
|
|
46
|
+
detail: ['Waits until job ID reaches a final state, or until the timeout. With --drained, waits until your queue has drained.', '',
|
|
47
|
+
'Options:', ' --timeout S seconds to wait: 1 to 3600 for a job (default: 300); 1 to 86400 with --drained (default: 1740)', '',
|
|
48
|
+
'--drained needs --producer-thread ID unless the command runs inside a Claude Code or Codex session, which supplies it.', '',
|
|
49
|
+
'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.'] },
|
|
50
|
+
{ 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]',
|
|
51
|
+
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'] },
|
|
52
|
+
{ name: 'decide', group: 'everyday', summary: 'Record your decision on a finished job', usage: 'dalan decide ID WORD [--note TEXT]',
|
|
53
|
+
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'] },
|
|
54
|
+
{ name: 'apply', group: 'everyday', summary: 'Apply a finished job\'s patch to a directory', usage: 'dalan apply ID [--dir PATH]',
|
|
55
|
+
detail: ['Applies the patch from a finished job to a directory (default: the current directory) and records the decision "applied" for you.', 'There is no need to accept the job first.'] },
|
|
56
|
+
{ name: 'mcp', group: 'everyday', summary: 'Serve submit, wait, result and status as local MCP tools over stdio', usage: 'dalan mcp',
|
|
57
|
+
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.'] },
|
|
58
|
+
{ 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]',
|
|
59
|
+
detail: ['Subcommands:', ' allow NAME OWNER/REPO let a worker use a repository', ' deny NAME OWNER/REPO stop a worker using it', ' list [NAME] show each worker\'s repository access', ' migrate-repos convert an old repository policy; stop the service first'] },
|
|
60
|
+
{ name: 'tool', group: 'operator', summary: 'Register tools and choose which workers may call them', usage: 'dalan tool add --file PATH | remove NAME | list | grant NAME WORKER | revoke NAME WORKER [--json]',
|
|
61
|
+
detail: ['Manages the owner-side tool registry. A worker sees and calls only the tools granted to it. Changing the registry never changes the advertised MCP tool list.', '', 'Subcommands:', ' add --file PATH register a tool from a JSON file: name, description, class (read|write), inputSchema, handler', ' remove NAME remove a tool and its grants', ' list show tools, classes, schema hashes and granted workers', ' grant NAME WORKER let a worker call a tool', ' revoke NAME WORKER stop a worker calling a tool'] },
|
|
62
|
+
{ name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks] [--json]',
|
|
63
|
+
detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --json print JSON'] },
|
|
64
|
+
{ name: 'paths', group: 'operator', summary: 'Print where Dalan keeps its files', usage: 'dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]' },
|
|
65
|
+
{ name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
|
|
66
|
+
{ name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },
|
|
67
|
+
// Reachable, but not on the first screen.
|
|
68
|
+
{ name: 'artifact', summary: 'Download a job artifact', usage: 'dalan artifact ID --output PATH' },
|
|
69
|
+
{ name: 'cancel', summary: 'Cancel a job', usage: 'dalan cancel ID [--reason TEXT]' },
|
|
70
|
+
{ name: 'cancel-if-queued', summary: 'Cancel a job only if it has not started', usage: 'dalan cancel-if-queued ID' },
|
|
71
|
+
{ name: 'accept', summary: 'same as: dalan decide REQUEST_ID accepted', usage: 'dalan accept ID [--note TEXT]' },
|
|
72
|
+
{ name: 'reject', summary: 'same as: dalan decide REQUEST_ID not_useful', usage: 'dalan reject ID [--note TEXT]' },
|
|
73
|
+
{ name: 'note', summary: 'Add a note to a job', usage: 'dalan note ID TEXT [--json]' },
|
|
74
|
+
{ name: 'questions', summary: 'List a job\'s open worker questions', usage: 'dalan questions ID [--json]' },
|
|
75
|
+
{ name: 'answer', summary: 'Answer a worker question', usage: 'dalan answer ID QUESTION_ID TEXT [--json]' },
|
|
76
|
+
{ name: 'tell', summary: 'Send a message to workers', usage: 'dalan tell [--worker NAME] TEXT [--json]' },
|
|
77
|
+
{ name: 'untell', summary: 'Withdraw a message', usage: 'dalan untell MESSAGE_ID [--worker NAME] [--json]' },
|
|
78
|
+
{ name: 'audit', summary: 'Show the audit trail', usage: 'dalan audit [--since RFC3339]' },
|
|
79
|
+
{ name: 'claims', summary: 'List active worker claims', usage: 'dalan claims [--json]' },
|
|
80
|
+
{ name: 'abandon', summary: 'Release a stuck claim', usage: 'dalan abandon ID [--reason TEXT]' },
|
|
81
|
+
{ name: 'reconcile', internal: true, summary: 'Reconcile one job record with the bridge', usage: 'dalan reconcile ID [--adopt]' },
|
|
82
|
+
{ 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]' },
|
|
83
|
+
{ name: 'integrate', summary: 'Mark a job as integrated', usage: 'dalan integrate ID [--reason TEXT]' },
|
|
84
|
+
{ name: 'metrics', summary: 'Show bridge metrics', usage: 'dalan metrics [--since RFC3339] [--json]' },
|
|
85
|
+
{ name: 'rejections', summary: 'Summarize rejected jobs', usage: 'dalan rejections [--since RFC3339] [--json]' },
|
|
86
|
+
{ name: 'backfill-objectives', internal: true, summary: 'Backfill objective records', usage: 'dalan backfill-objectives [--dry-run] [--json]' },
|
|
87
|
+
{ name: 'break', summary: 'Record or clear a capacity break', usage: 'dalan break --reason TEXT [--since RFC3339] | dalan break --clear' },
|
|
88
|
+
{ name: 'breaks', summary: 'List capacity breaks', usage: 'dalan breaks [--json]' },
|
|
89
|
+
{ name: 'learned', summary: 'Show or clear learned limits', usage: 'dalan learned [--clear] [--json]' },
|
|
90
|
+
{ name: 'break-usage-backfill', internal: true, summary: 'Backfill usage for a capacity break', usage: 'dalan break-usage-backfill --id N [--log PATH] [--json]' },
|
|
91
|
+
{ 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]' },
|
|
92
|
+
{ name: 'as-rotate-keys', summary: 'Rotate the authorization server keys', usage: 'dalan as-rotate-keys [--jwks-only|--cookies-only] [--json] (stop the bridge first)' },
|
|
93
|
+
{ name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]' },
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
const GROUPS = [['start', 'Getting started'], ['everyday', 'Everyday'], ['operator', 'Operator']];
|
|
97
|
+
const find = name => COMMANDS.find(c => c.name === name);
|
|
98
|
+
const section = (title, rows) => [`${title}:`, ...rows.map(c => ` ${c.name.padEnd(10)} ${c.summary}`)];
|
|
99
|
+
|
|
100
|
+
export function shortHelp() {
|
|
101
|
+
return ['Dalan: hand bounded jobs to a worker agent, follow their progress and review the results.', '',
|
|
102
|
+
'Usage: dalan <command> [options]', '',
|
|
103
|
+
...GROUPS.flatMap(([key, title]) => [...section(title, COMMANDS.filter(c => c.group === key)), '']),
|
|
104
|
+
'Environment:', ' DALAN_HOME bridge home that commands use; for the trial: export DALAN_HOME=~/.local/share/dalan-trial', '',
|
|
105
|
+
'Start here: dalan try',
|
|
106
|
+
'Details: dalan <command> --help', 'More: dalan help --all', 'Version: dalan --version', ''].join('\n').trimEnd();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const width = Math.max(...COMMANDS.map(c => c.name.length)) + 2;
|
|
110
|
+
const rows = commands => commands.map(c => ` ${c.name.padEnd(width)}${c.summary}`);
|
|
111
|
+
|
|
112
|
+
export function fullHelp() {
|
|
113
|
+
return [shortHelp(), '', 'Other commands:', ...rows(COMMANDS.filter(c => !c.group && !c.internal)), '',
|
|
114
|
+
'Internal maintenance commands: dalan help --internal'].join('\n');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function internalHelp() {
|
|
118
|
+
return ['Internal maintenance commands. Operators run these for recovery or upgrades; a normal setup does not need them.', '',
|
|
119
|
+
...rows(COMMANDS.filter(c => c.internal)), '', 'Details: dalan <command> --help'].join('\n');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function commandHelp(name) {
|
|
123
|
+
const c = find(name);
|
|
124
|
+
if (!c) return null;
|
|
125
|
+
return [`${c.summary}.`, '', `Usage: ${c.usage}`, ...(c.detail ? ['', ...c.detail] : []), '', 'Other commands: dalan help --all. Internal maintenance commands: dalan help --internal.'].join('\n');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function distance(a, b) {
|
|
129
|
+
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
130
|
+
for (let i = 1; i <= a.length; i++) {
|
|
131
|
+
const row = [i];
|
|
132
|
+
for (let j = 1; j <= b.length; j++) row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
133
|
+
prev = row;
|
|
134
|
+
}
|
|
135
|
+
return prev[b.length];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function suggest(name) {
|
|
139
|
+
const scored = COMMANDS.map(c => ({ name: c.name, d: c.name.startsWith(name) && name.length >= 2 ? 1 : distance(name, c.name) }));
|
|
140
|
+
const best = scored.sort((a, b) => a.d - b.d)[0];
|
|
141
|
+
return best && best.d <= Math.max(1, Math.min(2, Math.floor(name.length / 3))) ? best.name : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const FREE_TEXT = new Set(['note', 'answer', 'tell']);
|
|
145
|
+
// Free-text commands keep rejecting option-like words (`tell --help` is an error); `dalan help tell` shows their usage.
|
|
146
|
+
const wantsHelp = (command, rest) => !FREE_TEXT.has(command) && (rest[0] === '-h' || rest.includes('--help'));
|
|
147
|
+
|
|
148
|
+
// Decide whether argv (after the node and script names) is a help request or an unknown command.
|
|
149
|
+
// Returns null when the command should run normally; otherwise { stream, code, text }.
|
|
150
|
+
export function resolveHelp(argv) {
|
|
151
|
+
const [command, ...rest] = argv;
|
|
152
|
+
if (command === undefined) return { stream: 'stdout', code: 0, text: shortHelp() };
|
|
153
|
+
if (command === '--help' || command === '-h') return { stream: 'stdout', code: 0, text: shortHelp() };
|
|
154
|
+
if (command === 'help') {
|
|
155
|
+
const topic = rest.find(a => !a.startsWith('-'));
|
|
156
|
+
if (topic) {
|
|
157
|
+
const text = commandHelp(topic);
|
|
158
|
+
if (!text) return unknown(topic, rest.includes('--json'));
|
|
159
|
+
return { stream: 'stdout', code: 0, text };
|
|
160
|
+
}
|
|
161
|
+
return { stream: 'stdout', code: 0, text: rest.includes('--internal') ? internalHelp() : rest.includes('--all') ? fullHelp() : shortHelp() };
|
|
162
|
+
}
|
|
163
|
+
if (!find(command)) return unknown(command, rest.includes('--json'));
|
|
164
|
+
if (wantsHelp(command, rest)) return { stream: 'stdout', code: 0, text: commandHelp(command) };
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function unknown(name, json) {
|
|
169
|
+
const hint = suggest(name);
|
|
170
|
+
if (json) return { stream: 'stderr', code: 1, text: JSON.stringify({ error: `unknown command "${name}"${hint ? `; did you mean "${hint}"?` : ''}`, kind: 'local' }) };
|
|
171
|
+
return { stream: 'stderr', code: 1, text: `dalan: unknown command "${name}"${hint ? `. Did you mean "${hint}"?` : ''}\nRun 'dalan --help' for usage.` };
|
|
172
|
+
}
|
package/src/cli-name.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// How to tell the user to run this CLI again: `dalan` when that name on PATH is this same file (a normal npm install),
|
|
2
|
+
// `npx @tnunamak/dalan` under npx or `npm exec` (npm sets npm_command=exec): that PATH entry is npx's temporary bin, which the
|
|
3
|
+
// user's shell does not have. Otherwise node and the absolute path, so a checkout works without being on PATH.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const defaultBin = path.resolve(import.meta.dirname, '..', 'bin/dalan.mjs');
|
|
8
|
+
const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
9
|
+
|
|
10
|
+
export function cliCommand(argv1, env = process.env) {
|
|
11
|
+
const real = p => { try { return fs.realpathSync(p); } catch { return null; } };
|
|
12
|
+
const self = real(path.resolve(argv1 ?? defaultBin));
|
|
13
|
+
const onPath = self && (env.PATH ?? '').split(path.delimiter).some(dir => dir && real(path.join(dir, 'dalan')) === self);
|
|
14
|
+
if (onPath) return env.npm_command === 'exec' ? 'npx @tnunamak/dalan' : 'dalan';
|
|
15
|
+
return `node ${shellQuote(self ?? path.resolve(argv1 ?? defaultBin))}`;
|
|
16
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { assertPrivateDir, untrusted, writeAtomic } from './as-files.mjs';
|
|
5
|
+
import { normalizeCode, PAIRING_MINUTES } from './as-files.mjs';
|
|
6
|
+
import { pollIntervalSeconds, readExposureRecords, WAKE_POLL_SECONDS_NGROK } from '../scripts/lib/expose-tailscale.mjs';
|
|
7
|
+
|
|
8
|
+
// `dalan connect ...`: the owner's side of the built-in authorization server. Every call goes through the owner Unix
|
|
9
|
+
// socket with the operator key; none of it exists on the public listener.
|
|
10
|
+
const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
|
|
11
|
+
|
|
12
|
+
// Terminal-safe text: vendor-supplied strings never reach the terminal as raw bytes.
|
|
13
|
+
const q = value => JSON.stringify(String(value ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim());
|
|
14
|
+
|
|
15
|
+
export function formatPending(result) {
|
|
16
|
+
if (!result.window) return 'No pairing window is open. Run: dalan connect start --worker NAME';
|
|
17
|
+
const lines = [`Pairing window open for worker ${result.window.worker} until ${result.window.expires_at}`];
|
|
18
|
+
if (!result.pending.length) lines.push('No pending connections.');
|
|
19
|
+
for (const p of result.pending) {
|
|
20
|
+
lines.push('', `code ${p.code}`, `worker ${p.worker}`, `client_id ${q(p.client_id)}`, `client_name [untrusted, set by the app] ${q(p.client_name)}`,
|
|
21
|
+
`redirect ${q(p.redirect_uri)}`, `resource ${q(p.resource)}`, `scopes ${p.scopes.map(q).join(' ')}`, `age ${p.age_seconds}s (expires in ${p.expires_in_seconds}s)`,
|
|
22
|
+
...(p.superseded ? [`SUPERSEDED by the newer attempt ${p.superseded_by}; an app that registered again cannot finish this one, so approve the newest code`] : []),
|
|
23
|
+
...(p.native ? ['WARNING native client, identity not verified: host and name prove nothing; teammate must read this code from the browser page on their own machine and compare it over a trusted channel', ' redirect confirmation is a typo check only; it is not identity proof', `APPROVE dalan connect approve ${p.code} --worker ${p.worker} (approves this code only; other pending codes are unaffected. A native client also needs the exact redirect shown above.)`] : []));
|
|
24
|
+
}
|
|
25
|
+
if (result.pending.length) lines.push('', 'Compare the code the teammate reads from their browser page over a trusted channel. Approve only that matching transaction. The code of a native client is approved by that code only; confirm the exact redirect shown above as a typo check.');
|
|
26
|
+
return lines.join('\n');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function formatClients(result) {
|
|
30
|
+
if (!result.clients.length) return 'No OAuth clients are registered.';
|
|
31
|
+
return result.clients.map(client => [
|
|
32
|
+
`client_id ${q(client.client_id)}`, `type ${client.type}`, `client_name [untrusted] ${q(client.client_name)}`,
|
|
33
|
+
`redirect_uris ${client.redirect_uris.map(q).join(' ')}`, `created_at ${client.created_at}`,
|
|
34
|
+
].join('\n')).join('\n\n');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function connectCommand(args, { request, operator, option, json }) {
|
|
38
|
+
const sub = args.shift();
|
|
39
|
+
const headers = () => ({ 'x-operator-key': operator() });
|
|
40
|
+
const flags = new Set(['--json', '--replace', '--rotate']);
|
|
41
|
+
const valued = new Set(['--worker', '--minutes', '--redirect-uri', '--name', '--confirm-redirect']);
|
|
42
|
+
const positional = [];
|
|
43
|
+
for (let i = 0; i < args.length; i++) {
|
|
44
|
+
if (valued.has(args[i])) {
|
|
45
|
+
if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`${args[i]} requires a value`);
|
|
46
|
+
i++; continue;
|
|
47
|
+
}
|
|
48
|
+
if (flags.has(args[i])) continue;
|
|
49
|
+
if (args[i].startsWith('--')) throw new Error(`unknown option ${args[i]}; ${USAGE}`);
|
|
50
|
+
positional.push(args[i]);
|
|
51
|
+
}
|
|
52
|
+
if (sub !== 'add-client' && (args.includes('--redirect-uri') || args.includes('--name'))) throw new Error(`${sub} does not accept --redirect-uri or --name; ${USAGE}`);
|
|
53
|
+
if (sub !== 'approve' && args.includes('--confirm-redirect')) throw new Error(`${sub} does not accept --confirm-redirect; ${USAGE}`);
|
|
54
|
+
const worker = option('--worker');
|
|
55
|
+
if (args.includes('--worker') && (!worker || worker.startsWith('--'))) throw new Error('--worker requires a name');
|
|
56
|
+
switch (sub) {
|
|
57
|
+
case 'add-client': {
|
|
58
|
+
const redirectUri = option('--redirect-uri'), name = option('--name');
|
|
59
|
+
if (!redirectUri || positional.length || args.includes('--worker') || args.includes('--minutes') || args.includes('--replace')
|
|
60
|
+
|| args.filter(arg => arg === '--redirect-uri').length !== 1 || args.filter(arg => arg === '--name').length > 1) throw new Error(USAGE);
|
|
61
|
+
const result = await request('/connect/add-client', 'POST', { redirect_uri: redirectUri, ...(name !== null ? { name } : {}) }, headers());
|
|
62
|
+
return json ? { result } : { result: `Created public client.\nclient_id ${q(result.client_id)}`, plain: true };
|
|
63
|
+
}
|
|
64
|
+
case 'clients': {
|
|
65
|
+
if (positional.length || args.some(arg => arg !== '--json')) throw new Error(USAGE);
|
|
66
|
+
const result = await request('/connect/clients', 'GET', null, headers());
|
|
67
|
+
return json ? { result } : { result: formatClients(result), plain: true };
|
|
68
|
+
}
|
|
69
|
+
case 'remove-client': {
|
|
70
|
+
if (positional.length !== 1 || args.some(arg => arg.startsWith('--') && arg !== '--json')) throw new Error(USAGE);
|
|
71
|
+
const result = await request('/connect/remove-client', 'POST', { client_id: positional[0] }, headers());
|
|
72
|
+
return json ? { result } : { result: `Removed static client ${q(result.client_id)}.`, plain: true };
|
|
73
|
+
}
|
|
74
|
+
case 'start': {
|
|
75
|
+
if (!worker || positional.length) throw new Error(USAGE);
|
|
76
|
+
const minutes = option('--minutes');
|
|
77
|
+
if (args.includes('--minutes') && (!/^\d+$/.test(minutes ?? ''))) throw new Error('--minutes requires an integer');
|
|
78
|
+
return { result: await request('/connect/start', 'POST', { worker, ...(minutes ? { minutes: Number(minutes) } : {}) }, headers()) };
|
|
79
|
+
}
|
|
80
|
+
case 'reset': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/reset', 'POST', {}, headers()) };
|
|
81
|
+
case 'stop': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/stop', 'POST', {}, headers()) };
|
|
82
|
+
case 'pending': {
|
|
83
|
+
if (positional.length) throw new Error(USAGE);
|
|
84
|
+
const result = await request('/connect/pending', 'GET', null, headers());
|
|
85
|
+
return json ? { result } : { result: formatPending(result), plain: true };
|
|
86
|
+
}
|
|
87
|
+
case 'approve': {
|
|
88
|
+
if (positional.length !== 1 || !worker) throw new Error(USAGE);
|
|
89
|
+
const view = await request('/connect/pending', 'GET', null, headers());
|
|
90
|
+
const matches = view.pending.filter(item => normalizeCode(item.code) === normalizeCode(positional[0]));
|
|
91
|
+
if (matches.length !== 1) {
|
|
92
|
+
const reason = matches.length ? 'More than one pending pairing matches this code. Run dalan connect pending and compare codes before approval.'
|
|
93
|
+
: `No pending pairing matches this code. The attempt may have expired (attempts last ${PAIRING_MINUTES} minutes) or the code may be mistyped. Start the sign-in again in the client, then compare codes with dalan connect pending before approval.`;
|
|
94
|
+
throw new Error(`${reason}\n\n${formatPending({ ...view, pending: matches.length ? matches : view.pending })}`);
|
|
95
|
+
}
|
|
96
|
+
const pairing = matches[0];
|
|
97
|
+
const confirmRedirect = option('--confirm-redirect');
|
|
98
|
+
if (pairing.native) {
|
|
99
|
+
const review = formatPending({ ...view, pending: [pairing] });
|
|
100
|
+
if (confirmRedirect === null) throw new Error(`Native callback needs explicit redirect typo confirmation. Compare the full URI with the browser page and compare the code the teammate reads from that page over a trusted channel; this flag does not prove identity. Rerun with --confirm-redirect ${q(pairing.redirect_uri)}.\n\n${review}`);
|
|
101
|
+
if (confirmRedirect !== pairing.redirect_uri) throw new Error(`confirmed redirect does not match the pending callback ${q(pairing.redirect_uri)}; this flag is only a typo check, not identity proof.\n\n${review}`);
|
|
102
|
+
} else if (confirmRedirect !== null) throw new Error('--confirm-redirect is only valid for a native callback');
|
|
103
|
+
const approval = await request('/connect/approve', 'POST', { code: positional[0], worker, replace: args.includes('--replace'), ...(confirmRedirect !== null ? { confirm_redirect: confirmRedirect } : {}) }, headers());
|
|
104
|
+
const review = formatPending({ ...view, pending: [pairing] });
|
|
105
|
+
return json ? { result: approval, review } : { result: `${review}\n\nApproved ${q(pairing.code)} for worker ${q(pairing.worker)}.${approval.replaced ? ` Replaced connection ${q(approval.replaced)}: this client now gets every queued and future job for worker ${q(pairing.worker)}, including briefs approved before the switch.` : ''}`, plain: true };
|
|
106
|
+
}
|
|
107
|
+
case 'list': if (positional.length) throw new Error(USAGE); return { result: await request('/connect/list', 'GET', null, headers()) };
|
|
108
|
+
case 'revoke': if (positional.length !== 1 || worker) throw new Error(USAGE); return { result: await request('/connect/revoke', 'POST', { worker: positional[0] }, headers()) };
|
|
109
|
+
case 'signal-token': {
|
|
110
|
+
if (positional.length || args.some((arg, i) => arg !== '--json' && arg !== '--rotate' && arg !== '--worker' && args[i - 1] !== '--worker')) throw new Error(USAGE);
|
|
111
|
+
const result = await request('/connect/signal-token', 'POST', { rotate: args.includes('--rotate'), ...(worker ? { worker } : {}) }, headers());
|
|
112
|
+
// The poll interval comes from the exposure record in this home (ngrok = 300 s, otherwise 60 s). It is set in the hook, not on the bridge.
|
|
113
|
+
const seconds = pollIntervalSeconds(readExposureRecords(os.homedir()));
|
|
114
|
+
const dir = defaultPath(os.homedir(),'.config/dot-bridge');
|
|
115
|
+
assertPrivateDir(dir);
|
|
116
|
+
const file = path.join(dir, `signal-url.${result.worker}`);
|
|
117
|
+
writeAtomic(file, `${result.url}\n`);
|
|
118
|
+
// stdout contains only the private file path; the hook owner can read it without exposing the URL in logs.
|
|
119
|
+
if (json) return { result: { path: file, worker: result.worker, rotated: result.rotated, poll_interval_seconds: seconds } };
|
|
120
|
+
process.stderr.write(`Hook poll interval: ${seconds} s or more. ${seconds === WAKE_POLL_SECONDS_NGROK ? 'For this exposure, do not poll faster than 300 s.' : 'Do not poll faster than every 60 s.'}\n`);
|
|
121
|
+
return { result: file, plain: true };
|
|
122
|
+
}
|
|
123
|
+
case 'allow-callback': if (positional.length !== 1) throw new Error(USAGE); return { result: await request('/connect/allow-callback', 'POST', { pattern: positional[0] }, headers()) };
|
|
124
|
+
default: throw new Error(USAGE);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Who a result is for, and how urgent that makes it. Code decides, never the submitter.
|
|
2
|
+
//
|
|
3
|
+
// A submitter can lie about anything it writes: a manifest field, a payload key, a --source flag. So the consumer type
|
|
4
|
+
// and the tier come only from facts the code path owns: the request id that proves a drainer or fix-loop identity
|
|
5
|
+
// (verifyObjective), and the priority the bridge enforces for that identity. A self-declared consumer, severity or tier
|
|
6
|
+
// is refused, not ignored, so a producer that tries it learns at once. Naming a requester (consumer.type thread or lane) is
|
|
7
|
+
// not refused; nothing reads it yet.
|
|
8
|
+
import { verifyObjective, fixLoopSource, fromStoredSource } from './objectives.mjs';
|
|
9
|
+
|
|
10
|
+
// Pseudo-consumers belong to the code path that owns them. A submitter never names one.
|
|
11
|
+
// fix_pipeline fix-loop assignments (proved by the fix-loop request id)
|
|
12
|
+
// reserve work nobody asked for: the drainer's audits and PR reviews (proved by the drainer request id)
|
|
13
|
+
// ledger no code path assigns it yet, so nothing can hold it
|
|
14
|
+
export const systemConsumers = Object.freeze(['fix_pipeline', 'ledger', 'reserve']);
|
|
15
|
+
|
|
16
|
+
// Fields that would let a submitter pick its own consumer or promote its own work. `value_tier` and `tier` are never the
|
|
17
|
+
// submitter's. `consumer` may name a requester (a thread or lane, for later) but never a system consumer. `severity` is the
|
|
18
|
+
// producer's own claim about its finding: a drainer or fix-loop submission cannot use it to rank itself, and an agent's
|
|
19
|
+
// severity hint is harmless (agent work is already tier 0) and passes.
|
|
20
|
+
export const forbiddenDeclarations = Object.freeze(['value_tier', 'tier']);
|
|
21
|
+
|
|
22
|
+
// Tier 0 is work an agent asked for; a lower number runs first. Only these three exist until the data justify more.
|
|
23
|
+
const tiers = { agent: 0, fix_pipeline: 1, reserve: 5 };
|
|
24
|
+
|
|
25
|
+
// The forbidden declarations at the top level of a manifest, assignment or request body. Empty when clean.
|
|
26
|
+
// `source` is the submitter's claimed source; without one the value is treated as an agent's.
|
|
27
|
+
export function declaredConsumerFields(value, source = 'agent') {
|
|
28
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return [];
|
|
29
|
+
const found = forbiddenDeclarations.filter(key => Object.hasOwn(value, key));
|
|
30
|
+
const named = typeof value.consumer === 'string' ? value.consumer : value.consumer?.type;
|
|
31
|
+
if (Object.hasOwn(value, 'consumer') && (systemConsumers.includes(named) || typeof named !== 'string')) found.push('consumer');
|
|
32
|
+
if (Object.hasOwn(value, 'severity') && source !== 'agent') found.push('severity');
|
|
33
|
+
return found;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function assertNoDeclaredConsumer(value, label, source = 'agent') {
|
|
37
|
+
const found = declaredConsumerFields(value, source);
|
|
38
|
+
if (found.length) throw new Error(`${label} declares ${found.join(', ')}; the bridge assigns the consumer and tier from the code path, never from the submitter`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// row: {request_id, payload (object or JSON), meta: {objective_key, revision, task_kind, source}}.
|
|
42
|
+
// Returns {type, tier, proven} and, when not proven, the reason verifyObjective gives. A claim of source drainer or fix-loop that the request id does not prove is not a consumer
|
|
43
|
+
// at all: the caller must refuse it (see unprovenSource).
|
|
44
|
+
export function consumerOf(row) {
|
|
45
|
+
const source = row.meta?.source ?? 'agent', normalizedSource = fromStoredSource(source);
|
|
46
|
+
if (normalizedSource === fixLoopSource || normalizedSource === 'drainer') {
|
|
47
|
+
const type = normalizedSource === fixLoopSource ? 'fix_pipeline' : 'reserve';
|
|
48
|
+
const reason = verifyObjective({ request_id: row.request_id, payload: row.payload }, row.meta);
|
|
49
|
+
return { type, tier: tiers[type], proven: reason === null, ...(reason === null ? {} : { reason }) };
|
|
50
|
+
}
|
|
51
|
+
return { type: 'agent', tier: tiers.agent, proven: true };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Why this submission may not use its claimed source, or null. A drainer or fix-loop identity needs its request id proof, and
|
|
55
|
+
// drainer work is always background: no manifest can put itself ahead of agent-requested work.
|
|
56
|
+
export function unprovenSource(row, priority) {
|
|
57
|
+
const consumer = consumerOf(row);
|
|
58
|
+
if (!consumer.proven) return `source ${row.meta.source} is proven by the request id of its own code path, and this one is not: ${consumer.reason}`;
|
|
59
|
+
if (consumer.type === 'reserve' && priority !== 'background') return 'drainer work is always background priority';
|
|
60
|
+
return null;
|
|
61
|
+
}
|