@zortexhq/indra-v2.5 0.2.2 → 0.2.4

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 (124) hide show
  1. package/dist/box-level1-setup.js +1 -1
  2. package/dist/calcom-level1-setup.js +1 -1
  3. package/dist/cli-run.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/discord-level1-setup.js +1 -1
  6. package/dist/dropbox-level1-setup.js +1 -1
  7. package/dist/figma-level1-setup.js +1 -1
  8. package/dist/freshdesk-level1-setup.js +1 -1
  9. package/dist/freshrss-level1-setup.js +1 -1
  10. package/dist/front-level1-setup.js +1 -1
  11. package/dist/gateway.js +1 -1
  12. package/dist/google-chat-level1-setup.js +1 -1
  13. package/dist/google-contacts-level1-setup.js +1 -1
  14. package/dist/hubspot-level1-setup.js +1 -1
  15. package/dist/joplin-selection.js +1 -1
  16. package/dist/local-cloud.js +1 -1
  17. package/dist/mattermost-level1-setup.js +1 -1
  18. package/dist/mcp.js +2 -2
  19. package/dist/measurement-context.js +1 -1
  20. package/dist/miniflux-level1-setup.js +1 -1
  21. package/dist/nextcloud-level1-setup.js +1 -1
  22. package/dist/operation-telemetry.js +1 -0
  23. package/dist/prepared-level1-setup.js +1 -0
  24. package/dist/product-feedback.js +2 -2
  25. package/dist/profile.js +1 -1
  26. package/dist/proton-mail-level1-setup.js +1 -1
  27. package/dist/recovery-launch.js +10 -0
  28. package/dist/recovery-support.js +1 -1
  29. package/dist/recovery-surface.js +1 -0
  30. package/dist/recovery.js +1 -1
  31. package/dist/resident-host.js +2 -2
  32. package/dist/resident-jobs.js +1 -1
  33. package/dist/resident-platform.js +1 -1
  34. package/dist/resident-telemetry.js +1 -0
  35. package/dist/resource-telemetry.js +1 -0
  36. package/dist/salesforce-level1-setup.js +1 -1
  37. package/dist/smartsheet-level1-setup.js +1 -1
  38. package/dist/startup.js +2 -2
  39. package/dist/thunderbird-level1-setup.js +1 -1
  40. package/dist/wakatime-level1-setup.js +1 -1
  41. package/dist/wallabag-level1-setup.js +1 -1
  42. package/dist/web.js +2 -2
  43. package/dist/zendesk-level1-setup.js +1 -1
  44. package/dist/zoom-level1-setup.js +1 -1
  45. package/dist/zulip-level1-setup.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  53. package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
  54. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/localizer.js +1 -1
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -0
  61. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
  62. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
  63. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
  64. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +98 -0
  65. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -0
  68. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +13 -0
  69. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy.html +141 -0
  70. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
  71. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-state.js +1 -1
  72. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/panels-live.js +3 -3
  73. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/product.js +1 -1
  74. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +12 -1
  75. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  76. package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
  77. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
  78. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
  79. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
  80. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
  81. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
  82. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
  83. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
  84. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
  85. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
  86. package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -0
  87. package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
  88. package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
  89. package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
  90. package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
  91. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  92. package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
  93. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
  94. package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
  95. package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
  96. package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
  97. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  98. package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
  99. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  100. package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
  101. package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
  102. package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
  103. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  104. package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
  105. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
  106. package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
  107. package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
  108. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  109. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
  110. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
  111. package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
  112. package/node_modules/@zortexhq/plugin-telemetry/dist/device-identity.js +1 -0
  113. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  114. package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
  115. package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
  116. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  117. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
  118. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  119. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
  120. package/package.json +6 -6
  121. package/profiles/core.yml +1 -0
  122. package/release-provenance.json +26 -26
  123. package/update-manifest.json +419 -197
  124. package/dist/recovery-page.js +0 -215
@@ -0,0 +1,141 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Your digital twin</title>
7
+ <script src="look.js"></script>
8
+ <link rel="stylesheet" href="vendor/galaxy.css">
9
+ <link rel="stylesheet" href="zx-tokens.css">
10
+ <link rel="stylesheet" href="star-graph.css">
11
+ <link rel="stylesheet" href="product.css"></head>
12
+ <body>
13
+ <canvas id="universe" role="img" aria-label="Your digital twin. Drag to move around it, Option-drag to turn it; scroll or use the zoom buttons to zoom." tabindex="-1"></canvas>
14
+ <!-- The window's controls, where Apple Maps keeps them: the twin's modes and the whole view, and zoom (the compass is gone, founder 2026-10-06). -->
15
+ <nav class="map-controls" id="controls" aria-label="Twin controls" hidden>
16
+ <div class="capsule">
17
+ <button id="world-toggle" type="button" aria-label="Twin modes" title="Twin modes" aria-expanded="false" aria-controls="world">
18
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path class="fill" d="M3.2 6.7 8 4.6v14.7l-4.8 2.1zM9.4 4.6l5.2 2.1v14.7l-5.2-2.1zM16 6.7l4.8-2.1v14.7L16 21.4z"/></svg>
19
+ </button>
20
+ <button id="recenter" type="button" aria-label="Show the whole twin" title="Show the whole twin">
21
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 4 4.2 10.9l7.1 1.8 1.8 7.1z"/></svg>
22
+ </button>
23
+ </div>
24
+ <div class="capsule play-only">
25
+ <button id="settings-btn" type="button" aria-label="Graph settings" title="Graph settings" aria-expanded="false" aria-controls="world">
26
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h9M17 7h3M4 17h3M11 17h9"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="17" r="2"/></svg>
27
+ </button>
28
+ <button id="full-btn" type="button" aria-label="Full screen" title="Full screen: only the galaxy (Esc to come back)">
29
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 9V5h4M19 9V5h-4M5 15v4h4M19 15v4h-4"/></svg>
30
+ </button>
31
+ </div>
32
+ <div class="capsule">
33
+ <button id="zoom-in" type="button" aria-label="Zoom in" title="Zoom in"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5.5v13M5.5 12h13"/></svg></button>
34
+ <button id="zoom-out" type="button" aria-label="Zoom out" title="Zoom out"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.5 12h13"/></svg></button>
35
+ </div>
36
+ </nav>
37
+ <!-- One glass panel beside the controls, like the Map Modes popover in Apple Maps. It shows the twin's modes, what
38
+ shapes it, or the playground. The window's engine steps aside while it is open (app.js watches #world). -->
39
+ <!-- the time bar hidden: a small button to bring it back, and one to jump to today -->
40
+ <div id="time-shown" class="time-shown" hidden><button id="time-unhide" type="button">Show the time bar</button><button id="time-today" type="button">Today</button></div>
41
+ <button id="full-exit" class="full-exit" type="button">Exit full screen <kbd>esc</kbd></button>
42
+ <section id="world" class="world" role="dialog" aria-labelledby="modes-title" data-view="modes" hidden>
43
+ <div class="view" data-for="modes">
44
+ <header><h2 id="modes-title">Twin Modes</h2>
45
+ <button class="close" type="button" aria-label="Close" data-close><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m6 6 8 8M14 6l-8 8"/></svg></button></header>
46
+ <div class="modes" id="modes" role="radiogroup" aria-labelledby="modes-title">
47
+ <button class="mode" type="button" role="radio" data-mode="twin" aria-checked="true"><canvas></canvas><span>Twin</span></button>
48
+ <button class="mode" type="button" role="radio" data-mode="time" aria-checked="false" hidden><canvas></canvas><span>Timeline</span></button>
49
+ <button class="mode" type="button" role="radio" data-mode="play" aria-checked="false"><canvas></canvas><span>Playground</span></button>
50
+ <button class="mode" type="button" role="radio" data-mode="others" aria-checked="false"><canvas></canvas><span>People</span></button>
51
+ <button class="mode" type="button" role="radio" data-mode="insights" aria-checked="false"><canvas></canvas><span>Analytics</span></button>
52
+ </div>
53
+ <button class="row" type="button" data-view="facts"><span>What shapes your twin</span><small id="facts-count"></small>
54
+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="m8 5 5 5-5 5"/></svg></button>
55
+ <p class="world-foot" id="modes-foot"></p>
56
+ </div>
57
+ <div class="view" data-for="facts" hidden>
58
+ <header><button class="back" type="button" data-view="modes" aria-label="Back to modes"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m12 5-5 5 5 5"/></svg></button>
59
+ <h2 id="world-title">What shapes your world</h2>
60
+ <button class="close" type="button" aria-label="Close" data-close><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m6 6 8 8M14 6l-8 8"/></svg></button></header>
61
+ <p class="world-sub" id="world-sub"></p>
62
+ <div id="world-facts"></div>
63
+ <p class="world-note" id="world-note">The twin is a picture of a saved snapshot, drawn from these numbers. No star is a single record or a person.</p>
64
+ </div>
65
+ <div class="view" data-for="play" hidden>
66
+ <!-- one bar that stays at the top while the settings scroll (founder, 2026-10-05: "hard to navigate", TW-38) -->
67
+ <div class="play-bar">
68
+ <header><button class="back" type="button" data-view="modes" aria-label="Back to modes"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m12 5-5 5 5 5"/></svg></button>
69
+ <h2 id="play-title">Playground</h2><button class="done" id="play-done" type="button">Done</button></header>
70
+ <div class="play-tools">
71
+ <button type="button" class="tool" id="play-reset" title="Put every setting back">Reset all</button>
72
+ <button type="button" class="tool" id="play-shuffle">Surprise me</button>
73
+ <span class="spacer"></span>
74
+ <button type="button" class="tool play-only" id="play-clip" title="Records the twin month by month, from its first month to today, names hidden, and saves it as a video">Record by month</button><button type="button" class="tool play-only" id="play-clip-year" title="Records the twin year by year, from its first month to today, names hidden, and saves it as a video">By year</button><button type="button" class="tool" id="play-save">Save</button><button type="button" class="tool" id="play-flip" disabled>Flip</button>
75
+ </div>
76
+ <div class="saved" id="play-saved" role="radiogroup" aria-label="Saved settings" hidden></div>
77
+ </div>
78
+ <p class="world-sub" id="play-sub">Move a setting and the twin follows. Shape, colour and light show on Today; earlier months keep their own. The mark under a slider is your own value; ↺ puts one back.</p>
79
+ <!-- the timeline's two choices, moved here from the time bar (founder, 2026-10-07) -->
80
+ <div class="play-time play-only">
81
+ <div class="ctl choice-row"><label>Below the dots</label><button id="time-marks" class="pill" type="button">App logos</button></div>
82
+ <div class="ctl choice-row"><label>New things appear</label><button id="time-spawn" class="pill" type="button">A · from edge</button></div>
83
+ </div>
84
+ <div id="play-groups"></div>
85
+ <details class="group" id="play-start" hidden><summary>Start from someone else<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m6 8 4 4 4-4"/></svg></summary>
86
+ <p class="group-note">The sliders take that person’s values instead of yours.</p>
87
+ <div class="presets" id="play-presets" role="radiogroup" aria-label="Start from"></div>
88
+ </details>
89
+ <div class="play-actions"><button type="button" class="tool" id="play-copy">Copy settings</button></div>
90
+ <p class="world-foot" id="play-foot">Only you see these. Done puts your twin back; the playground remembers where you left it.</p>
91
+ </div>
92
+ </section>
93
+ <!-- Your twin over time (one step per month), and other people's twins: the same rules drawn from other numbers. -->
94
+ <!-- beside the timeline, on the left: the day, how the twin has grown, and what is coming in now (founder, 2026-10-07) -->
95
+ <aside id="time-side" class="time-side" aria-label="Where the timeline is" hidden>
96
+ <p class="side-date" id="time-date"></p><p class="side-line" id="time-line"></p>
97
+ <canvas id="time-growth" aria-hidden="true"></canvas>
98
+ <p class="growth-total"><b id="time-total"></b> things and people</p>
99
+ <div id="feed" class="feed" aria-label="What is coming in now" aria-live="off" hidden></div>
100
+ </aside>
101
+ <div class="topic-explore" id="topic-explore" hidden></div>
102
+ <section id="time" class="strip" aria-label="Your twin over time" hidden>
103
+ <div class="strip-head">
104
+ <button id="time-play" class="play" type="button" aria-label="Play"><svg viewBox="0 0 16 16" aria-hidden="true"><path class="tri" d="M5 3.2v9.6L12.8 8z"/><path class="bars" d="M5 3.5h2v9H5zM9 3.5h2v9H9z"/></svg></button>
105
+ <button id="time-speed" class="speed" type="button" aria-label="Speed 1×, click for faster">1×</button>
106
+ <button id="time-hide" class="close" type="button" aria-label="Hide the time bar" title="Hide the time bar"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m6 8 4 4 4-4"/></svg></button>
107
+ </div>
108
+ <div class="track" id="time-track" tabindex="0" role="slider" aria-label="When" aria-valuemin="0"><canvas id="time-bars"></canvas></div>
109
+ <div class="years" id="time-years"></div>
110
+ </section>
111
+ <section id="others" class="strip" aria-labelledby="others-title" hidden>
112
+ <div class="strip-head">
113
+ <div class="strip-text"><p class="strip-title" id="others-title">Other people’s twins</p><p class="strip-line" id="others-line">Made-up people, drawn by the same rules as yours.</p></div>
114
+ <button id="others-close" class="close" type="button" aria-label="Back to your twin"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="m6 6 8 8M14 6l-8 8"/></svg></button>
115
+ </div>
116
+ <div class="people" id="others-list"></div>
117
+ </section>
118
+ <!-- The real things on the twin's stars (star-graph-nodes.js): their names, and the one you opened. -->
119
+ <canvas id="links" aria-hidden="true"></canvas>
120
+ <canvas id="nodes" aria-hidden="true"></canvas>
121
+ <section id="node-card" class="node-card" role="dialog" aria-labelledby="node-title" hidden></section>
122
+ <p id="graph-message" role="status" hidden></p>
123
+ <!-- The renderer binds these; the page shows its own controls instead. -->
124
+ <div id="dock-wrap" class="dock-wrap" hidden>
125
+ <div id="speed-popover" class="speed-popover glass" hidden>
126
+ <input id="speed" type="range" min="0.15" max="2.5" step="0.05" value="1"><output id="speed-label" for="speed">1×</output>
127
+ </div>
128
+ <nav id="dock" class="dock glass">
129
+ <button id="dock-grip" class="grip control" type="button"></button>
130
+ <button id="pause" class="control primary" type="button"><svg id="pause-icon" viewBox="0 0 20 20"><path d="M7 5v10M13 5v10"/></svg></button>
131
+ <button id="speed-toggle" class="control" type="button"></button>
132
+ <button id="reset" class="control" type="button"></button>
133
+ <button id="cinema" class="control" type="button"></button>
134
+ </nav>
135
+ </div>
136
+ <button id="restore" class="restore glass" type="button" hidden></button>
137
+ <div id="status" class="sr-only" role="status" aria-live="polite"></div>
138
+ <div id="loader" hidden><span></span></div>
139
+ <script type="module" src="star-graph.js"></script>
140
+ <script src="app-i18n-twin.js"></script><script type="module" src="product.js"></script></body>
141
+ </html>
@@ -1 +1 @@
1
- export{aiScopeSummary,MODS,WORKFLOWS,modOn,getMod,dropMod,dependents}from"./product-model.js";import{syncSummary}from"./sync-model.js";const names={"google-chrome":"Google Chrome","microsoft-edge":"Microsoft Edge","gmail":"Gmail","google-drive":"Google Drive","google-calendar":"Google Calendar","youtube":"YouTube","notion":"Notion","slack":"Slack","outlook":"Outlook"};export function connectionRows(state){return state.coverage.map(row=>{const sync=syncSummary(row.sync),guidance=row.support,progress=row.progress;const running=progress&&progress.stage!=="finished";const failed=progress?.stage==="finished"&&!!progress.errorCode;const attempt=running?`Current attempt: ${progress.stage}`:failed?`Latest attempt failed: ${progress.errorCode}. Open zortex help to review and retry.`:null;return{id:row.source,name:names[row.source]||row.source,group:guidance?.state==="unsupported"?"Unavailable in Help":guidance?.state==="setup-required"||row.registration==="deferred"?"Setup required":row.registered?"Registered source":row.configured?"Product candidate source":row.directory?"Source directory":"Additional local source",items:row.items,detail:`${attempt?`${attempt} \xB7 `:""}${row.registered===null?"connection status unavailable":row.registration==="deferred"?"setup required \xB7 open zortex help":row.verification==="configuration-only"?"configured \xB7 connection unverified":row.readiness?`Actions ready \xB7 ${failed?"latest attempt failed":row.readiness.operation.state==="not-run"?"read not run":row.readiness.operation.returned===void 0?"action succeeded":`read returned ${row.readiness.operation.returned}`}`:row.readEvidence?failed?"connected \xB7 latest attempt failed":`connected \xB7 read returned ${row.readEvidence.returned}`:row.connectionState} \xB7 ${row.items.toLocaleString()} stored records \xB7 ${row.dataState.replaceAll("_"," ")}${guidance?` \xB7 ${guidance.message}`:""}${sync?` \xB7 ${sync}`:""}`,status:row.connectionState,reason:attempt??guidance?.message??row.connectionState,bucket:running?"connecting":failed?"attention":row.connectionState==="connected"?"connected":"attention"}})}
1
+ import{syncSummary}from"./sync-model.js";import{connectionView}from"./app-model.js";const names={"google-chrome":"Google Chrome","microsoft-edge":"Microsoft Edge","gmail":"Gmail","google-drive":"Google Drive","google-calendar":"Google Calendar","youtube":"YouTube","notion":"Notion","slack":"Slack","outlook":"Outlook"};export function connectionRows(state,apps=[]){const catalog=new Map(apps.filter(app=>typeof app.id==="string"&&app.id).map(app=>[app.id,app]));const coverage=new Map((state.coverage||[]).map(row=>[row.source,row]));const reports=new Map([...state.connectionReport?.sources||[],...state.connectionReport?.others||[]].map(row=>[row.source,row]));return[...new Set([...coverage.keys(),...catalog.keys(),...reports.keys()])].map(source=>{const row=coverage.get(source)||{source,directory:catalog.has(source),registered:false,configured:false,connectionState:"unverified",items:null,dataState:"unverified"};const app=catalog.get(source);const sync=syncSummary(row.sync),guidance=row.support,progress=row.progress,report=reports.get(row.source),view=report?connectionView(row,report):null;const running=progress&&progress.stage!=="finished";const failed=progress?.stage==="finished"&&!!progress.errorCode;const attempt=running?`Current attempt: ${progress.stage}`:failed?`Latest attempt failed: ${progress.errorCode}. Open this app to review and retry.`:null;const label=app?.name&&app.name!==source?app.name:report?.label||names[source]||source;const stored=Number.isSafeInteger(row.items)?`${row.items.toLocaleString()} stored records`:"Stored records unverified";return{id:row.source,name:label,group:guidance?.state==="unsupported"?"Unavailable here":guidance?.state==="setup-required"||row.registration==="deferred"?"Setup required":row.registered?"Registered source":row.configured?"Product candidate source":row.directory?"Source directory":"Additional local source",items:row.items,detail:view?`${view.status} \xB7 ${view.description}${sync?` \xB7 ${sync}`:""}`:`${attempt?`${attempt} \xB7 `:""}${row.registered===null?"connection status unavailable":row.registration==="deferred"?"setup required in this app":row.verification==="configuration-only"?"configured \xB7 connection unverified":row.readiness?`Actions ready \xB7 ${failed?"latest attempt failed":row.readiness.operation.state==="not-run"?"read not run":row.readiness.operation.returned===void 0?"action succeeded":`read returned ${row.readiness.operation.returned}`}`:row.readEvidence?failed?"connected \xB7 latest attempt failed":`connected \xB7 read returned ${row.readEvidence.returned}`:row.connectionState} \xB7 ${stored} \xB7 ${row.dataState.replaceAll("_"," ")}${guidance?` \xB7 ${guidance.message}`:""}${sync?` \xB7 ${sync}`:""}`,status:report&&["connected","not-connected","unavailable"].includes(report.connection)?report.connection:row.connectionState,reason:attempt??guidance?.message??row.connectionState,bucket:view?view.kind==="working"?"connecting":view.attention?"attention":view.connected?"connected":"attention":running?"connecting":failed?"attention":row.connectionState==="connected"?"connected":"attention"}})}
@@ -1 +1 @@
1
- let current={coverage:[]};const observers=new Set;export function setSnapshot(snapshot){current=snapshot||{coverage:[]};for(const notify of observers)notify()}export function loadState(){return{coverage:current.coverage||[],ais:[],cloud:{mode:null},mods:{},appSettings:{actions:"never"},appPrefs:{}}}export function observeState(notify){observers.add(notify);return()=>observers.delete(notify)}
1
+ let current={coverage:[]};const observers=new Set;export function setSnapshot(snapshot){current=snapshot||{coverage:[]};for(const notify of observers)notify()}export function loadState(){return{coverage:current.coverage||[],connectionReport:current.connectionReport,ais:[],cloud:{mode:null},mods:{},appSettings:{actions:"never"},appPrefs:{}}}export function observeState(notify){observers.add(notify);return()=>observers.delete(notify)}
@@ -1,8 +1,8 @@
1
- import{loadState as loadDemo,observeState as observeDemo}from"./live-state.js";import{connectionRows,aiScopeSummary,MODS,WORKFLOWS,modOn,getMod,dropMod,dependents}from"./live-model.js";import{esc}from"./setup-model.js";import{modIcon}from"./mod-icons.js";import{READS,ACTIONS,ACTION_SUMMARY,GROUP_ACTIONS,appSkills,appFlows,prefsFor,setPrefs,actionFor,readOn,skillOn,flowOn}from"./apps-model.js";const chev='<svg class="chev" viewBox="0 0 20 20" aria-hidden="true"><path d="m8 5 5 5-5 5"/></svg>';const plus='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5.5v13M5.5 12h13"/></svg>';const cap=s=>String(s||"").replace(/^./,c=>c.toUpperCase());const and=names=>names.length<2?names.join(""):names.slice(0,-1).join(", ")+" and "+names.at(-1);const compact=n=>new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(n);export async function mountPanels({open,openStore,sourceDetails}){const $=id=>document.getElementById(id),el=$("panel"),body=$("panel-body"),tools=$("panel-tools");const fetchApps=()=>fetch("abilities.json",{cache:"no-store"}).then(r=>{if(!r.ok)throw new Error(`apps: HTTP ${r.status}`);return r.json()});const first=await fetchApps(),{iconSources,iconAliases={},localIconPaths={}}=first;let apps=first.apps;let reading=null;const refreshApps=()=>reading??=fetchApps().then(next=>{if(Array.isArray(next?.apps))apps=next.apps}).catch(()=>{}).finally(()=>{reading=null});let demo=loadDemo(),rows=connectionRows(demo,apps),at=null,drawn=null,linking=null;const ui={q:"",pending:new Set,ask:null,mode:"cloud",waiting:null,done:null};const timers=new Set,scrolls=new Map;const say=text=>{$("panel-status").textContent=text};const ico=id=>{if(localIconPaths[id])return`<span class="app-ico s"><img src="${esc(localIconPaths[id])}" alt=""></span>`;const icon=iconAliases[id]||id,source=iconSources[icon];if(!source)return'<span class="app-ico"><span aria-hidden="true">'+esc(String(id).slice(0,1).toUpperCase())+"</span></span>";const src=`icons/${encodeURIComponent(icon)}.${source==="s"?"svg":"png"}`;return`<span class="app-ico ${source}">${source==="f"?`<span><img src="${src}" alt=""></span>`:`<img src="${src}" alt="">`}</span>`};const aiIco=ai=>ai.icon==="zortex"?'<span class="app-ico z"><span><img src="zortex-mark.png" alt=""></span></span>':ico(ai.icon);const card=(to,icon,name,line,wrap=false)=>`<button class="p-card${wrap?" wrap":""}" type="button" data-to="${esc(to)}">${icon}<span class="p-words"><b>${esc(name)}</b><small>${esc(line)}</small></span></button>`;const link=(to,name,value="",disabled=false)=>`<button class="p-row" type="button" data-to="${esc(to)}" ${disabled?"disabled":""}><span class="grow">${esc(name)}</span><span class="value">${esc(value)}</span>${chev}</button>`;const sw=(id,attrs,on,label,disabled=false)=>`<input class="switch" type="checkbox" role="switch" id="${esc(id)}" ${attrs} aria-label="${esc(label)}" ${on?"checked":""} ${disabled?"disabled":""}>`;const pick=(id,attrs,value,options,label,disabled=false)=>`<select class="pick" id="${esc(id)}" ${attrs} aria-label="${esc(label)}" ${disabled?"disabled":""}>${Object.entries(options).map(([v,l])=>`<option value="${v}" ${v===value?"selected":""}>${esc(l)}</option>`).join("")}</select>`;const search=(id,label)=>`<label class="p-search"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4"/></svg><input id="${id}" type="search" placeholder="Search" aria-label="${esc(label)}" autocomplete="off" spellcheck="false" value="${esc(ui.q)}"></label>`;const fact=(key,value)=>`<div class="p-row tall"><span class="key">${esc(key)}</span><span class="grow">${esc(value)}</span></div>`;const hero=(icon,lines2)=>`<div class="p-hero">${icon}<p>${lines2}</p></div>`;const lines=(title,items)=>items.length?`<p class="p-label">${esc(title)}</p><div class="p-group">${items.map(t=>`<div class="p-row">${esc(t)}</div>`).join("")}</div>`:"";const confirm=(key,title,text,attr)=>ui.ask!==key?"":`<div class="p-callout" role="alert"><b>${esc(title)}</b> ${esc(text)}<div class="p-actions"><button class="p-pill" type="button" ${attr}>Turn Off</button><button class="text-button" type="button" data-cancel>Cancel</button></div></div>`;const findAI=id=>demo.ais.find(a=>a.id===id);const live=ai=>ai.connected&&(ai.where!=="cloud"||!!demo.cloud.mode);const reads=(ai,id)=>ai.apps==="selected"||(ai.apps||[]).includes(id);const linked=()=>rows.filter(a=>a.bucket==="connected");function aisView(){return{title:"Connected AIs",html:'<p class="p-lead">Use Zortex through your connected AI.</p><p class="p-note">Host grants and cloud AI authorizations are not exposed by the current product status API. Their connection state is unverified. No demo authorization is offered.</p>'}}const findApp=id=>rows.find(a=>a.id===id);const appState=a=>ui.pending.has(a.id)||a.bucket==="connecting"?"connecting":a.bucket==="connected"?"on":a.bucket==="attention"?"attention":"off";const appLine=a=>a.detail||"Connection unverified";const paused=()=>MODS.length>0&&!modOn(demo,"apps");const readers=()=>demo.ais.filter(ai=>ai.connected&&ai.context);function appsView([a,b]){if(a)return a==="all"?{title:"All Apps",back:"apps",html:'<p class="p-note">Permissions are managed by your connected AI. This view reports actual connection and read evidence; it does not change grants.</p>'}:{title:findApp(a)?.name||a,back:"apps",html:"<div data-source-receipt></div>"};const off=paused(),s=demo.appSettings;if(!a){const sorted=[...rows].sort((x,y)=>x.name.localeCompare(y.name)),on2=rows.filter(x=>appState(x)==="on").length;return{title:"Apps",html:`${search("panel-q","Search your apps")}
1
+ import{loadState as loadDemo,observeState as observeDemo}from"./live-state.js";import{connectionRows}from"./live-model.js";import{aiScopeSummary,MODS,WORKFLOWS,modOn,getMod,dropMod,dependents}from"./product-model.js";import{esc}from"./setup-model.js";import{modIcon}from"./mod-icons.js";import{READS,ACTIONS,ACTION_SUMMARY,GROUP_ACTIONS,appSkills,appFlows,prefsFor,setPrefs,actionFor,readOn,skillOn,flowOn}from"./apps-model.js";const chev='<svg class="chev" viewBox="0 0 20 20" aria-hidden="true"><path d="m8 5 5 5-5 5"/></svg>';const plus='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5.5v13M5.5 12h13"/></svg>';const cap=s=>String(s||"").replace(/^./,c=>c.toUpperCase());const and=names=>names.length<2?names.join(""):names.slice(0,-1).join(", ")+" and "+names.at(-1);const compact=n=>new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(n);export async function mountPanels({open,openStore,sourceDetails,sourceAction,connectSource}){const $=id=>document.getElementById(id),el=$("panel"),body=$("panel-body"),tools=$("panel-tools");const fetchApps=()=>fetch("abilities.json",{cache:"no-store"}).then(r=>{if(!r.ok)throw new Error(`apps: HTTP ${r.status}`);return r.json()});const first=await fetchApps(),{iconSources,iconAliases={},localIconPaths={}}=first;let apps=first.apps;let reading=null;const refreshApps=()=>reading??=fetchApps().then(next=>{if(Array.isArray(next?.apps))apps=next.apps}).catch(()=>{}).finally(()=>{reading=null});let demo=loadDemo(),rows=connectionRows(demo,apps),at=null,drawn=null,linking=null;const ui={q:"",pending:new Set,ask:null,mode:"cloud",waiting:null,done:null};const timers=new Set,scrolls=new Map;const say=text=>{$("panel-status").textContent=text};const ico=id=>{if(localIconPaths[id])return`<span class="app-ico s"><img src="${esc(localIconPaths[id])}" alt=""></span>`;const icon=iconAliases[id]||id,source=iconSources[icon];if(!source)return'<span class="app-ico"><span aria-hidden="true">'+esc(String(id).slice(0,1).toUpperCase())+"</span></span>";const src=`icons/${encodeURIComponent(icon)}.${source==="s"?"svg":"png"}`;return`<span class="app-ico ${source}">${source==="f"?`<span><img src="${src}" alt=""></span>`:`<img src="${src}" alt="">`}</span>`};const aiIco=ai=>ai.icon==="zortex"?'<span class="app-ico z"><span><img src="zortex-mark.png" alt=""></span></span>':ico(ai.icon);const card=(to,icon,name,line,wrap=false)=>`<button class="p-card${wrap?" wrap":""}" type="button" data-to="${esc(to)}">${icon}<span class="p-words"><b>${esc(name)}</b><small>${esc(line)}</small></span></button>`;const link=(to,name,value="",disabled=false)=>`<button class="p-row" type="button" data-to="${esc(to)}" ${disabled?"disabled":""}><span class="grow">${esc(name)}</span><span class="value">${esc(value)}</span>${chev}</button>`;const sw=(id,attrs,on,label,disabled=false)=>`<input class="switch" type="checkbox" role="switch" id="${esc(id)}" ${attrs} aria-label="${esc(label)}" ${on?"checked":""} ${disabled?"disabled":""}>`;const pick=(id,attrs,value,options,label,disabled=false)=>`<select class="pick" id="${esc(id)}" ${attrs} aria-label="${esc(label)}" ${disabled?"disabled":""}>${Object.entries(options).map(([v,l])=>`<option value="${v}" ${v===value?"selected":""}>${esc(l)}</option>`).join("")}</select>`;const search=(id,label)=>`<label class="p-search"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4"/></svg><input id="${id}" type="search" placeholder="Search" aria-label="${esc(label)}" autocomplete="off" spellcheck="false" value="${esc(ui.q)}"></label>`;const fact=(key,value)=>`<div class="p-row tall"><span class="key">${esc(key)}</span><span class="grow">${esc(value)}</span></div>`;const hero=(icon,lines2)=>`<div class="p-hero">${icon}<p>${lines2}</p></div>`;const lines=(title,items)=>items.length?`<p class="p-label">${esc(title)}</p><div class="p-group">${items.map(t=>`<div class="p-row">${esc(t)}</div>`).join("")}</div>`:"";const confirm=(key,title,text,attr)=>ui.ask!==key?"":`<div class="p-callout" role="alert"><b>${esc(title)}</b> ${esc(text)}<div class="p-actions"><button class="p-pill" type="button" ${attr}>Turn Off</button><button class="text-button" type="button" data-cancel>Cancel</button></div></div>`;const findAI=id=>demo.ais.find(a=>a.id===id);const live=ai=>ai.connected&&(ai.where!=="cloud"||!!demo.cloud.mode);const reads=(ai,id)=>ai.apps==="selected"||(ai.apps||[]).includes(id);const linked=()=>rows.filter(a=>a.bucket==="connected");function aisView(){return{title:"Connected AIs",html:'<p class="p-lead">Use Zortex through your connected AI.</p><p class="p-note">Connected AI status is not available yet.</p>'}}const findApp=id=>rows.find(a=>a.id===id);const appState=a=>ui.pending.has(a.id)||a.bucket==="connecting"?"connecting":a.bucket==="connected"?"on":a.bucket==="attention"?"attention":"off";const appLine=a=>a.detail||"Connection unverified";const paused=()=>MODS.length>0&&!modOn(demo,"apps");const readers=()=>demo.ais.filter(ai=>ai.connected&&ai.context);function appsView([a,b]){if(a)return a==="all"?{title:"All Apps",back:"apps",html:'<p class="p-note">Permissions are managed by your connected AI. This view reports actual connection and read evidence; it does not change grants.</p>'}:{title:findApp(a)?.name||a,back:"apps",html:"<div data-source-receipt></div>"};const off=paused(),s=demo.appSettings;if(!a){const sorted=[...rows].sort((x,y)=>x.name.localeCompare(y.name)),on2=rows.filter(x=>appState(x)==="on").length;return{title:"Apps",html:`${search("panel-q","Search your apps")}
2
2
  ${off?'<div class="p-callout"><b>Apps is off.</b> Your AI can\u2019t read any of your apps until you turn it back on.<div class="p-actions"><button class="p-pill" type="button" data-mod-get="apps">Turn On</button></div></div>':""}
3
3
 
4
4
  <p class="p-label">${on2} of ${rows.length} on</p>
5
- <div data-filter>${sorted.map(x=>{const st2=appState(x);return`<div class="p-app ${st2}" data-name="${esc([x.name,x.group,x.detail].join(" ").toLowerCase())}"><button type="button" data-to="apps/${esc(x.id)}">${ico(x.id)}<span class="p-words"><b>${esc(x.name)}</b><small>${esc(appLine(x,st2))}</small></span></button>${sw(`app-${x.id}`,`data-app-allow="${esc(x.id)}"`,st2==="on"||st2==="connecting",`Allow ${x.name}`,true)}</div>`}).join("")}</div>
5
+ <div data-filter>${sorted.map(x=>{const st2=appState(x);return`<div class="p-app ${st2}" data-name="${esc([x.name,x.group,x.detail].join(" ").toLowerCase())}"><button type="button" data-to="apps/${esc(x.id)}">${ico(x.id)}<span class="p-words"><b>${esc(x.name)}</b><small>${esc(appLine(x,st2))}</small></span></button><button type="button" class="p-pill" data-source-connect="${esc(x.id)}" aria-label="${esc((sourceAction?.(x.id)?.actionLabel||"Open app")+" \xB7 "+x.name)}">${esc(sourceAction?.(x.id)?.actionLabel||"Open app")}</button></div>`}).join("")}</div>
6
6
  <p class="p-none" data-none hidden>No matching apps.</p>`}}if(a==="all"){const n=readers().length;return{title:"All Apps",back:"apps",html:`<p class="p-lead">These apply to every app, unless you change one on its own page.</p>
7
7
  <div class="p-group"><label class="p-row"><span class="grow">Actions<small>What your AI may do in your apps, like sending, paying or deleting.</small></span>${pick("g-actions",'data-global="actions"',s.actions,ACTIONS,"Actions for all apps")}</label></div>
8
8
  <p class="p-label">Read your apps</p>
@@ -32,4 +32,4 @@ import{loadState as loadDemo,observeState as observeDemo}from"./live-state.js";i
32
32
  ${lines("Can read",m.reads)}${lines("Can do",m.does)}
33
33
  ${needs.length?`<p class="p-label">Needs</p><div class="p-group">${needs.join("")}</div>`:""}
34
34
  ${m.access.length?`<p class="p-label">Permissions</p><div class="p-group">${m.access.map(x=>`<div class="p-row"><span class="grow">${esc(x.name)}${x.why?`<small>${esc(x.why)}</small>`:""}</span></div>`).join("")}</div>`:""}
35
- <div class="p-actions"><button class="text-button" type="button" data-store="mod/${esc(m.id)}">See it in the Mods store</button></div>`}}function filter(){const q=ui.q.trim().toLowerCase(),list=body.querySelector("[data-filter]");if(!list)return;let shown=0;for(const row of list.children){const hit=!q||row.dataset.name.includes(q);row.hidden=!hit;shown+=hit}list.hidden=!shown;const none=body.querySelector("[data-none]");if(none)none.hidden=shown>0}function draw(){if(!at)return;demo=loadDemo();rows=connectionRows(demo,apps);const key=[at.panel,...at.sub].join("/"),v={ais:aisView,apps:appsView,mods:modsView}[at.panel](at.sub);if(v.to!=null){open(v.to,true);return}const same=key===drawn,top=body.scrollTop,focus=same&&body.contains(document.activeElement)?document.activeElement:null;const caret=focus?.type==="search"?focus.selectionStart:null;if(!same&&drawn)scrolls.set(drawn,top);$("panel-title").textContent=v.title;$("panel-back").hidden=!v.back;$("panel-back").dataset.to=v.back||"";body.innerHTML=v.html;tools.innerHTML=v.tools||"";tools.hidden=!v.tools;if(at.panel==="apps"&&at.sub[0]&&at.sub[0]!=="all")sourceDetails(body.querySelector("[data-source-receipt]"),at.sub[0]);for(const input of body.querySelectorAll('input:not([type="search"]), select'))input.disabled=true;for(const button of body.querySelectorAll("button:not([data-to]):not([data-store]):not([data-live-action])"))button.disabled=true;filter();body.scrollTop=same?top:drawn?.startsWith(key+"/")?scrolls.get(key)||0:0;if(focus?.id){const next=document.getElementById(focus.id);next?.focus({preventScroll:true});if(caret!=null)next?.setSelectionRange(caret,caret)}else if(!same)$("panel-title").focus({preventScroll:true});drawn=key;const going=rows.some(a=>a.bucket==="connecting");if(going&&!linking){let tick=0;linking=setInterval(()=>{if(++tick%3===0)void refreshApps().then(()=>{if(at)draw()});else draw()},1e3)}else if(!going&&linking){clearInterval(linking);linking=null}}const refreshVisibleApps=()=>{if(at&&!linking&&document.visibilityState==="visible")void refreshApps().then(()=>{if(at&&!linking)draw()})};const statusTimer=setInterval(refreshVisibleApps,3e3);document.addEventListener("visibilitychange",refreshVisibleApps);el.addEventListener("click",e=>{const b=e.target.closest("button");if(!b||b.disabled)return;const d=b.dataset;if(b.id==="panel-back"||d.to!=null){ui.ask=null;ui.q="";open(d.to);return}if(b.id==="panel-close"){open("");return}if("store"in d)openStore(d.store)});el.addEventListener("input",e=>{if(e.target.id==="panel-q"){ui.q=e.target.value;filter()}});observeDemo(draw);addEventListener("pagehide",()=>{clearInterval(linking);clearInterval(statusTimer);document.removeEventListener("visibilitychange",refreshVisibleApps);timers.forEach(clearTimeout)});return{show(panel,sub=[]){const fresh=!at||at.panel!==panel;if(fresh){ui.q="";ui.ask=null;scrolls.clear()}at={panel,sub};el.hidden=false;draw();refreshVisibleApps()},hide(){if(!at)return;at=null;drawn=null;el.hidden=true;ui.ask=null;ui.done=null;clearInterval(linking);linking=null},get back(){return at?$("panel-back").hidden?"":$("panel-back").dataset.to:null},refresh:draw}}
35
+ <div class="p-actions"><button class="text-button" type="button" data-store="mod/${esc(m.id)}">See it in the Mods store</button></div>`}}function filter(){const q=ui.q.trim().toLowerCase(),list=body.querySelector("[data-filter]");if(!list)return;let shown=0;for(const row of list.children){const hit=!q||row.dataset.name.includes(q);row.hidden=!hit;shown+=hit}list.hidden=!shown;const none=body.querySelector("[data-none]");if(none)none.hidden=shown>0}function draw(){if(!at)return;demo=loadDemo();rows=connectionRows(demo,apps);const key=[at.panel,...at.sub].join("/"),v={ais:aisView,apps:appsView,mods:modsView}[at.panel](at.sub);if(v.to!=null){open(v.to,true);return}const same=key===drawn,top=body.scrollTop,focus=same&&body.contains(document.activeElement)?document.activeElement:null;if(same&&focus?.closest("[data-connection-panel]")&&focus.matches("input,textarea,select"))return;const caret=focus?.type==="search"?focus.selectionStart:null;if(!same&&drawn)scrolls.set(drawn,top);$("panel-title").textContent=v.title;$("panel-back").hidden=!v.back;$("panel-back").dataset.to=v.back||"";body.innerHTML=v.html;tools.innerHTML=v.tools||"";tools.hidden=!v.tools;if(at.panel==="apps"&&at.sub[0]&&at.sub[0]!=="all")sourceDetails(body.querySelector("[data-source-receipt]"),at.sub[0]);for(const input of body.querySelectorAll('input:not([type="search"]), select'))if(!input.closest("[data-connection-panel]"))input.disabled=true;for(const button of body.querySelectorAll("button:not([data-to]):not([data-store]):not([data-live-action]):not([data-source-connect])"))if(!button.closest("[data-connection-panel]"))button.disabled=true;filter();body.scrollTop=same?top:drawn?.startsWith(key+"/")?scrolls.get(key)||0:0;if(focus?.id){const next=document.getElementById(focus.id);next?.focus({preventScroll:true});if(caret!=null)next?.setSelectionRange(caret,caret)}else if(!same)$("panel-title").focus({preventScroll:true});drawn=key;const going=rows.some(a=>a.bucket==="connecting");if(going&&!linking){let tick=0;linking=setInterval(()=>{if(++tick%3===0)void refreshApps().then(()=>{if(at)draw()});else draw()},1e3)}else if(!going&&linking){clearInterval(linking);linking=null}}const refreshVisibleApps=()=>{if(at&&!linking&&document.visibilityState==="visible")void refreshApps().then(()=>{if(at&&!linking)draw()})};const statusTimer=setInterval(refreshVisibleApps,3e3);document.addEventListener("visibilitychange",refreshVisibleApps);el.addEventListener("click",e=>{const b=e.target.closest("button");if(!b||b.disabled)return;const d=b.dataset;if(b.id==="panel-back"||d.to!=null){ui.ask=null;ui.q="";open(d.to);return}if(b.id==="panel-close"){open("");return}if(d.sourceConnect){void connectSource?.(d.sourceConnect);return}if("store"in d)openStore(d.store)});el.addEventListener("input",e=>{if(e.target.id==="panel-q"){ui.q=e.target.value;filter()}});observeDemo(draw);addEventListener("pagehide",()=>{clearInterval(linking);clearInterval(statusTimer);document.removeEventListener("visibilitychange",refreshVisibleApps);timers.forEach(clearTimeout)});return{show(panel,sub=[]){const fresh=!at||at.panel!==panel;if(fresh){ui.q="";ui.ask=null;scrolls.clear()}at={panel,sub};el.hidden=false;draw();refreshVisibleApps()},hide(){if(!at)return;at=null;drawn=null;el.hidden=true;ui.ask=null;ui.done=null;clearInterval(linking);linking=null},get back(){return at?$("panel-back").hidden?"":$("panel-back").dataset.to:null},refresh:draw}}
@@ -1 +1 @@
1
- const renderStarted=performance.now();const el=(tag,text,parent)=>{const node=document.createElement(tag);if(text!==void 0)node.textContent=text;parent?.appendChild(node);return node};const panel=el("details",void 0,document.body);panel.className="zx-vault";panel.open=false;if(window.parent!==window)panel.hidden=true;const summary=el("summary","Loading your local Vault\u2026",panel);const number=n=>Number(n).toLocaleString();try{const response=await fetch("snapshot.json");if(!response.ok)throw new Error("Vault unavailable");const data=await response.json();const measured=data.portrait?.state==="measured-subset";summary.textContent=`${data.inventory?.label??"Current Vault"} \xB7 ${number(data.inventory?.storedRecords??data.totalItems)} ${data.inventory?"stored records":"mapped records"}`;el("p",`Map sample: ${number(data.totalItems)} records. Stored counts include revisions and provider cache entries.`,panel);el("p",`${data.productVersion?`Zortex ${data.productVersion} \xB7 `:""}${data.status==="live-local"?"Real local aggregates":data.status==="empty"?"No local records":"Vault unavailable"}`,panel);el("p",measured?"Privacy view: local cached vectors and source-proven authorship determine measured dimensions. Missing contacts and topic taxonomy remain unknown; their geometry is layout only. No new embeddings are requested.":"Privacy view: anonymized record nodes, sources and record timestamps. Semantic portrait, authorship and relationships are unverified; geometry is layout only.",panel);el("p",`Latest mapped record: ${data.latest??"Not available"}`,panel);el("h2",`${data.coverage.length} directory, product candidate, registered or observed sources`,panel);el("p","Connection status and local records are separate evidence. Sources without a registered status remain unverified; no demo data is substituted.",panel);const table=el("table",void 0,panel);table.setAttribute("aria-label","Local source coverage");const head=el("tr",void 0,el("thead",void 0,table));el("th","Source / evidence",head);el("th","Records",head);const body=el("tbody",void 0,table);for(const source of data.coverage){const row=el("tr",void 0,body),name=el("td",source.source,row);el("span",`Connection: ${source.connectionState}`,name).className="zx-state";el("span",`Data: ${source.dataState.replaceAll("_"," ")}`,name).className="zx-state";if(source.readiness)el("span",`Actions ready \xB7 ${source.readiness.operation.state==="not-run"?"read not run":source.readiness.operation.returned===void 0?"action succeeded":`read returned ${source.readiness.operation.returned}`}`,name).className="zx-state";el("td",number(source.items),row);row.title=`First: ${source.first??"unknown"}; latest: ${source.latest??"unknown"}`}const days=[...new Set(data.sourceDays.map(row=>row.day))].sort();if(days.length){const label=el("label","Records by date",panel),range=el("input",void 0,label);range.type="range";range.min="0";range.max=String(days.length-1);range.value=range.max;const result=el("p","",panel);result.setAttribute("aria-live","polite");const show=()=>{const day=days[Number(range.value)],rows=data.sourceDays.filter(row=>row.day===day);range.setAttribute("aria-valuetext",day);result.textContent=`${day}: ${number(rows.reduce((sum,row)=>sum+row.items,0))} records \xB7 ${rows.map(row=>`${row.source} ${number(row.items)}`).join(" \xB7 ")}`};range.addEventListener("input",show);show()}const refresh=el("button","Refresh local counts",panel);refresh.type="button";refresh.addEventListener("click",()=>location.reload());if(data.status==="live-local"){await new Promise((resolve,reject)=>{const started=performance.now();const check=()=>{if(window.galaxy?.ready&&document.getElementById("universe")?.classList.contains("ready"))return resolve();if(performance.now()-started>3e4)return reject(new Error("Renderer unavailable"));setTimeout(check,100)};check()});await fetch("loaded",{method:"POST",headers:{"X-Zortex-Galaxy":document.querySelector('meta[name="zortex-galaxy-token"]').content,"X-Zortex-Render-Ms":String(Math.round(performance.now()-renderStarted))}})}}catch(error){el("p",error.message==="Renderer unavailable"?"Local counts loaded; the original Galaxy renderer did not become ready.":"Local Vault data could not be read. No demo data is shown.",panel).setAttribute("role","status")}
1
+ const renderStarted=performance.now();const el=(tag,text,parent)=>{const node=document.createElement(tag);if(text!==void 0)node.textContent=text;parent?.appendChild(node);return node};const panel=el("details",void 0,document.body);panel.className="zx-vault";panel.open=false;if(window.parent!==window)panel.hidden=true;const summary=el("summary","Loading your local Vault\u2026",panel);const number=n=>Number(n).toLocaleString();try{const response=await fetch("snapshot.json");if(!response.ok)throw new Error("Vault unavailable");const data=await response.json();const sample=data.sampleData===true;const measured=data.portrait?.state==="measured-subset";summary.textContent=`${data.inventory?.label??"Current Vault"} \xB7 ${number(data.inventory?.storedRecords??data.totalItems)} ${data.inventory?"stored records":"mapped records"}`;el("p",`Mapped records: ${number(data.portrait?.mappedThings??data.totalItems)}. Stored counts include revisions and provider cache entries.`,panel);el("p",`${data.productVersion?`Zortex ${data.productVersion} \xB7 `:""}${data.status==="live-local"?"Vault records":data.status==="empty"?"No local records":"Vault unavailable"}`,panel);el("p",measured?"Privacy view: local cached vectors and source-proven authorship determine measured dimensions. Missing contacts and topic taxonomy remain unknown; their geometry is layout only. No new embeddings are requested.":"Privacy view: anonymized record nodes, sources and record timestamps. Semantic portrait, authorship and relationships are unverified; geometry is layout only.",panel);el("p",`Latest mapped record: ${data.latest??"Not available"}`,panel);el("h2",`${data.coverage.length} directory, product candidate, registered or observed sources`,panel);el("p","Connection status and local records are separate evidence. Sources without a registered status remain unverified.",panel);const table=el("table",void 0,panel);table.setAttribute("aria-label","Local source coverage");const head=el("tr",void 0,el("thead",void 0,table));el("th","Source / evidence",head);el("th","Records",head);const body=el("tbody",void 0,table);for(const source of data.coverage){const row=el("tr",void 0,body),name=el("td",source.source,row);el("span",`Connection: ${source.connectionState}`,name).className="zx-state";el("span",`Data: ${source.dataState.replaceAll("_"," ")}`,name).className="zx-state";if(source.readiness)el("span",`Actions ready \xB7 ${source.readiness.operation.state==="not-run"?"read not run":source.readiness.operation.returned===void 0?"action succeeded":`read returned ${source.readiness.operation.returned}`}`,name).className="zx-state";el("td",number(source.items),row);row.title=`First: ${source.first??"unknown"}; latest: ${source.latest??"unknown"}`}const days=[...new Set(data.sourceDays.map(row=>row.day))].sort();if(days.length){const label=el("label","Records by date",panel),range=el("input",void 0,label);range.type="range";range.min="0";range.max=String(days.length-1);range.value=range.max;const result=el("p","",panel);result.setAttribute("aria-live","polite");const show=()=>{const day=days[Number(range.value)],rows=data.sourceDays.filter(row=>row.day===day);range.setAttribute("aria-valuetext",day);result.textContent=`${day}: ${number(rows.reduce((sum,row)=>sum+row.items,0))} records \xB7 ${rows.map(row=>`${row.source} ${number(row.items)}`).join(" \xB7 ")}`};range.addEventListener("input",show);show()}const refresh=el("button","Refresh local counts",panel);refresh.type="button";refresh.addEventListener("click",()=>location.reload());if(data.status==="live-local"&&!sample){await new Promise((resolve,reject)=>{const started=performance.now();const check=()=>{if(window.galaxy?.ready&&document.getElementById("universe")?.classList.contains("ready"))return resolve();if(performance.now()-started>3e4)return reject(new Error("Renderer unavailable"));setTimeout(check,100)};check()});await fetch("loaded",{method:"POST",headers:{"X-Zortex-Galaxy":document.querySelector('meta[name="zortex-galaxy-token"]')?.content||"","X-Zortex-Render-Ms":String(Math.round(performance.now()-renderStarted))}})}}catch(error){el("p",error.message==="Renderer unavailable"?"Local counts loaded; the original Galaxy renderer did not become ready.":"Vault data could not be read. Please refresh to try again.",panel).setAttribute("role","status")}
@@ -1,6 +1,17 @@
1
1
  /* Product-only states around the unchanged original demo shell. */
2
2
  button:disabled{opacity:.48;cursor:not-allowed}.composer:has(textarea:disabled){opacity:.7}#input:disabled{color:var(--zx-muted);cursor:not-allowed}.p-note{color:var(--zx-muted);font-size:13px;line-height:1.6;margin:14px 4px}.p-search input{width:100%;background:none;border:0;color:inherit;min-width:0;padding:10px;font:inherit}.p-row .key{min-width:90px}.p-row .grow{overflow-wrap:anywhere}.zx-store{background:#f7f7f5;color:#202020;z-index:6}.zx-store .p-note{color:#666}.zx-store .p-card{background:white;border-color:#ddd;color:#222}.zx-store .p-pill{color:#222;border:1px solid #aaa}#account-menu,#setup{display:none!important}
3
- @media(max-width:600px){html[data-sidebar][data-panel]{--side-x:0px}html[data-panel] #sidebar{visibility:hidden}.panel{max-width:calc(100vw - 24px)}.engine-side{min-width:0}}
3
+ @media(max-width:600px){html[data-sidebar][data-panel]{--side-x:0px}html[data-panel] #sidebar{visibility:hidden}.panel{max-width:calc(100vw - 24px)}.engine-side{min-width:0}}
4
4
  /* Language choice, just above the account row in the sidebar. */
5
5
  #sidebar .zx-language{align-self:flex-start;margin:0 12px 8px;padding:6px 28px 6px 12px;font:inherit;font-size:13px;color:inherit;background:transparent;border:1px solid color-mix(in srgb,currentColor 25%,transparent);border-radius:100px;cursor:pointer}
6
6
  #sidebar .zx-language option{color:#202020;background:#fff}
7
+
8
+ /* Manual recovery lives inside the original Apps list and panel. */
9
+ .p-app > button[data-source-connect]{flex:0 0 auto;min-height:28px;max-width:130px;padding:5px 10px;border-radius:var(--zx-pill);background:var(--zx-fill-hover);font-size:12px;text-align:center;line-height:1.25}
10
+ [data-connection-panel] .p-actions{flex-wrap:wrap}
11
+ [data-connection-panel] :is(input,textarea,select){box-sizing:border-box;min-width:0;width:54%;padding:8px;border:1px solid var(--zx-line);border-radius:8px;background:var(--zx-fill);color:var(--zx-ink);font:inherit}
12
+ [data-connection-panel] textarea{min-height:80px;resize:vertical}
13
+ [data-connection-panel] code{overflow-wrap:anywhere;word-break:break-all}
14
+ [data-connection-panel] img{max-width:100%;height:auto;background:#fff;border-radius:8px}
15
+ [data-connection-panel] a.p-pill{text-decoration:none}
16
+ [data-connection-panel] [data-connection-state="success"], [data-connection-panel] [data-connection-state="empty"]{border:1px solid color-mix(in srgb,#6bbf8a 50%,transparent)}
17
+ h1[tabindex="-1"]:focus{outline:none}
@@ -1 +1 @@
1
- import{mountPanels}from"./panels-live.js";import{setSnapshot}from"./live-state.js";import{createSnapshotRefresh}from"./refresh-model.js";import{syncFacts,syncNotes,engineSyncLine,syncSummary,readinessFacts}from"./sync-model.js";const $=id=>document.getElementById(id),root=document.documentElement;const node=(tag,text,parent,cls)=>{const n=document.createElement(tag);if(text!==void 0)n.textContent=text;if(cls)n.className=cls;parent?.append(n);return n};const number=n=>Number(n||0).toLocaleString();let snapshot=null,loadError="",current="home";const knownNames={"google-chrome":"Google Chrome","microsoft-edge":"Microsoft Edge","gmail":"Gmail","google-drive":"Google Drive","google-calendar":"Google Calendar","youtube":"YouTube","notion":"Notion","slack":"Slack","outlook":"Outlook"};const sourceName=id=>knownNames[id]||id;const seconds=n=>Number.isFinite(n)?`${(n/1e3).toFixed(1)} s`:"Not measured";const go=route=>{location.hash=route==="home"?"":route};root.dataset.shell=/Electron/.test(navigator.userAgent)?"app":"web";function leftInset(){if(matchMedia("(max-width:700px)").matches)return 0;const px=name=>parseFloat(getComputedStyle(root).getPropertyValue(name))||0;return(root.hasAttribute("data-sidebar")?px("--zx-side")+8:0)+(root.hasAttribute("data-panel")?px("--zx-panel")+8:0)}const tellTwin=()=>{$("twin").contentWindow?.postMessage({type:"zortex-twin",visible:current!=="engine"&&current!=="store",inset:leftInset()},location.origin)};function sidebar(on){root.toggleAttribute("data-sidebar",on);$("sidebar").inert=!on;$("sidebar-show").setAttribute("aria-expanded",String(on));requestAnimationFrame(tellTwin)}$("sidebar-show").onclick=()=>sidebar(true);$("sidebar-hide").onclick=()=>sidebar(false);document.querySelectorAll("[data-go]").forEach(b=>b.onclick=()=>go(b.dataset.go));const newChat=document.querySelector("[data-zx-new-chat]");newChat.disabled=true;newChat.title="In-app chat is not available in this version. Use your connected AI.";$("engine-close").onclick=()=>go("home");$("engine-corner").onclick=()=>go("engine");$("account-name").textContent="This computer";$("avatar").textContent="Z";$("account").onclick=()=>go("about");$("account").removeAttribute("aria-haspopup");$("account").removeAttribute("aria-controls");$("setup-again").disabled=true;const input=$("input");input.placeholder="Ask your connected AI about your Vault";$("ghost").textContent="";input.disabled=true;input.setAttribute("aria-label","Chat in your connected AI. In-app chat is not available in this version.");$("composer").title="Use Zortex through your connected AI. In-app chat is not available in this version.";$("composer").onsubmit=e=>{e.preventDefault();go("ais")};const mini=window.EngineGraphics?.createEngineDisplay($("engine-mini"),{vehicle:"booster",interactive:false,motion:"auto"});const big=window.EngineGraphics?.createEngineDisplay($("engine-big"),{vehicle:"booster",interactive:false,motion:"auto"});const dateText=value=>{const d=new Date(value);return value&&!Number.isNaN(+d)?d.toISOString().replace("T"," ").replace(/\.\d{3}Z$/," UTC"):"Not available"};const fact=(name,value,parent)=>{const r=node("div",void 0,parent,"p-row tall");node("span",name,r,"key");node("span",value??"Not available",r,"grow")};const note=(text,parent)=>node("p",text,parent,"p-note");function card(parent,title,detail,action){const b=node("button",void 0,parent,"p-card wrap");b.type="button";const words=node("span",void 0,b,"p-words");node("b",title,words);node("small",detail,words);b.onclick=action;return b}function refreshButton(parent){const b=node("button","Refresh local counts",parent,"p-pill");b.type="button";b.dataset.liveAction="refresh";b.onclick=async()=>{b.disabled=true;await load();render()}}function dataNotice(parent){if(snapshot?.coverageNote?.providerCache==="unavailable")note("Partial count: provider cache could not be read (invalid_argument).",parent);if(snapshot?.coverageNote?.bounded)note(`The map draws a sample of ${number(snapshot.totalItems)} records. The full stored count includes revisions and provider cache entries.`,parent);note("Local records, source availability and tested operations are separate facts. A valid empty operation is successful; missing evidence remains unverified.",parent)}function sourceDetails(parent,row){fact("Source catalog",row.configured?"In the product candidate list":row.directory?"Source directory entry":"Additional registered or observed local source",parent);fact("Registration",row.registered===null?"Status unavailable":row.registration==="deferred"?"Setup required; open zortex help":row.registered?"Registered with the connector hub":"Not verified",parent);const support=row.support;fact("Manual connection",support?{"supported":"Available in Help","setup-required":"Setup required in Help","unsupported":"Unavailable in Help"}[support.state]??"Not verified":"Not verified",parent);if(support){fact("Support reason",support.message,parent);fact("Next step",support.nextStep,parent);fact("Support code",support.reasonCode,parent)}fact("Connection",row.connectionState,parent);fact("Local records",number(row.items),parent);fact("Data evidence",row.dataState.replaceAll("_"," "),parent);if(row.readiness){fact("Actions",`Ready \xB7 ${number(row.readiness.actions)} available`,parent);fact("Read check",row.readiness.operation.state==="not-run"?"Not run":row.readiness.operation.returned===void 0?"Action succeeded \xB7 record read unverified":`Read succeeded \xB7 ${number(row.readiness.operation.returned)} returned`,parent);note("This check belongs to the current connection session. Available Actions do not establish a successful read or stored records.",parent)}if(row.publicRead){fact(row.source==="appstore"?"Public App Store read":"Public data read",row.publicRead.state,parent);if(row.source==="appstore")note("Public catalog access does not establish an Apple account connection or stored records.",parent)}if(row.readEvidence){fact("Live read",`${number(row.readEvidence.returned)} returned`,parent);note("Live read results are separate from records stored in the Vault.",parent)}fact("First record",dateText(row.first),parent);fact("Latest mapped record",dateText(row.latest),parent);if(row.sync){node("h2","Full sync",parent,"p-label");for(const[name,value]of syncFacts(row.sync,snapshot?.sync,Date.now()))fact(name,value,parent);for(const text of syncNotes(snapshot?.sync))note(text,parent)}const p=row.progress,e=p?.evidence;node("h2","Latest connection attempt",parent,"p-label");fact("Stage",p?.stage??"Not observed",parent);fact("Elapsed",seconds(p?.durationMs),parent);fact("Connect",seconds(p?.connectMs),parent);fact("Read",seconds(p?.readMs),parent);fact("Attempt connection",p?.connectionState??"Unverified",parent);for(const[label,value]of readinessFacts(row))fact(label,value,parent);const live=e&&e.origin!=="vault-cache";if(!p?.readiness&&!Number.isSafeInteger(row.readiness?.operation?.returned))fact("First page",live?`Read \xB7 ${Number.isFinite(p.returned)?`${number(p.returned)} returned`:"count not reported"}`:e?.origin==="vault-cache"?"Cached records only \xB7 live read unverified":"Unverified",parent);if(e?.stage==="read-own-posts")fact("Your own posts",live&&e.ownRecords>0?`${number(e.ownRecords)} verified`:"Unverified",parent);if(e){fact("Evidence origin",e.origin,parent);fact("Observed",dateText(e.observedAt),parent)}if(p?.errorCode)fact("Reason",p.errorCode,parent);note("Available Actions can be used before an operation is tested. Stored records and verified own posts require their own evidence.",parent);note("This page reads aggregate counts only. Account details, record titles and message content are not exposed.",parent);refreshButton(parent);note("Run zortex help to open manual connection controls. This page follows the same connection progress automatically.",parent)}function store(){const view=$("view");view.hidden=true;const page=$("chat");page.hidden=false;page.classList.add("zx-store");const content=$("messages");content.replaceChildren();node("h1","Mods",content);note("Your Zortex, with more possibilities.",content);note("The marketplace is not available in this build. No demo catalogue, purchases or installed states are shown.",content);card(content,"Galaxy","Included \xB7 current local Vault",()=>go("home"));const b=node("button","Back to Galaxy",content,"p-pill");b.onclick=()=>go("home")}function engine(){const rows=snapshot?.coverage||[],verified=rows.filter(r=>r.connectionState==="connected");$("engine-sub").textContent=`${verified.length} connected \xB7 ${rows.length} sources \xB7 ${number(snapshot?.inventory?.storedRecords??snapshot?.totalItems)} ${snapshot?.inventory?"stored records":"mapped records"}`;$("engine-sync").textContent=engineSyncLine(rows,Date.now())??"Current local Vault snapshot";$("engine-sync-now").textContent="Refresh counts";$("engine-sync-now").onclick=async()=>{await load();render()};const updates=Array.from({length:33},(_,i)=>({id:"B"+String(i+1).padStart(2,"0"),state:i<verified.length?"on":"off",throttle:i<verified.length?1:0}));mini?.setEngines(updates);big?.setEngines(updates);const list=$("connector-list");list.replaceChildren();for(const row of rows.filter(r=>sourceName(r.source).toLowerCase().includes($("engine-q").value.toLowerCase()))){const li=node("li",void 0,list);const b=node("button",void 0,li);b.className=row.connectionState==="connected"?"on":"off";node("i",void 0,b);node("span",sourceName(row.source),b,"nm");node("span",number(row.items),b,"n");const sync=syncSummary(row.sync);b.title=`${row.connectionState} \xB7 ${row.dataState}${sync?` \xB7 ${sync}`:""}`;b.onclick=()=>go(`apps/${row.source}`)}$("engine-empty").hidden=list.children.length!==0;$("engine-card").hidden=true}$("engine-q").oninput=engine;function render(){current=decodeURIComponent(location.hash.slice(1)||"home");const[page,id]=current.split("/");root.dataset.route=page==="engine"?"engine":page==="store"?"store":"home";root.toggleAttribute("data-panel",!["home","engine","store"].includes(page));for(const el of[$("sidebar"),$("sidebar-show")]){if(page==="store")el.dataset.surface="store";else delete el.dataset.surface}$("panel").hidden=["home","engine","store"].includes(page);$("engine").hidden=page!=="engine";$("chat").hidden=true;$("chat").classList.remove("zx-store");$("view").hidden=true;$("panel-back").hidden=!id;$("panel-body").replaceChildren();$("panel-tools").hidden=true;const titles={ais:"Connected AIs",apps:"Apps",mods:"Mods",about:"This computer"};$("panel-title").textContent=id?sourceName(id):titles[page]||"Zortex";if(!$("panel").hidden)sidebar(true);if(loadError)note(loadError,$("panel-body"));if(["apps","ais","mods"].includes(page))panels.show(page,id?[id]:[]);else if(page==="engine")engine();else if(page==="store")store();else if(page==="about"){fact("Version",snapshot?.productVersion,$("panel-body"));fact("Vault",snapshot?.status,$("panel-body"));fact("Source Vault",snapshot?.inventory?.label??"Current Vault",$("panel-body"));fact("Stored records",snapshot?.inventory?number(snapshot.inventory.storedRecords):"Unavailable",$("panel-body"));fact("Map sample",number(snapshot?.totalItems),$("panel-body"));fact("Latest mapped record",dateText(snapshot?.latest),$("panel-body"));note(snapshot?.portrait?.state==="measured-subset"?"Measured subset from existing local vectors and source-proven authored records. Contacts and topic taxonomy are unavailable; unknown dimensions use layout defaults.":"This view contains source names, counts and times only. Record nodes use source labels and recorded timestamps. Semantic portrait, authorship and relationships are not yet measured; the shape is layout only.",$("panel-body"));refreshButton($("panel-body"))}document.querySelectorAll("[data-go]").forEach(b=>b.setAttribute("aria-current",b.dataset.go===page?"page":"false"));tellTwin()}const panels=await mountPanels({open:go,openStore:()=>go("store"),sourceDetails:(parent,id)=>{const row=snapshot?.coverage?.find(r=>r.source===id);if(row)sourceDetails(parent,row)}});const refreshSnapshot=createSnapshotRefresh({read:async()=>{const r=await fetch("snapshot.json");if(!r.ok)throw Error();return r.json()},publish:value=>{snapshot=value;setSnapshot(snapshot);loadError=""},reload:()=>$("twin").contentWindow?.location.reload()});async function load(){try{await refreshSnapshot()}catch{loadError="Local Vault unavailable. Last displayed data may be stale. No demo data is substituted."}}addEventListener("hashchange",render);addEventListener("resize",tellTwin);$("twin").addEventListener("load",tellTwin);addEventListener("message",e=>{if(e.origin!==location.origin||e.source!==$("twin").contentWindow)return;if(e.data?.type==="zortex-twin-ready")tellTwin();if(e.data?.type==="zortex-twin-mode"&&["twin","time","play","others"].includes(e.data.mode))root.dataset.twinMode=e.data.mode;if(e.data?.type==="zortex-twin-full")root.toggleAttribute("data-twin-full",e.data.on===true)});addEventListener("keydown",e=>{if(e.key==="Escape")go("home");if((e.ctrlKey||e.metaKey)&&e.key==="\\"){e.preventDefault();sidebar(!root.hasAttribute("data-sidebar"))}});sidebar(true);await load();engine();render();let refreshing=false;setInterval(async()=>{if(refreshing||document.hidden)return;refreshing=true;const route=current;try{await load();if(current===route&&!document.activeElement?.matches('input,textarea,[contenteditable="true"]'))render()}finally{refreshing=false}},5e3);
1
+ import{mountPanels}from"./panels-live.js";import{createConnectionPanel}from"./connection-panel.js";import{setSnapshot}from"./live-state.js";import{createSnapshotRefresh}from"./refresh-model.js";import{syncFacts,syncNotes,engineSyncLine,syncSummary,readinessFacts}from"./sync-model.js";const $=id=>document.getElementById(id),root=document.documentElement;const node=(tag,text,parent,cls)=>{const n=document.createElement(tag);if(text!==void 0)n.textContent=text;if(cls)n.className=cls;parent?.append(n);return n};const number=n=>Number(n||0).toLocaleString();const runtime=await fetch("runtime.json",{cache:"no-store"}).then(r=>{if(!r.ok)throw Error();return r.json()}).catch(()=>({mode:"local",canConnect:false}));const accountLabel=runtime.displayName||runtime.accountLabel||"Your account";let snapshot=null,loadError="",current="home";const connections=createConnectionPanel({runtime,token:document.querySelector('meta[name="zortex-galaxy-token"]')?.content,onChange:async()=>{await load();render()}});const sourceRow=id=>snapshot?.coverage?.find(row=>row.source===id)||{source:id,directory:true,registered:false,items:null,dataState:"unverified",connectionState:"unverified"};const knownNames={"google-chrome":"Google Chrome","microsoft-edge":"Microsoft Edge","gmail":"Gmail","google-drive":"Google Drive","google-calendar":"Google Calendar","youtube":"YouTube","notion":"Notion","slack":"Slack","outlook":"Outlook"};const sourceName=id=>knownNames[id]||id;const seconds=n=>Number.isFinite(n)?`${(n/1e3).toFixed(1)} s`:"Not measured";const go=route=>{location.hash=route==="home"?"":route};root.dataset.shell=/Electron/.test(navigator.userAgent)?"app":"web";function leftInset(){if(matchMedia("(max-width:700px)").matches)return 0;const px=name=>parseFloat(getComputedStyle(root).getPropertyValue(name))||0;return(root.hasAttribute("data-sidebar")?px("--zx-side")+8:0)+(root.hasAttribute("data-panel")?px("--zx-panel")+8:0)}const tellTwin=()=>{$("twin").contentWindow?.postMessage({type:"zortex-twin",visible:current!=="engine"&&current!=="store",inset:leftInset()},location.origin)};function sidebar(on){root.toggleAttribute("data-sidebar",on);$("sidebar").inert=!on;$("sidebar-show").setAttribute("aria-expanded",String(on));requestAnimationFrame(tellTwin)}$("sidebar-show").onclick=()=>sidebar(true);$("sidebar-hide").onclick=()=>sidebar(false);document.querySelectorAll("[data-go]").forEach(b=>b.onclick=()=>go(b.dataset.go));const newChat=document.querySelector("[data-zx-new-chat]");newChat.disabled=true;newChat.title="In-app chat is not available in this version. Use your connected AI.";$("engine-close").onclick=()=>go("home");$("engine-corner").onclick=()=>go("engine");$("account-name").textContent=accountLabel;$("account-name").dataset.noTranslate="";$("avatar").textContent=accountLabel.slice(0,1).toUpperCase();$("account").onclick=()=>go("about");$("account").removeAttribute("aria-haspopup");$("account").removeAttribute("aria-controls");$("setup-again").disabled=true;const input=$("input");input.placeholder="Ask your connected AI about your Vault";$("ghost").textContent="";input.disabled=true;input.setAttribute("aria-label","Chat in your connected AI. In-app chat is not available in this version.");$("composer").title="Use Zortex through your connected AI. In-app chat is not available in this version.";$("composer").onsubmit=e=>{e.preventDefault();go("ais")};const mini=window.EngineGraphics?.createEngineDisplay($("engine-mini"),{vehicle:"booster",interactive:false,motion:"auto"});const big=window.EngineGraphics?.createEngineDisplay($("engine-big"),{vehicle:"booster",interactive:false,motion:"auto"});const dateText=value=>{const d=new Date(value);return value&&!Number.isNaN(+d)?d.toISOString().replace("T"," ").replace(/\.\d{3}Z$/," UTC"):"Not available"};const fact=(name,value,parent)=>{const r=node("div",void 0,parent,"p-row tall");node("span",name,r,"key");node("span",value??"Not available",r,"grow")};const note=(text,parent)=>node("p",text,parent,"p-note");function card(parent,title,detail,action){const b=node("button",void 0,parent,"p-card wrap");b.type="button";const words=node("span",void 0,b,"p-words");node("b",title,words);node("small",detail,words);b.onclick=action;return b}function refreshButton(parent){const b=node("button","Refresh local counts",parent,"p-pill");b.type="button";b.dataset.liveAction="refresh";b.onclick=async()=>{b.disabled=true;await load();render()}}function dataNotice(parent){if(snapshot?.coverageNote?.providerCache==="unavailable")note("Partial count: provider cache could not be read (invalid_argument).",parent);if(snapshot?.coverageNote?.bounded)note(`The map displays ${number(snapshot.totalItems)} records. The full stored count includes revisions and provider cache entries.`,parent);note("Local records, source availability and tested operations are separate facts. A valid empty operation is successful; missing evidence remains unverified.",parent)}function sourceDetails(parent,row){const controls=node("div",void 0,parent);connections.mount(controls,row.source,row);const details=node("details",void 0,parent);node("summary","Connection details",details,"p-note");parent=details;fact("Source catalog",row.configured?"In the product candidate list":row.directory?"Source directory entry":"Additional registered or observed local source",parent);fact("Registration",row.registered===null?"Status unavailable":row.registration==="deferred"?"Setup required in this app":row.registered?"Registered with the connector hub":"Not verified",parent);const support=row.support;fact("Manual connection",support?{"supported":"Available here","setup-required":"Setup required here","unsupported":"Unavailable here"}[support.state]??"Not verified":"Not verified",parent);if(support){fact("Support reason",support.message,parent);fact("Next step",support.nextStep,parent);fact("Support code",support.reasonCode,parent)}fact("Connection",row.connectionState,parent);fact("Local records",Number.isSafeInteger(row.items)?number(row.items):"Unverified",parent);fact("Data evidence",row.dataState.replaceAll("_"," "),parent);if(row.readiness){fact("Actions",`Ready \xB7 ${number(row.readiness.actions)} available`,parent);fact("Read check",row.readiness.operation.state==="not-run"?"Not run":row.readiness.operation.returned===void 0?"Action succeeded \xB7 record read unverified":`Read succeeded \xB7 ${number(row.readiness.operation.returned)} returned`,parent);note("This check belongs to the current connection session. Available Actions do not establish a successful read or stored records.",parent)}if(row.publicRead){fact(row.source==="appstore"?"Public App Store read":"Public data read",row.publicRead.state,parent);if(row.source==="appstore")note("Public catalog access does not establish an Apple account connection or stored records.",parent)}if(row.readEvidence){fact("Live read",`${number(row.readEvidence.returned)} returned`,parent);note("Live read results are separate from records stored in the Vault.",parent)}fact("First record",dateText(row.first),parent);fact("Latest mapped record",dateText(row.latest),parent);if(row.sync){node("h2","Full sync",parent,"p-label");for(const[name,value]of syncFacts(row.sync,snapshot?.sync,Date.now()))fact(name,value,parent);for(const text of syncNotes(snapshot?.sync))note(text,parent)}const p=row.progress,e=p?.evidence;node("h2","Latest connection attempt",parent,"p-label");fact("Stage",p?.stage??"Not observed",parent);fact("Elapsed",seconds(p?.durationMs),parent);fact("Connect",seconds(p?.connectMs),parent);fact("Read",seconds(p?.readMs),parent);fact("Attempt connection",p?.connectionState??"Unverified",parent);for(const[label,value]of readinessFacts(row))fact(label,value,parent);const live=e&&e.origin!=="vault-cache";if(!p?.readiness&&!Number.isSafeInteger(row.readiness?.operation?.returned))fact("First page",live?`Read \xB7 ${Number.isFinite(p.returned)?`${number(p.returned)} returned`:"count not reported"}`:e?.origin==="vault-cache"?"Cached records only \xB7 live read unverified":"Unverified",parent);if(e?.stage==="read-own-posts")fact("Your own posts",live&&e.ownRecords>0?`${number(e.ownRecords)} verified`:"Unverified",parent);if(e){fact("Evidence origin",e.origin,parent);fact("Observed",dateText(e.observedAt),parent)}if(p?.errorCode)fact("Reason",p.errorCode,parent);note("Available Actions can be used before an operation is tested. Stored records and verified own posts require their own evidence.",parent);note("This page reads aggregate counts only. Account details, record titles and message content are not exposed.",parent);refreshButton(parent);note("Connection controls and progress stay in this app.",parent)}function store(){const view=$("view");view.hidden=true;const page=$("chat");page.hidden=false;page.classList.add("zx-store");const content=$("messages");content.replaceChildren();node("h1","Mods",content);note("Your Zortex, with more possibilities.",content);note("The marketplace is not available in this build.",content);card(content,"Galaxy","Included \xB7 current local Vault",()=>go("home"));const b=node("button","Back to Galaxy",content,"p-pill");b.onclick=()=>go("home")}function engine(){const rows=snapshot?.coverage||[],verified=rows.filter(r=>r.connectionState==="connected");$("engine-sub").textContent=`${verified.length} connected \xB7 ${rows.length} sources \xB7 ${number(snapshot?.inventory?.storedRecords??snapshot?.totalItems)} ${snapshot?.inventory?"stored records":"mapped records"}`;$("engine-sync").textContent=engineSyncLine(rows,Date.now())??"Current local Vault snapshot";$("engine-sync-now").textContent="Refresh counts";$("engine-sync-now").onclick=async()=>{await load();render()};const updates=Array.from({length:33},(_,i)=>({id:"B"+String(i+1).padStart(2,"0"),state:i<verified.length?"on":"off",throttle:i<verified.length?1:0}));mini?.setEngines(updates);big?.setEngines(updates);const list=$("connector-list");list.replaceChildren();for(const row of rows.filter(r=>sourceName(r.source).toLowerCase().includes($("engine-q").value.toLowerCase()))){const li=node("li",void 0,list);const b=node("button",void 0,li);b.className=row.connectionState==="connected"?"on":"off";node("i",void 0,b);node("span",sourceName(row.source),b,"nm");node("span",number(row.items),b,"n");const sync=syncSummary(row.sync);b.title=`${row.connectionState} \xB7 ${row.dataState}${sync?` \xB7 ${sync}`:""}`;b.onclick=()=>go(`apps/${row.source}`)}$("engine-empty").hidden=list.children.length!==0;$("engine-card").hidden=true}$("engine-q").oninput=engine;function render(){current=decodeURIComponent(location.hash.slice(1)||"home");const[page,id]=current.split("/");root.dataset.route=page==="engine"?"engine":page==="store"?"store":"home";root.toggleAttribute("data-panel",!["home","engine","store"].includes(page));for(const el of[$("sidebar"),$("sidebar-show")]){if(page==="store")el.dataset.surface="store";else delete el.dataset.surface}$("panel").hidden=["home","engine","store"].includes(page);$("engine").hidden=page!=="engine";$("chat").hidden=true;$("chat").classList.remove("zx-store");$("view").hidden=true;$("panel-back").hidden=!id;if(!["apps","ais","mods"].includes(page)){$("panel-body").replaceChildren();panels.hide()}$("panel-tools").hidden=true;const titles={ais:"Connected AIs",apps:"Apps",mods:"Mods",about:accountLabel};$("panel-title").textContent=id?sourceName(id):titles[page]||"Zortex";if(!$("panel").hidden)sidebar(true);if(loadError)note(loadError,$("panel-body"));if(["apps","ais","mods"].includes(page))panels.show(page,id?[id]:[]);else if(page==="engine")engine();else if(page==="store")store();else if(page==="about"){$("panel").hidden=false;const accountButton=node("button","Zortex account",$("panel-body"),"p-pill");accountButton.onclick=()=>dispatchEvent(new Event("zortex-account-open"));fact("Version",snapshot?.productVersion,$("panel-body"));fact("Vault",snapshot?.status,$("panel-body"));fact("Source Vault",snapshot?.inventory?.label??"Current Vault",$("panel-body"));fact("Stored records",snapshot?.inventory?number(snapshot.inventory.storedRecords):"Unavailable",$("panel-body"));fact("Mapped records",number(snapshot?.portrait?.mappedThings??snapshot?.totalItems),$("panel-body"));fact("Latest mapped record",dateText(snapshot?.latest),$("panel-body"));const summary=snapshot?.portrait?.summary;note(typeof summary==="string"&&summary.trim()?summary.trim():"Galaxy brings your saved records into a visual map. It uses the information already in your workspace.",$("panel-body"));refreshButton($("panel-body"))}document.querySelectorAll("[data-go]").forEach(b=>b.setAttribute("aria-current",b.dataset.go===page?"page":"false"));tellTwin()}const panels=await mountPanels({open:go,openStore:()=>go("store"),sourceDetails:(parent,id)=>sourceDetails(parent,sourceRow(id)),sourceAction:id=>{const view=connections.view(id,sourceRow(id));return runtime.canConnect?view:{...view,actionLabel:"View connection"}},connectSource:async id=>{go(`apps/${id}`);await connections.primary(id,sourceRow(id))}});const refreshSnapshot=createSnapshotRefresh({read:async()=>{const r=await fetch("snapshot.json");if(!r.ok)throw Error();return r.json()},publish:value=>{snapshot=value;setSnapshot({...snapshot,connectionReport:connections.getReport()});loadError=""},reload:()=>$("twin").contentWindow?.location.reload()});async function load(){try{await connections.refresh()}catch{}try{await refreshSnapshot()}catch{loadError="Workspace unavailable. Please refresh or sign in again."}}addEventListener("hashchange",render);addEventListener("resize",tellTwin);$("twin").addEventListener("load",tellTwin);addEventListener("message",e=>{if(e.origin!==location.origin||e.source!==$("twin").contentWindow)return;if(e.data?.type==="zortex-twin-ready")tellTwin();if(e.data?.type==="zortex-twin-mode"&&["twin","time","play","others"].includes(e.data.mode))root.dataset.twinMode=e.data.mode;if(e.data?.type==="zortex-twin-full")root.toggleAttribute("data-twin-full",e.data.on===true)});addEventListener("keydown",e=>{if(e.key==="Escape")go("home");if((e.ctrlKey||e.metaKey)&&e.key==="\\"){e.preventDefault();sidebar(!root.hasAttribute("data-sidebar"))}});sidebar(true);await load();engine();render();let refreshing=false;const refreshTimer=setInterval(async()=>{if(refreshing||document.hidden)return;refreshing=true;const route=current;try{await load();if(current===route&&!document.activeElement?.matches('input,textarea,select,[contenteditable="true"]'))render()}finally{refreshing=false}},5e3);addEventListener("pagehide",()=>{clearInterval(refreshTimer);connections.dispose()});
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1 +1 @@
1
- import{AUTHORIZATION_REASON_CODES,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";function page(snapshot){if(!snapshot||!Array.isArray(snapshot.controls))return"unknown";const text=((typeof snapshot.title==="string"?snapshot.title:"")+" "+(typeof snapshot.text==="string"?snapshot.text:"")).slice(0,1e5);try{const url=new URL(snapshot.url);if(url.searchParams.has("error"))return"error";if(url.searchParams.has("code"))return"callback";if(/chooser/i.test(url.pathname))return"account_picker";if(/consent/i.test(url.pathname))return"consent"}catch{return"unknown"}if(/captcha|verification code|two.step|2.step|security check|验证码|驗證碼|人机|人機/i.test(text))return"challenge";if(snapshot.controls.some(control=>control?.secure)||/password|passkey|密码|密碼/i.test(text))return"login";if(snapshot.controls.some(control=>control&&/@/.test(control.label))||/choose.*account|选择.*帐号|選擇.*帳戶/i.test(text))return"account_picker";if(/permission|allow|authorize|consent|授权|授權|允許|允许/i.test(text))return"consent";if(/unverified|hasn.t verified|未经.*验证|未經.*驗證/i.test(text))return"notice";return"unknown"}export function browserFeedback(metrics,source,flow){const trace=createTraceRecorder(metrics,source,flow);let seen="unknown";function wrap(browser){return{...typeof browser.close==="function"?{close:()=>browser.close()}:{},async observe(){try{const snapshot=await browser.observe();seen=page(snapshot);await trace.step("page_observed","completed",{page:seen});return snapshot}catch(error){await trace.step("page_observed","failed",{error:"unknown"});throw error}},async act(control,action,value){const selected=action==="type"?"type":seen==="account_picker"?"choose_account":seen==="consent"?"approve":seen==="notice"?"continue":"click";await trace.step("action_executed","started",{action:selected});try{const result=await browser.act(control,action,value);await trace.step("action_executed",result?"completed":"failed",{action:selected});return result}catch(error){await trace.step("action_executed","failed",{action:selected,error:"unknown"});throw error}},async scroll(){await trace.step("action_executed","started",{action:"scroll"});try{const result=await browser.scroll();await trace.step("action_executed",result?"completed":"failed",{action:"scroll"});return result}catch(error){await trace.step("action_executed","failed",{action:"scroll",error:"unknown"});throw error}}}}return{trace,wrap,decider(decider){return{get lastCostUsd(){return decider.lastCostUsd},async choose(...args){try{const result=await decider.choose(...args);await trace.step("action_selected","completed",{action:["click","type","scroll","wait"].includes(result.action)?result.action:"unknown"});return result}catch(error){await trace.step("action_selected","failed",{error:"provider"});throw error}}}},async finish(state,reason){const safe=AUTHORIZATION_REASON_CODES.find(code=>code===reason);await trace.step("automation_finished",state==="completed"||state==="verified"||state==="accounts"?"completed":"failed",{mode:"automatic",...reason?{reason:safe??"unknown"}:{}})}}}
1
+ import{AUTHORIZATION_REASON_CODES,createTraceRecorder,startOperationalStep,operationalReason}from"@zortexhq/plugin-telemetry/api";function page(snapshot){if(!snapshot||!Array.isArray(snapshot.controls))return"unknown";const text=((typeof snapshot.title==="string"?snapshot.title:"")+" "+(typeof snapshot.text==="string"?snapshot.text:"")).slice(0,1e5);try{const url=new URL(snapshot.url);if(url.searchParams.has("error"))return"error";if(url.searchParams.has("code"))return"callback";if(/chooser/i.test(url.pathname))return"account_picker";if(/consent/i.test(url.pathname))return"consent"}catch{return"unknown"}if(/captcha|verification code|two.step|2.step|security check|验证码|驗證碼|人机|人機/i.test(text))return"challenge";if(snapshot.controls.some(control=>control?.secure)||/password|passkey|密码|密碼/i.test(text))return"login";if(snapshot.controls.some(control=>control&&/@/.test(control.label))||/choose.*account|选择.*帐号|選擇.*帳戶/i.test(text))return"account_picker";if(/permission|allow|authorize|consent|授权|授權|允許|允许/i.test(text))return"consent";if(/unverified|hasn.t verified|未经.*验证|未經.*驗證/i.test(text))return"notice";return"unknown"}export function browserFeedback(metrics,source,flow){const trace=createTraceRecorder(metrics,source,flow);let seen="unknown";const operation=startOperationalStep(metrics,{source,phase:"browser",action:"goal",operationId:"browser.run_goal"});const observed=async(action,run,accepted)=>{const operationId=action==="cleanup"?"browser.close":action==="plan"?"browser.plan":action==="observe"?"browser.observe":action==="click"?"browser.click":action==="type"?"browser.type":"browser.scroll";const step=operation.run(()=>startOperationalStep(metrics,{source,phase:"browser",action,operationId}));try{const result=await step.run(run);step.finish(accepted&&!accepted(result)?{state:"failed",reason:"stale_control"}:{state:"completed"});return result}catch(error){const reason=operationalReason(error instanceof Error?error.message:void 0);step.finish({state:reason==="cancelled"?"cancelled":"failed",reason});throw error}};function wrap(browser){return{...typeof browser.close==="function"?{close:()=>observed("cleanup",()=>browser.close())}:{},async observe(){try{const snapshot=await observed("observe",()=>browser.observe());seen=page(snapshot);await trace.step("page_observed","completed",{page:seen});return snapshot}catch(error){await trace.step("page_observed","failed",{error:"unknown"});throw error}},async act(control,action,value){const selected=action==="type"?"type":seen==="account_picker"?"choose_account":seen==="consent"?"approve":seen==="notice"?"continue":"click";await trace.step("action_executed","started",{action:selected});try{const result=await observed(action,()=>browser.act(control,action,value),value2=>value2===true);await trace.step("action_executed",result?"completed":"failed",{action:selected});return result}catch(error){await trace.step("action_executed","failed",{action:selected,error:"unknown"});throw error}},async scroll(){await trace.step("action_executed","started",{action:"scroll"});try{const result=await observed("scroll",()=>browser.scroll());await trace.step("action_executed",result?"completed":"failed",{action:"scroll"});return result}catch(error){await trace.step("action_executed","failed",{action:"scroll",error:"unknown"});throw error}}}}return{trace:{...trace,async step(...args){await trace.step(...args);if(args[0]==="startup_failed"||args[0]==="automation_finished")operation.finish({state:args[1]==="completed"?"completed":args[1]==="cancelled"?"cancelled":args[1]==="unknown"?"unknown":"failed",...args[2]?.reason?{reason:args[2].reason}:{}})}},wrap,decider(decider){return{get lastCostUsd(){return decider.lastCostUsd},async choose(...args){try{const result=await observed("plan",()=>decider.choose(...args));await trace.step("action_selected","completed",{action:["click","type","scroll","wait"].includes(result.action)?result.action:"unknown"});return result}catch(error){await trace.step("action_selected","failed",{error:"provider"});throw error}}}},async finish(state,reason){const safe=AUTHORIZATION_REASON_CODES.find(code=>code===reason);const waiting=["login_required","admin_approval_required","needs-user"].includes(state);const succeeded=state==="completed"||state==="verified"||state==="accounts";if(waiting){operation.mark({state:"waiting",...reason?{reason:safe??"unknown"}:{}});await trace.step("manual_required","waiting",{mode:"manual",action:"request_manual",...reason?{reason:safe??"unknown"}:{}})}operation.finish({state:succeeded?"completed":reason==="cancelled"?"cancelled":waiting||state==="unknown"?"unknown":"failed",...reason?{reason:safe??"unknown"}:{}});await trace.step("automation_finished",succeeded?"completed":reason==="cancelled"?"cancelled":waiting||state==="unknown"?"unknown":"failed",{...state==="completed"||state==="accounts"?{mode:"automatic"}:{},...reason?{reason:safe??"unknown"}:{}})}}}
@@ -1 +1 @@
1
- import{randomBytes,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{ChromeAuthorizationRequired}from"./attached.js";import{driveGoogleOAuth}from"./google-oauth-driver.js";import{decideGoogleUia}from"./google-uia-decision.js";const PATH="/google-oauth/v1";const DECISION_PATH=`${PATH}/decision`;const MAX_BODY=16384;const MAX_REQUESTS=20;function authorized(value,token){if(!value?.startsWith("Bearer "))return false;const supplied=Buffer.from(value.slice(7));const expected=Buffer.from(token);return supplied.length===expected.length&&timingSafeEqual(supplied,expected)}function reply(res,status,body){res.writeHead(status,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"});res.end(JSON.stringify(body))}async function bounded(task,message){let timer;try{return await Promise.race([task,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),15e3)})])}finally{clearTimeout(timer)}}export async function startGoogleOAuthBridge(open,jev,options={}){const token=randomBytes(32).toString("hex");const stop=new AbortController;let closed=false;let busy=false;let requests=0;const active=new Set;const browsers=new Set;const trackedOpen=async(url,onAttachFailure)=>{let browser;try{browser=await open(url)}catch(error){if(error instanceof ChromeAuthorizationRequired)onAttachFailure();throw error}if(stop.signal.aborted){await browser.close();throw new Error("OAuth bridge is closed.")}browsers.add(browser);return{observe:()=>browser.observe(),act:(control,action,value)=>browser.act(control,action,value),scroll:()=>browser.scroll(),close:async()=>{try{await browser.close()}finally{browsers.delete(browser)}}}};const serve=async(req,res)=>{if(closed||stop.signal.aborted||req.method!=="POST"||![PATH,DECISION_PATH].includes(req.url??"")){reply(res,404,{state:"ui_drift"});return}if(!authorized(req.headers.authorization,token)){reply(res,401,{state:"ui_drift"});return}if(busy||++requests>MAX_REQUESTS){reply(res,429,{state:"ui_drift"});return}busy=true;try{let bytes=0;const chunks=[];const bodyTimer=setTimeout(()=>req.destroy(),5e3);try{for await(const chunk of req){const data=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);bytes+=data.length;if(bytes>MAX_BODY){reply(res,413,{state:"ui_drift"});return}chunks.push(data)}}finally{clearTimeout(bodyTimer)}let request;try{request=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(res,400,{state:"ui_drift"});return}try{const signal=AbortSignal.any([stop.signal,options.signal??new AbortController().signal]);if(req.url===DECISION_PATH){const feedback2=options.feedback?.(),decision=await decideGoogleUia(request,feedback2?feedback2.decider(jev):jev,signal);const phase=request&&typeof request==="object"&&"phase"in request?request.phase:void 0;await feedback2?.trace.step("page_observed","completed",{page:phase==="account"?"account_picker":phase==="scope"||phase==="consent"?"consent":phase==="notice"?"notice":"unknown"});await feedback2?.trace.step("action_selected",decision.state==="selected"?"completed":"failed",{action:phase==="account"?"choose_account":phase==="consent"||phase==="scope"?"approve":"continue"});reply(res,200,decision);return}let attachFailed=false;const feedback=options.feedback?.();const outcome=await driveGoogleOAuth(request,async url=>{const browser=await trackedOpen(url,()=>{attachFailed=true});return feedback?feedback.wrap(browser):browser},feedback?feedback.decider(jev):jev,signal,{allowUnverifiedZortex:options.allowUnverifiedZortex===true});const visibleFallback=process.platform==="win32"&&(attachFailed||outcome.state==="login_required"||outcome.state!=="accounts"&&outcome.reason==="account_chooser_unavailable");if(visibleFallback)await feedback?.trace.step("action_selected","unknown",{action:"continue",mode:"unknown"});else await feedback?.finish(outcome.state,"reason"in outcome?outcome.reason:void 0);reply(res,200,visibleFallback?{state:"uia_required"}:outcome.state==="accounts"?{state:"accounts",accounts:outcome.accounts}:{state:outcome.state})}catch{reply(res,400,{state:"ui_drift"})}}catch{if(!res.writableEnded)reply(res,500,{state:"ui_drift"})}finally{busy=false}};const server=createServer((req,res)=>{const task=serve(req,res);active.add(task);void task.finally(()=>active.delete(task))});server.headersTimeout=5e3;server.requestTimeout=1e4;try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)})}catch(error){server.close();throw error}const address=server.address();if(!address||typeof address==="string"){server.close();throw new Error("Invalid OAuth bridge address.")}const endpoint=`http://127.0.0.1:${address.port}${PATH}`;let closing;const close=()=>closing??=(async()=>{closed=true;stop.abort();server.closeAllConnections();const serverClosed=new Promise((resolve,reject)=>server.close(error=>{if(!error||error.code==="ERR_SERVER_NOT_RUNNING"||error.message==="Server is not running.")resolve();else reject(error)}));const results=await Promise.allSettled([bounded(serverClosed,"OAuth bridge shutdown timed out."),bounded(Promise.all([...browsers].map(browser=>browser.close())).then(()=>void 0),"OAuth browser cleanup timed out."),bounded(Promise.allSettled([...active]),"OAuth browser task shutdown timed out.")]);const failures=results.flatMap((result,index)=>result.status==="rejected"?[`${index}:${result.reason instanceof Error?result.reason.message:"unknown"}`]:[]);if(failures.length)throw new Error(`OAuth bridge cleanup failed (${failures.join(", ")}).`)})();return{endpoint,token,close}}
1
+ import{randomBytes,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{ChromeAuthorizationRequired}from"./attached.js";import{driveGoogleOAuth}from"./google-oauth-driver.js";import{decideGoogleUia}from"./google-uia-decision.js";const PATH="/google-oauth/v1";const DECISION_PATH=`${PATH}/decision`;const MAX_BODY=16384;const MAX_REQUESTS=20;function authorized(value,token){if(!value?.startsWith("Bearer "))return false;const supplied=Buffer.from(value.slice(7));const expected=Buffer.from(token);return supplied.length===expected.length&&timingSafeEqual(supplied,expected)}function reply(res,status,body){res.writeHead(status,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"});res.end(JSON.stringify(body))}async function bounded(task,message){let timer;try{return await Promise.race([task,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),15e3)})])}finally{clearTimeout(timer)}}export async function startGoogleOAuthBridge(open,jev,options={}){const token=randomBytes(32).toString("hex");const stop=new AbortController;let closed=false;let busy=false;let requests=0;const active=new Set;const browsers=new Set;const trackedOpen=async(url,onAttachFailure)=>{let browser;try{browser=await open(url)}catch(error){if(error instanceof ChromeAuthorizationRequired)onAttachFailure();throw error}if(stop.signal.aborted){await browser.close();throw new Error("OAuth bridge is closed.")}browsers.add(browser);return{observe:()=>browser.observe(),act:(control,action,value)=>browser.act(control,action,value),scroll:()=>browser.scroll(),close:async()=>{try{await browser.close()}finally{browsers.delete(browser)}}}};const serve=async(req,res)=>{if(closed||stop.signal.aborted||req.method!=="POST"||![PATH,DECISION_PATH].includes(req.url??"")){reply(res,404,{state:"ui_drift"});return}if(!authorized(req.headers.authorization,token)){reply(res,401,{state:"ui_drift"});return}if(busy||++requests>MAX_REQUESTS){reply(res,429,{state:"ui_drift"});return}busy=true;try{let bytes=0;const chunks=[];const bodyTimer=setTimeout(()=>req.destroy(),5e3);try{for await(const chunk of req){const data=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);bytes+=data.length;if(bytes>MAX_BODY){reply(res,413,{state:"ui_drift"});return}chunks.push(data)}}finally{clearTimeout(bodyTimer)}let request;try{request=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(res,400,{state:"ui_drift"});return}try{const signal=AbortSignal.any([stop.signal,options.signal??new AbortController().signal]);if(req.url===DECISION_PATH){const feedback2=options.feedback?.(),decision=await decideGoogleUia(request,feedback2?feedback2.decider(jev):jev,signal);const phase=request&&typeof request==="object"&&"phase"in request?request.phase:void 0;await feedback2?.trace.step("page_observed","completed",{page:phase==="account"?"account_picker":phase==="scope"||phase==="consent"?"consent":phase==="notice"?"notice":"unknown"});await feedback2?.trace.step("action_selected",decision.state==="selected"?"completed":"failed",{action:phase==="account"?"choose_account":phase==="consent"||phase==="scope"?"approve":"continue"});await feedback2?.trace.step("automation_finished","unknown");reply(res,200,decision);return}let attachFailed=false;const feedback=options.feedback?.();const outcome=await driveGoogleOAuth(request,async url=>{const browser=await trackedOpen(url,()=>{attachFailed=true});return feedback?feedback.wrap(browser):browser},feedback?feedback.decider(jev):jev,signal,{allowUnverifiedZortex:options.allowUnverifiedZortex===true});const visibleFallback=process.platform==="win32"&&(attachFailed||outcome.state==="login_required"||outcome.state!=="accounts"&&outcome.reason==="account_chooser_unavailable");if(visibleFallback)await feedback?.trace.step("action_selected","unknown",{action:"continue",mode:"unknown"});else await feedback?.finish(outcome.state,"reason"in outcome?outcome.reason:void 0);reply(res,200,visibleFallback?{state:"uia_required"}:outcome.state==="accounts"?{state:"accounts",accounts:outcome.accounts}:{state:outcome.state})}catch{reply(res,400,{state:"ui_drift"})}}catch{if(!res.writableEnded)reply(res,500,{state:"ui_drift"})}finally{busy=false}};const server=createServer((req,res)=>{const task=serve(req,res);active.add(task);void task.finally(()=>active.delete(task))});server.headersTimeout=5e3;server.requestTimeout=1e4;try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)})}catch(error){server.close();throw error}const address=server.address();if(!address||typeof address==="string"){server.close();throw new Error("Invalid OAuth bridge address.")}const endpoint=`http://127.0.0.1:${address.port}${PATH}`;let closing;const close=()=>closing??=(async()=>{closed=true;stop.abort();server.closeAllConnections();const serverClosed=new Promise((resolve,reject)=>server.close(error=>{if(!error||error.code==="ERR_SERVER_NOT_RUNNING"||error.message==="Server is not running.")resolve();else reject(error)}));const results=await Promise.allSettled([bounded(serverClosed,"OAuth bridge shutdown timed out."),bounded(Promise.all([...browsers].map(browser=>browser.close())).then(()=>void 0),"OAuth browser cleanup timed out."),bounded(Promise.allSettled([...active]),"OAuth browser task shutdown timed out.")]);const failures=results.flatMap((result,index)=>result.status==="rejected"?[`${index}:${result.reason instanceof Error?result.reason.message:"unknown"}`]:[]);if(failures.length)throw new Error(`OAuth bridge cleanup failed (${failures.join(", ")}).`)})();return{endpoint,token,close}}
@@ -1 +1 @@
1
- import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{AttachedChrome,ChromeAuthorizationRequired}from"./attached.js";import{IsolatedChrome}from"./browser.js";import{JevDecider}from"./decision.js";import{ExtensionChrome}from"./extension-transport.js";import{startGoogleOAuthBridge}from"./google-oauth-bridge.js";import{runBrowserTask}from"./runner.js";import{driveSlackOAuth}from"./slack-oauth-driver.js";import{startSlackOAuthBridge}from"./slack-oauth-bridge.js";import{driveMicrosoftOAuth}from"./microsoft-oauth-driver.js";import{startMicrosoftOAuthBridge}from"./microsoft-oauth-bridge.js";import{currentFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{browserFeedback}from"./feedback.js";export{ExtensionChrome}from"./extension-transport.js";export const name="zortex-jev-autopilot";export function defaultChromeDirectory(){return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),"Google/Chrome/User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support/Google/Chrome"):join(homedir(),".config/google-chrome")}export function apply(ctx,config){const extensionId=config?.extensionId??process.env.ZORTEX_JEV_EXTENSION_ID;const gmailTransport=config?.gmailTransport??(extensionId?"extension":"attached");if(!config||!Array.isArray(config.allowedOrigins)||config.allowedOrigins.length>20||config.allowedOrigins.some(x=>{try{const u=new URL(x);return u.protocol!=="https:"||u.origin!==x||!!u.username||!!u.password}catch{return true}})||!Number.isInteger(config.maxSteps??12)||(config.maxSteps??12)<1||(config.maxSteps??12)>50||!Number.isInteger(config.timeoutMs??3e4)||(config.timeoutMs??3e4)<1e3||(config.timeoutMs??3e4)>12e4||config.sessionMode!==void 0&&!["isolated","attached"].includes(config.sessionMode)||!["attached","extension"].includes(gmailTransport)||gmailTransport==="extension"&&!extensionId||extensionId!==void 0&&!/^[a-p]{32}$/.test(extensionId)||config.allowUnverifiedZortex!==void 0&&typeof config.allowUnverifiedZortex!=="boolean"||config.chromeUserDataDir!==void 0&&(typeof config.chromeUserDataDir!=="string"||config.chromeUserDataDir!==""&&!isAbsolute(config.chromeUserDataDir))||config.allowHeaded!==void 0&&typeof config.allowHeaded!=="boolean"||Object.keys(config).some(k=>!["allowedOrigins","maxSteps","timeoutMs","allowHeaded","sessionMode","chromeUserDataDir","gmailTransport","extensionId","allowUnverifiedZortex"].includes(k)))throw new Error("Invalid Jev autopilot settings.");const sessionMode=config.sessionMode??"isolated";const attached=sessionMode==="attached"?new AttachedChrome(config.chromeUserDataDir||defaultChromeDirectory()):void 0;const googleChrome=attached??new AttachedChrome(config.chromeUserDataDir||defaultChromeDirectory());let closed=false;const running=new Set;const tasks=new Set;const bridges=new Set;const extensionSessions=new Set;ctx.effect(()=>async()=>{closed=true;for(const controller of running)controller.abort();await Promise.allSettled([...tasks]);await Promise.allSettled([...bridges].map(bridge=>bridge.close()));await Promise.allSettled([...extensionSessions].map(browser=>browser.dispose()));await googleChrome.dispose()});const service={async run(request,options={}){if(closed)return businessError("unavailable","Jev autopilot is disabled.","plugin");return start(request,options)},async startGoogleOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");const extension=gmailTransport==="extension"?new ExtensionChrome({extensionId}):void 0;let bridge;const flow=currentFeedbackFlow();const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),flow?.source??"other",flow);try{if(extension){await extension.start();extensionSessions.add(extension)}bridge=await startGoogleOAuthBridge(url=>extension?extension.open(url):googleChrome.open(url),new JevDecider,{...options,allowUnverifiedZortex:config.allowUnverifiedZortex===true,feedback:()=>feedback})}catch(error){await feedback.trace.step("startup_failed","failed",{error:"unknown"});if(extension){extensionSessions.delete(extension);try{await extension.dispose()}catch{process.stderr.write("Jev extension cleanup also failed.\n")}}throw error}if(closed){await bridge.close();if(extension){extensionSessions.delete(extension);await extension.dispose()}throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);try{await bridge.close()}finally{if(extension){extensionSessions.delete(extension);await extension.dispose()}}}};bridges.add(handle);return handle},async startSlackOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for Slack.");const bridge=await startSlackOAuthBridge((request,signal)=>service.runSlackOAuth(request,{signal}),options.signal);if(closed){await bridge.close();throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);await bridge.close()}};bridges.add(handle);return handle},async runSlackOAuth(request,options={}){if(closed)throw new Error("Jev autopilot is disabled.");const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"slack");if(!extensionId){await feedback.trace.step("startup_failed","failed",{error:"unknown"});throw new Error("Installed Jev Chrome extension is required for Slack.")}const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{let result,failure;let started=false,failed=false;try{await extension.start();started=true;result=await driveSlackOAuth(request,async url=>feedback.wrap(await extension.openSlack({...request,authorizationUrl:url})),feedback.decider(new JevDecider),options.signal)}catch(error){failed=true;failure=error}extensionSessions.delete(extension);try{await extension.dispose()}catch(error){if(failed)process.stderr.write("Jev extension cleanup also failed.\n");else failure=error;failed=true}if(failed){await feedback.trace.step(started?"automation_finished":"startup_failed","failed",{error:"unknown"});throw failure}await feedback.finish(result.state,result.reason);return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task},async startMicrosoftOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for Microsoft OAuth.");const bridge=await startMicrosoftOAuthBridge((request,signal)=>service.runMicrosoftOAuth(request,{signal}),options.signal);if(closed){await bridge.close();throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);await bridge.close()}};bridges.add(handle);return handle},async runMicrosoftOAuth(request,options={}){if(closed)throw new Error("Jev autopilot is disabled.");const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"outlook");if(!extensionId){await feedback.trace.step("startup_failed","failed",{error:"unknown"});throw new Error("Installed Jev Chrome extension is required for Microsoft OAuth.")}const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{let result,failure;let started=false,failed=false;try{await extension.start();started=true;result=await driveMicrosoftOAuth(request,async url=>feedback.wrap(await extension.openMicrosoft({...request,authorizationUrl:url})),feedback.decider(new JevDecider),options.signal)}catch(error){failed=true;failure=error}extensionSessions.delete(extension);try{await extension.dispose()}catch(error){if(failed)process.stderr.write("Jev extension cleanup also failed.\n");else failure=error;failed=true}if(failed){await feedback.trace.step(started?"automation_finished":"startup_failed","failed",{error:"unknown"});throw failure}await feedback.finish(result.state,result.reason);return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task},async checkWhatsAppSession(){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for WhatsApp Web.");const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"whatsapp-web");try{await extension.start();const result=await extension.checkWhatsAppSession();await feedback.trace.step("page_observed","completed",{page:result.state==="pairing_required"?"challenge":"unknown"});return result}finally{extensionSessions.delete(extension);await extension.dispose()}})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task}};async function start(request,options){let url;try{url=new URL(request?.url)}catch{return businessError("invalid_argument","A public HTTPS URL is required.","plugin")}if(url.protocol!=="https:"||url.username||url.password)return businessError("invalid_argument","A valid HTTPS URL is required.","plugin");if(request.headed&&sessionMode==="attached")return businessError("invalid_argument","Attached Chrome uses an owned hidden target.","plugin");const controller=new AbortController;running.add(controller);const signal=AbortSignal.any([controller.signal,options.signal??new AbortController().signal]);const task=(async()=>{const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"other");let browser;let result;let cleanupFailed=false;try{browser=attached?await attached.open(request.url):await IsolatedChrome.open(request.url,request.headed??false);result=ok(await runBrowserTask(request,feedback.wrap(browser),feedback.decider(new JevDecider),{maxSteps:config.maxSteps??12,timeoutMs:config.timeoutMs??3e4,signal}))}catch(error){if(error instanceof ChromeAuthorizationRequired)result=ok({state:"failed",reason:error.message,steps:[],modelCalls:0,elapsedMs:0});else{result=businessError(signal.aborted?"aborted":"unavailable",signal.aborted?"Browser task was cancelled.":error instanceof Error&&error.message==="provider_missing_key"?"OpenRouter key is not configured.":"Browser task could not start.","plugin")}}finally{running.delete(controller);try{await browser?.close()}catch{cleanupFailed=true}}if(cleanupFailed)result=businessError("internal","Owned browser target cleanup failed.","plugin");if("ok"in result)await feedback.finish(result.ok.state,result.ok.reason);else await feedback.trace.step(browser?"automation_finished":"startup_failed",result.err.code==="aborted"?"cancelled":"failed",{error:"unknown"});return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task}ctx.provide("zortexJevAutopilot",service)}
1
+ import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{AttachedChrome,ChromeAuthorizationRequired}from"./attached.js";import{IsolatedChrome}from"./browser.js";import{JevDecider}from"./decision.js";import{ExtensionChrome}from"./extension-transport.js";import{startGoogleOAuthBridge}from"./google-oauth-bridge.js";import{runBrowserTask}from"./runner.js";import{driveSlackOAuth}from"./slack-oauth-driver.js";import{startSlackOAuthBridge}from"./slack-oauth-bridge.js";import{driveMicrosoftOAuth}from"./microsoft-oauth-driver.js";import{startMicrosoftOAuthBridge}from"./microsoft-oauth-bridge.js";import{currentFeedbackFlow,createTraceRecorder,startOperationalStep}from"@zortexhq/plugin-telemetry/api";import{browserFeedback}from"./feedback.js";export{ExtensionChrome}from"./extension-transport.js";export const name="zortex-jev-autopilot";export function defaultChromeDirectory(){return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),"Google/Chrome/User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support/Google/Chrome"):join(homedir(),".config/google-chrome")}export function apply(ctx,config){const extensionId=config?.extensionId??process.env.ZORTEX_JEV_EXTENSION_ID;const gmailTransport=config?.gmailTransport??(extensionId?"extension":"attached");if(!config||!Array.isArray(config.allowedOrigins)||config.allowedOrigins.length>20||config.allowedOrigins.some(x=>{try{const u=new URL(x);return u.protocol!=="https:"||u.origin!==x||!!u.username||!!u.password}catch{return true}})||!Number.isInteger(config.maxSteps??12)||(config.maxSteps??12)<1||(config.maxSteps??12)>50||!Number.isInteger(config.timeoutMs??3e4)||(config.timeoutMs??3e4)<1e3||(config.timeoutMs??3e4)>12e4||config.sessionMode!==void 0&&!["isolated","attached"].includes(config.sessionMode)||!["attached","extension"].includes(gmailTransport)||gmailTransport==="extension"&&!extensionId||extensionId!==void 0&&!/^[a-p]{32}$/.test(extensionId)||config.allowUnverifiedZortex!==void 0&&typeof config.allowUnverifiedZortex!=="boolean"||config.chromeUserDataDir!==void 0&&(typeof config.chromeUserDataDir!=="string"||config.chromeUserDataDir!==""&&!isAbsolute(config.chromeUserDataDir))||config.allowHeaded!==void 0&&typeof config.allowHeaded!=="boolean"||Object.keys(config).some(k=>!["allowedOrigins","maxSteps","timeoutMs","allowHeaded","sessionMode","chromeUserDataDir","gmailTransport","extensionId","allowUnverifiedZortex"].includes(k)))throw new Error("Invalid Jev autopilot settings.");const sessionMode=config.sessionMode??"isolated";const attached=sessionMode==="attached"?new AttachedChrome(config.chromeUserDataDir||defaultChromeDirectory()):void 0;const googleChrome=attached??new AttachedChrome(config.chromeUserDataDir||defaultChromeDirectory());let closed=false;const running=new Set;const tasks=new Set;const bridges=new Set;const extensionSessions=new Set;ctx.effect(()=>async()=>{closed=true;for(const controller of running)controller.abort();await Promise.allSettled([...tasks]);await Promise.allSettled([...bridges].map(bridge=>bridge.close()));await Promise.allSettled([...extensionSessions].map(browser=>browser.dispose()));await googleChrome.dispose()});const service={async run(request,options={}){if(closed)return businessError("unavailable","Jev autopilot is disabled.","plugin");return start(request,options)},async startGoogleOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");const extension=gmailTransport==="extension"?new ExtensionChrome({extensionId}):void 0;let bridge;const flow=currentFeedbackFlow();const feedback=()=>browserFeedback(()=>ctx.get("zortexTelemetry"),flow?.source??"other",flow);try{if(extension){await extension.start();extensionSessions.add(extension)}bridge=await startGoogleOAuthBridge(url=>extension?extension.open(url):googleChrome.open(url),new JevDecider,{...options,allowUnverifiedZortex:config.allowUnverifiedZortex===true,feedback})}catch(error){await feedback().trace.step("startup_failed","failed",{error:"unknown"});if(extension){extensionSessions.delete(extension);try{await extension.dispose()}catch{process.stderr.write("Jev extension cleanup also failed.\n")}}throw error}if(closed){await bridge.close();if(extension){extensionSessions.delete(extension);await extension.dispose()}throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);try{await bridge.close()}finally{if(extension){extensionSessions.delete(extension);await extension.dispose()}}}};bridges.add(handle);return handle},async startSlackOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for Slack.");const bridge=await startSlackOAuthBridge((request,signal)=>service.runSlackOAuth(request,{signal}),options.signal);if(closed){await bridge.close();throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);await bridge.close()}};bridges.add(handle);return handle},async runSlackOAuth(request,options={}){if(closed)throw new Error("Jev autopilot is disabled.");const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"slack");if(!extensionId){await feedback.trace.step("startup_failed","failed",{error:"unknown"});throw new Error("Installed Jev Chrome extension is required for Slack.")}const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{let result,failure;let started=false,failed=false;try{await extension.start();started=true;result=await driveSlackOAuth(request,async url=>feedback.wrap(await extension.openSlack({...request,authorizationUrl:url})),feedback.decider(new JevDecider),options.signal)}catch(error){failed=true;failure=error}extensionSessions.delete(extension);try{await extension.dispose()}catch(error){if(failed)process.stderr.write("Jev extension cleanup also failed.\n");else failure=error;failed=true}if(failed){await feedback.trace.step(started?"automation_finished":"startup_failed","failed",{error:"unknown"});throw failure}await feedback.finish(result.state,result.reason);return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task},async startMicrosoftOAuthBridge(options={}){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for Microsoft OAuth.");const bridge=await startMicrosoftOAuthBridge((request,signal)=>service.runMicrosoftOAuth(request,{signal}),options.signal);if(closed){await bridge.close();throw new Error("Jev autopilot is disabled.")}const handle={endpoint:bridge.endpoint,token:bridge.token,close:async()=>{bridges.delete(handle);await bridge.close()}};bridges.add(handle);return handle},async runMicrosoftOAuth(request,options={}){if(closed)throw new Error("Jev autopilot is disabled.");const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"outlook");if(!extensionId){await feedback.trace.step("startup_failed","failed",{error:"unknown"});throw new Error("Installed Jev Chrome extension is required for Microsoft OAuth.")}const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{let result,failure;let started=false,failed=false;try{await extension.start();started=true;result=await driveMicrosoftOAuth(request,async url=>feedback.wrap(await extension.openMicrosoft({...request,authorizationUrl:url})),feedback.decider(new JevDecider),options.signal)}catch(error){failed=true;failure=error}extensionSessions.delete(extension);try{await extension.dispose()}catch(error){if(failed)process.stderr.write("Jev extension cleanup also failed.\n");else failure=error;failed=true}if(failed){await feedback.trace.step(started?"automation_finished":"startup_failed","failed",{error:"unknown"});throw failure}await feedback.finish(result.state,result.reason);return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task},async checkWhatsAppSession(){if(closed)throw new Error("Jev autopilot is disabled.");if(!extensionId)throw new Error("Installed Jev Chrome extension is required for WhatsApp Web.");const extension=new ExtensionChrome({extensionId});extensionSessions.add(extension);const task=(async()=>{const metrics=()=>ctx.get("zortexTelemetry"),trace=createTraceRecorder(metrics,"whatsapp-web");const readiness=startOperationalStep(metrics,{source:"whatsapp-web",phase:"browser",action:"readiness",route:"extension",profile:"existing"});try{const result=await readiness.run(async()=>{await extension.start();return extension.checkWhatsAppSession()});await trace.step("page_observed","completed",{page:result.state==="pairing_required"?"challenge":"unknown"});readiness.finish({state:result.state==="unknown"?"unknown":"completed"});return result}catch(error){readiness.finish({state:"failed",errorCategory:"provider"});throw error}finally{extensionSessions.delete(extension);const cleanup=readiness.run(()=>startOperationalStep(metrics,{source:"whatsapp-web",phase:"browser",action:"cleanup",operationId:"browser.close",route:"extension",profile:"existing"}));try{await cleanup.run(()=>extension.dispose());cleanup.finish({state:"completed"})}catch(error){cleanup.finish({state:"failed",errorCategory:"provider"});throw error}}})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task}};async function start(request,options){let url;try{url=new URL(request?.url)}catch{return businessError("invalid_argument","A public HTTPS URL is required.","plugin")}if(url.protocol!=="https:"||url.username||url.password)return businessError("invalid_argument","A valid HTTPS URL is required.","plugin");if(request.headed&&sessionMode==="attached")return businessError("invalid_argument","Attached Chrome uses an owned hidden target.","plugin");const controller=new AbortController;running.add(controller);const signal=AbortSignal.any([controller.signal,options.signal??new AbortController().signal]);const task=(async()=>{const feedback=browserFeedback(()=>ctx.get("zortexTelemetry"),"other");let browser;let result;let cleanupFailed=false;try{browser=attached?await attached.open(request.url):await IsolatedChrome.open(request.url,request.headed??false);result=ok(await runBrowserTask(request,feedback.wrap(browser),feedback.decider(new JevDecider),{maxSteps:config.maxSteps??12,timeoutMs:config.timeoutMs??3e4,signal}))}catch(error){if(error instanceof ChromeAuthorizationRequired)result=ok({state:"failed",reason:error.message,steps:[],modelCalls:0,elapsedMs:0});else{result=businessError(signal.aborted?"aborted":"unavailable",signal.aborted?"Browser task was cancelled.":error instanceof Error&&error.message==="provider_missing_key"?"OpenRouter key is not configured.":"Browser task could not start.","plugin")}}finally{running.delete(controller);try{await browser?.close()}catch{cleanupFailed=true}}if(cleanupFailed)result=businessError("internal","Owned browser target cleanup failed.","plugin");if("ok"in result)await feedback.finish(result.ok.state,result.ok.reason);else await feedback.trace.step(browser?"automation_finished":"startup_failed",result.err.code==="aborted"?"cancelled":"failed",{error:"unknown"});return result})();tasks.add(task);void task.finally(()=>tasks.delete(task)).catch(()=>void 0);return task}ctx.provide("zortexJevAutopilot",service)}