oh-my-opencode 5.1.72 → 5.1.73

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 (76) hide show
  1. package/dist/cli/index.js +2280 -463
  2. package/dist/cli-node/index.js +2280 -463
  3. package/dist/index.js +13 -13
  4. package/dist/skills/browser/runtime/omowright/manifest.json +1 -1
  5. package/dist/skills/frontend/references/design/print-paged-media.md +1 -1
  6. package/dist/skills/ulw-execute/SKILL.md +2 -2
  7. package/dist/skills/ulw-plan/references/full-workflow.md +1 -1
  8. package/dist/skills/ulw-plan/scripts/plan-templates.mjs +1 -1
  9. package/dist/skills/ulw-research/references/research-collection.md +1 -1
  10. package/dist/tui.js +13 -13
  11. package/package.json +13 -13
  12. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
  13. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  14. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  15. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  16. package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
  17. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  18. package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
  19. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  20. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
  21. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +2 -2
  22. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  23. package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
  24. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  25. package/packages/omo-codex/plugin/components/rules/package.json +1 -1
  26. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  27. package/packages/omo-codex/plugin/components/teammode/package.json +1 -1
  28. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  29. package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
  30. package/packages/omo-codex/plugin/components/ultrawork/agents/plan.toml +2 -2
  31. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  32. package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
  33. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/full-workflow.md +1 -1
  34. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/scripts/plan-templates.mjs +1 -1
  35. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
  36. package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
  37. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
  38. package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
  39. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +1 -1
  40. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  41. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  42. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  43. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  44. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  45. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  46. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  47. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
  48. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  49. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  50. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  51. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  52. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  53. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  54. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  55. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
  56. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  57. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  58. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  59. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  60. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  61. package/packages/omo-codex/plugin/package-lock.json +12 -12
  62. package/packages/omo-codex/plugin/package.json +1 -1
  63. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
  64. package/packages/omo-codex/plugin/skills/frontend/references/design/print-paged-media.md +1 -1
  65. package/packages/omo-codex/plugin/skills/ulw-execute/SKILL.md +2 -2
  66. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +1 -1
  67. package/packages/omo-codex/plugin/skills/ulw-plan/references/full-workflow.md +1 -1
  68. package/packages/omo-codex/plugin/skills/ulw-plan/scripts/plan-templates.mjs +1 -1
  69. package/packages/omo-codex/plugin/skills/ulw-research/references/research-collection.md +1 -1
  70. package/packages/omo-codex/scripts/install-dist/install-local.mjs +2 -2
  71. package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +1 -1
  72. package/packages/shared-skills/skills/frontend/references/design/print-paged-media.md +1 -1
  73. package/packages/shared-skills/skills/ulw-execute/SKILL.md +2 -2
  74. package/packages/shared-skills/skills/ulw-plan/references/full-workflow.md +1 -1
  75. package/packages/shared-skills/skills/ulw-plan/scripts/plan-templates.mjs +1 -1
  76. package/packages/shared-skills/skills/ulw-research/references/research-collection.md +1 -1
@@ -2133,7 +2133,7 @@ var package_default;
2133
2133
  var init_package = __esm(() => {
2134
2134
  package_default = {
2135
2135
  name: "oh-my-opencode",
2136
- version: "5.1.72",
2136
+ version: "5.1.73",
2137
2137
  description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",
2138
2138
  main: "./dist/index.js",
2139
2139
  types: "dist/index.d.ts",
@@ -2404,18 +2404,18 @@ var init_package = __esm(() => {
2404
2404
  typescript: "^7.0.2"
2405
2405
  },
2406
2406
  optionalDependencies: {
2407
- "oh-my-opencode-darwin-arm64": "5.1.72",
2408
- "oh-my-opencode-darwin-x64": "5.1.72",
2409
- "oh-my-opencode-darwin-x64-baseline": "5.1.72",
2410
- "oh-my-opencode-linux-arm64": "5.1.72",
2411
- "oh-my-opencode-linux-arm64-musl": "5.1.72",
2412
- "oh-my-opencode-linux-x64": "5.1.72",
2413
- "oh-my-opencode-linux-x64-baseline": "5.1.72",
2414
- "oh-my-opencode-linux-x64-musl": "5.1.72",
2415
- "oh-my-opencode-linux-x64-musl-baseline": "5.1.72",
2416
- "oh-my-opencode-windows-arm64": "5.1.72",
2417
- "oh-my-opencode-windows-x64": "5.1.72",
2418
- "oh-my-opencode-windows-x64-baseline": "5.1.72"
2407
+ "oh-my-opencode-darwin-arm64": "5.1.73",
2408
+ "oh-my-opencode-darwin-x64": "5.1.73",
2409
+ "oh-my-opencode-darwin-x64-baseline": "5.1.73",
2410
+ "oh-my-opencode-linux-arm64": "5.1.73",
2411
+ "oh-my-opencode-linux-arm64-musl": "5.1.73",
2412
+ "oh-my-opencode-linux-x64": "5.1.73",
2413
+ "oh-my-opencode-linux-x64-baseline": "5.1.73",
2414
+ "oh-my-opencode-linux-x64-musl": "5.1.73",
2415
+ "oh-my-opencode-linux-x64-musl-baseline": "5.1.73",
2416
+ "oh-my-opencode-windows-arm64": "5.1.73",
2417
+ "oh-my-opencode-windows-x64": "5.1.73",
2418
+ "oh-my-opencode-windows-x64-baseline": "5.1.73"
2419
2419
  },
2420
2420
  overrides: {
2421
2421
  hono: "^4.13.8",
@@ -92956,7 +92956,7 @@ var package_default2;
92956
92956
  var init_package2 = __esm(() => {
92957
92957
  package_default2 = {
92958
92958
  name: "@oh-my-opencode/omo-codex",
92959
- version: "5.1.72",
92959
+ version: "5.1.73",
92960
92960
  type: "module",
92961
92961
  private: true,
92962
92962
  description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -116082,20 +116082,25 @@ var CLOSED_WHOAMI_HELP = `Show the current OmO device sign-in.
116082
116082
  omo whoami [--api <url>]
116083
116083
 
116084
116084
  This runs while OmO accounts are closed.`;
116085
+ var CLOSED_AUTH_HELP = { login: CLOSED_LOGIN_HELP, logout: CLOSED_LOGOUT_HELP, whoami: CLOSED_WHOAMI_HELP };
116085
116086
  function refuseClosedServiceAuth() {
116086
116087
  console.error(CLOSED_LOGIN_MESSAGE);
116087
116088
  process.exit(1);
116088
116089
  }
116089
116090
  function describeClosedAuthCommand(name) {
116090
116091
  return () => {
116091
- console.log(name === "login" ? CLOSED_LOGIN_HELP : name === "logout" ? CLOSED_LOGOUT_HELP : CLOSED_WHOAMI_HELP);
116092
+ console.log(CLOSED_AUTH_HELP[name]);
116092
116093
  process.exit(0);
116093
116094
  };
116094
116095
  }
116095
116096
  function configureClosedServiceAuthCommands(program, hooks) {
116096
116097
  configureClosedDeviceLogin(program, hooks);
116097
116098
  for (const name of ["logout", "whoami"]) {
116098
- const command = program.command(name, { hidden: true }).helpOption(false).allowUnknownOption().allowExcessArguments().option("--api <url>").action((options) => {
116099
+ const command = program.command(name, { hidden: true }).helpOption(false).allowUnknownOption().allowExcessArguments().option("--api <url>").option("--help").action((options) => {
116100
+ if (options.help === true) {
116101
+ console.log(CLOSED_AUTH_HELP[name]);
116102
+ return;
116103
+ }
116099
116104
  if (command.args.length !== 0)
116100
116105
  refuseClosedServiceAuth();
116101
116106
  return run3(name, options, hooks);
@@ -116130,11 +116135,19 @@ function configureServiceAuthCommands(program, open = serviceAccountsOpen(), hoo
116130
116135
  import { existsSync as existsSync68 } from "node:fs";
116131
116136
 
116132
116137
  // packages/device-service-core/src/device-service.ts
116133
- import { join as join121 } from "node:path";
116138
+ import { join as join122 } from "node:path";
116134
116139
 
116135
116140
  // packages/device-service-core/src/local-api/access.ts
116136
- import { createHmac as createHmac2, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
116137
- import { chmodSync as chmodSync8, closeSync as closeSync5, lstatSync as lstatSync6, openSync as openSync5, readFileSync as readFileSync46, renameSync as renameSync10, rmSync as rmSync10, writeFileSync as writeFileSync18 } from "node:fs";
116141
+ import {
116142
+ chmodSync as chmodSync8,
116143
+ closeSync as closeSync5,
116144
+ lstatSync as lstatSync6,
116145
+ openSync as openSync5,
116146
+ readFileSync as readFileSync46,
116147
+ renameSync as renameSync10,
116148
+ rmSync as rmSync10,
116149
+ writeFileSync as writeFileSync18
116150
+ } from "node:fs";
116138
116151
  import { join as join118 } from "node:path";
116139
116152
 
116140
116153
  // packages/device-service-core/src/local-api/errors.ts
@@ -116145,7 +116158,9 @@ class LocalApiError extends Error {
116145
116158
  limit_chars;
116146
116159
  path_refusal;
116147
116160
  command_id;
116148
- not_sent;
116161
+ candidates;
116162
+ incomplete;
116163
+ sign_in_reason;
116149
116164
  constructor(code, reason, extra = {}) {
116150
116165
  super(`${code}: ${reason}`);
116151
116166
  this.name = "LocalApiError";
@@ -116158,40 +116173,112 @@ class LocalApiError extends Error {
116158
116173
  this.path_refusal = extra.path_refusal;
116159
116174
  if (extra.command_id !== undefined)
116160
116175
  this.command_id = extra.command_id;
116161
- if (extra.not_sent === true)
116162
- this.not_sent = true;
116176
+ if (extra.candidates !== undefined)
116177
+ this.candidates = extra.candidates;
116178
+ if (extra.incomplete !== undefined)
116179
+ this.incomplete = extra.incomplete;
116180
+ if (extra.sign_in_reason !== undefined)
116181
+ this.sign_in_reason = extra.sign_in_reason;
116163
116182
  }
116164
116183
  }
116165
116184
  var protocolViolation = (detail) => {
116166
116185
  throw new LocalApiError("protocol_violation", detail);
116167
116186
  };
116168
116187
 
116188
+ // packages/device-service-core/src/local-api/proof.ts
116189
+ import { createHmac as createHmac2, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
116190
+
116191
+ // packages/device-service-core/src/local-api/bytes-encoding.ts
116192
+ var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
116193
+ var portable = {
116194
+ hex: (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""),
116195
+ base64: (bytes) => {
116196
+ let out = "";
116197
+ for (let i = 0;i < bytes.length; i += 3) {
116198
+ const [a = 0, b = 0, c = 0] = [bytes[i], bytes[i + 1], bytes[i + 2]];
116199
+ const n = a << 16 | b << 8 | c;
116200
+ out += ALPHABET.charAt(n >> 18 & 63) + ALPHABET.charAt(n >> 12 & 63);
116201
+ out += i + 1 < bytes.length ? ALPHABET.charAt(n >> 6 & 63) : "=";
116202
+ out += i + 2 < bytes.length ? ALPHABET.charAt(n & 63) : "=";
116203
+ }
116204
+ return out;
116205
+ },
116206
+ fromBase64url: (text) => {
116207
+ if (!/^[A-Za-z0-9_-]*={0,2}$/.test(text))
116208
+ throw new SyntaxError("invalid base64url");
116209
+ const clean = text.replaceAll("-", "+").replaceAll("_", "/").replace(/=+$/, "");
116210
+ if (clean.length % 4 === 1)
116211
+ throw new SyntaxError("invalid base64url");
116212
+ const out = new Uint8Array(Math.floor(clean.length * 3 / 4));
116213
+ let bits = 0;
116214
+ let value = 0;
116215
+ let at = 0;
116216
+ for (const ch of clean) {
116217
+ value = value << 6 | ALPHABET.indexOf(ch);
116218
+ bits += 6;
116219
+ if (bits >= 8) {
116220
+ bits -= 8;
116221
+ out[at++] = value >> bits & 255;
116222
+ }
116223
+ }
116224
+ return out;
116225
+ }
116226
+ };
116227
+ var native = (bytes) => bytes;
116228
+ var from = Uint8Array;
116229
+ var toHex = (bytes) => native(bytes).toHex?.() ?? portable.hex(bytes);
116230
+ var toBase64 = (bytes) => native(bytes).toBase64?.() ?? portable.base64(bytes);
116231
+ var toBase64url = (bytes) => native(bytes).toBase64?.({ alphabet: "base64url", omitPadding: true }) ?? portable.base64(bytes).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
116232
+ var fromBase64url = (text) => from.fromBase64?.(text, { alphabet: "base64url" }) ?? portable.fromBase64url(text);
116233
+ var fromBase64 = (text) => {
116234
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text))
116235
+ throw new SyntaxError("invalid base64");
116236
+ return from.fromBase64?.(text) ?? portable.fromBase64url(text.replaceAll("+", "-").replaceAll("/", "_"));
116237
+ };
116238
+
116239
+ // packages/device-service-core/src/local-api/proof.ts
116240
+ var NONCE_BYTES = 32;
116241
+ var mintNonce = () => toBase64url(randomBytes7(NONCE_BYTES));
116242
+ var mintId = () => toBase64url(randomBytes7(16));
116243
+ var decodedBytes = (value, bytes, what) => {
116244
+ const violation = () => new LocalApiError("protocol_violation", `${what} is not ${bytes} base64url bytes`);
116245
+ let out;
116246
+ try {
116247
+ out = fromBase64url(value);
116248
+ } catch (error) {
116249
+ if (error instanceof Error)
116250
+ throw violation();
116251
+ throw error;
116252
+ }
116253
+ if (out.length !== bytes || toBase64url(out) !== value)
116254
+ throw violation();
116255
+ return out;
116256
+ };
116257
+ var proof = (token, label, nonce, endpoint) => toBase64url(createHmac2("sha256", token).update(label).update(decodedBytes(nonce, NONCE_BYTES, "a nonce")).update(endpoint).digest());
116258
+ var serverProof = (token, clientNonce, endpoint) => proof(token, "server", clientNonce, endpoint);
116259
+ var clientProof = (token, serverNonce, endpoint) => proof(token, "client", serverNonce, endpoint);
116260
+ var proofMatches = (expected, actual) => {
116261
+ const a = new TextEncoder().encode(expected);
116262
+ const b = new TextEncoder().encode(actual);
116263
+ return a.length === b.length && timingSafeEqual2(a, b);
116264
+ };
116265
+
116169
116266
  // packages/device-service-core/src/local-api/dacl.ts
116170
116267
  import { spawn as spawn6 } from "node:child_process";
116171
116268
  var runPowerShell = async (script, env) => {
116172
116269
  const encoded = Buffer.from(script, "utf16le").toString("base64");
116173
116270
  const proc = spawn6("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
116174
116271
  const chunks = [];
116175
- const errChunks = [];
116176
116272
  proc.stdout.on("data", (chunk) => chunks.push(chunk));
116177
- proc.stderr.on("data", (chunk) => errChunks.push(chunk));
116273
+ proc.stderr.resume();
116178
116274
  const code = await new Promise((resolve, reject) => {
116179
116275
  proc.once("error", reject);
116180
116276
  proc.once("close", (exitCode) => resolve(exitCode ?? -1));
116181
116277
  });
116182
- return {
116183
- code,
116184
- out: Buffer.concat(chunks).toString("utf8"),
116185
- err: Buffer.concat(errChunks).toString("utf8")
116186
- };
116187
- };
116188
- var firstErrorLine = (err) => {
116189
- const line = (err ?? "").split(/\r?\n/).find((text) => text.trim() !== "" && !text.startsWith("#< CLIXML"))?.trim() ?? "";
116190
- return line === "" ? "" : `: ${line.slice(0, 300)}`;
116278
+ return { code, out: new TextDecoder().decode(Buffer.concat(chunks)) };
116191
116279
  };
116192
- var APPLY = String.raw`
116280
+ var APPLY_DACL_SCRIPT = String.raw`
116193
116281
  $ErrorActionPreference = 'Stop'
116194
- trap { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }
116195
116282
  $sid = New-Object System.Security.Principal.SecurityIdentifier($env:LA_SID)
116196
116283
  if ($env:LA_KIND -eq 'dir') {
116197
116284
  $acl = New-Object System.Security.AccessControl.DirectorySecurity
@@ -116206,11 +116293,7 @@ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($sid,
116206
116293
  $acl.SetAccessRuleProtection($true, $false)
116207
116294
  $acl.SetOwner($sid)
116208
116295
  $acl.AddAccessRule($rule)
116209
- if ($env:LA_KIND -eq 'dir') {
116210
- [System.IO.Directory]::SetAccessControl($env:LA_PATH, $acl)
116211
- } else {
116212
- [System.IO.File]::SetAccessControl($env:LA_PATH, $acl)
116213
- }
116296
+ Set-Acl -LiteralPath $env:LA_PATH -AclObject $acl
116214
116297
  Write-Output 'applied'
116215
116298
  `;
116216
116299
  var DESCRIBE_DACL_SCRIPT = String.raw`
@@ -116243,10 +116326,6 @@ public static class LaSddl {
116243
116326
  '@
116244
116327
  [LaSddl]::Read($env:LA_PATH)
116245
116328
  `;
116246
- var SID_TOKEN_SCRIPT = String.raw`
116247
- $ErrorActionPreference = 'Stop'
116248
- (New-Object System.Security.AccessControl.RawSecurityDescriptor("O:$env:LA_SID")).GetSddlForm('Owner')
116249
- `;
116250
116329
  var CURRENT_USER_SID_SCRIPT = "[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value";
116251
116330
  var ACE_TYPES = new Set([
116252
116331
  "A",
@@ -116332,10 +116411,9 @@ var parseSddl = (sddl) => {
116332
116411
  }
116333
116412
  return { sddl, owner, protected: tokens.includes("P"), flags: tokens.join(""), aces };
116334
116413
  };
116335
- var exactDaclVerdict = (dacl, userSid, kind, userAlias) => {
116336
- const isUser = (token) => token === userSid || userAlias !== undefined && token === userAlias;
116414
+ var exactDaclVerdict = (dacl, userSid, kind) => {
116337
116415
  const [ace, ...others] = dacl.aces;
116338
- return isUser(dacl.owner) && dacl.flags === "PAI" && ace !== undefined && others.length === 0 && ace.type === "A" && ace.flags === (kind === "dir" ? "OICI" : "") && ace.rights === "FA" && ace.objectGuid === "" && ace.inheritObjectGuid === "" && isUser(ace.sid) && ace.extra === undefined;
116416
+ return dacl.owner === userSid && dacl.flags === "PAI" && ace !== undefined && others.length === 0 && ace.type === "A" && ace.flags === (kind === "dir" ? "OICI" : "") && ace.rights === "FA" && ace.objectGuid === "" && ace.inheritObjectGuid === "" && ace.sid === userSid && ace.extra === undefined;
116339
116417
  };
116340
116418
  var currentUserSid = async (run = runPowerShell) => {
116341
116419
  const { code, out } = await run(CURRENT_USER_SID_SCRIPT, {});
@@ -116344,16 +116422,6 @@ var currentUserSid = async (run = runPowerShell) => {
116344
116422
  throw new LocalApiError("insecure_state_dir", "the user SID is unreadable");
116345
116423
  return sid;
116346
116424
  };
116347
- var userSidToken = async (userSid, run = runPowerShell) => {
116348
- const { code, out } = await run(SID_TOKEN_SCRIPT, { LA_SID: userSid });
116349
- const match = code === 0 ? /^O:(S-1-\d+(?:-\d+)+|[A-Z]{2})$/.exec(out.trim()) : null;
116350
- return match?.[1];
116351
- };
116352
- var applyExactDacl = async (path, userSid, kind, run = runPowerShell) => {
116353
- const { code, err } = await run(APPLY, { LA_PATH: path, LA_SID: userSid, LA_KIND: kind });
116354
- if (code !== 0)
116355
- throw new LocalApiError("insecure_state_dir", `the exact DACL could not be applied${firstErrorLine(err)}`);
116356
- };
116357
116425
  var describeDacl = async (path, run = runPowerShell) => {
116358
116426
  const { code, out } = await run(DESCRIBE_DACL_SCRIPT, { LA_PATH: path });
116359
116427
  const dacl = code === 0 ? parseSddl(out.trim()) : undefined;
@@ -116361,51 +116429,16 @@ var describeDacl = async (path, run = runPowerShell) => {
116361
116429
  throw new LocalApiError("insecure_state_dir", "the DACL could not be read back");
116362
116430
  return dacl;
116363
116431
  };
116364
- var verifyExactDacl = async (path, userSid, kind, run = runPowerShell) => {
116365
- let dacl;
116366
- try {
116367
- dacl = await describeDacl(path, run);
116368
- } catch (error) {
116369
- if (error instanceof LocalApiError)
116370
- return false;
116371
- throw error;
116372
- }
116373
- return exactDaclVerdict(dacl, userSid, kind, await userSidToken(userSid, run));
116374
- };
116375
- var windowsSecureFile = (userSid, run = runPowerShell) => async (path, kind) => {
116376
- const target = kind === "dir" ? "dir" : "file";
116377
- await applyExactDacl(path, userSid, target, run);
116378
- if (!await verifyExactDacl(path, userSid, target, run))
116379
- throw new LocalApiError("insecure_state_dir", "the DACL is not exactly one ACE for the user");
116380
- };
116381
116432
 
116382
116433
  // packages/device-service-core/src/local-api/access.ts
116383
116434
  var TOKEN_FILE = "token";
116384
116435
  var TOKEN_BYTES = 32;
116385
- var NONCE_BYTES = 32;
116386
116436
  var SOCKET_FILE = "service.sock";
116387
- var base64url2 = (bytes) => Buffer.from(bytes).toString("base64url");
116388
- var mintNonce = () => base64url2(randomBytes7(NONCE_BYTES));
116389
- var mintId = () => base64url2(randomBytes7(16));
116390
116437
  var insecure = (detail) => {
116391
116438
  throw new LocalApiError("insecure_state_dir", detail);
116392
116439
  };
116393
- var decoded = (value, bytes, what) => {
116394
- const out = Buffer.from(value, "base64url");
116395
- if (out.length !== bytes || base64url2(out) !== value)
116396
- throw new LocalApiError("protocol_violation", `${what} is not ${bytes} base64url bytes`);
116397
- return out;
116398
- };
116399
116440
  var UNIX_ENDPOINT = "unix";
116400
116441
  var tcpEndpoint = (port) => `tcp:${port}`;
116401
- var proof = (token, label, nonce, endpoint) => base64url2(createHmac2("sha256", token).update(label).update(decoded(nonce, NONCE_BYTES, "a nonce")).update(endpoint, "utf8").digest());
116402
- var serverProof = (token, clientNonce, endpoint) => proof(token, "server", clientNonce, endpoint);
116403
- var clientProof = (token, serverNonce, endpoint) => proof(token, "client", serverNonce, endpoint);
116404
- var proofMatches = (expected, actual) => {
116405
- const a = Buffer.from(expected);
116406
- const b = Buffer.from(actual);
116407
- return a.length === b.length && timingSafeEqual2(a, b);
116408
- };
116409
116442
  var isMissing = (error) => typeof error === "object" && error !== null && ("code" in error) && (error.code === "ENOENT" || error.code === "ENOTDIR");
116410
116443
  var currentUid = () => process.getuid?.() ?? insecure("this platform has no uid");
116411
116444
  var privateEntry = (path, kind, uid, checkMode = true) => {
@@ -116447,7 +116480,7 @@ var readToken = (stateDir) => {
116447
116480
  throw error;
116448
116481
  }
116449
116482
  try {
116450
- return decoded(value, TOKEN_BYTES, "the token");
116483
+ return decodedBytes(value, TOKEN_BYTES, "the token");
116451
116484
  } catch (error) {
116452
116485
  if (error instanceof LocalApiError)
116453
116486
  return insecure("the token is malformed");
@@ -116459,31 +116492,45 @@ var readToken = (stateDir) => {
116459
116492
  import { createHash as createHash16 } from "node:crypto";
116460
116493
 
116461
116494
  // packages/device-service-core/src/local-api/spec-proto.ts
116495
+ class ProtoError extends Error {
116496
+ code;
116497
+ constructor(code, detail) {
116498
+ super(`${code}: ${detail}`);
116499
+ this.code = code;
116500
+ this.name = "ProtoError";
116501
+ }
116502
+ }
116462
116503
  var SESSION_BLOB_MAX = 16777216;
116463
- var SESSION_COMMAND_TEXT_MAX_CHARS = 1e6;
116464
- var SESSION_COMMAND_TEXT_MAX_BYTES = 3000000;
116504
+ var SESSION_KIND_MAX_CHARS = 32;
116505
+ var SESSION_ID_MAX_CHARS = 128;
116465
116506
  var SESSION_DEVICE_MAX_CHARS = 64;
116466
116507
  var SESSION_PROJECT_MAX_CHARS = 256;
116467
- var SESSION_ID_MAX_CHARS = 128;
116468
- var SESSION_KIND_MAX_CHARS = 32;
116469
116508
  var SESSION_READ_TAIL_MAX = 200;
116470
116509
  var SESSION_SUMMARY_TITLE_MAX_CHARS = 256;
116471
116510
  var SESSION_SUMMARY_PROJECT_MAX_CHARS = 128;
116472
116511
  var SESSION_SUMMARY_PATH_MAX_CHARS = 1024;
116473
-
116474
- class ProtoError extends Error {
116475
- code;
116476
- constructor(code, message) {
116477
- super(message);
116478
- this.code = code;
116479
- }
116480
- }
116481
- var validateCommandText = (text) => {
116482
- if (typeof text !== "string" || !text.isWellFormed())
116483
- throw new ProtoError("malformed", "command text");
116484
- if (text.length > SESSION_COMMAND_TEXT_MAX_CHARS || new TextEncoder().encode(text).length > SESSION_COMMAND_TEXT_MAX_BYTES)
116485
- throw new ProtoError("payload_too_large", "session command text over the limit");
116486
- return text;
116512
+ var SESSION_MODEL_PROVIDER_MAX_CHARS = 64;
116513
+ var SESSION_MODEL_ID_MAX_CHARS = 128;
116514
+ var SESSION_SETTLED_DAYS_MAX = 36500;
116515
+ var SESSION_SETTLED_THREAD_TITLE_MAX_CHARS = 256;
116516
+ var SESSION_KEY_CHARS = 22;
116517
+ var UNSAFE_KEYS2 = ["__proto__", "constructor", "prototype"];
116518
+ var sessionFail = (detail) => {
116519
+ throw new ProtoError("bad_request", `session payload ${detail}`);
116520
+ };
116521
+ var B64URL = /^[A-Za-z0-9_-]+$/;
116522
+ var base64UrlId = (v, n, detail) => typeof v === "string" && v.length === n && B64URL.test(v) ? v : sessionFail(detail);
116523
+ var sessionKeyOf = (v) => base64UrlId(v, SESSION_KEY_CHARS, "session key");
116524
+ var safeKey = (key, detail) => UNSAFE_KEYS2.includes(key) ? sessionFail(detail) : key;
116525
+ var STREAM_INLINE_MAX = 12000;
116526
+ var validateStreamSessionKey = (v) => sessionKeyOf(v);
116527
+ var validRosterDeviceId = (value) => typeof value === "string" && value.length > 0 && value.length <= 64 && value.isWellFormed();
116528
+ var METHOD = /^(?=.{1,64}$)[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/;
116529
+ var methodOf = (v, what) => {
116530
+ const type = typeof v === "string" && METHOD.test(v) ? v : sessionFail(what);
116531
+ for (const segment of type.split("."))
116532
+ safeKey(segment, what);
116533
+ return type;
116487
116534
  };
116488
116535
 
116489
116536
  // packages/device-service-core/src/local-api/limits.ts
@@ -116491,6 +116538,10 @@ var LOCAL_INLINE_MAX = 524288;
116491
116538
  var LOCAL_CHUNK_MAX = 262144;
116492
116539
  var LOCAL_JSON_EXPANSION_MAX = 6;
116493
116540
  var LOCAL_BLOB_MAX = LOCAL_JSON_EXPANSION_MAX * SESSION_BLOB_MAX;
116541
+ var MACHINE_UPLOAD_MAX_BYTES = 3840000;
116542
+ var MACHINE_UPLOAD_PARTS_MAX = Math.ceil(MACHINE_UPLOAD_MAX_BYTES / LOCAL_CHUNK_MAX);
116543
+ var grouped = (n) => n.toLocaleString("en-US");
116544
+ var MACHINE_UPLOAD_LIMIT = `an uploaded batch is at most ${grouped(MACHINE_UPLOAD_MAX_BYTES)} bytes (${MACHINE_UPLOAD_PARTS_MAX} parts of ${grouped(LOCAL_CHUNK_MAX)} bytes)`;
116494
116545
  var encoder2 = new TextEncoder;
116495
116546
  var lineBytes = (value) => encoder2.encode(JSON.stringify(value)).length + 1;
116496
116547
  var sha256Hex = (data) => createHash16("sha256").update(data).digest("hex");
@@ -116499,7 +116550,7 @@ var chunkPayload = (data) => {
116499
116550
  for (let off = 0;off < data.length; off += LOCAL_CHUNK_MAX)
116500
116551
  chunks.push({
116501
116552
  off,
116502
- b: Buffer.from(data.subarray(off, off + LOCAL_CHUNK_MAX)).toString("base64")
116553
+ b: toBase64(data.subarray(off, off + LOCAL_CHUNK_MAX))
116503
116554
  });
116504
116555
  return chunks;
116505
116556
  };
@@ -116522,8 +116573,10 @@ var STATUS_STATES = [
116522
116573
  "authorization_stale",
116523
116574
  "service_degraded",
116524
116575
  "update_required",
116525
- "signed_out"
116576
+ "signed_out",
116577
+ "fail_closed"
116526
116578
  ];
116579
+ var STATUS_UPDATE_PHASES = ["trial", "committed"];
116527
116580
  var POLICY_STATES = ["off", "pending", "active"];
116528
116581
  var THIS_DEVICE_STATES = [
116529
116582
  "unclassified",
@@ -116549,9 +116602,26 @@ var ROUND_DEVICE_STATES = [
116549
116602
  var LISTING_SOURCES = ["live", "cache"];
116550
116603
  var SESSION_ROW_STATES = ["running", "idle", "ended"];
116551
116604
  var FILTER_KEYS = ["device", "project", "state"];
116605
+ var LISTING_SETTLED_BY_KINDS = [
116606
+ "user",
116607
+ "agent",
116608
+ "pr-merged",
116609
+ "pr-closed",
116610
+ "inactivity"
116611
+ ];
116552
116612
  var BLOB_OF = ["state", "record", "entry"];
116553
- var BLOB_ABORT_REASONS = ["digest_mismatch", "source_gone", "too_large", "detached"];
116554
- var UPLOAD_ABORT_REASONS = ["message_too_long", "parts_conflict", "malformed", "detached"];
116613
+ var BLOB_ABORT_REASONS = [
116614
+ "digest_mismatch",
116615
+ "source_gone",
116616
+ "too_large",
116617
+ "detached"
116618
+ ];
116619
+ var UPLOAD_ABORT_REASONS = [
116620
+ "message_too_long",
116621
+ "parts_conflict",
116622
+ "malformed",
116623
+ "detached"
116624
+ ];
116555
116625
  var DETACH_REASONS = [
116556
116626
  "authorization_expired",
116557
116627
  "activation_pending",
@@ -116564,6 +116634,14 @@ var DETACH_REASONS = [
116564
116634
  "session_closed",
116565
116635
  "session_replaced"
116566
116636
  ];
116637
+ var UPDATE_NOTICE_PHASES = [
116638
+ "draining",
116639
+ "final",
116640
+ "updated",
116641
+ "rolled_back",
116642
+ "failed"
116643
+ ];
116644
+ var UPDATE_POLICIES = ["defer", "force", "ask"];
116567
116645
  var ATTACH_PENDING_REASONS = ["stream_key_pending"];
116568
116646
  var COMMAND_ID_CHARS = 22;
116569
116647
  var COMMAND_STATES = [
@@ -116588,7 +116666,8 @@ var COMMAND_UNCERTAIN_REASONS = [
116588
116666
  "cancelled",
116589
116667
  "hand_restarted",
116590
116668
  "result_expired",
116591
- "record_too_large"
116669
+ "record_too_large",
116670
+ "result_undecodable"
116592
116671
  ];
116593
116672
  var COMMAND_REFUSAL_REASONS = [
116594
116673
  "parts_conflict",
@@ -116606,9 +116685,15 @@ var COMMAND_REFUSAL_REASONS = [
116606
116685
  "scope_unknown",
116607
116686
  "scope_closed",
116608
116687
  "epoch_fenced",
116609
- "epoch_step_exceeded"
116688
+ "epoch_step_exceeded",
116689
+ "route_unlisted",
116690
+ "rate_limited",
116691
+ "unknown_reason"
116692
+ ];
116693
+ var RETRYABLE_STATES = [
116694
+ "not confirmed",
116695
+ "not delivered: never_sent"
116610
116696
  ];
116611
- var RETRYABLE_STATES = ["not confirmed", "not delivered: never_sent"];
116612
116697
  var ERROR_CODES = [
116613
116698
  "unauthenticated",
116614
116699
  "client_proof_invalid",
@@ -116630,6 +116715,7 @@ var ERROR_CODES = [
116630
116715
  "peer_not_found",
116631
116716
  "peer_not_session_client",
116632
116717
  "session_not_found",
116718
+ "session_ambiguous",
116633
116719
  "engine_too_old",
116634
116720
  "not_attached",
116635
116721
  "command_id_conflict",
@@ -116642,6 +116728,13 @@ var ERROR_CODES = [
116642
116728
  "unsupported",
116643
116729
  "unknown_delivery"
116644
116730
  ];
116731
+ var ALIAS_INCOMPLETE_REASONS = [
116732
+ "cache",
116733
+ "timed_out",
116734
+ "undelivered",
116735
+ "skipped",
116736
+ "stopped"
116737
+ ];
116645
116738
  var PATH_REFUSAL_PROBLEMS = [
116646
116739
  "not_absolute",
116647
116740
  "not_found",
@@ -116652,6 +116745,16 @@ var PATH_REFUSAL_PROBLEMS = [
116652
116745
  "world_writable",
116653
116746
  "windows_acl"
116654
116747
  ];
116748
+ var MACHINE_OP_STATES = [
116749
+ "queued",
116750
+ "transport_confirmed",
116751
+ "host_dispatched",
116752
+ "host_applied",
116753
+ "link_down"
116754
+ ];
116755
+ var MACHINE_STATES = ["online", "offline", "unsupported"];
116756
+ var MACHINE_LOOKUP_STATES = ["in_flight", "terminal", "unknown"];
116757
+ var MACHINE_BLOB_ABORT_REASONS = ["digest_mismatch", "source_gone", "too_large"];
116655
116758
  var CHANNEL_CLOSED_REASONS = [
116656
116759
  "event_overflow",
116657
116760
  "event_too_large",
@@ -116731,11 +116834,18 @@ var sha256Field = (v, what) => typeof v === "string" && SHA256_HEX.test(v) ? v :
116731
116834
  var base64Bytes = (v, max, what) => {
116732
116835
  if (typeof v !== "string" || v.length === 0 || v.length > 4 * Math.ceil(max / 3))
116733
116836
  return fail(what);
116734
- const bytes = Buffer.from(v, "base64");
116735
- return bytes.length <= max && bytes.toString("base64") === v ? new Uint8Array(bytes) : fail(what);
116837
+ let bytes;
116838
+ try {
116839
+ bytes = fromBase64(v);
116840
+ } catch (error) {
116841
+ if (error instanceof Error)
116842
+ return fail(what);
116843
+ throw error;
116844
+ }
116845
+ return bytes.length <= max && toBase64(bytes) === v ? bytes : fail(what);
116736
116846
  };
116737
- var UNSAFE_KEYS2 = ["__proto__", "constructor", "prototype"];
116738
- var safeKey = (key, what) => UNSAFE_KEYS2.includes(key) ? fail(what) : key;
116847
+ var UNSAFE_KEYS3 = ["__proto__", "constructor", "prototype"];
116848
+ var safeKey2 = (key, what) => UNSAFE_KEYS3.includes(key) ? fail(what) : key;
116739
116849
  var jsonValue = (v, what) => {
116740
116850
  if (v === null || typeof v === "boolean" || typeof v === "string")
116741
116851
  return v;
@@ -116755,9 +116865,20 @@ var jsonObject = (v, what) => {
116755
116865
  out[key] = jsonValue(item, what);
116756
116866
  return out;
116757
116867
  };
116868
+ // packages/device-service-core/src/local-api/command-text.ts
116869
+ var COMMAND_TEXT_MAX_CHARS = 1e6;
116870
+ var COMMAND_TEXT_MAX_BYTES = 3000000;
116871
+ var validateCommandText = (text) => {
116872
+ if (typeof text !== "string" || !text.isWellFormed())
116873
+ throw new ProtoError("bad_request", "session payload command text");
116874
+ if (text.length > COMMAND_TEXT_MAX_CHARS || new TextEncoder().encode(text).length > COMMAND_TEXT_MAX_BYTES)
116875
+ throw new ProtoError("payload_too_large", "session command text over the limit");
116876
+ return text;
116877
+ };
116878
+
116758
116879
  // packages/device-service-core/src/local-api/upload.ts
116759
- var MESSAGE_LIMIT_CHARS = SESSION_COMMAND_TEXT_MAX_CHARS;
116760
- var LOCAL_UPLOAD_PARTS_MAX = Math.ceil(SESSION_COMMAND_TEXT_MAX_BYTES / LOCAL_CHUNK_MAX);
116880
+ var MESSAGE_LIMIT_CHARS = COMMAND_TEXT_MAX_CHARS;
116881
+ var LOCAL_UPLOAD_PARTS_MAX = Math.ceil(COMMAND_TEXT_MAX_BYTES / LOCAL_CHUNK_MAX);
116761
116882
  var checkCommandText = (value) => {
116762
116883
  try {
116763
116884
  validateCommandText(value);
@@ -116791,7 +116912,7 @@ class LocalBlobAssembler {
116791
116912
  return;
116792
116913
  case "session.blob_chunk": {
116793
116914
  const open = this.#current(event.id);
116794
- const data = Buffer.from(event.b, "base64");
116915
+ const data = fromBase64(event.b);
116795
116916
  const end = this.#received + data.length;
116796
116917
  if (event.off !== this.#received || end > open.bytes)
116797
116918
  return protocolViolation("blob chunk out of order");
@@ -116898,6 +117019,107 @@ class ListingTracker {
116898
117019
  }
116899
117020
  }
116900
117021
 
117022
+ // packages/device-service-core/src/local-api/session-ref.ts
117023
+ var KEY_CHARS = 22;
117024
+ var MIN_CHARS = KEY_CHARS + 2;
117025
+ var MAX_CHARS = KEY_CHARS + 65;
117026
+ var isStreamSessionKey = (v) => {
117027
+ try {
117028
+ validateStreamSessionKey(v);
117029
+ return true;
117030
+ } catch (error) {
117031
+ if (error instanceof ProtoError)
117032
+ return false;
117033
+ throw error;
117034
+ }
117035
+ };
117036
+ var parseSessionRef = (v) => {
117037
+ if (typeof v !== "string" || !v.isWellFormed())
117038
+ return;
117039
+ if (v.length < MIN_CHARS || v.length > MAX_CHARS || v[v.length - KEY_CHARS - 1] !== ".")
117040
+ return;
117041
+ const device = v.slice(0, -KEY_CHARS - 1);
117042
+ const key = v.slice(-KEY_CHARS);
117043
+ return isStreamSessionKey(key) && validRosterDeviceId(device) ? { device, key } : undefined;
117044
+ };
117045
+ var formatSessionRef = (ref) => {
117046
+ if (!isStreamSessionKey(ref.key) || !validRosterDeviceId(ref.device))
117047
+ throw new RangeError("not a session id: the device or the key is malformed");
117048
+ return `${ref.device}.${ref.key}`;
117049
+ };
117050
+ var CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
117051
+ var ALIAS_MAX_CHARS = 256;
117052
+ var unsafeAlias = (s) => s !== s.trim() || CONTROL.test(s) || parseSessionRef(s) !== undefined || isStreamSessionKey(s);
117053
+
117054
+ // packages/device-service-core/src/local-api/validate-snapshot-from.ts
117055
+ var SNAPSHOT_OPTIONAL_FIELDS = ["from"];
117056
+ var snapshotFromOf = (v) => {
117057
+ const m = known(v, ["last_entry_id", "delta"], [], "from");
117058
+ return {
117059
+ last_entry_id: entryId(m["last_entry_id"], "from.last_entry_id"),
117060
+ delta: bool(m["delta"], "from.delta")
117061
+ };
117062
+ };
117063
+
117064
+ // packages/device-service-core/src/local-api/protocol-status.ts
117065
+ var SIGN_IN_REASONS = ["not_adopted", "device_revoked", "reauth_required"];
117066
+
117067
+ // packages/device-service-core/src/local-api/validate-session-answer.ts
117068
+ var refOf = (v, what) => {
117069
+ const m = known(v, ["device", "key", "session"], [], what);
117070
+ const ref = parseSessionRef(m["session"]);
117071
+ if (ref === undefined || ref.device !== m["device"] || ref.key !== m["key"])
117072
+ return fail(what);
117073
+ return { device: ref.device, key: ref.key, session: formatSessionRef(ref) };
117074
+ };
117075
+ var commandAnswerOf = (v) => {
117076
+ const m = known(v, ["command_id"], ["device", "key", "session"], "session.command data");
117077
+ const command_id = commandId(m["command_id"]);
117078
+ if (m["device"] === undefined && m["key"] === undefined && m["session"] === undefined)
117079
+ return { command_id };
117080
+ const { device, key, session } = m;
117081
+ return { command_id, ...refOf({ device, key, session }, "session.command data") };
117082
+ };
117083
+ var listOf = (v, item, what) => Array.isArray(v) ? v.map(item) : fail(what);
117084
+ var incompleteOf = (v) => {
117085
+ const m = known(v, ["device", "reason"], [], "error.incomplete");
117086
+ const device = m["device"];
117087
+ if (typeof device !== "string" || device.length === 0)
117088
+ return fail("error.incomplete");
117089
+ return { device, reason: oneOf(ALIAS_INCOMPLETE_REASONS, m["reason"], "error.incomplete") };
117090
+ };
117091
+ var aliasErrorFields = (code, m) => {
117092
+ const { candidates, incomplete } = m;
117093
+ if (candidates !== undefined !== (code === "session_ambiguous"))
117094
+ return fail("error.candidates");
117095
+ if (incomplete !== undefined && code !== "session_not_found")
117096
+ return fail("error.incomplete");
117097
+ return {
117098
+ ...candidates === undefined ? {} : {
117099
+ candidates: listOf(candidates, (c) => refOf(c, "error.candidates"), "error.candidates")
117100
+ },
117101
+ ...incomplete === undefined ? {} : { incomplete: listOf(incomplete, incompleteOf, "error.incomplete") }
117102
+ };
117103
+ };
117104
+
117105
+ // packages/device-service-core/src/local-api/validate-update.ts
117106
+ var READY_REASON_MAX_CHARS = 64;
117107
+ var statusUpdateOf = (v) => {
117108
+ const m = known(v, ["update_id", "phase", "target_version", "ready", "ready_reason"], [], "status.update");
117109
+ return {
117110
+ update_id: localId(m["update_id"], "status.update.update_id"),
117111
+ phase: oneOf(STATUS_UPDATE_PHASES, m["phase"], "status.update.phase"),
117112
+ target_version: semver(m["target_version"], "status.update.target_version"),
117113
+ ready: bool(m["ready"], "status.update.ready"),
117114
+ ready_reason: nullable2(m["ready_reason"], (r) => text(r, READY_REASON_MAX_CHARS, "status.update.ready_reason"))
117115
+ };
117116
+ };
117117
+ var updateCommittedOf = (m, id) => ({
117118
+ id,
117119
+ type: "owner.update_committed",
117120
+ update_id: localId(m["update_id"], "update_id")
117121
+ });
117122
+
116901
117123
  // packages/device-service-core/src/local-api/validate-shapes.ts
116902
117124
  var CODE = /^[a-z_]{1,64}$/;
116903
117125
  var ATTACH_ID_MAX = 4294967295;
@@ -116934,9 +117156,8 @@ var policyOf = (v) => {
116934
117156
  };
116935
117157
  };
116936
117158
  var statusOf = (v) => {
116937
- const m = known(v, ["state", "since_ms", "device", "origin_configured", "enabled"], ["detail", "policy"], "status");
116938
- const detail = m["detail"];
116939
- const policy = m["policy"];
117159
+ const m = known(v, ["state", "since_ms", "device", "origin_configured", "enabled"], ["detail", "policy", "update", "exe"], "status");
117160
+ const { detail, policy, update, exe } = m;
116940
117161
  return {
116941
117162
  state: oneOf(STATUS_STATES, m["state"], "status.state"),
116942
117163
  since_ms: millis(m["since_ms"], "status.since_ms"),
@@ -116944,60 +117165,41 @@ var statusOf = (v) => {
116944
117165
  device: nullable2(m["device"], (d) => deviceRef(d, "status.device", known)),
116945
117166
  origin_configured: bool(m["origin_configured"], "status.origin_configured"),
116946
117167
  enabled: bool(m["enabled"], "status.enabled"),
116947
- ...policy === undefined ? {} : { policy: policyOf(policy) }
117168
+ ...policy === undefined ? {} : { policy: policyOf(policy) },
117169
+ ...update === undefined ? {} : { update: statusUpdateOf(update) },
117170
+ ...exe === undefined ? {} : { exe: absolutePath(exe, "status.exe") }
116948
117171
  };
116949
117172
  };
116950
117173
  var detailOf = (v) => {
116951
- const m = known(v, ["code", "action"], [], "status.detail");
116952
- const code = m["code"];
117174
+ const m = known(v, ["code", "action"], ["sign_in_reason"], "status.detail");
117175
+ const { code, sign_in_reason: reason } = m;
116953
117176
  return {
116954
117177
  code: typeof code === "string" && CODE.test(code) ? code : fail("status.detail.code"),
116955
- action: nullable2(m["action"], (a) => text(a, LABEL_MAX_CHARS, "status.detail.action"))
117178
+ action: nullable2(m["action"], (a) => text(a, LABEL_MAX_CHARS, "status.detail.action")),
117179
+ ...reason === undefined ? {} : { sign_in_reason: oneOf(SIGN_IN_REASONS, reason, "status.detail.sign_in_reason") }
116956
117180
  };
116957
117181
  };
116958
117182
  var deviceRowOf = (v) => {
116959
- const m = known(v, ["device", "label", "kind", "platform", "last_seen_ms", "online"], [], "device row");
117183
+ const m = known(v, ["device", "label", "kind", "platform", "last_seen_ms", "online"], ["managed"], "device row");
117184
+ const managed = m["managed"];
116960
117185
  return {
116961
117186
  device: deviceId(m["device"]),
116962
117187
  label: text(m["label"], LABEL_MAX_CHARS, "label", 0),
116963
117188
  kind: text(m["kind"], 64, "kind", 0),
116964
117189
  platform: text(m["platform"], 64, "platform", 0),
116965
117190
  last_seen_ms: nullable2(m["last_seen_ms"], (t) => millis(t, "last_seen_ms")),
116966
- online: bool(m["online"], "online")
117191
+ online: bool(m["online"], "online"),
117192
+ ...managed === undefined ? {} : { managed: bool(managed, "managed") }
116967
117193
  };
116968
117194
  };
116969
- var ROW_FIELDS = ["device", "session_id", "title", "project", "path", "state", "updated_ms", "source", "as_of"];
116970
- var ROW_KIND = new RegExp(`^[a-z][a-z0-9_-]{0,${SESSION_KIND_MAX_CHARS - 1}}$`);
116971
- var rowLinks = (m) => {
116972
- const kind = m["kind"];
116973
- if (Object.hasOwn(m, "parent") !== Object.hasOwn(m, "parent_listed"))
116974
- fail("parent_listed");
116975
- return {
116976
- ...kind === undefined ? {} : { kind: typeof kind === "string" && ROW_KIND.test(kind) ? kind : fail("row kind") },
116977
- ...m["parent"] === undefined ? {} : {
116978
- parent: sessionId(m["parent"]),
116979
- parent_listed: bool(m["parent_listed"], "parent_listed")
116980
- }
116981
- };
116982
- };
116983
- var listingRowOf = (v) => {
116984
- const m = known(v, ROW_FIELDS, ["kind", "parent", "parent_listed", "durable_id"], "listing row");
116985
- const durable = m["durable_id"];
116986
- return {
116987
- ...rowLinks(m),
116988
- ...durable === undefined ? {} : { durable_id: text(durable, SESSION_ID_MAX_CHARS, "durable_id") },
116989
- device: deviceId(m["device"]),
116990
- session_id: sessionId(m["session_id"]),
116991
- title: text(m["title"], SESSION_SUMMARY_TITLE_MAX_CHARS, "title", 0),
116992
- project: text(m["project"], SESSION_SUMMARY_PROJECT_MAX_CHARS, "project"),
116993
- path: text(m["path"], SESSION_SUMMARY_PATH_MAX_CHARS, "path"),
116994
- state: oneOf(SESSION_ROW_STATES, m["state"], "row state"),
116995
- updated_ms: millis(m["updated_ms"], "updated_ms"),
116996
- source: oneOf(LISTING_SOURCES, m["source"], "row source"),
116997
- as_of: millis(m["as_of"], "as_of")
116998
- };
116999
- };
117000
- var BODY_FIELDS = ["attach_id", "cursor", "state", "entries", "history_truncated", "oldest_entry_id"];
117195
+ var BODY_FIELDS = [
117196
+ "attach_id",
117197
+ "cursor",
117198
+ "state",
117199
+ "entries",
117200
+ "history_truncated",
117201
+ "oldest_entry_id"
117202
+ ];
117001
117203
  var snapshotBodyOf = (m) => {
117002
117204
  const cursor = known(m["cursor"], ["marker_id", "last_entry_id"], [], "cursor");
117003
117205
  const entries = m["entries"];
@@ -117012,10 +117214,11 @@ var snapshotBodyOf = (m) => {
117012
117214
  state: jsonObject(m["state"], "state"),
117013
117215
  entries: entries.map((e) => jsonValue(e, "entries")),
117014
117216
  history_truncated: bool(m["history_truncated"], "history_truncated"),
117015
- oldest_entry_id: nullable2(m["oldest_entry_id"], (e) => entryId(e, "oldest_entry_id"))
117217
+ oldest_entry_id: nullable2(m["oldest_entry_id"], (e) => entryId(e, "oldest_entry_id")),
117218
+ ...m["from"] === undefined ? {} : { from: snapshotFromOf(m["from"]) }
117016
117219
  };
117017
117220
  };
117018
- var snapshotBlobOf = (v) => snapshotBodyOf(known(v, BODY_FIELDS, [], "snapshot"));
117221
+ var snapshotBlobOf = (v) => snapshotBodyOf(known(v, BODY_FIELDS, SNAPSHOT_OPTIONAL_FIELDS, "snapshot"));
117019
117222
  var SNAPSHOT_FIELDS = BODY_FIELDS;
117020
117223
  var readEntryOf = (v) => {
117021
117224
  const m = known(v, ["kind", "entry_id"], ["entry", "bytes", "sha256"], "read entry");
@@ -117042,8 +117245,11 @@ var pathRefusalOf = (v) => {
117042
117245
  };
117043
117246
  };
117044
117247
  var errorBodyOf = (v) => {
117045
- const m = known(v, ["code", "reason", "action"], ["limit_chars", "path_refusal"], "error");
117248
+ const m = known(v, ["code", "reason", "action"], ["limit_chars", "path_refusal", "candidates", "incomplete", "sign_in_reason"], "error");
117046
117249
  const code = oneOf(ERROR_CODES, m["code"], "error.code");
117250
+ const reason = m["sign_in_reason"];
117251
+ if (reason !== undefined && code !== "sign_in_required")
117252
+ return fail("error.sign_in_reason");
117047
117253
  const limit = m["limit_chars"];
117048
117254
  if (code === "message_too_long" !== (limit !== undefined))
117049
117255
  return fail("error.limit_chars");
@@ -117055,78 +117261,12 @@ var errorBodyOf = (v) => {
117055
117261
  reason: text(m["reason"], REASON_MAX_CHARS, "error.reason", 0),
117056
117262
  action: nullable2(m["action"], (a) => text(a, LABEL_MAX_CHARS, "error.action")),
117057
117263
  ...limit === undefined ? {} : { limit_chars: uint(limit, 1, MILLIS_MAX, "error.limit_chars") },
117058
- ...refusal === undefined ? {} : { path_refusal: pathRefusalOf(refusal) }
117264
+ ...refusal === undefined ? {} : { path_refusal: pathRefusalOf(refusal) },
117265
+ ...reason === undefined ? {} : { sign_in_reason: oneOf(SIGN_IN_REASONS, reason, "error.sign_in_reason") },
117266
+ ...aliasErrorFields(code, m)
117059
117267
  };
117060
117268
  };
117061
117269
 
117062
- // packages/device-service-core/src/local-api/validate-command.ts
117063
- var commandRpcOf = (v) => jsonObject(v, "rpc");
117064
- var requestFields = (v, names, optional = []) => exactly(v, ["id", "type", ...names], optional, "request");
117065
- var commandIdField = (v) => v === undefined ? {} : { command_id: commandId(v) };
117066
- var ROUTE_FIELDS = ["command_id", "delegated", "endpoint"];
117067
- var routeFields = (m) => {
117068
- const delegated = m["delegated"];
117069
- if (delegated !== undefined && delegated !== true)
117070
- return fail("delegated");
117071
- return {
117072
- ...delegated === true ? { delegated: true } : {},
117073
- ...m["endpoint"] === undefined ? {} : { endpoint: endpointKey(m["endpoint"]) }
117074
- };
117075
- };
117076
- var COMMAND_REQUEST_VALIDATORS = {
117077
- "session.command": (v, id) => {
117078
- if (Object.hasOwn(v, "device")) {
117079
- const m = requestFields(v, ["device", "endpoint", "rpc"], ["command_id", "locate"]);
117080
- const locate = m["locate"];
117081
- if (locate !== undefined && locate !== true)
117082
- return fail("locate");
117083
- return {
117084
- id,
117085
- type: "session.command",
117086
- device: deviceId(m["device"]),
117087
- endpoint: endpointKey(m["endpoint"]),
117088
- ...commandIdField(m["command_id"]),
117089
- ...locate === true ? { locate: true } : {},
117090
- rpc: commandRpcOf(m["rpc"])
117091
- };
117092
- }
117093
- if (Object.hasOwn(v, "upload_id")) {
117094
- const m = requestFields(v, ["attach", "upload_id"], ROUTE_FIELDS);
117095
- return {
117096
- id,
117097
- type: "session.command",
117098
- attach: localId(m["attach"], "attach"),
117099
- ...commandIdField(m["command_id"]),
117100
- upload_id: localId(m["upload_id"], "upload_id"),
117101
- ...routeFields(m)
117102
- };
117103
- }
117104
- const m = requestFields(v, ["attach", "rpc"], ROUTE_FIELDS);
117105
- return {
117106
- id,
117107
- type: "session.command",
117108
- attach: localId(m["attach"], "attach"),
117109
- ...commandIdField(m["command_id"]),
117110
- rpc: commandRpcOf(m["rpc"]),
117111
- ...routeFields(m)
117112
- };
117113
- },
117114
- "session.command_part": (v, id) => {
117115
- const m = requestFields(v, ["attach", "upload_id", "index", "count", "b"]);
117116
- const count = uint(m["count"], 1, LOCAL_UPLOAD_PARTS_MAX, "count");
117117
- base64Bytes(m["b"], LOCAL_CHUNK_MAX, "b");
117118
- return {
117119
- id,
117120
- type: "session.command_part",
117121
- attach: localId(m["attach"], "attach"),
117122
- upload_id: localId(m["upload_id"], "upload_id"),
117123
- index: uint(m["index"], 0, count - 1, "index"),
117124
- count,
117125
- b: typeof m["b"] === "string" ? m["b"] : fail("b")
117126
- };
117127
- }
117128
- };
117129
-
117130
117270
  // packages/device-service-core/src/local-api/validate-stream-events.ts
117131
117271
  var eventFields = (v, names, optional = []) => known(v, ["type", "kind", ...names], optional, "event");
117132
117272
  var attachOf = (m) => localId(m["attach"], "attach");
@@ -117153,9 +117293,15 @@ var targetOf = (m) => {
117153
117293
  }
117154
117294
  }
117155
117295
  };
117296
+ var seqsOf = (v, count) => {
117297
+ if (!Array.isArray(v) || v.length !== count)
117298
+ return fail("seqs");
117299
+ const seqs = v.map((s) => uint(s, 1, Number.MAX_SAFE_INTEGER, "seq"));
117300
+ return seqs.every((s, i) => i === 0 || s > (seqs[i - 1] ?? s)) ? seqs : fail("seqs order");
117301
+ };
117156
117302
  var STREAM_EVENT_VALIDATORS = {
117157
117303
  "session.snapshot": (v) => {
117158
- const m = eventFields(v, ["attach", ...SNAPSHOT_FIELDS]);
117304
+ const m = eventFields(v, ["attach", ...SNAPSHOT_FIELDS], SNAPSHOT_OPTIONAL_FIELDS);
117159
117305
  return { type: "event", kind: "session.snapshot", attach: attachOf(m), ...snapshotBodyOf(m) };
117160
117306
  },
117161
117307
  "session.snapshot_loading": (v) => {
@@ -117168,7 +117314,7 @@ var STREAM_EVENT_VALIDATORS = {
117168
117314
  };
117169
117315
  },
117170
117316
  "session.records": (v) => {
117171
- const m = eventFields(v, ["attach", "attach_id", "records"]);
117317
+ const m = eventFields(v, ["attach", "attach_id", "records"], ["seqs"]);
117172
117318
  const records = m["records"];
117173
117319
  if (!Array.isArray(records) || records.length === 0)
117174
117320
  return fail("records");
@@ -117178,7 +117324,8 @@ var STREAM_EVENT_VALIDATORS = {
117178
117324
  kind: "session.records",
117179
117325
  attach: attachOf(m),
117180
117326
  attach_id,
117181
- records: records.map((r) => jsonObject(r, "record"))
117327
+ records: records.map((r) => jsonObject(r, "record")),
117328
+ ...m["seqs"] === undefined ? {} : { seqs: seqsOf(m["seqs"], records.length) }
117182
117329
  };
117183
117330
  },
117184
117331
  "session.blob_open": (v) => {
@@ -117242,32 +117389,97 @@ var STREAM_EVENT_VALIDATORS = {
117242
117389
  // packages/device-service-core/src/local-api/validate-delegated.ts
117243
117390
  var ENDPOINT_KEY = /^[A-Za-z0-9_-]{22}$/;
117244
117391
  var ENDPOINTS_MAX = 16;
117392
+ var ENVIRONMENTS_MAX = 4;
117245
117393
  var endpointKey = (v, what = "endpoint") => typeof v === "string" && ENDPOINT_KEY.test(v) ? v : fail(what);
117246
- var ENGINE_ID_MAX_CHARS = 128;
117247
- var engineId = (v) => typeof v === "string" && v.length >= 1 && v.length <= ENGINE_ID_MAX_CHARS && v.isWellFormed() ? v : fail("engine_id");
117394
+ var engineId = (v) => typeof v === "string" && v.length >= 1 && v.length <= SESSION_ID_MAX_CHARS && v.isWellFormed() ? v : fail("engine_id");
117248
117395
  var DELEGATED_REQUEST_VALIDATORS = {
117249
- "session.endpoints": (v, id) => ({
117250
- id,
117251
- type: "session.endpoints",
117252
- device: deviceId(requestFields(v, ["device"])["device"])
117253
- }),
117396
+ "session.endpoints": (v, id) => {
117397
+ const m = requestFields(v, ["device"], ["primary", "environments"]);
117398
+ if (m["primary"] !== undefined && m["primary"] !== true)
117399
+ return fail("primary");
117400
+ if (m["environments"] !== undefined && m["environments"] !== true)
117401
+ return fail("environments");
117402
+ return {
117403
+ id,
117404
+ type: "session.endpoints",
117405
+ device: deviceId(m["device"]),
117406
+ ...m["primary"] === true ? { primary: true } : {},
117407
+ ...m["environments"] === true ? { environments: true } : {}
117408
+ };
117409
+ },
117254
117410
  "session.locate": (v, id) => {
117255
- const m = requestFields(v, ["device", "engine_id"]);
117256
- return { id, type: "session.locate", device: deviceId(m["device"]), engine_id: engineId(m["engine_id"]) };
117411
+ const m = requestFields(v, ["device", "engine_id"], ["single"]);
117412
+ if (m["single"] !== undefined && m["single"] !== true)
117413
+ return fail("single");
117414
+ return {
117415
+ id,
117416
+ type: "session.locate",
117417
+ device: deviceId(m["device"]),
117418
+ engine_id: engineId(m["engine_id"]),
117419
+ ...m["single"] === true ? { single: true } : {}
117420
+ };
117257
117421
  }
117258
117422
  };
117259
- var locateData = (v) => {
117260
- const m = known(v, ["device", "key", "session"], [], "data");
117261
- const device = deviceId(m["device"]);
117262
- const key = endpointKey(m["key"], "key");
117263
- return m["session"] === `${device}.${key}` ? { device, key, session: `${device}.${key}` } : fail("session");
117423
+ var keysOf2 = (v, max, what) => {
117424
+ if (!Array.isArray(v) || v.length > max)
117425
+ return fail(what);
117426
+ const keys = v.map((e) => endpointKey(e, what));
117427
+ return new Set(keys).size === keys.length ? keys : fail(what);
117264
117428
  };
117265
117429
  var endpointsData = (v) => {
117266
- const endpoints = known(v, ["endpoints"], [], "data")["endpoints"];
117267
- if (!Array.isArray(endpoints) || endpoints.length > ENDPOINTS_MAX)
117268
- return fail("endpoints");
117269
- const keys = endpoints.map((e) => endpointKey(e, "endpoints"));
117270
- return new Set(keys).size === keys.length ? { endpoints: keys } : fail("endpoints");
117430
+ const m = known(v, ["endpoints"], ["environments", "primary"], "data");
117431
+ const endpoints = keysOf2(m["endpoints"], ENDPOINTS_MAX, "endpoints");
117432
+ const primary = m["primary"] === undefined ? undefined : endpointKey(m["primary"], "primary");
117433
+ if (primary !== undefined && !endpoints.includes(primary))
117434
+ return fail("primary");
117435
+ return {
117436
+ endpoints,
117437
+ ...m["environments"] === undefined ? {} : { environments: keysOf2(m["environments"], ENVIRONMENTS_MAX, "environments") },
117438
+ ...primary === undefined ? {} : { primary }
117439
+ };
117440
+ };
117441
+ var agentDirOf = (v) => absolutePath(requestFields(v, ["agent_dir"])["agent_dir"], "agent_dir");
117442
+ var environmentOf = (v, required) => {
117443
+ const m = requestFields(v, required);
117444
+ return m["kind"] === "environment" ? m : fail("kind");
117445
+ };
117446
+ var endpointsRegister = (v, id) => {
117447
+ if (v["kind"] === undefined)
117448
+ return { id, type: "endpoints.register", agent_dir: agentDirOf(v) };
117449
+ const m = environmentOf(v, ["kind", "socket", "key_root"]);
117450
+ return {
117451
+ id,
117452
+ type: "endpoints.register",
117453
+ kind: "environment",
117454
+ socket: absolutePath(m["socket"], "socket"),
117455
+ key_root: absolutePath(m["key_root"], "key_root")
117456
+ };
117457
+ };
117458
+ var endpointsUnregister = (v, id) => {
117459
+ if (v["kind"] === undefined)
117460
+ return { id, type: "endpoints.unregister", agent_dir: agentDirOf(v) };
117461
+ const m = environmentOf(v, ["kind", "socket"]);
117462
+ return {
117463
+ id,
117464
+ type: "endpoints.unregister",
117465
+ kind: "environment",
117466
+ socket: absolutePath(m["socket"], "socket")
117467
+ };
117468
+ };
117469
+ var endpointsList = (v, id) => {
117470
+ requestFields(v, []);
117471
+ return { id, type: "endpoints.list" };
117472
+ };
117473
+ var endpointsListData = (m) => {
117474
+ const dirs = m["agent_dirs"];
117475
+ if (!Array.isArray(dirs))
117476
+ return fail("agent_dirs");
117477
+ return { agent_dirs: dirs.map((d) => absolutePath(d, "agent_dirs")) };
117478
+ };
117479
+ var endpointRequests = {
117480
+ "endpoints.register": endpointsRegister,
117481
+ "endpoints.unregister": endpointsUnregister,
117482
+ "endpoints.list": endpointsList
117271
117483
  };
117272
117484
  var blobId = (m) => localId(m["id"], "blob id");
117273
117485
  var blobRefOf = (v) => {
@@ -117280,7 +117492,9 @@ var blobRefOf = (v) => {
117280
117492
  };
117281
117493
  var locatedOf = (device, v) => {
117282
117494
  const m = known(v, ["key", "session"], [], "located");
117283
- const key = endpointKey(m["key"], "located key");
117495
+ const key = m["key"];
117496
+ if (typeof key !== "string" || !isStreamSessionKey(key))
117497
+ return fail("located key");
117284
117498
  return m["session"] === `${device}.${key}` ? { key, session: `${device}.${key}` } : fail("located session");
117285
117499
  };
117286
117500
  var COMMAND_EVENT_FIELDS = ["blob", "frame", "command_id", "response", "located"];
@@ -117337,6 +117551,451 @@ var DELEGATED_EVENT_VALIDATORS = {
117337
117551
  }
117338
117552
  };
117339
117553
 
117554
+ // packages/device-service-core/src/local-api/validate-command.ts
117555
+ var commandRpcOf = (v) => jsonObject(v, "rpc");
117556
+ var requestFields = (v, names, optional = []) => exactly(v, ["id", "type", ...names], optional, "request");
117557
+ var acceptsField = (v) => {
117558
+ if (v === undefined)
117559
+ return {};
117560
+ if (!Array.isArray(v) || v.length !== 1 || v[0] !== "session-wake:v1")
117561
+ return fail("accepts");
117562
+ return { accepts: ["session-wake:v1"] };
117563
+ };
117564
+ var commandIdField = (v) => v === undefined ? {} : { command_id: commandId(v) };
117565
+ var ROUTE_FIELDS = ["command_id", "delegated", "endpoint", "locate"];
117566
+ var routeFields = (m) => {
117567
+ const delegated = m["delegated"];
117568
+ if (delegated !== undefined && delegated !== true)
117569
+ return fail("delegated");
117570
+ const locate = m["locate"];
117571
+ if (locate !== undefined && locate !== true)
117572
+ return fail("locate");
117573
+ return {
117574
+ ...delegated === true ? { delegated: true } : {},
117575
+ ...locate === true ? { locate: true } : {},
117576
+ ...m["endpoint"] === undefined ? {} : { endpoint: endpointKey(m["endpoint"]) }
117577
+ };
117578
+ };
117579
+ var TARGETS = ["attach", "device", "session", "alias", "wake"];
117580
+ var targetField = (v) => {
117581
+ const named = TARGETS.filter((f) => Object.hasOwn(v, f));
117582
+ const [only] = named;
117583
+ return named.length === 1 && only !== undefined ? only : fail("request names one target");
117584
+ };
117585
+ var TARGET_FIELDS = {
117586
+ attach: ["attach"],
117587
+ device: ["device", "endpoint"],
117588
+ session: ["session"],
117589
+ alias: ["alias"],
117590
+ wake: ["wake"]
117591
+ };
117592
+ var sessionField = (v) => typeof v === "string" && parseSessionRef(v) !== undefined ? v : fail("session");
117593
+ var aliasField = (v) => typeof v === "string" && v.length >= 1 && v.length <= ALIAS_MAX_CHARS && v.isWellFormed() && !unsafeAlias(v) ? v : fail("alias");
117594
+ var wakeField = (v) => {
117595
+ const m = exactly(v, ["device", "durable_id"], [], "wake");
117596
+ return { device: deviceId(m["device"], "wake.device"), durable_id: durableId(m["durable_id"]) };
117597
+ };
117598
+ var oneField = (m, field) => {
117599
+ switch (field) {
117600
+ case "attach":
117601
+ return { attach: localId(m["attach"], "attach") };
117602
+ case "session":
117603
+ return { session: sessionField(m["session"]) };
117604
+ case "alias":
117605
+ return { alias: aliasField(m["alias"]) };
117606
+ case "wake":
117607
+ return { wake: wakeField(m["wake"]) };
117608
+ }
117609
+ };
117610
+ var targetOf2 = (m, field) => field === "device" ? { device: deviceId(m["device"]), endpoint: endpointKey(m["endpoint"]) } : oneField(m, field);
117611
+ var partTargetOf = (m, field) => field === "device" ? { device: deviceId(m["device"]) } : oneField(m, field);
117612
+ var COMMAND_REQUEST_VALIDATORS = {
117613
+ "session.command": (v, id) => {
117614
+ const field = targetField(v);
117615
+ if (field !== "device" && Object.hasOwn(v, "locate"))
117616
+ return fail("locate acts only on a device and endpoint command");
117617
+ const target = TARGET_FIELDS[field];
117618
+ const body = Object.hasOwn(v, "upload_id") ? "upload_id" : "rpc";
117619
+ const delegated = field === "session" || field === "alias" || field === "wake";
117620
+ const optional = [
117621
+ ...delegated ? ["command_id"] : ROUTE_FIELDS.filter((f) => !target.includes(f)),
117622
+ "accepts"
117623
+ ];
117624
+ const m = requestFields(v, [...target, body], optional);
117625
+ return {
117626
+ id,
117627
+ type: "session.command",
117628
+ ...commandIdField(m["command_id"]),
117629
+ ...acceptsField(m["accepts"]),
117630
+ ...body === "upload_id" ? { upload_id: localId(m["upload_id"], "upload_id") } : { rpc: commandRpcOf(m["rpc"]) },
117631
+ ...routeFields(m),
117632
+ ...targetOf2(m, field)
117633
+ };
117634
+ },
117635
+ "session.command_part": (v, id) => {
117636
+ const target = targetField(v);
117637
+ const m = requestFields(v, [target, "upload_id", "index", "count", "b"]);
117638
+ const count = uint(m["count"], 1, LOCAL_UPLOAD_PARTS_MAX, "count");
117639
+ base64Bytes(m["b"], LOCAL_CHUNK_MAX, "b");
117640
+ return {
117641
+ id,
117642
+ type: "session.command_part",
117643
+ ...partTargetOf(m, target),
117644
+ upload_id: localId(m["upload_id"], "upload_id"),
117645
+ index: uint(m["index"], 0, count - 1, "index"),
117646
+ count,
117647
+ b: typeof m["b"] === "string" ? m["b"] : fail("b")
117648
+ };
117649
+ }
117650
+ };
117651
+
117652
+ // packages/device-service-core/src/local-api/validate-machine.ts
117653
+ var MACHINE_OPS_MAX = 4096;
117654
+ var MACHINE_REF_MAX_CHARS = 128;
117655
+ var MACHINE_CREDIT_MAX_BYTES = SESSION_BLOB_MAX;
117656
+ var BASE64URL2 = /^[A-Za-z0-9_-]+$/;
117657
+ var machineId = (v, what) => typeof v === "string" && v.length === COMMAND_ID_CHARS && BASE64URL2.test(v) ? v : fail(what);
117658
+ var machineRef = (v, what) => text(v, MACHINE_REF_MAX_CHARS, what);
117659
+ var opName = (v) => {
117660
+ try {
117661
+ return methodOf(v, "op");
117662
+ } catch (error) {
117663
+ if (error instanceof ProtoError)
117664
+ return fail("op");
117665
+ throw error;
117666
+ }
117667
+ };
117668
+ var opOf = (v) => {
117669
+ const m = exactly(v, ["op_id", "op", "args"], ["deadline_ms", "constraints"], "op");
117670
+ const deadline = m["deadline_ms"];
117671
+ const constraints = m["constraints"];
117672
+ return {
117673
+ op_id: machineId(m["op_id"], "op_id"),
117674
+ op: opName(m["op"]),
117675
+ args: jsonObject(m["args"], "args"),
117676
+ ...deadline === undefined ? {} : { deadline_ms: uint(deadline, 1, Number.MAX_SAFE_INTEGER, "deadline_ms") },
117677
+ ...constraints === undefined ? {} : { constraints: jsonObject(constraints, "constraints") }
117678
+ };
117679
+ };
117680
+ var uniqueIds = (ids, what) => new Set(ids).size === ids.length ? ids : fail(`duplicate ${what}`);
117681
+ var machineOpsOf = (v) => {
117682
+ if (!Array.isArray(v) || v.length === 0 || v.length > MACHINE_OPS_MAX)
117683
+ return fail("ops");
117684
+ const ops = v.map(opOf);
117685
+ uniqueIds(ops.map((o) => o.op_id), "op_id");
117686
+ return ops;
117687
+ };
117688
+ var refOf2 = (m) => m["session_ref"] === undefined ? {} : { session_ref: machineRef(m["session_ref"], "session_ref") };
117689
+ var bare = (v) => {
117690
+ requestFields(v, []);
117691
+ };
117692
+ var MACHINE_REQUEST_VALIDATORS = {
117693
+ "machine.list": (v, id) => {
117694
+ bare(v);
117695
+ return { id, type: "machine.list" };
117696
+ },
117697
+ "machine.events.subscribe": (v, id) => {
117698
+ bare(v);
117699
+ return { id, type: "machine.events.subscribe" };
117700
+ },
117701
+ "machine.describe": (v, id) => ({
117702
+ id,
117703
+ type: "machine.describe",
117704
+ device: deviceId(requestFields(v, ["device"])["device"])
117705
+ }),
117706
+ "machine.batch": (v, id) => {
117707
+ if (Object.hasOwn(v, "upload_id")) {
117708
+ const m = requestFields(v, ["device", "upload_id"], ["session_ref"]);
117709
+ const upload_id = localId(m["upload_id"], "upload_id");
117710
+ return { id, type: "machine.batch", device: deviceId(m["device"]), upload_id, ...refOf2(m) };
117711
+ }
117712
+ const m = requestFields(v, ["device", "ops"], ["session_ref"]);
117713
+ if (lineBytes(v) > LOCAL_INLINE_MAX)
117714
+ return fail("an inline batch over LOCAL_INLINE_MAX is an upload");
117715
+ return {
117716
+ id,
117717
+ type: "machine.batch",
117718
+ device: deviceId(m["device"]),
117719
+ ops: machineOpsOf(m["ops"]),
117720
+ ...refOf2(m)
117721
+ };
117722
+ },
117723
+ "machine.batch_part": (v, id) => {
117724
+ const m = requestFields(v, ["upload_id", "index", "count", "b"]);
117725
+ const count = uint(m["count"], 1, MACHINE_UPLOAD_PARTS_MAX, `count: ${MACHINE_UPLOAD_LIMIT}`);
117726
+ base64Bytes(m["b"], LOCAL_CHUNK_MAX, "b");
117727
+ return {
117728
+ id,
117729
+ type: "machine.batch_part",
117730
+ upload_id: localId(m["upload_id"], "upload_id"),
117731
+ index: uint(m["index"], 0, count - 1, "index"),
117732
+ count,
117733
+ b: typeof m["b"] === "string" ? m["b"] : fail("b")
117734
+ };
117735
+ },
117736
+ "machine.cancel": (v, id) => {
117737
+ const ids = requestFields(v, ["op_ids"])["op_ids"];
117738
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > MACHINE_OPS_MAX)
117739
+ return fail("op_ids");
117740
+ const op_ids = uniqueIds(ids.map((o) => machineId(o, "op_id")), "op_id");
117741
+ return { id, type: "machine.cancel", op_ids };
117742
+ },
117743
+ "machine.credit": (v, id) => {
117744
+ const m = requestFields(v, ["handle", "bytes"]);
117745
+ return {
117746
+ id,
117747
+ type: "machine.credit",
117748
+ handle: machineRef(m["handle"], "handle"),
117749
+ bytes: uint(m["bytes"], 1, MACHINE_CREDIT_MAX_BYTES, "bytes")
117750
+ };
117751
+ },
117752
+ "machine.result_of": (v, id) => ({
117753
+ id,
117754
+ type: "machine.result_of",
117755
+ op_id: machineId(requestFields(v, ["op_id"])["op_id"], "op_id")
117756
+ })
117757
+ };
117758
+ var empty = (v) => {
117759
+ known(v, [], [], "data");
117760
+ return {};
117761
+ };
117762
+ var fields = (v, names) => known(v, names, [], "data");
117763
+ var LEGACY_MACHINE_ROUTE_KINDS = ["internet", "lan"];
117764
+ var legacyRouteOf = (v) => {
117765
+ const r = known(v, ["kind", "online"], [], "machine route");
117766
+ const kind = oneOf(LEGACY_MACHINE_ROUTE_KINDS, r["kind"], "machine route kind");
117767
+ bool(r["online"], "online");
117768
+ return kind;
117769
+ };
117770
+ var machineRowOf = (v) => {
117771
+ const m = known(v, ["device", "label", "state"], ["routes"], "machine row");
117772
+ const routes = m["routes"];
117773
+ if (routes !== undefined && (!Array.isArray(routes) || routes.length > LEGACY_MACHINE_ROUTE_KINDS.length))
117774
+ return fail("routes");
117775
+ const listed = routes?.map(legacyRouteOf);
117776
+ if (listed !== undefined && new Set(listed).size !== listed.length)
117777
+ return fail("routes");
117778
+ return {
117779
+ device: deviceId(m["device"]),
117780
+ label: text(m["label"], LABEL_MAX_CHARS, "label", 0),
117781
+ state: oneOf(MACHINE_STATES, m["state"], "machine state")
117782
+ };
117783
+ };
117784
+ var MACHINE_DATA = {
117785
+ "machine.list": (v) => {
117786
+ const machines = fields(v, ["machines"])["machines"];
117787
+ return Array.isArray(machines) ? { machines: machines.map(machineRowOf) } : fail("machines");
117788
+ },
117789
+ "machine.describe": (v) => {
117790
+ const m = fields(v, ["device", "description"]);
117791
+ if (!isRecord19(m["description"]))
117792
+ return fail("description");
117793
+ return {
117794
+ device: deviceId(m["device"]),
117795
+ description: jsonObject(m["description"], "description")
117796
+ };
117797
+ },
117798
+ "machine.batch": (v) => ({
117799
+ batch_id: machineId(fields(v, ["batch_id"])["batch_id"], "batch_id")
117800
+ }),
117801
+ "machine.batch_part": (v) => ({
117802
+ received: uint(fields(v, ["received"])["received"], 0, MACHINE_UPLOAD_PARTS_MAX - 1, "received")
117803
+ }),
117804
+ "machine.cancel": empty,
117805
+ "machine.credit": empty,
117806
+ "machine.result_of": (v) => ({
117807
+ state: oneOf(MACHINE_LOOKUP_STATES, fields(v, ["state"])["state"], "lookup state")
117808
+ }),
117809
+ "machine.events.subscribe": empty
117810
+ };
117811
+
117812
+ // packages/device-service-core/src/local-api/validate-machine-events.ts
117813
+ var MACHINE_OUTPUT_MAX_BYTES = STREAM_INLINE_MAX;
117814
+ var blobId2 = (m) => localId(m["id"], "blob id");
117815
+ var blobRefOf2 = (v) => {
117816
+ const m = known(v, ["id", "bytes", "sha256"], [], "blob");
117817
+ return {
117818
+ id: blobId2(m),
117819
+ bytes: uint(m["bytes"], 1, LOCAL_BLOB_MAX, "blob bytes"),
117820
+ sha256: sha256Field(m["sha256"], "blob sha256")
117821
+ };
117822
+ };
117823
+ var base64Of = (v, max, what) => {
117824
+ base64Bytes(v, max, what);
117825
+ return typeof v === "string" ? v : fail(what);
117826
+ };
117827
+ var TIMING_FIELDS = [
117828
+ "enqueued_ms",
117829
+ "flushed_ms",
117830
+ "confirmed_ms",
117831
+ "dispatched_ms",
117832
+ "settled_ms",
117833
+ "applied_ms"
117834
+ ];
117835
+ var timingOf = (v) => {
117836
+ const m = known(v, [], TIMING_FIELDS, "timing");
117837
+ return Object.fromEntries(TIMING_FIELDS.flatMap((k) => m[k] === undefined ? [] : [[k, uint(m[k], 0, Number.MAX_SAFE_INTEGER, k)]]));
117838
+ };
117839
+ var opResultOf = (v) => {
117840
+ const head = { type: "event", kind: "machine.op_result" };
117841
+ const all = eventFields(v, ["op_id"], ["blob", "response"]);
117842
+ const shape = (name) => exactly(all, ["type", "kind", "op_id", name], [], "event");
117843
+ if (Object.hasOwn(all, "blob")) {
117844
+ const m = shape("blob");
117845
+ return { ...head, op_id: machineId(m["op_id"], "op_id"), blob: blobRefOf2(m["blob"]) };
117846
+ }
117847
+ const m = shape("response");
117848
+ if (lineBytes(v) > LOCAL_INLINE_MAX)
117849
+ return fail("an inline result over LOCAL_INLINE_MAX is a blob");
117850
+ return {
117851
+ ...head,
117852
+ op_id: machineId(m["op_id"], "op_id"),
117853
+ response: jsonObject(m["response"], "response")
117854
+ };
117855
+ };
117856
+ var MACHINE_EVENT_VALIDATORS = {
117857
+ "machine.op_state": (v) => {
117858
+ const m = eventFields(v, ["op_id", "state"], ["timing"]);
117859
+ return {
117860
+ type: "event",
117861
+ kind: "machine.op_state",
117862
+ op_id: machineId(m["op_id"], "op_id"),
117863
+ state: oneOf(MACHINE_OP_STATES, m["state"], "op state"),
117864
+ ...m["timing"] === undefined ? {} : { timing: timingOf(m["timing"]) }
117865
+ };
117866
+ },
117867
+ "machine.op_result": opResultOf,
117868
+ "machine.output": (v) => {
117869
+ const m = eventFields(v, ["handle", "seq", "bytes"]);
117870
+ return {
117871
+ type: "event",
117872
+ kind: "machine.output",
117873
+ handle: machineRef(m["handle"], "handle"),
117874
+ seq: uint(m["seq"], 0, Number.MAX_SAFE_INTEGER, "seq"),
117875
+ bytes: base64Of(m["bytes"], MACHINE_OUTPUT_MAX_BYTES, "bytes")
117876
+ };
117877
+ },
117878
+ "machine.changed": (v) => {
117879
+ const m = eventFields(v, ["device", "state"]);
117880
+ return {
117881
+ type: "event",
117882
+ kind: "machine.changed",
117883
+ device: deviceId(m["device"]),
117884
+ state: oneOf(MACHINE_STATES, m["state"], "machine state")
117885
+ };
117886
+ },
117887
+ "machine.blob_chunk": (v) => {
117888
+ const m = eventFields(v, ["id", "off", "b"]);
117889
+ return {
117890
+ type: "event",
117891
+ kind: "machine.blob_chunk",
117892
+ id: blobId2(m),
117893
+ off: uint(m["off"], 0, LOCAL_BLOB_MAX, "blob off"),
117894
+ b: base64Of(m["b"], LOCAL_CHUNK_MAX, "blob chunk")
117895
+ };
117896
+ },
117897
+ "machine.blob_done": (v) => ({
117898
+ type: "event",
117899
+ kind: "machine.blob_done",
117900
+ id: blobId2(eventFields(v, ["id"]))
117901
+ }),
117902
+ "machine.blob_abort": (v) => {
117903
+ const m = eventFields(v, ["id", "reason"]);
117904
+ return {
117905
+ type: "event",
117906
+ kind: "machine.blob_abort",
117907
+ id: blobId2(m),
117908
+ reason: oneOf(MACHINE_BLOB_ABORT_REASONS, m["reason"], "blob abort reason")
117909
+ };
117910
+ }
117911
+ };
117912
+
117913
+ // packages/device-service-core/src/local-api/protocol-presenter.ts
117914
+ var PRESENTER_LOCAL_LANES = ["control", "delegated"];
117915
+ var PRESENTER_LOCAL_LINE_MAX = {
117916
+ control: 16 * 1024,
117917
+ delegated: 1024 * 1024
117918
+ };
117919
+ var PRESENTER_ENDED_REASONS = [
117920
+ "viewer_closed",
117921
+ "engine_closed",
117922
+ "no_control_endpoint",
117923
+ "no_delegated_connection",
117924
+ "not_granted",
117925
+ "conn_collision",
117926
+ "busy",
117927
+ "idle",
117928
+ "event_lost",
117929
+ "too_large",
117930
+ "malformed",
117931
+ "rate"
117932
+ ];
117933
+
117934
+ // packages/device-service-core/src/local-api/validate-presenter.ts
117935
+ var BASE64URL3 = /^[A-Za-z0-9_-]+$/;
117936
+ var presenterLineText = (v, lane) => {
117937
+ const max = PRESENTER_LOCAL_LINE_MAX[lane];
117938
+ if (typeof v !== "string" || v.length === 0 || v.length > Math.ceil(max * 4 / 3))
117939
+ return fail("line too long");
117940
+ if (!BASE64URL3.test(v))
117941
+ return fail("line");
117942
+ let bytes;
117943
+ try {
117944
+ bytes = fromBase64url(v);
117945
+ } catch (error) {
117946
+ if (error instanceof Error)
117947
+ return fail("line");
117948
+ throw error;
117949
+ }
117950
+ return bytes.length <= max && toBase64url(bytes) === v ? v : fail("line");
117951
+ };
117952
+ var laneOf = (v) => oneOf(PRESENTER_LOCAL_LANES, v["lane"], "lane");
117953
+ var PRESENTER_REQUEST_VALIDATORS = {
117954
+ "session.presenter_open": (v, id) => {
117955
+ const m = requestFields(v, ["device", "session"]);
117956
+ return {
117957
+ id,
117958
+ type: "session.presenter_open",
117959
+ device: deviceId(m["device"]),
117960
+ session: sessionId(m["session"])
117961
+ };
117962
+ },
117963
+ "session.presenter_send": (v, id) => {
117964
+ const m = requestFields(v, ["device", "lane", "b"]);
117965
+ const lane = laneOf(m);
117966
+ return {
117967
+ id,
117968
+ type: "session.presenter_send",
117969
+ device: deviceId(m["device"]),
117970
+ lane,
117971
+ b: presenterLineText(m["b"], lane)
117972
+ };
117973
+ }
117974
+ };
117975
+ var frameOf = (v) => {
117976
+ const m = eventFields(v, ["device", "lane", "b"]);
117977
+ const lane = laneOf(m);
117978
+ return {
117979
+ type: "event",
117980
+ kind: "session.presenter_frame",
117981
+ device: deviceId(m["device"]),
117982
+ lane,
117983
+ b: presenterLineText(m["b"], lane)
117984
+ };
117985
+ };
117986
+ var PRESENTER_EVENT_VALIDATORS = {
117987
+ "session.presenter_frame": frameOf,
117988
+ "session.presenter_ended": (v) => {
117989
+ const m = eventFields(v, ["device", "reason"]);
117990
+ return {
117991
+ type: "event",
117992
+ kind: "session.presenter_ended",
117993
+ device: deviceId(m["device"]),
117994
+ reason: oneOf(PRESENTER_ENDED_REASONS, m["reason"], "presenter end reason")
117995
+ };
117996
+ }
117997
+ };
117998
+
117340
117999
  // packages/device-service-core/src/local-api/validate-deliveries.ts
117341
118000
  var PROTOCOL_MAX = 1e6;
117342
118001
  var PAIRS_MAX = 4096;
@@ -117351,9 +118010,17 @@ var DELIVERIES_REQUEST_VALIDATORS = {
117351
118010
  const pairs = requestFields(v, ["pairs"])["pairs"];
117352
118011
  if (!Array.isArray(pairs) || pairs.length > PAIRS_MAX)
117353
118012
  return fail("pairs");
117354
- return { id, type: "delivery.pending", pairs: pairs.map((p) => pairOf(exactly(p, PAIR_FIELDS, [], "pair"))) };
118013
+ return {
118014
+ id,
118015
+ type: "delivery.pending",
118016
+ pairs: pairs.map((p) => pairOf(exactly(p, PAIR_FIELDS, [], "pair")))
118017
+ };
117355
118018
  },
117356
- "delivery.drained": (v, id) => ({ id, type: "delivery.drained", ...pairOf(requestFields(v, PAIR_FIELDS)) }),
118019
+ "delivery.drained": (v, id) => ({
118020
+ id,
118021
+ type: "delivery.drained",
118022
+ ...pairOf(requestFields(v, PAIR_FIELDS))
118023
+ }),
117357
118024
  "deliveries.serve": (v, id) => {
117358
118025
  const m = requestFields(v, ["agent_dir", "v"]);
117359
118026
  return {
@@ -117375,19 +118042,31 @@ var DELIVERIES_REQUEST_VALIDATORS = {
117375
118042
  },
117376
118043
  "delivery.held": (v, id) => {
117377
118044
  const m = requestFields(v, ["ask_id", "holds"]);
117378
- return { id, type: "delivery.held", ask_id: localId(m["ask_id"], "ask_id"), holds: bool(m["holds"], "holds") };
118045
+ return {
118046
+ id,
118047
+ type: "delivery.held",
118048
+ ask_id: localId(m["ask_id"], "ask_id"),
118049
+ holds: bool(m["holds"], "holds")
118050
+ };
117379
118051
  },
117380
- "peer.admitted": (v, id) => ({ id, type: "peer.admitted", device: deviceId(requestFields(v, ["device"])["device"]) })
118052
+ "peer.admitted": (v, id) => ({
118053
+ id,
118054
+ type: "peer.admitted",
118055
+ device: deviceId(requestFields(v, ["device"])["device"])
118056
+ })
117381
118057
  };
117382
- var empty = (v) => {
118058
+ var empty2 = (v) => {
117383
118059
  known(v, [], [], "data");
117384
118060
  return {};
117385
118061
  };
117386
118062
  var DELIVERIES_DATA = {
117387
- "deliveries.serve": (v) => ({ wake: bool(known(v, ["wake"], [], "data")["wake"], "wake") }),
117388
- "delivery.answer": empty,
117389
- "delivery.held": empty,
117390
- "delivery.pending": empty,
118063
+ "deliveries.serve": (v) => {
118064
+ const m = known(v, ["wake"], [], "data");
118065
+ return { wake: bool(m["wake"], "wake") };
118066
+ },
118067
+ "delivery.answer": empty2,
118068
+ "delivery.held": empty2,
118069
+ "delivery.pending": empty2,
117391
118070
  "delivery.drained": (v) => {
117392
118071
  const m = known(v, ["kept"], ["expecting"], "data");
117393
118072
  const kept = bool(m["kept"], "kept");
@@ -117395,14 +118074,15 @@ var DELIVERIES_DATA = {
117395
118074
  return m["expecting"] === undefined ? { kept } : fail("expecting");
117396
118075
  return { kept, expecting: commandId(m["expecting"]) };
117397
118076
  },
117398
- "peer.admitted": (v) => ({ admitted: bool(known(v, ["admitted"], [], "data")["admitted"], "admitted") })
118077
+ "peer.admitted": (v) => ({
118078
+ admitted: bool(known(v, ["admitted"], [], "data")["admitted"], "admitted")
118079
+ })
117399
118080
  };
117400
118081
  var DELIVERIES_EVENT_VALIDATORS = {
117401
- "delivery.wake": (v) => ({
117402
- type: "event",
117403
- kind: "delivery.wake",
117404
- enabled: bool(eventFields(v, ["enabled"])["enabled"], "enabled")
117405
- }),
118082
+ "delivery.wake": (v) => {
118083
+ const m = eventFields(v, ["enabled"]);
118084
+ return { type: "event", kind: "delivery.wake", enabled: bool(m["enabled"], "enabled") };
118085
+ },
117406
118086
  "delivery.inbound": (v) => {
117407
118087
  const m = eventFields(v, ["command_id", "sender_device", "durable_id", "record"]);
117408
118088
  return {
@@ -117425,6 +118105,116 @@ var DELIVERIES_EVENT_VALIDATORS = {
117425
118105
  }
117426
118106
  };
117427
118107
 
118108
+ // packages/device-service-core/src/local-api/validate-listing-row.ts
118109
+ var ROW_FIELDS = [
118110
+ "device",
118111
+ "session_id",
118112
+ "title",
118113
+ "project",
118114
+ "path",
118115
+ "state",
118116
+ "updated_ms",
118117
+ "source",
118118
+ "as_of"
118119
+ ];
118120
+ var ROW_KIND = new RegExp(`^[a-z][a-z0-9_-]{0,${SESSION_KIND_MAX_CHARS - 1}}$`);
118121
+ var rowLinks = (m) => {
118122
+ const kind = m["kind"];
118123
+ if (Object.hasOwn(m, "parent") !== Object.hasOwn(m, "parent_listed"))
118124
+ fail("parent_listed");
118125
+ return {
118126
+ ...kind === undefined ? {} : { kind: typeof kind === "string" && ROW_KIND.test(kind) ? kind : fail("row kind") },
118127
+ ...m["parent"] === undefined ? {} : {
118128
+ parent: sessionId(m["parent"]),
118129
+ parent_listed: bool(m["parent_listed"], "parent_listed")
118130
+ }
118131
+ };
118132
+ };
118133
+ var rowModel = (v) => {
118134
+ if (v === undefined)
118135
+ return {};
118136
+ const m = known(v, ["provider", "id"], [], "model");
118137
+ return {
118138
+ model: {
118139
+ provider: text(m["provider"], SESSION_MODEL_PROVIDER_MAX_CHARS, "model provider"),
118140
+ id: text(m["id"], SESSION_MODEL_ID_MAX_CHARS, "model id")
118141
+ }
118142
+ };
118143
+ };
118144
+ var settledByOf = (v) => {
118145
+ const named = known(v, ["kind"], [], "settled_by")["kind"];
118146
+ if (typeof named !== "string")
118147
+ return fail("settled_by kind");
118148
+ const kind = LISTING_SETTLED_BY_KINDS.find((k) => k === named);
118149
+ switch (kind) {
118150
+ case undefined:
118151
+ return;
118152
+ case "user":
118153
+ return { kind };
118154
+ case "agent": {
118155
+ const m = known(v, ["kind"], ["threadId", "threadTitle"], "settled_by");
118156
+ const id = m["threadId"];
118157
+ const title = m["threadTitle"];
118158
+ return {
118159
+ kind,
118160
+ ...id === undefined ? {} : { threadId: text(id, SESSION_ID_MAX_CHARS, "settled_by threadId") },
118161
+ ...title === undefined ? {} : {
118162
+ threadTitle: text(title, SESSION_SETTLED_THREAD_TITLE_MAX_CHARS, "settled_by threadTitle", 0)
118163
+ }
118164
+ };
118165
+ }
118166
+ case "pr-merged":
118167
+ case "pr-closed": {
118168
+ const n = known(v, ["kind"], ["pullRequestNumber"], "settled_by")["pullRequestNumber"];
118169
+ return {
118170
+ kind,
118171
+ ...n === undefined ? {} : {
118172
+ pullRequestNumber: uint(n, 0, Number.MAX_SAFE_INTEGER, "settled_by pullRequestNumber")
118173
+ }
118174
+ };
118175
+ }
118176
+ case "inactivity": {
118177
+ const days = known(v, ["kind", "days"], [], "settled_by")["days"];
118178
+ return { kind, days: uint(days, 0, SESSION_SETTLED_DAYS_MAX, "settled_by days") };
118179
+ }
118180
+ default:
118181
+ return assertNever(kind);
118182
+ }
118183
+ };
118184
+ var rowSettled = (m) => {
118185
+ const reason = m["settled_by"];
118186
+ if (m["settled"] === undefined)
118187
+ return reason === undefined ? {} : fail("settled_by");
118188
+ const settled = bool(m["settled"], "settled");
118189
+ if (reason === undefined)
118190
+ return { settled };
118191
+ if (!settled)
118192
+ return fail("settled_by");
118193
+ const by = settledByOf(reason);
118194
+ return by === undefined ? { settled } : { settled, settled_by: by };
118195
+ };
118196
+ var listingRowOf = (v) => {
118197
+ const m = known(v, ROW_FIELDS, ["kind", "parent", "parent_listed", "durable_id", "model", "archived", "settled", "settled_by"], "listing row");
118198
+ const durable = m["durable_id"];
118199
+ const archived = m["archived"];
118200
+ return {
118201
+ ...rowLinks(m),
118202
+ ...rowModel(m["model"]),
118203
+ ...rowSettled(m),
118204
+ ...archived === undefined ? {} : { archived: archived === true ? true : fail("archived") },
118205
+ ...durable === undefined ? {} : { durable_id: text(durable, SESSION_ID_MAX_CHARS, "durable_id") },
118206
+ device: deviceId(m["device"]),
118207
+ session_id: sessionId(m["session_id"]),
118208
+ title: text(m["title"], SESSION_SUMMARY_TITLE_MAX_CHARS, "title", 0),
118209
+ project: text(m["project"], SESSION_SUMMARY_PROJECT_MAX_CHARS, "project"),
118210
+ path: text(m["path"], SESSION_SUMMARY_PATH_MAX_CHARS, "path"),
118211
+ state: oneOf(SESSION_ROW_STATES, m["state"], "row state"),
118212
+ updated_ms: millis(m["updated_ms"], "updated_ms"),
118213
+ source: oneOf(LISTING_SOURCES, m["source"], "row source"),
118214
+ as_of: millis(m["as_of"], "as_of")
118215
+ };
118216
+ };
118217
+
117428
118218
  // packages/device-service-core/src/local-api/validate-events.ts
117429
118219
  var revisionOf = (m) => uint(m["revision"], 1, Number.MAX_SAFE_INTEGER, "revision");
117430
118220
  var devicesOf = (v) => {
@@ -117432,7 +118222,7 @@ var devicesOf = (v) => {
117432
118222
  return fail("round devices");
117433
118223
  const out = {};
117434
118224
  for (const [device, state] of Object.entries(v))
117435
- out[safeKey(deviceId(device), "round device")] = oneOf(ROUND_DEVICE_STATES, state, "round device state");
118225
+ out[safeKey2(deviceId(device), "round device")] = oneOf(ROUND_DEVICE_STATES, state, "round device state");
117436
118226
  return out;
117437
118227
  };
117438
118228
  var commandStateOf = (v) => {
@@ -117475,7 +118265,9 @@ var commandStateOf = (v) => {
117475
118265
  };
117476
118266
  var VALIDATORS = {
117477
118267
  ...STREAM_EVENT_VALIDATORS,
118268
+ ...MACHINE_EVENT_VALIDATORS,
117478
118269
  ...DELEGATED_EVENT_VALIDATORS,
118270
+ ...PRESENTER_EVENT_VALIDATORS,
117479
118271
  ...DELIVERIES_EVENT_VALIDATORS,
117480
118272
  "status.changed": (v) => ({
117481
118273
  type: "event",
@@ -117515,6 +118307,15 @@ var VALIDATORS = {
117515
118307
  rows: rows.map(listingRowOf)
117516
118308
  };
117517
118309
  },
118310
+ "sessions.listing_changed": (v) => {
118311
+ const m = eventFields(v, ["device", "generation"]);
118312
+ return {
118313
+ type: "event",
118314
+ kind: "sessions.listing_changed",
118315
+ device: deviceId(m["device"]),
118316
+ generation: nullable2(m["generation"], (g) => uint(g, 0, Number.MAX_SAFE_INTEGER, "generation"))
118317
+ };
118318
+ },
117518
118319
  "sessions.listing_end": (v) => {
117519
118320
  const m = eventFields(v, ["query_id", "revision", "incomplete"]);
117520
118321
  const incomplete = m["incomplete"];
@@ -117548,6 +118349,20 @@ var VALIDATORS = {
117548
118349
  next_before
117549
118350
  };
117550
118351
  },
118352
+ "host.update_notice": (v) => {
118353
+ const m = eventFields(v, ["target_version", "phase", "policy"], ["update_id", "deadline_ms"]);
118354
+ const id = m["update_id"];
118355
+ const deadline = m["deadline_ms"];
118356
+ return {
118357
+ type: "event",
118358
+ kind: "host.update_notice",
118359
+ ...id === undefined ? {} : { update_id: localId(id, "update_id") },
118360
+ target_version: semver(m["target_version"], "target_version"),
118361
+ phase: oneOf(UPDATE_NOTICE_PHASES, m["phase"], "update notice phase"),
118362
+ ...deadline === undefined ? {} : { deadline_ms: millis(deadline, "deadline_ms") },
118363
+ policy: oneOf(UPDATE_POLICIES, m["policy"], "update policy")
118364
+ };
118365
+ },
117551
118366
  "session.upload_abort": (v) => {
117552
118367
  const m = eventFields(v, ["upload_id", "reason"]);
117553
118368
  const reason = oneOf(UPLOAD_ABORT_REASONS, m["reason"], "upload abort reason");
@@ -117566,8 +118381,36 @@ var validateEventFields = (v) => {
117566
118381
  return VALIDATORS[oneOf(EVENT_KINDS, v["kind"], "event kind")](v);
117567
118382
  };
117568
118383
 
118384
+ // packages/device-service-core/src/local-api/validate-session-wake.ts
118385
+ var SESSION_WAKE_VALIDATORS = {
118386
+ "control.session_wake.get": (v, id) => {
118387
+ requestFields(v, []);
118388
+ return { id, type: "control.session_wake.get" };
118389
+ },
118390
+ "control.session_wake.set": (v, id) => {
118391
+ const raw = requestFields(v, ["enabled"])["enabled"];
118392
+ return {
118393
+ id,
118394
+ type: "control.session_wake.set",
118395
+ enabled: raw === null ? null : bool(raw, "enabled")
118396
+ };
118397
+ }
118398
+ };
118399
+ var storedOf = (v) => v === null || v === "unreadable" || typeof v === "boolean" ? v : fail("stored");
118400
+ var sessionWakeState = (v) => {
118401
+ const m = known(v, ["enabled", "stored", "changedAt", "overridden"], [], "data");
118402
+ const stored = m["stored"];
118403
+ const changedAt = m["changedAt"];
118404
+ return {
118405
+ enabled: bool(m["enabled"], "enabled"),
118406
+ stored: storedOf(stored),
118407
+ changedAt: typeof changedAt === "string" ? changedAt : fail("changedAt"),
118408
+ overridden: bool(m["overridden"], "overridden")
118409
+ };
118410
+ };
118411
+
117569
118412
  // packages/device-service-core/src/local-api/validate-requests.ts
117570
- var ENVIRONMENTS_MAX = 1024;
118413
+ var ENVIRONMENTS_MAX2 = 1024;
117571
118414
  var PKCS8_KEY_BYTES = 48;
117572
118415
  var PKCS8_PREFIX = {
117573
118416
  ed25519: "302e020100300506032b657004220420",
@@ -117575,7 +118418,7 @@ var PKCS8_PREFIX = {
117575
118418
  };
117576
118419
  var pkcs8 = (v, algorithm, what) => {
117577
118420
  const bytes = base64Bytes(v, PKCS8_KEY_BYTES, what);
117578
- const prefix = Buffer.from(bytes.subarray(0, 16)).toString("hex");
118421
+ const prefix = toHex(bytes.subarray(0, 16));
117579
118422
  const exact = bytes.length === PKCS8_KEY_BYTES && prefix === PKCS8_PREFIX[algorithm];
117580
118423
  return exact && typeof v === "string" ? v : fail(what);
117581
118424
  };
@@ -117588,7 +118431,7 @@ var filterOf = (v) => {
117588
118431
  };
117589
118432
  };
117590
118433
  var environmentsOf = (v) => {
117591
- if (!Array.isArray(v) || v.length > ENVIRONMENTS_MAX)
118434
+ if (!Array.isArray(v) || v.length > ENVIRONMENTS_MAX2)
117592
118435
  return fail("environments");
117593
118436
  const rows = v.map((e) => {
117594
118437
  const m = exactly(e, ["environment_id", "revoked", "closed"], [], "environment");
@@ -117600,43 +118443,62 @@ var environmentsOf = (v) => {
117600
118443
  });
117601
118444
  return new Set(rows.map((r) => r.environment_id)).size === rows.length ? rows : fail("duplicate environment_id");
117602
118445
  };
117603
- var bare = (v) => {
118446
+ var resumeOf = (v) => {
118447
+ const m = exactly(v, ["attach_id", "seq"], [], "resume");
118448
+ const seq = uint(m["seq"], 0, Number.MAX_SAFE_INTEGER, "resume.seq");
118449
+ return { attach_id: attachId(m["attach_id"]), seq };
118450
+ };
118451
+ var fromOf = (v) => {
118452
+ const m = exactly(v, ["last_entry_id"], [], "from");
118453
+ return { last_entry_id: entryId(m["last_entry_id"], "from.last_entry_id") };
118454
+ };
118455
+ var bare2 = (v) => {
117604
118456
  requestFields(v, []);
117605
118457
  };
117606
- var agentDir = (v) => absolutePath(requestFields(v, ["agent_dir"])["agent_dir"], "agent_dir");
117607
118458
  var VALIDATORS2 = {
117608
118459
  ...COMMAND_REQUEST_VALIDATORS,
118460
+ ...MACHINE_REQUEST_VALIDATORS,
117609
118461
  ...DELEGATED_REQUEST_VALIDATORS,
118462
+ ...PRESENTER_REQUEST_VALIDATORS,
117610
118463
  ...DELIVERIES_REQUEST_VALIDATORS,
117611
118464
  authenticate: (v, id) => {
117612
118465
  const m = requestFields(v, ["client_proof"]);
117613
118466
  return { id, type: "authenticate", client_proof: text(m["client_proof"], 64, "client_proof") };
117614
118467
  },
117615
118468
  "status.get": (v, id) => {
117616
- bare(v);
117617
- return { id, type: "status.get" };
118469
+ const { exe, sign_in_reason: reason } = requestFields(v, [], ["exe", "sign_in_reason"]);
118470
+ if (exe !== undefined && exe !== true)
118471
+ return fail("exe");
118472
+ if (reason !== undefined && reason !== true)
118473
+ return fail("sign_in_reason");
118474
+ return {
118475
+ id,
118476
+ type: "status.get",
118477
+ ...exe === true ? { exe } : {},
118478
+ ...reason === true ? { sign_in_reason: reason } : {}
118479
+ };
117618
118480
  },
117619
118481
  "status.subscribe": (v, id) => {
117620
- bare(v);
118482
+ bare2(v);
117621
118483
  return { id, type: "status.subscribe" };
117622
118484
  },
117623
- "control.session_wake.get": (v, id) => {
117624
- bare(v);
117625
- return { id, type: "control.session_wake.get" };
117626
- },
117627
- "control.session_wake.set": (v, id) => {
117628
- const value = requestFields(v, ["enabled"])["enabled"];
117629
- const enabled = value === null || typeof value === "boolean" ? value : fail("enabled");
117630
- return { id, type: "control.session_wake.set", enabled };
117631
- },
117632
118485
  "control.attach.get": (v, id) => {
117633
- bare(v);
118486
+ bare2(v);
117634
118487
  return { id, type: "control.attach.get" };
117635
118488
  },
117636
118489
  "control.attach.set": (v, id) => {
117637
118490
  const attached = bool(requestFields(v, ["attached"])["attached"], "attached");
117638
118491
  return { id, type: "control.attach.set", attached };
117639
118492
  },
118493
+ "control.remote_commands.get": (v, id) => {
118494
+ bare2(v);
118495
+ return { id, type: "control.remote_commands.get" };
118496
+ },
118497
+ "control.remote_commands.set": (v, id) => {
118498
+ const enabled = bool(requestFields(v, ["enabled"])["enabled"], "enabled");
118499
+ return { id, type: "control.remote_commands.set", enabled };
118500
+ },
118501
+ ...SESSION_WAKE_VALIDATORS,
117640
118502
  "service.set_enabled": (v, id) => {
117641
118503
  const enabled = bool(requestFields(v, ["enabled"])["enabled"], "enabled");
117642
118504
  return { id, type: "service.set_enabled", enabled };
@@ -117652,32 +118514,42 @@ var VALIDATORS2 = {
117652
118514
  };
117653
118515
  },
117654
118516
  "device.adopt": (v, id) => {
117655
- const m = requestFields(v, ["device", "signing_private_key", "sealing_private_key"]);
118517
+ const m = requestFields(v, ["device", "signing_private_key", "sealing_private_key"], ["account", "sign_in_reason"]);
118518
+ const reason = m["sign_in_reason"];
118519
+ if (reason !== undefined && reason !== true)
118520
+ return fail("sign_in_reason");
117656
118521
  return {
117657
118522
  id,
117658
118523
  type: "device.adopt",
117659
118524
  device: deviceRef(m["device"]),
118525
+ ...m["account"] === undefined ? {} : { account: text(m["account"], 256, "account") },
118526
+ ...reason === true ? { sign_in_reason: reason } : {},
117660
118527
  signing_private_key: pkcs8(m["signing_private_key"], "ed25519", "signing_private_key"),
117661
118528
  sealing_private_key: pkcs8(m["sealing_private_key"], "x25519", "sealing_private_key")
117662
118529
  };
117663
118530
  },
117664
118531
  "device.forget": (v, id) => {
117665
- bare(v);
118532
+ bare2(v);
117666
118533
  return { id, type: "device.forget" };
117667
118534
  },
117668
118535
  "device.info": (v, id) => {
117669
- bare(v);
118536
+ bare2(v);
117670
118537
  return { id, type: "device.info" };
117671
118538
  },
117672
- "endpoints.register": (v, id) => ({ id, type: "endpoints.register", agent_dir: agentDir(v) }),
117673
- "endpoints.unregister": (v, id) => ({ id, type: "endpoints.unregister", agent_dir: agentDir(v) }),
118539
+ ...endpointRequests,
117674
118540
  "devices.list": (v, id) => {
117675
- bare(v);
117676
- return { id, type: "devices.list" };
118541
+ const { managed } = requestFields(v, [], ["managed"]);
118542
+ if (managed !== undefined && managed !== true)
118543
+ return fail("managed");
118544
+ return { id, type: "devices.list", ...managed === undefined ? {} : { managed } };
118545
+ },
118546
+ "sessions.events.subscribe": (v, id) => {
118547
+ bare2(v);
118548
+ return { id, type: "sessions.events.subscribe" };
117677
118549
  },
117678
118550
  "sessions.list": (v, id) => {
117679
118551
  const { filter, rows } = requestFields(v, [], ["filter", "rows"]);
117680
- if (rows !== undefined && rows !== 2 && rows !== 3)
118552
+ if (rows !== undefined && rows !== 2 && rows !== 3 && rows !== 4 && rows !== 5)
117681
118553
  return fail("rows");
117682
118554
  return {
117683
118555
  id,
@@ -117687,12 +118559,20 @@ var VALIDATORS2 = {
117687
118559
  };
117688
118560
  },
117689
118561
  "session.attach": (v, id) => {
117690
- const m = requestFields(v, ["device", "session_id"]);
118562
+ const m = requestFields(v, ["device", "session_id"], ["seqs", "resume", "from"]);
118563
+ const { seqs, resume, from, session_id } = m;
118564
+ if (seqs !== undefined && seqs !== true)
118565
+ return fail("seqs");
118566
+ if (!isStreamSessionKey(session_id))
118567
+ return fail("session_id");
117691
118568
  return {
117692
118569
  id,
117693
118570
  type: "session.attach",
117694
118571
  device: deviceId(m["device"]),
117695
- session_id: sessionId(m["session_id"])
118572
+ session_id,
118573
+ ...seqs === undefined ? {} : { seqs },
118574
+ ...resume === undefined ? {} : { resume: resumeOf(resume) },
118575
+ ...from === undefined ? {} : { from: fromOf(from) }
117696
118576
  };
117697
118577
  },
117698
118578
  "session.detach": (v, id) => ({
@@ -117726,7 +118606,8 @@ var VALIDATORS2 = {
117726
118606
  "owner.shutdown_for_upgrade": (v, id) => {
117727
118607
  const target_version = semver(requestFields(v, ["target_version"])["target_version"], "target_version");
117728
118608
  return { id, type: "owner.shutdown_for_upgrade", target_version };
117729
- }
118609
+ },
118610
+ "owner.update_committed": (v, id) => updateCommittedOf(requestFields(v, ["update_id"]), id)
117730
118611
  };
117731
118612
  var REQUEST_TYPES = keysOf(VALIDATORS2);
117732
118613
 
@@ -117747,7 +118628,16 @@ var validateWelcome = (v) => asViolation(() => {
117747
118628
  }
117748
118629
  if (isRecord19(v) && v["type"] === "welcome" && v["v"] !== LOCAL_API_VERSION)
117749
118630
  return { type: "refused", reason: "version" };
117750
- const fields = ["type", "v", "service_version", "owner", "server_proof", "server_nonce", "capabilities", "state"];
118631
+ const fields = [
118632
+ "type",
118633
+ "v",
118634
+ "service_version",
118635
+ "owner",
118636
+ "server_proof",
118637
+ "server_nonce",
118638
+ "capabilities",
118639
+ "state"
118640
+ ];
117751
118641
  const m = known(v, fields, [], "welcome");
117752
118642
  const capabilities = m["capabilities"];
117753
118643
  if (m["type"] !== "welcome" || m["owner"] !== "service")
@@ -117765,7 +118655,7 @@ var validateWelcome = (v) => asViolation(() => {
117765
118655
  state: statusOf(m["state"])
117766
118656
  };
117767
118657
  });
117768
- var empty2 = (v) => {
118658
+ var empty3 = (v) => {
117769
118659
  known(v, [], [], "data");
117770
118660
  return {};
117771
118661
  };
@@ -117778,51 +118668,57 @@ var attachState = (v) => {
117778
118668
  changedAt: typeof changedAt === "string" ? changedAt : fail("changedAt")
117779
118669
  };
117780
118670
  };
117781
- var sessionWakeState = (v) => {
117782
- const m = known(v, ["enabled", "stored", "changedAt", "overridden"], [], "data");
117783
- const s = m["stored"];
118671
+ var remoteCommandsState = (v) => {
118672
+ const m = known(v, ["enabled", "changedAt", "overridden"], [], "data");
117784
118673
  const changedAt = m["changedAt"];
117785
118674
  return {
117786
118675
  enabled: bool(m["enabled"], "enabled"),
117787
- stored: s === null || typeof s === "boolean" ? s : s === "unreadable" ? "unreadable" : fail("stored"),
117788
118676
  changedAt: typeof changedAt === "string" ? changedAt : fail("changedAt"),
117789
118677
  overridden: bool(m["overridden"], "overridden")
117790
118678
  };
117791
118679
  };
117792
118680
  var DATA = {
117793
- authenticate: empty2,
118681
+ authenticate: empty3,
117794
118682
  "status.get": statusOf,
117795
- "status.subscribe": empty2,
118683
+ "status.subscribe": empty3,
117796
118684
  "service.set_enabled": (v) => ({ enabled: bool(one(v, "enabled"), "enabled") }),
117797
- "refresher.register": empty2,
118685
+ "refresher.register": empty3,
117798
118686
  "device.adopt": (v) => ({ device: deviceRef(one(v, "device"), "device", known) }),
117799
- "device.forget": empty2,
118687
+ "device.forget": empty3,
117800
118688
  "device.info": (v) => ({
117801
118689
  device: nullable2(one(v, "device"), (d) => deviceRef(d, "device", known))
117802
118690
  }),
117803
- "endpoints.register": empty2,
117804
- "endpoints.unregister": empty2,
118691
+ "endpoints.register": empty3,
118692
+ "endpoints.unregister": empty3,
118693
+ "endpoints.list": (v) => endpointsListData(known(v, ["agent_dirs"], [], "data")),
118694
+ "session.presenter_open": empty3,
118695
+ "session.presenter_send": empty3,
117805
118696
  "devices.list": (v) => {
117806
118697
  const devices = one(v, "devices");
117807
118698
  return Array.isArray(devices) ? { devices: devices.map(deviceRowOf) } : fail("devices");
117808
118699
  },
117809
118700
  "sessions.list": (v) => ({ query_id: localId(one(v, "query_id"), "query_id") }),
118701
+ "sessions.events.subscribe": empty3,
117810
118702
  "session.attach": (v) => ({ attach: localId(one(v, "attach"), "attach") }),
117811
- "session.detach": empty2,
117812
- "session.command": (v) => ({ command_id: commandId(one(v, "command_id")) }),
118703
+ "session.detach": empty3,
118704
+ "session.command": commandAnswerOf,
117813
118705
  "session.command_part": (v) => ({
117814
118706
  received: uint(one(v, "received"), 0, LOCAL_UPLOAD_PARTS_MAX - 1, "received")
117815
118707
  }),
117816
118708
  "session.read": (v) => ({ query_id: localId(one(v, "query_id"), "query_id") }),
117817
- "enforcement.report": empty2,
117818
- "owner.shutdown_for_upgrade": empty2,
117819
- "session.endpoints": endpointsData,
117820
- "session.locate": locateData,
117821
- ...DELIVERIES_DATA,
118709
+ "enforcement.report": empty3,
118710
+ "owner.shutdown_for_upgrade": empty3,
118711
+ "owner.update_committed": empty3,
118712
+ "control.attach.get": attachState,
118713
+ "control.attach.set": attachState,
118714
+ "control.remote_commands.get": remoteCommandsState,
118715
+ "control.remote_commands.set": remoteCommandsState,
117822
118716
  "control.session_wake.get": sessionWakeState,
117823
118717
  "control.session_wake.set": sessionWakeState,
117824
- "control.attach.get": attachState,
117825
- "control.attach.set": attachState
118718
+ "session.endpoints": endpointsData,
118719
+ "session.locate": (v) => refOf(v, "session.locate data"),
118720
+ ...MACHINE_DATA,
118721
+ ...DELIVERIES_DATA
117826
118722
  };
117827
118723
  var validateResponse = (v, type) => asViolation(() => {
117828
118724
  const m = known(v, ["id", "type", "ok"], ["data", "error"], "response");
@@ -117899,16 +118795,27 @@ class EventAssembler {
117899
118795
  case "session.detached":
117900
118796
  return this.#detached(event.attach);
117901
118797
  case "status.changed":
118798
+ case "sessions.listing_changed":
117902
118799
  case "session.snapshot":
117903
118800
  case "session.snapshot_loading":
117904
118801
  case "session.records":
117905
118802
  case "session.attach_pending":
117906
118803
  case "session.command_state":
117907
118804
  case "session.upload_abort":
118805
+ case "machine.op_state":
118806
+ case "machine.op_result":
118807
+ case "machine.output":
118808
+ case "machine.changed":
118809
+ case "machine.blob_chunk":
118810
+ case "machine.blob_done":
118811
+ case "machine.blob_abort":
117908
118812
  case "session.command_event":
117909
118813
  case "session.command_blob_chunk":
117910
118814
  case "session.command_blob_done":
117911
118815
  case "session.channel_closed":
118816
+ case "session.presenter_frame":
118817
+ case "session.presenter_ended":
118818
+ case "host.update_notice":
117912
118819
  case "delivery.inbound":
117913
118820
  case "delivery.holds":
117914
118821
  case "delivery.wake":
@@ -117956,7 +118863,8 @@ class EventAssembler {
117956
118863
  kind: "session.records",
117957
118864
  attach,
117958
118865
  attach_id: open.position.attach_id,
117959
- records
118866
+ records,
118867
+ seqs: [open.position.seq]
117960
118868
  });
117961
118869
  }
117962
118870
  case "entry": {
@@ -118179,12 +119087,8 @@ class ClientConnection {
118179
119087
  throw error;
118180
119088
  }
118181
119089
  if (!response.ok) {
118182
- const { code, reason, action, limit_chars, path_refusal } = response.error;
118183
- reject(new LocalApiError(code, reason, {
118184
- action,
118185
- ...limit_chars === undefined ? {} : { limit_chars },
118186
- ...path_refusal === undefined ? {} : { path_refusal }
118187
- }));
119090
+ const { code, reason, ...extra } = response.error;
119091
+ reject(new LocalApiError(code, reason, extra));
118188
119092
  return;
118189
119093
  }
118190
119094
  onAnswer?.(response.data);
@@ -118242,64 +119146,7 @@ class ClientConnection {
118242
119146
  }
118243
119147
  }
118244
119148
 
118245
- // packages/device-service-core/src/local-api/transport.ts
118246
- import { lstatSync as lstatSync7, readFileSync as readFileSync47, unlinkSync as unlinkSync11 } from "node:fs";
118247
- import { createConnection, createServer as createServer4 } from "node:net";
118248
- import { join as join119 } from "node:path";
118249
- var ENDPOINT_FILE = "endpoint.json";
118250
- var wrap = (socket, endpoint) => {
118251
- const closeListeners = [];
118252
- let closed = false;
118253
- socket.on("close", () => {
118254
- closed = true;
118255
- for (const listener of closeListeners.splice(0))
118256
- listener();
118257
- });
118258
- socket.on("error", () => {});
118259
- return {
118260
- endpoint,
118261
- write: (bytes) => {
118262
- if (!closed)
118263
- socket.write(bytes);
118264
- },
118265
- close: () => {
118266
- socket.end();
118267
- },
118268
- destroy: () => {
118269
- socket.destroy();
118270
- },
118271
- onData: (listener) => {
118272
- socket.on("data", (chunk) => listener(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)));
118273
- },
118274
- onClose: (listener) => {
118275
- if (closed)
118276
- listener();
118277
- else
118278
- closeListeners.push(listener);
118279
- }
118280
- };
118281
- };
118282
- var readEndpointPort = (stateDir) => {
118283
- const parsed = JSON.parse(readFileSync47(join119(stateDir, ENDPOINT_FILE), "utf8"));
118284
- const port = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "port") : undefined;
118285
- if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
118286
- throw new LocalApiError("insecure_state_dir", "endpoint.json holds no port");
118287
- return port;
118288
- };
118289
- var connectLocal = (stateDir, options = {}) => new Promise((resolve, reject) => {
118290
- const port = process.platform === "win32" ? readEndpointPort(stateDir) : undefined;
118291
- const endpoint = port === undefined ? UNIX_ENDPOINT : tcpEndpoint(port);
118292
- const socket = port === undefined ? createConnection({ path: join119(stateDir, SOCKET_FILE) }) : createConnection({ host: "127.0.0.1", port });
118293
- if (options.background === true)
118294
- socket.unref();
118295
- socket.once("error", reject);
118296
- socket.once("connect", () => {
118297
- socket.off("error", reject);
118298
- resolve(wrap(socket, endpoint));
118299
- });
118300
- });
118301
-
118302
- // packages/device-service-core/src/local-api/client.ts
119149
+ // packages/device-service-core/src/local-api/client-open.ts
118303
119150
  var HANDSHAKE_TIMEOUT_MS = 1e4;
118304
119151
  var REQUEST_TIMEOUT_MS = 30000;
118305
119152
  var realTimer = (expire, ms) => {
@@ -118318,7 +119165,7 @@ var proveAndAuthenticate = async (connection, options) => {
118318
119165
  const welcome = validateWelcome(await connection.firstMessage());
118319
119166
  if (welcome.type === "refused")
118320
119167
  throw new LocalApiError("refused", welcome.reason);
118321
- const token = (options.readToken ?? (() => readToken(options.stateDir)))();
119168
+ const token = options.readToken();
118322
119169
  if (!proofMatches(serverProof(token, nonce, connection.endpoint), welcome.server_proof))
118323
119170
  throw new LocalApiError("server_proof_invalid", "the owner did not prove the per-boot token");
118324
119171
  await connection.request("authenticate", {
@@ -118337,8 +119184,13 @@ var handshake = (connection, options) => new Promise((resolve, reject) => {
118337
119184
  }, HANDSHAKE_TIMEOUT_MS);
118338
119185
  proveAndAuthenticate(connection, options).then(resolve, reject).finally(cancel);
118339
119186
  });
118340
- var sendCommand = async (connection, attach, rpc, command_id, route, accepts) => {
118341
- const marked = accepts === undefined ? {} : { accepts };
119187
+ var sendCommand = async (connection, target, rpc, command_id, given = {}, mark = {}) => {
119188
+ const marked = mark.accepts === undefined ? {} : { accepts: mark.accepts };
119189
+ const route = {
119190
+ ...given.delegated === true && (("attach" in target) || ("endpoint" in target)) ? { delegated: true } : {},
119191
+ ...given.endpoint !== undefined && "attach" in target ? { endpoint: given.endpoint } : {},
119192
+ ...given.locate === true && "endpoint" in target ? { locate: true } : {}
119193
+ };
118342
119194
  const sent = command_id ?? mintId();
118343
119195
  const id = { command_id: sent };
118344
119196
  const timedOut = (error) => {
@@ -118351,8 +119203,9 @@ var sendCommand = async (connection, attach, rpc, command_id, route, accepts) =>
118351
119203
  const draft = {
118352
119204
  id: "x".repeat(REQUEST_ID_MAX_CHARS),
118353
119205
  type: "session.command",
118354
- attach,
119206
+ ...target,
118355
119207
  ...id,
119208
+ ...marked,
118356
119209
  ...route,
118357
119210
  rpc
118358
119211
  };
@@ -118363,50 +119216,14 @@ var sendCommand = async (connection, attach, rpc, command_id, route, accepts) =>
118363
119216
  limit_chars: MESSAGE_LIMIT_CHARS
118364
119217
  });
118365
119218
  const upload_id = mintId();
118366
- const parts = uploadParts(json).map((part) => connection.request("session.command_part", { attach, upload_id, ...part }));
119219
+ const on = "device" in target ? { device: target.device } : target;
119220
+ const parts = uploadParts(json).map((part) => connection.request("session.command_part", { ...on, upload_id, ...part }));
118367
119221
  await Promise.all(parts);
118368
- return (await connection.request("session.command", { attach, ...id, ...marked, ...route, upload_id }).catch(timedOut)).command_id;
119222
+ return (await connection.request("session.command", { ...target, ...id, ...marked, ...route, upload_id }).catch(timedOut)).command_id;
118369
119223
  }
118370
- return (await connection.request("session.command", { attach, ...id, ...marked, ...route, rpc }).catch(timedOut)).command_id;
119224
+ return (await connection.request("session.command", { ...target, ...id, ...marked, ...route, rpc }).catch(timedOut)).command_id;
118371
119225
  };
118372
- var sendWakeCommand = async (connection, device, durableId, rpc, command_id) => {
118373
- const sent = command_id ?? mintId();
118374
- const params = { wake: { device, durable_id: durableId }, command_id: sent, rpc };
118375
- if (lineBytes({ id: "x".repeat(REQUEST_ID_MAX_CHARS), type: "session.command", ...params }) > LOCAL_INLINE_MAX)
118376
- throw new LocalApiError("message_too_long", "a wake command travels inline only", {
118377
- limit_chars: MESSAGE_LIMIT_CHARS
118378
- });
118379
- try {
118380
- return (await connection.request("session.command", params)).command_id;
118381
- } catch (error) {
118382
- if (error instanceof LocalApiError && error.code === "request_timeout")
118383
- throw new LocalApiError("request_timeout", `command ${sent} may have been dispatched; follow its command state`, {
118384
- command_id: sent
118385
- });
118386
- throw error;
118387
- }
118388
- };
118389
- var sendEndpointCommand = async (connection, device, endpoint, rpc, command_id, locate) => {
118390
- const sent = command_id ?? mintId();
118391
- const params = { device, endpoint, command_id: sent, ...locate ? { locate: true } : {}, rpc };
118392
- if (lineBytes({ id: "x".repeat(REQUEST_ID_MAX_CHARS), type: "session.command", ...params }) > LOCAL_INLINE_MAX)
118393
- throw new LocalApiError("message_too_long", "an endpoint command travels inline only", {
118394
- limit_chars: MESSAGE_LIMIT_CHARS
118395
- });
118396
- try {
118397
- return (await connection.request("session.command", params)).command_id;
118398
- } catch (error) {
118399
- if (error instanceof LocalApiError && error.code === "request_timeout")
118400
- throw new LocalApiError("request_timeout", `command ${sent} may have been dispatched; follow its command state`, {
118401
- command_id: sent
118402
- });
118403
- throw error;
118404
- }
118405
- };
118406
- var connectLocalApi = async (options) => {
118407
- if (process.platform !== "win32")
118408
- checkPosixAccess(options.stateDir);
118409
- const transport = await (options.transport ?? (() => connectLocal(options.stateDir)))();
119226
+ var openLocalApiClient = async (transport, options) => {
118410
119227
  const listeners = new Set;
118411
119228
  const assembler = new EventAssembler((event) => {
118412
119229
  for (const listener of [...listeners])
@@ -118427,9 +119244,8 @@ var connectLocalApi = async (options) => {
118427
119244
  listeners.delete(listener);
118428
119245
  };
118429
119246
  },
118430
- command: (attach, rpc, command_id, route = {}, options) => sendCommand(connection, attach, rpc, command_id, route, options?.accepts),
118431
- wakeCommand: (device, durableId, rpc, command_id) => sendWakeCommand(connection, device, durableId, rpc, command_id),
118432
- endpointCommand: (device, endpoint, rpc, command_id, options) => sendEndpointCommand(connection, device, endpoint, rpc, command_id, options?.locate === true),
119247
+ command: (attach, rpc, command_id) => sendCommand(connection, { attach }, rpc, command_id),
119248
+ commandTo: (target, rpc, command_id, route, mark) => sendCommand(connection, target, rpc, command_id, route, mark),
118433
119249
  list: (filter, onRevision, rows) => new Promise((resolve, reject) => {
118434
119250
  const params = {
118435
119251
  ...filter === undefined ? {} : { filter },
@@ -118448,6 +119264,134 @@ var connectLocalApi = async (options) => {
118448
119264
  };
118449
119265
  };
118450
119266
 
119267
+ // packages/device-service-core/src/local-api/transport.ts
119268
+ import { lstatSync as lstatSync7, readFileSync as readFileSync47, unlinkSync as unlinkSync11 } from "node:fs";
119269
+ import { createConnection, createServer as createServer4 } from "node:net";
119270
+ import { join as join119 } from "node:path";
119271
+ var ENDPOINT_FILE = "endpoint.json";
119272
+ var wrap = (socket, endpoint) => {
119273
+ const closeListeners = [];
119274
+ let closed = false;
119275
+ socket.on("close", () => {
119276
+ closed = true;
119277
+ for (const listener of closeListeners.splice(0))
119278
+ listener();
119279
+ });
119280
+ socket.on("error", () => {});
119281
+ return {
119282
+ endpoint,
119283
+ write: (bytes) => {
119284
+ if (!closed)
119285
+ socket.write(bytes);
119286
+ },
119287
+ close: () => {
119288
+ socket.end();
119289
+ },
119290
+ destroy: () => {
119291
+ socket.destroy();
119292
+ },
119293
+ onData: (listener) => {
119294
+ socket.on("data", (chunk) => listener(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)));
119295
+ },
119296
+ onClose: (listener) => {
119297
+ if (closed)
119298
+ listener();
119299
+ else
119300
+ closeListeners.push(listener);
119301
+ }
119302
+ };
119303
+ };
119304
+ var readEndpointPort = (stateDir) => {
119305
+ const parsed = JSON.parse(readFileSync47(join119(stateDir, ENDPOINT_FILE), "utf8"));
119306
+ const port = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "port") : undefined;
119307
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
119308
+ throw new LocalApiError("insecure_state_dir", "endpoint.json holds no port");
119309
+ return port;
119310
+ };
119311
+ var connectLocal = (stateDir) => new Promise((resolve, reject) => {
119312
+ const port = process.platform === "win32" ? readEndpointPort(stateDir) : undefined;
119313
+ const endpoint = port === undefined ? UNIX_ENDPOINT : tcpEndpoint(port);
119314
+ const socket = port === undefined ? createConnection({ path: join119(stateDir, SOCKET_FILE) }) : createConnection({ host: "127.0.0.1", port });
119315
+ socket.once("error", reject);
119316
+ socket.once("connect", () => {
119317
+ socket.off("error", reject);
119318
+ resolve(wrap(socket, endpoint));
119319
+ });
119320
+ });
119321
+
119322
+ // packages/device-service-core/src/local-api/client.ts
119323
+ var connectLocalApi = async (options) => {
119324
+ if (process.platform !== "win32")
119325
+ checkPosixAccess(options.stateDir);
119326
+ const transport = await (options.transport ?? (() => connectLocal(options.stateDir)))();
119327
+ return openLocalApiClient(transport, {
119328
+ client: options.client,
119329
+ readToken: options.readToken ?? (() => readToken(options.stateDir)),
119330
+ ...options.handshakeTimer === undefined ? {} : { handshakeTimer: options.handshakeTimer },
119331
+ ...options.requestTimer === undefined ? {} : { requestTimer: options.requestTimer }
119332
+ });
119333
+ };
119334
+
119335
+ // packages/device-service-core/src/background-transport.ts
119336
+ import { createConnection as createConnection2 } from "node:net";
119337
+ import { join as join120 } from "node:path";
119338
+ var wrap2 = (socket, endpoint) => {
119339
+ const closeListeners = [];
119340
+ let closed = false;
119341
+ socket.on("close", () => {
119342
+ closed = true;
119343
+ for (const listener of closeListeners.splice(0))
119344
+ listener();
119345
+ });
119346
+ socket.on("error", () => {});
119347
+ return {
119348
+ endpoint,
119349
+ write: (bytes) => {
119350
+ if (!closed)
119351
+ socket.write(bytes);
119352
+ },
119353
+ close: () => {
119354
+ socket.end();
119355
+ },
119356
+ destroy: () => {
119357
+ socket.destroy();
119358
+ },
119359
+ onData: (listener) => {
119360
+ socket.on("data", (chunk) => listener(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)));
119361
+ },
119362
+ onClose: (listener) => {
119363
+ if (closed)
119364
+ listener();
119365
+ else
119366
+ closeListeners.push(listener);
119367
+ }
119368
+ };
119369
+ };
119370
+ var connectLocalBackground = (stateDir) => new Promise((resolve, reject) => {
119371
+ const port = process.platform === "win32" ? readEndpointPort(stateDir) : undefined;
119372
+ const endpoint = port === undefined ? UNIX_ENDPOINT : tcpEndpoint(port);
119373
+ const socket = port === undefined ? createConnection2({ path: join120(stateDir, SOCKET_FILE) }) : createConnection2({ host: "127.0.0.1", port });
119374
+ socket.unref();
119375
+ socket.once("error", reject);
119376
+ socket.once("connect", () => {
119377
+ socket.off("error", reject);
119378
+ resolve(wrap2(socket, endpoint));
119379
+ });
119380
+ });
119381
+
119382
+ // packages/device-service-core/src/not-sent-error.ts
119383
+ class NotSentError extends LocalApiError {
119384
+ not_sent = true;
119385
+ }
119386
+ var markNotSent = (error) => error instanceof LocalApiError ? new NotSentError(error.code, error.reason, {
119387
+ action: error.action,
119388
+ ...error.limit_chars === undefined ? {} : { limit_chars: error.limit_chars },
119389
+ ...error.path_refusal === undefined ? {} : { path_refusal: error.path_refusal },
119390
+ ...error.candidates === undefined ? {} : { candidates: error.candidates },
119391
+ ...error.incomplete === undefined ? {} : { incomplete: error.incomplete },
119392
+ ...error.sign_in_reason === undefined ? {} : { sign_in_reason: error.sign_in_reason }
119393
+ }) : error;
119394
+
118451
119395
  // packages/device-service-core/src/remote-attach.ts
118452
119396
  import { randomBytes as randomBytes8 } from "node:crypto";
118453
119397
 
@@ -118585,7 +119529,12 @@ var toRemote = (event) => {
118585
119529
  return { kind: "snapshot", snapshot };
118586
119530
  }
118587
119531
  case "session.records":
118588
- return { kind: "records", attach_id: event.attach_id, records: event.records };
119532
+ return {
119533
+ kind: "records",
119534
+ attach_id: event.attach_id,
119535
+ records: event.records,
119536
+ ...event.seqs === undefined ? {} : { seqs: event.seqs }
119537
+ };
118589
119538
  case "session.attach_pending":
118590
119539
  return { kind: "pending", reason: event.reason };
118591
119540
  case "session.detached":
@@ -118721,7 +119670,7 @@ function openAttach(client, device, sessionId) {
118721
119670
  resolve(response === undefined ? { outcome: event } : { outcome: event, response });
118722
119671
  });
118723
119672
  commands.add(end);
118724
- client.command(attach, rpc, commandId, { delegated: true }, options).catch((error) => {
119673
+ client.commandTo({ attach }, rpc, commandId, { delegated: true }, options).catch((error) => {
118725
119674
  settle();
118726
119675
  reject(error);
118727
119676
  });
@@ -118808,19 +119757,19 @@ var compareVersions4 = (a, b) => {
118808
119757
  // packages/device-service-core/src/state-dir.ts
118809
119758
  import { readFileSync as readFileSync48, statSync as statSync10 } from "node:fs";
118810
119759
  import { homedir as homedir36 } from "node:os";
118811
- import { dirname as dirname49, join as join120, posix as posix17, win32 as win3212 } from "node:path";
119760
+ import { dirname as dirname49, join as join121, posix as posix17, win32 as win3212 } from "node:path";
118812
119761
  var DEVICE_SERVICE_STATE_DIR_ENV = "OMO_DEVICE_SERVICE_STATE_DIR";
118813
119762
  var LOCATION_FILE = "device-service.location.json";
118814
119763
  var isAbsoluteOn = (platform, path) => (platform === "win32" ? win3212 : posix17).isAbsolute(path);
118815
119764
  function defaultStateDir(platform, env, home) {
118816
119765
  if (platform !== "win32")
118817
- return join120(home, ".omo", "device-service");
118818
- const localAppData = env.LOCALAPPDATA ?? join120(home, "AppData", "Local");
118819
- return join120(localAppData, "OmO", "device-service");
119766
+ return join121(home, ".omo", "device-service");
119767
+ const localAppData = env.LOCALAPPDATA ?? join121(home, "AppData", "Local");
119768
+ return join121(localAppData, "OmO", "device-service");
118820
119769
  }
118821
119770
  function discoveredStateDir(platform, defaultDir) {
118822
119771
  try {
118823
- const parsed = JSON.parse(readFileSync48(join120(dirname49(defaultDir), LOCATION_FILE), "utf8"));
119772
+ const parsed = JSON.parse(readFileSync48(join121(dirname49(defaultDir), LOCATION_FILE), "utf8"));
118824
119773
  if (typeof parsed !== "object" || parsed === null || !("v" in parsed) || !("state_dir" in parsed))
118825
119774
  return;
118826
119775
  const { v, state_dir: stateDir } = parsed;
@@ -118842,7 +119791,7 @@ function deviceServiceStateDir(platform = process.platform, env = process.env, h
118842
119791
  var ENDPOINT_COMMAND_WAIT_MS = 120000;
118843
119792
  function sendToEndpoint(client, device, endpoint, rpc, locate) {
118844
119793
  return followDelegatedCommand(client, device, (commandId) => {
118845
- const send = (asked) => client.endpointCommand(device, endpoint, rpc, commandId, { locate: asked });
119794
+ const send = (asked) => client.commandTo({ device, endpoint }, rpc, commandId, asked ? { locate: true } : {});
118846
119795
  return send(locate).catch((error) => locate && error instanceof LocalApiError && error.code === "invalid_request" ? send(false) : Promise.reject(error));
118847
119796
  });
118848
119797
  }
@@ -118884,14 +119833,8 @@ function followDelegatedCommand(client, device, send) {
118884
119833
  send(commandId).catch(fail);
118885
119834
  });
118886
119835
  }
118887
- var markNotSent = (error) => error instanceof LocalApiError ? new LocalApiError(error.code, error.reason, {
118888
- action: error.action,
118889
- ...error.limit_chars === undefined ? {} : { limit_chars: error.limit_chars },
118890
- ...error.path_refusal === undefined ? {} : { path_refusal: error.path_refusal },
118891
- not_sent: true
118892
- }) : error;
118893
119836
  function deviceServiceEndpointPath(stateDir, platform = process.platform) {
118894
- return join121(stateDir, platform === "win32" ? ENDPOINT_FILE : SOCKET_FILE);
119837
+ return join122(stateDir, platform === "win32" ? ENDPOINT_FILE : SOCKET_FILE);
118895
119838
  }
118896
119839
  var ADOPT_ACCOUNT_MIN_SERVICE_VERSION = "0.1.3";
118897
119840
  var acceptsAdoptAccount = (serviceVersion) => compareVersions4(serviceVersion, ADOPT_ACCOUNT_MIN_SERVICE_VERSION) >= 0;
@@ -118903,7 +119846,7 @@ async function connectDeviceService(options) {
118903
119846
  const client = await (options.connect ?? connectLocalApi)({
118904
119847
  stateDir,
118905
119848
  client: { name: "omo", version: options.version },
118906
- ...options.background === true ? { transport: () => connectLocal(stateDir, { background: true }) } : {}
119849
+ ...options.background === true ? { transport: () => connectLocalBackground(stateDir) } : {}
118907
119850
  });
118908
119851
  const wakeMarkMinimum = minimumInEffect(options.minimums, "wakeMark", WAKE_MARK_MIN_SERVICE_VERSION);
118909
119852
  const carriesWakeMark = serviceAtLeast(client.welcome.service_version, wakeMarkMinimum);
@@ -118964,7 +119907,7 @@ async function connectDeviceService(options) {
118964
119907
  throw markNotSent(error);
118965
119908
  }
118966
119909
  if (endpoint === undefined)
118967
- throw new LocalApiError("unsupported", "the device lists no engine endpoint", { not_sent: true });
119910
+ throw new NotSentError("unsupported", "the device lists no engine endpoint");
118968
119911
  return await sendToEndpoint(client, device, endpoint, rpc, options?.locate === true);
118969
119912
  },
118970
119913
  close: () => client.close(),
@@ -118976,8 +119919,8 @@ async function connectDeviceService(options) {
118976
119919
  }),
118977
119920
  wakeCommand: async (device, durableId, rpc) => {
118978
119921
  if (!carriesWakeMark)
118979
- throw new LocalApiError("unsupported", "this device service does not carry the wake target", { not_sent: true });
118980
- return await followDelegatedCommand(client, device, (commandId) => client.wakeCommand(device, durableId, rpc, commandId).catch((error) => {
119922
+ throw new NotSentError("unsupported", "this device service does not carry the wake target");
119923
+ return await followDelegatedCommand(client, device, (commandId) => client.commandTo({ wake: { device, durable_id: durableId } }, rpc, commandId).catch((error) => {
118981
119924
  throw error instanceof LocalApiError && error.command_id === undefined ? markNotSent(error) : error;
118982
119925
  }));
118983
119926
  }
@@ -119048,6 +119991,61 @@ var SERVICE_TABLE_ENV = "OMO_RELAYD_SERVICES";
119048
119991
 
119049
119992
  // packages/device-service-core/src/cold-wake/darwin.ts
119050
119993
  var TABLE_KEY = `EnvironmentVariables.${SERVICE_TABLE_ENV}`;
119994
+ // packages/device-service-core/src/release/windows-dacl.ts
119995
+ import { spawn as spawn7 } from "node:child_process";
119996
+ var SID_TOKEN_SCRIPT = String.raw`
119997
+ $ErrorActionPreference = 'Stop'
119998
+ (New-Object System.Security.AccessControl.RawSecurityDescriptor("O:$env:LA_SID")).GetSddlForm('Owner')
119999
+ `;
120000
+ var runPowerShell2 = async (script, env) => {
120001
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
120002
+ const proc = spawn7("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
120003
+ const chunks = [];
120004
+ const errChunks = [];
120005
+ proc.stdout.on("data", (chunk) => chunks.push(chunk));
120006
+ proc.stderr.on("data", (chunk) => errChunks.push(chunk));
120007
+ const code = await new Promise((resolve, reject) => {
120008
+ proc.once("error", reject);
120009
+ proc.once("close", (exitCode) => resolve(exitCode ?? -1));
120010
+ });
120011
+ return { code, out: Buffer.concat(chunks).toString("utf8"), err: Buffer.concat(errChunks).toString("utf8") };
120012
+ };
120013
+ var firstErrorLine = (err) => {
120014
+ const line = (err ?? "").split(/\r?\n/).find((text) => text.trim() !== "" && !text.startsWith("#< CLIXML"))?.trim() ?? "";
120015
+ return line === "" ? "" : `: ${line.slice(0, 300)}`;
120016
+ };
120017
+ var userSidToken = async (userSid, run = runPowerShell2) => {
120018
+ const { code, out } = await run(SID_TOKEN_SCRIPT, { LA_SID: userSid });
120019
+ const match = code === 0 ? /^O:(S-1-\d+(?:-\d+)+|[A-Z]{2})$/.exec(out.trim()) : null;
120020
+ return match?.[1];
120021
+ };
120022
+ var aliasedDaclVerdict = (dacl, userSid, kind, userAlias) => {
120023
+ const asSid = (token) => userAlias !== undefined && token === userAlias ? userSid : token;
120024
+ return exactDaclVerdict({ ...dacl, owner: asSid(dacl.owner), aces: dacl.aces.map((ace) => ({ ...ace, sid: asSid(ace.sid) })) }, userSid, kind);
120025
+ };
120026
+ var applyExactDacl2 = async (path, userSid, kind, run = runPowerShell2) => {
120027
+ const { code, err } = await run(APPLY_DACL_SCRIPT, { LA_PATH: path, LA_SID: userSid, LA_KIND: kind });
120028
+ if (code !== 0)
120029
+ throw new LocalApiError("insecure_state_dir", `the exact DACL could not be applied${firstErrorLine(err)}`);
120030
+ };
120031
+ var verifyExactDacl2 = async (path, userSid, kind, run = runPowerShell2) => {
120032
+ let dacl;
120033
+ try {
120034
+ dacl = await describeDacl(path, run);
120035
+ } catch (error) {
120036
+ if (error instanceof LocalApiError)
120037
+ return false;
120038
+ throw error;
120039
+ }
120040
+ return aliasedDaclVerdict(dacl, userSid, kind, await userSidToken(userSid, run));
120041
+ };
120042
+ var windowsSecureFile2 = (userSid, run = runPowerShell2) => async (path, kind) => {
120043
+ const target = kind === "dir" ? "dir" : "file";
120044
+ await applyExactDacl2(path, userSid, target, run);
120045
+ if (!await verifyExactDacl2(path, userSid, target, run))
120046
+ throw new LocalApiError("insecure_state_dir", "the DACL is not exactly one ACE for the user");
120047
+ };
120048
+
119051
120049
  // packages/device-service-core/src/release/release-assets.ts
119052
120050
  var MANIFEST = "latest.json";
119053
120051
  var CHECKSUMS_MAX_BYTES = 64 * 1024;
@@ -119113,13 +120111,13 @@ var parseReleaseKeySet = (value) => {
119113
120111
  };
119114
120112
  var DEVICE_SERVICE_RELEASE_KEYS = parseReleaseKeySet(release_key_default);
119115
120113
  // packages/device-service-core/src/release/acquire.ts
119116
- var platformSecure = process.platform === "win32" ? async (path, kind) => windowsSecureFile(await currentUserSid())(path, kind) : posixSecureFile;
120114
+ var platformSecure = process.platform === "win32" ? async (path, kind) => windowsSecureFile2(await currentUserSid())(path, kind) : posixSecureFile;
119117
120115
  // packages/device-service-core/src/registrant.ts
119118
120116
  var NONE2 = Symbol("none registered");
119119
120117
  // packages/omo-native/package.json
119120
120118
  var package_default4 = {
119121
120119
  name: "omo-ai",
119122
- version: "5.1.72",
120120
+ version: "5.1.73",
119123
120121
  type: "module",
119124
120122
  description: "OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",
119125
120123
  bin: {
@@ -119221,6 +120219,825 @@ function cliDeviceServiceHandoff(options) {
119221
120219
  };
119222
120220
  }
119223
120221
 
120222
+ // packages/memory-core/src/journal/fsync.ts
120223
+ var SKIPPABLE_SYNC_CODES = new Set(["ENOENT", "EISDIR", "EPERM", "EACCES", "EINVAL"]);
120224
+
120225
+ // packages/memory-core/src/sync/crypto/vendor/sync-format/keys.ts
120226
+ var hexBytes = (hex) => {
120227
+ const pairs = hex.match(/../g);
120228
+ return Uint8Array.from((pairs ?? []).map((pair) => Number.parseInt(pair, 16)));
120229
+ };
120230
+ var ED25519_PKCS8_PREFIX = hexBytes("302e020100300506032b657004220420");
120231
+ var ED25519_SPKI_PREFIX = hexBytes("302a300506032b6570032100");
120232
+ // packages/memory-core/src/sync/crypto/anchor.ts
120233
+ var anchors = new WeakSet;
120234
+ var candidates = new WeakSet;
120235
+ var bootstraps = new WeakSet;
120236
+
120237
+ // packages/memory-core/src/sync/crypto/strict-ed25519/strict-ed25519.ts
120238
+ var P2 = (1n << 255n) - 19n;
120239
+ var L2 = (1n << 252n) + 27742317777372353535851937790883648493n;
120240
+ var mod2 = (n) => {
120241
+ const r = n % P2;
120242
+ return r < 0n ? r + P2 : r;
120243
+ };
120244
+ var power2 = (base, exponent) => {
120245
+ let result = 1n;
120246
+ let b = mod2(base);
120247
+ for (let n = exponent;n > 0n; n >>= 1n) {
120248
+ if (n & 1n)
120249
+ result = mod2(result * b);
120250
+ b = mod2(b * b);
120251
+ }
120252
+ return result;
120253
+ };
120254
+ var D2 = mod2(-121665n * power2(121666n, P2 - 2n));
120255
+ var SQRT_MINUS_ONE2 = power2(2n, (P2 - 1n) / 4n);
120256
+ var keyCache2 = new Map;
120257
+
120258
+ // packages/memory-core/src/sync/crypto/trust-pin.ts
120259
+ var SOURCES = new Set(["pairing", "recovery", "creator"]);
120260
+
120261
+ // packages/omo-senpi/src/components/thread/errors.ts
120262
+ var THREAD_ERROR_CODES = [
120263
+ "invalid_arguments",
120264
+ "caller_context_missing",
120265
+ "not_found",
120266
+ "reply_target_mismatch",
120267
+ "ambiguous_target",
120268
+ "scope_denied",
120269
+ "name_conflict",
120270
+ "not_resumable",
120271
+ "orphaned",
120272
+ "foreign_live_owner",
120273
+ "no_active_turn",
120274
+ "turn_conflict",
120275
+ "not_steerable",
120276
+ "message_too_large",
120277
+ "queue_full",
120278
+ "cursor_invalid",
120279
+ "cursor_stale",
120280
+ "idempotency_conflict",
120281
+ "idempotency_in_progress",
120282
+ "idempotency_uncertain",
120283
+ "approval_unavailable",
120284
+ "approval_route_locked",
120285
+ "partial_commit",
120286
+ "unsupported",
120287
+ "overloaded",
120288
+ "transport_closed",
120289
+ "host_unavailable",
120290
+ "internal_error",
120291
+ "model_not_found",
120292
+ "model_ambiguous",
120293
+ "thinking_level_unsupported",
120294
+ "loop_detected",
120295
+ "binding_conflict",
120296
+ "binding_mismatch",
120297
+ "binding_inactive",
120298
+ "stale_revision",
120299
+ "stale_token",
120300
+ "already_answered",
120301
+ "answer_in_progress",
120302
+ "device_offline",
120303
+ "relay_requires_paid_plan",
120304
+ "alias_taken"
120305
+ ];
120306
+ var CODE_SET = new Set(THREAD_ERROR_CODES);
120307
+
120308
+ // packages/omo-senpi/src/components/thread/remote/outcome.ts
120309
+ var READ_UNCERTAIN = {
120310
+ request_gone: "retry",
120311
+ no_receipt: "retry",
120312
+ engine_restarted: "retry",
120313
+ recipient_revoked: "retry",
120314
+ transport_expired: "retry",
120315
+ unconfirmed: "retry",
120316
+ lease_expired: "retry",
120317
+ cancelled: "retry",
120318
+ hand_restarted: "retry",
120319
+ result_expired: "retry",
120320
+ record_too_large: "too_large",
120321
+ result_undecodable: "retry"
120322
+ };
120323
+ var UNANSWERED = new Set([
120324
+ "closed",
120325
+ "protocol_violation",
120326
+ "internal",
120327
+ "read_failed",
120328
+ "request_timeout",
120329
+ "handshake_timeout",
120330
+ "attach_failed",
120331
+ "reply_lost",
120332
+ "host_not_answering",
120333
+ "peer_not_found",
120334
+ "engine_stale",
120335
+ ...Object.entries(READ_UNCERTAIN).filter(([, answer]) => answer === "retry").map(([reason]) => reason)
120336
+ ]);
120337
+
120338
+ // packages/omo-native/remote-attach.ts
120339
+ var MAX_LINE_CHARS = 64 * 1024 * 1024;
120340
+
120341
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/memory/metrics.mjs
120342
+ var Metrics = {
120343
+ assign: 0,
120344
+ create: 0,
120345
+ clone: 0,
120346
+ discard: 0,
120347
+ update: 0
120348
+ };
120349
+
120350
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/guard/guard.mjs
120351
+ function IsArray(value) {
120352
+ return Array.isArray(value);
120353
+ }
120354
+ function IsBigInt(value) {
120355
+ return IsEqual(typeof value, "bigint");
120356
+ }
120357
+ function IsBoolean(value) {
120358
+ return IsEqual(typeof value, "boolean");
120359
+ }
120360
+ function IsNull(value) {
120361
+ return IsEqual(value, null);
120362
+ }
120363
+ function IsNumber(value) {
120364
+ return Number.isFinite(value);
120365
+ }
120366
+ function IsObject(value) {
120367
+ return IsEqual(typeof value, "object") && !IsNull(value);
120368
+ }
120369
+ function IsString(value) {
120370
+ return IsEqual(typeof value, "string");
120371
+ }
120372
+ function IsEqual(left, right) {
120373
+ return left === right;
120374
+ }
120375
+ function IsClassInstance(value) {
120376
+ if (!IsObject(value))
120377
+ return false;
120378
+ const proto = globalThis.Object.getPrototypeOf(value);
120379
+ if (IsNull(proto))
120380
+ return false;
120381
+ return IsEqual(typeof proto.constructor, "function") && !(IsEqual(proto.constructor, globalThis.Object) || IsEqual(proto.constructor.name, "Object"));
120382
+ }
120383
+ function IsUnsafePropertyKey(key) {
120384
+ return IsEqual(key, "__proto__") || IsEqual(key, "constructor") || IsEqual(key, "prototype");
120385
+ }
120386
+ function HasPropertyKey(value, key) {
120387
+ return IsUnsafePropertyKey(key) ? Object.prototype.hasOwnProperty.call(value, key) : (key in value);
120388
+ }
120389
+ function Keys(value) {
120390
+ return Object.getOwnPropertyNames(value);
120391
+ }
120392
+ function Symbols(value) {
120393
+ return Object.getOwnPropertySymbols(value);
120394
+ }
120395
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/guard/globals.mjs
120396
+ function IsTypeArray(value) {
120397
+ return globalThis.ArrayBuffer.isView(value);
120398
+ }
120399
+ function IsRegExp(value) {
120400
+ return value instanceof globalThis.RegExp;
120401
+ }
120402
+ function IsSet(value) {
120403
+ return value instanceof globalThis.Set;
120404
+ }
120405
+ function IsMap(value) {
120406
+ return value instanceof globalThis.Map;
120407
+ }
120408
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/settings/settings.mjs
120409
+ var settings2 = {
120410
+ immutableTypes: false,
120411
+ maxErrors: 8,
120412
+ maxParseErrors: 1,
120413
+ maxInstantiationCount: 128,
120414
+ useAcceleration: true,
120415
+ exactOptionalPropertyTypes: false,
120416
+ enumerableKind: false,
120417
+ correctiveParse: false,
120418
+ unionPrioritySort: true
120419
+ };
120420
+ function Get() {
120421
+ return settings2;
120422
+ }
120423
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/memory/freeze.mjs
120424
+ function Freeze(value) {
120425
+ return Get().immutableTypes ? Object.freeze(value) : value;
120426
+ }
120427
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/memory/clone.mjs
120428
+ function FromClassInstance(value) {
120429
+ return value;
120430
+ }
120431
+ function IsSchemaObject(value) {
120432
+ return HasPropertyKey(value, "~kind") || HasPropertyKey(value, "~unsafe");
120433
+ }
120434
+ function FromSchemaObject(value) {
120435
+ const result = {};
120436
+ for (const key of Keys(value)) {
120437
+ if (IsUnsafePropertyKey(key))
120438
+ continue;
120439
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
120440
+ descriptor.value = FromValue(descriptor.value);
120441
+ if (IsEqual(descriptor.enumerable, true)) {
120442
+ result[key] = descriptor.value;
120443
+ } else {
120444
+ Object.defineProperty(result, key, descriptor);
120445
+ }
120446
+ }
120447
+ return result;
120448
+ }
120449
+ function FromPlainObject(value) {
120450
+ const result = {};
120451
+ for (const key of Keys(value)) {
120452
+ if (IsUnsafePropertyKey(key))
120453
+ continue;
120454
+ result[key] = FromValue(value[key]);
120455
+ }
120456
+ for (const key of Symbols(value)) {
120457
+ result[key] = FromValue(value[key]);
120458
+ }
120459
+ return result;
120460
+ }
120461
+ function FromObject(value) {
120462
+ return IsClassInstance(value) ? FromClassInstance(value) : IsSchemaObject(value) ? FromSchemaObject(value) : FromPlainObject(value);
120463
+ }
120464
+ function FromArray(value) {
120465
+ return value.map((element) => FromValue(element));
120466
+ }
120467
+ function FromTypedArray(value) {
120468
+ return value.slice();
120469
+ }
120470
+ function FromRegExp(value) {
120471
+ return new RegExp(value.source, value.flags);
120472
+ }
120473
+ function FromMap(value) {
120474
+ return new Map(FromValue([...value.entries()]));
120475
+ }
120476
+ function FromSet(value) {
120477
+ return new Set(FromValue([...value.values()]));
120478
+ }
120479
+ function FromValue(value) {
120480
+ return IsTypeArray(value) ? FromTypedArray(value) : IsRegExp(value) ? FromRegExp(value) : IsMap(value) ? FromMap(value) : IsSet(value) ? FromSet(value) : IsArray(value) ? FromArray(value) : IsObject(value) ? FromObject(value) : value;
120481
+ }
120482
+ function Clone(value) {
120483
+ Metrics.clone += 1;
120484
+ return FromValue(value);
120485
+ }
120486
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/memory/create.mjs
120487
+ function MergeHidden(left, right) {
120488
+ for (const key of Object.keys(right)) {
120489
+ Object.defineProperty(left, key, {
120490
+ configurable: true,
120491
+ writable: true,
120492
+ enumerable: false,
120493
+ value: right[key]
120494
+ });
120495
+ }
120496
+ return left;
120497
+ }
120498
+ function Merge(left, right) {
120499
+ return { ...left, ...right };
120500
+ }
120501
+ function Create(hidden, enumerable, options = {}) {
120502
+ Metrics.create += 1;
120503
+ const withOptions = Merge(enumerable, options);
120504
+ const withHidden = Get().enumerableKind ? Merge(withOptions, hidden) : MergeHidden(withOptions, hidden);
120505
+ return Freeze(withHidden);
120506
+ }
120507
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/memory/update.mjs
120508
+ function Update(current, hidden, enumerable) {
120509
+ Metrics.update += 1;
120510
+ const settings = Get();
120511
+ const result = Clone(current);
120512
+ for (const key of Object.keys(hidden)) {
120513
+ Object.defineProperty(result, key, {
120514
+ configurable: true,
120515
+ writable: true,
120516
+ enumerable: settings.enumerableKind,
120517
+ value: hidden[key]
120518
+ });
120519
+ }
120520
+ for (const key of Object.keys(enumerable)) {
120521
+ Object.defineProperty(result, key, {
120522
+ configurable: true,
120523
+ enumerable: true,
120524
+ writable: true,
120525
+ value: enumerable[key]
120526
+ });
120527
+ }
120528
+ return Freeze(result);
120529
+ }
120530
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs
120531
+ function AddOptionalOperation(type) {
120532
+ return Update(type, { "~optional": true }, {});
120533
+ }
120534
+ function AddOptionalAction(type, options) {
120535
+ const result = Update(AddOptionalOperation(type), {}, options);
120536
+ return result;
120537
+ }
120538
+
120539
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/action/_add_optional.mjs
120540
+ function AddOptional(type, options = {}) {
120541
+ return AddOptionalAction(type, options);
120542
+ }
120543
+
120544
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/_optional.mjs
120545
+ function Optional(type) {
120546
+ return AddOptional(type);
120547
+ }
120548
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/system/hashing/hash.mjs
120549
+ var ByteMarker;
120550
+ (function(ByteMarker) {
120551
+ ByteMarker[ByteMarker["Array"] = 0] = "Array";
120552
+ ByteMarker[ByteMarker["BigInt"] = 1] = "BigInt";
120553
+ ByteMarker[ByteMarker["Boolean"] = 2] = "Boolean";
120554
+ ByteMarker[ByteMarker["Date"] = 3] = "Date";
120555
+ ByteMarker[ByteMarker["Constructor"] = 4] = "Constructor";
120556
+ ByteMarker[ByteMarker["Function"] = 5] = "Function";
120557
+ ByteMarker[ByteMarker["Null"] = 6] = "Null";
120558
+ ByteMarker[ByteMarker["Number"] = 7] = "Number";
120559
+ ByteMarker[ByteMarker["Object"] = 8] = "Object";
120560
+ ByteMarker[ByteMarker["RegExp"] = 9] = "RegExp";
120561
+ ByteMarker[ByteMarker["String"] = 10] = "String";
120562
+ ByteMarker[ByteMarker["Symbol"] = 11] = "Symbol";
120563
+ ByteMarker[ByteMarker["TypeArray"] = 12] = "TypeArray";
120564
+ ByteMarker[ByteMarker["Undefined"] = 13] = "Undefined";
120565
+ })(ByteMarker || (ByteMarker = {}));
120566
+ var Accumulator = BigInt("14695981039346656037");
120567
+ var [Prime, Size] = [BigInt("1099511628211"), BigInt("18446744073709551616")];
120568
+ var Bytes = Array.from({ length: 256 }).map((_, i) => BigInt(i));
120569
+ var F64 = new Float64Array(1);
120570
+ var F64In = new DataView(F64.buffer);
120571
+ var F64Out = new Uint8Array(F64.buffer);
120572
+ var encoder4 = new TextEncoder;
120573
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/boolean.mjs
120574
+ function Boolean2(options) {
120575
+ return Create({ "~kind": "Boolean" }, { type: "boolean" }, options);
120576
+ }
120577
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/integer.mjs
120578
+ var IntegerPattern = "-?(?:0|[1-9][0-9]*)";
120579
+ function Integer(options) {
120580
+ return Create({ "~kind": "Integer" }, { type: "integer" }, options);
120581
+ }
120582
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/literal.mjs
120583
+ class InvalidLiteralValue extends Error {
120584
+ constructor(value) {
120585
+ super(`Invalid Literal value`);
120586
+ Object.defineProperty(this, "cause", {
120587
+ value: { value },
120588
+ writable: false,
120589
+ configurable: false,
120590
+ enumerable: false
120591
+ });
120592
+ }
120593
+ }
120594
+ function LiteralTypeName(value) {
120595
+ return IsBigInt(value) ? "bigint" : IsBoolean(value) ? "boolean" : IsNumber(value) ? "number" : IsString(value) ? "string" : (() => {
120596
+ throw new InvalidLiteralValue(value);
120597
+ })();
120598
+ }
120599
+ function Literal(value, options) {
120600
+ return Create({ "~kind": "Literal" }, { type: LiteralTypeName(value), const: value }, options);
120601
+ }
120602
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/number.mjs
120603
+ var NumberPattern = "-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";
120604
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/string.mjs
120605
+ var StringPattern = ".*";
120606
+ function String2(options) {
120607
+ return Create({ "~kind": "String" }, { type: "string" }, options);
120608
+ }
120609
+
120610
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/union.mjs
120611
+ function Union(anyOf, options = {}) {
120612
+ return Create({ "~kind": "Union" }, { anyOf }, options);
120613
+ }
120614
+
120615
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/types/record.mjs
120616
+ var IntegerKey = `^${IntegerPattern}$`;
120617
+ var NumberKey = `^${NumberPattern}$`;
120618
+ var StringKey = `^${StringPattern}$`;
120619
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/script/token/internal/char.mjs
120620
+ function Range(start, end) {
120621
+ return Array.from({ length: end - start + 1 }, (_, i) => String.fromCharCode(start + i));
120622
+ }
120623
+ var Alpha = [
120624
+ ...Range(97, 122),
120625
+ ...Range(65, 90)
120626
+ ];
120627
+ var Zero = "0";
120628
+ var NonZero = Range(49, 57);
120629
+ var Digit = [Zero, ...NonZero];
120630
+ var UnderScore = "_";
120631
+ var DollarSign = "$";
120632
+
120633
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/script/token/unsigned_integer.mjs
120634
+ var AllowedDigits = [...Digit, UnderScore];
120635
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/script/token/ident.mjs
120636
+ var Initial = [...Alpha, UnderScore, DollarSign];
120637
+ var Remaining = [...Initial, ...Digit];
120638
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/script/token/unsigned_number.mjs
120639
+ var AllowedDigits2 = [...Digit, UnderScore];
120640
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/engine/helpers/keys.mjs
120641
+ var integerKeyPattern = new RegExp("^(?:0|[1-9][0-9]*)$");
120642
+
120643
+ // node_modules/.bun/typebox@1.3.34/node_modules/typebox/build/type/engine/indexed/from_object.mjs
120644
+ var NumericKeyPattern = new RegExp(IntegerKey);
120645
+ // packages/omo-senpi/src/components/thread/gateway/bindings.ts
120646
+ var BINDING_MAX_TTL_SECONDS = 366 * 24 * 60 * 60;
120647
+ var OUTBOX_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
120648
+ var RELAY_TEXT_MAX_BYTES = 32768;
120649
+
120650
+ // packages/omo-senpi/src/components/thread/contracts/fields.ts
120651
+ var THREAD_MESSAGE_MAX_BYTES = 32768;
120652
+ var THREAD_SUMMARY_MAX_LENGTH = 200;
120653
+ var ThreadAddress = String2({
120654
+ description: "Recipient thread id or unique name as returned by thread_list; a name shared by several threads returns ambiguous_target with candidates."
120655
+ });
120656
+ var AllScope = Optional(Boolean2({
120657
+ description: "Address threads in every workspace on this machine instead of only the caller's workspace; left unset, an exact id from another workspace returns scope_denied."
120658
+ }));
120659
+ var IdempotencyKey = Optional(String2({
120660
+ description: "Caller-chosen key that makes a retried call return the earlier result instead of repeating the side effect; reusing the key with different arguments returns idempotency_conflict."
120661
+ }));
120662
+ var ExpectedTurnId = Optional(String2({
120663
+ description: "Turn id the steer applies to; required with delivery steer, and a changed active turn returns turn_conflict with the message held undelivered."
120664
+ }));
120665
+ var Summary = Optional(String2({
120666
+ maxLength: THREAD_SUMMARY_MAX_LENGTH,
120667
+ description: "One-line preview shown to the caller when the completion notice arrives."
120668
+ }));
120669
+ var Message2 = String2({
120670
+ maxLength: THREAD_MESSAGE_MAX_BYTES,
120671
+ description: `Instruction to deliver to the target thread; longer than ${THREAD_MESSAGE_MAX_BYTES} UTF-8 bytes returns message_too_large.`
120672
+ });
120673
+ var BindingId = String2({
120674
+ minLength: 1,
120675
+ description: "Binding id as returned by thread_bind or thread_bindings."
120676
+ });
120677
+ var ExpectedRevision = Integer({
120678
+ minimum: 1,
120679
+ description: "Revision the caller last saw for this binding; a binding that moved since returns stale_revision."
120680
+ });
120681
+ var RelayText = String2({
120682
+ description: `Text relayed to or from the external thread; longer than ${RELAY_TEXT_MAX_BYTES} UTF-8 bytes returns message_too_large.`
120683
+ });
120684
+ var ThreadDeliveryMode = Union([Literal("auto"), Literal("steer"), Literal("follow_up")], {
120685
+ description: "auto steers the running turn when one is active and starts a new turn otherwise; steer requires expected_turn_id and becomes turn_conflict when the active turn changed; follow_up queues the message behind the running turn."
120686
+ });
120687
+
120688
+ // packages/omo-native/remote-session-args.ts
120689
+ var SESSION_VERBS = ["open", "send", "model", "interrupt", "close"];
120690
+
120691
+ // packages/omo-senpi/src/components/thread/control/port.ts
120692
+ var REFUSAL = Symbol.for("omo.thread.control.refusal");
120693
+
120694
+ // packages/omo-senpi/src/components/thread/control/close-ladder.ts
120695
+ var SESSION_GONE = new Set([
120696
+ "unknown_session",
120697
+ "session_identity_mismatch",
120698
+ "session_not_attached",
120699
+ "not_attached"
120700
+ ]);
120701
+
120702
+ // packages/omo-senpi/src/components/thread/thread-link.ts
120703
+ var THREAD_LINK_SCHEME = "omo-thread";
120704
+ var PREFIX = `${THREAD_LINK_SCHEME}://v1/`;
120705
+
120706
+ // packages/omo-senpi/src/components/thread/remote/address-book.ts
120707
+ var REMOTE_NOT_SET_UP = new Set(["not_configured", "disabled", "signed_out", "sign_in_required"]);
120708
+
120709
+ // packages/omo-senpi/src/components/thread/session-facts.ts
120710
+ var SESSION_FACTS_WINDOW_BYTES = 64 * 1024;
120711
+ var SESSION_FACTS_LAST_LINE_MAX_BYTES = SESSION_FACTS_WINDOW_BYTES * 4;
120712
+
120713
+ // packages/omo-senpi/src/components/thread/metadata.ts
120714
+ var THREAD_TOOL_EXPOSURE = "eval";
120715
+ var ROUTE_TO_TASK = "; to spawn a child task instead, use task.";
120716
+ var THREAD_TOOL_METADATA = [
120717
+ {
120718
+ name: "thread_create",
120719
+ label: "Create session",
120720
+ description: "Starts a fresh agent session that runs alongside this one, for when the user wants a second session working in parallel" + ROUTE_TO_TASK,
120721
+ exposure: THREAD_TOOL_EXPOSURE
120722
+ },
120723
+ {
120724
+ name: "thread_list",
120725
+ label: "List sessions",
120726
+ description: "Shows every addressable session on this device and the account's other devices with its id, name, status and device, plus the account's devices, for when the user needs a valid target address before acting on a session" + ROUTE_TO_TASK,
120727
+ exposure: THREAD_TOOL_EXPOSURE
120728
+ },
120729
+ {
120730
+ name: "thread_read",
120731
+ label: "Read session",
120732
+ description: "Returns the transcript and latest output of another session, for when the user asks what another session said or produced" + ROUTE_TO_TASK,
120733
+ exposure: THREAD_TOOL_EXPOSURE
120734
+ },
120735
+ {
120736
+ name: "thread_send",
120737
+ label: "Send message to session",
120738
+ description: "Delivers a message into another session that is already running, for when the user wants to talk to that session mid-task; its reply comes back through thread_read, and a bound chat thread's replies through thread_report and thread_answer" + ROUTE_TO_TASK,
120739
+ exposure: THREAD_TOOL_EXPOSURE
120740
+ },
120741
+ {
120742
+ name: "thread_interrupt",
120743
+ label: "Interrupt session turn",
120744
+ description: "Stops the turn running in another session, for when the user wants to halt a session that is going down the wrong path" + ROUTE_TO_TASK,
120745
+ exposure: THREAD_TOOL_EXPOSURE
120746
+ },
120747
+ {
120748
+ name: "thread_close",
120749
+ label: "Close session",
120750
+ description: "Closes another session on this device or on another of the account's devices, for when the user is done with that session and wants it shut down" + ROUTE_TO_TASK,
120751
+ exposure: THREAD_TOOL_EXPOSURE
120752
+ },
120753
+ {
120754
+ name: "thread_handoff",
120755
+ label: "Hand off session",
120756
+ description: "Moves the current request to an old session that has the context, for when the user says to hand this off or reopen that earlier conversation" + ROUTE_TO_TASK,
120757
+ exposure: THREAD_TOOL_EXPOSURE
120758
+ },
120759
+ {
120760
+ name: "thread_rename",
120761
+ label: "Rename session",
120762
+ description: "Changes the label a session is listed under, for when the user asks to call a session something clearer",
120763
+ exposure: THREAD_TOOL_EXPOSURE
120764
+ },
120765
+ {
120766
+ name: "thread_set_model",
120767
+ label: "Switch session model",
120768
+ description: "Moves a session onto a different model, for when the user asks to switch that session to another model or a cheaper one",
120769
+ exposure: THREAD_TOOL_EXPOSURE
120770
+ },
120771
+ {
120772
+ name: "thread_set_reasoning",
120773
+ label: "Set session reasoning level",
120774
+ description: "Sets how much reasoning a session applies, for when the user asks to raise or lower the thinking effort of a session",
120775
+ exposure: THREAD_TOOL_EXPOSURE
120776
+ },
120777
+ {
120778
+ name: "thread_bind",
120779
+ label: "Bind session to chat thread",
120780
+ description: "Attaches a session to an external chat thread on Discord, Telegram, Slack, Notion, Feishu, herdr or a custom connector, for when the user wants a chat conversation connected to a session",
120781
+ exposure: THREAD_TOOL_EXPOSURE
120782
+ },
120783
+ {
120784
+ name: "thread_unbind",
120785
+ label: "Unbind chat thread",
120786
+ description: "Detaches a session from its bound chat thread, for when the user wants that chat connection closed",
120787
+ exposure: THREAD_TOOL_EXPOSURE
120788
+ },
120789
+ {
120790
+ name: "thread_rebind",
120791
+ label: "Rebind chat thread",
120792
+ description: "Moves a bound chat thread over to another session, for when the user wants that chat served by a different session",
120793
+ exposure: THREAD_TOOL_EXPOSURE
120794
+ },
120795
+ {
120796
+ name: "thread_bindings",
120797
+ label: "List chat bindings",
120798
+ description: "Shows which chat threads are bound to which sessions with their revisions, for when the user needs a binding id or its revision",
120799
+ exposure: THREAD_TOOL_EXPOSURE
120800
+ },
120801
+ {
120802
+ name: "thread_report",
120803
+ label: "Report to chat thread",
120804
+ description: "Posts a milestone, result, question or completion from this session to its bound chat thread, for when the user wants progress relayed to that chat; replies flow back through thread_read, thread_report and thread_answer",
120805
+ exposure: THREAD_TOOL_EXPOSURE
120806
+ },
120807
+ {
120808
+ name: "thread_outbox",
120809
+ label: "Read chat outbox",
120810
+ description: "Returns the reports waiting for a bound chat thread with a cursor, for when a connector collects what sessions posted",
120811
+ exposure: THREAD_TOOL_EXPOSURE
120812
+ },
120813
+ {
120814
+ name: "thread_outbox_ack",
120815
+ label: "Acknowledge chat outbox",
120816
+ description: "Marks outbox rows up to a cursor as posted to the chat, for when a connector confirms delivery",
120817
+ exposure: THREAD_TOOL_EXPOSURE
120818
+ },
120819
+ {
120820
+ name: "thread_answer",
120821
+ label: "Answer relayed question",
120822
+ description: "Resolves a question a session relayed to a chat thread with the answer that arrived there, for when a connector hands back a chat user's reply",
120823
+ exposure: THREAD_TOOL_EXPOSURE
120824
+ }
120825
+ ];
120826
+
120827
+ // packages/omo-senpi/src/components/thread/control/relay-control.ts
120828
+ var IN_PROGRESS = new Set(["running", "compacting", "opening"]);
120829
+ var RUN_RECORDS = new Set([
120830
+ "agent_start",
120831
+ "turn_start",
120832
+ "message_start",
120833
+ "message_update",
120834
+ "message_end",
120835
+ "tool_execution_start",
120836
+ "tool_execution_update",
120837
+ "tool_execution_end",
120838
+ "turn_end",
120839
+ "agent_end"
120840
+ ]);
120841
+
120842
+ // packages/omo-senpi/src/components/thread/remote/session-state.ts
120843
+ var ACCESS_ENDED = new Set([
120844
+ "authorization_expired",
120845
+ "peer_revoked",
120846
+ "owner_transfer",
120847
+ "service_disabled"
120848
+ ]);
120849
+ var ACCESS_REFUSED = new Set([
120850
+ "unauthenticated",
120851
+ "forbidden",
120852
+ "owner_transfer",
120853
+ "signed_out",
120854
+ "service_disabled",
120855
+ "sign_in_required",
120856
+ "plan_required",
120857
+ "peer_not_found",
120858
+ "peer_not_session_client",
120859
+ "account_changed",
120860
+ "device_changed",
120861
+ "capability_missing",
120862
+ "engine_too_old"
120863
+ ]);
120864
+ var SESSION_LEFT = new Set(["session_closed", "session_replaced"]);
120865
+ var SESSION_GONE2 = new Set([
120866
+ "session_not_found",
120867
+ "unknown_session",
120868
+ "session_identity_mismatch"
120869
+ ]);
120870
+
120871
+ // packages/omo-senpi/src/components/thread/remote/device-service.ts
120872
+ var REFUSED_BEFORE_SENDING = new Set([
120873
+ "unauthenticated",
120874
+ "client_proof_invalid",
120875
+ "invalid_request",
120876
+ "unknown_type",
120877
+ "forbidden",
120878
+ "owner_transfer",
120879
+ "signed_out",
120880
+ "device_mismatch",
120881
+ "device_changed",
120882
+ "account_changed",
120883
+ "device_key_invalid",
120884
+ "service_disabled",
120885
+ "sign_in_required",
120886
+ "plan_required",
120887
+ "activation_pending",
120888
+ "authorization_stale",
120889
+ "peer_not_found",
120890
+ "peer_not_session_client",
120891
+ "session_not_found",
120892
+ "engine_too_old",
120893
+ "not_attached",
120894
+ "command_id_conflict",
120895
+ "message_too_long",
120896
+ "upload_incomplete",
120897
+ "malformed",
120898
+ "method_unclassified",
120899
+ "method_local_only",
120900
+ "host_not_answering",
120901
+ "unsupported"
120902
+ ]);
120903
+ var READ_ONLY_RECORDS = new Set(["get_state", "get_messages"]);
120904
+ var MARKED_RECORDS = new Set(["admit_external_message"]);
120905
+ var LOOKUP_NONE = new Set(["session_not_found", "peer_not_found", "peer_not_session_client"]);
120906
+
120907
+ // packages/omo-senpi/src/components/thread/gateway/constants.ts
120908
+ var QUEUED_TTL_MS = 24 * 60 * 60 * 1000;
120909
+ var ROOT_LIFETIME_MS = 7 * 24 * 60 * 60 * 1000;
120910
+ var TARGET_MAX_BYTES = 1024 * 1024;
120911
+ var GATEWAY_RECEIPT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
120912
+ var DELIVERY_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
120913
+ var RETENTION_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
120914
+
120915
+ // packages/omo-senpi/src/components/thread/gateway/session-args-schema.ts
120916
+ var TYPES = new Set(["object", "string", "number", "integer", "boolean", "array", "null"]);
120917
+ var ANNOTATIONS = new Set(["title", "description", "default", "examples"]);
120918
+ var COUNTS = ["minLength", "maxLength", "minItems", "maxItems"];
120919
+ var BOUNDS = ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"];
120920
+ var KEYWORDS = new Set([
120921
+ "type",
120922
+ "properties",
120923
+ "required",
120924
+ "additionalProperties",
120925
+ "enum",
120926
+ "const",
120927
+ "pattern",
120928
+ "items",
120929
+ "anyOf",
120930
+ ...COUNTS,
120931
+ ...BOUNDS,
120932
+ ...ANNOTATIONS
120933
+ ]);
120934
+
120935
+ // packages/omo-senpi/src/components/thread/remote/relay-transport.ts
120936
+ var ADMIT_UNSUPPORTED = new Set([
120937
+ "method_unclassified",
120938
+ "delegation_unclassified",
120939
+ "unknown_command",
120940
+ "engine_capability_missing",
120941
+ "unsupported_command",
120942
+ "method_unknown"
120943
+ ]);
120944
+ var WAITS = new Set(["wake", "hold", "approval"]);
120945
+
120946
+ // packages/omo-senpi/src/components/thread/remote/this-device.ts
120947
+ var known2 = new WeakMap;
120948
+
120949
+ // packages/omo-native/bin/lib/package-paths.js
120950
+ import { fileURLToPath as fileURLToPath9 } from "node:url";
120951
+ var packageRoot = fileURLToPath9(new URL("../..", import.meta.url));
120952
+
120953
+ // packages/omo-native/remote-session-verbs.ts
120954
+ var NO_SUCH_SESSION = new Set(["session_not_found", "unknown_session"]);
120955
+
120956
+ // packages/omo-native/remote-usage.ts
120957
+ var USAGE_HEAD = "usage: omo remote <command> [--json]";
120958
+ var USAGE_ENTRIES = [
120959
+ {
120960
+ verbs: ["status"],
120961
+ text: " status the device service's connection state"
120962
+ },
120963
+ {
120964
+ verbs: ["devices"],
120965
+ text: " devices the devices on this account"
120966
+ },
120967
+ {
120968
+ verbs: ["sessions"],
120969
+ text: ` sessions [--device D] [--project P] [--state running|idle|ended]
120970
+ sessions across the account's devices`
120971
+ },
120972
+ {
120973
+ verbs: ["enable", "disable"],
120974
+ text: " enable | disable turn remote sessions on or off for this device"
120975
+ },
120976
+ {
120977
+ verbs: ["control"],
120978
+ text: ` control [on|off] whether your other signed-in devices can view and command this
120979
+ device's sessions (on unless you turn it off)`
120980
+ },
120981
+ {
120982
+ verbs: ["wake"],
120983
+ text: ` wake [on|off|default] whether sessions on this device that are not running may be started
120984
+ by a message from your other signed-in devices; on unless turned off`
120985
+ },
120986
+ {
120987
+ verbs: ["bootstrap"],
120988
+ text: " bootstrap set up this device's service for your sign-in (every omo start runs it)"
120989
+ },
120990
+ {
120991
+ verbs: ["attach"],
120992
+ text: " attach <session> open a session in the terminal UI; also takes <device>/<session>"
120993
+ },
120994
+ {
120995
+ verbs: ["open"],
120996
+ text: ` open <device> [--project P] [--model provider/id] [--thinking LEVEL] [--permission-preset MODE]
120997
+ [--worktree [--branch B] [--base REF]] [--prompt TEXT [--steer|--follow-up]]
120998
+ start a session on another device; prints <device>/<session>; it runs
120999
+ in MODE (default: this device's own setting, else full-access), on the
121000
+ model and thinking level given (a model it cannot run opens nothing),
121001
+ in a new git worktree of P with --worktree, and is handed TEXT first`
121002
+ },
121003
+ {
121004
+ verbs: ["send"],
121005
+ text: ` send <session> <text> [--steer|--follow-up] [--no-wait]
121006
+ send a message and print the answer as it arrives (--steer: into the
121007
+ running turn; --no-wait: return once the session took it).
121008
+ Use the durable thread_id from open --json, or <device>/<session>.`
121009
+ },
121010
+ {
121011
+ verbs: ["model"],
121012
+ text: " model <session> <provider/id> switch the model; also takes <device>/<session>"
121013
+ },
121014
+ {
121015
+ verbs: ["interrupt"],
121016
+ text: " interrupt <session> stop the running turn; also takes <device>/<session>"
121017
+ },
121018
+ {
121019
+ verbs: ["close"],
121020
+ text: " close <session> end the session; also takes <device>/<session>"
121021
+ }
121022
+ ];
121023
+ var REMOTE_USAGE = [USAGE_HEAD, ...USAGE_ENTRIES.map((entry) => entry.text)].join(`
121024
+ `);
121025
+
121026
+ // packages/omo-native/remote-verbs.ts
121027
+ var VERBS = [
121028
+ "status",
121029
+ "devices",
121030
+ "sessions",
121031
+ "enable",
121032
+ "disable",
121033
+ "control",
121034
+ "wake",
121035
+ "bootstrap",
121036
+ ...SESSION_VERBS
121037
+ ];
121038
+ // packages/omo-native/remote-entry.ts
121039
+ var testSkipKey = Symbol.for("omo.test.skipRemoteLoginSetup");
121040
+
119224
121041
  // packages/omo-native/service-auth-command.ts
119225
121042
  var cliServiceAuthHooks = {
119226
121043
  deviceService: (api) => cliDeviceServiceHandoff({ api, log: (line) => process.stderr.write(`${line}
@@ -119430,7 +121247,7 @@ async function boulder(options) {
119430
121247
  return 0;
119431
121248
  }
119432
121249
  // packages/omo-opencode/src/cli/codex-ulw-loop.ts
119433
- import { spawn as spawn7 } from "node:child_process";
121250
+ import { spawn as spawn8 } from "node:child_process";
119434
121251
  import { existsSync as existsSync70, readFileSync as readFileSync49, realpathSync as realpathSync14 } from "node:fs";
119435
121252
  import { homedir as homedir37 } from "node:os";
119436
121253
  var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";
@@ -119460,7 +121277,7 @@ async function codexUlwLoop(args) {
119460
121277
  return 1;
119461
121278
  }
119462
121279
  const { promise, resolve } = Promise.withResolvers();
119463
- const child = spawn7(command.executable, [...command.argsPrefix, ...args], {
121280
+ const child = spawn8(command.executable, [...command.argsPrefix, ...args], {
119464
121281
  stdio: "inherit",
119465
121282
  env: { ...process.env, [ULW_LOOP_DELEGATION_SENTINEL]: "1" }
119466
121283
  });