aegisone 1.0.24 → 1.0.26

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 (71) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/scripts/predist.mjs +1 -1
  4. package/src/permissions.js +1 -1
  5. package/vendor/cli/bin/aegiscode.js +915 -2
  6. package/vendor/cli/package.json +1 -1
  7. package/vendor/cli/src/app.js +1 -1
  8. package/vendor/cli/src/autonomous.js +515 -1
  9. package/vendor/cli/src/caps.js +879 -1
  10. package/vendor/cli/src/chatflow.js +1 -1
  11. package/vendor/cli/src/commands.js +1 -1
  12. package/vendor/cli/src/engine.js +1 -1
  13. package/vendor/cli/src/gate.js +55 -1
  14. package/vendor/cli/src/history.js +1 -1
  15. package/vendor/cli/src/limits.js +190 -1
  16. package/vendor/cli/src/mcp.js +694 -1
  17. package/vendor/cli/src/models.js +1 -1
  18. package/vendor/cli/src/overlays.js +1 -1
  19. package/vendor/cli/src/permissions.js +290 -1
  20. package/vendor/cli/src/provenance.js +182 -2
  21. package/vendor/cli/src/provenance.lock.json +2 -2
  22. package/vendor/cli/vendor/client/aegis.js +1 -1
  23. package/vendor/cli/vendor/client/attest.js +1 -1
  24. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  25. package/vendor/cli/vendor/client/catalog-client.js +3 -0
  26. package/vendor/cli/vendor/client/conversation-export.js +3 -0
  27. package/vendor/cli/vendor/client/drive-upload.js +1 -1
  28. package/vendor/cli/vendor/client/session-store.js +1 -1
  29. package/vendor/cli/vendor/desktop/lib/local/attachments.js +3 -0
  30. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  31. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  32. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  33. package/vendor/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
  34. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  35. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  36. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  37. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -1
  38. package/vendor/cli/vendor/desktop/lib/local/spill.js +3 -0
  39. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1
  40. package/vendor/cli/vendor/one/src/permissions.js +1 -1
  41. package/vendor/desktop/lib/auto.js +1 -1
  42. package/vendor/desktop/lib/google-connect.js +1 -1
  43. package/vendor/desktop/lib/local/attachments.js +3 -0
  44. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  45. package/vendor/desktop/lib/local/context.js +1 -1
  46. package/vendor/desktop/lib/local/engine.js +1 -1
  47. package/vendor/desktop/lib/local/exec-plan.js +3 -0
  48. package/vendor/desktop/lib/local/local.js +1 -1
  49. package/vendor/desktop/lib/local/prompt.js +1 -1
  50. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  51. package/vendor/desktop/lib/local/shell.js +1 -1
  52. package/vendor/desktop/lib/local/spill.js +3 -0
  53. package/vendor/desktop/lib/local/tools.js +1 -1
  54. package/vendor/desktop/main.js +1 -1
  55. package/vendor/desktop/package.json +3 -2
  56. package/vendor/desktop/preload.js +1 -1
  57. package/vendor/desktop/renderer/app.js +1 -1
  58. package/vendor/desktop/renderer/budget.js +1 -1
  59. package/vendor/desktop/renderer/fingerprint.js +2 -2
  60. package/vendor/desktop/renderer/index.html +44 -4
  61. package/vendor/desktop/renderer/quick.html +4 -1
  62. package/vendor/desktop/renderer/quick.js +1 -1
  63. package/vendor/desktop/renderer/stream-policy.js +1 -1
  64. package/vendor/desktop/renderer/style.css +124 -0
  65. package/vendor/desktop/vendor/aegis.js +1 -1
  66. package/vendor/desktop/vendor/attest.js +1 -1
  67. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  68. package/vendor/desktop/vendor/catalog-client.js +3 -0
  69. package/vendor/desktop/vendor/conversation-export.js +3 -0
  70. package/vendor/desktop/vendor/drive-upload.js +1 -1
  71. package/vendor/desktop/vendor/session-store.js +1 -1
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";!function(e,t){const n=function(){const e={cardStatus:"fp-card-status",cardOpen:"fp-open",overlay:"fp-overlay",backdrop:"fp-backdrop",close:"fp-close",keySource:"fp-key-source",keyPath:"fp-key-path",keyTag:"fp-key-tag",keyWarning:"fp-key-warning",vaultTarget:"fp-vault-target",vaultBackendDrive:"fp-vault-backend-drive",vaultBackendCloud:"fp-vault-backend-aegiscloud",vaultBackendOff:"fp-vault-backend-off",label:"fp-label",publishOnMint:"fp-publish-on-mint",autoSeal:"fp-auto-seal",autoSealLabel:"fp-auto-seal-label",autoHint:"fp-auto-hint",sealNow:"fp-seal-now",keygen:"fp-keygen",seal:"fp-seal",sealCard:"fp-seal-card",verify:"fp-verify",publish:"fp-publish",anchor:"fp-anchor",backupTo:"fp-backup-to",backup:"fp-backup",vault:"fp-vault",audit:"fp-audit",vaultList:"fp-vault-list",out:"fp-out",driveStatus:"fp-drive-status",driveSignIn:"fp-drive-signin",driveConnect:"fp-drive-connect",driveSyncNow:"fp-drive-sync"},t=e=>null==e||""===e?"–":String(e);function n(e){return e?!1===e.ok?e.error||"unavailable":e.configured?`key ${t(e.keyFingerprint)} · ${t(e.keySource)}`:"no key — mint one to seal records":"checking…"}function a(e){if(!e||!1===e.ok)return[{k:"state",v:e&&e.error||"unavailable"}];const n=[{k:"key",v:e.configured?e.keyFingerprint:"none"},{k:"source",v:t(e.keySource)},{k:"expected at",v:t(e.defaultKeyPath)},{k:"history",v:e.historyPresent?e.historyPath:"none yet"}];return e.configured&&e.keyPath&&e.keyPath!==e.defaultKeyPath&&n.splice(2,0,{k:"in use",v:e.keyPath}),n}function o(e){const t=e&&e.error?String(e.error):"";return/chmod/i.test(t)?t:""}function i(e){if(!e||!1===e.ok)return[{name:"vault unavailable",detail:e&&e.error||"unknown error"}];const t=Array.isArray(e.records)?e.records:Array.isArray(e.items)?e.items:Array.isArray(e.entries)?e.entries:[];return t.length?t.map((e=>{const t=e.name||e.file||e.path||e.id||"record",n=[e.id,e.publishedAt||e.createdAt,e.url].filter(Boolean);return{name:String(t),detail:n.join(" · ")}})):[{name:"nothing published yet",detail:""}]}function r(e){return e&&!1!==e.ok?e.signedIn?e.connected?"Google Drive connected"+(e.email?` · ${e.email}`:""):"signed in · Google Drive not connected yet":"not signed in — sign in with Google first":e&&e.error||"unavailable"}function s(e){if(!e||!1===e.ok)return{ok:!1,label:e&&e.error||"anchor check failed",claims:[]};const t=void 0!==e.present?e.present:e.presence,n=[{k:"present",v:t},{k:"unchanged",v:e.unchanged},{k:"attested",v:e.attested}],a=!0===t&&!0===e.unchanged&&!0===e.attested;return{ok:a,label:a?"the published copy is this record":"the published copy is not verifiably this record",claims:n}}function l(e){if(!e||!1===e.ok)return{ok:!1,label:e&&e.error||"audit failed",findings:[]};const t=Array.isArray(e.findings)?e.findings:Array.isArray(e.leaks)?e.leaks:Array.isArray(e.hits)?e.hits:[];return t.length?{ok:!1,label:`${t.length} item(s) in the vault look like key material`,findings:t}:{ok:!0,label:"no key material in the vault",findings:[]}}function u(e){if(!e||!1===e.ok)return{ok:!1,text:e&&e.error||"seal failed"};const n=e.record||{},a=[`sealed ${t(n.id)}`,`key ${t(n.keyFingerprint)}`,e.out];return a.push(n.aiKey?`ai ${t(n.ai)} on ${t(n.aiKey)}`:"ai unobserved"+(n.ai?` (${t(n.ai)})`:"")),e.vault&&e.vault.url?a.push(`published ${e.vault.url}`):e.vault&&a.push(`published ${t(e.vault.remote||e.vault.path)}`),e.vaultError&&a.push(`publish failed: ${e.vaultError}`),{ok:!0,text:a.filter(Boolean).join(" · "),file:e.out||null,record:e.record||null}}function c(e){if(!e||"object"!=typeof e)return"–";if(!0!==e.enabled)return"off — sealing stays a button";const t=[],n=Number(e.quietMs);return t.push(Number.isFinite(n)?`seals ${Math.round(n/1e3)}s after the last turn`:"seals when the session goes quiet"),e.publish&&t.push("publishes to the vault"),e.pendingTurns&&t.push(`${e.pendingTurns} turn${1===e.pendingTurns?"":"s"} pending`),e.seals&&t.push(`${e.seals} sealed`),e.failures&&t.push(`${e.failures} failed`),e.lastError&&t.push(`last error: ${e.lastError}`),t.join(" · ")}return{IDS:e,mount:function({api:d,doc:f,auto:p}={}){const k=f||("undefined"!=typeof document?document:null);if(!k)throw new Error("fingerprint: mount needs a document");const y=d||("undefined"!=typeof window?window.aegis:null),h=p||("undefined"!=typeof window?window.auto:null),v=e=>k.getElementById(e),g={status:null,last:null,busy:!1,mounted:!0};function b(t,n){const a=v(e.out);a&&(a.textContent=t,a.className=n?"fp-out fp-bad":"fp-out")}async function m(e,t){if(!y||"function"!=typeof y[e])return{ok:!1,error:`this build has no ${e} bridge`};try{const n=await y[e](t);return n&&"object"==typeof n?n:{ok:!1,error:`${e} returned nothing`}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}async function $(){const t=await m("getVaultBackend");return g.vaultBackend=t&&t.backend?t.backend:"aegiscloud",function(t){const n={drive:v(e.vaultBackendDrive),aegiscloud:v(e.vaultBackendCloud),off:v(e.vaultBackendOff)};for(const[e,a]of Object.entries(n))a&&a.setAttribute("aria-pressed",String(e===t))}(g.vaultBackend),g.vaultBackend}const w=e=>L("vault: "+("drive"===e?"Google Drive":"off"===e?"no sync":"AE"),(async()=>{const t=await m("setVaultBackend",e);return t&&t.backend?{ok:!0,...t}:{ok:!1,error:"could not save that"}}),{after:e=>e&&e.ok?N():null,say:e=>e.ok?`vault backend set to ${t(e.backend)}`:`could not save that: ${e.error}`});async function S(){const t=await m("driveStatus");return g.drive=t,function(t){const n=v(e.driveStatus);n&&(n.textContent=r(t));const a=v(e.driveConnect);a&&(a.disabled=Boolean(t&&!t.signedIn));const o=v(e.driveSyncNow);o&&(o.disabled=Boolean(!t||!t.connected))}(t),t}const B=()=>L("sign in with Google",(()=>m("driveSignIn")),{after:e=>e&&e.ok?S():null,say:e=>e.ok?"signed in"+(e.username?` as ${e.username}`:""):`sign-in failed: ${e.error}`}),C=()=>L("connect Google Drive",(()=>m("driveConnect")),{after:e=>e&&e.ok?S():null,say:e=>e.ok?"Google Drive connected"+(e.email?` · ${e.email}`:""):`could not connect: ${e.error}`}),x=()=>L("back up memory to Drive",(()=>m("driveSyncMemory")),{say:e=>e.ok?`backed up ${e.count} memory entr${1===e.count?"y":"ies"}${e.webViewLink?` → ${e.webViewLink}`:""}`:`backup failed: ${e.error}`});function A(t){const n=v(e.vaultList);if(n){n.textContent="";for(const e of i(t)){const t=k.createElement("li");t.className="fp-vault-row";const a=k.createElement("span");if(a.className="fp-vault-name",a.textContent=e.name,t.appendChild(a),e.detail){const n=k.createElement("span");n.className="fp-vault-detail",n.textContent=e.detail,t.appendChild(n)}n.appendChild(t)}}}async function N(){return g.status=await m("fingerprintStatus"),function(){const i=g.status,r=v(e.cardStatus);r&&(r.textContent=n(i));const s=v(e.keySource),l=v(e.keyPath),u=v(e.keyTag),c=v(e.keyWarning),d=v(e.vaultTarget),f=a(i),p=e=>{const t=f.find((t=>t.k===e));return t?t.v:"–"};if(s&&(s.textContent=p("source")),l&&(l.textContent=i&&i.keyPath?i.keyPath:p("expected at")),u&&(u.textContent=i&&i.configured?t(i.keyFingerprint):"none"),c){const e=o(i);c.textContent=e,c.hidden=!e}d&&i&&i.vault?
3
+ "use strict";!function(e,t){const n=function(){const e={cardStatus:"fp-card-status",cardOpen:"fp-open",overlay:"fp-overlay",backdrop:"fp-backdrop",close:"fp-close",keySource:"fp-key-source",keyPath:"fp-key-path",keyTag:"fp-key-tag",keyWarning:"fp-key-warning",vaultTarget:"fp-vault-target",vaultBackendDrive:"fp-vault-backend-drive",vaultBackendCloud:"fp-vault-backend-aegiscloud",vaultBackendOff:"fp-vault-backend-off",label:"fp-label",publishOnMint:"fp-publish-on-mint",autoSeal:"fp-auto-seal",autoSealLabel:"fp-auto-seal-label",autoHint:"fp-auto-hint",sealNow:"fp-seal-now",keygen:"fp-keygen",seal:"fp-seal",sealCard:"fp-seal-card",verify:"fp-verify",publish:"fp-publish",anchor:"fp-anchor",backupTo:"fp-backup-to",backup:"fp-backup",vault:"fp-vault",audit:"fp-audit",vaultList:"fp-vault-list",out:"fp-out",driveStatus:"fp-drive-status",driveSignIn:"fp-drive-signin",driveConnect:"fp-drive-connect",driveSyncNow:"fp-drive-sync",driveBackupChat:"fp-drive-backup-chat",driveHint:"fp-drive-hint"},t=e=>null==e||""===e?"–":String(e);function n(e){return e?!1===e.ok?e.error||"unavailable":e.configured?`key ${t(e.keyFingerprint)} · ${t(e.keySource)}`:"no key — mint one to seal records":"checking…"}function a(e){if(!e||!1===e.ok)return[{k:"state",v:e&&e.error||"unavailable"}];const n=[{k:"key",v:e.configured?e.keyFingerprint:"none"},{k:"source",v:t(e.keySource)},{k:"expected at",v:t(e.defaultKeyPath)},{k:"history",v:e.historyPresent?e.historyPath:"none yet"}];return e.configured&&e.keyPath&&e.keyPath!==e.defaultKeyPath&&n.splice(2,0,{k:"in use",v:e.keyPath}),n}function o(e){const t=e&&e.error?String(e.error):"";return/chmod/i.test(t)?t:""}function i(e){if(!e||!1===e.ok)return[{name:"vault unavailable",detail:e&&e.error||"unknown error"}];const t=Array.isArray(e.records)?e.records:Array.isArray(e.items)?e.items:Array.isArray(e.entries)?e.entries:[];return t.length?t.map((e=>{const t=e.name||e.file||e.path||e.id||"record",n=[e.id,e.publishedAt||e.createdAt,e.url].filter(Boolean);return{name:String(t),detail:n.join(" · ")}})):[{name:"nothing published yet",detail:""}]}function r(e){return e&&!1!==e.ok?e.signedIn?e.connected?"Google Drive connected"+(e.email?` · ${e.email}`:""):"signed in · Google Drive not connected yet":"not signed in — sign in with Google first":e&&e.error||"unavailable"}function s(e){if(!e||!1===e.ok)return{ok:!1,label:e&&e.error||"anchor check failed",claims:[]};const t=void 0!==e.present?e.present:e.presence,n=[{k:"present",v:t},{k:"unchanged",v:e.unchanged},{k:"attested",v:e.attested}],a=!0===t&&!0===e.unchanged&&!0===e.attested;return{ok:a,label:a?"the published copy is this record":"the published copy is not verifiably this record",claims:n}}function l(e){if(!e||!1===e.ok)return{ok:!1,label:e&&e.error||"audit failed",findings:[]};const t=Array.isArray(e.findings)?e.findings:Array.isArray(e.leaks)?e.leaks:Array.isArray(e.hits)?e.hits:[];return t.length?{ok:!1,label:`${t.length} item(s) in the vault look like key material`,findings:t}:{ok:!0,label:"no key material in the vault",findings:[]}}function u(e){if(!e||!1===e.ok)return{ok:!1,text:e&&e.error||"seal failed"};const n=e.record||{},a=[`sealed ${t(n.id)}`,`key ${t(n.keyFingerprint)}`,e.out];return a.push(n.aiKey?`ai ${t(n.ai)} on ${t(n.aiKey)}`:"ai unobserved"+(n.ai?` (${t(n.ai)})`:"")),e.vault&&e.vault.url?a.push(`published ${e.vault.url}`):e.vault&&a.push(`published ${t(e.vault.remote||e.vault.path)}`),e.vaultError&&a.push(`publish failed: ${e.vaultError}`),{ok:!0,text:a.filter(Boolean).join(" · "),file:e.out||null,record:e.record||null}}function c(e){if(!e||"object"!=typeof e)return"–";if(!0!==e.enabled)return"off — sealing stays a button";const t=[],n=Number(e.quietMs);return t.push(Number.isFinite(n)?`seals ${Math.round(n/1e3)}s after the last turn`:"seals when the session goes quiet"),e.publish&&t.push("publishes to the vault"),e.pendingTurns&&t.push(`${e.pendingTurns} turn${1===e.pendingTurns?"":"s"} pending`),e.seals&&t.push(`${e.seals} sealed`),e.failures&&t.push(`${e.failures} failed`),e.lastError&&t.push(`last error: ${e.lastError}`),t.join(" · ")}return{IDS:e,mount:function({api:d,doc:f,auto:p,getSessionId:k}={}){const y=f||("undefined"!=typeof document?document:null);if(!y)throw new Error("fingerprint: mount needs a document");const h=d||("undefined"!=typeof window?window.aegis:null),v=p||("undefined"!=typeof window?window.auto:null),b=e=>y.getElementById(e),g={status:null,last:null,busy:!1,mounted:!0};function $(t,n){const a=b(e.out);a&&(a.textContent=t,a.className=n?"fp-out fp-bad":"fp-out")}async function w(e,t){if(!h||"function"!=typeof h[e])return{ok:!1,error:`this build has no ${e} bridge`};try{const n=await h[e](t);return n&&"object"==typeof n?n:{ok:!1,error:`${e} returned nothing`}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}async function m(){const t=await w("getVaultBackend");return g.vaultBackend=t&&t.backend?t.backend:"aegiscloud",function(t){const n={drive:b(e.vaultBackendDrive),aegiscloud:b(e.vaultBackendCloud),off:b(e.vaultBackendOff)};for(const[e,a]of Object.entries(n))a&&a.setAttribute("aria-pressed",String(e===t))}(g.vaultBackend),g.vaultBackend}const S=e=>I("vault: "+("drive"===e?"Google Drive":"off"===e?"no sync":"AE"),(async()=>{const t=await w("setVaultBackend",e);return t&&t.backend?{ok:!0,...t}:{ok:!1,error:"could not save that"}}),{after:e=>e&&e.ok?L():null,say:e=>e.ok?`vault backend set to ${t(e.backend)}`:`could not save that: ${e.error}`});function B(){try{return"function"==typeof k&&k()||null}catch{return null}}async function C(){const t=await w("driveStatus");return g.drive=t,function(t){const n=b(e.driveStatus);n&&(n.textContent=r(t));const a=b(e.driveConnect);a&&(a.disabled=Boolean(t&&!t.signedIn));const o=Boolean(t&&t.connected),i=b(e.driveSyncNow);i&&(i.disabled=!o);const s=b(e.driveBackupChat);s&&(s.disabled=!(o&&Boolean(B())));const l=b(e.driveHint);l&&(l.textContent=o?"Each saved file starts with who wrote it, so it still makes sense in Drive without this app.":"Nothing is uploaded until you pick one of the two backups below.")}(t),t}const x=()=>I("sign in with Google",(()=>w("driveSignIn")),{after:e=>e&&e.ok?C():null,say:e=>e.ok?"signed in"+(e.username?` as ${e.username}`:""):`sign-in failed: ${e.error}`}),A=()=>I("connect Google Drive",(()=>w("driveConnect")),{after:e=>e&&e.ok?C():null,say:e=>e.ok?"Google Drive connected"+(e.email?` · ${e.email}`:""):`could not connect: ${e.error}`}),D=()=>I("back up all memory to Drive",(()=>w("driveSyncMemory")),{say:e=>e.ok?`backed up all ${e.count} memory entr${1===e.count?"y":"ies"}${e.author?` · authored ${e.author}`:""}${e.webViewLink?` → ${e.webViewLink}`:""}`:`backup failed: ${e.error}`}),N=()=>I("back up this conversation to Drive",(()=>w("driveBackupConversation",{sessionId:B()})),{say:e=>e.ok?`saved ${e.title?`“${e.title}”`:"this conversation"}${e.author?` · authored ${e.author}`:""}${e.webViewLink?` → ${e.webViewLink}`:""}`:`could not save this conversation: ${e.error}`});function V(t){const n=b(e.vaultList);if(n){n.textContent="";for(const e of i(t)){const t=y.createElement("li");t.className="fp-vault-row";const a=y.createElement("span");if(a.className="fp-vault-name",a.textContent=e.name,t.appendChild(a),e.detail){const n=y.createElement("span");n.className="fp-vault-detail",n.textContent=e.detail,t.appendChild(n)}n.appendChild(t)}}}async function L(){return g.status=await w("fingerprintStatus"),function(){const i=g.status,r=b(e.cardStatus);r&&(r.textContent=n(i));const s=b(e.keySource),l=b(e.keyPath),u=b(e.keyTag),c=b(e.keyWarning),d=b(e.vaultTarget),f=a(i),p=e=>{const t=f.find((t=>t.k===e));return t?t.v:"–"};if(s&&(s.textContent=p("source")),l&&(l.textContent=i&&i.keyPath?i.keyPath:p("expected at")),u&&(u.textContent=i&&i.configured?t(i.keyFingerprint):"none"),c){const e=o(i);c.textContent=e,c.hidden=!e}d&&i&&i.vault?
4
4
  // not where anything goes — printing `gdrive:AEGIS-AGPL/records` for a
5
- d.textContent="off"===i.vault.backend?"nothing — sync is off":"aegiscloud"===i.vault.backend?`aegiscloud:${t(i.vault.recordsDir)}`:`${t(i.vault.remote)}:${t(i.vault.recordsDir||i.vault.root)}`:d&&(d.textContent="–");const k=v(e.keygen);k&&(k.textContent=i&&i.configured?"Replace key…":"Mint key")}(),await M(),await $(),await S(),g.status}function D(t){if(!t||"object"!=typeof t)return;const n=v(e.autoSeal);n&&(n.checked=!0===t.enabled);const a=v(e.autoSealLabel);a&&(a.textContent=t.enabled?"sealing automatically when quiet":"seal automatically when quiet");const o=v(e.autoHint);o&&(o.textContent=c(t))}async function M(){if(!h||"function"!=typeof h.status){const t=v(e.autoHint);return t&&(t.textContent="this build has no automation bridge — sealing stays a button"),null}try{const e=await h.status();return e&&e.mint&&D(e.mint),e}catch(t){const n=v(e.autoHint);return n&&(n.textContent=`automation status unavailable: ${t&&t.message||String(t)}`),null}}async function V(){const n=Boolean(v(e.publishOnMint)&&v(e.publishOnMint).checked);return L("seal now",(async()=>h&&"function"==typeof h.sealNow?h.sealNow(n):{ok:!1,error:"this build has no automation bridge"}),{paint:e=>{e&&e.ok&&e.out&&(g.last={file:e.out,record:e.record||null})},say:e=>{if(!e)return"seal now: nothing happened";if(!1===e.ok)return`seal failed: ${e.error||"unknown"}`;if("skip"===e.type)return`nothing to seal (${e.reason||"no new turns"})`;const n=u(e);return n.ok?`sealed ${t((e.record||{}).id)} → ${t(e.out)}`:`seal failed: ${n.text}`}})}async function L(e,t,n){const a=n||{};if(g.busy)return null;g.busy=!0,b(`${e}…`,!1);try{const n=await t();return a.paint&&a.paint(n),a.after&&await a.after(n),b(a.say?a.say(n):`${e}: ${n&&!1===n.ok?n.error:"done"}`,Boolean(n&&!1===n.ok)),n}finally{g.busy=!1}}const O=()=>L("mint key",(()=>m("fingerprintKeygen",{force:Boolean(g.status&&g.status.configured)})),{after:N,say:e=>e.ok?`minted ${t(e.keyFingerprint)} at ${t(e.path)}`:`mint failed: ${e.error}`}),P=()=>L("seal session",(()=>m("fingerprintMint",{label:v(e.label)&&v(e.label).value.trim()||null,publish:Boolean(v(e.publishOnMint)&&v(e.publishOnMint).checked)})),{paint:e=>{e.ok&&(g.last={file:e.out,record:e.record})},say:e=>{const n=u(e);return n.ok?`sealed ${t((e.record||{}).id)} → ${t(e.out)}`:`seal failed: ${n.text}`}}),E=()=>L("verify",(async()=>g.last&&g.last.file?m("fingerprintVerify",{file:g.last.file}):g.last&&g.last.record?m("fingerprintVerify",{record:g.last.record}):{ok:!1,error:"nothing sealed in this window yet — seal a session first"}),{say:e=>e.ok?`verified ${t(e.id)} · key ${t(e.keySource)}`:`not verified: ${e.error||e.reason}`}),I=()=>L("publish",(()=>g.last&&g.last.file?m("fingerprintPublish",{file:g.last.file}):g.last&&g.last.record?m("fingerprintPublish",{record:g.last.record}):{ok:!1,error:"nothing sealed in this window yet — seal a session first"}),{say:e=>e.ok?`published ${t(e.url||e.path)}${e.sha256?` · sha256 ${String(e.sha256).slice(0,12)}`:""}`:`publish failed: ${e.error}`}),T=()=>L("check anchor",(()=>g.last&&g.last.file?m("fingerprintAnchor",{file:g.last.file}):m("fingerprintAnchor",{})),{say:e=>{const t=s(e),n=t.claims.map((e=>`${e.k} ${!0===e.v?"yes":!1===e.v?"no":"unknown"}`)).join(" · ");return`${t.label}${n?` — ${n}`:""}`}}),j=()=>L("back up key",(()=>{const t=v(e.backupTo)&&v(e.backupTo).value.trim();return t?m("fingerprintBackup",{to:t}):{ok:!1,error:"backup needs a destination directory"}}),{say:e=>e.ok?`key copied to ${t(e.to||e.path)}`:`backup refused: ${e.error}`}),F=()=>L("list vault",(()=>m("fingerprintVault")),{paint:A,say:e=>e.ok?`vault listed — ${i(e).length} entry(ies)`:`vault unavailable: ${e.error}`}),G=()=>L("audit vault",(()=>m("fingerprintVaultAudit")),{say:e=>{const t=l(e),n=t.findings.map((e=>e&&(e.path||e.name)||String(e))).slice(0,3);return`${t.label}${n.length?` — ${n.join(", ")}`:""}`}});async function K(t){const n=v(e.overlay);if(!n)return;if(n.hidden=!1,k.body&&k.body.classList&&k.body.classList.add("fp-open"),await N(),await F(),t&&"drive"===t.focus){const t=v(e.driveStatus);t&&t.scrollIntoView&&t.scrollIntoView({block:"center"});const n=[e.driveSignIn,e.driveConnect,e.driveSyncNow].map(v).find((e=>e&&!e.disabled));return void(n&&n.focus())}const a=v(e.close);a&&a.focus()}function q(){const t=v(e.overlay);if(!t)return;t.hidden=!0,k.body&&k.body.classList&&k.body.classList.remove("fp-open");const n=v(e.cardOpen);n&&n.focus()}const H=(e,t,n)=>{const a=v(e);a&&a.addEventListener(t,n)};return H(e.cardOpen,"click",K),H(e.close,"click",q),H(e.backdrop,"click",q),H(e.keygen,"click",O),H(e.seal,"click",P),H(e.sealCard,"click",(async()=>{const e=await P();e&&e.ok&&await K()})),H(e.verify,"click",E),H(e.publish,"click",I),H(e.anchor,"click",T),H(e.backup,"click",j),H(e.vault,"click",F),H(e.audit,"click",G),H(e.vaultBackendDrive,"click",(()=>w("drive"))),H(e.vaultBackendCloud,"click",(()=>w("aegiscloud"))),H(e.vaultBackendOff,"click",(()=>w("off"))),H(e.driveSignIn,"click",B),H(e.driveConnect,"click",C),H(e.driveSyncNow,"click",x),v(e.autoSeal)&&H(e.autoSeal,"change",(()=>{const t=v(e.autoSeal);return async function(t){if(!h||"function"!=typeof h.setMint)return null;const n=Boolean(v(e.publishOnMint)&&v(e.publishOnMint).checked);try{const e=await h.setMint({enabled:Boolean(t),publish:n});return e&&e.mint?D(e.mint):e&&!1===e.ok&&b(e.error||"could not save that",!0),e}catch(e){return b(`could not save that: ${e&&e.message||String(e)}`,!0),null}}(Boolean(t&&t.checked))})),v(e.sealNow)&&H(e.sealNow,"click",V),{open:K,close:q,isOpen:()=>{const t=v(e.overlay);return Boolean(t)&&!t.hidden},refresh:N,loadAutoMint:M,state:g,actions:{doKeygen:O,doSeal:P,doSealNow:V,doVerify:E,doPublish:I,doAnchor:T,doBackup:j,doVault:F,doAudit:G,doSetVaultBackend:w,doDriveSignIn:B,doDriveConnect:C,doDriveSyncNow:x},loadVaultBackend:$,loadDriveStatus:S}},keyLine:n,statusRows:a,keyWarning:o,vaultRows:i,anchorVerdict:s,auditVerdict:l,sealLine:u,autoMintLine:c,driveLine:r,dash:t}}();"undefined"!=typeof module&&module.exports&&(module.exports=n),e&&(e.aegisFingerprint=n)}("undefined"!=typeof window?window:null);
5
+ d.textContent="off"===i.vault.backend?"nothing — sync is off":"aegiscloud"===i.vault.backend?`aegiscloud:${t(i.vault.recordsDir)}`:`${t(i.vault.remote)}:${t(i.vault.recordsDir||i.vault.root)}`:d&&(d.textContent="–");const k=b(e.keygen);k&&(k.textContent=i&&i.configured?"Replace key…":"Mint key")}(),await O(),await m(),await C(),g.status}function M(t){if(!t||"object"!=typeof t)return;const n=b(e.autoSeal);n&&(n.checked=!0===t.enabled);const a=b(e.autoSealLabel);a&&(a.textContent=t.enabled?"sealing automatically when quiet":"seal automatically when quiet");const o=b(e.autoHint);o&&(o.textContent=c(t))}async function O(){if(!v||"function"!=typeof v.status){const t=b(e.autoHint);return t&&(t.textContent="this build has no automation bridge — sealing stays a button"),null}try{const e=await v.status();return e&&e.mint&&M(e.mint),e}catch(t){const n=b(e.autoHint);return n&&(n.textContent=`automation status unavailable: ${t&&t.message||String(t)}`),null}}async function P(){const n=Boolean(b(e.publishOnMint)&&b(e.publishOnMint).checked);return I("seal now",(async()=>v&&"function"==typeof v.sealNow?v.sealNow(n):{ok:!1,error:"this build has no automation bridge"}),{paint:e=>{e&&e.ok&&e.out&&(g.last={file:e.out,record:e.record||null})},say:e=>{if(!e)return"seal now: nothing happened";if(!1===e.ok)return`seal failed: ${e.error||"unknown"}`;if("skip"===e.type)return`nothing to seal (${e.reason||"no new turns"})`;const n=u(e);return n.ok?`sealed ${t((e.record||{}).id)} → ${t(e.out)}`:`seal failed: ${n.text}`}})}async function I(e,t,n){const a=n||{};if(g.busy)return null;g.busy=!0,$(`${e}…`,!1);try{const n=await t();return a.paint&&a.paint(n),a.after&&await a.after(n),$(a.say?a.say(n):`${e}: ${n&&!1===n.ok?n.error:"done"}`,Boolean(n&&!1===n.ok)),n}finally{g.busy=!1}}const E=()=>I("mint key",(()=>w("fingerprintKeygen",{force:Boolean(g.status&&g.status.configured)})),{after:L,say:e=>e.ok?`minted ${t(e.keyFingerprint)} at ${t(e.path)}`:`mint failed: ${e.error}`}),T=()=>{const e=b("model-select");return e&&e.value?e.value:null},j=()=>I("seal session",(()=>w("fingerprintMint",{label:b(e.label)&&b(e.label).value.trim()||null,publish:Boolean(b(e.publishOnMint)&&b(e.publishOnMint).checked),model:T()})),{paint:e=>{e.ok&&(g.last={file:e.out,record:e.record})},say:e=>{const n=u(e);return n.ok?`sealed ${t((e.record||{}).id)} → ${t(e.out)}`:`seal failed: ${n.text}`}}),F=()=>I("verify",(async()=>g.last&&g.last.file?w("fingerprintVerify",{file:g.last.file}):g.last&&g.last.record?w("fingerprintVerify",{record:g.last.record}):{ok:!1,error:"nothing sealed in this window yet — seal a session first"}),{say:e=>e.ok?`verified ${t(e.id)} · key ${t(e.keySource)}`:`not verified: ${e.error||e.reason}`}),G=()=>I("publish",(()=>g.last&&g.last.file?w("fingerprintPublish",{file:g.last.file}):g.last&&g.last.record?w("fingerprintPublish",{record:g.last.record}):{ok:!1,error:"nothing sealed in this window yet — seal a session first"}),{say:e=>e.ok?`published ${t(e.url||e.path)}${e.sha256?` · sha256 ${String(e.sha256).slice(0,12)}`:""}`:`publish failed: ${e.error}`}),H=()=>I("check anchor",(()=>g.last&&g.last.file?w("fingerprintAnchor",{file:g.last.file}):w("fingerprintAnchor",{})),{say:e=>{const t=s(e),n=t.claims.map((e=>`${e.k} ${!0===e.v?"yes":!1===e.v?"no":"unknown"}`)).join(" · ");return`${t.label}${n?` — ${n}`:""}`}}),K=()=>I("back up key",(()=>{const t=b(e.backupTo)&&b(e.backupTo).value.trim();return t?w("fingerprintBackup",{to:t}):{ok:!1,error:"backup needs a destination directory"}}),{say:e=>e.ok?`key copied to ${t(e.to||e.path)}`:`backup refused: ${e.error}`}),q=()=>I("list vault",(()=>w("fingerprintVault")),{paint:V,say:e=>e.ok?`vault listed — ${i(e).length} entry(ies)`:`vault unavailable: ${e.error}`}),R=()=>I("audit vault",(()=>w("fingerprintVaultAudit")),{say:e=>{const t=l(e),n=t.findings.map((e=>e&&(e.path||e.name)||String(e))).slice(0,3);return`${t.label}${n.length?` — ${n.join(", ")}`:""}`}});async function W(t){const n=b(e.overlay);if(!n)return;if(n.hidden=!1,y.body&&y.body.classList&&y.body.classList.add("fp-open"),await L(),await q(),t&&"drive"===t.focus){const t=b(e.driveStatus);t&&t.scrollIntoView&&t.scrollIntoView({block:"center"});const n=[e.driveSignIn,e.driveConnect,e.driveBackupChat,e.driveSyncNow].map(b).find((e=>e&&!e.disabled));return void(n&&n.focus())}const a=b(e.close);a&&a.focus()}function z(){const t=b(e.overlay);if(!t)return;t.hidden=!0,y.body&&y.body.classList&&y.body.classList.remove("fp-open");const n=b(e.cardOpen);n&&n.focus()}const J=(e,t,n)=>{const a=b(e);a&&a.addEventListener(t,n)};return J(e.cardOpen,"click",W),J(e.close,"click",z),J(e.backdrop,"click",z),J(e.keygen,"click",E),J(e.seal,"click",j),J(e.sealCard,"click",(async()=>{const e=await j();e&&e.ok&&await W()})),J(e.verify,"click",F),J(e.publish,"click",G),J(e.anchor,"click",H),J(e.backup,"click",K),J(e.vault,"click",q),J(e.audit,"click",R),J(e.vaultBackendDrive,"click",(()=>S("drive"))),J(e.vaultBackendCloud,"click",(()=>S("aegiscloud"))),J(e.vaultBackendOff,"click",(()=>S("off"))),J(e.driveSignIn,"click",x),J(e.driveConnect,"click",A),J(e.driveSyncNow,"click",D),J(e.driveBackupChat,"click",N),b(e.autoSeal)&&J(e.autoSeal,"change",(()=>{const t=b(e.autoSeal);return async function(t){if(!v||"function"!=typeof v.setMint)return null;const n=Boolean(b(e.publishOnMint)&&b(e.publishOnMint).checked);try{const e=await v.setMint({enabled:Boolean(t),publish:n});return e&&e.mint?M(e.mint):e&&!1===e.ok&&$(e.error||"could not save that",!0),e}catch(e){return $(`could not save that: ${e&&e.message||String(e)}`,!0),null}}(Boolean(t&&t.checked))})),b(e.sealNow)&&J(e.sealNow,"click",P),{open:W,close:z,isOpen:()=>{const t=b(e.overlay);return Boolean(t)&&!t.hidden},refresh:L,loadAutoMint:O,state:g,actions:{doKeygen:E,doSeal:j,doSealNow:P,doVerify:F,doPublish:G,doAnchor:H,doBackup:K,doVault:q,doAudit:R,doSetVaultBackend:S,doDriveSignIn:x,doDriveConnect:A,doDriveSyncNow:D,doDriveBackupChat:N},loadVaultBackend:m,loadDriveStatus:C}},keyLine:n,statusRows:a,keyWarning:o,vaultRows:i,anchorVerdict:s,auditVerdict:l,sealLine:u,autoMintLine:c,driveLine:r,dash:t}}();"undefined"!=typeof module&&module.exports&&(module.exports=n),e&&(e.aegisFingerprint=n)}("undefined"!=typeof window?window:null);
@@ -191,6 +191,7 @@
191
191
  <option value="low">low</option>
192
192
  <option value="medium">medium</option>
193
193
  <option value="high" selected>high</option>
194
+ <option value="max" title="Deepens reasoning where the model defines a max level; the token ceiling stays high's.">max</option>
194
195
  </select>
195
196
  </span>
196
197
  </div>
@@ -349,6 +350,13 @@
349
350
  />
350
351
  <button type="button" id="quick-launcher-save" class="ghost-btn">Save</button>
351
352
  </div>
353
+ <!-- Says which key the popup spends. It asks the BYOK class, so a
354
+ press charges the provider key you configured, not the AEGIS
355
+ account balance the main composer may be using. -->
356
+ <p class="hint">
357
+ The launcher asks <strong>BYOK</strong> — it spends the provider key
358
+ you configured in Settings › Provider, and lists those models.
359
+ </p>
352
360
  <p class="hint" id="quick-launcher-hint"></p>
353
361
  </section>
354
362
 
@@ -717,11 +725,27 @@
717
725
  </div>
718
726
  </template>
719
727
  <div class="messages" id="messages" aria-live="polite"></div>
728
+ <!-- Whole-window drop veil. Shown by the dragenter/dragleave counter in
729
+ app.js (body.is-dropping), never hit-testable itself: the drop still
730
+ lands on the window handler. -->
731
+ <div class="drop-veil" id="drop-veil" aria-hidden="true">
732
+ <div class="drop-veil-label">Drop to attach — files, pictures, or a path</div>
733
+ </div>
720
734
  <form class="composer" id="composer">
735
+ <!-- Files dragged onto the window land here. The row is populated by
736
+ renderAttachments() in app.js and is empty (and collapsed) until
737
+ something is dropped — see ATTACH in app.js for why the drop
738
+ target is the whole window but the chips live in the composer. -->
739
+ <div class="attach-row" id="attach-row" hidden></div>
740
+ <!-- Capability warning for staged attachments: a picture dropped on a
741
+ destination that cannot receive pixels (PRO is a child process fed
742
+ text) says so here BEFORE the turn, instead of the file silently
743
+ arriving as a path. Populated by renderAttachments(). -->
744
+ <div class="attach-note" id="attach-note" hidden></div>
721
745
  <textarea
722
746
  id="prompt"
723
747
  rows="2"
724
- placeholder="Message AEGIS… (Enter to send, Shift+Enter for a newline)"
748
+ placeholder="Message AEGIS… (Enter to send, Shift+Enter for a newline, or drop a file)"
725
749
  ></textarea>
726
750
  <!-- The composer's control row: every switch that changes what this
727
751
  send will do lives INSIDE the composer box, on one line under the
@@ -937,11 +961,27 @@
937
961
  sign-in has actually landed. -->
938
962
  <div class="fp-controls">
939
963
  <div class="fp-row"><span class="fp-k">Google Drive</span><span class="fp-v" id="fp-drive-status">–</span></div>
964
+ <!-- Three steps, in the one order that works: sign-in first (it decides
965
+ which Google account the Drive grant attaches to), then connect,
966
+ then pick WHAT to back up. Written as a numbered recipe because the
967
+ question this card has to answer without a manual is "what do I
968
+ click first?" — see desktop/lib/google-connect.js's header. -->
969
+ <ol class="fp-steps">
970
+ <li><span class="fp-step-k">Sign in</span> — decides which Google account everything else uses.</li>
971
+ <li><span class="fp-step-k">Connect Drive</span> — lets the app write to your own Drive.</li>
972
+ <li><span class="fp-step-k">Back up</span> — choose one conversation, or all of your memory.</li>
973
+ </ol>
940
974
  <div class="fp-actions">
941
- <button type="button" id="fp-drive-signin" class="ghost-btn">Sign in with Google</button>
942
- <button type="button" id="fp-drive-connect" class="ghost-btn" disabled>Connect Drive</button>
943
- <button type="button" id="fp-drive-sync" class="ghost-btn" disabled>Back up memory now</button>
975
+ <button type="button" id="fp-drive-signin" class="ghost-btn">1. Sign in with Google</button>
976
+ <button type="button" id="fp-drive-connect" class="ghost-btn" disabled>2. Connect Drive</button>
977
+ </div>
978
+ <div class="fp-actions fp-drive-scopes">
979
+ <!-- TWO named scopes, not one vague "back up" button: "this
980
+ conversation" and "all memory" are different things to want. -->
981
+ <button type="button" id="fp-drive-backup-chat" class="ghost-btn" disabled title="Save only the conversation that is open right now">3a. Back up this conversation</button>
982
+ <button type="button" id="fp-drive-sync" class="ghost-btn" disabled title="Save every stored memory entry">3b. Back up all memory</button>
944
983
  </div>
984
+ <p class="fp-hint" id="fp-drive-hint">Each saved file starts with who wrote it, so it still makes sense in Drive without this app.</p>
945
985
  </div>
946
986
 
947
987
  <div class="fp-out" id="fp-out">Ready. The key is never displayed.</div>
@@ -23,7 +23,10 @@
23
23
  <form id="ql-form" class="ql-shell">
24
24
  <div class="ql-head">
25
25
  <span class="ql-badge">AEGIS</span>
26
- <span class="ql-model" id="ql-model-label">Aegis Cloud</span>
26
+ <!-- Painted by quick.js. The static text is what shows for the instant
27
+ before the BYOK catalog answers — it must not name a class the
28
+ launcher no longer asks for. -->
29
+ <span class="ql-model" id="ql-model-label">BYOK</span>
27
30
  <select id="ql-model-select" class="ql-model-select" title="Model" hidden></select>
28
31
  <div class="ql-spacer"></div>
29
32
  <button type="button" id="ql-stop" class="ql-stop" hidden>Stop</button>
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";!function(){if(!window.models||!window.quickLauncher)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.models/window.quickLauncher missing).",new Error("window.models/window.quickLauncher unavailable — not running under Electron");const e=window.models,t=window.quickLauncher,n="aegis",o="quick-launcher-model",l={form:document.getElementById("ql-form"),prompt:document.getElementById("ql-prompt"),response:document.getElementById("ql-response"),modelLabel:document.getElementById("ql-model-label"),modelSelect:document.getElementById("ql-model-select"),stopBtn:document.getElementById("ql-stop"),pushBtn:document.getElementById("ql-push"),status:document.getElementById("ql-status")};let s=!1,d=null,c="",i="",a=!1;function r(e){l.status.textContent=e}function m(e){s=e,l.stopBtn.hidden=!e,l.prompt.disabled=e}async function u(t){if(!t||s)return;a=!1,l.pushBtn.hidden=!0,l.response.textContent="",m(!0),r("thinking…"),d=`quick-${Date.now()}-${Math.random().toString(36).slice(2)}`;let o="";try{const s=await e.chat({class:n,model:l.modelSelect.value||void 0,prompt:t,tools:!1,sessionId:d},(e=>{e&&"string"==typeof e.delta&&e.delta&&(o+=e.delta,l.response.textContent=o,l.response.scrollTop=l.response.scrollHeight)})),m=s&&s.choices&&s.choices[0]&&s.choices[0].message,u=o||m&&m.content||"";l.response.textContent=u,c=t,i=u,a=Boolean(u),l.pushBtn.hidden=!a,r(a?"⌘/Ctrl+⏎ to add this to the main chat":"no answer")}catch(e){l.response.textContent=`Error: ${e&&e.message?e.message:e}`,r("failed")}finally{m(!1),d=null}}function p(){a&&t.pushToMain({prompt:c,response:i,model:l.modelSelect.value||null}).catch((()=>{}))}l.modelSelect.addEventListener("change",(()=>{localStorage.setItem(o,l.modelSelect.value)})),l.form.addEventListener("submit",(e=>{e.preventDefault(),u(l.prompt.value.trim())})),l.prompt.addEventListener("keydown",(e=>{if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return e.preventDefault(),void p();"Enter"!==e.key||e.shiftKey||(e.preventDefault(),u(l.prompt.value.trim()))})),l.stopBtn.addEventListener("click",(function(){d&&e.cancel(d).catch((()=>{}))})),l.pushBtn.addEventListener("click",p),window.addEventListener("focus",(()=>{s||(l.prompt.value="",l.response.textContent="",l.pushBtn.hidden=!0,a=!1,r("Enter to ask · Esc to close")),l.prompt.focus()})),async function(){try{const t=(await e.listClasses()||[]).find((e=>e.class===n));if(!t||!t.configured)return l.modelLabel.textContent="Aegis Cloud — no key configured",void(l.modelSelect.hidden=!0);const s=await e.listModels(n),d=s&&s.models||[];l.modelSelect.innerHTML="";for(const e of d){const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.modelSelect.appendChild(t)}const c=localStorage.getItem(o);c&&d.some((e=>e.id===c))&&(l.modelSelect.value=c),l.modelSelect.hidden=d.length<=1,l.modelLabel.textContent="Aegis Cloud"}catch{l.modelLabel.textContent="Aegis Cloud — unavailable",l.modelSelect.hidden=!0}}(),l.prompt.focus()}();
3
+ "use strict";!function(){if(!window.models||!window.quickLauncher)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.models/window.quickLauncher missing).",new Error("window.models/window.quickLauncher unavailable — not running under Electron");const e=window.models,t=window.quickLauncher,n="byok",o="quick-launcher-byok-model",l={form:document.getElementById("ql-form"),prompt:document.getElementById("ql-prompt"),response:document.getElementById("ql-response"),modelLabel:document.getElementById("ql-model-label"),modelSelect:document.getElementById("ql-model-select"),stopBtn:document.getElementById("ql-stop"),pushBtn:document.getElementById("ql-push"),status:document.getElementById("ql-status")};let d=!1,i=null,s="",r="",c=!1,a=null;function u(e){l.status.textContent=e}function m(e){d=e,l.stopBtn.hidden=!e,l.prompt.disabled=e}async function p(t){if(!t||d)return;if(a)return void u(a);c=!1,l.pushBtn.hidden=!0,l.response.textContent="",m(!0),u("thinking…"),i=`quick-${Date.now()}-${Math.random().toString(36).slice(2)}`;let o="";try{const d=await e.chat({class:n,model:l.modelSelect.value||void 0,prompt:t,tools:!1,sessionId:i},(e=>{e&&"string"==typeof e.delta&&e.delta&&(o+=e.delta,l.response.textContent=o,l.response.scrollTop=l.response.scrollHeight)})),a=d&&d.choices&&d.choices[0]&&d.choices[0].message,m=o||a&&a.content||"";l.response.textContent=m,s=t,r=m,c=Boolean(m),l.pushBtn.hidden=!c,u(c?"⌘/Ctrl+⏎ to add this to the main chat":"no answer")}catch(e){l.response.textContent=`Error: ${e&&e.message?e.message:e}`,u("failed")}finally{m(!1),i=null}}function h(){c&&t.pushToMain({prompt:s,response:r,model:l.modelSelect.value||null,class:n}).catch((()=>{}))}l.modelSelect.addEventListener("change",(()=>{localStorage.setItem(o,l.modelSelect.value)})),l.form.addEventListener("submit",(e=>{e.preventDefault(),p(l.prompt.value.trim())})),l.prompt.addEventListener("keydown",(e=>{if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return e.preventDefault(),void h();"Enter"!==e.key||e.shiftKey||(e.preventDefault(),p(l.prompt.value.trim()))})),l.stopBtn.addEventListener("click",(function(){i&&e.cancel(i).catch((()=>{}))})),l.pushBtn.addEventListener("click",h),window.addEventListener("focus",(()=>{d||(l.prompt.value="",l.response.textContent="",l.pushBtn.hidden=!0,c=!1,u(a||"Enter to ask · Esc to close")),l.prompt.focus()})),async function(){try{const t=(await e.listClasses()||[]).find((e=>e.class===n)),d=await e.listModels(n),i=(d&&d.models||[]).slice();i.sort(((e,t)=>{const n=e.configured?0:1,o=t.configured?0:1;if(n!==o)return n-o;const l=String(e.provider||""),d=String(t.provider||"");if(l!==d)return l<d?-1:1;const i=String(e.id||""),s=String(t.id||"");return i<s?-1:i>s?1:0})),l.modelSelect.innerHTML="";for(const e of i){const t=document.createElement("option");t.value=e.id,t.textContent=e.configured?e.label||e.id:`${e.label||e.id} (no key)`,t.disabled=!e.configured,e.configured||(t.title="No key saved for this provider yet."),l.modelSelect.appendChild(t)}const s=localStorage.getItem(o);if(s&&i.some((e=>e.id===s&&e.configured)))l.modelSelect.value=s;else{const e=i.find((e=>e.configured));e&&(l.modelSelect.value=e.id)}l.modelSelect.hidden=i.length<=1;const r=i.filter((e=>e.configured)).length;l.modelLabel.textContent=i.length<=1&&i[0]?i[0].label||i[0].id:`BYOK · ${r}/${i.length}`,a=function(e,t){return e&&e.providersFailed?`BYOK catalog unavailable — ${e&&e.providersError||"catalog unreachable"}`:t.length?e&&e.needsProviderKey?"No provider key saved — add one in Settings › Provider":e&&e.needsAegisKey?"BYOK also needs your AEGIS key — connect it in Settings":null:"No BYOK models — add a provider key in Settings › Provider"}(d,i),a?(l.modelSelect.hidden=i.length<=1,u(a)):t||u("BYOK is not offered by this build")}catch(e){l.modelLabel.textContent="BYOK — unavailable",l.modelSelect.hidden=!0,a=`BYOK unavailable — ${e&&e.message?e.message:e}`,u(a)}}(),l.prompt.focus()}();
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const STICK_SLOP_PX=48;function nearBottom(e,t){const o=e||{},n=Number.isFinite(t)?t:STICK_SLOP_PX;return(Number(o.scrollHeight)||0)-(Number(o.scrollTop)||0)-(Number(o.clientHeight)||0)<=n}function shouldFollow(e,t){const o=t||{};return!!o.force||!o.userScrolledUp&&nearBottom(e,o.slop)}const ABORT_SIGNATURES=[/AbortError/,/\boperation was aborted\b/i,/\buser aborted\b/i,/\brequest\s+aborted\b/i,/\bsignal is aborted\b/i,/\baborted without reason\b/i];function isCancellation(e,t){if((t||{}).userStopped)return!0;if(!e)return!1;if("AbortError"===e.name||"ABORT_ERR"===e.code)return!0;const o="string"==typeof e?e:e.message;return"string"==typeof o&&ABORT_SIGNATURES.some((e=>e.test(o)))}function stopAppliesTo(e,t){return null!=e&&e!==t}function salvageTurn(e){const t=e||{},o="string"==typeof t.streamedText?t.streamedText:"",n="string"==typeof t.reasoningText?t.reasoningText:"";return o?{text:o,reasoning:n,kind:"answer"}:n?{text:n,reasoning:"",kind:"reasoning-only"}:{text:"(stopped before any output)",reasoning:"",kind:"empty"}}function replayableContent(e,t){return"reasoning-only"===e?"(stopped: reasoning only)":"empty"===e?"(stopped before any output)":t}function replayHistory(e){const t=[];for(const o of Array.isArray(e)?e:[]){if(!o)continue;if("user"!==o.role&&"assistant"!==o.role)continue;const e="string"==typeof o.content?o.content:"string"==typeof o.text?o.text:"";if(!e.trim())continue;if("assistant"===o.role&&isPlaceholderContent(e))continue;const n=t[t.length-1];n&&n.role===o.role?n.content=`${n.content}\n\n${e}`:t.push({role:o.role,content:e})}for(;t.length&&"assistant"===t[0].role;)t.shift();return t}function isPlaceholderContent(e){const t="string"==typeof e?e.trim():"";return!!t&&("(stopped: reasoning only)"===t||"(stopped before any output)"===t||"(empty response)"===t||"(no response)"===t)}const LIVE_METER_MIN_GROWTH=32,LIVE_METER_GROWTH_FRACTION=32;function liveMeterDue(e,t){const o=Number(t)||0;if(null==e)return o>0;const n=o-(Number(e)||0);return!(n<=0)&&n>=Math.max(32,Math.floor(o/32))}function toolMark(e){const t=e||{};return!0===t.ok?"✓":!1===t.ok?"✗":"⊘"}"undefined"!=typeof module&&module.exports&&(module.exports={nearBottom:nearBottom,shouldFollow:shouldFollow,isCancellation:isCancellation,stopAppliesTo:stopAppliesTo,salvageTurn:salvageTurn,replayableContent:replayableContent,isPlaceholderContent:isPlaceholderContent,replayHistory:replayHistory,liveMeterDue:liveMeterDue,toolMark:toolMark,STICK_SLOP_PX:STICK_SLOP_PX,LIVE_METER_MIN_GROWTH:32,LIVE_METER_GROWTH_FRACTION:32});
3
+ "use strict";const STICK_SLOP_PX=48;function nearBottom(t,e){const n=t||{},o=Number.isFinite(e)?e:STICK_SLOP_PX;return(Number(n.scrollHeight)||0)-(Number(n.scrollTop)||0)-(Number(n.clientHeight)||0)<=o}function shouldFollow(t,e){const n=e||{};return!!n.force||!n.userScrolledUp&&nearBottom(t,n.slop)}const ABORT_SIGNATURES=[/AbortError/,/\boperation was aborted\b/i,/\buser aborted\b/i,/\brequest\s+aborted\b/i,/\bsignal is aborted\b/i,/\baborted without reason\b/i];function isCancellation(t,e){if((e||{}).userStopped)return!0;if(!t)return!1;if("AbortError"===t.name||"ABORT_ERR"===t.code)return!0;const n="string"==typeof t?t:t.message;return"string"==typeof n&&ABORT_SIGNATURES.some((t=>t.test(n)))}function stopAppliesTo(t,e){return null!=t&&t!==e}function salvageTurn(t){const e=t||{},n="string"==typeof e.streamedText?e.streamedText:"",o="string"==typeof e.reasoningText?e.reasoningText:"";return n?{text:n,reasoning:o,kind:"answer"}:o?{text:o,reasoning:"",kind:"reasoning-only"}:{text:"(stopped before any output)",reasoning:"",kind:"empty"}}function replayableContent(t,e){return"reasoning-only"===t?"(stopped: reasoning only)":"empty"===t?"(stopped before any output)":e}function flattenParts(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return"";const e=[];for(const n of t)n&&"object"==typeof n&&("string"==typeof n.text?e.push(n.text):"image_url"===n.type&&e.push("[image]"));return e.join("\n")}function joinContent(t,e){if("string"==typeof t&&"string"==typeof e)return`${t}\n\n${e}`;const n=[],o=t=>{if("string"!=typeof t){if(Array.isArray(t))for(const e of t)e&&"object"==typeof e&&("image_url"===e.type?n.push(e):"string"==typeof e.text&&n.push({type:"text",text:e.text}))}else t.trim()&&n.push({type:"text",text:t})};o(t),o(e);const r=n.filter((t=>"text"===t.type)).map((t=>t.text)),s=n.filter((t=>"image_url"===t.type)),i=[];return r.length&&i.push({type:"text",text:r.join("\n\n")}),i.push(...s),1===i.length&&"text"===i[0].type?i[0].text:i}function replayHistory(t){const e=[];for(const n of Array.isArray(t)?t:[]){if(!n)continue;if("user"!==n.role&&"assistant"!==n.role)continue;const t="string"==typeof n.content||Array.isArray(n.content)?n.content:"string"==typeof n.text?n.text:"",o=Array.isArray(t)?flattenParts(t):t;if(!o.trim())continue;if("assistant"===n.role&&isPlaceholderContent(o))continue;const r=e[e.length-1];r&&r.role===n.role?r.content=joinContent(r.content,t):e.push({role:n.role,content:t})}for(;e.length&&"assistant"===e[0].role;)e.shift();return e}function isPlaceholderContent(t){const e="string"==typeof t?t.trim():"";return!!e&&("(stopped: reasoning only)"===e||"(stopped before any output)"===e||"(empty response)"===e||"(no response)"===e)}const LIVE_METER_MIN_GROWTH=32,LIVE_METER_GROWTH_FRACTION=32;function liveMeterDue(t,e){const n=Number(e)||0;if(null==t)return n>0;const o=n-(Number(t)||0);return!(o<=0)&&o>=Math.max(32,Math.floor(n/32))}function toolMark(t){const e=t||{};return!0===e.ok?"✓":!1===e.ok?"✗":"⊘"}"undefined"!=typeof module&&module.exports&&(module.exports={nearBottom:nearBottom,shouldFollow:shouldFollow,isCancellation:isCancellation,stopAppliesTo:stopAppliesTo,salvageTurn:salvageTurn,replayableContent:replayableContent,isPlaceholderContent:isPlaceholderContent,replayHistory:replayHistory,liveMeterDue:liveMeterDue,toolMark:toolMark,STICK_SLOP_PX:STICK_SLOP_PX,LIVE_METER_MIN_GROWTH:32,LIVE_METER_GROWTH_FRACTION:32});
@@ -1551,6 +1551,130 @@ label[hidden] {
1551
1551
  box-shadow: 0 0 0 3px var(--accent-soft), var(--shadow-2);
1552
1552
  }
1553
1553
 
1554
+ /* ── Dropped attachments ───────────────────────────────────────────────────
1555
+ A file dropped anywhere on the window lands here as a chip. The chips live
1556
+ INSIDE the composer box (not on the drop target) because they are part of
1557
+ what will be sent: the drop target is the window, the staging area is the
1558
+ message. See the ATTACH block in app.js. */
1559
+ .attach-row {
1560
+ display: flex;
1561
+ flex-wrap: wrap;
1562
+ gap: var(--s-1);
1563
+ /* A hairline top padding keeps the first chip off the box edge; with no
1564
+ chips the row is `hidden` and costs nothing. */
1565
+ padding: 0 0 var(--s-1);
1566
+ }
1567
+
1568
+ /* Same trap as `.session-meter[hidden]` and `.typing-tokens[hidden]` above:
1569
+ `display: flex` here is an AUTHOR rule, and it outranks the UA stylesheet's
1570
+ `[hidden] { display: none }` regardless of specificity — so the row would
1571
+ stay visible with no chips in it. The attribute needs its own rule. */
1572
+ .attach-row[hidden] {
1573
+ display: none;
1574
+ }
1575
+
1576
+ .attach-chip {
1577
+ display: inline-flex;
1578
+ align-items: center;
1579
+ gap: 6px;
1580
+ max-width: 100%;
1581
+ border: 1px solid var(--border2);
1582
+ border-radius: 999px;
1583
+ background: var(--surface1, var(--surface2));
1584
+ color: var(--text2);
1585
+ padding: 3px 4px 3px 10px;
1586
+ font-size: 12px;
1587
+ line-height: 1.5;
1588
+ }
1589
+
1590
+ /* The label is the one part that may be long (a deep path), so it is the one
1591
+ part allowed to shrink and ellipsis. The remove button never shrinks. */
1592
+ .attach-chip .attach-name {
1593
+ overflow: hidden;
1594
+ text-overflow: ellipsis;
1595
+ white-space: nowrap;
1596
+ font-variant-numeric: tabular-nums;
1597
+ }
1598
+
1599
+ .attach-chip .attach-kind {
1600
+ flex: 0 0 auto;
1601
+ color: var(--text3);
1602
+ font-size: 11px;
1603
+ text-transform: uppercase;
1604
+ letter-spacing: 0.04em;
1605
+ }
1606
+
1607
+ /* An image chip is the only one that can be SEEN, so it gets a thumbnail
1608
+ instead of an icon. Fixed box + object-fit so a tall screenshot cannot
1609
+ stretch the composer. */
1610
+ .attach-chip .attach-thumb {
1611
+ flex: 0 0 auto;
1612
+ width: 20px;
1613
+ height: 20px;
1614
+ border-radius: 4px;
1615
+ object-fit: cover;
1616
+ background: var(--surface3, rgba(255, 255, 255, 0.06));
1617
+ }
1618
+
1619
+ /* Refused attachment: shown, not silently dropped. A chip that vanishes on
1620
+ drop is the failure mode where a user believes the file was sent. */
1621
+ .attach-chip.is-refused {
1622
+ border-color: var(--danger, #e5484d);
1623
+ color: var(--danger, #e5484d);
1624
+ }
1625
+
1626
+ .attach-chip .attach-remove {
1627
+ flex: 0 0 auto;
1628
+ border: none;
1629
+ border-radius: 999px;
1630
+ background: transparent;
1631
+ color: var(--text3);
1632
+ width: 18px;
1633
+ height: 18px;
1634
+ padding: 0;
1635
+ font: inherit;
1636
+ font-size: 14px;
1637
+ line-height: 1;
1638
+ cursor: pointer;
1639
+ }
1640
+
1641
+ .attach-chip .attach-remove:hover {
1642
+ background: var(--surface3, rgba(255, 255, 255, 0.08));
1643
+ color: var(--text);
1644
+ }
1645
+
1646
+ /* Whole-window drop target. Painted as an overlay rather than by outlining
1647
+ each element: the drop is valid over the transcript, the composer and the
1648
+ empty space between them, and per-element outlines would flicker as the
1649
+ pointer crossed a boundary. `pointer-events: none` is what lets the drop
1650
+ reach the window handler underneath. */
1651
+ .drop-veil {
1652
+ position: fixed;
1653
+ inset: 0;
1654
+ z-index: 60;
1655
+ display: none;
1656
+ align-items: center;
1657
+ justify-content: center;
1658
+ background: var(--accent-soft);
1659
+ border: 2px dashed var(--teal);
1660
+ /* The veil must not swallow the drop event it was drawn for. */
1661
+ pointer-events: none;
1662
+ }
1663
+
1664
+ body.is-dropping .drop-veil {
1665
+ display: flex;
1666
+ }
1667
+
1668
+ .drop-veil-label {
1669
+ border-radius: var(--r-lg);
1670
+ background: var(--surface2);
1671
+ box-shadow: var(--shadow-2);
1672
+ padding: var(--s-3) var(--s-4);
1673
+ color: var(--text);
1674
+ font-weight: 600;
1675
+ pointer-events: none;
1676
+ }
1677
+
1554
1678
  .composer textarea {
1555
1679
  /* `flex: 1` lives here from the row-era composer, where it let the input eat
1556
1680
  the leftover WIDTH. The composer is a column now, so a 0 flex-basis would
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){return`${e} — the upstream provider gave up before answering${Number(t)>0?` after ${(Number(t)/1e3).toFixed(1)}s`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),y),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${y/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<h;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>T?t.slice(0,T):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>T){const n=new Error(`Response from ${t} exceeded the ${T/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let S=null;const y=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,T=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,h=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function k(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function v(){if(r)return r;if(S)return S;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return S=e.memory_token,S}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&""!==n){const e=o[o.length-1];e&&"user"===e.role&&e.content===n||o.push({role:"user",content:n})}return o}function C(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=P(await w(e,{...t,stream:!1},r,{signal:s})),i=C(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=P(await O(f)),t=C(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(k(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const S=f.body.getReader(),y=new TextDecoder;let T="",h="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const v=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const $=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([S.read(),r,o]):Promise.race([S.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){S.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;T+=y.decode(l,{stream:!0});const u=T.split("\n");T=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:k({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),h=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,h,(e=>{const t=v(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!h&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-$):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=v.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=v.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",S=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:U(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):P(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const S=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const y={provider:t,messages:U(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(y.model=r);const T={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":S};return n&&(T["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",y,T,f,E):P(await w("/api/v1/byok/chat/completions",{...y,stream:!1},T))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:v,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await v()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await v()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await v()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await v()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await v()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await v()))},conversationSyncPush:async function(e){const t=await v();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await v()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
4
+ "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const s of t){const t=e[s];if(null==t)continue;const r="string"==typeof t?t:String(t);if(""!==r.trim())return r}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let s=0;for(const r of fs.readFileSync(e,"utf8").split("\n")){const e=r.trim();if(e)try{const r=JSON.parse(e);r&&"object"==typeof r?t.push(r):s+=1}catch{s+=1}}return{entries:t,skipped:s}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const s=firstKey(e[t],SESSION_KEYS);if(s)return s}return null}function selectTurns(e,{session:t=null,turns:s=null}={}){let r=e;if(t){const s=String(t);r=e.filter((e=>firstKey(e,SESSION_KEYS)===s))}return s&&Number.isFinite(Number(s))&&Number(s)>0&&(r=r.slice(-Math.floor(Number(s)))),r}function observationsFromTurns(e){const t=[];for(const s of Array.isArray(e)?e:[]){if(!s||"object"!=typeof s)continue;const e=firstKey(s,DIR_KEYS),r=firstKey(s,DEMAND_KEYS);t.push({tool:r||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(r||"").slice(0,8)}`,outcome:firstKey(s,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const s of Array.isArray(e)?e:[]){if(!s||"object"!=typeof s)continue;const e=firstKey(s,REPLY_KEYS),r=firstKey(s,OUTCOME_KEYS),o=firstKey(s,MODEL_KEYS),n=Boolean(e||r||o);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:r||null,model:o})}return t}function resolveAiSecret(e={}){const t=e.argv||[],s=e.env||{},r=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(r){const e=fs.readFileSync(r,"utf8").trim();if(!e)throw new Error(`attest: ${r} is empty — an empty AI credential is not one`);return{secret:e,source:r}}const o=s[AI_SECRET_ENV]&&String(s[AI_SECRET_ENV]).trim();return o?{secret:o,source:AI_SECRET_ENV}:{secret:null,source:"none"}}function firstFlag(e,t){for(const s of t){const t=e.indexOf(s);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:s=[]}={}){const r=new Set(s),o=[],n=(e,t)=>{const s=fs.statSync(t);if(!s.isFile())return;if(s.size>2097152)throw new Error(`attest: ${t} is ${s.size} bytes — too large to attest (max 2097152)`);if(o.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const r=fp.normaliseCodePath(e);r&&o.push({path:r,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),s=(e,t)=>{for(const o of fs.readdirSync(e).sort()){const i=path.join(e,o),a=t?`${t}/${o}`:o,c=fs.lstatSync(i);if(!c.isSymbolicLink())if(c.isDirectory()){if(SKIP_DIRS.has(o)||r.has(o))continue;s(i,a)}else n(a,i)}};s(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return o}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const s=e.history||DEFAULT_HISTORY(),{entries:r,skipped:o}=readHistory(s),n=selectTurns(r,{session:e.session||lastSessionId(r),turns:e.turns}),i=observationsFromTurns(n),a=e.code||[],c=void 0===e.aiSecret?resolveAiSecret(e):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},l=e.aiObservations||aiObservationsFromTurns(n),u=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map((e=>e.model)).filter(Boolean).pop()||"",S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:a,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:c.secret,aiModel:u,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:c.source,aiSamples:S.aiSamples,skippedLines:o}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
3
+ "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter((e=>firstKey(e,SESSION_KEYS)===r))}return r&&Number.isFinite(Number(r))&&Number(r)>0&&(o=o.slice(-Math.floor(Number(r)))),o}function observationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,DIR_KEYS),o=firstKey(r,DEMAND_KEYS);t.push({tool:o||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(o||"").slice(0,8)}`,outcome:firstKey(r,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,REPLY_KEYS),o=firstKey(r,OUTCOME_KEYS),s=firstKey(r,MODEL_KEYS),n=Boolean(e||o||s);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:o||null,model:s})}return t}function resolveAiSecret(e={}){const t=e.argv||[],r=e.env||{},o=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(o){const e=fs.readFileSync(o,"utf8").trim();if(!e)throw new Error(`attest: ${o} is empty — an empty AI credential is not one`);return{secret:e,source:o}}const s=r[AI_SECRET_ENV]&&String(r[AI_SECRET_ENV]).trim();if(s)return{secret:s,source:AI_SECRET_ENV};const n=String(e.aiModel||e.model||"").trim();if(n&&"function"==typeof envFile.providerForModelId){const t=envFile.providerForModelId(n,e.cls);if(t){const e=envFile.providerKeyFromEnv(t,r);if(e&&e.key)return{secret:e.key,source:e.env};const o=providerKeyFromFile(t,r);if(o)return o}}return{secret:null,source:"none"}}function providerKeyFromFile(e,t){const r="function"==typeof envFile.envVarFor?envFile.envVarFor(e):"";if(!r)return null;const o=t&&(t.AEGIS_HOME||t.AEGISCODE_HOME)?String(t.AEGIS_HOME||t.AEGISCODE_HOME):void 0;let s;try{s=envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(o),"utf8"))}catch{return null}const n=s&&"string"==typeof s[r]?s[r].trim():"";return n&&("function"!=typeof envFile.credentialLooksUsable||envFile.credentialLooksUsable(n))?{secret:n,source:r}:null}function firstFlag(e,t){for(const r of t){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:r=[]}={}){const o=new Set(r),s=[],n=(e,t)=>{const r=fs.statSync(t);if(!r.isFile())return;if(r.size>2097152)throw new Error(`attest: ${t} is ${r.size} bytes — too large to attest (max 2097152)`);if(s.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const o=fp.normaliseCodePath(e);o&&s.push({path:o,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),r=(e,t)=>{for(const s of fs.readdirSync(e).sort()){const i=path.join(e,s),c=t?`${t}/${s}`:s,l=fs.lstatSync(i);if(!l.isSymbolicLink())if(l.isDirectory()){if(SKIP_DIRS.has(s)||o.has(s))continue;r(i,c)}else n(c,i)}};r(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return s}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const r=e.history||DEFAULT_HISTORY(),{entries:o,skipped:s}=readHistory(r),n=selectTurns(o,{session:e.session||lastSessionId(o),turns:e.turns}),i=observationsFromTurns(n),c=e.code||[],l=e.aiObservations||aiObservationsFromTurns(n),a=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map((e=>e.model)).filter(Boolean).pop()||"",u=void 0===e.aiSecret?resolveAiSecret({...e,aiModel:a}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:c,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:u.secret,aiModel:a,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:u.source,aiSamples:S.aiSamples,skippedLines:s}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({deepseek:Object.freeze(["deepseek-flash","deepseek-v4-pro"]),anthropic:Object.freeze(["claude-opus-5","claude-fable-5","claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-1"]),grok:Object.freeze(["grok-4.7"]),gemini:Object.freeze(["gemini-3.8-flash"]),openai:Object.freeze(["gpt-5.5"])});function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",t=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(t)||!t.length){o.push(e);continue}const s=new Set(modelIdsOf(e)),i=t.filter((e=>!s.has(e)));if(!i.length){o.push(e);continue}const n=Array.isArray(e.models)?e.models:[];o.push({...e,models:[...n,...i]})}return o}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,addedModelsFor:addedModelsFor,withByokAdditions:withByokAdditions};
3
+ "use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro"})});function canonicalModelId(e,r){const s="string"==typeof r?r.trim():"";if(!s)return s;const o="string"==typeof e?e.trim():"",t=o?WIRE_MODEL_ALIASES[o]:null;return t&&Object.prototype.hasOwnProperty.call(t,s)?t[s]:s}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(s)?s.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const s=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(o)||!o.length){s.push(e);continue}const t=new Set(modelIdsOf(e)),n=o.filter((e=>!t.has(e)));if(!n.length){s.push(e);continue}const d=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...d,...n]})}return s}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,withByokAdditions:withByokAdditions};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={conversation:"one conversation",memory:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};