@nativestudio/cli 0.3.0-rc.19 → 0.3.0-rc.20

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 (77) hide show
  1. package/COMPATIBILITY.json +8 -8
  2. package/components/runtime.json +4 -4
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/{chunk-WXEERCXN.js → chunk-4M2SOMSN.js} +1 -1
  5. package/dist/_chunks/{chunk-2GV47BUV.js → chunk-4PAVWOPA.js} +1 -1
  6. package/dist/_chunks/{chunk-CTCEGOC7.js → chunk-6EZX2TRX.js} +1 -1
  7. package/dist/_chunks/{chunk-BZPQB66Z.js → chunk-AFNJRZLJ.js} +1 -1
  8. package/dist/_chunks/chunk-APNZQZFB.js +1 -0
  9. package/dist/_chunks/chunk-D74NHT4I.js +45 -0
  10. package/dist/_chunks/chunk-ELUJ44BO.js +1 -0
  11. package/dist/_chunks/{chunk-AIR7YOFU.js → chunk-FVY3PLG7.js} +1 -1
  12. package/dist/_chunks/{chunk-4NCE337I.js → chunk-GLAF74UU.js} +1 -1
  13. package/dist/_chunks/{chunk-GQ32ZQTM.js → chunk-HBDPYWMI.js} +1 -1
  14. package/dist/_chunks/{chunk-5TKBEFRX.js → chunk-IYDHDLTR.js} +1 -1
  15. package/dist/_chunks/{chunk-2MKMGMA4.js → chunk-K35CWLDH.js} +1 -1
  16. package/dist/_chunks/{chunk-HIBT6NXN.js → chunk-L3QA7FLZ.js} +1 -1
  17. package/dist/_chunks/chunk-LBK42NHW.js +1 -0
  18. package/dist/_chunks/{chunk-J2IYRUVM.js → chunk-MLZ3ZPGU.js} +1 -1
  19. package/dist/_chunks/{chunk-PAIJRAJB.js → chunk-NG4BDFEY.js} +1 -1
  20. package/dist/_chunks/chunk-OSO6KRE2.js +1 -0
  21. package/dist/_chunks/chunk-QE7O57PQ.js +1 -0
  22. package/dist/_chunks/{chunk-JL4MUI7K.js → chunk-QK4XPVKT.js} +1 -1
  23. package/dist/_chunks/{chunk-67QDMD7M.js → chunk-ROGOASYF.js} +1 -1
  24. package/dist/_chunks/{chunk-TIHGZGU3.js → chunk-UYKCN5DU.js} +1 -1
  25. package/dist/_chunks/{chunk-5G3AJAKI.js → chunk-XUSVNPR5.js} +1 -1
  26. package/dist/_chunks/component-contract-KXK7WIUI.js +1 -0
  27. package/dist/_chunks/component-preflight-WECLCZLF.js +1 -0
  28. package/dist/_chunks/device-management-TLRUMZL5.js +1 -0
  29. package/dist/_chunks/{device-preflight-QAPMMHWK.js → device-preflight-C7FFUXI2.js} +1 -1
  30. package/dist/_chunks/{devices-inventory-WZ3QAPTS.js → devices-inventory-BZF53UAU.js} +1 -1
  31. package/dist/_chunks/{devices-main-XKRRLX5B.js → devices-main-V3YHCB2C.js} +1 -1
  32. package/dist/_chunks/host-component-Q5IHRHRI.js +1 -0
  33. package/dist/_chunks/host-help-7BGYR4ET.js +1 -0
  34. package/dist/_chunks/host-main-JLIBRHC2.js +1 -0
  35. package/dist/_chunks/{library-main-4BQ2J73H.js → library-main-ATRFEAVN.js} +1 -1
  36. package/dist/_chunks/{local-main-GBC2HPD4.js → local-main-KTYCLHDA.js} +1 -1
  37. package/dist/_chunks/{local-mcp-FXHB3CKF.js → local-mcp-ISMU6ADI.js} +1 -1
  38. package/dist/_chunks/{main-R7DV24KT.js → main-MOZS2EK3.js} +1 -1
  39. package/dist/_chunks/mcp-M2SO3J2H.js +1 -0
  40. package/dist/_chunks/{observe-entry-NKXTUZYF.js → observe-entry-E6DFHIMW.js} +1 -1
  41. package/dist/_chunks/{remote-client-TIFVZEGG.js → remote-client-T75C45JO.js} +1 -1
  42. package/dist/_chunks/render-main-OGCO2LX4.js +1 -0
  43. package/dist/_chunks/series-main-FBERVYWG.js +1 -0
  44. package/dist/_chunks/{source-import-YYRII5FQ.js → source-import-55JJ26AA.js} +1 -1
  45. package/dist/_chunks/src-V2K52JDH.js +1 -0
  46. package/dist/_chunks/{workspace-main-LD56MMI6.js → workspace-main-3P56DSEQ.js} +1 -1
  47. package/dist/_types/cli/local/manager.d.ts +1 -1
  48. package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
  49. package/dist/_types/cli/local/releases.d.ts +1 -0
  50. package/dist/_types/contracts/enterprise-brand.d.ts +302 -0
  51. package/dist/_types/contracts/index.d.ts +6 -0
  52. package/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
  53. package/dist/_types/contracts/local-execution/lifecycle.d.ts +1 -1
  54. package/dist/_types/contracts/local-execution/local-navigation.d.ts +5 -5
  55. package/dist/_types/contracts/render-readiness.d.ts +175 -0
  56. package/dist/_types/contracts/series-canon.d.ts +97 -0
  57. package/dist/_types/contracts/series-character.d.ts +23 -0
  58. package/dist/_types/contracts/series-improvement.d.ts +1639 -0
  59. package/dist/_types/contracts/series-standard.d.ts +1641 -0
  60. package/dist/_types/sdk/local-runtime-client.d.ts +2 -2
  61. package/dist/entry.js +1 -1
  62. package/dist/local-management.js +1 -1
  63. package/dist/local-navigation.js +1 -1
  64. package/package.json +1 -1
  65. package/dist/_chunks/chunk-226SBV53.js +0 -1
  66. package/dist/_chunks/chunk-H46NB5FL.js +0 -1
  67. package/dist/_chunks/chunk-IF6AUKH3.js +0 -1
  68. package/dist/_chunks/chunk-LZPPTW2K.js +0 -1
  69. package/dist/_chunks/chunk-UITIQHVU.js +0 -45
  70. package/dist/_chunks/component-contract-HETXQ2J4.js +0 -1
  71. package/dist/_chunks/device-management-NP7HAXRU.js +0 -1
  72. package/dist/_chunks/host-component-H3Q7TU5Y.js +0 -1
  73. package/dist/_chunks/host-help-SBXGX457.js +0 -1
  74. package/dist/_chunks/host-main-VUEGUFTU.js +0 -1
  75. package/dist/_chunks/mcp-6D4KHCCL.js +0 -1
  76. package/dist/_chunks/render-main-KMP4SMK7.js +0 -1
  77. package/dist/_chunks/src-IX5ZVGZS.js +0 -1
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "protocol": "NVS_PRODUCT_COMPATIBILITY_V1",
3
3
  "product": "@nativestudio/cli",
4
- "version": "0.3.0-rc.19",
4
+ "version": "0.3.0-rc.20",
5
5
  "source": {
6
- "head": "65f172585d3e99a7d1a61f8473027d5aa3de0de9",
7
- "fileDigest": "b02c547c8f12edfc80d406f3d4997f51f02b5997233abc92a030a6e324216eef",
6
+ "head": "be3ecdb415f12a3d526993f08b0dd3c6174edc33",
7
+ "fileDigest": "a605a1f262d4cf170d797ad8dbbac2d5c96c06896bc85cf0ce67f1c03a8bc9c1",
8
8
  "dirty": false,
9
- "remoteMainHead": "65f172585d3e99a7d1a61f8473027d5aa3de0de9"
9
+ "remoteMainHead": "be3ecdb415f12a3d526993f08b0dd3c6174edc33"
10
10
  },
11
11
  "node": ">=24.12 <25",
12
12
  "discoveryProfile": "contextual-v1",
13
13
  "accountProtocol": "NVS_CLI_ACCOUNT_V1",
14
14
  "component": {
15
15
  "protocol": "NVS_PRODUCT_COMPONENT_V2",
16
- "version": "0.3.0-rc.19",
17
- "byteSize": 3345815,
18
- "sha512": "9ffe049bc10b072923bd2eb737be258d35b9d27a9355a03a9d538538fbfa85ec6b4acf5c81d8925aeb23e0bab3e9df40298fbc16e47495b6205ab8c1ef2d065d",
16
+ "version": "0.3.0-rc.20",
17
+ "byteSize": 3350366,
18
+ "sha512": "fe75ff83067caf79fffa9a2871438a58e6aafcf064d071068cb6194d538384ebb7844503bb7818a7932bf2ef7cf0eb7ae456c0656a16492153be1cd3228ec04e",
19
19
  "descriptor": {
20
20
  "protocol": "NVS_RUNTIME_DESCRIPTOR_V1",
21
- "version": "0.3.0-rc.19",
21
+ "version": "0.3.0-rc.20",
22
22
  "node": {
23
23
  "major": 24,
24
24
  "minMinor": 12
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "protocol": "NVS_PRODUCT_COMPONENT_V2",
3
- "version": "0.3.0-rc.19",
4
- "byteSize": 3345815,
5
- "sha512": "9ffe049bc10b072923bd2eb737be258d35b9d27a9355a03a9d538538fbfa85ec6b4acf5c81d8925aeb23e0bab3e9df40298fbc16e47495b6205ab8c1ef2d065d",
3
+ "version": "0.3.0-rc.20",
4
+ "byteSize": 3350366,
5
+ "sha512": "fe75ff83067caf79fffa9a2871438a58e6aafcf064d071068cb6194d538384ebb7844503bb7818a7932bf2ef7cf0eb7ae456c0656a16492153be1cd3228ec04e",
6
6
  "descriptor": {
7
7
  "protocol": "NVS_RUNTIME_DESCRIPTOR_V1",
8
- "version": "0.3.0-rc.19",
8
+ "version": "0.3.0-rc.20",
9
9
  "node": {
10
10
  "major": 24,
11
11
  "minMinor": 12
Binary file
@@ -1 +1 @@
1
- import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-HIBT6NXN.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-J2IYRUVM.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-IF6AUKH3.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-5TKBEFRX.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-CTCEGOC7.js";import{canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
1
+ import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-L3QA7FLZ.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-ELUJ44BO.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-IYDHDLTR.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
@@ -1 +1 @@
1
- import{DesktopChannelInfoSchema,DesktopRuntimeChannelSchema}from"./chunk-WXEERCXN.js";import{endpoint}from"./chunk-CTCEGOC7.js";import{canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{LocalClientError,fail,read,sha256,write}from"./chunk-DLW42PJ6.js";import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}export{desktopRuntimeChannel,desktopChannelInfo,configureDesktopChannel};
1
+ import{DesktopChannelInfoSchema,DesktopRuntimeChannelSchema}from"./chunk-4M2SOMSN.js";import{endpoint}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{LocalClientError,fail,read,sha256,write}from"./chunk-DLW42PJ6.js";import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}export{desktopRuntimeChannel,desktopChannelInfo,configureDesktopChannel};
@@ -1 +1 @@
1
- import{ComponentStatusSchema,CpuSpeechCapabilitySchema,CpuSpeechInputSchema,CpuSpeechInstallationSchema,DeviceEnrollmentScopeSchema,EnrollLocalDeviceSchema,KeyframeObservationSchema,LegacyCaptionRenderStyleSchema,LocalDeviceManagementCommandSchema,LocalDevicePlatformSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalFinalRenderAdmissionSchema,LocalIdSchema,LocalLeaseBindingSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementReceiptSchema,LocalPackageVersionSchema,LocalPreviewAdmissionSchema,LocalProjectScopeSchema,LocalRevisionSchema,LocalTimeSchema,LocalWhisperToolSelectionSchema,LocalWorkScopeSchema,RegularCaptionRenderStyleSchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RevokeLocalDeviceSchema,RoughCutRequirementSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,TenantProcessorKindSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VisualRequirementSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,kokoroCpuProfile,mediaCategoryOf}from"./chunk-LZPPTW2K.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var HYPERFRAME_RENDER_PROFILE={id:"HYPERFRAME_1080P30_FULL_PAINT_V1",adapter:"native-hyperframe-v1",engine:"0.8.134",producer:"0.8.134",gsap:"3.15.0",node:"v24.21.0",browser:"Google Chrome for Testing 154.0.8037.57",browserSha256:"60c03e8882f4bb47459a905ede1074e1e746c5b765e437c288e460320540a8a3",ffmpeg:"ffmpeg version 8.0.1-3ubuntu2 Copyright (c) 2000-2025 the FFmpeg developers",maxFrames:360,timeoutMs:6e5,maxRssBytes:3221225472,maxScratchBytes:3221225472,maxOutputBytes:134217728,maxCpuMs:6e5,capture:"PNG_SOFTWARE_SCREENSHOT_FULL_PAINT",encode:"H264_YUV420P_CRF18_THREADS2_NO_AUDIO"};var HYPERFRAME_ALPHA_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1",adapter:"native-hyperframe-alpha-v1",encode:"RGBA_PNG_SEQUENCE_30_V1",maxOutputBytes:67108864,maxDecodedBytes:536870912};var HYPERFRAME_CACHED_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_1080P30_FRAME_CACHE_V2",adapter:"native-hyperframe-cache-v2",encode:"H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO"};var executable=z.strictObject({path:z.string().min(1).max(4096),digest:LocalDigestSchema});var LocalManagedMediaReuseSchema=z.strictObject({schemaVersion:z.literal(1),ffmpeg:executable,ffprobe:executable});var mediaTools={ffmpeg:executable,ffprobe:executable};var LocalCompositionBrowserSelectionSchema=executable.extend({digest:z.literal(HYPERFRAME_CACHED_RENDER_PROFILE.browserSha256)});var LocalInstalledToolSelectionSchema=z.strictObject({mode:z.literal("INSTALLED"),...mediaTools,compositionBrowser:LocalCompositionBrowserSelectionSchema.optional(),whisper:LocalWhisperToolSelectionSchema.optional(),cpuSpeech:CpuSpeechInstallationSchema.optional()});var LocalToolSelectionSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED"),...mediaTools,cpuSpeech:CpuSpeechInstallationSchema.optional()}),LocalInstalledToolSelectionSchema]);import{z as z2}from"zod";var LocalRuntimeDescriptorSchema=z2.strictObject({protocol:z2.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z2.strictObject({major:z2.literal(24),minMinor:z2.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z2.literal("NVS_LOCAL_IPC_V1"),workProtocol:z2.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z2.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z2.array(z2.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalReleaseAssetSchema=z2.strictObject({url:z2.string().url().max(2048),byteSize:z2.int().positive().max(256*1024*1024),sha512:z2.string().length(128).regex(/^[0-9a-f]{128}$/)});import{z as z4}from"zod";import{z as z3}from"zod";var RuntimeCaptionAssets={"NotoSansSC.ttf":LegacyCaptionRenderStyleSchema.shape.fontSha256.value,"NativeStudioSC-Regular.ttf":RegularCaptionRenderStyleSchema.shape.fontSha256.value,"OFL.txt":"092c580f54ee69841e94731e91f63f5d2d2a793550f4827cec485656e462f1bd"};var LocalComponentBytesSchema=z3.strictObject({byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalRuntimeComponentSchema=LocalComponentBytesSchema.extend({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V2"),version:LocalPackageVersionSchema,descriptor:LocalRuntimeDescriptorSchema.omit({platform:true}),resources:z3.strictObject({captions:LocalComponentBytesSchema})}).refine(v=>v.version===v.descriptor.version);var LocalSessionConnectorSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z4.string().min(1).max(4096),credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,tenantId:z4.uuid(),deviceId:z4.uuid()});var LocalManagementInventorySchema=z4.strictObject({runtimeRevision:z4.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z4.int().nonnegative(),pendingExecutions:z4.int().nonnegative(),pendingRequests:z4.int().nonnegative(),pendingRenderers:z4.array(LocalDigestSchema).max(64)});var LocalReleaseSchema=z4.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z4.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable(),resources:z4.strictObject({captions:LocalReleaseAssetSchema.extend({byteSize:LocalComponentBytesSchema.shape.byteSize})}).optional()});var LocalBundledReleaseSchema=LocalReleaseSchema.extend({package:LocalComponentBytesSchema.extend({source:z4.literal("CLI")})});var LocalReleaseCatalogueSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z4.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z4.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z4.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z4.discriminatedUnion("mode",[z4.strictObject({mode:z4.literal("MANAGED"),cpuSpeech:CpuSpeechInstallationSchema.optional(),reuseMedia:LocalManagedMediaReuseSchema.optional()}),LocalInstalledToolSelectionSchema.extend({captionAssetsDirectory:z4.string().min(1).max(4096).optional()})]);var LocalUpdatePlanSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z4.int().nonnegative(),runtimeRevision:z4.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema.nullable(),trustFingerprint:LocalDigestSchema.optional(),release:z4.union([LocalReleaseSchema,LocalBundledReleaseSchema]),toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z4.strictObject({surface:z4.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z4.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z4.enum(["AVAILABLE","BLOCKED"]),reason:z4.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z11}from"zod";import{z as z10}from"zod";import{z as z5}from"zod";var LocalOfflineSnapshotSchema=z5.strictObject({projectId:z5.uuid(),title:z5.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z5.array(z5.strictObject({id:z5.uuid(),title:z5.string().max(200)})).max(40),possiblyTruncated:z5.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z5.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z5.discriminatedUnion("action",[z5.strictObject({action:z5.enum(["list","forget"]),key:LocalDigestSchema}),z5.strictObject({action:z5.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z5.strictObject({action:z5.literal("draft"),key:LocalDigestSchema,projectId:z5.uuid(),text,expectedRevision:z5.int().nonnegative()})]);var LocalOfflinePageSchema=z5.strictObject({historical:z5.literal(true),items:z5.array(z5.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z5.strictObject({text,revision:z5.int().nonnegative()})})).max(3)});import{z as z7}from"zod";import{z as z6}from"zod";var QualifiedLocalAgentVersionSchema=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z6.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),mediaDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z7.strictObject({profile:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z7.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z7.int().positive().max(134217728),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096),durationMs:z7.int().positive().max(6e4).optional(),frameRate:z7.union([z7.literal(24),z7.literal(30)]).optional(),hasAudio:z7.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z7.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z7.strictObject({checksumSha256:sha,byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}),timestampsMs:z7.array(z7.number().nonnegative().max(6e4)).max(6),audio:z7.strictObject({sampleRateHz:z7.literal(48e3),channels:z7.literal(1),samples:z7.int().positive().max(2881024),peak:z7.number().min(0).max(1),rms:z7.number().min(0).max(1),clippedSamples:z7.int().nonnegative().max(2881024)}).nullable(),limitations:z7.tuple([z7.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z7.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z7.strictObject({candidate:z7.strictObject({binary:z7.string().min(1).max(4096),binaryDigest:sha,version:z7.string().regex(/^\d+\.\d+\.\d+$/),qualified:z7.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z8}from"zod";var LocalResourcePolicySchema=z8.strictObject({acceptNewWork:z8.boolean().default(true),mode:z8.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z8.int().min(30).max(3600).default(300),maxConcurrentJobs:z8.int().min(1).max(2).default(1),cpuCores:z8.union([z8.literal(1),z8.literal(2)]).default(2),memoryMiB:z8.int().min(512).max(4096).default(4096),cacheQuotaBytes:z8.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z8.strictObject({revision:z8.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z8.strictObject({stage:z8.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z8.int().nonnegative(),sourceBytes:z8.int().nonnegative(),uploadedBytes:z8.int().nonnegative(),outputBytes:z8.int().nonnegative(),lastError:z8.strictObject({code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z8.strictObject({cacheBytes:z8.int().nonnegative(),protectedBytes:z8.int().nonnegative(),reclaimableBytes:z8.int().nonnegative(),transferBytes:z8.int().nonnegative(),journalBytes:z8.int().nonnegative(),reviewBytes:z8.int().nonnegative().optional(),ownerStagingBytes:z8.int().nonnegative().optional(),availableDiskBytes:z8.int().nonnegative(),quotaBytes:z8.int().positive(),overQuota:z8.boolean()});var LocalWorkspaceInspectionSchema=z8.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z8.strictObject({state:z8.enum(["READY","PAUSED","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z8.int().nonnegative(),idleObservationCurrent:z8.boolean()})});var LocalDiagnosticsSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z8.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z8.record(z8.string().regex(/^[A-Z_]{1,40}$/),z8.int().nonnegative()),failures:z8.array(z8.strictObject({taskFingerprint:z8.string().regex(/^[a-f0-9]{64}$/),code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z9}from"zod";var sha2=z9.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z9.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z9.int().positive(),reviewVersion:z9.int().nonnegative(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z9.array(z9.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z9.strictObject({contentType:z9.literal("image/png"),byteSize:z9.int().positive().max(8388608),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z9.strictObject({configured:z9.boolean(),available:z9.boolean(),reason:z9.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z9.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z9.strictObject({protocol:z9.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z9.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z9.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),observations:z9.array(z9.strictObject({key:z9.string().min(1).max(220),observed:z9.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),imageReadback:z9.string().trim().min(1).max(800),observations:z9.array(KeyframeObservationSchema.omit({region:true}).extend({key:z9.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z9.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z9.strictObject({protocol:z9.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z9.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z9.int().positive().max(8388608),contentType:z9.literal("image/png"),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)});var LocalAgentReviewViewSchema=z9.strictObject({plan:LocalAgentPlanSchema,revision:z9.int().positive(),phase:z9.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z9.strictObject({adapter:z9.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z9.string().max(100),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().max(100),inference:z9.literal("REMOTE_OPENAI"),evidence:z9.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z10.int().min(1).max(16).default(8),includeCompleted:z10.boolean().optional(),includeProgress:z10.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z10.boolean().optional()});var LocalIpcCallSchema=z10.discriminatedUnion("operation",[z10.strictObject({operation:z10.literal("library.capability")}),z10.strictObject({operation:z10.literal("library.call"),input:LocalLibraryCallSchema}),z10.strictObject({operation:z10.literal("agent.discover"),binary:z10.string().min(1).max(4096).optional()}),z10.strictObject({operation:z10.literal("offline.workspace"),input:LocalOfflineCallSchema}),z10.strictObject({operation:z10.literal("workspace.inspect")}),z10.strictObject({operation:z10.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z10.int().nonnegative()}),z10.strictObject({operation:z10.literal("workspace.activity"),idleSeconds:z10.int().min(0).max(86400),observedAt:z10.iso.datetime()}),z10.strictObject({operation:z10.literal("storage.clean")}),z10.strictObject({operation:z10.literal("diagnostics.read")}),z10.strictObject({operation:z10.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.probe")}),z10.strictObject({operation:z10.literal("agent.revoke"),approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z10.strictObject({operation:z10.literal("agent.start"),id:z10.uuid(),expectedRevision:LocalRevisionSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.inspect"),id:z10.uuid()}),z10.strictObject({operation:z10.literal("runtime.status"),includeDevice:z10.literal(true).optional()}),z10.strictObject({operation:z10.literal("runtime.doctor")}),z10.strictObject({operation:z10.literal("runtime.inventory")}),z10.strictObject({operation:z10.literal("session.issue"),tenantId:z10.uuid(),deviceId:z10.uuid(),expiresAt:z10.iso.datetime({offset:true})}),z10.strictObject({operation:z10.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z10.strictObject({operation:z10.literal("execution.list"),input:LocalExecutionListInputSchema}),z10.strictObject({operation:z10.literal("update.check")}),z10.strictObject({operation:z10.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z10.strictObject({call:LocalIpcCallSchema,availability:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z10.strictObject({component:z10.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z10.string().min(1).max(4096).nullable(),installOwner:z10.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z10.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z10.literal(1),workProtocols:z10.array(z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z10.array(LocalVersionReportSchema).max(8),deviceAuthority:z10.strictObject({tenantId:z10.uuid(),deviceId:z10.uuid(),origin:z10.url()}).optional(),capabilityMismatch:CapabilityVersionMismatchSchema.optional(),deviceCapabilities:z10.strictObject({deviceRevision:LocalRevisionSchema,tenantMediaValidation:z10.boolean(),tenantMediaProcessing:z10.boolean(),processorCapabilities:z10.array(TenantProcessorKindSchema).max(TenantProcessorKindSchema.options.length)}).optional(),nextActions:z10.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),availability:z10.enum(["AVAILABLE","UNAVAILABLE"]),reason:z10.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z10.boolean(),executionProfiles:z10.array(z10.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2","AUDIO_MEDIA_V1"])).max(3).optional(),tools:z10.array(z10.strictObject({name:z10.enum(["FFMPEG","FFPROBE"]),path:z10.string().min(1).max(4096),version:z10.string().min(1).max(200),digest:z10.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z10.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z10.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z10.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z10.strictObject({items:z10.array(LocalExecutionInspectionSchema).max(16),nextCursor:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z10.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED","LIBRARY_NOT_FOUND","LIBRARY_CONFLICT","LIBRARY_BYTES_INVALID","LIBRARY_ACCESS_DENIED","LIBRARY_SYNC_REQUIRED","LIBRARY_SYNC_UNAVAILABLE","LIBRARY_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z10.discriminatedUnion("semanticStatus",[z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z10.literal("SUCCESS"),data:z10.union([LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryReadReplySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z10.strictObject({state:z10.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z10.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z11.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"]);var LocalMcpActionSchema=z11.strictObject({tool:LocalMcpToolNameSchema,arguments:z11.record(z11.string(),z11.unknown()),availability:z11.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z11.string().max(100).optional()});var LocalMcpNavigationSchema=z11.strictObject({location:z11.literal("LOCAL"),state:z11.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),deviceAuthority:LocalRuntimeStatusSchema.shape.deviceAuthority,groups:z11.array(z11.strictObject({id:z11.string().max(40),label:z11.string().max(100),tools:z11.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z11.array(z11.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z11.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z11.strictObject({location:z11.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z11.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z11.strictObject({location:z11.literal("LOCAL"),running:z11.array(LocalVersionReportSchema).max(8),available:z11.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z11.strictObject({location:z11.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z11.object({name:LocalMcpToolNameSchema,description:z11.string(),inputSchema:z11.record(z11.string(),z11.unknown())}).passthrough()});var LocalMcpFailureSchema=z11.strictObject({semanticStatus:z11.enum(["BLOCKED","INVALID_INPUT"]),error:z11.strictObject({code:z11.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z11.literal("NO_WRITE")}),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_library_list:LocalLibraryProjectionPageSchema.extend({location:z11.literal("LOCAL")}),local_library_get:z11.strictObject({location:z11.literal("LOCAL"),item:LocalLibraryProjectionSchema.nullable()}),local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z11.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z12}from"zod";var uuid=z12.uuid().transform(value=>value.toLowerCase());var AgentComponentScopeSchema=DeviceEnrollmentScopeSchema.extend({tenantId:uuid,principalId:uuid,grantId:uuid});var AgentComponentStatusSchema=ComponentStatusSchema.extend({component:z12.literal("HOST_RUNTIME"),source:z12.literal("OWNED_INSTALLATION_IPC"),componentHome:z12.string().min(1).max(4096),initialized:z12.boolean(),installationRevision:z12.int().nonnegative(),installedVersion:z12.string().min(1).max(120).nullable(),runningVersion:z12.string().min(1).max(120).nullable(),loginService:z12.enum(["NONE","REGISTERED","STALE","INCOMPLETE","UNKNOWN"]),lastRequestId:z12.uuid().nullable(),deviceId:z12.uuid().nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z14}from"zod";function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",p=v.provenance,id=video?"sampled_frames":"normalized_image";const observations=v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);if(!requirement)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const sound="family"in requirement&&requirement.family==="SOUND"||/^(audio|sound):/.test(requirement.key);return{...o,status:video||!("status"in o)?"NOT_OBSERVABLE":o.status,confidence:video||!("confidence"in o)?"UNCERTAIN":o.confidence,observed:video?sound?"This draft has no listening evidence.":"Sampled frames are advisory. This draft has no playback coverage.":o.observed,evidenceIds:video&&sound?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}});return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`Advisory ${video?"sampled frame observations. Full playback, listening and transcription are unavailable":"normalized original image"}. ${p.inference} via ${p.adapter} using Codex ${p.version}, model ${p.model}, effort ${p.reasoningEffort??"DEFAULT"}, binary ${p.binaryDigest}. Source ${s.media.checksumSha256}, attachment ${v.evidenceReceipt.attachment.checksumSha256}, draft ${v.plan.id}, plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:observations.some(o=>o.evidenceIds.length)?[{id,label:video?"Ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}]:[],review:{kind:s.basis.target.kind,observations}}})}import{z as z13}from"zod";var CpuSpeechPrepareInputSchema=z13.strictObject({profileId:z13.literal(kokoroCpuProfile.id).default(kokoroCpuProfile.id),voiceIds:z13.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length).default([0,45])});var CpuSpeechPreparedSchema=z13.strictObject({semanticStatus:z13.literal("PREPARED"),selection:CpuSpeechInstallationSchema,capability:CpuSpeechCapabilitySchema,reused:z13.strictObject({engine:z13.boolean(),model:z13.boolean()})});function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json","x-native-tenant-id":this.options.tenantId},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z14.strictObject({semanticStatus:z14.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z15}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z15.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request3({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.device&&this.options.device.tenantId!==i.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");let r;try{r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream","user-agent":"NativeStudioDependencyClient"}})}catch{fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}const length=r.headers.get("content-length");if(!r.ok||length!==null&&(!/^[0-9]+$/.test(length)||Number(length)>maximum)){void r.body?.cancel().catch(()=>{});fail(r.status===403?"RELEASE_ACCESS_DENIED":r.status===404?"RELEASE_NOT_PUBLISHED":r.ok?"RELEASE_LIMIT":"RELEASE_UNAVAILABLE")}const reader=r.body?.getReader(),parts=[];let size=0;try{if(reader)while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>maximum)fail("RELEASE_LIMIT");parts.push(part.value)}return Buffer.concat(parts)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="RELEASE_LIMIT")throw error;fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}finally{void reader?.cancel().catch(()=>{});reader?.releaseLock()}}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));let signed;try{signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()))}catch{fail("RELEASE_METADATA_INVALID")}const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.version}const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalCompositionBrowserSelectionSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,RuntimeCaptionAssets,LocalRuntimeComponentSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,localAgentMediaSnapshot,localAgentMediaProposal,AgentComponentScopeSchema,AgentComponentStatusSchema,CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
1
+ import{ComponentStatusSchema,CpuSpeechCapabilitySchema,CpuSpeechInputSchema,CpuSpeechInstallationSchema,DeviceEnrollmentScopeSchema,EnrollLocalDeviceSchema,KeyframeObservationSchema,LegacyCaptionRenderStyleSchema,LocalDeviceManagementCommandSchema,LocalDevicePlatformSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalFinalRenderAdmissionSchema,LocalIdSchema,LocalLeaseBindingSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementReceiptSchema,LocalPackageVersionSchema,LocalPreviewAdmissionSchema,LocalProjectScopeSchema,LocalRevisionSchema,LocalTimeSchema,LocalWhisperToolSelectionSchema,LocalWorkScopeSchema,RegularCaptionRenderStyleSchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RevokeLocalDeviceSchema,RoughCutRequirementSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,TenantProcessorKindSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VisualRequirementSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,kokoroCpuProfile,mediaCategoryOf}from"./chunk-APNZQZFB.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var HYPERFRAME_RENDER_PROFILE={id:"HYPERFRAME_1080P30_FULL_PAINT_V1",adapter:"native-hyperframe-v1",engine:"0.8.134",producer:"0.8.134",gsap:"3.15.0",node:"v24.21.0",browser:"Google Chrome for Testing 154.0.8037.57",browserSha256:"60c03e8882f4bb47459a905ede1074e1e746c5b765e437c288e460320540a8a3",ffmpeg:"ffmpeg version 8.0.1-3ubuntu2 Copyright (c) 2000-2025 the FFmpeg developers",maxFrames:360,timeoutMs:6e5,maxRssBytes:3221225472,maxScratchBytes:3221225472,maxOutputBytes:134217728,maxCpuMs:6e5,capture:"PNG_SOFTWARE_SCREENSHOT_FULL_PAINT",encode:"H264_YUV420P_CRF18_THREADS2_NO_AUDIO"};var HYPERFRAME_ALPHA_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1",adapter:"native-hyperframe-alpha-v1",encode:"RGBA_PNG_SEQUENCE_30_V1",maxOutputBytes:67108864,maxDecodedBytes:536870912};var HYPERFRAME_CACHED_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_1080P30_FRAME_CACHE_V2",adapter:"native-hyperframe-cache-v2",encode:"H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO"};var executable=z.strictObject({path:z.string().min(1).max(4096),digest:LocalDigestSchema});var LocalManagedMediaReuseSchema=z.strictObject({schemaVersion:z.literal(1),ffmpeg:executable,ffprobe:executable});var mediaTools={ffmpeg:executable,ffprobe:executable};var LocalCompositionBrowserSelectionSchema=executable.extend({digest:z.literal(HYPERFRAME_CACHED_RENDER_PROFILE.browserSha256)});var LocalInstalledToolSelectionSchema=z.strictObject({mode:z.literal("INSTALLED"),...mediaTools,compositionBrowser:LocalCompositionBrowserSelectionSchema.optional(),whisper:LocalWhisperToolSelectionSchema.optional(),cpuSpeech:CpuSpeechInstallationSchema.optional()});var LocalToolSelectionSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED"),...mediaTools,cpuSpeech:CpuSpeechInstallationSchema.optional()}),LocalInstalledToolSelectionSchema]);import{z as z2}from"zod";var LocalRuntimeDescriptorSchema=z2.strictObject({protocol:z2.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z2.strictObject({major:z2.literal(24),minMinor:z2.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z2.literal("NVS_LOCAL_IPC_V1"),workProtocol:z2.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z2.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z2.array(z2.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalReleaseAssetSchema=z2.strictObject({url:z2.string().url().max(2048),byteSize:z2.int().positive().max(256*1024*1024),sha512:z2.string().length(128).regex(/^[0-9a-f]{128}$/)});import{z as z4}from"zod";import{z as z3}from"zod";var RuntimeCaptionAssets={"NotoSansSC.ttf":LegacyCaptionRenderStyleSchema.shape.fontSha256.value,"NativeStudioSC-Regular.ttf":RegularCaptionRenderStyleSchema.shape.fontSha256.value,"OFL.txt":"092c580f54ee69841e94731e91f63f5d2d2a793550f4827cec485656e462f1bd"};var LocalComponentBytesSchema=z3.strictObject({byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalRuntimeComponentSchema=LocalComponentBytesSchema.extend({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V2"),version:LocalPackageVersionSchema,descriptor:LocalRuntimeDescriptorSchema.omit({platform:true}),resources:z3.strictObject({captions:LocalComponentBytesSchema})}).refine(v=>v.version===v.descriptor.version);var LocalSessionConnectorSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z4.string().min(1).max(4096),credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,tenantId:z4.uuid(),deviceId:z4.uuid()});var LocalManagementInventorySchema=z4.strictObject({runtimeRevision:z4.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z4.int().nonnegative(),pendingExecutions:z4.int().nonnegative(),pendingRequests:z4.int().nonnegative(),pendingRenderers:z4.array(LocalDigestSchema).max(64)});var LocalReleaseSchema=z4.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z4.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable(),resources:z4.strictObject({captions:LocalReleaseAssetSchema.extend({byteSize:LocalComponentBytesSchema.shape.byteSize})}).optional()});var LocalBundledReleaseSchema=LocalReleaseSchema.extend({package:LocalComponentBytesSchema.extend({source:z4.literal("CLI")})});var LocalReleaseCatalogueSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z4.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z4.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z4.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z4.discriminatedUnion("mode",[z4.strictObject({mode:z4.literal("MANAGED"),cpuSpeech:CpuSpeechInstallationSchema.optional(),reuseMedia:LocalManagedMediaReuseSchema.optional()}),LocalInstalledToolSelectionSchema.extend({captionAssetsDirectory:z4.string().min(1).max(4096).optional()})]);var LocalUpdatePlanSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z4.int().nonnegative(),runtimeRevision:z4.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema.nullable(),trustFingerprint:LocalDigestSchema.optional(),release:z4.union([LocalReleaseSchema,LocalBundledReleaseSchema]),toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z4.strictObject({surface:z4.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z4.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z4.enum(["AVAILABLE","BLOCKED"]),reason:z4.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z11}from"zod";import{z as z10}from"zod";import{z as z5}from"zod";var LocalOfflineSnapshotSchema=z5.strictObject({projectId:z5.uuid(),title:z5.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z5.array(z5.strictObject({id:z5.uuid(),title:z5.string().max(200)})).max(40),possiblyTruncated:z5.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z5.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z5.discriminatedUnion("action",[z5.strictObject({action:z5.enum(["list","forget"]),key:LocalDigestSchema}),z5.strictObject({action:z5.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z5.strictObject({action:z5.literal("draft"),key:LocalDigestSchema,projectId:z5.uuid(),text,expectedRevision:z5.int().nonnegative()})]);var LocalOfflinePageSchema=z5.strictObject({historical:z5.literal(true),items:z5.array(z5.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z5.strictObject({text,revision:z5.int().nonnegative()})})).max(3)});import{z as z7}from"zod";import{z as z6}from"zod";var QualifiedLocalAgentVersionSchema=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z6.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),mediaDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z7.strictObject({profile:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z7.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z7.int().positive().max(134217728),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096),durationMs:z7.int().positive().max(6e4).optional(),frameRate:z7.union([z7.literal(24),z7.literal(30)]).optional(),hasAudio:z7.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z7.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z7.strictObject({checksumSha256:sha,byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}),timestampsMs:z7.array(z7.number().nonnegative().max(6e4)).max(6),audio:z7.strictObject({sampleRateHz:z7.literal(48e3),channels:z7.literal(1),samples:z7.int().positive().max(2881024),peak:z7.number().min(0).max(1),rms:z7.number().min(0).max(1),clippedSamples:z7.int().nonnegative().max(2881024)}).nullable(),limitations:z7.tuple([z7.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z7.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z7.strictObject({candidate:z7.strictObject({binary:z7.string().min(1).max(4096),binaryDigest:sha,version:z7.string().regex(/^\d+\.\d+\.\d+$/),qualified:z7.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z8}from"zod";var LocalResourcePolicySchema=z8.strictObject({acceptNewWork:z8.boolean().default(true),mode:z8.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z8.int().min(30).max(3600).default(300),maxConcurrentJobs:z8.int().min(1).max(2).default(1),cpuCores:z8.union([z8.literal(1),z8.literal(2)]).default(2),memoryMiB:z8.int().min(512).max(4096).default(4096),cacheQuotaBytes:z8.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z8.strictObject({revision:z8.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z8.strictObject({stage:z8.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z8.int().nonnegative(),sourceBytes:z8.int().nonnegative(),uploadedBytes:z8.int().nonnegative(),outputBytes:z8.int().nonnegative(),lastError:z8.strictObject({code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z8.strictObject({cacheBytes:z8.int().nonnegative(),protectedBytes:z8.int().nonnegative(),reclaimableBytes:z8.int().nonnegative(),transferBytes:z8.int().nonnegative(),journalBytes:z8.int().nonnegative(),reviewBytes:z8.int().nonnegative().optional(),ownerStagingBytes:z8.int().nonnegative().optional(),availableDiskBytes:z8.int().nonnegative(),quotaBytes:z8.int().positive(),overQuota:z8.boolean()});var LocalWorkspaceInspectionSchema=z8.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z8.strictObject({state:z8.enum(["READY","PAUSED","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z8.int().nonnegative(),idleObservationCurrent:z8.boolean()})});var LocalDiagnosticsSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z8.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z8.record(z8.string().regex(/^[A-Z_]{1,40}$/),z8.int().nonnegative()),failures:z8.array(z8.strictObject({taskFingerprint:z8.string().regex(/^[a-f0-9]{64}$/),code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z9}from"zod";var sha2=z9.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z9.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z9.int().positive(),reviewVersion:z9.int().nonnegative(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z9.array(z9.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z9.strictObject({contentType:z9.literal("image/png"),byteSize:z9.int().positive().max(8388608),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z9.strictObject({configured:z9.boolean(),available:z9.boolean(),reason:z9.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z9.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z9.strictObject({protocol:z9.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z9.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z9.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),observations:z9.array(z9.strictObject({key:z9.string().min(1).max(220),observed:z9.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),imageReadback:z9.string().trim().min(1).max(800),observations:z9.array(KeyframeObservationSchema.omit({region:true}).extend({key:z9.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z9.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z9.strictObject({protocol:z9.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z9.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z9.int().positive().max(8388608),contentType:z9.literal("image/png"),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)});var LocalAgentReviewViewSchema=z9.strictObject({plan:LocalAgentPlanSchema,revision:z9.int().positive(),phase:z9.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z9.strictObject({adapter:z9.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z9.string().max(100),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().max(100),inference:z9.literal("REMOTE_OPENAI"),evidence:z9.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z10.int().min(1).max(16).default(8),includeCompleted:z10.boolean().optional(),includeProgress:z10.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z10.boolean().optional()});var LocalIpcCallSchema=z10.discriminatedUnion("operation",[z10.strictObject({operation:z10.literal("library.capability")}),z10.strictObject({operation:z10.literal("library.call"),input:LocalLibraryCallSchema}),z10.strictObject({operation:z10.literal("agent.discover"),binary:z10.string().min(1).max(4096).optional()}),z10.strictObject({operation:z10.literal("offline.workspace"),input:LocalOfflineCallSchema}),z10.strictObject({operation:z10.literal("workspace.inspect")}),z10.strictObject({operation:z10.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z10.int().nonnegative()}),z10.strictObject({operation:z10.literal("workspace.activity"),idleSeconds:z10.int().min(0).max(86400),observedAt:z10.iso.datetime()}),z10.strictObject({operation:z10.literal("storage.clean")}),z10.strictObject({operation:z10.literal("diagnostics.read")}),z10.strictObject({operation:z10.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.probe")}),z10.strictObject({operation:z10.literal("agent.revoke"),approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z10.strictObject({operation:z10.literal("agent.start"),id:z10.uuid(),expectedRevision:LocalRevisionSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.inspect"),id:z10.uuid()}),z10.strictObject({operation:z10.literal("runtime.status"),includeDevice:z10.literal(true).optional()}),z10.strictObject({operation:z10.literal("runtime.doctor")}),z10.strictObject({operation:z10.literal("runtime.inventory")}),z10.strictObject({operation:z10.literal("session.issue"),tenantId:z10.uuid(),deviceId:z10.uuid(),expiresAt:z10.iso.datetime({offset:true})}),z10.strictObject({operation:z10.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z10.strictObject({operation:z10.literal("execution.list"),input:LocalExecutionListInputSchema}),z10.strictObject({operation:z10.literal("update.check")}),z10.strictObject({operation:z10.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z10.strictObject({call:LocalIpcCallSchema,availability:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z10.strictObject({component:z10.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z10.string().min(1).max(4096).nullable(),installOwner:z10.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z10.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z10.literal(1),workProtocols:z10.array(z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z10.array(LocalVersionReportSchema).max(8),deviceAuthority:z10.strictObject({tenantId:z10.uuid(),deviceId:z10.uuid(),origin:z10.url()}).optional(),capabilityMismatch:CapabilityVersionMismatchSchema.optional(),deviceCapabilities:z10.strictObject({deviceRevision:LocalRevisionSchema,tenantMediaValidation:z10.boolean(),tenantMediaProcessing:z10.boolean(),processorCapabilities:z10.array(TenantProcessorKindSchema).max(TenantProcessorKindSchema.options.length)}).optional(),nextActions:z10.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),availability:z10.enum(["AVAILABLE","UNAVAILABLE"]),reason:z10.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z10.boolean(),executionProfiles:z10.array(z10.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2","AUDIO_MEDIA_V1"])).max(3).optional(),tools:z10.array(z10.strictObject({name:z10.enum(["FFMPEG","FFPROBE"]),path:z10.string().min(1).max(4096),version:z10.string().min(1).max(200),digest:z10.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z10.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z10.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z10.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z10.strictObject({items:z10.array(LocalExecutionInspectionSchema).max(16),nextCursor:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z10.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED","LIBRARY_NOT_FOUND","LIBRARY_CONFLICT","LIBRARY_BYTES_INVALID","LIBRARY_ACCESS_DENIED","LIBRARY_SYNC_REQUIRED","LIBRARY_SYNC_UNAVAILABLE","LIBRARY_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z10.discriminatedUnion("semanticStatus",[z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z10.literal("SUCCESS"),data:z10.union([LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryReadReplySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z10.strictObject({state:z10.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z10.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z11.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"]);var LocalMcpActionSchema=z11.strictObject({tool:LocalMcpToolNameSchema,arguments:z11.record(z11.string(),z11.unknown()),availability:z11.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z11.string().max(100).optional()});var LocalMcpNavigationSchema=z11.strictObject({location:z11.literal("LOCAL"),state:z11.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),deviceAuthority:LocalRuntimeStatusSchema.shape.deviceAuthority,groups:z11.array(z11.strictObject({id:z11.string().max(40),label:z11.string().max(100),tools:z11.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z11.array(z11.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z11.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z11.strictObject({location:z11.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z11.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z11.strictObject({location:z11.literal("LOCAL"),running:z11.array(LocalVersionReportSchema).max(8),available:z11.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z11.strictObject({location:z11.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z11.object({name:LocalMcpToolNameSchema,description:z11.string(),inputSchema:z11.record(z11.string(),z11.unknown())}).passthrough()});var LocalMcpFailureSchema=z11.strictObject({semanticStatus:z11.enum(["BLOCKED","INVALID_INPUT"]),error:z11.strictObject({code:z11.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z11.literal("NO_WRITE")}),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_library_list:LocalLibraryProjectionPageSchema.extend({location:z11.literal("LOCAL")}),local_library_get:z11.strictObject({location:z11.literal("LOCAL"),item:LocalLibraryProjectionSchema.nullable()}),local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z11.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z12}from"zod";var uuid=z12.uuid().transform(value=>value.toLowerCase());var AgentComponentScopeSchema=DeviceEnrollmentScopeSchema.extend({tenantId:uuid,principalId:uuid,grantId:uuid});var AgentComponentStatusSchema=ComponentStatusSchema.extend({component:z12.literal("HOST_RUNTIME"),source:z12.literal("OWNED_INSTALLATION_IPC"),componentHome:z12.string().min(1).max(4096),initialized:z12.boolean(),installationRevision:z12.int().nonnegative(),installedVersion:z12.string().min(1).max(120).nullable(),runningVersion:z12.string().min(1).max(120).nullable(),loginService:z12.enum(["NONE","REGISTERED","STALE","INCOMPLETE","UNKNOWN"]),lastRequestId:z12.uuid().nullable(),deviceId:z12.uuid().nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z14}from"zod";function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",p=v.provenance,id=video?"sampled_frames":"normalized_image";const observations=v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);if(!requirement)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const sound="family"in requirement&&requirement.family==="SOUND"||/^(audio|sound):/.test(requirement.key);return{...o,status:video||!("status"in o)?"NOT_OBSERVABLE":o.status,confidence:video||!("confidence"in o)?"UNCERTAIN":o.confidence,observed:video?sound?"This draft has no listening evidence.":"Sampled frames are advisory. This draft has no playback coverage.":o.observed,evidenceIds:video&&sound?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}});return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`Advisory ${video?"sampled frame observations. Full playback, listening and transcription are unavailable":"normalized original image"}. ${p.inference} via ${p.adapter} using Codex ${p.version}, model ${p.model}, effort ${p.reasoningEffort??"DEFAULT"}, binary ${p.binaryDigest}. Source ${s.media.checksumSha256}, attachment ${v.evidenceReceipt.attachment.checksumSha256}, draft ${v.plan.id}, plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:observations.some(o=>o.evidenceIds.length)?[{id,label:video?"Ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}]:[],review:{kind:s.basis.target.kind,observations}}})}import{z as z13}from"zod";var CpuSpeechPrepareInputSchema=z13.strictObject({profileId:z13.literal(kokoroCpuProfile.id).default(kokoroCpuProfile.id),voiceIds:z13.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length).default([0,45])});var CpuSpeechPreparedSchema=z13.strictObject({semanticStatus:z13.literal("PREPARED"),selection:CpuSpeechInstallationSchema,capability:CpuSpeechCapabilitySchema,reused:z13.strictObject({engine:z13.boolean(),model:z13.boolean()})});function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json","x-native-tenant-id":this.options.tenantId},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z14.strictObject({semanticStatus:z14.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z15}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z15.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request3({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.device&&this.options.device.tenantId!==i.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");let r;try{r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream","user-agent":"NativeStudioDependencyClient"}})}catch{fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}const length=r.headers.get("content-length");if(!r.ok||length!==null&&(!/^[0-9]+$/.test(length)||Number(length)>maximum)){void r.body?.cancel().catch(()=>{});fail(r.status===403?"RELEASE_ACCESS_DENIED":r.status===404?"RELEASE_NOT_PUBLISHED":r.ok?"RELEASE_LIMIT":"RELEASE_UNAVAILABLE")}const reader=r.body?.getReader(),parts=[];let size=0;try{if(reader)while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>maximum)fail("RELEASE_LIMIT");parts.push(part.value)}return Buffer.concat(parts)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="RELEASE_LIMIT")throw error;fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}finally{void reader?.cancel().catch(()=>{});reader?.releaseLock()}}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile&&!trust.publicKey)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));let signed;try{signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()))}catch{fail("RELEASE_METADATA_INVALID")}const key=createPublicKey(trust.publicKeyFile?(await read(trust.publicKeyFile,16384)).toString():trust.publicKey);if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.version}const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalCompositionBrowserSelectionSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,RuntimeCaptionAssets,LocalRuntimeComponentSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,localAgentMediaSnapshot,localAgentMediaProposal,AgentComponentScopeSchema,AgentComponentStatusSchema,CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
@@ -1 +1 @@
1
- import{DesktopDeviceScopeSchema,DesktopDeviceStateSchema}from"./chunk-5TKBEFRX.js";import{canonicalLocalJson}from"./chunk-LZPPTW2K.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceRecords,desktopDeviceConnector};
1
+ import{DesktopDeviceScopeSchema,DesktopDeviceStateSchema}from"./chunk-IYDHDLTR.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceRecords,desktopDeviceConnector};