@platless/axom-cli 0.5.9 → 0.6.52

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 (258) hide show
  1. package/README.md +25 -6
  2. package/dist/axom-patch/cli/README.md +129 -12
  3. package/dist/axom-patch/cli/account-limits/generate.py +15 -12
  4. package/dist/axom-patch/cli/account-limits/kimi-proxy.mjs +20 -3
  5. package/dist/axom-patch/cli/claude-account-limits.json +9 -9
  6. package/dist/axom-patch/cli/claude-replay-lifecycle.json +16 -0
  7. package/dist/axom-patch/cli/codex-account-limits.json +11 -11
  8. package/dist/axom-patch/cli/codex-terminal-output.json +16 -0
  9. package/dist/axom-patch/cli/commandcode-account-limits.json +9 -9
  10. package/dist/axom-patch/cli/kimi-quota.mjs +12 -0
  11. package/dist/axom-patch/cli/kimi-subagents.mjs +173 -0
  12. package/dist/axom-patch/cli/nightly-task.md +55 -13
  13. package/dist/axom-patch/cli/probes/claude-replay-lifecycle.mjs +31 -0
  14. package/dist/axom-patch/cli/probes/codex-terminal-output.mjs +33 -0
  15. package/dist/axom-patch/cli/probes/kimi-subagent-subwork.mjs +82 -0
  16. package/dist/axom-patch/cli/probes/zcode-env-account.mjs +81 -0
  17. package/dist/axom-patch/cli/probes/zcode-subagent-subwork.mjs +7 -0
  18. package/dist/axom-patch/cli/qoder/dist/axom-acp-compat.mjs +1687 -0
  19. package/dist/axom-patch/cli/qoder/releases/1.1.75.json +277 -0
  20. package/dist/axom-patch/cli/qoder-background-terminal.md +13 -6
  21. package/dist/axom-patch/cli/qoder-foreground-output.md +14 -8
  22. package/dist/axom-patch/cli/qoder-native-acp.json +227 -0
  23. package/dist/axom-patch/cli/qoder-steering.md +20 -25
  24. package/dist/axom-patch/cli/qoder-subagent-subwork.md +17 -68
  25. package/dist/axom-patch/cli/runtime.json +19 -19
  26. package/dist/axom-patch/cli/zcode/env-account.mjs +13 -0
  27. package/dist/axom-patch/cli/zcode/generate-env-account.py +52 -0
  28. package/dist/axom-patch/cli/zcode-account-limits.json +10 -11
  29. package/dist/axom-patch/cli/zcode-env-account.json +58 -0
  30. package/dist/axom-patch/cli/zcode-models.json +9 -10
  31. package/dist/axom-patch/cli/zcode-subagent-subwork.json +10 -11
  32. package/dist/cli.js +11 -45
  33. package/dist/commands/auth.js +4 -1
  34. package/dist/commands/knowledge.js +47 -0
  35. package/dist/commands/update.js +126 -3
  36. package/dist/commands/workstation.js +101 -164
  37. package/dist/commands/workstationRegistrations.js +116 -0
  38. package/dist/credentialBroker.js +13 -2
  39. package/dist/credentials.js +16 -0
  40. package/dist/install/claude/commands.js +15 -15
  41. package/dist/keepers/terminal/keeper.mjs +1089 -673
  42. package/dist/keepers/terminal/manifest.json +4 -4
  43. package/dist/mcp.js +1 -1
  44. package/dist/native/darwin-x64/axom-quic +0 -0
  45. package/dist/workstation/acp/acpAgents.js +113 -102
  46. package/dist/workstation/acp/acpClient.js +26 -0
  47. package/dist/workstation/acp/builds/install/npm.js +99 -10
  48. package/dist/workstation/acp/initializeResponse.js +6 -1
  49. package/dist/workstation/acp/managedPatches.js +189 -25
  50. package/dist/workstation/acp/managedRuntime.js +314 -0
  51. package/dist/workstation/acp/outbox.js +12 -5
  52. package/dist/workstation/acp/patchAssets.js +40 -0
  53. package/dist/workstation/acp/permission.js +2 -2
  54. package/dist/workstation/acp/processor/checkpoint.js +26 -34
  55. package/dist/workstation/acp/processor/control.js +7 -80
  56. package/dist/workstation/acp/processor/jsonrpc.js +8 -0
  57. package/dist/workstation/acp/processor/runtime.js +5 -81
  58. package/dist/workstation/acp/processor/session.js +54 -82
  59. package/dist/workstation/acp/processor/state.js +7 -13
  60. package/dist/workstation/acp/processor/step.js +3 -20
  61. package/dist/workstation/acp/processor/test/fixtureLog.js +9 -16
  62. package/dist/workstation/acp/processor/transport/local.js +19 -3
  63. package/dist/workstation/acp/processor/updates.js +156 -105
  64. package/dist/workstation/acp/processorSession.js +20 -173
  65. package/dist/workstation/acp/registry/catalog.js +65 -39
  66. package/dist/workstation/acp/registry/launch.js +16 -1
  67. package/dist/workstation/acp/switching.js +0 -3
  68. package/dist/workstation/acp/test/fakeAgent.js +13 -0
  69. package/dist/workstation/acp/test/keeperWorld.js +32 -3
  70. package/dist/workstation/acp/test/raw/sources.js +16 -130
  71. package/dist/workstation/acp/test/realAdapter.js +1 -47
  72. package/dist/workstation/acp/test/scriptAgent.js +11 -3
  73. package/dist/workstation/agentFlow.js +1 -1
  74. package/dist/workstation/agentSessions.js +114 -166
  75. package/dist/workstation/channels/agent.js +9 -1
  76. package/dist/workstation/channels/computer.js +27 -4
  77. package/dist/workstation/channels/management.js +130 -15
  78. package/dist/workstation/channels/url.js +1 -1
  79. package/dist/workstation/config.js +33 -9
  80. package/dist/workstation/connection/encryptedChannel.js +4 -1
  81. package/dist/workstation/control/bindingStore.js +204 -0
  82. package/dist/workstation/control/commands.js +125 -0
  83. package/dist/workstation/control/daemonIdentity.js +143 -0
  84. package/dist/workstation/control/deviceCommands.js +191 -0
  85. package/dist/workstation/control/deviceProtocol.js +68 -0
  86. package/dist/workstation/control/enrollment.js +106 -0
  87. package/dist/workstation/control/inspect.js +71 -0
  88. package/dist/workstation/control/locks.js +110 -0
  89. package/dist/workstation/control/protocol.js +40 -0
  90. package/dist/workstation/control/restartGuard.js +46 -0
  91. package/dist/workstation/control/rootFormat.js +16 -0
  92. package/dist/workstation/control/runtimeClient.js +152 -0
  93. package/dist/workstation/control/runtimeHost.js +235 -0
  94. package/dist/workstation/control/serverIdentity.js +35 -0
  95. package/dist/workstation/control/updateTransition.js +91 -0
  96. package/dist/workstation/daemon.js +266 -264
  97. package/dist/workstation/daemonctl.js +226 -25
  98. package/dist/workstation/desktopControl/audio.js +99 -0
  99. package/dist/workstation/desktopControl/automationDevice.js +219 -0
  100. package/dist/workstation/desktopControl/automationJson.js +74 -0
  101. package/dist/workstation/desktopControl/automationLocalState.js +23 -0
  102. package/dist/workstation/desktopControl/automationProtocol.js +253 -0
  103. package/dist/workstation/desktopControl/automationSchema.generated.js +1 -0
  104. package/dist/workstation/desktopControl/automationSession.js +81 -0
  105. package/dist/workstation/desktopControl/automationTransport.js +138 -0
  106. package/dist/workstation/desktopControl/capabilities.js +93 -0
  107. package/dist/workstation/desktopControl/captureModes.js +9 -0
  108. package/dist/workstation/desktopControl/captureTargetLabel.js +9 -0
  109. package/dist/workstation/desktopControl/deviceAdmission.js +229 -0
  110. package/dist/workstation/desktopControl/deviceOwnership.js +130 -0
  111. package/dist/workstation/desktopControl/deviceSockets.js +246 -0
  112. package/dist/workstation/desktopControl/helperProcess.js +602 -0
  113. package/dist/workstation/desktopControl/hostGrant.js +65 -0
  114. package/dist/workstation/desktopControl/lobby.js +131 -0
  115. package/dist/workstation/desktopControl/macProvider.js +156 -0
  116. package/dist/workstation/desktopControl/media.js +331 -0
  117. package/dist/workstation/desktopControl/nativeDeviceAdmission.js +207 -0
  118. package/dist/workstation/desktopControl/nativeProvider.js +1044 -0
  119. package/dist/workstation/desktopControl/networkEvidence.js +43 -0
  120. package/dist/workstation/desktopControl/overview.js +58 -0
  121. package/dist/workstation/desktopControl/ownershipProtocol.js +31 -0
  122. package/dist/workstation/desktopControl/protocol.js +311 -0
  123. package/dist/workstation/desktopControl/provider.js +1 -0
  124. package/dist/workstation/desktopControl/quicMedia.js +240 -0
  125. package/dist/workstation/desktopControl/rateController.js +226 -0
  126. package/dist/workstation/desktopControl/supervisor.js +1774 -0
  127. package/dist/workstation/desktopControl/transport.js +27 -0
  128. package/dist/workstation/desktopControl/wallpaper.js +98 -0
  129. package/dist/workstation/exec/policy.js +5 -0
  130. package/dist/workstation/files/client.js +10 -1
  131. package/dist/workstation/files/credentials.js +142 -0
  132. package/dist/workstation/files/host.js +9 -2
  133. package/dist/workstation/files/text.js +42 -8
  134. package/dist/workstation/journal.js +5 -2
  135. package/dist/workstation/keepers/acp/client.js +38 -2
  136. package/dist/workstation/keepers/kit/buildVersion.js +35 -11
  137. package/dist/workstation/keepers/kit/bundle.js +21 -17
  138. package/dist/workstation/keepers/kit/client.js +2 -2
  139. package/dist/workstation/keepers/kit/launcher.js +123 -7
  140. package/dist/workstation/keepers/kit/paths.js +2 -1
  141. package/dist/workstation/keepers/legacy.js +16 -2
  142. package/dist/workstation/keepers/policy.js +5 -34
  143. package/dist/workstation/keepers/terminal/client.js +115 -23
  144. package/dist/workstation/keepers/terminal/exec.js +6 -3
  145. package/dist/workstation/keepers/terminal/frames.js +73 -0
  146. package/dist/workstation/keepers/terminal/generations.js +5 -8
  147. package/dist/workstation/keepers/terminal/gridProtocol.js +16 -0
  148. package/dist/workstation/keepers/terminal/input.js +146 -0
  149. package/dist/workstation/keepers/terminal/keeper.js +22 -8
  150. package/dist/workstation/keepers/terminal/main.js +1 -1
  151. package/dist/workstation/keepers/terminal/metadata.js +138 -0
  152. package/dist/workstation/keepers/terminal/protocol.js +4 -28
  153. package/dist/workstation/keepers/terminal/pty.js +1 -330
  154. package/dist/workstation/keepers/terminal/screen.js +246 -0
  155. package/dist/workstation/keepers/terminal/sessions.js +526 -0
  156. package/dist/workstation/managedInstall.js +57 -0
  157. package/dist/workstation/oauth/deviceAuthorization.js +31 -17
  158. package/dist/workstation/protocol/agent.js +2 -15
  159. package/dist/workstation/protocol/management.js +113 -5
  160. package/dist/workstation/protocol/runtimeDiagnostics.js +15 -0
  161. package/dist/workstation/rd/artifact.js +120 -0
  162. package/dist/workstation/rd/control.js +117 -0
  163. package/dist/workstation/rd/display.js +29 -0
  164. package/dist/workstation/rd/host.js +213 -0
  165. package/dist/workstation/rd/migrationReadiness.js +46 -0
  166. package/dist/workstation/rd/provider.js +256 -0
  167. package/dist/workstation/rd/sessions.js +391 -0
  168. package/dist/workstation/rd/state.js +57 -0
  169. package/dist/workstation/rd/update.js +168 -0
  170. package/dist/workstation/rd/upkeep.js +80 -0
  171. package/dist/workstation/register.js +27 -37
  172. package/dist/workstation/registrations/enrollment.js +250 -0
  173. package/dist/workstation/registrations/enrollmentPending.js +361 -0
  174. package/dist/workstation/registrations/migration.js +356 -0
  175. package/dist/workstation/registrations/model.js +34 -0
  176. package/dist/workstation/registrations/removal.js +222 -0
  177. package/dist/workstation/registrations/store.js +737 -0
  178. package/dist/workstation/runtime/desktopBinding.js +20 -0
  179. package/dist/workstation/runtime/deviceDesktop.js +193 -0
  180. package/dist/workstation/runtime/deviceRuntime.js +568 -0
  181. package/dist/workstation/runtime/deviceServices.js +117 -0
  182. package/dist/workstation/runtime/events.js +20 -0
  183. package/dist/workstation/runtime/ownership.js +100 -0
  184. package/dist/workstation/runtime/registrationRuntime.js +575 -0
  185. package/dist/workstation/runtime/remoteDesktopAdapter.js +186 -0
  186. package/dist/workstation/runtime/removalActivity.js +184 -0
  187. package/dist/workstation/service/installer.js +197 -14
  188. package/dist/workstation/service/launchd.js +2 -0
  189. package/dist/workstation/service/systemd.js +1 -0
  190. package/dist/workstation/storageMetrics.js +118 -0
  191. package/dist/workstation/systemMetrics.js +47 -92
  192. package/dist/workstation/toolchain.js +94 -0
  193. package/dist/workstation/tools/browser.js +28 -4
  194. package/dist/workstation/tools/client.js +8 -27
  195. package/dist/workstation/tools/info.js +6 -13
  196. package/dist/workstation/tools/terminalRouter.js +17 -172
  197. package/dist/workstation/tools/validation.js +55 -1
  198. package/dist/workstation/update/archiveEvidence.js +206 -0
  199. package/dist/workstation/update/artifact.js +2 -1
  200. package/dist/workstation/update/coordinator.js +34 -13
  201. package/dist/workstation/update/deviceCompatibility.js +119 -0
  202. package/dist/workstation/update/deviceCoordinator.js +369 -0
  203. package/dist/workstation/update/deviceHealth.js +104 -0
  204. package/dist/workstation/update/deviceHealthProtocol.js +26 -0
  205. package/dist/workstation/update/deviceRecoveryLifecycle.js +46 -0
  206. package/dist/workstation/update/deviceRollback.js +78 -0
  207. package/dist/workstation/update/globalInstall.js +186 -0
  208. package/dist/workstation/update/legacyBridge.js +414 -0
  209. package/dist/workstation/update/legacyOwner.js +39 -0
  210. package/dist/workstation/update/npmInstaller.js +51 -25
  211. package/dist/workstation/update/privateDurability.js +61 -0
  212. package/dist/workstation/update/rdRollback.js +145 -0
  213. package/dist/workstation/update/recoveryPlan.js +124 -0
  214. package/dist/workstation/update/runUpdate.js +10 -3
  215. package/dist/workstation/update/taskRegistry.js +161 -3
  216. package/dist/workstation/update/watchdog.js +29806 -333
  217. package/dist/workstation/update/watchdogProcess.js +72 -0
  218. package/package.json +11 -7
  219. package/skills/axom/SKILL.md +11 -11
  220. package/skills/axom-definition/SKILL.md +3 -3
  221. package/skills/axom-platform/SKILL.md +3 -3
  222. package/dist/axom-patch/cli/probes/qoder-steering.mjs +0 -89
  223. package/dist/axom-patch/cli/probes/qoder-subagent-origin.mjs +0 -61
  224. package/dist/axom-patch/cli/qoder-steering.json +0 -52
  225. package/dist/axom-patch/cli/qoder-subagent-origin.json +0 -73
  226. package/dist/commands/guide.js +0 -38
  227. package/dist/runtime-deps/qoder-sdk/package-lock.json +0 -1189
  228. package/dist/runtime-deps/qoder-sdk/package.json +0 -8
  229. package/dist/workstation/acp/delegationMcp.js +0 -24
  230. package/dist/workstation/acp/processor/sideChannel.js +0 -80
  231. package/dist/workstation/acp/qoderStartup.js +0 -45
  232. package/dist/workstation/acp/test/raw/qoderCaptures.js +0 -125
  233. package/dist/workstation/qoderAdapter/backgroundProcess.js +0 -118
  234. package/dist/workstation/qoderAdapter/backgroundTerminal.js +0 -193
  235. package/dist/workstation/qoderAdapter/backgroundTerminalFold.js +0 -372
  236. package/dist/workstation/qoderAdapter/callbackContext.js +0 -76
  237. package/dist/workstation/qoderAdapter/completedContinuation.js +0 -139
  238. package/dist/workstation/qoderAdapter/contract.js +0 -78
  239. package/dist/workstation/qoderAdapter/foregroundOutput.js +0 -36
  240. package/dist/workstation/qoderAdapter/history.js +0 -85
  241. package/dist/workstation/qoderAdapter/identityIndex.js +0 -191
  242. package/dist/workstation/qoderAdapter/inputQueue.js +0 -42
  243. package/dist/workstation/qoderAdapter/main.js +0 -95
  244. package/dist/workstation/qoderAdapter/mapper.js +0 -117
  245. package/dist/workstation/qoderAdapter/observerPlugin.js +0 -245
  246. package/dist/workstation/qoderAdapter/observerReceiver.js +0 -187
  247. package/dist/workstation/qoderAdapter/permissions.js +0 -61
  248. package/dist/workstation/qoderAdapter/profile.js +0 -93
  249. package/dist/workstation/qoderAdapter/sdkDriver.js +0 -48
  250. package/dist/workstation/qoderAdapter/sdkRuntime.js +0 -93
  251. package/dist/workstation/qoderAdapter/sdkRuntimeInstall.js +0 -145
  252. package/dist/workstation/qoderAdapter/session.js +0 -319
  253. package/dist/workstation/qoderAdapter/subagentMeta.js +0 -28
  254. package/dist/workstation/qoderAdapter/subwork.js +0 -85
  255. package/dist/workstation/qoderAdapter/taskControl.js +0 -38
  256. package/dist/workstation/qoderAdapter/taskLedger.js +0 -163
  257. package/dist/workstation/qoderAdapter/usage.js +0 -37
  258. /package/dist/workstation/{qoderAdapter/types.js → desktopControl/automationPreparation.js} +0 -0
@@ -0,0 +1,131 @@
1
+ import { z } from 'zod';
2
+ import { decodeDesktopSessionRequest, parseDesktopJson } from './protocol.js';
3
+ const identifier = z.string().regex(/^[a-f0-9]{32}$/);
4
+ const safe = z.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
5
+ const sourceAxis = z.number().int().min(2).max(4096);
6
+ const axis = sourceAxis.refine(value => value % 2 === 0);
7
+ const sourceModeSchema = z.strictObject({ width: sourceAxis, height: sourceAxis });
8
+ const modeSchema = z.strictObject({ width: axis, height: axis });
9
+ const viewportSchema = z.strictObject({ widthDp: z.number().finite().positive().max(16384),
10
+ heightDp: z.number().finite().positive().max(16384), deviceScale: z.number().finite().min(0.5).max(8),
11
+ orientation: z.enum(['landscape', 'portrait']) });
12
+ const resolutionSchema = z.discriminatedUnion('mode', [z.strictObject({ mode: z.literal('fit') }),
13
+ z.strictObject({ mode: z.literal('fixed'), width: axis, height: axis })]);
14
+ export const lobbyRequestSchema = z.strictObject({ requestId: identifier, revision: safe, viewport: viewportSchema,
15
+ resolution: resolutionSchema, dpi: z.number().int().min(64).max(384).nullable(),
16
+ transports: z.array(z.enum(['quic', 'wss'])).min(1).max(2).refine(values => new Set(values).size === values.length),
17
+ targetId: identifier.nullable().optional(), viewer: z.unknown().nullable().optional(),
18
+ backgroundVersion: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).nullish() });
19
+ const rangeSchema = z.strictObject({ minWidth: axis, minHeight: axis, maxWidth: axis, maxHeight: axis });
20
+ export const lobbyPlanSchema = z.strictObject({ lobbyId: identifier, planId: identifier, revision: safe, targetId: identifier,
21
+ desktop: sourceModeSchema, dpi: z.number().int().min(64).max(384).nullable(), resize: z.enum(['none', 'modes', 'dynamic']),
22
+ modes: z.array(modeSchema).max(32), resizeRange: rangeSchema.nullable(), dynamicDpi: z.boolean(), canAcquire: z.boolean(),
23
+ reason: z.string().max(128).nullable(), maxDpi: z.number().int().min(64).max(384).nullable(), captureViewport: z.boolean(),
24
+ sampling: modeSchema, targets: z.array(z.strictObject({ id: identifier, label: z.string().min(1).max(128),
25
+ kind: z.enum(['display', 'window']), available: z.boolean() })).max(128) });
26
+ export function decodeLobbyRequest(text) {
27
+ if (Buffer.byteLength(text) > 49152)
28
+ throw new Error('invalid_request');
29
+ const request = lobbyRequestSchema.parse(parseDesktopJson(text));
30
+ if (request.viewer != null)
31
+ decodeDesktopSessionRequest(JSON.stringify({ requestId: request.requestId,
32
+ displayId: request.targetId ?? request.requestId, viewer: request.viewer, viewport: request.viewport,
33
+ resolution: request.resolution, quality: 'auto', takeover: false }));
34
+ return request;
35
+ }
36
+ export const wallpaperAssetSchema = z.strictObject({ assetId: z.string().min(1).max(128), version: z.string().min(1).max(128),
37
+ originalWidth: z.number().int().min(1).max(65536), originalHeight: z.number().int().min(1).max(65536),
38
+ width: z.number().int().min(1).max(4096), height: z.number().int().min(1).max(4096),
39
+ placement: z.enum(['cover', 'fit', 'stretch', 'center', 'tile']).default('cover'),
40
+ coverage: z.enum(['full_asset', 'composited']).default('full_asset'), compatibleDesktop: sourceModeSchema.nullable().optional(),
41
+ anchorX: z.number().finite().min(0).max(1).default(0.5), anchorY: z.number().finite().min(0).max(1).default(0.5),
42
+ background: z.string().regex(/^#[a-fA-F0-9]{6}$/).default('#000000'),
43
+ intrinsicScale: z.number().finite().min(0.125).max(16).default(1),
44
+ mimeType: z.enum(['image/jpeg', 'image/webp']).default('image/jpeg'),
45
+ fidelity: z.enum(['exact', 'approximate']).default('exact'), colorSpace: z.literal('srgb').default('srgb')
46
+ }).refine(asset => asset.width * asset.height <= 8_388_608 && (asset.coverage !== 'composited' || asset.compatibleDesktop != null));
47
+ export function composeWallpaper(value, selected) {
48
+ const asset = wallpaperAssetSchema.parse(value);
49
+ const desktop = sourceModeSchema.parse(selected);
50
+ if (asset.coverage === 'composited' && (asset.compatibleDesktop?.width !== desktop.width || asset.compatibleDesktop.height !== desktop.height))
51
+ throw new Error('incompatible_wallpaper');
52
+ const full = { x: 0, y: 0, width: 1, height: 1 };
53
+ if (asset.coverage === 'composited' || asset.placement === 'stretch')
54
+ return { source: full, destination: full, version: 1 };
55
+ const imageWidth = asset.originalWidth * asset.intrinsicScale;
56
+ const imageHeight = asset.originalHeight * asset.intrinsicScale;
57
+ if (asset.placement === 'tile')
58
+ return { source: full, destination: full,
59
+ tileWidth: imageWidth / desktop.width, tileHeight: imageHeight / desktop.height, version: 1 };
60
+ const scale = asset.placement === 'cover' ? Math.max(desktop.width / imageWidth, desktop.height / imageHeight) :
61
+ asset.placement === 'fit' ? Math.min(desktop.width / imageWidth, desktop.height / imageHeight) : 1;
62
+ const sourceWidth = Math.min(1, desktop.width / (imageWidth * scale));
63
+ const sourceHeight = Math.min(1, desktop.height / (imageHeight * scale));
64
+ const destinationWidth = Math.min(1, imageWidth * scale / desktop.width);
65
+ const destinationHeight = Math.min(1, imageHeight * scale / desktop.height);
66
+ return { source: { x: (1 - sourceWidth) * asset.anchorX, y: (1 - sourceHeight) * asset.anchorY,
67
+ width: sourceWidth, height: sourceHeight },
68
+ destination: { x: (1 - destinationWidth) * asset.anchorX, y: (1 - destinationHeight) * asset.anchorY,
69
+ width: destinationWidth, height: destinationHeight }, version: 1 };
70
+ }
71
+ export function planLobby(request, capabilities, lobbyId, planId, automaticDpi = true) {
72
+ const target = capabilities.displays.find(display => display.id === request.targetId) ??
73
+ (request.targetId == null ? capabilities.displays.find(display => display.kind !== 'window') : undefined);
74
+ if (!target)
75
+ throw new Error('unavailable');
76
+ const viewer = request.viewer == null ? null : decodeDesktopSessionRequest(JSON.stringify({ requestId: request.requestId,
77
+ displayId: target.id, viewer: request.viewer, viewport: request.viewport, resolution: request.resolution,
78
+ quality: 'auto', takeover: false })).viewer;
79
+ const limits = capabilities.encoderBackends.flatMap(backend => backend.formats).filter(format => format.cappedRate &&
80
+ capabilities.formats.includes(format.format) && (!viewer || viewer.formats.includes(format.format)));
81
+ const limit = limits.sort((first, second) => second.maxPixels - first.maxPixels)[0];
82
+ if (!limit || viewer && (viewer.protocols.min > 2 || viewer.protocols.max < 2))
83
+ throw new Error('unsupported_client');
84
+ const maxWidth = Math.min(viewer?.maxWidth ?? 4096, limit.maxWidth);
85
+ const maxHeight = Math.min(viewer?.maxHeight ?? 4096, limit.maxHeight);
86
+ const maxPixels = Math.min(viewer?.maxPixels ?? 4_000_000, limit.maxPixels);
87
+ const layoutScale = !automaticDpi && !target.captureViewport ? 1 : request.viewport.deviceScale;
88
+ const desired = request.resolution.mode === 'fixed' ? request.resolution : {
89
+ width: Math.max(2, Math.floor(request.viewport.widthDp * layoutScale / 2) * 2),
90
+ height: Math.max(2, Math.floor(request.viewport.heightDp * layoutScale / 2) * 2)
91
+ };
92
+ let desktop;
93
+ if (target.captureViewport || target.resize === 'none')
94
+ desktop = { width: target.width, height: target.height };
95
+ else if (target.resize === 'dynamic' && target.resizeRange) {
96
+ const range = target.resizeRange;
97
+ const factor = Math.min(1, Math.min(maxWidth, range.maxWidth) / desired.width, Math.min(maxHeight, range.maxHeight) / desired.height, Math.sqrt(Math.min(maxPixels, 4_000_000) / (desired.width * desired.height)));
98
+ desktop = { width: Math.max(range.minWidth, Math.floor(desired.width * factor / 2) * 2),
99
+ height: Math.max(range.minHeight, Math.floor(desired.height * factor / 2) * 2) };
100
+ }
101
+ else {
102
+ desktop = [...target.modes].filter(candidate => candidate.width <= maxWidth && candidate.height <= maxHeight &&
103
+ candidate.width * candidate.height <= maxPixels).sort((first, second) => {
104
+ const score = (candidate) => Math.abs(Math.log((candidate.width / candidate.height) / (desired.width / desired.height))) * 10 +
105
+ Math.abs(Math.log(candidate.width * candidate.height / (desired.width * desired.height)));
106
+ return score(first) - score(second);
107
+ })[0] ?? { width: target.width, height: target.height };
108
+ }
109
+ const maximumDpi = target.maxDpi == null ? undefined : Math.min(target.maxDpi, viewer?.maxDpi ?? target.maxDpi);
110
+ const baselineDpi = automaticDpi && request.resolution.mode === 'fit' ? Math.max(96, Math.round(96 * Math.min(desktop.width / request.viewport.widthDp, desktop.height / request.viewport.heightDp))) : 96;
111
+ const dpi = maximumDpi == null ? null : Math.min(maximumDpi, request.dpi ?? baselineDpi);
112
+ let sampling = desktop;
113
+ if (target.captureViewport) {
114
+ const density = Math.min(target.capturePixelScale ?? 1, request.resolution.mode === 'fixed' ?
115
+ Math.min(desired.width / desktop.width, desired.height / desktop.height) :
116
+ Math.min(request.viewport.widthDp / desktop.width, request.viewport.heightDp / desktop.height) * request.viewport.deviceScale);
117
+ const width = desktop.width * density, height = desktop.height * density;
118
+ const factor = Math.min(1, maxWidth / width, maxHeight / height, Math.sqrt(maxPixels / (width * height)));
119
+ sampling = { width: Math.max(2, Math.floor(width * factor / 2) * 2), height: Math.max(2, Math.floor(height * factor / 2) * 2) };
120
+ }
121
+ const supported = sampling.width <= maxWidth && sampling.height <= maxHeight && sampling.width * sampling.height <= maxPixels;
122
+ const modes = target.captureViewport ? [sampling] : target.resize === 'none' ? [desktop] : [...target.modes.filter(candidate => candidate.width <= maxWidth && candidate.height <= maxHeight && candidate.width * candidate.height <= maxPixels &&
123
+ (candidate.width !== desktop.width || candidate.height !== desktop.height)).slice(0, 31), desktop];
124
+ return { lobbyId, planId, revision: request.revision, targetId: target.id, desktop, dpi,
125
+ resize: target.captureViewport ? 'none' : target.resize, modes,
126
+ resizeRange: target.captureViewport ? null : target.resizeRange ?? null, dynamicDpi: maximumDpi != null,
127
+ maxDpi: maximumDpi ?? null, captureViewport: target.captureViewport ?? false, sampling,
128
+ canAcquire: supported && capabilities.configured && capabilities.health === 'ready' && ['granted', 'not_applicable'].includes(capabilities.permission),
129
+ reason: supported ? capabilities.reason : 'unsupported_client', targets: capabilities.displays.map(display => ({ id: display.id, label: display.label,
130
+ kind: display.kind ?? 'display', available: true })) };
131
+ }
@@ -0,0 +1,156 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { createConnection } from 'node:net';
6
+ import { z } from 'zod';
7
+ import { NativeProvider } from './nativeProvider.js';
8
+ import { HelperProcess, bounded, NativeCommandError } from './helperProcess.js';
9
+ import { readDeviceHostGrant } from './hostGrant.js';
10
+ import { desktopCapabilitiesSchema } from './protocol.js';
11
+ import { NativeDeviceAdmission } from './nativeDeviceAdmission.js';
12
+ import { captureTargetLabel } from './captureTargetLabel.js';
13
+ import { decodeWallpaper } from './wallpaper.js';
14
+ import { captureSamplingModes as macCaptureModes } from './captureModes.js';
15
+ const execute = promisify(execFile);
16
+ export const macDesktopGrantSchema = z.strictObject({ schemaVersion: z.literal(2),
17
+ hostGeneration: z.string().min(1).max(128),
18
+ executable: z.string().startsWith('/').max(4096), sha256: z.string().regex(/^[a-f0-9]{64}$/),
19
+ socket: z.string().startsWith('/').max(103), token: z.string().regex(/^[a-f0-9]{64}$/) });
20
+ const target = z.object({ id: z.string().regex(/^[0-9a-f]{32}$/), kind: z.enum(['display', 'window']), label: z.string(), displayIdentity: z.string().min(1).max(256), capturePixelScale: z.number().min(1).max(16).optional(),
21
+ width: z.number().int().min(2).max(4096).refine(n => n % 2 === 0), height: z.number().int().min(2).max(4096).refine(n => n % 2 === 0) }).refine(t => t.width * t.height <= 16777216);
22
+ const geometry = z.object({ targets: z.array(target).min(1).max(128), screenRecording: z.boolean(), accessibility: z.boolean(), independentCursor: z.boolean(), captureViewport: z.boolean().optional(), overview: z.boolean().optional(), cursorVisibility: z.boolean().optional(), audio: z.boolean().optional() });
23
+ export { captureTargetLabel } from './captureTargetLabel.js';
24
+ export { captureSamplingModes as macCaptureModes } from './captureModes.js';
25
+ export async function checkMacHost(grant) {
26
+ const socket = createConnection(grant.socket);
27
+ try {
28
+ await bounded(new Promise((resolve, reject) => {
29
+ socket.once('error', reject);
30
+ socket.once('connect', () => socket.write(grant.token));
31
+ socket.once('data', bytes => bytes.length === 1 && bytes[0] === 1 ? resolve() : reject(new NativeCommandError('unavailable')));
32
+ socket.once('end', () => reject(new NativeCommandError('unavailable')));
33
+ }), 1000, 'unavailable');
34
+ }
35
+ finally {
36
+ socket.destroy();
37
+ }
38
+ }
39
+ /** Discovery can report permissions but cannot prompt, capture, encode or inject input. */
40
+ export class MacProvider {
41
+ directory;
42
+ sourceFile;
43
+ async prepareAutomation(binding) {
44
+ const provider = await this.liveProvider();
45
+ if (!provider)
46
+ throw new NativeCommandError('unavailable');
47
+ return provider.prepareAutomation(binding);
48
+ }
49
+ admission;
50
+ original;
51
+ get deviceAdmission() { return this.admission; }
52
+ static async connect(directory, sourceFile) {
53
+ const provider = new MacProvider(directory, undefined, sourceFile);
54
+ if (!await provider.liveProvider())
55
+ throw new NativeCommandError('unavailable');
56
+ return provider;
57
+ }
58
+ provider;
59
+ identity = '';
60
+ revisions = new Map();
61
+ constructor(directory, _binding, sourceFile) {
62
+ this.directory = directory;
63
+ this.sourceFile = sourceFile;
64
+ }
65
+ async grant() {
66
+ const grant = await readDeviceHostGrant(this.sourceFile ?? path.join(this.directory, 'desktop-provider.json'));
67
+ if (this.original && JSON.stringify(grant) !== JSON.stringify(this.original))
68
+ throw new NativeCommandError('unavailable');
69
+ if (!grant.executable.endsWith('/Axom Work Computer Use.app/Contents/MacOS/Axom Work Computer Use'))
70
+ throw new NativeCommandError('unavailable');
71
+ await execute('/usr/bin/codesign', ['--verify', '--strict', '-R', '=identifier "com.platless.axom.computer-use"', path.resolve(grant.executable, '../../..')], { timeout: 7000, maxBuffer: 65536 });
72
+ await checkMacHost(grant);
73
+ return grant;
74
+ }
75
+ async capabilities() {
76
+ const grant = await this.grant();
77
+ const { stdout } = await execute(grant.executable, ['--probe'], { timeout: 7000, maxBuffer: 65536, env: { ...process.env, AXOM_KEEPER_SOCKET: grant.socket, AXOM_KEEPER_TOKEN: grant.token } });
78
+ const g = geometry.parse(JSON.parse(stdout));
79
+ const displays = g.targets.map(t => {
80
+ const previous = this.revisions.get(t.id);
81
+ const identity = t.displayIdentity;
82
+ const revision = previous ? (previous.identity === identity ? previous.revision : previous.revision + 1) : 1;
83
+ this.revisions.set(t.id, { identity, revision });
84
+ return { ...(g.overview ? { overview: true } : {}), id: t.id, kind: t.kind, label: captureTargetLabel(t.label), width: t.width, height: t.height, revision, resize: g.captureViewport ? 'dynamic' : 'none', modes: g.captureViewport ? macCaptureModes(t.width, t.height, t.capturePixelScale ?? 1) : [], ...(g.captureViewport ? { captureViewport: true, capturePixelScale: t.capturePixelScale ?? 1, resizeRange: { minWidth: 2, minHeight: 2, maxWidth: Math.min(4096, Math.floor(t.width * (t.capturePixelScale ?? 1) / 2) * 2), maxHeight: Math.min(4096, Math.floor(t.height * (t.capturePixelScale ?? 1) / 2) * 2) } } : {}) };
85
+ });
86
+ const liveIds = new Set(displays.map(d => d.id));
87
+ for (const id of this.revisions.keys())
88
+ if (!liveIds.has(id))
89
+ this.revisions.delete(id);
90
+ const formats = ['h264-420-v1'];
91
+ const permission = g.screenRecording && g.accessibility, ready = permission && g.independentCursor;
92
+ return desktopCapabilitiesSchema.parse({ protocols: { min: 2, max: g.audio ? 3 : 2 }, providerId: 'macos-arm64-v1', providerVersion: 'axom-macos-1', configured: true, cursorEmbedded: false, cursorVisibility: g.cursorVisibility === true,
93
+ permission: permission ? 'granted' : 'required', health: ready ? 'ready' : 'unavailable', reason: ready ? null : permission ? 'cursor_unavailable' : 'permission_required', formats,
94
+ encoderBackends: [{ id: 'videotoolbox', kind: 'hardware', formats: formats.map(format => ({ format, maxWidth: 4096, maxHeight: 4096, maxPixels: 8847360, maxFps: 30, cappedRate: true })) }],
95
+ input: { pointer: true, physicalKeyboard: true, unicodeText: true, clipboard: true, textPaste: true },
96
+ displays });
97
+ }
98
+ async liveProvider() {
99
+ try {
100
+ const grant = await this.grant(), identity = grant.sha256 + grant.token;
101
+ if (this.original && identity !== this.identity)
102
+ return null;
103
+ if (identity !== this.identity) {
104
+ const admission = await NativeDeviceAdmission.connect(grant);
105
+ if (admission.hostLifetimeId !== grant.hostGeneration)
106
+ throw new NativeCommandError('unavailable');
107
+ this.original = grant;
108
+ this.admission = admission;
109
+ this.identity = identity;
110
+ this.provider = new NativeProvider({ helperPath: grant.executable, runtimeDir: this.directory, backend: 'videotoolbox',
111
+ deviceAdmission: admission, environment: { ...process.env, AXOM_KEEPER_SOCKET: grant.socket, AXOM_KEEPER_TOKEN: grant.token },
112
+ enumerate: () => this.capabilities(), sessionHelperFactory: async (binding) => HelperProcess.launch(grant.executable, { ...process.env, AXOM_KEEPER_TARGET: binding.displayId,
113
+ AXOM_KEEPER_SOCKET: grant.socket, AXOM_KEEPER_TOKEN: grant.token,
114
+ AXOM_DEVICE_CONTEXT: admission.context(binding.deviceGrant?.registrationId ?? '', binding.deviceGeneration, binding.sessionId, binding.deviceGrant) }, 'macos') });
115
+ }
116
+ return this.provider;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ async probe() {
123
+ // Only explicit removal of the desktop grant disables discovery. A stopped or
124
+ // unresponsive keeper is a connection failure, not a disappearing capability.
125
+ try {
126
+ await fs.lstat(path.join(this.directory, 'desktop-provider.json'));
127
+ }
128
+ catch (error) {
129
+ if (error.code === 'ENOENT')
130
+ return null;
131
+ throw error;
132
+ }
133
+ return this.capabilities();
134
+ }
135
+ async prepare(selection, binding, current) {
136
+ const provider = await this.liveProvider();
137
+ if (!provider)
138
+ throw new NativeCommandError('unavailable');
139
+ // NativeProvider.prepare performs fresh permission/geometry admission itself.
140
+ // Repeating full enumeration here added another WindowServer round trip per window.
141
+ return provider.prepare(selection, binding, current);
142
+ }
143
+ async wallpaper(targetId, pixels = { width: 1920, height: 1080 }) {
144
+ const grant = await this.grant();
145
+ if (!/^[a-f0-9]{32}$/.test(targetId))
146
+ throw new NativeCommandError('invalid_request');
147
+ const result = await execute(grant.executable, ['--wallpaper', targetId, String(pixels.width), String(pixels.height)], { timeout: 8000, maxBuffer: 3 * 1024 * 1024,
148
+ env: { ...process.env, AXOM_KEEPER_SOCKET: grant.socket, AXOM_KEEPER_TOKEN: grant.token } });
149
+ return decodeWallpaper(result.stdout);
150
+ }
151
+ async recoverDisplay(binding, reserved) {
152
+ if (!await this.probe() || !this.provider)
153
+ throw new NativeCommandError('unavailable');
154
+ return this.provider.recoverDisplay(binding, reserved);
155
+ }
156
+ }
@@ -0,0 +1,331 @@
1
+ import { z } from 'zod';
2
+ import { DesktopProtocolError, parseDesktopJson } from './protocol.js';
3
+ export function mediaRequire(value) {
4
+ if (!value)
5
+ throw new DesktopProtocolError('Invalid desktop media');
6
+ }
7
+ const integer = (n, min = 0, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(n) && n >= min && n <= max;
8
+ const axis = z.number().int().min(2).max(4096).refine(n => n % 2 === 0);
9
+ const label = z.string().min(1).refine(s => Buffer.byteLength(s) <= 128 && !/[\x00-\x1f\x7f]/.test(s));
10
+ const codecSchema = z.strictObject({ codec: z.literal('h264'), representation: z.literal(1),
11
+ width: axis, height: axis, fpsCeiling: z.union([z.literal(15), z.literal(30), z.literal(60)]),
12
+ profile: label, level: label, colorMatrix: z.literal('bt709'), colorRange: z.literal('limited'), parameterSets: z.array(z.string()) });
13
+ function checked(read) {
14
+ try {
15
+ return read();
16
+ }
17
+ catch {
18
+ throw new DesktopProtocolError('Invalid desktop media');
19
+ }
20
+ }
21
+ export function decodeConfig(bytes) {
22
+ return checked(() => {
23
+ const c = codecSchema.parse(parseDesktopJson(bytes, 16384));
24
+ mediaRequire(c.parameterSets.length === 2);
25
+ c.parameterSets.forEach((encoded, i) => {
26
+ mediaRequire(encoded.length <= 2732);
27
+ const nal = Buffer.from(encoded, 'base64');
28
+ mediaRequire(nal.length >= 1 && nal.length <= 2048 && nal.toString('base64') === encoded &&
29
+ (nal[0] & 128) === 0 && (nal[0] & 31) === (i % 2 === 0 ? 7 : 8));
30
+ });
31
+ return c;
32
+ });
33
+ }
34
+ function validateUnit(p, bytes) {
35
+ if (p.type === 1)
36
+ mediaRequire(decodeConfig(bytes).representation === p.representation);
37
+ else if (p.type === 3) {
38
+ const w = bytes.readUInt16BE(), h = bytes.readUInt16BE(2);
39
+ mediaRequire(w >= 1 && w <= 256 && h >= 1 && h <= 256 && bytes.readUInt16BE(4) < w &&
40
+ bytes.readUInt16BE(6) < h && w * h * 4 + 8 === p.unitLength);
41
+ }
42
+ else if (p.type === 5) {
43
+ mediaRequire(bytes.length >= 95 && bytes.subarray(0, 16).equals(Buffer.from('28b4619e8e524cf29ae8415852473034', 'hex')) && bytes[16] === 4 && bytes[37] === 1 && bytes.readUInt32BE(38) === 0 && bytes.readUInt16BE(42) > 0 && bytes.readUInt16BE(42) <= 1024);
44
+ const focusRevision = bytes.readBigUInt64BE(44), [x, y, w, h, sw, sh] = [52, 56, 60, 64, 68, 72].map(o => bytes.readUInt32BE(o));
45
+ mediaRequire(focusRevision > 0n && focusRevision <= BigInt(Number.MAX_SAFE_INTEGER) && w > 0 && h > 0 && sw >= 2 && sh >= 2 && sw <= 4096 && sh <= 4096 && x + w <= sw && y + h <= sh);
46
+ mediaRequire(axis.safeParse(bytes.readUInt16BE(17)).success && axis.safeParse(bytes.readUInt16BE(19)).success && bytes.readBigUInt64BE(21) > 0n && bytes.readBigUInt64BE(21) <= BigInt(Number.MAX_SAFE_INTEGER) && bytes.readBigUInt64BE(29) > 0n && bytes.readBigUInt64BE(29) <= BigInt(Number.MAX_SAFE_INTEGER));
47
+ }
48
+ else if (p.type === 4)
49
+ cursor(bytes);
50
+ }
51
+ function cursor(bytes) {
52
+ return checked(() => z.strictObject({ x: z.number().int().min(0).max(4095),
53
+ y: z.number().int().min(0).max(4095), visible: z.boolean() }).parse(parseDesktopJson(bytes, 1024)));
54
+ }
55
+ /** Validates the header and current identity before retaining/reassembling payload. */
56
+ export function decodeMedia(bytes, fence = () => { }) {
57
+ return checked(() => {
58
+ mediaRequire(bytes.length >= 65 && bytes.length <= 65600 && bytes.subarray(0, 5).equals(Buffer.from('AXDS\x01')) &&
59
+ bytes.readUInt16BE(8) === 64 && bytes.readUInt16BE(10) === 0 && bytes.readUIntBE(61, 3) === 0);
60
+ const u64 = (offset) => { const n = bytes.readBigUInt64BE(offset); mediaRequire(n <= BigInt(Number.MAX_SAFE_INTEGER)); return Number(n); };
61
+ const length = bytes.readUInt32BE(48);
62
+ const p = { type: bytes[5], flags: bytes.readUInt16BE(6), epoch: bytes.readUInt32BE(12),
63
+ displayRevision: bytes.readUInt32BE(16), sequence: bytes.readUInt32BE(20), frameId: u64(24), timestampUs: u64(32),
64
+ lastInputSequence: u64(40), unitLength: bytes.readUInt32BE(52), fragmentIndex: bytes.readUInt16BE(56),
65
+ fragmentCount: bytes.readUInt16BE(58), representation: bytes[60], payload: Buffer.alloc(0) };
66
+ mediaRequire(p.type >= 1 && p.type <= 5 && p.representation === 1 && p.flags <= 1 &&
67
+ (p.type === 2 || p.flags === 0) && p.epoch > 0 && p.displayRevision > 0 && p.sequence > 0 &&
68
+ ((p.type === 2 || p.type === 5) ? p.frameId > 0 : p.frameId === 0 && p.timestampUs === 0));
69
+ mediaRequire(length > 0 && length <= 65536 && bytes.length === 64 + length && p.unitLength > 0 && p.unitLength <= 8388608);
70
+ const count = Math.ceil(p.unitLength / 65536);
71
+ mediaRequire(p.fragmentCount === count && p.fragmentIndex < count &&
72
+ length === (p.fragmentIndex === count - 1 ? p.unitLength - p.fragmentIndex * 65536 : 65536));
73
+ if (p.type === 1)
74
+ mediaRequire(count === 1 && p.unitLength <= 16384);
75
+ if (p.type === 3)
76
+ mediaRequire(p.unitLength >= 12 && p.unitLength <= 262152);
77
+ if (p.type === 5)
78
+ mediaRequire(count === 1 && p.unitLength >= 95 && p.unitLength <= 24576);
79
+ if (p.type === 4)
80
+ mediaRequire(count === 1 && p.unitLength <= 1024);
81
+ fence(p);
82
+ p.payload = bytes.subarray(64);
83
+ if (count === 1)
84
+ validateUnit(p, p.payload);
85
+ return p;
86
+ });
87
+ }
88
+ export class DesktopMediaStream {
89
+ sourceDimensions;
90
+ constructor(sourceDimensions = () => undefined) {
91
+ this.sourceDimensions = sourceDimensions;
92
+ }
93
+ configuration = null;
94
+ epoch = 0;
95
+ revision = 0;
96
+ picture = { sequence: 0, lastFrame: 0, pending: undefined, storage: undefined, next: 0 };
97
+ cursorLane = { sequence: 0, lastFrame: 0, pending: undefined, storage: undefined, next: 0 };
98
+ exactLane = { sequence: 0, lastFrame: 0, pending: undefined, storage: undefined, next: 0 };
99
+ lane(type) { return type === 3 || type === 4 ? this.cursorLane : type === 5 ? this.exactLane : this.picture; }
100
+ exactSequence = 0;
101
+ recentFrames = [];
102
+ needsIdr = true;
103
+ failed = false;
104
+ accept(bytes) {
105
+ mediaRequire(!this.failed);
106
+ try {
107
+ const p = decodeMedia(bytes, packet => this.validate(packet));
108
+ const lane = this.lane(p.type);
109
+ lane.sequence = p.sequence;
110
+ if (p.type === 1) {
111
+ this.configuration = decodeConfig(p.payload);
112
+ this.epoch = p.epoch;
113
+ this.revision = p.displayRevision;
114
+ this.needsIdr = true;
115
+ this.exactSequence = 0;
116
+ this.exactLane.sequence = 0;
117
+ this.exactLane.pending = undefined;
118
+ this.exactLane.storage = undefined;
119
+ this.exactLane.next = 0;
120
+ this.cursorLane.sequence = 0;
121
+ this.cursorLane.pending = undefined;
122
+ this.cursorLane.storage = undefined;
123
+ this.cursorLane.next = 0;
124
+ return null;
125
+ }
126
+ if (p.fragmentCount === 1)
127
+ return this.complete(p, p.payload);
128
+ if (!lane.pending) {
129
+ lane.pending = { ...p, payload: Buffer.alloc(0) };
130
+ lane.storage = Buffer.alloc(p.unitLength);
131
+ lane.next = 0;
132
+ }
133
+ p.payload.copy(lane.storage, lane.next++ * 65536);
134
+ if (lane.next !== p.fragmentCount)
135
+ return null;
136
+ const first = lane.pending, unit = lane.storage;
137
+ lane.pending = undefined;
138
+ lane.storage = undefined;
139
+ validateUnit(first, unit);
140
+ return this.complete(first, unit);
141
+ }
142
+ catch {
143
+ this.failed = true;
144
+ this.picture.pending = this.cursorLane.pending = this.exactLane.pending = undefined;
145
+ this.picture.storage = this.cursorLane.storage = this.exactLane.storage = undefined;
146
+ throw new DesktopProtocolError('Invalid desktop stream');
147
+ }
148
+ }
149
+ applyMotionCut(pictureThrough, frameThrough) {
150
+ mediaRequire(!this.failed && this.configuration && integer(pictureThrough, this.picture.sequence, 0xffffffff) && integer(frameThrough, this.picture.lastFrame));
151
+ this.picture.sequence = pictureThrough;
152
+ this.picture.lastFrame = frameThrough;
153
+ this.picture.pending = undefined;
154
+ this.picture.storage = undefined;
155
+ this.picture.next = 0;
156
+ this.needsIdr = true;
157
+ }
158
+ validate(p) {
159
+ const lane = this.lane(p.type);
160
+ if (p.type === 1) {
161
+ mediaRequire(!this.picture.pending && p.epoch > this.epoch && p.sequence === 1);
162
+ return;
163
+ }
164
+ mediaRequire(this.configuration && p.epoch === this.epoch && p.displayRevision === this.revision &&
165
+ p.representation === this.configuration.representation && p.sequence === lane.sequence + 1);
166
+ if (!lane.pending) {
167
+ mediaRequire(p.fragmentIndex === 0);
168
+ if (p.type === 2 || p.type === 5)
169
+ mediaRequire(p.frameId > lane.lastFrame && !this.recentFrames.includes(p.frameId) && p.frameId !== this.picture.pending?.frameId && (!this.needsIdr || p.type === 2 && p.flags === 1));
170
+ }
171
+ else {
172
+ const first = lane.pending;
173
+ mediaRequire(['type', 'flags', 'frameId', 'timestampUs', 'lastInputSequence', 'unitLength', 'fragmentCount']
174
+ .every(k => p[k] === first[k]) && p.fragmentIndex === lane.next);
175
+ }
176
+ }
177
+ complete(p, bytes) {
178
+ if (p.type === 4) {
179
+ const c = cursor(bytes), source = this.sourceDimensions() ?? this.configuration;
180
+ mediaRequire(c.x < source.width && c.y < source.height);
181
+ }
182
+ if (p.type !== 2 && p.type !== 5)
183
+ return null;
184
+ const exactSequence = p.type === 5 ? Number(bytes.readBigUInt64BE(29)) : 0;
185
+ if (p.type === 5) {
186
+ mediaRequire(exactSequence === this.exactSequence + 1 && bytes.readUInt16BE(17) === this.configuration.width && bytes.readUInt16BE(19) === this.configuration.height);
187
+ this.exactSequence = exactSequence;
188
+ }
189
+ else
190
+ this.needsIdr = false;
191
+ this.lane(p.type).lastFrame = p.frameId;
192
+ this.recentFrames.push(p.frameId);
193
+ if (this.recentFrames.length > 128)
194
+ this.recentFrames.shift();
195
+ return { ...p, payload: bytes, mainAU: bytes, exactSequence };
196
+ }
197
+ }
198
+ const lanes = ['motion', 'cursor', 'exact'];
199
+ const consumedKey = { motion: 'motionConsumedBytes', cursor: 'cursorConsumedBytes', exact: 'exactConsumedBytes' };
200
+ const freshTotals = () => ({ motion: 0, cursor: 0, exact: 0 });
201
+ export function desktopMediaLane(type) {
202
+ mediaRequire(integer(type, 1, 5));
203
+ return type <= 2 ? 'motion' : type <= 4 ? 'cursor' : 'exact';
204
+ }
205
+ /** One epoch's bounded reservations and actual transport admissions. Pipe writes never commit. */
206
+ export class DesktopMediaFlowWindow {
207
+ window;
208
+ records = new Map();
209
+ committed = freshTotals();
210
+ reserved = freshTotals();
211
+ observed = freshTotals();
212
+ consumed = freshTotals();
213
+ lastId = 0;
214
+ constructor(window = 0) {
215
+ this.window = window;
216
+ mediaRequire(window === 0 || integer(window, 196608, 524288));
217
+ }
218
+ get inFlightBytes() { return lanes.reduce((n, l) => n + this.debt(l), 0); }
219
+ get recordCount() { return this.records.size; }
220
+ get hasCredit() { return this.window > 0; }
221
+ get appliedCredit() { return { motionConsumedBytes: this.consumed.motion, cursorConsumedBytes: this.consumed.cursor, exactConsumedBytes: this.consumed.exact, windowBytes: this.window }; }
222
+ debt(lane) { return this.committed[lane] + this.reserved[lane] - this.consumed[lane]; }
223
+ laneRecords(lane) { return [...this.records.values()].filter(r => r.lane === lane).length; }
224
+ admit(lane, bytes) {
225
+ mediaRequire(lanes.includes(lane) && integer(bytes, 1, lane === 'exact' ? 24576 : 65536));
226
+ const others = lanes.filter(l => l !== lane && l !== 'motion');
227
+ const protectedBytes = others.reduce((n, l) => n + Math.max(0, (l === 'cursor' ? 65536 : 24576) - this.debt(l)), 0);
228
+ const protectedRecords = others.reduce((n, l) => n + (this.laneRecords(l) === 0 ? 1 : 0), 0);
229
+ return this.records.size + 1 <= 128 - protectedRecords && this.inFlightBytes + bytes <= this.window - protectedBytes;
230
+ }
231
+ /** IDs are fresh monotonically increasing local admission attempts, including failed attempts. */
232
+ reserve(id, lane, bytes) {
233
+ mediaRequire(integer(id, this.lastId + 1));
234
+ this.lastId = id;
235
+ if (!this.admit(lane, bytes))
236
+ return false;
237
+ mediaRequire(this.committed[lane] <= Number.MAX_SAFE_INTEGER - this.reserved[lane] - bytes);
238
+ this.reserved[lane] += bytes;
239
+ this.records.set(id, { lane, bytes, remaining: bytes, committed: false });
240
+ return true;
241
+ }
242
+ commit(id) {
243
+ const r = this.records.get(id);
244
+ mediaRequire(r && !r.committed);
245
+ this.reserved[r.lane] -= r.bytes;
246
+ this.committed[r.lane] += r.bytes;
247
+ r.committed = true;
248
+ this.applyPending();
249
+ }
250
+ cancel(id) {
251
+ const r = this.records.get(id);
252
+ mediaRequire(r && !r.committed);
253
+ mediaRequire(this.observed[r.lane] <= this.committed[r.lane] + this.reserved[r.lane] - r.bytes);
254
+ this.reserved[r.lane] -= r.bytes;
255
+ this.records.delete(id);
256
+ }
257
+ credit(value) {
258
+ mediaRequire(integer(value.windowBytes, 196608, 524288) && Number.isSafeInteger(value.motionConsumedBytes + value.cursorConsumedBytes + value.exactConsumedBytes));
259
+ for (const l of lanes)
260
+ mediaRequire(integer(value[consumedKey[l]], this.observed[l], this.committed[l] + this.reserved[l]));
261
+ for (const l of lanes)
262
+ this.observed[l] = value[consumedKey[l]];
263
+ this.window = value.windowBytes;
264
+ this.applyPending();
265
+ }
266
+ applyPending() {
267
+ for (const lane of lanes) {
268
+ if (this.observed[lane] > this.committed[lane])
269
+ continue;
270
+ let delta = this.observed[lane] - this.consumed[lane];
271
+ this.consumed[lane] = this.observed[lane];
272
+ for (const [id, r] of this.records)
273
+ if (delta && r.lane === lane && r.committed) {
274
+ const used = Math.min(delta, r.remaining);
275
+ r.remaining -= used;
276
+ delta -= used;
277
+ if (!r.remaining)
278
+ this.records.delete(id);
279
+ }
280
+ mediaRequire(delta === 0);
281
+ }
282
+ }
283
+ }
284
+ /** Sender-clock complete-frame send -> feedback. Feedback scheduling is not network delay. */
285
+ export class DesktopDeliveryDelay {
286
+ frames = new Map();
287
+ samples = [];
288
+ observation = 0;
289
+ sampled = 0;
290
+ sent(frame, at) {
291
+ this.frames.set(frame, at);
292
+ if (this.frames.size > 512)
293
+ this.frames.delete(this.frames.keys().next().value);
294
+ }
295
+ received(frame, at) {
296
+ const sent = this.frames.get(frame);
297
+ if (sent === undefined)
298
+ return;
299
+ this.samples.push({ at, delay: Math.max(0, at - sent), observation: ++this.observation });
300
+ if (this.samples.length > 500)
301
+ this.samples.shift();
302
+ // Independent exact/motion completion may insert IDs out of numeric order.
303
+ for (const id of this.frames.keys())
304
+ if (id <= frame)
305
+ this.frames.delete(id);
306
+ }
307
+ excess(now) {
308
+ this.samples = this.samples.filter(s => now - s.at <= 90000);
309
+ const recent = this.samples.filter(s => now - s.at <= 1250);
310
+ if (!recent.length)
311
+ return 0;
312
+ return Math.max(0, Math.min(...recent.map(s => s.delay)) - Math.min(...this.samples.map(s => s.delay)));
313
+ }
314
+ sample(now) {
315
+ const raw = this.excess(now);
316
+ const fresh = this.samples.filter(s => s.observation > this.sampled && now - s.at <= 1250);
317
+ this.sampled = this.observation;
318
+ if (!fresh.length)
319
+ return { excessMs: raw, observations: 0, delayMs: undefined };
320
+ const excessMs = Math.max(0, Math.min(...fresh.map(s => s.delay)) - Math.min(...this.samples.map(s => s.delay)));
321
+ // The active feedback cadence allows 200ms of scheduling uncertainty. Only
322
+ // the excess beyond that can establish >40ms congestion; ambiguity must hold.
323
+ const delayMs = excessMs <= 40 ? excessMs : excessMs > 240 ? excessMs - 200 : undefined;
324
+ return { excessMs, observations: fresh.length, delayMs };
325
+ }
326
+ reset() {
327
+ this.frames.clear();
328
+ this.samples = [];
329
+ this.sampled = this.observation;
330
+ }
331
+ }