@mogragsigma/dsh-dual-host-plugin 0.0.0-stage → 0.33.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/LICENSE +58 -0
- package/LICENSE.en.md +94 -0
- package/README.md +88 -2
- package/bundle/ASSET_NOTICE.md +19 -0
- package/bundle/LICENSE +58 -0
- package/bundle/LICENSE.en.md +94 -0
- package/bundle/README.md +75 -0
- package/bundle/THIRD_PARTY_NOTICES.md +94 -0
- package/bundle/a2a-dispatches.js +38 -0
- package/bundle/a2a-endpoint.js +112 -0
- package/bundle/a2a-tools.js +11 -0
- package/bundle/a2a-worker.js +63 -0
- package/bundle/approval-auth.js +5 -0
- package/bundle/approval-chat.js +150 -0
- package/bundle/approval-feishu.js +52 -0
- package/bundle/approval-guidance.js +68 -0
- package/bundle/approval-http.js +8 -0
- package/bundle/approval-ledger.js +142 -0
- package/bundle/approval-local-relay.js +86 -0
- package/bundle/approval-receipts.js +62 -0
- package/bundle/approval-reference.js +33 -0
- package/bundle/approval-semantic-model.js +26 -0
- package/bundle/approval-semantics.js +51 -0
- package/bundle/approval-ui/app.js +1 -0
- package/bundle/approval-ui/index.html +1 -0
- package/bundle/approval-ui/style.css +1 -0
- package/bundle/approval-workbench.js +45 -0
- package/bundle/artifact-media.js +34 -0
- package/bundle/bounded-text.js +44 -0
- package/bundle/compatibility.json +980 -0
- package/bundle/cordis.patch.yml +5 -0
- package/bundle/delivery-approval.js +133 -0
- package/bundle/delivery-artifacts.js +52 -0
- package/bundle/delivery-commit.js +125 -0
- package/bundle/delivery-contract.js +42 -0
- package/bundle/delivery-git-read.js +217 -0
- package/bundle/delivery-index.js +23 -0
- package/bundle/delivery-journal.js +207 -0
- package/bundle/delivery-object-plan.js +138 -0
- package/bundle/delivery-preview.js +153 -0
- package/bundle/delivery-process-receipts.js +90 -0
- package/bundle/delivery-process.js +46 -0
- package/bundle/delivery-process.py +228 -0
- package/bundle/delivery-push-approval.js +89 -0
- package/bundle/delivery-push-plan.js +98 -0
- package/bundle/delivery-push-recovery.js +32 -0
- package/bundle/delivery-push.js +83 -0
- package/bundle/delivery-recovery.js +143 -0
- package/bundle/delivery-runtime.js +182 -0
- package/bundle/delivery-ssh.js +64 -0
- package/bundle/delivery-state.js +106 -0
- package/bundle/development-attention.js +35 -0
- package/bundle/development-bridge.js +136 -0
- package/bundle/development-command-review.js +110 -0
- package/bundle/development-container.js +110 -0
- package/bundle/development-contract.js +17 -0
- package/bundle/development-files.js +101 -0
- package/bundle/development-gate.js +236 -0
- package/bundle/development-model-budget.js +48 -0
- package/bundle/development-peer.js +155 -0
- package/bundle/development-plan.js +43 -0
- package/bundle/development-reconciliation.js +62 -0
- package/bundle/development-review.js +81 -0
- package/bundle/development-rules/AGENTS.md +51 -0
- package/bundle/development-runtime.js +68 -0
- package/bundle/development-source.js +48 -0
- package/bundle/development-test-runner.js +13 -0
- package/bundle/development-tools.js +45 -0
- package/bundle/development-worker-review.js +110 -0
- package/bundle/development-worker.js +68 -0
- package/bundle/development-workspace.js +54 -0
- package/bundle/diagnostics.js +78 -0
- package/bundle/distribution-lock.json +773 -0
- package/bundle/drained-process.js +26 -0
- package/bundle/durable-inbox.js +294 -0
- package/bundle/feishu-policy.js +24 -0
- package/bundle/gateway-maintenance.js +55 -0
- package/bundle/global-rules/AGENTS.md +83 -0
- package/bundle/im-delivery.js +60 -0
- package/bundle/index.js +445 -0
- package/bundle/intervention-actions.js +135 -0
- package/bundle/intervention-job-control.js +28 -0
- package/bundle/intervention-state.js +43 -0
- package/bundle/job-version.js +15 -0
- package/bundle/legacy-feishu-adapter.js +89 -0
- package/bundle/link-contract.js +80 -0
- package/bundle/maintenance-process-identity.js +93 -0
- package/bundle/model-selection.js +71 -0
- package/bundle/native-context.js +14 -0
- package/bundle/native-entry-admission.js +2 -0
- package/bundle/native-entry.js +58 -0
- package/bundle/native-file-reference.js +32 -0
- package/bundle/native-owner-origin.js +12 -0
- package/bundle/native-rules/AGENTS.md +199 -0
- package/bundle/native-tools.js +108 -0
- package/bundle/notification-artifacts.js +70 -0
- package/bundle/notification-contract.js +29 -0
- package/bundle/notification-defaults.js +81 -0
- package/bundle/notification-discovery.js +65 -0
- package/bundle/notification-endpoint.js +54 -0
- package/bundle/notification-feishu.js +51 -0
- package/bundle/notification-media-endpoint.js +94 -0
- package/bundle/notification-review.js +27 -0
- package/bundle/notification-targets.js +54 -0
- package/bundle/onboarding-activity.js +66 -0
- package/bundle/onboarding-agent-hold.js +94 -0
- package/bundle/onboarding-boundary.js +20 -0
- package/bundle/onboarding-cloud-contract.js +29 -0
- package/bundle/onboarding-cloud-file-review.js +58 -0
- package/bundle/onboarding-cloud-files.js +100 -0
- package/bundle/onboarding-cloud-im.js +34 -0
- package/bundle/onboarding-cloud-model-probe.js +53 -0
- package/bundle/onboarding-cloud-models.js +68 -0
- package/bundle/onboarding-cloud-operation.js +276 -0
- package/bundle/onboarding-cloud-package.js +38 -0
- package/bundle/onboarding-cloud-repositories.js +89 -0
- package/bundle/onboarding-cloud-retirement.js +59 -0
- package/bundle/onboarding-cloud-task-runtime.js +90 -0
- package/bundle/onboarding-cloud-web.js +85 -0
- package/bundle/onboarding-cloud.js +110 -0
- package/bundle/onboarding-coordinated-hold.js +94 -0
- package/bundle/onboarding-exclusive-rename.js +16 -0
- package/bundle/onboarding-existing-host.js +63 -0
- package/bundle/onboarding-existing-setup.js +123 -0
- package/bundle/onboarding-file-contract.js +31 -0
- package/bundle/onboarding-file-review-contract.js +38 -0
- package/bundle/onboarding-file-transfer.js +133 -0
- package/bundle/onboarding-handoff-remote.js +98 -0
- package/bundle/onboarding-handoff.js +112 -0
- package/bundle/onboarding-host-stop-observation.js +44 -0
- package/bundle/onboarding-host.js +254 -0
- package/bundle/onboarding-identity.js +9 -0
- package/bundle/onboarding-im-maintenance-native.js +30 -0
- package/bundle/onboarding-im-maintenance.js +70 -0
- package/bundle/onboarding-im.js +31 -0
- package/bundle/onboarding-inspection-guard.js +15 -0
- package/bundle/onboarding-install-fs.js +58 -0
- package/bundle/onboarding-installer.js +157 -0
- package/bundle/onboarding-local-pair-native.js +21 -0
- package/bundle/onboarding-local-pair.js +99 -0
- package/bundle/onboarding-maintenance-fs.js +69 -0
- package/bundle/onboarding-maintenance-plan.js +213 -0
- package/bundle/onboarding-maintenance-record.js +169 -0
- package/bundle/onboarding-maintenance.js +163 -0
- package/bundle/onboarding-model-probe.js +119 -0
- package/bundle/onboarding-models.js +107 -0
- package/bundle/onboarding-native-host.js +101 -0
- package/bundle/onboarding-native-probe.js +56 -0
- package/bundle/onboarding-native-runner.js +29 -0
- package/bundle/onboarding-node-bootstrap.py +678 -0
- package/bundle/onboarding-node.js +77 -0
- package/bundle/onboarding-notification-defaults.js +93 -0
- package/bundle/onboarding-package-source.js +33 -0
- package/bundle/onboarding-paths.js +58 -0
- package/bundle/onboarding-peer-binding.js +61 -0
- package/bundle/onboarding-peer-contract.js +12 -0
- package/bundle/onboarding-plugin-repair.js +116 -0
- package/bundle/onboarding-plugin-version.js +143 -0
- package/bundle/onboarding-remote-control.js +140 -0
- package/bundle/onboarding-remote-probe.js +40 -0
- package/bundle/onboarding-repositories.js +88 -0
- package/bundle/onboarding-repository.js +49 -0
- package/bundle/onboarding-runtime-activation.js +83 -0
- package/bundle/onboarding-runtime-artifacts-client.js +87 -0
- package/bundle/onboarding-runtime-artifacts.js +126 -0
- package/bundle/onboarding-runtime-extension.js +400 -0
- package/bundle/onboarding-runtime-inventory.js +88 -0
- package/bundle/onboarding-runtime-program.js +42 -0
- package/bundle/onboarding-runtime-reclaim-client.js +94 -0
- package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
- package/bundle/onboarding-runtime-reclaim.js +132 -0
- package/bundle/onboarding-runtime-repair-client.js +50 -0
- package/bundle/onboarding-runtime-repair.js +88 -0
- package/bundle/onboarding-runtime-stop.js +90 -0
- package/bundle/onboarding-runtime-uninstall-client.js +88 -0
- package/bundle/onboarding-runtime-uninstall.js +167 -0
- package/bundle/onboarding-runtime-version-client.js +138 -0
- package/bundle/onboarding-runtime-version.js +145 -0
- package/bundle/onboarding-schema.js +42 -0
- package/bundle/onboarding-self-disable.js +3 -0
- package/bundle/onboarding-self-lifecycle.js +95 -0
- package/bundle/onboarding-self-maintenance.js +52 -0
- package/bundle/onboarding-self-remove.js +3 -0
- package/bundle/onboarding-self-stop.js +85 -0
- package/bundle/onboarding-ssh-forward.js +48 -0
- package/bundle/onboarding-ssh.js +105 -0
- package/bundle/onboarding-state.js +95 -0
- package/bundle/onboarding-task-runtime-contract.js +38 -0
- package/bundle/onboarding-task-runtime-native.js +80 -0
- package/bundle/onboarding-task-runtime.js +66 -0
- package/bundle/onboarding-token-plan.js +52 -0
- package/bundle/onboarding-version-activation-client.js +48 -0
- package/bundle/onboarding-version-candidate.js +96 -0
- package/bundle/onboarding-version-repair.js +128 -0
- package/bundle/package-lock.json +773 -0
- package/bundle/package.json +99 -0
- package/bundle/peer-file-fs.js +62 -0
- package/bundle/peer-file-migration.js +59 -0
- package/bundle/peer-file-review.js +107 -0
- package/bundle/peer-files.js +157 -0
- package/bundle/peer-mailbox.js +75 -0
- package/bundle/protocol.js +17 -0
- package/bundle/recovery.js +40 -0
- package/bundle/repository-catalog.js +85 -0
- package/bundle/repository-gitee.js +76 -0
- package/bundle/repository-managed.js +46 -0
- package/bundle/repository-writer.js +43 -0
- package/bundle/rules/AGENTS.md +22 -0
- package/bundle/runtime-im-lock.json +11577 -0
- package/bundle/runtime-im-package.json +18 -0
- package/bundle/runtime-lock.json +10152 -0
- package/bundle/runtime-package.json +17 -0
- package/bundle/scheduler-migration.js +45 -0
- package/bundle/search-contract.js +19 -0
- package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
- package/bundle/skills/task-a2a/SKILL.md +55 -0
- package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
- package/bundle/skills/task-approval/SKILL.md +128 -0
- package/bundle/skills/task-artifacts/SKILL.md +46 -0
- package/bundle/skills/task-development/SKILL.md +144 -0
- package/bundle/skills/task-diagnostics/SKILL.md +41 -0
- package/bundle/skills/task-direct-link/SKILL.md +143 -0
- package/bundle/skills/task-file-transfer/SKILL.md +107 -0
- package/bundle/skills/task-handoff/SKILL.md +23 -0
- package/bundle/skills/task-intake/SKILL.md +13 -0
- package/bundle/skills/task-notify/SKILL.md +102 -0
- package/bundle/skills/task-onboarding/SKILL.md +708 -0
- package/bundle/skills/task-recovery/SKILL.md +54 -0
- package/bundle/skills/task-repository/SKILL.md +145 -0
- package/bundle/skills/task-research/SKILL.md +43 -0
- package/bundle/skills/task-schedule/SKILL.md +79 -0
- package/bundle/skills/task-sidebar/SKILL.md +122 -0
- package/bundle/skills/task-workbench/SKILL.md +30 -0
- package/bundle/skills/task-worker/SKILL.md +88 -0
- package/bundle/source-search.js +89 -0
- package/bundle/source-web.js +17 -0
- package/bundle/ssh-connector.js +24 -0
- package/bundle/store.js +102 -0
- package/bundle/task-a2a.js +298 -0
- package/bundle/task-artifacts.js +179 -0
- package/bundle/task-board-a2a.js +55 -0
- package/bundle/task-board-development.js +83 -0
- package/bundle/task-board-planning.js +84 -0
- package/bundle/task-board.js +132 -0
- package/bundle/task-branch.js +2 -0
- package/bundle/task-catalog.js +77 -0
- package/bundle/task-context.js +40 -0
- package/bundle/task-envelope.js +96 -0
- package/bundle/task-interventions.js +54 -0
- package/bundle/task-jobs.js +156 -0
- package/bundle/task-notifications.js +132 -0
- package/bundle/task-results.js +16 -0
- package/bundle/task-scheduler.js +77 -0
- package/bundle/task-sources.js +101 -0
- package/bundle/task-trigger-time.js +46 -0
- package/bundle/task-triggers.js +157 -0
- package/bundle/task-worker.js +73 -0
- package/bundle/task-workflows.js +117 -0
- package/bundle/tools.js +13 -0
- package/bundle/workbench-assets/asset-provenance.json +26 -0
- package/bundle/workbench-assets/whale-ui-states.png +0 -0
- package/bundle/workbench-client.js +811 -0
- package/bundle/workbench-decisions.js +48 -0
- package/bundle/workbench-host.js +122 -0
- package/bundle/workbench-im-identity.js +51 -0
- package/bundle/workbench-proxy.js +127 -0
- package/bundle/worker-rules/AGENTS.md +84 -0
- package/bundle/worker-tools.js +13 -0
- package/compatibility.json +980 -0
- package/cordis.patch.yml +3 -0
- package/package.json +57 -4
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Safe receiver state for the owned runtime. Contract 4 separately attests explicit read-only worker consent.
|
|
2
|
+
export function isManagedTaskRuntime(s){
|
|
3
|
+
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
|
|
4
|
+
return !!s&&[1,2,3,4].includes(s.contract)&&s.available===true&&s.owned===true&&s.scope==='current_host_only'&&s.role==='cloud'&&s.configured===true&&s.desiredEnabled===true&&s.state==='active'&&uuid(s.id)&&uuid(s.instanceId)&&uuid(s.appliedOperation)&&/^[a-f0-9]{64}$/.test(s.appliedPlanHash)&&Number.isSafeInteger(s.revision)&&s.revision>0&&s.listen==='127.0.0.1'&&Number.isInteger(s.port)&&s.port>0&&s.port<65536&&s.repositoryRuntime===true&&validWorker(s)&&(s.contract>=3?validPairing(s.pairing,s)&&s.peerEnabled===s.pairing.mounted:s.peerEnabled===false)&&s.writeAuthorized===false&&s.publishEnabled===false&&s.error===null;
|
|
5
|
+
}
|
|
6
|
+
export function isManagedGatewayReceipt(r){return r?.gatewayBound===true&&r.runtimeScopeVerified===true&&isManagedTaskRuntime(r.taskRuntime);}
|
|
7
|
+
// Attest the actual mounted runtime, including only the independently granted
|
|
8
|
+
// contract-3 mailbox. A gateway object or a claimed receipt alone is insufficient.
|
|
9
|
+
export function isManagedGatewayRuntime(g,s){
|
|
10
|
+
return !!g&&isManagedTaskRuntime(s)&&g.instanceId===s.instanceId&&g.c?.role==='cloud'&&g.c.namespace==='managed-'+s.id&&(s.workerEnabled?g.scheduler?.started===true&&!g.scheduler.closed&&g.c.scheduler?.preset==='dsh-onboarding-readonly-worker'&&g.scheduler.executors.size===1&&g.scheduler.executors.has('plan'):!g.scheduler)&&!g.development&&!g.deliveryRuntime&&!!g.peer===s.peerEnabled&&(!s.peerEnabled||g.c.peerEnabled===true&&g.peer.role==='cloud'&&g.peer.namespace===s.pairing.namespace);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const exact=(v,ks)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===ks.slice().sort().join();
|
|
14
|
+
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
|
|
15
|
+
const hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
16
|
+
const revision=v=>Number.isSafeInteger(v)&&v>=0&&v<Number.MAX_SAFE_INTEGER-1;
|
|
17
|
+
const fail=()=>{throw Error('ONBOARDING_TASK_RUNTIME_RESPONSE_REVIEW');};
|
|
18
|
+
function target(v){if(!exact(v,['role','name','source','platform'])||v.role!=='cloud'||v.name!=='云端大肥鱼'||v.source!=='setup_configuration'||v.platform!=='linux')fail();}
|
|
19
|
+
export function cloudTaskRuntimePlan(v){
|
|
20
|
+
if(!exact(v,['id','enabled','revision','target','expiresAt','fingerprint','contract','scope','workerEnabled','peerEnabled','writeAuthorized','publishEnabled'])||![2,3,4].includes(v.contract)||!uuid(v.id)||typeof v.enabled!=='boolean'||!revision(v.revision)||!Number.isSafeInteger(v.expiresAt)||!hex(v.fingerprint)||v.scope!=='current_host_only'||(v.contract===4?typeof v.workerEnabled!=='boolean'||v.workerEnabled&&!v.enabled:v.workerEnabled!==false)||v.peerEnabled!==false||v.writeAuthorized!==false||v.publishEnabled!==false)fail();target(v.target);return v;
|
|
21
|
+
}
|
|
22
|
+
export function cloudTaskRuntimeStatus(v){
|
|
23
|
+
if(!exact(v,['contract','available','scope','owned','role','target','id','revision','appliedOperation','appliedPlanHash','desiredEnabled','configured','state','instanceId','listen','port','repositoryRuntime','workerEnabled','peerEnabled','writeAuthorized','publishEnabled','error',...(v?.contract>=3?['pairing']:[]),...(v?.contract===4?['workerDesiredEnabled']:[])])||![2,3,4].includes(v.contract)||v.available!==true||v.owned!==true||v.role!=='cloud'||v.scope!=='current_host_only'||!revision(v.revision)||typeof v.desiredEnabled!=='boolean'||typeof v.configured!=='boolean'||!validWorker(v)||(v.contract>=3?(!validPairing(v.pairing,v)||v.peerEnabled!==v.pairing.mounted):v.peerEnabled!==false)||v.writeAuthorized!==false||v.publishEnabled!==false||v.repositoryRuntime!==v.configured||v.error!==null&&!/^ONBOARDING_TASK_RUNTIME_[A-Z_]+$/.test(v.error))fail();target(v.target);
|
|
24
|
+
if(v.revision===0){if(v.id!==null||v.appliedOperation!==null||v.appliedPlanHash!==null||v.desiredEnabled)fail();}else if(!uuid(v.id)||!uuid(v.appliedOperation)||!hex(v.appliedPlanHash))fail();
|
|
25
|
+
if(v.configured){if(!isManagedTaskRuntime(v))fail();}else if(v.instanceId!==null||v.listen!==null||v.port!==null||v.state!==(v.error?'needs_review':v.desiredEnabled?'activation_pending':v.revision?'disabled':'not_configured'))fail();return v;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Runtime contract 3 attests the owned single-controller transport separately.
|
|
29
|
+
function validPairing(p,s){
|
|
30
|
+
if(!exact(p,['contract','revision','id','localId','runtimeId','enabled','mounted','namespace','appliedOperation','appliedPlanHash','workerEnabled','writeAuthorized','publishEnabled'])||p.contract!==1||!revision(p.revision)||p.runtimeId!==s.id||p.namespace!==(s.id?'managed-'+s.id:null)||typeof p.enabled!=='boolean'||typeof p.mounted!=='boolean'||p.workerEnabled!==false||p.writeAuthorized!==false||p.publishEnabled!==false||p.mounted&&(!p.enabled||!s.configured)||p.enabled&&!s.desiredEnabled)return false;
|
|
31
|
+
return p.revision===0?p.id===null&&p.localId===null&&p.appliedOperation===null&&p.appliedPlanHash===null&&!p.enabled&&!p.mounted:uuid(p.id)&&uuid(p.localId)&&uuid(p.runtimeId)&&uuid(p.appliedOperation)&&hex(p.appliedPlanHash);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Authorization and live scheduling are separate facts. Legacy receipts can never grant execution.
|
|
35
|
+
function validWorker(s){
|
|
36
|
+
if(s.contract!==4)return s.workerEnabled===false;
|
|
37
|
+
return typeof s.workerDesiredEnabled==='boolean'&&typeof s.workerEnabled==='boolean'&&(!s.workerDesiredEnabled||s.desiredEnabled===true)&&s.workerEnabled===(s.configured===true&&s.workerDesiredEnabled);
|
|
38
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {createOnboardingFileTransfer,isManagedFileOutbox} from './onboarding-file-transfer.js';
|
|
2
|
+
// Fixed own runtime configuration. Never writes the DSH profile or loads user tokens.
|
|
3
|
+
import {peerBindingKey} from './onboarding-peer-binding.js';
|
|
4
|
+
import {errorInfo} from './link-contract.js';
|
|
5
|
+
import fs from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
const workerPreset='dsh-onboarding-readonly-worker';
|
|
9
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
10
|
+
import {Gateway,inject as gatewayInject} from './index.js';
|
|
11
|
+
import {onboardingBoundary} from './onboarding-boundary.js';
|
|
12
|
+
import {createOnboardingRepository} from './onboarding-repository.js';
|
|
13
|
+
import {createOnboardingRepositories} from './onboarding-repositories.js';
|
|
14
|
+
import {installWorkbench} from './workbench-host.js';
|
|
15
|
+
import {installTaskBoard} from './task-board.js';
|
|
16
|
+
import {installArtifactAccess} from './task-artifacts.js';
|
|
17
|
+
import * as nativeTools from './native-tools.js';
|
|
18
|
+
const fail=c=>{throw Error('ONBOARDING_TASK_RUNTIME_'+c);};
|
|
19
|
+
async function checked(p,dir){const s=await fs.lstat(p);if(s.isSymbolicLink()||!(dir?s.isDirectory():s.isFile())||!dir&&s.nlink!==1||(s.mode&0o077)||process.getuid&&s.uid!==process.getuid())fail('PATH_REVIEW');return s;}
|
|
20
|
+
export async function taskRuntimeLease(config,runtime,id){
|
|
21
|
+
if(typeof id!=='string'||!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(id))fail('ARGUMENTS');
|
|
22
|
+
const {paths}=onboardingBoundary(config,runtime,'persistence'),parent=path.join(paths.dsh.path,'dual-host-task-runtime'),root=path.join(parent,id);
|
|
23
|
+
// DSH root exists already; never recursively create or follow arbitrary ancestors.
|
|
24
|
+
for(let p=paths.dsh.path;p!==path.dirname(p);p=path.dirname(p)){const s=await fs.lstat(p);if(s.isSymbolicLink()||!s.isDirectory())fail('PATH_REVIEW');}
|
|
25
|
+
try{await fs.mkdir(parent,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}await checked(parent,true);
|
|
26
|
+
const owner=JSON.stringify({owner:'dsh-dual-host-task-runtime',schema:1,id});
|
|
27
|
+
try{await fs.mkdir(root,{mode:0o700});await fs.writeFile(path.join(root,'owner.json'),owner,{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}
|
|
28
|
+
await checked(root,true);await checked(path.join(root,'owner.json'),false);if(await fs.readFile(path.join(root,'owner.json'),'utf8')!==owner)fail('PATH_REVIEW');
|
|
29
|
+
const lock=path.join(root,'exclusive.sqlite');try{await fs.writeFile(lock,'',{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}await checked(lock,false);
|
|
30
|
+
const db=new DatabaseSync(lock);try{db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE;');}catch{db.close();fail('ALREADY_RUNNING');}
|
|
31
|
+
// Under the exclusive lease, refuse pre-existing linked/foreign state before SQLite opens it.
|
|
32
|
+
try{
|
|
33
|
+
// SQLite inherits the initial file mode; do not change the process-wide umask.
|
|
34
|
+
for(const relative of ['state','state/coordinator']){const p=path.join(root,relative);try{await fs.mkdir(p,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}await checked(p,true);}
|
|
35
|
+
for(const relative of ['state/gateway.sqlite','state/coordinator/tasks.sqlite']){const p=path.join(root,relative);try{await fs.writeFile(p,'',{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}await checked(p,false);}
|
|
36
|
+
let seen=0;async function inspect(dir){for(const name of await fs.readdir(dir)){if(++seen>10000)fail('PATH_REVIEW');const p=path.join(dir,name),s=await fs.lstat(p);await checked(p,s.isDirectory());if(s.isDirectory()&&!isManagedFileOutbox(root,p))await inspect(p);}}await inspect(root);}catch(e){db.exec('ROLLBACK');db.close();throw e;}
|
|
37
|
+
let released=false;return {root,release(){if(released)return;released=true;try{db.exec('ROLLBACK');}finally{db.close();}}};
|
|
38
|
+
}
|
|
39
|
+
export function nativeTaskRuntimeAdapter(ctx,config,runtime,state){
|
|
40
|
+
return {async open(p,authorize){
|
|
41
|
+
if(ctx.get('taskGateway'))fail('SERVICE_CONFLICT');
|
|
42
|
+
const lease=await taskRuntimeLease(config,runtime,p.id);let g,fiber,tools,files,unregisterWorker;
|
|
43
|
+
try{
|
|
44
|
+
const workspace=path.join(lease.root,'worker-workspace');
|
|
45
|
+
if(p.workerEnabled){try{await fs.mkdir(workspace,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}await checked(workspace,true);}
|
|
46
|
+
const repository={state,fetch:runtime.repositoryFetch,registry:createOnboardingRepositories({state,credentials:()=>runtime.credentials,repository:createOnboardingRepository({state,config,runtime}),config,runtime})};
|
|
47
|
+
fiber=ctx.plugin({name:'dual-host-managed-task-runtime',inject:gatewayInject,async apply(scope){
|
|
48
|
+
await authorize();
|
|
49
|
+
g=new Gateway(scope,{role:'cloud',stateDir:path.join(lease.root,'state'),namespace:'managed-'+p.id,port:0,entryMode:'native',legacyFeishu:false,peerEnabled:!!p.pairing?.enabled,repositoryAccess:{managedOnboarding:true},workbench:{enabled:true},...(p.workerEnabled?{scheduler:{lockPort:0,workspace,preset:workerPreset,maxConcurrent:1,timeoutMs:180000}}:{})},{scheduler:{allowEphemeralLock:true},secrets:{localToken:p.localToken,cloudToken:p.cloudToken},authorize,repository});
|
|
50
|
+
const {paths}=onboardingBoundary(config,runtime,'persistence');files=createOnboardingFileTransfer({g,root:lease.root,credentials:()=>runtime.credentials??scope.credentials,protectedRoots:[paths.dsh.path,paths.agents.path]});await files.start();
|
|
51
|
+
scope.provide('taskGateway',g);
|
|
52
|
+
if(p.workerEnabled){
|
|
53
|
+
unregisterWorker=await scope.agentPresets.register({id:workerPreset,name:'云端只读任务 Worker',description:'本项目只读后台执行;不改变原生模式或开放仓库写入。',plugins:[
|
|
54
|
+
{name:'@deepseek-ai/dsh-agent-instructions',config:{dshHome:fileURLToPath(new URL('./worker-rules',import.meta.url)),maxBytes:16384}},
|
|
55
|
+
{name:'@deepseek-ai/dsh-skill-filesystem',config:{providerName:'dsh-onboarding-worker-skills',includeDefaultRoots:false,customSkillDirs:[fileURLToPath(new URL('./skills',import.meta.url))],watch:false}},
|
|
56
|
+
{name:'@deepseek-ai/dsh-tool-skill'},
|
|
57
|
+
{name:fileURLToPath(new URL('./worker-tools.js',import.meta.url))}
|
|
58
|
+
]});
|
|
59
|
+
scope.effect(()=>()=>unregisterWorker?.());
|
|
60
|
+
}
|
|
61
|
+
installWorkbench(scope,g,{enabled:true});installTaskBoard(scope,g);installArtifactAccess(scope,g);
|
|
62
|
+
tools=scope.plugin({name:'dual-host-managed-native-tools',inject:nativeTools.inject,apply:nativeTools.apply});
|
|
63
|
+
}});await fiber.await();await tools?.await();
|
|
64
|
+
if(p.workerEnabled){const row=(await ctx.agentPresets.list()).find(x=>x.id===workerPreset);if(!row||row.broken)fail('WORKER_PRESET_REVIEW');}
|
|
65
|
+
await g.start();
|
|
66
|
+
if(!g?.server?.listening||g.closed||ctx.get('taskGateway')!==g)fail('START_REVIEW');
|
|
67
|
+
let ending;
|
|
68
|
+
return {files,id:p.id,instanceId:g.instanceId,pairingKey:peerBindingKey(p.pairing),get workerEnabled(){return !!g.scheduler?.started&&!g.scheduler.closed;},port:g.server.address().port,
|
|
69
|
+
async forward(frame){
|
|
70
|
+
await authorize();if(!p.pairing?.enabled||ending)fail('PAIR_AUTH_DENIED');
|
|
71
|
+
const res=await fetch('http://127.0.0.1:'+g.server.address().port+'/rpc',{method:'POST',redirect:'error',headers:{'Content-Type':'application/json',Authorization:'Bearer '+p.localToken},body:JSON.stringify(frame),signal:AbortSignal.timeout(20000)});
|
|
72
|
+
let size=0,chunks=[];for await(const chunk of res.body){size+=chunk.length;if(size>524288)fail('PAIR_RESPONSE_REVIEW');chunks.push(chunk);}let value;try{value=JSON.parse(Buffer.concat(chunks));}catch{fail('PAIR_RESPONSE_REVIEW');}
|
|
73
|
+
return res.ok?{ok:true,value}:{ok:false,error:errorInfo(value?.error).code};
|
|
74
|
+
},active:()=>!ending&&!g.closed&&g.server.listening,
|
|
75
|
+
async quiescent(){if(!g.maintenance.status().canHold)fail('BUSY');},
|
|
76
|
+
hold(){const plan=g.maintenance.preview();try{g.maintenance.apply({id:plan.id,fingerprint:plan.fingerprint,confirm:true});}catch{fail('BUSY');}},
|
|
77
|
+
close(){return ending??=(async()=>{try{await files?.close();await g.close();await unregisterWorker?.();await fiber.dispose();}finally{lease.release();}})();}};
|
|
78
|
+
}catch(e){try{await files?.close();await g?.close();await unregisterWorker?.();await fiber?.dispose();}finally{lease.release();}throw e;}
|
|
79
|
+
}};
|
|
80
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Intake and read-only worker are separate explicit choices. Neither grants development consent.
|
|
2
|
+
import {createOnboardingPeerBinding,peerBindingKey} from './onboarding-peer-binding.js';
|
|
3
|
+
import {credentialKey} from '@deepseek-ai/dsh-credentials';
|
|
4
|
+
import {randomUUID,randomBytes} from 'node:crypto';
|
|
5
|
+
import {digest} from './onboarding-ssh.js';
|
|
6
|
+
import {onboardingIdentity} from './onboarding-identity.js';
|
|
7
|
+
const KEY=credentialKey('dsh-task-gateway','onboarding-task-runtime-v1'),OWNER='dsh-dual-host-task-runtime';
|
|
8
|
+
const exact=(v,ks)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===ks.slice().sort().join();
|
|
9
|
+
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
|
|
10
|
+
const hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
11
|
+
const fail=c=>{throw Error('ONBOARDING_TASK_RUNTIME_'+c);};
|
|
12
|
+
function record(r){
|
|
13
|
+
if(!r)return null;const p=r.payload;
|
|
14
|
+
if(r.kind!=='grant'||!exact(p,['owner','schema','id','revision','operation','planHash','enabled','updatedAt','localToken','cloudToken',...(p?.schema===2?['workerEnabled']:[])])||p.owner!==OWNER||![1,2].includes(p.schema)||p.schema===2&&(typeof p.workerEnabled!=='boolean'||p.workerEnabled&&!p.enabled)||!uuid(p.id)||!uuid(p.operation)||!hex(p.planHash)||!Number.isSafeInteger(p.revision)||p.revision<1||p.revision>=Number.MAX_SAFE_INTEGER-1||!Number.isSafeInteger(p.updatedAt)||typeof p.enabled!=='boolean'||!hex(p.localToken)||!hex(p.cloudToken)||p.localToken===p.cloudToken)fail('RECORD_REVIEW');return {...p,workerEnabled:p.schema===2&&p.workerEnabled};
|
|
15
|
+
}
|
|
16
|
+
export function createOnboardingTaskRuntime({state,credentials,config={},adapter,now=Date.now,platform=process.platform}){
|
|
17
|
+
const identity={...onboardingIdentity(config),platform};let pending=null,handle=null,busy=false,closed=false,lastError=null;
|
|
18
|
+
const available=()=>!closed&&identity.role==='cloud'&&!config.role&&!config.stateDir&&!config.tokenFile&&state.available()&&!!credentials()&&!!adapter;
|
|
19
|
+
const ready=()=>{if(!available())fail('UNAVAILABLE');return credentials();};
|
|
20
|
+
const read=async()=>record(await ready().readRecord(KEY));
|
|
21
|
+
const pairing=createOnboardingPeerBinding({credentials,available,runtime:read,handle:()=>handle,run,refresh:async()=>sync(await read()),now});
|
|
22
|
+
async function run(fn){if(busy)fail('BUSY');busy=true;try{return await fn();}finally{busy=false;}}
|
|
23
|
+
async function authorized(id){const p=await read();if(!p?.enabled||p.id!==id)fail('DISABLED');}
|
|
24
|
+
async function sync(p){
|
|
25
|
+
if(!p?.enabled){await handle?.close();handle=null;lastError=null;return;}
|
|
26
|
+
const binding=await pairing.binding(p.id);
|
|
27
|
+
if(handle?.id===p.id&&handle.active()&&(handle.pairingKey??null)===peerBindingKey(binding)&&!!handle.workerEnabled===p.workerEnabled)return;
|
|
28
|
+
await handle?.close();handle=null;
|
|
29
|
+
try{const candidate=await adapter.open({...p,pairing:binding},()=>authorized(p.id));if(closed){await candidate.close();fail('CLOSED');}if(!!candidate.workerEnabled!==p.workerEnabled){await candidate.close();fail('WORKER_START_REVIEW');}handle=candidate;lastError=null;}
|
|
30
|
+
catch(e){lastError=/^ONBOARDING_TASK_RUNTIME_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_TASK_RUNTIME_START_REVIEW';}
|
|
31
|
+
}
|
|
32
|
+
async function start(){if(!available())return;return run(async()=>{try{await sync(await read());}catch{lastError='ONBOARDING_TASK_RUNTIME_RECORD_REVIEW';}});}
|
|
33
|
+
async function status(a={}){
|
|
34
|
+
if(!exact(a,[]))fail('ARGUMENTS');
|
|
35
|
+
if(!available())return {contract:4,available:false,owned:false,configured:false,writeAuthorized:false};
|
|
36
|
+
const p=await read(),peer=await pairing.status({}),active=!!p?.enabled&&handle?.id===p.id&&handle.active()===true;
|
|
37
|
+
return {contract:4,available:true,scope:'current_host_only',owned:true,role:'cloud',target:identity,id:p?.id??null,revision:p?.revision??0,appliedOperation:p?.operation??null,appliedPlanHash:p?.planHash??null,desiredEnabled:p?.enabled??false,configured:active,state:active?'active':lastError?'needs_review':p?.enabled?'activation_pending':p?'disabled':'not_configured',instanceId:active?handle.instanceId:null,listen:active?'127.0.0.1':null,port:active?handle.port:null,repositoryRuntime:active,workerDesiredEnabled:p?.workerEnabled??false,workerEnabled:active&&handle.workerEnabled===true,peerEnabled:peer.mounted,pairing:peer,writeAuthorized:false,publishEnabled:false,error:lastError};
|
|
38
|
+
}
|
|
39
|
+
async function preview(a){return run(async()=>{
|
|
40
|
+
pending=null;if(!exact(a,['enabled',...(a.workerEnabled!==undefined?['workerEnabled']:[])])||typeof a.enabled!=='boolean'||a.workerEnabled!==undefined&&typeof a.workerEnabled!=='boolean'||a.workerEnabled&&!a.enabled)fail('ARGUMENTS');
|
|
41
|
+
const p=await read();if(!a.enabled){if((await pairing.status({})).enabled)fail('PAIR_REVOKE_REQUIRED');await pairing.quiescent();}
|
|
42
|
+
const body={id:randomUUID(),enabled:a.enabled,workerEnabled:a.workerEnabled??false,revision:p?.revision??0,target:identity,expiresAt:now()+300000};pending={...body,fingerprint:digest(body)};
|
|
43
|
+
return {...pending,contract:4,scope:'current_host_only',peerEnabled:false,writeAuthorized:false,publishEnabled:false};
|
|
44
|
+
});}
|
|
45
|
+
async function apply(a){return run(async()=>{
|
|
46
|
+
if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
|
|
47
|
+
const p=pending;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');pending=null;
|
|
48
|
+
if(!p.enabled){if((await pairing.status({})).enabled)fail('PAIR_REVOKE_REQUIRED');await pairing.quiescent();}
|
|
49
|
+
// Close admission synchronously while idle, before the async credential CAS.
|
|
50
|
+
// A lost write result leaves the runtime closed, not executing under uncertain consent.
|
|
51
|
+
await pairing.quiescent();
|
|
52
|
+
if(handle){if(typeof handle.hold!=='function')fail('HOLD_UNAVAILABLE');handle.hold();}
|
|
53
|
+
try{
|
|
54
|
+
await ready().modifyRecord(KEY,old=>{const prior=record(old);if((prior?.revision??0)!==p.revision)fail('CONFLICT');return {kind:'grant',payload:{owner:OWNER,schema:2,id:prior?.id??randomUUID(),revision:p.revision+1,operation:p.id,planHash:p.fingerprint,enabled:p.enabled,workerEnabled:p.workerEnabled,updatedAt:now(),localToken:prior?.localToken??randomBytes(32).toString('hex'),cloudToken:prior?.cloudToken??randomBytes(32).toString('hex')}};});
|
|
55
|
+
await handle?.close();handle=null;await sync(await read());return status({});
|
|
56
|
+
}catch(e){try{await handle?.close();}finally{handle=null;lastError='ONBOARDING_TASK_RUNTIME_AUTHORIZATION_REVIEW';}throw e;}
|
|
57
|
+
});}
|
|
58
|
+
async function fence(a){return run(async()=>{
|
|
59
|
+
if(!exact(a,['operation','expectedRevision','confirm'])||!uuid(a.operation)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.expectedRevision>=Number.MAX_SAFE_INTEGER-1||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
|
|
60
|
+
// Fencing preserves existing authorization and data; it never activates or stops a runtime.
|
|
61
|
+
await ready().modifyRecord(KEY,old=>{const p=record(old);if((p?.revision??0)!==a.expectedRevision)fail('CONFLICT');return {kind:'grant',payload:{owner:OWNER,schema:2,id:p?.id??randomUUID(),revision:a.expectedRevision+1,operation:a.operation,planHash:digest(a),enabled:p?.enabled??false,workerEnabled:p?.workerEnabled??false,updatedAt:now(),localToken:p?.localToken??randomBytes(32).toString('hex'),cloudToken:p?.cloudToken??randomBytes(32).toString('hex')}};});
|
|
62
|
+
return status({});
|
|
63
|
+
});}
|
|
64
|
+
async function close(){closed=true;pending=null;await handle?.close();handle=null;}
|
|
65
|
+
return {available,start,status,preview,apply,fence,close,pairing,get files(){return handle?.files;},get configured(){return !closed&&handle?.active()===true;}};
|
|
66
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Optional native adapter, in our namespace. No changes to upstream plugin config.
|
|
2
|
+
import {createOnboardingModelBinding} from './onboarding-models.js';
|
|
3
|
+
export const TOKEN_PLAN_PROVIDER='dsh-onboarding-token-cn';
|
|
4
|
+
export const TOKEN_PLAN_NAME='阿里云 Token Plan(双端配置)';
|
|
5
|
+
export const TOKEN_PLAN_ENDPOINT='https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1';
|
|
6
|
+
const fail=()=>{throw Error('ONBOARDING_MODEL_ADAPTER_UNAVAILABLE');};
|
|
7
|
+
// Load only when this optional service is previewed/enabled. A missing optional
|
|
8
|
+
// dependency must not prevent the base DeepSeek onboarding from starting.
|
|
9
|
+
async function dependencies(){
|
|
10
|
+
try{
|
|
11
|
+
const [native,models,catalog,protocol,llm]=await Promise.all([
|
|
12
|
+
import('@deepseek-ai/dsh-llm-pi-ai'),import('@earendil-works/pi-ai/models'),
|
|
13
|
+
import('@earendil-works/pi-ai/providers/qwen-token-plan-cn'),
|
|
14
|
+
import('@earendil-works/pi-ai/api/openai-completions.lazy'),import('@deepseek-ai/dsh-llm')
|
|
15
|
+
]);
|
|
16
|
+
return {native,models,catalog,protocol,llm};
|
|
17
|
+
}catch{fail();}
|
|
18
|
+
}
|
|
19
|
+
export function createOnboardingTokenPlanModels(ctx,config={},runtime={}){
|
|
20
|
+
let prepared;
|
|
21
|
+
async function prepare(){
|
|
22
|
+
if(!prepared)prepared=(async()=>{
|
|
23
|
+
const d=await (runtime.loadTokenPlan??dependencies)(),source=d.catalog.qwenTokenPlanCnProvider();
|
|
24
|
+
if(source.id!=='qwen-token-plan-cn'||source.baseUrl!==TOKEN_PLAN_ENDPOINT)fail();
|
|
25
|
+
const catalog=source.getModels();
|
|
26
|
+
if(!catalog.length||catalog.some(m=>m.api!=='openai-completions'||m.baseUrl!==TOKEN_PLAN_ENDPOINT))fail();
|
|
27
|
+
const piProvider=d.models.createProvider({id:TOKEN_PLAN_PROVIDER,name:TOKEN_PLAN_NAME,baseUrl:TOKEN_PLAN_ENDPOINT,
|
|
28
|
+
// No env, file, OAuth or native credential fallback. resolveApiKey below is authoritative.
|
|
29
|
+
auth:{apiKey:{name:TOKEN_PLAN_NAME,resolve:async({credential})=>credential?.key?{auth:{apiKey:credential.key},source:TOKEN_PLAN_NAME}:undefined}},
|
|
30
|
+
models:catalog.map(m=>({...m,provider:TOKEN_PLAN_PROVIDER})),api:d.protocol.openAICompletionsApi()});
|
|
31
|
+
const profile={provider:TOKEN_PLAN_PROVIDER,displayName:TOKEN_PLAN_NAME,baseURL:TOKEN_PLAN_ENDPOINT,
|
|
32
|
+
api:'openai-completions',reasoning:'high',streamIdleTimeoutMs:300000,maxRequestImageBytes:20971520,
|
|
33
|
+
requestImagePixelBudget:4194304,requestImageMaxBytes:1048576,
|
|
34
|
+
retryPolicy:d.llm.resolveRetryPolicy({mode:'normal',maxRetries:0}),piProvider,
|
|
35
|
+
modelErrors:new Map(),configuredMaxTokens:new Map()};
|
|
36
|
+
return {d,profiles:new Map([[TOKEN_PLAN_PROVIDER,profile]])};
|
|
37
|
+
})().catch(()=>{prepared=undefined;fail();});
|
|
38
|
+
return prepared;
|
|
39
|
+
}
|
|
40
|
+
const definition={provider:TOKEN_PLAN_PROVIDER,providerName:TOKEN_PLAN_NAME,slot:'token-plan',record:'onboarding-token-cn-binding-v1',endpoint:TOKEN_PLAN_ENDPOINT,prepare,
|
|
41
|
+
async register(modelContext,resolveKey){
|
|
42
|
+
const {d,profiles}=await prepare(),deny=async()=>{throw new d.llm.LlmError('请使用本项目配置导览管理凭据。','MISSING_CREDENTIAL');};
|
|
43
|
+
const adapter=new d.native.PiAiAdapter({profiles:()=>profiles,
|
|
44
|
+
resolveApiKey:async provider=>{if(provider!==TOKEN_PLAN_PROVIDER)throw new d.llm.LlmError('非本项目模型路由。','NO_ADAPTER');return resolveKey();},
|
|
45
|
+
auth:{credentials:{read:async()=>undefined,list:async()=>[],modify:deny,delete:deny},authContext:{env:async()=>undefined,fileExists:async()=>false}},
|
|
46
|
+
resolveAttachments:()=>modelContext.get?.('attachments'),
|
|
47
|
+
resolveImageAccess:(attachments,ref)=>d.llm.resolveImageAttachmentAccess(attachments,p=>modelContext.get?.('fs')?.processPathFromHostPath(p),ref)});
|
|
48
|
+
(runtime.llm??modelContext.llm).registerAdapter([TOKEN_PLAN_PROVIDER],adapter);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
return createOnboardingModelBinding(ctx,config,runtime,definition);
|
|
52
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Point-in-time diagnostics only. Never changes file receipts or grants restart authority.
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {credentialKey} from '@deepseek-ai/dsh-credentials';
|
|
4
|
+
import {parseVersionRequest,versionPending,versionRecordKey} from './onboarding-runtime-version-client.js';
|
|
5
|
+
import {runtimeProgram,runtimeCommand} from './onboarding-runtime-program.js';
|
|
6
|
+
const hash=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
7
|
+
const fail=c=>{throw Error('ONBOARDING_CLOUD_VERSION_ACTIVATION_'+c);};
|
|
8
|
+
const exact=(v,k)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===k.slice().sort().join();
|
|
9
|
+
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
|
|
10
|
+
const version=v=>typeof v==='string'&&v.length<100&&/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(v);
|
|
11
|
+
const scope='maintained_plugin_version_observed';
|
|
12
|
+
const fields=['contract','scope','activationVerified','cached','liveStateVerified','observedAt','restartId','sameRecordedHost','automaticRestart','versionMaintenance','transactionState','pluginVersion','versionTransactionId','sameRecordedRelease','operationId','runtimeId','initialization','requestedTransactionId'];
|
|
13
|
+
export const versionActivationKey=id=>credentialKey('dsh-task-gateway','onboarding-version-activation-v1-'+id);
|
|
14
|
+
function check(v,p,runtimeId){
|
|
15
|
+
if(!exact(v,fields)||v.operationId!==p.id||v.runtimeId!==runtimeId||!uuid(runtimeId)||!uuid(v.requestedTransactionId)||v.contract!==1||v.scope!==scope||v.versionMaintenance!==true||v.initialization!==false||v.automaticRestart!==false||v.liveStateVerified!==false||!['activationVerified','cached','sameRecordedHost','sameRecordedRelease'].every(k=>typeof v[k]==='boolean')||v.cached===v.activationVerified)fail('RESPONSE_REVIEW');
|
|
16
|
+
if(v.observedAt===null){if(v.activationVerified||v.restartId!==null||v.transactionState!==null||v.pluginVersion!==null||v.versionTransactionId!==null||v.sameRecordedHost||v.sameRecordedRelease)fail('RESPONSE_REVIEW');}
|
|
17
|
+
else if(!Number.isSafeInteger(v.observedAt)||v.observedAt<=0||!uuid(v.restartId)||!uuid(v.versionTransactionId)||!version(v.pluginVersion)||!['committed','rolled_back'].includes(v.transactionState)||v.activationVerified&&(!v.sameRecordedHost||!v.sameRecordedRelease||v.versionTransactionId!==v.requestedTransactionId))fail('RESPONSE_REVIEW');
|
|
18
|
+
return v;
|
|
19
|
+
}
|
|
20
|
+
export async function runtimeVersionActivationClient({args,p,a,b,runtimeId,credentials,ssh}){
|
|
21
|
+
const action=args?.action,local=action==='activation_record';
|
|
22
|
+
if(!['activation_record','activation_status','activation_verify'].includes(action)||!exact(args,['action','operationId',...(local?[]:['id'])])||args.operationId!==p.id||!local&&!uuid(args.id))fail('ARGUMENTS');
|
|
23
|
+
const c=credentials(),key=versionActivationKey(p.id),binding=hash({operationId:p.id,archiveHash:p.archiveHash,bindingFingerprint:p.bindingFingerprint});
|
|
24
|
+
const parse=record=>{if(!record)return null;const d=record.payload;
|
|
25
|
+
if(record.kind!=='grant'||!exact(d,['schema','operationId','runtimeId','binding','records'])||d.schema!==1||d.operationId!==p.id||!uuid(d.runtimeId)||runtimeId&&d.runtimeId!==runtimeId||d.binding!==binding||!Array.isArray(d.records)||d.records.length>128)fail('LOCAL_LEDGER_REVIEW');
|
|
26
|
+
for(const r of d.records)check(r,p,d.runtimeId);return d;
|
|
27
|
+
};
|
|
28
|
+
let ledger=parse(await c.readRecord(key));
|
|
29
|
+
const decode=n=>{const f=a.files.find(f=>f.path==='plugin/'+n);if(!f)fail('ARCHIVE_REVIEW');return Buffer.from(f.data,'base64').toString();};
|
|
30
|
+
const compat=JSON.parse(decode('compatibility.json')),supported=['onboardingPluginVersion','onboardingPluginVersionRequests','onboardingPluginVersionArtifacts','onboardingVersionActivation'].every(k=>compat[k]===1);
|
|
31
|
+
const historical=r=>({...r,activationVerified:false,cached:true,historical:true});
|
|
32
|
+
if(local)return {operationId:p.id,runtimeId:ledger?.runtimeId??runtimeId??null,supported,cached:true,historical:true,activationVerified:false,records:(ledger?.records??[]).map(historical)};
|
|
33
|
+
if(!supported)fail('UNSUPPORTED');if(!uuid(runtimeId))fail('RUNTIME_RECORD_REQUIRED');
|
|
34
|
+
const versions=parseVersionRequest(await c.readRecord(versionRecordKey(p.id)),p.id);
|
|
35
|
+
if(!versions||versions.binding!==binding||versions.runtimeId!==runtimeId||!versions.plans.some(v=>v.kind==='apply'&&v.id===args.id))fail('TRANSACTION_UNKNOWN');
|
|
36
|
+
if(action==='activation_verify'&&versionPending(versions))fail('RECOVERY_REQUIRED');
|
|
37
|
+
const program=runtimeProgram(decode('onboarding-remote-control.js'),decode('onboarding-runtime-extension.js')),command=runtimeCommand(a.baseline.node.path,program,'runtimeVersionCLI');
|
|
38
|
+
const q={action:'runtime_version',root:p.root,operationId:p.id,installationId:p.installationId,proof:p.proof,planHash:p.planHash,versionAction:action,args:{id:args.id}};
|
|
39
|
+
let result;try{result=JSON.parse(await ssh.execute(b,command,JSON.stringify(q),{timeoutMs:120000}));}catch{fail('OBSERVATION_UNAVAILABLE');}
|
|
40
|
+
if(result?.ok!==true)throw Error(typeof result?.error==='string'&&/^ONBOARDING_CLOUD_[A-Z_]{1,100}$/.test(result.error)?result.error:'ONBOARDING_CLOUD_VERSION_ACTIVATION_RESPONSE_REVIEW');
|
|
41
|
+
const v=check(result.value,p,runtimeId);
|
|
42
|
+
if(v.requestedTransactionId!==args.id||v.activationVerified!==(action==='activation_verify'))fail('RESPONSE_REVIEW');
|
|
43
|
+
const records=[...(ledger?.records??[])],last=records.at(-1),same=last&&['requestedTransactionId','versionTransactionId','restartId','pluginVersion','transactionState'].every(k=>last[k]===v[k]);
|
|
44
|
+
if(same)records[records.length-1]=v;else{if(records.length>=128)fail('HISTORY_FULL');records.push(v);}
|
|
45
|
+
const next={schema:1,operationId:p.id,runtimeId,binding,records};parse({kind:'grant',payload:next});
|
|
46
|
+
await c.modifyRecord(key,old=>{if(JSON.stringify(parse(old))!==JSON.stringify(ledger))fail('LOCAL_CONFLICT');return {kind:'grant',payload:next};});
|
|
47
|
+
return {...v,historical:action==='activation_status'};
|
|
48
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Original-archive candidate receiver. No URL, tar extraction, dependency
|
|
2
|
+
// installation or code execution. Called only under the runtime owner lock.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {fs,bytes,snapshot,syncWrite,hash,ancestors} from './onboarding-install-fs.js';
|
|
5
|
+
import {syncDirectory,statMaybe} from './onboarding-maintenance-fs.js';
|
|
6
|
+
const fail=c=>{throw Error('ONBOARDING_CLOUD_VERSION_CANDIDATE_'+c);};
|
|
7
|
+
const exact=(x,keys)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===keys.slice().sort().join();
|
|
8
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
|
|
9
|
+
const hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
|
|
10
|
+
const rel=x=>typeof x==='string'&&x.length<=240&&/^[A-Za-z0-9_./-]+$/.test(x)&&x.split('/').every(p=>p&&p!=='.'&&p!=='..'&&p!=='.control'&&p!=='node_modules');
|
|
11
|
+
const ident=s=>({dev:s.dev,ino:s.ino,uid:s.uid,mode:s.mode&0o777});
|
|
12
|
+
const digest=x=>hash(JSON.stringify(x));
|
|
13
|
+
function validate(files,manifestHash){
|
|
14
|
+
if(!Array.isArray(files)||!files.length||files.length>512||!hex(manifestHash))fail('PACKAGE');
|
|
15
|
+
const seen=new Set(),dirs=new Set(),data=new Map();let total=0;
|
|
16
|
+
for(const f of files){
|
|
17
|
+
if(!exact(f,['path','bytes','sha256','mode','data'])||!f.path.startsWith('plugin/')||!rel(f.path.slice(7))||seen.has(f.path.toLowerCase())||f.mode!==0o600||!Number.isSafeInteger(f.bytes)||f.bytes<0||f.bytes>4194304||!hex(f.sha256)||typeof f.data!=='string'||f.data.length>5592408)fail('PACKAGE');
|
|
18
|
+
const b=Buffer.from(f.data,'base64');if(b.toString('base64')!==f.data||b.length!==f.bytes||hash(b)!==f.sha256)fail('PACKAGE');
|
|
19
|
+
total+=b.length;if(total>8388608)fail('LIMIT');seen.add(f.path.toLowerCase());data.set(f.path,b);
|
|
20
|
+
let p=path.posix.dirname(f.path);while(p!=='.'){dirs.add(p);p=path.posix.dirname(p);}
|
|
21
|
+
}
|
|
22
|
+
if(dirs.size>2048||[...dirs].some(p=>seen.has(p.toLowerCase()))||new Set([...dirs].map(p=>p.toLowerCase())).size!==dirs.size)fail('PACKAGE');
|
|
23
|
+
const manifest=files.map(({data,...f})=>f).sort((a,b)=>a.path<b.path?-1:1);
|
|
24
|
+
if(digest(manifest)!==manifestHash)fail('HASH');return {manifest,data,dirs:[...dirs].sort((a,b)=>a.split('/').length-b.split('/').length||a.localeCompare(b)),total};
|
|
25
|
+
}
|
|
26
|
+
function compatibility(data,original){
|
|
27
|
+
const json=p=>{try{return JSON.parse(data.get('plugin/'+p));}catch{fail('COMPATIBILITY');}};
|
|
28
|
+
const pkg=json('package.json'),compat=json('compatibility.json'),base=original.package,baseCompat=original.compatibility;
|
|
29
|
+
if(pkg.name!=='@mogragsigma/dsh-dual-host-plugin'||typeof pkg.version!=='string'||pkg.version.length>99||!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(pkg.version)||compat.version!==pkg.version||compat.hostBaseline!==baseCompat.hostBaseline||compat.onboardingPluginVersion!==1)fail('COMPATIBILITY');
|
|
30
|
+
if((compat.onboardingPluginVersionLifecycle===1||baseCompat.onboardingPluginVersionLifecycle===1)&&(compat.onboardingPluginVersionLifecycle!==1||baseCompat.onboardingPluginVersionLifecycle!==1||compat.onboardingNativePluginIdentity!==1||baseCompat.onboardingNativePluginIdentity!==1))fail('LIFECYCLE_UNSUPPORTED');
|
|
31
|
+
if((compat.onboardingVersionRepair===1||baseCompat.onboardingVersionRepair===1)&&(compat.onboardingVersionRepair!==1||baseCompat.onboardingVersionRepair!==1))fail('REPAIR_LIFECYCLE_UNSUPPORTED');
|
|
32
|
+
// Activation is an additive read-only observation. An older original archive
|
|
33
|
+
// can install the image but never gains the new authority; the original
|
|
34
|
+
// contract still controls verify/status. An archive that requires it cannot
|
|
35
|
+
// accept its removal or a different contract revision.
|
|
36
|
+
const activation=compat.onboardingVersionRepairActivation,required=baseCompat.onboardingVersionRepairActivation;
|
|
37
|
+
if(activation!==undefined&&activation!==1||required!==undefined&&required!==1||required===1&&activation!==1)fail('REPAIR_ACTIVATION_UNSUPPORTED');
|
|
38
|
+
const versionActivation=compat.onboardingVersionActivation,requiredVersionActivation=baseCompat.onboardingVersionActivation;
|
|
39
|
+
if(versionActivation!==undefined&&versionActivation!==1||requiredVersionActivation!==undefined&&requiredVersionActivation!==1||requiredVersionActivation===1&&versionActivation!==1)fail('VERSION_ACTIVATION_UNSUPPORTED');
|
|
40
|
+
// Installing a newer image never grants an older original controller deletion
|
|
41
|
+
// authority. Keep a required reclamation contract; reject unknown revisions.
|
|
42
|
+
const reclamation=compat.onboardingRuntimeReclamation,originalReclamation=baseCompat.onboardingRuntimeReclamation;
|
|
43
|
+
if(reclamation!==undefined&&reclamation!==1||originalReclamation!==undefined&&originalReclamation!==1||originalReclamation===1&&reclamation!==1)fail('RECLAMATION_UNSUPPORTED');
|
|
44
|
+
const worker=compat.onboardingRuntimeReclamationWorker,requiredWorker=baseCompat.onboardingRuntimeReclamationWorker;
|
|
45
|
+
if(worker!==undefined&&worker!==1||requiredWorker!==undefined&&requiredWorker!==1||requiredWorker===1&&worker!==1||worker===1&&(compat.onboardingRuntimeReclamationRequests!==1||reclamation!==1))fail('RECLAMATION_WORKER_UNSUPPORTED');
|
|
46
|
+
const reclaimRequests=compat.onboardingRuntimeReclamationRequests,requiredRequests=baseCompat.onboardingRuntimeReclamationRequests;
|
|
47
|
+
if(reclaimRequests!==undefined&&reclaimRequests!==1||requiredRequests!==undefined&&requiredRequests!==1||requiredRequests===1&&reclaimRequests!==1||reclaimRequests===1&&reclamation!==1)fail('RECLAMATION_REQUESTS_UNSUPPORTED');
|
|
48
|
+
// This release route cannot change native/dependency bindings or install scripts.
|
|
49
|
+
const strip=p=>{const {version,description,...rest}=p;return rest;};
|
|
50
|
+
if(digest(strip(pkg))!==digest(strip(base)))fail('DEPENDENCIES');
|
|
51
|
+
for(const name of ['runtime-package.json','runtime-lock.json','runtime-im-package.json','runtime-im-lock.json'])if(!data.has('plugin/'+name)||hash(data.get('plugin/'+name))!==original.files.get('plugin/'+name)?.sha256)fail('DEPENDENCIES');
|
|
52
|
+
const lock=json('package-lock.json'),before=structuredClone(original.lock);if(lock.version!==pkg.version||lock.packages?.['']?.version!==pkg.version)fail('DEPENDENCIES');
|
|
53
|
+
before.version=pkg.version;before.packages[''].version=pkg.version;if(digest(lock)!==digest(before))fail('DEPENDENCIES');
|
|
54
|
+
return pkg.version;
|
|
55
|
+
}
|
|
56
|
+
export function validateVersionCandidatePackage(files,manifestHash,original){const p=validate(files,manifestHash);return {...p,version:compatibility(p.data,original)};}
|
|
57
|
+
export function createVersionCandidates({q,j,original,regular,signed,verified,atomicJSON,guard,hook}){
|
|
58
|
+
const parent=path.join(q.root,'.control/runtime/plugin-candidates');
|
|
59
|
+
const binding=digest({root:q.root,operationId:q.operationId,runtimeId:j.id,inventoryHash:j.inventoryHash});
|
|
60
|
+
async function directory(p){await ancestors(p);const s=await fs.lstat(p);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid()||(s.mode&0o777)!==0o700)fail('DIRECTORY_REVIEW');return ident(s);}
|
|
61
|
+
function candidateId(id){if(!uuid(id))fail('ARGUMENTS');return path.join(parent,id);}
|
|
62
|
+
async function read(id){
|
|
63
|
+
const dir=candidateId(id);await directory(parent);const identity=await directory(dir),f=await regular(path.join(dir,'receipt.json'),262144);
|
|
64
|
+
if(!f||f.identity.uid!==process.getuid()||f.identity.mode!==0o600)fail('RECEIPT_REVIEW');
|
|
65
|
+
const r=verified(JSON.parse(f.data),q.proof);
|
|
66
|
+
if(r.schema!==1||r.binding!==binding||r.id!==id||digest(r.directory)!==digest(identity)||!['receiving','ready','needs_review'].includes(r.state)||!hex(r.manifestHash)||!Array.isArray(r.manifest)||r.manifest.length>512||!r.manifest.length)fail('RECEIPT_REVIEW');
|
|
67
|
+
if((await fs.readdir(dir)).some(n=>!['receipt.json','plugin'].includes(n)))fail('RECEIPT_REVIEW');return r;
|
|
68
|
+
}
|
|
69
|
+
async function inspect(r){
|
|
70
|
+
const dir=candidateId(r.id),tree=path.join(dir,'plugin'),expected=new Map(r.manifest.map(f=>[f.path,f])),rows=[];
|
|
71
|
+
async function walk(at,rel){if(rows.length>=4096)fail('LIMIT');const s=await fs.lstat(at);if(s.isDirectory()&&!s.isSymbolicLink()){await directory(at);rows.push({path:rel,kind:'directory',...ident(s)});for(const n of (await fs.readdir(at)).sort())await walk(path.join(at,n),rel+'/'+n);}
|
|
72
|
+
else{const f=expected.get(rel);if(!f||s.uid!==process.getuid())fail('DRIFT');const b=await snapshot(at,4194304);if(b.mode!==0o600||b.size!==f.bytes||b.sha256!==f.sha256)fail('DRIFT');rows.push({path:rel,kind:'file',...ident(s),bytes:b.size,sha256:b.sha256});expected.delete(rel);}}
|
|
73
|
+
await walk(tree,'plugin');rows.sort((a,b)=>a.path<b.path?-1:1);if(expected.size||digest(rows)!==r.imageHash)fail('DRIFT');return rows;
|
|
74
|
+
}
|
|
75
|
+
function view(r){return {contract:1,id:r.id,state:r.state,version:r.version,manifestHash:r.manifestHash,files:r.manifest.length,bytes:r.bytes,scope:'candidate_files_only',runtimeChanged:false,hostStarted:false,activationVerified:false,automaticRetry:false,recoveryRequired:r.state!=='ready'};}
|
|
76
|
+
async function status(id){const r=await read(id);if(r.state==='ready')await inspect(r);return {...view(r),historical:true};}
|
|
77
|
+
async function receive(a){
|
|
78
|
+
if(!exact(a,['id','manifestHash','files','confirm'])||a.confirm!==true)fail('CONFIRMATION_REQUIRED');const dir=candidateId(a.id),p=validateVersionCandidatePackage(a.files,a.manifestHash,original),version=p.version;await guard();
|
|
79
|
+
if(await statMaybe(dir)){const old=await read(a.id);if(old.manifestHash!==a.manifestHash)fail('ID_REUSED');return {...await status(a.id),notResent:true};}
|
|
80
|
+
if(!await statMaybe(parent)){await fs.mkdir(parent,{mode:0o700});await syncDirectory(path.dirname(parent));}await directory(parent);
|
|
81
|
+
if((await fs.readdir(parent)).length>=16)fail('HISTORY_FULL');
|
|
82
|
+
await fs.mkdir(dir,{mode:0o700});await syncDirectory(parent);
|
|
83
|
+
const r={schema:1,binding,id:a.id,directory:await directory(dir),manifestHash:a.manifestHash,manifest:p.manifest,version,bytes:p.total,state:'receiving',imageHash:null};
|
|
84
|
+
const save=()=>atomicJSON(path.join(dir,'receipt.json'),signed(r,q.proof));await save();
|
|
85
|
+
try{
|
|
86
|
+
const rows=[];
|
|
87
|
+
for(const d of p.dirs){const at=path.join(dir,d);await fs.mkdir(at,{mode:0o700});rows.push({path:d,kind:'directory',...await directory(at)});}
|
|
88
|
+
await hook?.('candidate_created');for(const f of p.manifest){await guard();const at=path.join(dir,f.path);await syncWrite(at,p.data.get(f.path));rows.push({path:f.path,kind:'file',...ident(await fs.lstat(at)),bytes:f.bytes,sha256:f.sha256});}
|
|
89
|
+
for(const d of p.dirs.slice().reverse())await syncDirectory(path.join(dir,d));await syncDirectory(dir);
|
|
90
|
+
// A receipt seals exact identities too; equal bytes at a replaced path are not accepted.
|
|
91
|
+
rows.sort((a,b)=>a.path<b.path?-1:1);r.imageHash=digest(rows);await inspect(r);await guard();r.state='ready';await save();return view(r);
|
|
92
|
+
}catch(e){r.state='needs_review';await save();throw e;}
|
|
93
|
+
}
|
|
94
|
+
async function release(id){const r=await read(id);if(r.state!=='ready')fail('RECOVERY_REQUIRED');await inspect(r);return {candidateId:id,version:r.version,manifest:r.manifest.map(f=>({path:f.path.slice(7),sha256:f.sha256}))};}
|
|
95
|
+
return {receive,status,release};
|
|
96
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Nested repairs belong to a signed version epoch, not to a new release.
|
|
2
|
+
// Only the latest version journal is mutable. Its child pins the completed
|
|
3
|
+
// repair history through parentHash; rollback retains both damaged backups
|
|
4
|
+
// and the repaired discarded image. Nothing here starts a Host.
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
import {fs,hash as sha} from './onboarding-install-fs.js';
|
|
8
|
+
import {statMaybe,syncDirectory} from './onboarding-maintenance-fs.js';
|
|
9
|
+
import {createPluginRepair} from './onboarding-plugin-repair.js';
|
|
10
|
+
const hash=x=>sha(JSON.stringify(x)),fail=c=>{throw Error('ONBOARDING_PLUGIN_VERSION_REPAIR_'+c);};
|
|
11
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
|
|
12
|
+
const hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
|
|
13
|
+
const exact=(x,k)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===k.slice().sort().join();
|
|
14
|
+
const pending=r=>['preparing','applying','needs_review'].includes(r.state);
|
|
15
|
+
export function createVersionRepair({root,operationId,runtimeId,proof,original,readAll,save,guard,privateDir,verifyImage,readImage,now,hook,verifyRepairCandidate}){
|
|
16
|
+
const folder=j=>path.join(root,'.control/runtime/plugin-versions',j.id,'repairs');
|
|
17
|
+
const control=(j,r)=>path.join(folder(j),r.slot);
|
|
18
|
+
const phase=j=>j.state==='committed'?'after':j.state==='rolled_back'?'before':null;
|
|
19
|
+
const base=(j,p)=>p==='after'?{...j.after,image:j.stage}:j.before;
|
|
20
|
+
function merge(j,p,{until,allowPending=false}={}){
|
|
21
|
+
let current=structuredClone(base(j,p).image);
|
|
22
|
+
for(const r of j.repairs??[]){
|
|
23
|
+
if(r.phase!==p)continue;
|
|
24
|
+
if(r.baseHash!==hash(current))fail('OWNERSHIP_REVIEW');
|
|
25
|
+
if(r===until)break;
|
|
26
|
+
if(pending(r)&&!allowPending)fail('RECOVERY_REQUIRED');
|
|
27
|
+
const map=new Map(current.map(x=>[x.path,x]));
|
|
28
|
+
for(const d of r.delta){const before=map.get(d.before?.path),a=d.after;
|
|
29
|
+
if(!exact(d,['before','after'])||!before||before.kind!=='file'||hash(before)!==hash(d.before)||!exact(a,['path','kind','dev','ino','uid','mode','bytes','sha256'])||a.path!==before.path||a.kind!=='file'||a.sha256!==before.sha256||a.bytes!==before.bytes||a.dev!==before.dev||a.uid!==before.uid||a.mode!==before.mode||!Number.isSafeInteger(a.ino)||a.ino<0)fail('OWNERSHIP_REVIEW');
|
|
30
|
+
map.set(a.path,a);
|
|
31
|
+
}
|
|
32
|
+
current=[...map.values()];
|
|
33
|
+
}
|
|
34
|
+
return current;
|
|
35
|
+
}
|
|
36
|
+
async function validate(j){
|
|
37
|
+
if(j.repairs===undefined){if(await statMaybe(folder(j)))fail('JOURNAL_REVIEW');return;}
|
|
38
|
+
if(!Array.isArray(j.repairs)||j.repairs.length>128||new Set(j.repairs.map(r=>r.slot)).size!==j.repairs.length||new Set(j.repairs.map(r=>r.id)).size!==j.repairs.length)fail('JOURNAL_REVIEW');
|
|
39
|
+
for(const [n,r] of j.repairs.entries()){
|
|
40
|
+
if(!exact(r,['slot','id','phase','baseHash','state','fingerprint','delta','updatedAt','directoryIdentity'])||!uuid(r.slot)||!uuid(r.id)||!['before','after'].includes(r.phase)||!hex(r.baseHash)||!['preparing','planned','applying','committed','rolled_back','needs_review'].includes(r.state)||r.fingerprint!==null&&!hex(r.fingerprint)||!Number.isSafeInteger(r.updatedAt)||!Array.isArray(r.delta)||r.delta.length>512||r.state!=='committed'&&r.delta.length||new Set(r.delta.map(x=>x.after?.path)).size!==r.delta.length||pending(r)&&n!==j.repairs.length-1)fail('JOURNAL_REVIEW');
|
|
41
|
+
if(r.phase==='before'&&j.state!=='rolled_back')fail('JOURNAL_REVIEW');
|
|
42
|
+
if(r.directoryIdentity){if(hash(await privateDir(control(j,r)))!==hash(r.directoryIdentity)||(await fs.readdir(control(j,r))).some(n=>!['plugin-repair-plan.json','plugin-repairs'].includes(n)))fail('JOURNAL_REVIEW');}
|
|
43
|
+
else if(!pending(r))fail('JOURNAL_REVIEW');
|
|
44
|
+
}
|
|
45
|
+
if(await statMaybe(folder(j))){await privateDir(folder(j));if((await fs.readdir(folder(j))).some(n=>!j.repairs.some(r=>r.slot===n)))fail('JOURNAL_REVIEW');}
|
|
46
|
+
else if(j.repairs.some(r=>r.directoryIdentity))fail('JOURNAL_REVIEW');
|
|
47
|
+
merge(j,'before',{allowPending:true});if(j.stage)merge(j,'after',{allowPending:true});
|
|
48
|
+
}
|
|
49
|
+
function settled(j){if((j.repairs??[]).some(pending))fail('RECOVERY_REQUIRED');}
|
|
50
|
+
function current(j){settled(j);const p=phase(j);if(!p)fail('VERSION_RECOVERY_REQUIRED');return {...base(j,p),image:merge(j,p)};}
|
|
51
|
+
function source(j,rows){
|
|
52
|
+
const b=base(j,phase(j));
|
|
53
|
+
if(b.version===original.version&&hash(b.manifest)===hash(original.manifest))return path.join(root,'plugin');
|
|
54
|
+
const owner=rows.findLast(x=>x.after.version===b.version&&hash(x.after.manifest)===hash(b.manifest));
|
|
55
|
+
if(!owner)fail('SOURCE_UNAVAILABLE');return path.join(root,'.control/runtime/plugin-candidates',owner.candidateId,'plugin');
|
|
56
|
+
}
|
|
57
|
+
async function sourceVerified(j,rows){
|
|
58
|
+
const p=source(j,rows),b=base(j,phase(j));
|
|
59
|
+
if(p!==path.join(root,'plugin')&&verifyRepairCandidate){const checked=await verifyRepairCandidate(path.basename(path.dirname(p)));if(checked.version!==b.version||hash(checked.manifest.slice().sort((a,b)=>a.path.localeCompare(b.path,'en')))!==hash(b.manifest))fail('SOURCE_DRIFT');}
|
|
60
|
+
const observed=await readImage(p);
|
|
61
|
+
// The immutable signed release pins bytes, types, modes and names. Source
|
|
62
|
+
// inodes need not be installed inodes, and are never adopted as target ownership.
|
|
63
|
+
const canonical=a=>a?.map(({dev,ino,...x})=>x);
|
|
64
|
+
if(hash(canonical(observed))!==hash(canonical(b.image)))fail('SOURCE_DRIFT');return p;
|
|
65
|
+
}
|
|
66
|
+
async function repairable(expected){
|
|
67
|
+
const observed=await readImage(path.join(root,'runtime/plugin'));if(!observed)fail('DIRECTORY_REVIEW');
|
|
68
|
+
const map=new Map(expected.map(x=>[x.path,x])),seen=new Set();
|
|
69
|
+
for(const item of observed){const old=map.get(item.path);if(!old)fail('UNKNOWN_FILE');seen.add(item.path);
|
|
70
|
+
if(item.kind!==old.kind)fail('TYPE_REVIEW');
|
|
71
|
+
if(item.kind==='directory'){if(hash(item)!==hash(old))fail('DIRECTORY_REVIEW');}
|
|
72
|
+
else if(item.dev!==old.dev||item.uid!==old.uid||item.mode!==old.mode||item.sha256===old.sha256&&item.ino!==old.ino)fail('OWNERSHIP_REVIEW');
|
|
73
|
+
}
|
|
74
|
+
if(expected.some(x=>x.kind==='directory'&&!seen.has(x.path)))fail('DIRECTORY_REVIEW');
|
|
75
|
+
}
|
|
76
|
+
function engine(j,r,rows){
|
|
77
|
+
const image=merge(j,r.phase,{until:r,allowPending:true});
|
|
78
|
+
return createPluginRepair({root,operationId,runtimeId,proof,manifest:base(j,r.phase).manifest,
|
|
79
|
+
inventory:image.filter(x=>x.path).map(x=>({path:x.path,kind:x.kind,identity:{dev:x.dev,ino:x.ino,mode:x.mode},sha256:x.sha256??null})),
|
|
80
|
+
versionContext:{source:source(j,rows),control:control(j,r),targetIdentity:((x)=>({dev:x.dev,ino:x.ino,uid:x.uid,mode:x.mode}))(image.find(x=>x.path===''))},
|
|
81
|
+
exclusive:f=>f(),verifyOwnedStopped:async()=>{await guard();return {operationId,runtimeId,stopped:true,ownershipVerified:true};},now,hook});
|
|
82
|
+
}
|
|
83
|
+
function view(j,r){return {contract:1,id:r?.id??null,state:r?.state??'not_started',recoveryRequired:!!r&&pending(r),ownershipRebased:r?.state==='committed',activationVerified:false,activationSupported:false,activeVersionRepair:!!r&&r.phase===phase(j),versionUpgrade:false,version:base(j,r?.phase??phase(j)).version,versionTransactionId:j.id,files:r?.delta.map(x=>x.after.path)??[],hostStarted:false,backupsRetained:true};}
|
|
84
|
+
async function finish(j,r,e,result){
|
|
85
|
+
await guard();let delta=[];
|
|
86
|
+
if(result.state==='committed'){
|
|
87
|
+
const expected=merge(j,r.phase,{until:r,allowPending:true}),map=new Map(expected.map(x=>[x.path,x]));
|
|
88
|
+
delta=(await e.ownership({id:r.id})).map(x=>{const before=map.get(x.path);return {before,after:{...before,dev:x.identity.dev,ino:x.identity.ino,mode:x.identity.mode,bytes:x.bytes,sha256:x.sha256}};});
|
|
89
|
+
}
|
|
90
|
+
r.state=result.state;r.delta=delta;r.updatedAt=now();await validate(j);
|
|
91
|
+
if(r.state==='committed')await verifyImage(path.join(root,'runtime/plugin'),merge(j,r.phase));
|
|
92
|
+
await save(j);return view(j,r);
|
|
93
|
+
}
|
|
94
|
+
async function action(name,args={}){
|
|
95
|
+
const rows=await readAll(),j=rows.at(-1);if(!j||!phase(j))fail('VERSION_RECOVERY_REQUIRED');
|
|
96
|
+
if(name==='status')return view(j,(j.repairs??[]).at(-1));
|
|
97
|
+
if(name==='verify')fail('ACTIVATION_UNSUPPORTED');
|
|
98
|
+
await guard();
|
|
99
|
+
if(name==='preview'){
|
|
100
|
+
if(!exact(args,[]))fail('ARGUMENTS');settled(j);await sourceVerified(j,rows);
|
|
101
|
+
if((j.repairs??[]).length>=128)fail('HISTORY_FULL');
|
|
102
|
+
const image=current(j).image;await repairable(image);
|
|
103
|
+
const slot=randomUUID(),r={slot,id:slot,phase:phase(j),baseHash:hash(image),state:'preparing',fingerprint:null,delta:[],updatedAt:now(),directoryIdentity:null};
|
|
104
|
+
(j.repairs??=[]).push(r);await save(j);
|
|
105
|
+
try{
|
|
106
|
+
if(!await statMaybe(folder(j))){await fs.mkdir(folder(j),{mode:0o700});await syncDirectory(path.dirname(folder(j)));}
|
|
107
|
+
await privateDir(folder(j));await fs.mkdir(control(j,r),{mode:0o700});await syncDirectory(folder(j));r.directoryIdentity=await privateDir(control(j,r));await save(j);
|
|
108
|
+
const p=await engine(j,r,rows).preview();r.id=p.id;r.fingerprint=p.fingerprint;r.state='planned';r.updatedAt=now();await save(j);
|
|
109
|
+
return {...p,version:base(j,r.phase).version,versionTransactionId:j.id,historyAware:true,activationSupported:false};
|
|
110
|
+
}catch(e){r.state='needs_review';await save(j);throw e;}
|
|
111
|
+
}
|
|
112
|
+
if(!['apply','recover'].includes(name))fail('ARGUMENTS');
|
|
113
|
+
const r=(j.repairs??[]).find(x=>x.id===args.id);if(!r)fail('NOT_FOUND');
|
|
114
|
+
if(!exact(args,name==='apply'?['id','fingerprint','confirm']:['id','confirm'])||args.confirm!==true||name==='apply'&&args.fingerprint!==r.fingerprint)fail('CONFIRMATION_REQUIRED');
|
|
115
|
+
if(['committed','rolled_back'].includes(r.state))return {...view(j,r),notResent:true};
|
|
116
|
+
if(r!==j.repairs.at(-1)||r.phase!==phase(j))fail('NOT_LATEST');
|
|
117
|
+
if(!r.fingerprint||!r.directoryIdentity)fail('JOURNAL_REVIEW');
|
|
118
|
+
const e=engine(j,r,rows);
|
|
119
|
+
if(name==='apply'){
|
|
120
|
+
if(r.state!=='planned')return {...view(j,r),notResent:true};
|
|
121
|
+
await sourceVerified(j,rows);await e.validate(args);r.state='applying';r.updatedAt=now();await save(j);await hook?.('version_repair_intent');
|
|
122
|
+
}else if(r.state==='planned')fail('NOT_STARTED');
|
|
123
|
+
try{const result=await e[name](args);await hook?.('version_repair_result');return await finish(j,r,e,result);}
|
|
124
|
+
catch(error){r.state='needs_review';r.delta=[];r.updatedAt=now();await save(j);throw error;}
|
|
125
|
+
}
|
|
126
|
+
async function binding(){const rows=await readAll(),j=rows.at(-1);if(!j||!phase(j))fail('VERSION_RECOVERY_REQUIRED');const release=current(j),r=j.repairs?.at(-1);return {release,versionTransactionId:j.id,repair:r?.phase===phase(j)?{id:r.id,fingerprint:r.fingerprint,updatedAt:r.updatedAt,state:r.state}:null};}
|
|
127
|
+
return {validate,settled,current,after:j=>merge(j,'after'),action,binding};
|
|
128
|
+
}
|