@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.
Files changed (271) hide show
  1. package/LICENSE +58 -0
  2. package/LICENSE.en.md +94 -0
  3. package/README.md +88 -2
  4. package/bundle/ASSET_NOTICE.md +19 -0
  5. package/bundle/LICENSE +58 -0
  6. package/bundle/LICENSE.en.md +94 -0
  7. package/bundle/README.md +75 -0
  8. package/bundle/THIRD_PARTY_NOTICES.md +94 -0
  9. package/bundle/a2a-dispatches.js +38 -0
  10. package/bundle/a2a-endpoint.js +112 -0
  11. package/bundle/a2a-tools.js +11 -0
  12. package/bundle/a2a-worker.js +63 -0
  13. package/bundle/approval-auth.js +5 -0
  14. package/bundle/approval-chat.js +150 -0
  15. package/bundle/approval-feishu.js +52 -0
  16. package/bundle/approval-guidance.js +68 -0
  17. package/bundle/approval-http.js +8 -0
  18. package/bundle/approval-ledger.js +142 -0
  19. package/bundle/approval-local-relay.js +86 -0
  20. package/bundle/approval-receipts.js +62 -0
  21. package/bundle/approval-reference.js +33 -0
  22. package/bundle/approval-semantic-model.js +26 -0
  23. package/bundle/approval-semantics.js +51 -0
  24. package/bundle/approval-ui/app.js +1 -0
  25. package/bundle/approval-ui/index.html +1 -0
  26. package/bundle/approval-ui/style.css +1 -0
  27. package/bundle/approval-workbench.js +45 -0
  28. package/bundle/artifact-media.js +34 -0
  29. package/bundle/bounded-text.js +44 -0
  30. package/bundle/compatibility.json +980 -0
  31. package/bundle/cordis.patch.yml +5 -0
  32. package/bundle/delivery-approval.js +133 -0
  33. package/bundle/delivery-artifacts.js +52 -0
  34. package/bundle/delivery-commit.js +125 -0
  35. package/bundle/delivery-contract.js +42 -0
  36. package/bundle/delivery-git-read.js +217 -0
  37. package/bundle/delivery-index.js +23 -0
  38. package/bundle/delivery-journal.js +207 -0
  39. package/bundle/delivery-object-plan.js +138 -0
  40. package/bundle/delivery-preview.js +153 -0
  41. package/bundle/delivery-process-receipts.js +90 -0
  42. package/bundle/delivery-process.js +46 -0
  43. package/bundle/delivery-process.py +228 -0
  44. package/bundle/delivery-push-approval.js +89 -0
  45. package/bundle/delivery-push-plan.js +98 -0
  46. package/bundle/delivery-push-recovery.js +32 -0
  47. package/bundle/delivery-push.js +83 -0
  48. package/bundle/delivery-recovery.js +143 -0
  49. package/bundle/delivery-runtime.js +182 -0
  50. package/bundle/delivery-ssh.js +64 -0
  51. package/bundle/delivery-state.js +106 -0
  52. package/bundle/development-attention.js +35 -0
  53. package/bundle/development-bridge.js +136 -0
  54. package/bundle/development-command-review.js +110 -0
  55. package/bundle/development-container.js +110 -0
  56. package/bundle/development-contract.js +17 -0
  57. package/bundle/development-files.js +101 -0
  58. package/bundle/development-gate.js +236 -0
  59. package/bundle/development-model-budget.js +48 -0
  60. package/bundle/development-peer.js +155 -0
  61. package/bundle/development-plan.js +43 -0
  62. package/bundle/development-reconciliation.js +62 -0
  63. package/bundle/development-review.js +81 -0
  64. package/bundle/development-rules/AGENTS.md +51 -0
  65. package/bundle/development-runtime.js +68 -0
  66. package/bundle/development-source.js +48 -0
  67. package/bundle/development-test-runner.js +13 -0
  68. package/bundle/development-tools.js +45 -0
  69. package/bundle/development-worker-review.js +110 -0
  70. package/bundle/development-worker.js +68 -0
  71. package/bundle/development-workspace.js +54 -0
  72. package/bundle/diagnostics.js +78 -0
  73. package/bundle/distribution-lock.json +773 -0
  74. package/bundle/drained-process.js +26 -0
  75. package/bundle/durable-inbox.js +294 -0
  76. package/bundle/feishu-policy.js +24 -0
  77. package/bundle/gateway-maintenance.js +55 -0
  78. package/bundle/global-rules/AGENTS.md +83 -0
  79. package/bundle/im-delivery.js +60 -0
  80. package/bundle/index.js +445 -0
  81. package/bundle/intervention-actions.js +135 -0
  82. package/bundle/intervention-job-control.js +28 -0
  83. package/bundle/intervention-state.js +43 -0
  84. package/bundle/job-version.js +15 -0
  85. package/bundle/legacy-feishu-adapter.js +89 -0
  86. package/bundle/link-contract.js +80 -0
  87. package/bundle/maintenance-process-identity.js +93 -0
  88. package/bundle/model-selection.js +71 -0
  89. package/bundle/native-context.js +14 -0
  90. package/bundle/native-entry-admission.js +2 -0
  91. package/bundle/native-entry.js +58 -0
  92. package/bundle/native-file-reference.js +32 -0
  93. package/bundle/native-owner-origin.js +12 -0
  94. package/bundle/native-rules/AGENTS.md +199 -0
  95. package/bundle/native-tools.js +108 -0
  96. package/bundle/notification-artifacts.js +70 -0
  97. package/bundle/notification-contract.js +29 -0
  98. package/bundle/notification-defaults.js +81 -0
  99. package/bundle/notification-discovery.js +65 -0
  100. package/bundle/notification-endpoint.js +54 -0
  101. package/bundle/notification-feishu.js +51 -0
  102. package/bundle/notification-media-endpoint.js +94 -0
  103. package/bundle/notification-review.js +27 -0
  104. package/bundle/notification-targets.js +54 -0
  105. package/bundle/onboarding-activity.js +66 -0
  106. package/bundle/onboarding-agent-hold.js +94 -0
  107. package/bundle/onboarding-boundary.js +20 -0
  108. package/bundle/onboarding-cloud-contract.js +29 -0
  109. package/bundle/onboarding-cloud-file-review.js +58 -0
  110. package/bundle/onboarding-cloud-files.js +100 -0
  111. package/bundle/onboarding-cloud-im.js +34 -0
  112. package/bundle/onboarding-cloud-model-probe.js +53 -0
  113. package/bundle/onboarding-cloud-models.js +68 -0
  114. package/bundle/onboarding-cloud-operation.js +276 -0
  115. package/bundle/onboarding-cloud-package.js +38 -0
  116. package/bundle/onboarding-cloud-repositories.js +89 -0
  117. package/bundle/onboarding-cloud-retirement.js +59 -0
  118. package/bundle/onboarding-cloud-task-runtime.js +90 -0
  119. package/bundle/onboarding-cloud-web.js +85 -0
  120. package/bundle/onboarding-cloud.js +110 -0
  121. package/bundle/onboarding-coordinated-hold.js +94 -0
  122. package/bundle/onboarding-exclusive-rename.js +16 -0
  123. package/bundle/onboarding-existing-host.js +63 -0
  124. package/bundle/onboarding-existing-setup.js +123 -0
  125. package/bundle/onboarding-file-contract.js +31 -0
  126. package/bundle/onboarding-file-review-contract.js +38 -0
  127. package/bundle/onboarding-file-transfer.js +133 -0
  128. package/bundle/onboarding-handoff-remote.js +98 -0
  129. package/bundle/onboarding-handoff.js +112 -0
  130. package/bundle/onboarding-host-stop-observation.js +44 -0
  131. package/bundle/onboarding-host.js +254 -0
  132. package/bundle/onboarding-identity.js +9 -0
  133. package/bundle/onboarding-im-maintenance-native.js +30 -0
  134. package/bundle/onboarding-im-maintenance.js +70 -0
  135. package/bundle/onboarding-im.js +31 -0
  136. package/bundle/onboarding-inspection-guard.js +15 -0
  137. package/bundle/onboarding-install-fs.js +58 -0
  138. package/bundle/onboarding-installer.js +157 -0
  139. package/bundle/onboarding-local-pair-native.js +21 -0
  140. package/bundle/onboarding-local-pair.js +99 -0
  141. package/bundle/onboarding-maintenance-fs.js +69 -0
  142. package/bundle/onboarding-maintenance-plan.js +213 -0
  143. package/bundle/onboarding-maintenance-record.js +169 -0
  144. package/bundle/onboarding-maintenance.js +163 -0
  145. package/bundle/onboarding-model-probe.js +119 -0
  146. package/bundle/onboarding-models.js +107 -0
  147. package/bundle/onboarding-native-host.js +101 -0
  148. package/bundle/onboarding-native-probe.js +56 -0
  149. package/bundle/onboarding-native-runner.js +29 -0
  150. package/bundle/onboarding-node-bootstrap.py +678 -0
  151. package/bundle/onboarding-node.js +77 -0
  152. package/bundle/onboarding-notification-defaults.js +93 -0
  153. package/bundle/onboarding-package-source.js +33 -0
  154. package/bundle/onboarding-paths.js +58 -0
  155. package/bundle/onboarding-peer-binding.js +61 -0
  156. package/bundle/onboarding-peer-contract.js +12 -0
  157. package/bundle/onboarding-plugin-repair.js +116 -0
  158. package/bundle/onboarding-plugin-version.js +143 -0
  159. package/bundle/onboarding-remote-control.js +140 -0
  160. package/bundle/onboarding-remote-probe.js +40 -0
  161. package/bundle/onboarding-repositories.js +88 -0
  162. package/bundle/onboarding-repository.js +49 -0
  163. package/bundle/onboarding-runtime-activation.js +83 -0
  164. package/bundle/onboarding-runtime-artifacts-client.js +87 -0
  165. package/bundle/onboarding-runtime-artifacts.js +126 -0
  166. package/bundle/onboarding-runtime-extension.js +400 -0
  167. package/bundle/onboarding-runtime-inventory.js +88 -0
  168. package/bundle/onboarding-runtime-program.js +42 -0
  169. package/bundle/onboarding-runtime-reclaim-client.js +94 -0
  170. package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
  171. package/bundle/onboarding-runtime-reclaim.js +132 -0
  172. package/bundle/onboarding-runtime-repair-client.js +50 -0
  173. package/bundle/onboarding-runtime-repair.js +88 -0
  174. package/bundle/onboarding-runtime-stop.js +90 -0
  175. package/bundle/onboarding-runtime-uninstall-client.js +88 -0
  176. package/bundle/onboarding-runtime-uninstall.js +167 -0
  177. package/bundle/onboarding-runtime-version-client.js +138 -0
  178. package/bundle/onboarding-runtime-version.js +145 -0
  179. package/bundle/onboarding-schema.js +42 -0
  180. package/bundle/onboarding-self-disable.js +3 -0
  181. package/bundle/onboarding-self-lifecycle.js +95 -0
  182. package/bundle/onboarding-self-maintenance.js +52 -0
  183. package/bundle/onboarding-self-remove.js +3 -0
  184. package/bundle/onboarding-self-stop.js +85 -0
  185. package/bundle/onboarding-ssh-forward.js +48 -0
  186. package/bundle/onboarding-ssh.js +105 -0
  187. package/bundle/onboarding-state.js +95 -0
  188. package/bundle/onboarding-task-runtime-contract.js +38 -0
  189. package/bundle/onboarding-task-runtime-native.js +80 -0
  190. package/bundle/onboarding-task-runtime.js +66 -0
  191. package/bundle/onboarding-token-plan.js +52 -0
  192. package/bundle/onboarding-version-activation-client.js +48 -0
  193. package/bundle/onboarding-version-candidate.js +96 -0
  194. package/bundle/onboarding-version-repair.js +128 -0
  195. package/bundle/package-lock.json +773 -0
  196. package/bundle/package.json +99 -0
  197. package/bundle/peer-file-fs.js +62 -0
  198. package/bundle/peer-file-migration.js +59 -0
  199. package/bundle/peer-file-review.js +107 -0
  200. package/bundle/peer-files.js +157 -0
  201. package/bundle/peer-mailbox.js +75 -0
  202. package/bundle/protocol.js +17 -0
  203. package/bundle/recovery.js +40 -0
  204. package/bundle/repository-catalog.js +85 -0
  205. package/bundle/repository-gitee.js +76 -0
  206. package/bundle/repository-managed.js +46 -0
  207. package/bundle/repository-writer.js +43 -0
  208. package/bundle/rules/AGENTS.md +22 -0
  209. package/bundle/runtime-im-lock.json +11577 -0
  210. package/bundle/runtime-im-package.json +18 -0
  211. package/bundle/runtime-lock.json +10152 -0
  212. package/bundle/runtime-package.json +17 -0
  213. package/bundle/scheduler-migration.js +45 -0
  214. package/bundle/search-contract.js +19 -0
  215. package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
  216. package/bundle/skills/task-a2a/SKILL.md +55 -0
  217. package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
  218. package/bundle/skills/task-approval/SKILL.md +128 -0
  219. package/bundle/skills/task-artifacts/SKILL.md +46 -0
  220. package/bundle/skills/task-development/SKILL.md +144 -0
  221. package/bundle/skills/task-diagnostics/SKILL.md +41 -0
  222. package/bundle/skills/task-direct-link/SKILL.md +143 -0
  223. package/bundle/skills/task-file-transfer/SKILL.md +107 -0
  224. package/bundle/skills/task-handoff/SKILL.md +23 -0
  225. package/bundle/skills/task-intake/SKILL.md +13 -0
  226. package/bundle/skills/task-notify/SKILL.md +102 -0
  227. package/bundle/skills/task-onboarding/SKILL.md +708 -0
  228. package/bundle/skills/task-recovery/SKILL.md +54 -0
  229. package/bundle/skills/task-repository/SKILL.md +145 -0
  230. package/bundle/skills/task-research/SKILL.md +43 -0
  231. package/bundle/skills/task-schedule/SKILL.md +79 -0
  232. package/bundle/skills/task-sidebar/SKILL.md +122 -0
  233. package/bundle/skills/task-workbench/SKILL.md +30 -0
  234. package/bundle/skills/task-worker/SKILL.md +88 -0
  235. package/bundle/source-search.js +89 -0
  236. package/bundle/source-web.js +17 -0
  237. package/bundle/ssh-connector.js +24 -0
  238. package/bundle/store.js +102 -0
  239. package/bundle/task-a2a.js +298 -0
  240. package/bundle/task-artifacts.js +179 -0
  241. package/bundle/task-board-a2a.js +55 -0
  242. package/bundle/task-board-development.js +83 -0
  243. package/bundle/task-board-planning.js +84 -0
  244. package/bundle/task-board.js +132 -0
  245. package/bundle/task-branch.js +2 -0
  246. package/bundle/task-catalog.js +77 -0
  247. package/bundle/task-context.js +40 -0
  248. package/bundle/task-envelope.js +96 -0
  249. package/bundle/task-interventions.js +54 -0
  250. package/bundle/task-jobs.js +156 -0
  251. package/bundle/task-notifications.js +132 -0
  252. package/bundle/task-results.js +16 -0
  253. package/bundle/task-scheduler.js +77 -0
  254. package/bundle/task-sources.js +101 -0
  255. package/bundle/task-trigger-time.js +46 -0
  256. package/bundle/task-triggers.js +157 -0
  257. package/bundle/task-worker.js +73 -0
  258. package/bundle/task-workflows.js +117 -0
  259. package/bundle/tools.js +13 -0
  260. package/bundle/workbench-assets/asset-provenance.json +26 -0
  261. package/bundle/workbench-assets/whale-ui-states.png +0 -0
  262. package/bundle/workbench-client.js +811 -0
  263. package/bundle/workbench-decisions.js +48 -0
  264. package/bundle/workbench-host.js +122 -0
  265. package/bundle/workbench-im-identity.js +51 -0
  266. package/bundle/workbench-proxy.js +127 -0
  267. package/bundle/worker-rules/AGENTS.md +84 -0
  268. package/bundle/worker-tools.js +13 -0
  269. package/compatibility.json +980 -0
  270. package/cordis.patch.yml +3 -0
  271. package/package.json +57 -4
@@ -0,0 +1,31 @@
1
+ // Exact cloud wire shapes; root/role identity is verified independently of grant state.
2
+ // v2's imTemporaryRootsIncluded=false is a legacy constant, NOT a scope inventory.
3
+ // Preserve it for immutable controllers; actual scope is sendRoots (plan.scope.sendRoots).
4
+ // Consumers must not use it to infer inclusion/exclusion of an explicitly selected IM directory.
5
+ import path from 'node:path';
6
+ import {digest} from './onboarding-ssh.js';
7
+ const exact=(v,ks)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===ks.slice().sort().join();
8
+ 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),hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v),rev=v=>Number.isSafeInteger(v)&&v>=0&&v<Number.MAX_SAFE_INTEGER-1;
9
+ const fail=()=>{throw Error('ONBOARDING_FILES_RESPONSE_REVIEW');};
10
+ const abs=v=>typeof v==='string'&&v.length<=4096&&v.startsWith('/')&&path.posix.normalize(v)===v&&!/[\x00-\x1f\x7f]/u.test(v);
11
+ function limits(v){if(!exact(v,['maxBytes','queueEntries','chunkBytes','automaticDeletion'])||v.maxBytes!==2097152||v.queueEntries!==64||v.chunkBytes!==49152||v.automaticDeletion!==false)fail();}
12
+ export function fileConfigurationInput(v){if(!exact(v,['enabled','sendRoots','maxBytes'])||typeof v.enabled!=='boolean'||!Array.isArray(v.sendRoots)||v.sendRoots.length>8||!v.sendRoots.every(abs)||new Set(v.sendRoots).size!==v.sendRoots.length||!Number.isSafeInteger(v.maxBytes)||v.maxBytes<1||v.maxBytes>2097152)fail();return v;}
13
+ function scope(s){if(!exact(s,['runtimeId','role','namespace','root','rootIdentity','sendRoots','receiveRoot','maxBytes'])||!uuid(s.runtimeId)||s.role!=='cloud'||s.namespace!=='managed-'+s.runtimeId||!abs(s.root)||path.posix.basename(s.root)!==s.runtimeId||!/^\d+:\d+$/.test(s.rootIdentity)||s.receiveRoot!==s.root+'/files/inbox'||!Array.isArray(s.sendRoots)||!s.sendRoots.length||s.sendRoots.some(x=>!exact(x,['path','identity'])||!abs(x.path)||typeof x.identity!=='string'||!(x.path===s.root+'/files/outbox'?x.identity==='owned-outbox':/^\d+:\d+$/.test(x.identity))))fail();fileConfigurationInput({enabled:true,sendRoots:s.sendRoots.map(x=>x.path),maxBytes:s.maxBytes});}
14
+ export function cloudFilePlan(v){if(v?.kind==='scope_migration')return cloudFileMigrationPlan(v);if(!exact(v,['id','expectedRevision','enabled','scope','expiresAt','fingerprint','contract','limits','writes','modelRequests','imTemporaryRootsIncluded','repositoryWriteAuthorized','executionAuthorized'])||v.contract!==2||!uuid(v.id)||!rev(v.expectedRevision)||typeof v.enabled!=='boolean'||!Number.isSafeInteger(v.expiresAt)||!hex(v.fingerprint)||v.writes!==0||v.modelRequests!==0||v.imTemporaryRootsIncluded!==false||v.repositoryWriteAuthorized!==false||v.executionAuthorized!==false)fail();scope(v.scope);limits(v.limits);return v;}
15
+ export function fileMigrationInput(v){if(!exact(v,['sendRoots','maxBytes']))fail();fileConfigurationInput({...v,enabled:false});return v;}
16
+ export function cloudFileMigrationPlan(v){
17
+ const fields=['id','expectedRevision','enabled','scope','migration','expiresAt','fingerprint','contract','kind','limits','writes','modelRequests','preservesFiles','holdsPendingTransfers','requiresSeparateEnable','executionAuthorized','repositoryWriteAuthorized'];
18
+ if(!exact(v,fields)||v.contract!==1||v.kind!=='scope_migration'||!uuid(v.id)||!rev(v.expectedRevision)||v.expectedRevision<1||v.enabled!==false||!Number.isSafeInteger(v.expiresAt)||!hex(v.fingerprint)||v.writes!==0||v.modelRequests!==0||v.preservesFiles!==true||v.holdsPendingTransfers!==true||v.requiresSeparateEnable!==true||v.executionAuthorized!==false||v.repositoryWriteAuthorized!==false||!exact(v.migration,['previousScope','snapshot']))fail();
19
+ scope(v.scope);scope(v.migration.previousScope);limits(v.limits);const old=v.migration.previousScope,s=v.scope,z=v.migration.snapshot;
20
+ if(['runtimeId','role','namespace','root','rootIdentity','receiveRoot'].some(k=>s[k]!==old[k])||digest(s)===digest(old)||!exact(z,['ownerHash','queueHash','held'])||!hex(z.ownerHash)||!hex(z.queueHash)||!exact(z.held,['outgoing','incoming','broker'])||!Object.values(z.held).every(x=>rev(x)&&x<=64))fail();return v;
21
+ }
22
+ export function cloudFileStatus(v){
23
+ if(v?.available===false){if(!exact(v,['contract','available','state','executionAuthorized','repositoryWriteAuthorized'])||v.contract!==2||v.state!=='runtime_required'||v.executionAuthorized!==false||v.repositoryWriteAuthorized!==false)fail();return v;}
24
+ const fields=['contract','available','scope','scopeHash','role','runtimeId','namespace','revision','appliedOperation','appliedPlanHash','enabled','active','state','sendRoots','receiveRoot','maxBytes','limits','counts','error','imTemporaryRootsIncluded','repositoryWriteAuthorized','executionAuthorized','automaticDeletion'];
25
+ if(!exact(v,[...fields,...(v?.notReapplied!==undefined?['notReapplied']:[])])||v.notReapplied!==undefined&&v.notReapplied!==true||v.contract!==2||v.available!==true||v.scope!=='current_managed_host_only'||v.role!=='cloud'||!uuid(v.runtimeId)||v.namespace!=='managed-'+v.runtimeId||!rev(v.revision)||typeof v.enabled!=='boolean'||typeof v.active!=='boolean'||v.active&&!v.enabled||v.enabled&&!hex(v.scopeHash)||v.scopeHash!==null&&!hex(v.scopeHash)||!abs(v.receiveRoot)||!v.receiveRoot.endsWith('/'+v.runtimeId+'/files/inbox')||v.imTemporaryRootsIncluded!==false||v.repositoryWriteAuthorized!==false||v.executionAuthorized!==false||v.automaticDeletion!==false||v.error!==null&&!/^ONBOARDING_FILES_[A-Z_]+$/.test(v.error))fail();
26
+ fileConfigurationInput({enabled:v.enabled,sendRoots:v.sendRoots,maxBytes:v.maxBytes});if(!v.sendRoots.length||!exact(v.counts,['outgoing','incoming','broker'])||!Object.values(v.counts).every(x=>rev(x)&&x<=64))fail();limits(v.limits);
27
+ if(v.revision===0){if(v.appliedOperation!==null||v.appliedPlanHash!==null||v.enabled||v.active||v.scopeHash!==null)fail();}else if(!uuid(v.appliedOperation)||!hex(v.appliedPlanHash))fail();
28
+ if(v.state!==(v.active?'active':v.error?'needs_review':v.enabled?'activation_pending':v.revision?'disabled':'not_configured'))fail();return v;
29
+ }
30
+ export function bindCloudFiles(v,target){const root=target.root+'/runtime/native-home/dsh/dual-host-task-runtime/';if(v.scope&&typeof v.scope==='object'){if(v.scope.root!==root+v.scope.runtimeId)fail();}else if(v.available&&v.receiveRoot!==root+v.runtimeId+'/files/inbox')fail();return v;}
31
+ export const fileAuthorizationHash=v=>digest({runtimeId:v.runtimeId,enabled:v.enabled,scopeHash:v.scopeHash});
@@ -0,0 +1,38 @@
1
+ // Bounded wire contract for a single cloud queue decision, never file content.
2
+ import {digest} from './onboarding-ssh.js';
3
+ import {fileName} from './peer-file-fs.js';
4
+ const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===keys.slice().sort().join();
5
+ export const reviewUuid=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);
6
+ export const reviewHash=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
7
+ const int=(v,max=Number.MAX_SAFE_INTEGER-2)=>Number.isSafeInteger(v)&&v>=0&&v<=max;
8
+ const fail=()=>{throw Error('ONBOARDING_FILES_RESPONSE_REVIEW');};
9
+ export function reviewItem(v){if(!exact(v,['queue','id','origin'])||!['outgoing','incoming','broker'].includes(v.queue)||typeof v.id!=='string'||!/^file-[a-f0-9]{64}$/.test(v.id)||!(v.queue==='broker'?['local','cloud'].includes(v.origin):v.origin===''))fail();return v;}
10
+ export function reviewInput(v){if(!exact(v,['item','decision'])||!['resume','retain'].includes(v.decision))fail();reviewItem(v.item);return v;}
11
+ function details(v){
12
+ reviewItem(v.item);if(v.name!==null){try{fileName(v.name);}catch{fail();}}
13
+ for(const k of ['from','to'])if(v[k]!==null&&!['local','cloud'].includes(v[k]))fail();
14
+ if(v.from!==null&&(v.from===v.to||v.from!==(v.item.queue==='outgoing'?'cloud':v.item.queue==='incoming'?'local':v.item.origin)))fail();
15
+ if(v.size!==null&&!int(v.size,2097152)||v.sha256!==null&&!reviewHash(v.sha256)||v.taskId!==null&&(typeof v.taskId!=='string'||!/^task-[a-f0-9-]{36}$/.test(v.taskId)))fail();
16
+ if(v.attempts!==null&&!int(v.attempts)||v.nextAt!==null&&!int(v.nextAt))fail();
17
+ }
18
+ function noAuthority(v){if(v.executionAuthorized!==false||v.repositoryWriteAuthorized!==false)fail();}
19
+ export function cloudQueueList(v,s){
20
+ if(!exact(v,['contract','role','runtimeId','items','writes','automaticRetry','automaticDeletion','executionAuthorized','repositoryWriteAuthorized','revision','enabled'])||v.contract!==1||v.role!=='cloud'||v.runtimeId!==s.runtimeId||v.revision!==s.revision||v.enabled!==s.enabled||!Array.isArray(v.items)||v.items.length>192||v.writes!==0||v.automaticRetry!==false||v.automaticDeletion!==false)fail();noAuthority(v);
21
+ for(const row of v.items){if(!exact(row,['item','name','from','to','size','sha256','taskId','state','reason','recoveryCheck','retained','attempts','nextAt'])||row.state!=='needs_review'||typeof row.retained!=='boolean'||!/^PEER_FILE_[A-Z_]+$/.test(row.reason)||!(row.recoveryCheck==='requires_byte_validation'||/^ONBOARDING_FILES_[A-Z_]+$/.test(row.recoveryCheck)))fail();details(row);}
22
+ if(new Set(v.items.map(x=>JSON.stringify(x.item))).size!==v.items.length)fail();for(const q of ['outgoing','incoming','broker'])if(v.items.filter(x=>x.item.queue===q).length>64)fail();return v;
23
+ }
24
+ export function cloudQueuePlan(v,s=null){
25
+ const keys=['id','runtimeId','role','expectedRevision','scopeHash','review','expiresAt','fingerprint','contract','kind','writes','modelRequests'];
26
+ if(!exact(v,keys)||v.contract!==2||v.kind!=='queue_review'||!reviewUuid(v.id)||!reviewUuid(v.runtimeId)||v.role!=='cloud'||!int(v.expectedRevision)||v.expectedRevision<1||!reviewHash(v.scopeHash)||!int(v.expiresAt)||!reviewHash(v.fingerprint)||v.writes!==0||v.modelRequests!==0)fail();
27
+ const r=v.review;if(!exact(r,['item','decision','name','from','to','size','sha256','taskId','restoreState','snapshot','attempts','nextAt','snapshotOnly','requiresSeparateEnable','preservesFiles','executionAuthorized','repositoryWriteAuthorized']))fail();reviewInput({item:r.item,decision:r.decision});details(r);noAuthority(r);
28
+ if(r.requiresSeparateEnable!==true||r.preservesFiles!==true||r.snapshotOnly!==(r.item.queue==='outgoing')||!exact(r.snapshot,['ownerHash','rowHash','holdHash','filesHash'])||!['ownerHash','rowHash','holdHash'].every(k=>reviewHash(r.snapshot[k]))||!(r.decision==='resume'?reviewHash(r.snapshot.filesHash):r.snapshot.filesHash===null))fail();
29
+ if(r.decision==='retain'?r.restoreState!=='needs_review':!({outgoing:['queued','broker_saved'],incoming:['receiving','publishing'],broker:['receiving','available']}[r.item.queue].includes(r.restoreState)&&r.name!==null&&r.sha256!==null&&r.size!==null&&(r.attempts===null||r.attempts<16)))fail();
30
+ const body=Object.fromEntries(keys.slice(0,7).map(k=>[k,v[k]]));if(digest(body)!==v.fingerprint)fail();if(s&&(s.runtimeId!==v.runtimeId||s.scopeHash!==v.scopeHash||s.revision!==v.expectedRevision||s.enabled||s.active))fail();return v;
31
+ }
32
+ export function cloudQueueReceipt(v,p){
33
+ const fields=['contract','operation','fingerprint','runtimeId','role','item','decision','stateAtDecision','attempts','nextAt','requiresSeparateEnable','preservesFiles','executionAuthorized','repositoryWriteAuthorized'];
34
+ if(!exact(v,[...fields,...(v?.notReapplied!==undefined?['notReapplied']:[])])||v.notReapplied!==undefined&&v.notReapplied!==true||v.contract!==1||v.operation!==p.id||v.fingerprint!==p.fingerprint||v.runtimeId!==p.runtimeId||v.role!=='cloud'||digest(v.item)!==digest(p.review.item)||v.decision!==p.review.decision||v.stateAtDecision!==p.review.restoreState||v.attempts!==p.review.attempts||v.nextAt!==p.review.nextAt||v.requiresSeparateEnable!==true||v.preservesFiles!==true)fail();noAuthority(v);return v;
35
+ }
36
+ export function cloudQueueOutcome(v,p){
37
+ if(!exact(v,['contract','runtimeId','role','operation','fingerprint','receipt','closed','automaticRetry'])||v.contract!==2||v.runtimeId!==p.runtimeId||v.role!=='cloud'||v.operation!==p.id||v.fingerprint!==p.fingerprint||typeof v.closed!=='boolean'||v.automaticRetry!==false||v.receipt!==null&&v.closed)fail();if(v.receipt!==null)cloudQueueReceipt(v.receipt,p);return v;
38
+ }
@@ -0,0 +1,133 @@
1
+ // Explicit, per-runtime file consent. No user profile writes or implicit IM export.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {credentialKey} from '@deepseek-ai/dsh-credentials';
6
+ import {PeerFiles,FILE_MAX} from './peer-files.js';
7
+ import {FileRoot} from './peer-file-fs.js';
8
+ import {migrationSnapshot,migrateFileScope} from './peer-file-migration.js';
9
+ import {fileQueueList,fileQueuePlan,fileQueueReceipt,fileQueueClosed,closeFileQueuePlan,applyFileQueuePlan} from './peer-file-review.js';
10
+ import {digest} from './onboarding-ssh.js';
11
+ const owner='dsh-dual-host-file-transfer',exact=(v,ks)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===ks.slice().sort().join();
12
+ 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),hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
13
+ const fail=c=>{throw Error('ONBOARDING_FILES_'+c);},within=(a,b)=>a===b||a.startsWith(b+path.sep);
14
+ const limits={maxBytes:FILE_MAX,queueEntries:64,chunkBytes:48*1024,automaticDeletion:false};
15
+ // The outbox contains user input, not executable runtime state. Recognize only our
16
+ // exact private marker; callers must still validate the directory itself. Never
17
+ // traverse, chmod or adopt its contents here: PeerFiles validates each send.
18
+ export function isManagedFileOutbox(root,p){
19
+ if(p!==path.join(root,'files','outbox'))return false;
20
+ try{const marker=path.join(root,'files','owner.json'),s=fs.lstatSync(marker);if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1||(s.mode&0o077)||s.size>1024||process.getuid&&s.uid!==process.getuid())return false;const v=JSON.parse(fs.readFileSync(marker,'utf8'));return exact(v,['owner','schema','runtimeId','role','namespace'])&&v.owner===owner&&v.schema===1&&uuid(v.runtimeId)&&v.runtimeId===path.basename(root)&&['local','cloud'].includes(v.role)&&typeof v.namespace==='string'&&v.namespace.startsWith('managed-')&&uuid(v.namespace.slice(8));}catch{return false;}
21
+ }
22
+ export function createOnboardingFileTransfer({g,root,credentials,protectedRoots=[],now=Date.now}){
23
+ const runtimeId=path.basename(root),role=g.c.role,namespace=g.c.namespace,base=new FileRoot(root),folder=path.join(root,'files'),outbox=path.join(folder,'outbox'),inbox=path.join(folder,'inbox');
24
+ if(!uuid(runtimeId)||!['local','cloud'].includes(role)||!/^managed-[a-f0-9-]{36}$/.test(namespace)||path.resolve(g.c.stateDir)!==path.join(root,'state'))fail('RUNTIME_REQUIRED');
25
+ const key=credentialKey('dsh-task-gateway','onboarding-files-v1-'+runtimeId),marker=JSON.stringify({owner,schema:1,runtimeId,role,namespace});let pending=null,queuePending=null,mounted=null,raw=null,busy=false,closed=false,lastError=null;
26
+ const available=()=>!closed&&!g.closed&&!!credentials();
27
+ const ready=()=>{if(!available())fail('UNAVAILABLE');base.check();};
28
+ function owned(p,dir){const s=fs.lstatSync(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;}
29
+ function inspectOwned(){base.check();if(!fs.existsSync(folder))return;owned(folder,true);owned(path.join(folder,'owner.json'),false);if(fs.readFileSync(path.join(folder,'owner.json'),'utf8')!==marker)fail('PATH_REVIEW');for(const p of [outbox,inbox])if(fs.existsSync(p))owned(p,true);}
30
+ function makeOwned(){inspectOwned();if(!fs.existsSync(folder)){fs.mkdirSync(folder,{mode:0o700});fs.writeFileSync(path.join(folder,'owner.json'),marker,{flag:'wx',mode:0o600});}for(const p of [outbox,inbox]){try{fs.mkdirSync(p,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}owned(p,true);}}
31
+ function scope(roots,maxBytes){
32
+ ready();inspectOwned();if(!Array.isArray(roots)||roots.length>8||!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>FILE_MAX)fail('ARGUMENTS');
33
+ const selected=(roots.length?roots:[outbox]).map(p=>{
34
+ if(typeof p!=='string'||p.length>4096||!path.isAbsolute(p)||path.resolve(p)!==p||/[\x00-\x1f\x7f]/u.test(p))fail('SOURCE_REVIEW');
35
+ if(p===outbox)return {path:p,identity:'owned-outbox'};
36
+ if(p===path.dirname(p)||within(p,root)||within(root,p)||protectedRoots.some(x=>within(p,x)||within(x,p))||p.split(path.sep).some(x=>/^(?:\.ssh|\.dsh|\.agents|\.\u0063\u006f\u0064\u0065\u0078|\.aws|\.aliyun|credentials|secrets)$/iu.test(x)))fail('SOURCE_DENIED');
37
+ const r=new FileRoot(p);if(r.canonical!==p)fail('SOURCE_REVIEW');return {path:p,identity:r.id};
38
+ }).sort((a,b)=>a.path.localeCompare(b.path));
39
+ if(new Set(selected.map(x=>x.path)).size!==selected.length||selected.some((a,i)=>selected.some((b,j)=>i!==j&&within(a.path,b.path))))fail('SOURCE_OVERLAP');
40
+ return {runtimeId,role,namespace,root,rootIdentity:base.id,sendRoots:selected,receiveRoot:inbox,maxBytes};
41
+ }
42
+ function checkedScope(s){if(!exact(s,['runtimeId','role','namespace','root','rootIdentity','sendRoots','receiveRoot','maxBytes'])||s.runtimeId!==runtimeId||s.role!==role||s.namespace!==namespace||s.root!==root||s.rootIdentity!==base.id||s.receiveRoot!==inbox||!Array.isArray(s.sendRoots)||!s.sendRoots.length||s.sendRoots.length>8||s.sendRoots.some(x=>!exact(x,['path','identity'])||typeof x.path!=='string'||!path.isAbsolute(x.path)||path.resolve(x.path)!==x.path||typeof x.identity!=='string'||!(x.path===outbox?x.identity==='owned-outbox':/^\d+:\d+$/.test(x.identity)))||!Number.isSafeInteger(s.maxBytes)||s.maxBytes<1||s.maxBytes>FILE_MAX)fail('LEDGER_REVIEW');return s;}
43
+ function record(r){if(!r)return null;const p=r.payload;
44
+ if(r.kind!=='grant'||!exact(p,['owner','schema','revision','operation','planHash','enabled','scope','updatedAt',...(p?.schema===2?['transition']:[])])||p.owner!==owner||![1,2].includes(p.schema)||!Number.isSafeInteger(p.revision)||p.revision<1||p.revision>=Number.MAX_SAFE_INTEGER-1||!uuid(p.operation)||!hex(p.planHash)||typeof p.enabled!=='boolean'||!Number.isSafeInteger(p.updatedAt))fail('LEDGER_REVIEW');
45
+ if(p.scope===null){if(p.enabled||p.schema===2)fail('LEDGER_REVIEW');return p;}checkedScope(p.scope);
46
+ if(p.schema===2){const t=p.transition;if(p.enabled||!exact(t,['previousScope','snapshot'])||!exact(t.snapshot,['ownerHash','queueHash','held'])||!hex(t.snapshot.ownerHash)||!hex(t.snapshot.queueHash)||!exact(t.snapshot.held,['outgoing','incoming','broker'])||!Object.values(t.snapshot.held).every(x=>Number.isSafeInteger(x)&&x>=0&&x<=64))fail('LEDGER_REVIEW');checkedScope(t.previousScope);}
47
+ return p;
48
+ }
49
+ function settled(p){if(p?.transition)fail('MIGRATION_PENDING');}
50
+ async function completeMigration(p){
51
+ if(!p?.transition)return p;
52
+ // The persistent intent is already an explicit disabled-only authorization.
53
+ // Resume only that exact operation; never infer consent from the new DB owner.
54
+ if(g.files||raw||mounted)fail('MIGRATION_DISABLE_REQUIRED');inspectOwned();
55
+ if(digest(scope(p.scope.sendRoots.map(x=>x.path),p.scope.maxBytes))!==digest(p.scope))fail('SOURCE_CHANGED');
56
+ migrateFileScope(g.db,{operation:p.operation,planHash:p.planHash,previous:p.transition.previousScope,next:p.scope,snapshot:p.transition.snapshot});
57
+ let next;await credentials().modifyRecord(key,current=>{const c=record(current);if(c?.revision!==p.revision||c.operation!==p.operation||c.planHash!==p.planHash||digest(c.scope)!==digest(p.scope))fail('CONFLICT');if(!c.transition){next=c;return undefined;}if(digest(c.transition)!==digest(p.transition))fail('CONFLICT');const {transition,...rest}=c;next={...rest,schema:1};return {kind:'grant',payload:next};});lastError=null;return next;
58
+ }
59
+ async function read(){ready();return record(await credentials().readRecord(key));}
60
+ async function run(fn){ready();if(busy)fail('BUSY');busy=true;try{return await fn();}finally{busy=false;}}
61
+ async function suspend(){const prior=raw;if(g.files===mounted)g.files=undefined;mounted=null;raw=null;if(prior?.pending)await prior.pending.catch(()=>{});}
62
+ async function sync(p){
63
+ await suspend();lastError=null;if(!p?.enabled)return;
64
+ if(g.files)fail('SERVICE_CONFLICT');if(digest(scope(p.scope.sendRoots.map(x=>x.path),p.scope.maxBytes))!==digest(p.scope))fail('SOURCE_CHANGED');makeOwned();
65
+ let acceptedRevision=p.revision;const engine=new PeerFiles(g,{enabled:true,sendRoots:p.scope.sendRoots.map(x=>x.path),receiveRoot:inbox,maxBytes:p.scope.maxBytes});let facade;
66
+ async function authorized(){const latest=await read();if(g.files!==facade||!latest?.enabled||latest.revision!==acceptedRevision||digest(latest.scope)!==digest(p.scope))fail('DISABLED');}
67
+ const tracked=fn=>g.maintenance?g.maintenance.run('managed_files',fn):fn();
68
+ facade={scopeHash:digest(p.scope),advanceRevision:r=>{acceptedRevision=r;},code:e=>engine.code(e),get pending(){return engine.pending;},get lastError(){return engine.lastError;},set lastError(e){engine.lastError=e;},snapshot:()=>engine.snapshot(),async scope(){await authorized();return {...engine.scope(),revision:acceptedRevision,scope_hash:digest(p.scope)};},async enqueue(a){return tracked(async()=>{await authorized();return engine.enqueue(a);});},async list(a){return tracked(async()=>{await authorized();return engine.list(a);});},async call(...a){return tracked(async()=>{await authorized();return engine.call(...a);});},async sync(){if(g.maintenance?.blocked)return;return tracked(async()=>{await authorized();return engine.sync();});}};
69
+ if(g.files)fail('SERVICE_CONFLICT');raw=engine;mounted=facade;g.files=facade;mounted.revision=p.revision;
70
+ }
71
+ async function start(){if(!available())return;return run(async()=>{try{await sync(await completeMigration(await read()));}catch(e){lastError=safe(e);}});}
72
+ function safe(e){return /^ONBOARDING_FILES_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_FILES_NEEDS_REVIEW';}
73
+ function counts(){const db=g.db,exists=db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='peer_file_out'").get();if(!exists)return {outgoing:0,incoming:0,broker:0};return {outgoing:db.prepare('SELECT count(*) n FROM peer_file_out').get().n,incoming:db.prepare('SELECT count(*) n FROM peer_file_in').get().n,broker:db.prepare('SELECT count(*) n FROM peer_file_broker').get().n};}
74
+ async function status(a={}){if(!exact(a,[]))fail('ARGUMENTS');const p=await read(),active=!p?.transition&&!!p?.enabled&&g.files===mounted&&mounted?.revision===p.revision;
75
+ return {contract:2,available:true,scope:'current_managed_host_only',scopeHash:p?.scope?digest(p.scope):null,role,runtimeId,namespace,revision:p?.revision??0,appliedOperation:p?.operation??null,appliedPlanHash:p?.planHash??null,enabled:p?.enabled??false,active:!!active,state:active?'active':p?.transition||lastError?'needs_review':p?.enabled?'activation_pending':p?'disabled':'not_configured',sendRoots:p?.scope?.sendRoots.map(x=>x.path)??[outbox],receiveRoot:inbox,maxBytes:p?.scope?.maxBytes??FILE_MAX,limits,counts:counts(),error:p?.transition?'ONBOARDING_FILES_MIGRATION_PENDING':lastError,imTemporaryRootsIncluded:false,repositoryWriteAuthorized:false,executionAuthorized:false,automaticDeletion:false};}
76
+ async function preview(a){return run(async()=>{pending=null;if(!exact(a,['enabled','sendRoots','maxBytes'])||typeof a.enabled!=='boolean')fail('ARGUMENTS');const p=await read();settled(p);let s;if(!a.enabled){if(!p?.scope)fail('NOT_CONFIGURED');if(!Array.isArray(a.sendRoots)||digest(a.sendRoots.length?a.sendRoots.slice().sort():[outbox])!==digest(p.scope.sendRoots.map(x=>x.path).sort())||a.maxBytes!==p.scope.maxBytes)fail('ARGUMENTS');s=p.scope;}else s=scope(a.sendRoots,a.maxBytes);if(p?.scope&&digest(p.scope)!==digest(s))fail('SCOPE_CHANGE_REQUIRES_MIGRATION');
77
+ const body={id:randomUUID(),expectedRevision:p?.revision??0,enabled:a.enabled,scope:s,expiresAt:now()+300000};pending={...body,fingerprint:digest(body)};return {...pending,contract:2,limits,writes:0,modelRequests:0,imTemporaryRootsIncluded:false,repositoryWriteAuthorized:false,executionAuthorized:false};});}
78
+ async function migrationPreview(a){return run(async()=>{
79
+ pending=null;if(!exact(a,['sendRoots','maxBytes']))fail('ARGUMENTS');const p=await read();settled(p);
80
+ if(!p?.scope)fail('NOT_CONFIGURED');if(p.enabled||g.files||mounted||raw)fail('MIGRATION_DISABLE_REQUIRED');
81
+ const s=scope(a.sendRoots,a.maxBytes);if(digest(s)===digest(p.scope))fail('MIGRATION_NO_CHANGE');
82
+ const migration={previousScope:p.scope,snapshot:migrationSnapshot(g.db,p.scope)};
83
+ const body={id:randomUUID(),expectedRevision:p.revision,enabled:false,scope:s,migration,expiresAt:now()+300000};pending={...body,fingerprint:digest(body)};
84
+ return {...pending,contract:1,kind:'scope_migration',limits,writes:0,modelRequests:0,preservesFiles:true,holdsPendingTransfers:true,requiresSeparateEnable:true,executionAuthorized:false,repositoryWriteAuthorized:false};
85
+ });}
86
+ async function migrationRecover(a){return run(async()=>{
87
+ if(!exact(a,['operation','confirm'])||!uuid(a.operation)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');const p=await read();if(p?.operation!==a.operation)fail('CONFLICT');
88
+ if(!p.transition){lastError=null;return {...await status({}),notReapplied:true};}
89
+ try{await completeMigration(p);}catch(e){lastError=safe(e);throw e;}return status({});
90
+ });}
91
+ function queueReady(p){settled(p);if(!p?.scope)fail('NOT_CONFIGURED');if(p.enabled||g.files||raw||mounted)fail('QUEUE_DISABLE_REQUIRED');inspectOwned();}
92
+ async function queueList(a){return run(async()=>{if(!exact(a,[]))fail('ARGUMENTS');const p=await read();settled(p);if(!p?.scope)fail('NOT_CONFIGURED');inspectOwned();return {...fileQueueList(g,p.scope),revision:p.revision,enabled:p.enabled};});}
93
+ async function queueReviewPreview(a){return run(async()=>{
94
+ queuePending=null;if(!exact(a,['item','decision']))fail('ARGUMENTS');const p=await read();queueReady(p);
95
+ const body={id:randomUUID(),runtimeId,role,expectedRevision:p.revision,scopeHash:digest(p.scope),review:fileQueuePlan(g,p.scope,a),expiresAt:now()+300000};queuePending={...body,fingerprint:digest(body)};
96
+ return {...queuePending,contract:2,kind:'queue_review',writes:0,modelRequests:0};
97
+ });}
98
+ async function queueReviewApply(a){return run(async()=>{
99
+ if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
100
+ const prior=fileQueueReceipt(g.db,a.id,a.fingerprint);if(prior)return {...prior,notReapplied:true};
101
+ if(fileQueueClosed(g.db,a.id,a.fingerprint))fail('QUEUE_CLOSED');
102
+ const plan=queuePending;if(!plan||plan.id!==a.id||plan.fingerprint!==a.fingerprint||plan.expiresAt<=now())fail('PLAN_EXPIRED');queuePending=null;
103
+ const p=await read();queueReady(p);if(p.revision!==plan.expectedRevision||digest(p.scope)!==plan.scopeHash)fail('CONFLICT');
104
+ // No await between this last disabled-grant check and the synchronous DB commit.
105
+ // Queue intent is the atomic receipt, not a new grant; restart cannot enable it.
106
+ return applyFileQueuePlan(g,p.scope,plan);
107
+ });}
108
+ async function queueReviewStatus(a){return run(async()=>{
109
+ if(!exact(a,['operation','fingerprint'])||!uuid(a.operation)||!hex(a.fingerprint))fail('ARGUMENTS');
110
+ return queueOutcome(a);
111
+ });}
112
+ function queueOutcome(a){return {contract:2,runtimeId,role,operation:a.operation,fingerprint:a.fingerprint,receipt:fileQueueReceipt(g.db,a.operation,a.fingerprint),closed:fileQueueClosed(g.db,a.operation,a.fingerprint),automaticRetry:false};}
113
+ async function queueReviewClose(a){return run(async()=>{
114
+ if(!exact(a,['operation','fingerprint','confirm'])||!uuid(a.operation)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
115
+ // This barrier does not require or change the file grant, queue, or engine.
116
+ closeFileQueuePlan(g.db,a.operation,a.fingerprint);return queueOutcome(a);
117
+ });}
118
+ async function apply(a){return run(async()=>{if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');const old=await read();if(old?.operation===a.id&&old.planHash===a.fingerprint)return {...await status({}),notReapplied:true};const p=pending;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');pending=null;
119
+ if((p.enabled||p.migration)&&digest(scope(p.scope.sendRoots.map(x=>x.path),p.scope.maxBytes))!==digest(p.scope))fail('SOURCE_CHANGED');
120
+ if(p.migration&&(old?.enabled||g.files||mounted||raw))fail('MIGRATION_DISABLE_REQUIRED');
121
+ await credentials().modifyRecord(key,current=>{const prior=record(current);settled(prior);if((prior?.revision??0)!==p.expectedRevision)fail('CONFLICT');return {kind:'grant',payload:{owner,schema:p.migration?2:1,revision:p.expectedRevision+1,operation:p.id,planHash:p.fingerprint,enabled:p.enabled,scope:p.scope,updatedAt:now(),...(p.migration?{transition:p.migration}:{})}};});
122
+ try{await sync(await completeMigration(await read()));}catch(e){lastError=safe(e);await suspend();}return status({});
123
+ });}
124
+ async function fence(a){return run(async()=>{
125
+ 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');
126
+ let next;await credentials().modifyRecord(key,current=>{const p=record(current);settled(p);if(p?.operation===a.operation&&p.planHash===digest(a)){next=p;return undefined;}if((p?.revision??0)!==a.expectedRevision)fail('CONFLICT');next={owner,schema:1,revision:a.expectedRevision+1,operation:a.operation,planHash:digest(a),enabled:p?.enabled??false,scope:p?.scope??null,updatedAt:now()};return {kind:'grant',payload:next};});
127
+ // A fence closes an uncertain old write; it must not mount, stop, or adopt a directory.
128
+ if(mounted&&g.files===mounted&&next.enabled&&mounted.revision===a.expectedRevision&&mounted.scopeHash===digest(next.scope)){mounted.revision=next.revision;mounted.advanceRevision(next.revision);}
129
+ return status({});
130
+ });}
131
+ async function close(){closed=true;pending=null;queuePending=null;await suspend();}
132
+ return {available,start,status,preview,apply,fence,migrationPreview,migrationRecover,queueList,queueReviewPreview,queueReviewApply,queueReviewStatus,queueReviewClose,close};
133
+ }
@@ -0,0 +1,98 @@
1
+ // Evaluated only with the exact archived controller and runtime extension.
2
+ // Destination address comes from a live, signed, owned native runtime. Never input a URL.
3
+ async function handoffSession(q){
4
+ const source=await runtimeSource(q),j=await runtimeRecord(q);
5
+ if(await cleanupRead(q)||!j||j.state!=='host_ready'||!await runtimeAlive(j.host)||await runtimeAlive(j.worker)||await runtimeAlive(j.child)||await runtimeAlive(j.restart?.launcher)||j.nativeReceipt?.ok!==true||j.nativeReceipt.nonce!==j.nativeNonce||j.nativeReceipt.pid!==j.host.pid)fail('HANDOFF_HOST_NOT_READY');
6
+ if(!uuid(j.nativeNonce)||j.restart&&!uuid(j.restart.id)||j.nativeReceipt.dshHome!==path.join(runtimeRoot(q),'native-home/dsh')||j.nativeReceipt.agentsHome!==path.join(runtimeRoot(q),'native-home/agents'))fail('HANDOFF_IDENTITY_REVIEW');
7
+ const compat=JSON.parse((await regular(path.join(q.root,'plugin/compatibility.json'))).data);
8
+ if(compat.onboardingPluginVersionLifecycle===1)await runtimeVerifyPlugin(q,j);
9
+ else for(const f of source.owner.manifest){const name=path.join(runtimeRoot(q),f.path);await checkAncestors(path.dirname(name));const copy=await regular(name);if(!copy||copy.sha256!==f.sha256||copy.identity.mode!==f.mode||copy.identity.uid!==process.getuid())fail('HANDOFF_RUNTIME_SOURCE_CHANGED');}
10
+ if(j.nativeReceipt.gatewayBound!==false){const {isManagedGatewayReceipt}=await import(runtimeURL(path.join(runtimeRoot(q),'plugin/onboarding-task-runtime-contract.js')));if(!isManagedGatewayReceipt(j.nativeReceipt))fail('HANDOFF_HOST_NOT_READY');}
11
+ const control=j.restart?path.join(runtimeDir(q),'restarts',j.restart.id):runtimeDir(q);
12
+ await checkAncestors(control);const file=await regular(path.join(control,'native-access.json'),16384);
13
+ if(!file||file.identity.uid!==process.getuid()||file.identity.mode!==0o600)fail('HANDOFF_ACCESS_REVIEW');
14
+ let access;try{access=new URL(JSON.parse(file.data).url);}catch{fail('HANDOFF_ACCESS_REVIEW');}
15
+ if(access.protocol!=='http:'||access.hostname!=='127.0.0.1'||access.username||access.password||access.pathname!=='/'||access.hash||access.origin!==j.nativeReceipt.origin||[...access.searchParams.keys()].join()!=='token'||!access.searchParams.get('token'))fail('HANDOFF_ACCESS_REVIEW');
16
+ const target={operationId:q.operationId,installationId:q.installationId,runtimeId:j.id,manifestHash:source.owner.manifestHash,root:q.root,role:'cloud',hostVersion:j.nativeReceipt.hostVersion};
17
+ const login=new URL('/connect',access.origin);login.searchParams.set('token',access.searchParams.get('token'));login.searchParams.set('interactions','none');
18
+ const response=await fetch(login,{redirect:'manual',signal:AbortSignal.timeout(5000)}),cookie=response.headers.get('set-cookie')?.split(';')[0];
19
+ if(response.status!==302||!cookie||/[\r\n]/.test(cookie))fail('HANDOFF_AUTH_FAILED');
20
+ async function rpc(method,args){
21
+ const rpcId=randomUUID(),body={type:'client-request',rpcId,method:'task-onboarding/control',payload:{method,args}};
22
+ const res=await fetch(new URL('/api/task-onboarding/control',access.origin),{method:'POST',redirect:'manual',headers:{'content-type':'application/json',cookie},body:JSON.stringify(body),signal:AbortSignal.timeout(method==='task_pair_forward'?25000:method==='repository_inspect'||method==='repository_registry_preview'?15000:8000)});
23
+ let size=0,chunks=[];if(!res.ok)fail('HANDOFF_RESPONSE_REVIEW');for await(const chunk of res.body){size+=chunk.length;if(size>(method==='task_pair_forward'?589824:(method.startsWith('repository_registry_')||method.startsWith('file_transfer_'))?196608:65536))fail('HANDOFF_RESPONSE_REVIEW');chunks.push(chunk);}
24
+ let v;try{v=JSON.parse(Buffer.concat(chunks));}catch{fail('HANDOFF_RESPONSE_REVIEW');}
25
+ if(v?.type!=='server-response'||v.rpcId!==rpcId)fail('HANDOFF_RESPONSE_REVIEW');
26
+ if(v.result?.ok!==true){if(method.startsWith('file_transfer_')&&/^ONBOARDING_FILES_[A-Z_]+$/.test(v.result?.error?.code))throw Error(v.result.error.code);if((method.startsWith('task_runtime_')||method.startsWith('task_pair_'))&&/^ONBOARDING_TASK_RUNTIME_[A-Z_]+$/.test(v.result?.error?.code))throw Error(v.result.error.code);if(method.startsWith('repository_')&&/^ONBOARDING_REPOSITORY_[A-Z_]+$/.test(v.result?.error?.code))throw Error(v.result.error.code);if(/^(?:token_)?model_/.test(method)&&/^ONBOARDING_MODEL_[A-Z_]+$/.test(v.result?.error?.code))throw Error(v.result.error.code);fail('HANDOFF_RESPONSE_REVIEW');}return v.result.value;
27
+ }
28
+ const description=await rpc('describe',{}),d=await rpc('detect',{});
29
+ if(description.contract!==1||typeof description.configured!=='boolean'||description.capabilities?.write!==false||description.capabilities?.cloudCredentialReceipt!==true||d.role!=='cloud'||d.platform!=='linux'||d.paths?.dsh?.path!==j.nativeReceipt.dshHome||d.paths?.agents?.path!==j.nativeReceipt.agentsHome)fail('HANDOFF_IDENTITY_REVIEW');
30
+ if(description.configured){if(![1,2,3,4].includes(description.capabilities?.managedTaskRuntimeContract))fail('HANDOFF_IDENTITY_REVIEW');const {isManagedTaskRuntime}=await import(runtimeURL(path.join(runtimeRoot(q),'plugin/onboarding-task-runtime-contract.js')));if(!isManagedTaskRuntime(await rpc('task_runtime_status',{})))fail('HANDOFF_IDENTITY_REVIEW');}
31
+ if(!await runtimeAlive(j.host))fail('HANDOFF_HOST_NOT_READY');
32
+ return {target,rpc,notificationDiscovery:description.capabilities?.notificationDiscoveryContract===1,files:description.capabilities?.managedFileTransferContract===2,filesQueueReview:description.capabilities?.managedFileQueueReviewContract===2,filesMigration:description.capabilities?.managedFileScopeMigrationContract===1,modelClarification:description.capabilities?.modelClarificationContract===1,tokenModelClarification:description.capabilities?.tokenModelClarificationContract===1,modelProbe:description.capabilities?.modelProbeContract===2,tokenModelProbe:description.capabilities?.tokenModelProbeContract===2,taskRuntime:[2,3,4].includes(description.capabilities?.managedTaskRuntimeContract),peerBinding:[3,4].includes(description.capabilities?.managedTaskRuntimeContract)&&description.capabilities?.managedPeerBindingContract===1,webAccess:{port:Number(access.port),token:access.searchParams.get('token'),nativeNonce:j.nativeNonce},repositoryRegistry:description.capabilities?.repositoryRegistryContract===2,repositoryCheck:description.capabilities?.repositoryCheckContract===1,giteeReceipt:description.capabilities?.giteeCredentialReceipt===true,giteeFence:description.capabilities?.giteeCredentialFence===true,imInventory:description.capabilities?.imInventoryContract===1,fencingSupported:description.capabilities?.cloudCredentialFence===true,modelBinding:description.capabilities?.modelBinding===true,tokenPlanBinding:description.capabilities?.tokenPlanBinding===true,tokenPlanReceipt:description.capabilities?.tokenPlanCredentialReceipt===true,tokenPlanFence:description.capabilities?.tokenPlanCredentialFence===true};
33
+ }
34
+ export async function handoffControl(q){
35
+ const keys=['action','root','operationId','installationId','proof','planHash','handoff'];
36
+ if(!exact(q,keys)||q.action!=='handoff'||!['notification_defaults_discover','notification_defaults_candidate','file_transfer_queueList','file_transfer_queueReviewPreview','file_transfer_queueReviewApply','file_transfer_queueReviewStatus','file_transfer_queueReviewClose','file_transfer_migrationPreview','file_transfer_migrationRecover','file_transfer_status','file_transfer_preview','file_transfer_apply','file_transfer_fence','task_pair_status','task_pair_preview','task_pair_apply','task_pair_fence','task_pair_forward','task_runtime_status','task_runtime_preview','task_runtime_apply','task_runtime_fence','repository_registry_status','repository_registry_preview','repository_registry_apply','repository_registry_fence','repository_inspect','gitee_inspect','gitee_receipt','gitee_put','gitee_fence','web_access','im_inventory','inspect','receipt','put','fence','model_status','model_preview','model_apply','model_resolve','model_probe_status','model_probe_preview','model_probe_start','token_model_probe_status','token_model_probe_preview','token_model_probe_start','token_inspect','token_receipt','token_put','token_fence','token_model_status','token_model_preview','token_model_apply','token_model_resolve'].includes(q.handoff?.action))fail('HANDOFF_ARGUMENTS');
37
+ const raw=q.handoff,token=raw.action.startsWith('token_'),gitee=raw.action.startsWith('gitee_'),a={...raw,action:token||gitee?raw.action.slice(6):raw.action},model=a.action.startsWith('model_'),slot=gitee?'gitee':token?'token-plan':'deepseek-local';
38
+ if(a.action.startsWith('file_transfer_')){
39
+ const fields={file_transfer_queueList:['action','targetHash'],file_transfer_queueReviewPreview:['action','item','decision','targetHash'],file_transfer_queueReviewApply:['action','id','fingerprint','confirm','targetHash'],file_transfer_queueReviewStatus:['action','operation','fingerprint','targetHash'],file_transfer_queueReviewClose:['action','operation','fingerprint','confirm','targetHash'],file_transfer_migrationPreview:['action','sendRoots','maxBytes'],file_transfer_migrationRecover:['action','operation','confirm','targetHash'],file_transfer_status:['action',...(a.targetHash!==undefined?['targetHash']:[])],file_transfer_preview:['action','enabled','sendRoots','maxBytes'],file_transfer_apply:['action','id','fingerprint','confirm','targetHash'],file_transfer_fence:['action','operation','expectedRevision','confirm','targetHash']}[a.action];
40
+ if(a.action.startsWith('file_transfer_queue')&&(!hex(a.targetHash)||a.action==='file_transfer_queueReviewPreview'&&(!exact(a.item,['queue','id','origin'])||!['outgoing','incoming','broker'].includes(a.item.queue)||typeof a.item.id!=='string'||!/^file-[a-f0-9]{64}$/.test(a.item.id)||!(a.item.queue==='broker'?['local','cloud'].includes(a.item.origin):a.item.origin==='')||!['resume','retain'].includes(a.decision))||a.action==='file_transfer_queueReviewApply'&&(!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)||['file_transfer_queueReviewStatus','file_transfer_queueReviewClose'].includes(a.action)&&(!uuid(a.operation)||!hex(a.fingerprint)||a.action==='file_transfer_queueReviewClose'&&a.confirm!==true)))fail('HANDOFF_ARGUMENTS');
41
+ if(!fields||!exact(a,fields)||a.targetHash!==undefined&&!hex(a.targetHash)||(a.action==='file_transfer_preview'||a.action==='file_transfer_migrationPreview')&&(a.action==='file_transfer_preview'&&typeof a.enabled!=='boolean'||!Array.isArray(a.sendRoots)||a.sendRoots.length>8||a.sendRoots.some(x=>typeof x!=='string'||x.length>4096||!x.startsWith('/')||/[\x00-\x1f\x7f]/.test(x))||!Number.isSafeInteger(a.maxBytes)||a.maxBytes<1||a.maxBytes>2097152)||a.action==='file_transfer_apply'&&(!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)||a.action==='file_transfer_migrationRecover'&&(!uuid(a.operation)||a.confirm!==true)||a.action==='file_transfer_fence'&&(!uuid(a.operation)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.expectedRevision>=Number.MAX_SAFE_INTEGER-1||a.confirm!==true))fail('HANDOFF_ARGUMENTS');
42
+ }else if(a.action.startsWith('task_pair_')){
43
+ const fields={task_pair_status:['action',...(a.targetHash!==undefined?['targetHash']:[])],task_pair_preview:['action','enabled','localId','targetHash'],task_pair_apply:['action','id','fingerprint','confirm','targetHash'],task_pair_fence:['action','operation','expectedRevision','id','localId','runtimeId','confirm','targetHash'],task_pair_forward:['action','id','localId','revision','frame','targetHash']}[a.action];
44
+ if(!fields||!exact(a,fields)||a.targetHash!==undefined&&!hex(a.targetHash)||a.action==='task_pair_preview'&&(typeof a.enabled!=='boolean'||!uuid(a.localId))||a.action==='task_pair_apply'&&(!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)||a.action==='task_pair_fence'&&(![a.operation,a.id,a.localId,a.runtimeId].every(uuid)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.confirm!==true)||a.action==='task_pair_forward'&&(![a.id,a.localId].every(uuid)||!Number.isSafeInteger(a.revision)||a.revision<1||!a.frame||typeof a.frame!=='object'||Array.isArray(a.frame)||Buffer.byteLength(JSON.stringify(a.frame))>131072))fail('HANDOFF_ARGUMENTS');
45
+ }else if(a.action.startsWith('task_runtime_')){
46
+ const fields={task_runtime_status:['action',...(a.targetHash!==undefined?['targetHash']:[])],task_runtime_preview:['action','enabled',...(a.workerEnabled!==undefined?['workerEnabled']:[])],task_runtime_apply:['action','id','fingerprint','confirm','targetHash'],task_runtime_fence:['action','operation','expectedRevision','confirm','targetHash']}[a.action];
47
+ if(!fields||!exact(a,fields)||a.targetHash!==undefined&&!hex(a.targetHash)||a.action==='task_runtime_preview'&&(typeof a.enabled!=='boolean'||a.workerEnabled!==undefined&&typeof a.workerEnabled!=='boolean'||a.workerEnabled&&!a.enabled)||a.action==='task_runtime_apply'&&(!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)||a.action==='task_runtime_fence'&&(!uuid(a.operation)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.confirm!==true))fail('HANDOFF_ARGUMENTS');
48
+ }else if(a.action.startsWith('repository_registry_')){
49
+ const fields={repository_registry_status:['action',...(a.targetHash!==undefined?['targetHash']:[])],repository_registry_preview:['action','url','alias','authentication','enabled'],repository_registry_apply:['action','id','fingerprint','confirm','targetHash'],repository_registry_fence:['action','operation','expectedRevision','confirm','targetHash']}[a.action];
50
+ if(!fields||!exact(a,fields)||a.targetHash!==undefined&&!hex(a.targetHash)||a.action==='repository_registry_preview'&&(typeof a.url!=='string'||a.url.length>500||typeof a.alias!=='string'||a.alias.length>120||!['anonymous','managed'].includes(a.authentication)||typeof a.enabled!=='boolean')||a.action==='repository_registry_apply'&&(!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)||a.action==='repository_registry_fence'&&(!uuid(a.operation)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.confirm!==true))fail('HANDOFF_ARGUMENTS');
51
+ }else if(a.action==='repository_inspect'){if(!exact(a,['action','url','branch','authentication'])||typeof a.url!=='string'||a.url.length>500||typeof a.branch!=='string'||a.branch.length>200||!['anonymous','managed'].includes(a.authentication))fail('HANDOFF_ARGUMENTS');}
52
+ else if(a.action.startsWith('notification_defaults_')){if(a.host!=='cloud'||!exact(a,['action','host',...(a.action==='notification_defaults_candidate'?['candidate_id','label']:[])]))fail('HANDOFF_ARGUMENTS');}
53
+ else if(['web_access','im_inventory'].includes(a.action)){if(!exact(a,['action']))fail('HANDOFF_ARGUMENTS');}
54
+ else if(a.action.startsWith('model_probe_')){
55
+ const fields={model_probe_status:['action'],model_probe_preview:['action','query','acknowledgeUnknown',...(a.clarification!==undefined?['clarification']:[])],model_probe_start:['action','id','fingerprint','confirm','targetHash']}[a.action];
56
+ if(!fields||!exact(a,fields)||a.action==='model_probe_preview'&&(typeof a.query!=='string'||!a.query.trim()||a.query.length>200||/[\x00-\x1f\x7f]/.test(a.query)||a.acknowledgeUnknown!==null&&!uuid(a.acknowledgeUnknown))||a.action==='model_probe_start'&&(!uuid(a.id)||!hex(a.fingerprint)||!hex(a.targetHash)||a.confirm!==true))fail('HANDOFF_ARGUMENTS');
57
+ }else if(model){
58
+ const fields={model_status:['action'],model_preview:['action','enabled'],model_apply:['action','id','fingerprint','confirm','targetHash'],model_resolve:['action','query',...(a.clarification!==undefined?['clarification']:[])]}[a.action];
59
+ if(!exact(a,fields)||a.action==='model_preview'&&typeof a.enabled!=='boolean'||a.action==='model_apply'&&(!uuid(a.id)||!hex(a.fingerprint)||!hex(a.targetHash)||a.confirm!==true)||a.action==='model_resolve'&&(typeof a.query!=='string'||a.query.length>200||/[\x00-\x1f\x7f]/.test(a.query)))fail('HANDOFF_ARGUMENTS');
60
+ }else{
61
+ const fields=a.action==='inspect'?['action']:['action','operation','expectedRevision','targetHash',...(a.action==='put'?['secret']:[])];
62
+ if(!exact(a,fields)||a.action!=='inspect'&&(!uuid(a.operation)||!hex(a.targetHash)||!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<0||a.expectedRevision>=Number.MAX_SAFE_INTEGER)||a.action==='put'&&(typeof a.secret!=='string'||a.secret.length<8||a.secret.length>4096||!/^[\x21-\x7e]+$/.test(a.secret)||a.secret.includes('PRIVATE KEY')))fail('HANDOFF_ARGUMENTS');
63
+ }
64
+ if(a.clarification!==undefined&&(typeof a.clarification!=='string'||!a.clarification.trim()||a.clarification.length>200||/[\x00-\x1f\x7f]/.test(a.clarification)))fail('HANDOFF_ARGUMENTS');
65
+ base(q);await runtimeSource(q);
66
+ async function run(){
67
+ const session=await handoffSession(q),{target,rpc}=session,fencingSupported=gitee?session.giteeFence:token?session.tokenPlanFence:session.fencingSupported,modelBinding=token?session.tokenPlanBinding:session.modelBinding;
68
+ if(a.action.startsWith('file_transfer_')){if(!session.files)fail('HANDOFF_FILES_UNSUPPORTED');if(a.action.startsWith('file_transfer_queue')&&!session.filesQueueReview)fail('HANDOFF_FILES_QUEUE_UNSUPPORTED');if(a.action.startsWith('file_transfer_migration')&&!session.filesMigration)fail('HANDOFF_FILES_MIGRATION_UNSUPPORTED');if(a.targetHash!==undefined&&hash(target)!==a.targetHash)fail('HANDOFF_TARGET_CHANGED');const {action,targetHash,...args}=a;return {target,value:await rpc(action,args)};}
69
+ if(a.action.startsWith('task_pair_')){if(!session.peerBinding)fail('HANDOFF_PAIR_UNSUPPORTED');if(a.targetHash!==undefined&&hash(target)!==a.targetHash)fail('HANDOFF_TARGET_CHANGED');const {action,targetHash,...args}=a;return {target,value:await rpc(action,args)};}
70
+ if(a.action.startsWith('task_runtime_')){if(!session.taskRuntime)fail('HANDOFF_TASK_RUNTIME_UNSUPPORTED');if(a.targetHash!==undefined&&hash(target)!==a.targetHash)fail('HANDOFF_TARGET_CHANGED');const {action,targetHash,...args}=a;return {target,value:await rpc(action,args)};}
71
+ if(gitee&&!session.giteeReceipt)fail('HANDOFF_REPOSITORY_UNSUPPORTED');
72
+ if(a.action==='repository_inspect'){if(!session.repositoryCheck)fail('HANDOFF_REPOSITORY_UNSUPPORTED');return {target,value:await rpc('repository_inspect',{url:a.url,branch:a.branch,authentication:a.authentication})};}
73
+ if(token&&!session.tokenPlanReceipt)fail('HANDOFF_TOKEN_UNSUPPORTED');if(a.targetHash!==undefined&&hash(target)!==a.targetHash)fail('HANDOFF_TARGET_CHANGED');
74
+ if(a.action.startsWith('repository_registry_')){if(!session.repositoryRegistry)fail('HANDOFF_REPOSITORY_UNSUPPORTED');const {action,targetHash,...args}=a;return {target,value:await rpc(action,args)};}
75
+ if(a.action==='web_access')return {target,value:session.webAccess};
76
+ if(a.action.startsWith('notification_defaults_')){if(!session.notificationDiscovery)fail('HANDOFF_IM_UNSUPPORTED');const {action,...args}=a;return {target,value:await rpc(action,args)};}
77
+ if(a.action==='im_inventory'){if(!session.imInventory)fail('HANDOFF_IM_UNSUPPORTED');return {target,value:await rpc('im_inventory',{})};}
78
+ if(a.clarification!==undefined&&!(token?session.tokenModelClarification:session.modelClarification))fail('HANDOFF_MODEL_CLARIFICATION_UNSUPPORTED');
79
+ if(a.action.startsWith('model_probe_')){if(!(token?session.tokenModelProbe:session.modelProbe))fail('HANDOFF_MODEL_PROBE_UNSUPPORTED');const {action,targetHash,...args}=a;return {target,value:await rpc(raw.action,args)};}
80
+ if(model){
81
+ if(!modelBinding)fail('HANDOFF_MODEL_UNAVAILABLE');
82
+ const args=a.action==='model_preview'?{enabled:a.enabled}:a.action==='model_apply'?{id:a.id,fingerprint:a.fingerprint,confirm:true}:a.action==='model_resolve'?{query:a.query,...(a.clarification!==undefined?{clarification:a.clarification}:{})}:{};
83
+ return {target,value:await rpc(raw.action,args)};
84
+ }
85
+ if(a.action==='inspect'){
86
+ const s=await rpc('secret_status',{}),row=s?.slots?.find(x=>x.slot===slot);if(!row||!Number.isSafeInteger(row.revision)||row.revision<0||typeof row.configured!=='boolean'||row.writable!==true)fail('HANDOFF_SLOT_REVIEW');
87
+ return {target,slot,revision:row.revision,configured:row.configured,fencingSupported};
88
+ }
89
+ const request={slot,operation:a.operation,expectedRevision:a.expectedRevision};
90
+ if(a.action==='fence'){if(!fencingSupported)fail('HANDOFF_FENCE_UNSUPPORTED');await rpc('secret_fence',{...request,confirm:true});}
91
+ if(a.action==='put')await rpc('secret_put',{...request,secret:a.secret,confirm:true});
92
+ const r=await rpc('secret_receipt',request);
93
+ if(r?.slot!==slot||!Number.isSafeInteger(r.revision)||r.revision<0||typeof r.configured!=='boolean'||typeof r.operationMatched!=='boolean')fail('HANDOFF_RECEIPT_REVIEW');
94
+ return {target,slot,revision:r.revision,configured:r.configured,operationMatched:r.operationMatched,fencingSupported};
95
+ }
96
+ return ['file_transfer_queueReviewApply','file_transfer_queueReviewClose','file_transfer_migrationRecover','file_transfer_apply','file_transfer_fence','put','fence','model_probe_start','model_apply','repository_registry_apply','repository_registry_fence','task_runtime_apply','task_runtime_fence','task_pair_apply','task_pair_fence','task_pair_forward'].includes(a.action)?runtimeLock(q,run):run();
97
+ }
98
+ export async function handoffCLI(){try{const value=await handoffControl(await runtimeReadInput(196608));console.log(JSON.stringify({ok:true,value}));}catch(e){console.log(JSON.stringify({ok:false,error:/^ONBOARDING_(?:CLOUD|MODEL|REPOSITORY|TASK_RUNTIME|FILES)_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_CLOUD_HANDOFF_FAILED'}));}}
@@ -0,0 +1,112 @@
1
+ // Durable metadata only: no Key, Key hash, authenticated URL or SSH proof in this ledger.
2
+ import {randomUUID} from 'node:crypto';
3
+ import {credentialKey} from '@deepseek-ai/dsh-credentials';
4
+ import {digest} from './onboarding-ssh.js';
5
+ const OWNER='dsh-dual-host-onboarding';
6
+ const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===keys.sort().join();
7
+ 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);
8
+ const rev=x=>Number.isSafeInteger(x)&&x>=0&&x<Number.MAX_SAFE_INTEGER;
9
+ const hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
10
+ const fail=x=>{throw Error('ONBOARDING_HANDOFF_'+x);};
11
+ export function handoffTarget(v){
12
+ if(!exact(v,['operationId','installationId','runtimeId','manifestHash','root','role','hostVersion'])||![v.operationId,v.installationId,v.runtimeId].every(uuid)||!hex(v.manifestHash)||typeof v.root!=='string'||!v.root.startsWith('/')||v.root.length>2048||/[\x00-\x1f\x7f]/.test(v.root)||v.role!=='cloud'||typeof v.hostVersion!=='string'||v.hostVersion.length>64)fail('TARGET_REVIEW');
13
+ return v;
14
+ }
15
+ function parse(r,owner=OWNER){
16
+ if(!r)return null;const p=r.payload;
17
+ if(r.kind!=='grant'||!exact(p,['owner','schema','id','revision','planHash','sourceRevision','destinationRevision','target','phase','createdAt','updatedAt','error',...(p?.recovery?['recovery']:[])])||p.owner!==owner||p.schema!==1||!uuid(p.id)||!rev(p.revision)||!p.revision||!hex(p.planHash)||!rev(p.sourceRevision)||!p.sourceRevision||!rev(p.destinationRevision)||!['sending','delivered','needs_review','recovering','closed'].includes(p.phase)||!Number.isSafeInteger(p.createdAt)||!Number.isSafeInteger(p.updatedAt)||p.error!==null&&!/^ONBOARDING_[A-Z_]+$/.test(p.error))fail('LEDGER_REVIEW');
18
+ if(p.recovery&&(!exact(p.recovery,['id','planHash','expectedRevision','mode','createdAt'])||!uuid(p.recovery.id)||!hex(p.recovery.planHash)||!rev(p.recovery.expectedRevision)||p.recovery.expectedRevision<p.destinationRevision||!['fence','already_advanced'].includes(p.recovery.mode)||!Number.isSafeInteger(p.recovery.createdAt)))fail('LEDGER_REVIEW');
19
+ if(['recovering','closed'].includes(p.phase)&&!p.recovery)fail('LEDGER_REVIEW');
20
+ handoffTarget(p.target);return p;
21
+ }
22
+ function remoteShape(v,keys){return exact(v,[...keys,...(v?.fencingSupported!==undefined?['fencingSupported']:[])])&&(v.fencingSupported===undefined||typeof v.fencingSupported==='boolean');}
23
+ function receipt(v,target,expected,slot='deepseek-local'){
24
+ if(!remoteShape(v,['target','slot','revision','configured','operationMatched'])||digest(handoffTarget(v.target))!==digest(target)||v.slot!==slot||!rev(v.revision)||v.revision<expected||typeof v.configured!=='boolean'||typeof v.operationMatched!=='boolean'||v.operationMatched&&v.revision!==expected+1)fail('RECEIPT_REVIEW');
25
+ return v.operationMatched&&v.revision===expected+1&&v.configured;
26
+ }
27
+ function view(p,sourceSlot='deepseek-cloud',destinationSlot='deepseek-local'){return p?{id:p.id,state:p.phase,revision:p.revision,target:p.target,sourceSlot,sourceRevision:p.sourceRevision,destinationSlot,destinationRevision:p.destinationRevision,observedAt:p.updatedAt,freshness:'cached',recovery:p.recovery??null,error:p.error,enablesModel:false,verifiesModel:false,notAuthorization:true}:{state:'not_started',enablesModel:false,verifiesModel:false,notAuthorization:true};}
28
+ export function createOnboardingHandoff({state,credentials,remote:transport,enabled,now=Date.now,service='deepseek'}){
29
+ if(!['deepseek','token-plan','gitee'].includes(service))fail('SERVICE_REVIEW');
30
+ const token=service==='token-plan',gitee=service==='gitee',sourceSlot=gitee?'gitee-cloud':token?'token-plan-cloud':'deepseek-cloud',destinationSlot=gitee?'gitee':token?'token-plan':'deepseek-local';
31
+ const KEY=credentialKey('dsh-task-gateway',gitee?'onboarding-gitee-cloud-handoff-v1':token?'onboarding-token-cloud-handoff-v1':'onboarding-cloud-handoff-v1'),owner=gitee?OWNER+'/gitee':token?OWNER+'/token-plan':OWNER;
32
+ const parseRecord=r=>parse(r,owner),snapshot=p=>view(p,sourceSlot,destinationSlot),checkedReceipt=(v,t,e)=>receipt(v,t,e,destinationSlot);
33
+ const remote=(action,args)=>transport((gitee?'gitee_':token?'token_':'')+action,args);
34
+ let plan=null,recoveryPlan=null,busy=false;
35
+ const available=()=>enabled()&&state.available();
36
+ const ready=()=>{if(!available())fail('UNAVAILABLE');};
37
+ const read=async()=>parseRecord(await credentials().readRecord(KEY));
38
+ async function locked(fn){ready();if(busy)fail('BUSY');busy=true;try{return await fn();}finally{busy=false;}}
39
+ async function settle(p,phase,error){
40
+ let value;await credentials().modifyRecord(KEY,old=>{const c=parseRecord(old);if(c?.id!==p.id)fail('LEDGER_CONFLICT');if(c.revision!==p.revision){value=c;return undefined;}value={...c,revision:c.revision+1,phase,error,updatedAt:now()};return {kind:'grant',payload:value};});return snapshot(value);
41
+ }
42
+ async function query(p){
43
+ const r=await remote('receipt',{operation:p.id,expectedRevision:p.destinationRevision,targetHash:digest(p.target)});
44
+ checkedReceipt(r,p.target,p.destinationRevision);return r;
45
+ }
46
+ async function reconcile(p){
47
+ try{
48
+ const r=await query(p),delivered=checkedReceipt(r,p.target,p.destinationRevision);
49
+ const closed=!!p.recovery&&!delivered&&r.revision>p.destinationRevision;
50
+ const value=await settle(p,delivered?'delivered':closed?'closed':'needs_review',delivered||closed?null:'ONBOARDING_HANDOFF_NOT_CONFIRMED');
51
+ return {...value,freshness:'remote_checked',checkedAt:now(),currentDestinationRevision:r.revision};
52
+ }catch{return {...await settle(p,'needs_review','ONBOARDING_HANDOFF_STATUS_UNKNOWN'),freshness:'check_failed',checkedAt:now()};}
53
+ }
54
+ async function status(a){
55
+ if(!exact(a,['refresh'])||typeof a.refresh!=='boolean')fail('ARGUMENTS');ready();
56
+ if(!a.refresh)return snapshot(await read());
57
+ return locked(async()=>{const p=await read();if(!p||p.phase==='closed')return snapshot(p);return reconcile(p);});
58
+ }
59
+ // Closing is a distinct user decision. A trusted revision greater than the
60
+ // old CAS fences a late send. If unchanged, explicitly advance it WITHOUT
61
+ // changing its value. Missing receipts never authorize a resend or deletion.
62
+ async function recoveryPreview(a){
63
+ if(!exact(a,[]))fail('ARGUMENTS');return locked(async()=>{
64
+ recoveryPlan=null;const p=await read();if(!p||!['sending','needs_review'].includes(p.phase))fail('RECOVERY_NOT_READY');
65
+ const r=await query(p);if(checkedReceipt(r,p.target,p.destinationRevision))fail('ALREADY_DELIVERED');
66
+ const mode=r.revision>p.destinationRevision?'already_advanced':'fence';
67
+ if(mode==='fence'&&!r.fencingSupported)fail('FENCE_UNSUPPORTED');
68
+ const body={id:randomUUID(),handoffId:p.id,ledgerRevision:p.revision,target:p.target,expectedRevision:r.revision,mode,preservesConfiguredValue:r.configured,expiresAt:now()+300000};
69
+ recoveryPlan={...body,fingerprint:digest(body)};return {...recoveryPlan,sendsKey:false,removesKey:false,requiresExplicitConfirmation:true};
70
+ });
71
+ }
72
+ async function recoveryApply(a){
73
+ if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
74
+ return locked(async()=>{
75
+ const old=await read();if(old?.recovery?.id===a.id&&old.recovery.planHash===a.fingerprint)return {...snapshot(old),notResent:true};
76
+ const p=recoveryPlan;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');
77
+ if(!old||old.id!==p.handoffId||old.revision!==p.ledgerRevision||!['sending','needs_review'].includes(old.phase))fail('LEDGER_CONFLICT');
78
+ const r=await query(old);if(checkedReceipt(r,old.target,old.destinationRevision))fail('ALREADY_DELIVERED');
79
+ if(r.revision!==p.expectedRevision||r.configured!==p.preservesConfiguredValue||p.mode==='fence'&&!r.fencingSupported)fail('RECOVERY_CHANGED');
80
+ const record={...old,revision:old.revision+1,phase:'recovering',updatedAt:now(),error:null,recovery:{id:p.id,planHash:p.fingerprint,expectedRevision:p.expectedRevision,mode:p.mode,createdAt:now()}};
81
+ await credentials().modifyRecord(KEY,previous=>{const c=parseRecord(previous);if(c?.id!==old.id||c.revision!==old.revision)fail('LEDGER_CONFLICT');return {kind:'grant',payload:record};});recoveryPlan=null;
82
+ if(p.mode==='fence'){
83
+ try{const f=await remote('fence',{operation:p.id,expectedRevision:p.expectedRevision,targetHash:digest(p.target)});checkedReceipt(f,p.target,p.expectedRevision);}
84
+ catch{/* Query the ORIGINAL send: a racing send may have won; never repeat a fence. */}
85
+ }
86
+ return reconcile(record);
87
+ });
88
+ }
89
+ async function preview(a){
90
+ if(!exact(a,[]))fail('ARGUMENTS');return locked(async()=>{
91
+ plan=null;const p=await read();if(p&&!['delivered','closed'].includes(p.phase))fail('RECOVERY_REQUIRED');
92
+ const secret=await state.readManagedSecret(sourceSlot);if(!secret.value)fail('SOURCE_REQUIRED');
93
+ const r=await remote('inspect',{});handoffTarget(r?.target);
94
+ if(!remoteShape(r,['target','slot','revision','configured'])||r.slot!==destinationSlot||!rev(r.revision)||typeof r.configured!=='boolean')fail('TARGET_REVIEW');
95
+ const body={id:randomUUID(),sourceRevision:secret.revision,destinationRevision:r.revision,target:r.target,replacesOwnCredential:r.configured,priorRevision:p?.revision??0,priorId:p?.id??null,expiresAt:now()+300000};plan={...body,fingerprint:digest(body)};
96
+ return {...plan,sourceSlot,destinationSlot,enablesModel:false,verifiesModel:false,requiresExplicitConfirmation:true};
97
+ });
98
+ }
99
+ async function apply(a){
100
+ if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
101
+ return locked(async()=>{
102
+ const existing=await read();if(existing?.id===a.id&&existing.planHash===a.fingerprint)return {...snapshot(existing),notResent:true};
103
+ const p=plan;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');
104
+ const secret=await state.readManagedSecret(sourceSlot);if(!secret.value||secret.revision!==p.sourceRevision)fail('SOURCE_CHANGED');
105
+ const record={owner,schema:1,id:p.id,revision:1,planHash:p.fingerprint,sourceRevision:p.sourceRevision,destinationRevision:p.destinationRevision,target:p.target,phase:'sending',createdAt:now(),updatedAt:now(),error:null};
106
+ await credentials().modifyRecord(KEY,old=>{const current=parseRecord(old);if((current?.id??null)!==p.priorId||(current?.revision??0)!==p.priorRevision||current&&!['delivered','closed'].includes(current.phase))fail('LEDGER_CONFLICT');return {kind:'grant',payload:record};});plan=null;
107
+ try{const r=await remote('put',{operation:p.id,expectedRevision:p.destinationRevision,targetHash:digest(p.target),secret:secret.value});const ok=checkedReceipt(r,p.target,p.destinationRevision);return settle(record,ok?'delivered':'needs_review',ok?null:'ONBOARDING_HANDOFF_NOT_CONFIRMED');}
108
+ catch{return settle(record,'needs_review','ONBOARDING_HANDOFF_OUTCOME_UNKNOWN');}
109
+ });
110
+ }
111
+ return {available,status,preview,apply,recoveryPreview,recoveryApply};
112
+ }
@@ -0,0 +1,44 @@
1
+ // Read-only snapshot, NOT an ingress barrier. Only the original managed Host
2
+ // and its public plugin RPC are consulted. Never follow/activate a session.
3
+ import path from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ const count=n=>Number.isSafeInteger(n)&&n>=0;
6
+ const keys=(v,k)=>v&&Object.keys(v).sort().join()===k.slice().sort().join();
7
+ export async function observeRuntimeHost(api,q,j,options={}){
8
+ const {regular,runtimeAlive,runtimeSource,checkAncestors,fail}=api;
9
+ const base=path.join(q.root,'runtime'),control=path.join(q.root,'.control/runtime',...(j.restart?['restarts',j.restart.id]:[]));
10
+ if(j.state!=='host_ready'||j.nativeReceipt?.ok!==true||j.nativeReceipt.pid!==j.host?.pid||j.nativeReceipt.nonce!==j.nativeNonce||!await runtimeAlive(j.host))fail('RUNTIME_HOST_OBSERVATION_REQUIRED');
11
+ if(j.nativeReceipt.dshHome!==path.join(base,'native-home/dsh')||j.nativeReceipt.agentsHome!==path.join(base,'native-home/agents'))fail('RUNTIME_HOST_IDENTITY_REVIEW');
12
+ const source=await runtimeSource(q);
13
+ if(api.runtimeVerifyPlugin)await api.runtimeVerifyPlugin(q,j);
14
+ else for(const f of source.owner.manifest){const p=path.join(base,f.path);await checkAncestors(path.dirname(p));const r=await regular(p);if(!r||r.sha256!==f.sha256||r.identity.mode!==f.mode||r.identity.uid!==process.getuid())fail('RUNTIME_HOST_SOURCE_CHANGED');}
15
+ await checkAncestors(control);const r=await regular(path.join(control,'native-access.json'),16384);
16
+ if(!r||r.identity.mode!==0o600||r.identity.uid!==process.getuid())fail('RUNTIME_HOST_ACCESS_REVIEW');
17
+ let url;try{url=new URL(JSON.parse(r.data).url);}catch{fail('RUNTIME_HOST_ACCESS_REVIEW');}
18
+ if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.username||url.password||url.pathname!=='/'||url.hash||url.origin!==j.nativeReceipt.origin||[...url.searchParams.keys()].join()!=='token'||!url.searchParams.get('token'))fail('RUNTIME_HOST_ACCESS_REVIEW');
19
+ const login=new URL('/connect',url.origin);login.searchParams.set('token',url.searchParams.get('token'));login.searchParams.set('interactions','none');
20
+ const response=await fetch(login,{redirect:'manual',signal:AbortSignal.timeout(3000)}),cookie=response.headers.get('set-cookie')?.split(';')[0];
21
+ if(response.status!==302||!cookie||/[\r\n]/.test(cookie))fail('RUNTIME_HOST_AUTH_FAILED');
22
+ async function rpc(method){
23
+ const rpcId=randomUUID(),res=await fetch(new URL('/api/task-onboarding/control',url.origin),{method:'POST',redirect:'manual',headers:{'content-type':'application/json',cookie},body:JSON.stringify({type:'client-request',rpcId,method:'task-onboarding/control',payload:{method,args:{}}}),signal:AbortSignal.timeout(3000)});
24
+ if(!res.ok)fail('RUNTIME_HOST_RESPONSE_REVIEW');let size=0;const chunks=[];for await(const c of res.body){size+=c.length;if(size>262144)fail('RUNTIME_HOST_RESPONSE_REVIEW');chunks.push(c);}
25
+ let v;try{v=JSON.parse(Buffer.concat(chunks));}catch{fail('RUNTIME_HOST_RESPONSE_REVIEW');}
26
+ if(v?.type!=='server-response'||v.rpcId!==rpcId||v.result?.ok!==true)fail('RUNTIME_HOST_RESPONSE_REVIEW');return v.result.value;
27
+ }
28
+ const joint=await rpc('coordinated_hold_status'),own=await rpc('onboarding_hold_status'),agents=await rpc('agent_hold_status'),im=j.optionalIm?await rpc('im_maintenance_status'):null;
29
+ if(joint?.contract!==1||joint.scope!=='coordinated_components_only'||own?.contract!==1||own.scope!=='own_onboarding_only'||agents?.contract!==1||agents.scope!=='native_agents_only'||!keys(agents.counts,['agents','running','unsupported','held','pendingNextTurn','pendingNextStep','inboxUnknown'])||!keys(own.counts,['rpc','startup','model_attempt','workbench_http','workbench_websocket']))fail('RUNTIME_HOST_RESPONSE_REVIEW');
30
+ const rows=joint.components,gateway=rows?.gateway;
31
+ if(rows?.onboarding?.instanceId!==own.instanceId||rows?.agents?.instanceId!==agents.instanceId||typeof own.instanceId!=='string'||typeof agents.instanceId!=='string'||!gateway||!Object.values(own.counts).every(count)||!Object.values(agents.counts).every(count))fail('RUNTIME_HOST_RESPONSE_REVIEW');
32
+ if(gateway.state!=='not_configured'&&(!gateway.counts||!Object.keys(gateway.counts).length||!Object.values(gateway.counts).every(count)||typeof gateway.instanceId!=='string'))fail('RUNTIME_HOST_RESPONSE_REVIEW');
33
+ if(im&&(im.contract!==1||im.inventoryState!=='observed'||typeof im.pending!=='boolean'||typeof im.operationInFlight!=='boolean'||typeof im.instanceId!=='string'))fail('RUNTIME_HOST_RESPONSE_REVIEW');
34
+ const reasons=[];
35
+ if(!['open','held'].includes(joint.state)||!['open','held'].includes(own.state)||!['open','held'].includes(agents.state)||!['not_configured','open','held'].includes(gateway.state))reasons.push('component_unavailable');
36
+ if(Object.values(own.counts).some(n=>n!==0)||gateway.counts&&Object.values(gateway.counts).some(n=>n!==0))reasons.push('own_work_active');
37
+ if(agents.counts.running||agents.counts.unsupported||agents.counts.inboxUnknown||agents.counts.pendingNextTurn||agents.counts.pendingNextStep||agents.inboxState!=='empty')reasons.push('native_work_active_or_unknown');
38
+ if(im&&(im.pending||im.operationInFlight))reasons.push('im_maintenance_pending');
39
+ const installation=options.installation===true?await rpc('install_status'):null;
40
+ const description=options.versionIdentity===true?await rpc('describe'):null;
41
+ if(options.versionIdentity===true&&(typeof description?.pluginVersion!=='string'||description.pluginVersion.length>99||!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(description.pluginVersion)))fail('RUNTIME_HOST_VERSION_REVIEW');
42
+ if(!await runtimeAlive(j.host))fail('RUNTIME_HOST_IDENTITY_REVIEW');
43
+ return {contract:1,nativeNonce:j.nativeNonce,instances:{onboarding:own.instanceId,agents:agents.instanceId,gateway:gateway.instanceId??null,im:im?.instanceId??null},idle:reasons.length===0,reasons,observedAt:Date.now(),ingressFrozen:false,imInFlightVerified:false,...(options.installation===true?{installation}:{} ),...(options.versionIdentity===true?{pluginVersion:description.pluginVersion}:{})};
44
+ }