@zortexhq/indra-v2.5 0.2.3 → 0.2.5
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.
- package/dist/measurement-context.js +1 -1
- package/dist/product-feedback.js +2 -2
- package/dist/profile.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/localizer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +92 -36
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +13 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy.html +141 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-state.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/panels-live.js +3 -3
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/product.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +16 -46
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/device-identity.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/package.json +6 -6
- package/profiles/core.yml +1 -0
- package/release-provenance.json +14 -14
- package/update-manifest.json +94 -70
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-catalog.js +0 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/demo.js +0 -1
|
@@ -1,47 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
:
|
|
3
|
-
:
|
|
4
|
-
|
|
5
|
-
.
|
|
6
|
-
|
|
7
|
-
.button{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:40px;border-radius:8px;padding:10px 16px;font-size:12px;line-height:1.2;font-weight:550;border:1px solid transparent;text-align:center}.button.primary{background:var(--ink);color:var(--page)}.button.primary:hover{opacity:.86}.button.secondary{border-color:var(--line);background:var(--surface)}.button.secondary:hover{background:var(--soft)}.button.compact{font-size:11px;min-height:32px;padding:7px 11px;border-radius:20px;background:var(--soft);color:var(--ink);white-space:nowrap}.button.compact[data-urgent]{color:var(--amber);background:var(--amber-bg)}.button.text{padding-left:0;padding-right:0;color:var(--muted)}.button svg{width:15px;height:15px}.button-row{display:flex;gap:9px;align-items:center;flex-wrap:wrap}.text-link{font-size:12px;color:var(--muted);text-decoration:underline;text-underline-offset:3px}.back-link{display:inline-flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);margin-bottom:30px;min-height:30px}.back-link svg{width:15px;height:15px}
|
|
8
|
-
.app-detail-head{display:flex;gap:22px;align-items:center;margin-bottom:30px}.app-detail-head h1{font-size:32px;letter-spacing:-1px}.app-detail-head p{font-size:13px;margin-top:7px}.detail-meta{display:flex;gap:12px;align-items:center;margin-top:11px}.detail-meta>span{font-size:11px;color:var(--muted)}.detail-grid{display:grid;grid-template-columns:minmax(0,1fr) 258px;gap:25px;align-items:start}.connection-card{border:1px solid var(--line);border-radius:16px;overflow:hidden}.connection-stage{padding:31px}.stage-icon{width:42px;height:42px;border-radius:50%;background:var(--soft);display:grid;place-items:center;margin-bottom:21px}.stage-icon svg{width:21px;height:21px}.connection-stage[data-tone=success]{background:linear-gradient(135deg,var(--good-bg),var(--surface) 80%)}.connection-stage[data-tone=success] .stage-icon{color:var(--good);background:var(--good-bg);border:1px solid color-mix(in srgb,var(--good) 15%,transparent)}.connection-stage[data-tone=attention] .stage-icon{color:var(--amber);background:var(--amber-bg)}.connection-stage[data-tone=working] .stage-icon{color:var(--blue);background:var(--blue-bg)}.connection-stage h2{font-size:24px;letter-spacing:-.7px;max-width:440px}.connection-stage>p{font-size:13px;line-height:1.7;margin:10px 0 22px;max-width:430px}.connection-facts{border-top:1px solid var(--line);padding:9px 24px;background:var(--surface)}.fact{display:flex;justify-content:space-between;align-items:baseline;gap:20px;padding:12px 0;border-bottom:1px solid var(--line);font-size:12px}.fact:last-child{border:0}.fact dt{color:var(--muted)}.fact dd{margin:0;text-align:right;overflow-wrap:anywhere}.detail-aside{border:1px solid var(--line);border-radius:13px;padding:23px}.detail-aside h3{font-size:13px}.detail-aside p{font-size:12px;line-height:1.7;margin-top:10px}.detail-aside ul{padding-left:17px;margin:12px 0;color:var(--muted);font-size:12px}.detail-aside li{margin:8px 0}.detail-aside .divider{margin:20px 0}.detail-section{margin-top:27px}.detail-section>h2{font-size:16px;margin-bottom:13px}.help-note{display:flex;gap:10px;align-items:flex-start;color:var(--muted);font-size:12px;line-height:1.7;padding:15px 18px;background:var(--soft);border-radius:10px;margin-top:18px}.help-note svg{width:17px;height:17px;margin-top:2px}.manage-actions{display:flex;flex-wrap:wrap;gap:5px 17px}.manage-actions button{font-size:12px;color:var(--muted);min-height:40px}.diagnostics{margin-top:24px;font-size:11px;color:var(--muted)}.diagnostics summary{cursor:pointer;min-height:36px;padding:8px 0}.diagnostics pre{white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.6 ui-monospace,monospace;background:var(--soft);border-radius:8px;padding:16px;color:var(--muted)}
|
|
9
|
-
.setup-form{display:grid;gap:14px;margin:24px 0 10px}.field{display:grid;gap:6px}.field label{font-size:12px;font-weight:550}.field small{font-size:11px;color:var(--muted);line-height:1.6}.field input,.field select,.field textarea,.account-dialog input{width:100%;min-height:43px;border:1px solid var(--line);border-radius:8px;padding:10px 12px;background:var(--surface);color:var(--ink);font-size:13px}.field textarea{min-height:80px;resize:vertical}.field-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}.form-error{font-size:12px;color:var(--amber);background:var(--amber-bg);padding:10px 13px;border-radius:7px;margin-top:12px}.pairing-code{display:block;font:12px/1.7 ui-monospace,monospace;overflow-wrap:anywhere;border:1px solid var(--line);border-radius:9px;background:var(--soft);padding:14px;margin:14px 0;color:var(--ink)}.qr-panel{display:flex;gap:24px;align-items:center;margin:23px 0}.qr-frame{width:186px;height:186px;padding:12px;flex:none;border:1px solid var(--line);border-radius:13px;background:#fff;display:grid;place-items:center;position:relative}.qr-frame img{width:160px;height:160px;object-fit:contain}.qr-panel ol{padding-left:19px;margin:0;color:var(--muted);font-size:12px;line-height:1.8}.qr-panel li{margin:10px 0}.demo-qr{position:relative;width:152px;height:152px;background:repeating-conic-gradient(#172820 0 25%,#fff 0 50%) 0/13px 13px;opacity:.22;filter:blur(1px)}.demo-qr-label{position:absolute;padding:6px 10px;background:#fff;color:#36453c;font-size:11px;border:1px solid #ddd;border-radius:5px;box-shadow:0 2px 12px #fff}.device-code{font:24px/1.4 ui-monospace,monospace;letter-spacing:4px;padding:18px;background:var(--soft);border:1px solid var(--line);border-radius:10px;text-align:center;margin-bottom:15px}.demo-controls{margin-top:26px;display:flex;align-items:center;gap:10px;padding:12px 15px;border:1px dashed var(--line);border-radius:9px;font-size:11px;color:var(--muted);flex-wrap:wrap}.demo-controls select{border:1px solid var(--line);background:var(--surface);border-radius:5px;padding:7px;font-size:12px;color:var(--ink);min-width:0}.demo-controls span{flex:1}
|
|
10
|
-
.empty-state{padding:55px 25px;text-align:center;border:1px dashed var(--line);border-radius:13px}.empty-state .stage-icon{margin:0 auto 16px}.empty-state h2{font-size:19px}.empty-state p{font-size:13px;max-width:370px;margin:10px auto 20px;line-height:1.7}.overview-hero{background:var(--soft);border-radius:18px;padding:35px;display:flex;justify-content:space-between;align-items:center;gap:35px;margin-bottom:26px}.overview-hero h2{font-size:29px;line-height:1.25;letter-spacing:-.8px;max-width:380px}.overview-hero p{font-size:13px;margin:13px 0 23px;max-width:380px;line-height:1.7}.orbit-art{width:150px;height:150px;position:relative;flex:none;display:grid;place-items:center;color:var(--accent)}.orbit-art:before,.orbit-art:after{content:'';position:absolute;inset:20px;border:1px solid color-mix(in srgb,var(--accent) 30%,transparent);border-radius:50%;transform:rotate(-30deg) scaleX(1.35)}.orbit-art:after{transform:rotate(50deg) scaleX(1.35)}.orbit-art svg{width:30px;height:30px}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.stat{border:1px solid var(--line);border-radius:12px;padding:20px}.stat strong{display:block;font-size:28px;font-weight:500;letter-spacing:-.8px}.stat span{display:block;font-size:12px;color:var(--muted);margin-top:3px}.attention-list{border:1px solid var(--line);border-radius:12px;overflow:hidden}.attention-row{display:flex;align-items:center;gap:13px;padding:17px 20px;border-bottom:1px solid var(--line)}.attention-row:last-child{border:0}.attention-row>div{flex:1}.attention-row h3{font-size:13px}.attention-row p{font-size:12px;margin-top:3px}.attention-row .button{flex:none}
|
|
11
|
-
.mode-banner{padding:9px 48px;background:var(--amber-bg);color:var(--amber);display:flex;justify-content:space-between;align-items:center;gap:15px;font-size:11px;line-height:1.6}.mode-banner a{font-weight:550;text-decoration:underline;text-underline-offset:3px;white-space:nowrap}.load-notice{margin:20px 48px 0;padding:13px 16px;background:var(--amber-bg);color:var(--amber);border-radius:9px;font-size:12px}.load-notice button{font-weight:600;text-decoration:underline;margin-left:8px}.toast{position:fixed;bottom:26px;left:calc(50% + 122px);transform:translateX(-50%);background:var(--ink);color:var(--page);border-radius:10px;padding:12px 20px;font-size:12px;z-index:80;box-shadow:var(--shadow);max-width:min(550px,calc(100vw - 30px))}.account-dialog{border:1px solid var(--line);border-radius:18px;padding:28px;color:var(--ink);background:var(--surface);width:400px;max-width:calc(100vw - 32px);box-shadow:var(--shadow)}.account-dialog::backdrop{background:#1116;backdrop-filter:blur(3px)}.dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:15px}.account-dialog p{font-size:13px;line-height:1.7;margin:12px 0 20px}.account-dialog label{display:block;font-size:12px;margin:16px 0 7px}.account-dialog .button{margin-top:12px}.account-dialog .demo-account-link{font-size:12px;display:block;padding-top:20px;margin-top:20px;border-top:1px solid var(--line)}.divider{border:0;border-top:1px solid var(--line)}.settings-group{border:1px solid var(--line);border-radius:13px;padding:5px 23px;max-width:740px;margin-top:23px}.settings-row{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:21px 0;border-bottom:1px solid var(--line)}.settings-row:last-child{border:0}.settings-row h3{font-size:13px}.settings-row p{font-size:12px;margin-top:4px}.settings-row select{border:1px solid var(--line);padding:8px 12px;background:var(--surface);color:var(--ink);border-radius:7px;font-size:12px}.galaxy-frame{width:100%;height:calc(100dvh - 220px);min-height:420px;border:1px solid var(--line);border-radius:16px;background:var(--soft)}.skeleton-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.skeleton-grid>div{height:180px;border:1px solid var(--line);border-radius:13px;background:linear-gradient(110deg,var(--soft),var(--page),var(--soft));background-size:250% 100%;animation:shimmer 2s infinite}.spinner{animation:spin 1.6s linear infinite}.skip-link{position:fixed;top:-60px;left:16px;z-index:100;padding:12px 18px;background:var(--ink);color:var(--page);border-radius:7px}.skip-link:focus{top:12px}.mobile-menu{display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@keyframes spin{to{transform:rotate(360deg)}}@keyframes shimmer{to{background-position:-250% 0}}
|
|
12
|
-
@media(min-width:1600px){.workspace{padding-top:55px}}
|
|
13
|
-
@media(max-width:1150px){.sidebar{width:212px;padding-left:13px;padding-right:13px}main{margin-left:212px}.topbar{padding:0 30px}.workspace{padding:34px 30px 60px}.app-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.detail-grid{grid-template-columns:minmax(0,1fr) 225px;gap:18px}.connection-stage{padding:26px}.feature-card{padding:20px;min-height:185px}.feature-card h3{font-size:18px}.mode-banner{padding-left:30px;padding-right:30px}.load-notice{margin-left:30px;margin-right:30px}.toast{left:calc(50% + 106px)}}
|
|
14
|
-
@media(max-width:880px){.detail-grid{grid-template-columns:1fr}.detail-aside{display:grid;grid-template-columns:1fr 1fr;gap:20px}.detail-aside .divider{display:none}.feature-grid{gap:10px}.feature-card{padding:16px;min-height:184px}.feature-card .app-icon{width:36px;height:36px}.feature-card h3{font-size:16px}.toolbar{align-items:flex-start;flex-direction:column;gap:15px}.search{max-width:none;width:100%}.overview-hero{padding:27px}.orbit-art{width:100px;height:100px}.overview-hero h2{font-size:24px}}
|
|
15
|
-
@media(max-width:700px){.sidebar{transform:translateX(-100%);width:260px;transition:transform .18s;box-shadow:var(--shadow);padding-top:28px}.sidebar[data-open]{transform:none}main{margin-left:0}.topbar{height:64px;padding:0 19px;position:sticky;top:0;background:var(--page);z-index:20}.mobile-menu{display:flex}.breadcrumb{margin-right:auto;font-size:11px;gap:8px}.breadcrumb>span:first-child,.breadcrumb>span:nth-child(2){display:none}.topbar-actions{gap:7px}.connection-indicator{display:none}.workspace{padding:29px 22px 45px}h1{font-size:31px}.page-heading{margin-bottom:24px}.page-heading>p{max-width:320px;font-size:13px;line-height:1.7}.eyebrow{font-size:9px;margin-bottom:10px}.feature-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.feature-card{padding:14px 12px;min-height:157px;border-radius:11px}.feature-card h3{font-size:14px;line-height:1.35}.feature-card p{font-size:10px;margin-top:6px}.feature-category,.feature-arrow{display:none}.feature-top{margin-bottom:16px}.feature-card .app-icon{width:32px;height:32px;border-radius:8px}.feature-card .app-icon img{width:22px;height:22px}.toolbar{margin-top:25px;margin-bottom:17px;gap:13px}.filters{gap:1px;flex-wrap:nowrap;width:100%}.filter{padding:9px 10px;font-size:11px;min-height:42px}.search{height:44px}.search input{font-size:13px}.search kbd{display:none}.app-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.app-card{padding:16px 13px 13px;border-radius:11px}.app-card-top{gap:9px}.app-card .app-icon{width:35px;height:35px;border-radius:9px}.app-card .app-icon img{width:23px;height:23px}.app-card-name h3{font-size:12px}.app-card-name span{font-size:10px}.app-description{font-size:11px;margin:13px 0 15px}.app-card-bottom{align-items:flex-start;flex-direction:column;gap:10px}.button.compact{min-height:40px;width:100%;font-size:11px}.status-label{font-size:10px}.button{min-height:44px}.mode-banner{padding:10px 22px;font-size:10px;align-items:flex-start}.mode-banner>span{max-width:240px}.load-notice{margin:14px 22px 0;font-size:12px}.nav-scrim{position:fixed;inset:0;z-index:25;background:#0005;backdrop-filter:blur(2px)}.toast{left:50%;bottom:18px;width:max-content;max-width:calc(100vw - 32px)}.back-link{margin-bottom:20px;min-height:40px}.app-detail-head{gap:17px;margin-bottom:25px}.app-detail-head h1{font-size:27px}.app-detail-head p{font-size:12px;line-height:1.6}.app-icon.large{width:63px;height:63px;border-radius:16px}.app-icon.large img{width:37px;height:37px}.connection-stage{padding:25px 22px}.connection-stage h2{font-size:23px;line-height:1.3}.connection-stage>p{font-size:13px}.connection-facts{padding:7px 21px}.fact{font-size:12px;gap:12px}.detail-aside{grid-template-columns:1fr;padding:21px;gap:13px}.detail-aside .divider{display:block;margin:8px 0}.qr-panel{flex-direction:column;align-items:stretch;gap:15px}.qr-frame{align-self:center}.qr-panel ol{font-size:13px}.field-row{grid-template-columns:1fr}.overview-hero{padding:25px}.overview-hero h2{font-size:24px}.orbit-art{display:none}.stats{gap:9px}.stat{padding:16px 12px}.stat strong{font-size:24px}.stat span{font-size:11px}.attention-row{padding:15px;flex-wrap:wrap;gap:11px}.attention-row>div{min-width:150px}.attention-row .button{margin-left:53px}.settings-group{padding:2px 18px}.settings-row{gap:14px}.galaxy-frame{height:calc(100dvh - 225px)}.heading-row{align-items:flex-start}.section-heading{margin-top:27px}.skeleton-grid{grid-template-columns:1fr 1fr}.skeleton-grid>div:last-child{display:none}}
|
|
16
|
-
@media(max-width:380px){.workspace{padding-left:17px;padding-right:17px}.feature-card h3{font-size:12px}.feature-card p{font-size:9px}.app-card-top{align-items:flex-start;flex-direction:column}.filter{padding-left:8px;padding-right:8px}.detail-meta{flex-wrap:wrap;gap:7px}}
|
|
17
|
-
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
|
|
18
|
-
/* Product-owned setup outcomes stay visible beside the next action. */
|
|
19
|
-
.connection-guidance{margin:18px 0;padding:14px 16px;text-align:left;border:1px solid var(--line);border-radius:12px;background:var(--soft)}
|
|
20
|
-
.connection-guidance p{margin:0;font-size:13px;line-height:1.6}
|
|
21
|
-
.connection-guidance p+p{margin-top:6px}
|
|
22
|
-
.sync-details{border:1px solid var(--line);border-radius:12px;overflow:hidden}
|
|
23
|
-
.sync-details summary{padding:17px 20px;font-size:14px;cursor:pointer}
|
|
24
|
-
.sync-details summary span{float:right;color:var(--muted);font-size:12px;max-width:62%;text-align:right}
|
|
25
|
-
.sync-notes{padding:16px 20px;border-top:1px solid var(--line)}
|
|
26
|
-
.sync-notes p{font-size:12px;line-height:1.7}.sync-notes p+p{margin-top:8px}
|
|
27
|
-
.sidebar .zx-language{display:block;width:calc(100% - 18px);min-height:40px;margin:8px 9px 1px;padding:8px 10px;border:1px solid var(--line);border-radius:8px;background:var(--sidebar);color:var(--muted);font:inherit;font-size:12px;cursor:pointer}
|
|
28
|
-
.workspace-status{font-size:12px;line-height:1.6;margin-top:15px}
|
|
29
|
-
.account-button>span:nth-child(2){min-width:0;flex:1}.account-button strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
30
|
-
@media(max-width:700px){
|
|
31
|
-
.feature-grid{display:flex;overflow-x:auto;gap:12px;scroll-snap-type:x proximity;padding:1px 0 12px;scrollbar-width:thin}
|
|
32
|
-
.feature-card{flex:0 0 min(80%,280px);min-height:182px;padding:21px;scroll-snap-align:start}
|
|
33
|
-
.feature-card h3{font-size:20px}.feature-card p{font-size:13px;line-height:1.6}.feature-card .app-icon{width:38px;height:38px}
|
|
34
|
-
.feature-top{margin-bottom:18px}.feature-arrow{display:block}.feature-category{display:none}
|
|
35
|
-
.app-card-name h3{font-size:14px}.app-card-name span{font-size:11px}.app-description{font-size:13px;line-height:1.6}
|
|
36
|
-
.status-label{font-size:11px}.button,.button.compact{font-size:13px}.filters{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:3px}.filter{font-size:12px;padding:8px 7px;white-space:normal;line-height:1.35}
|
|
37
|
-
.search input,.field input,.field textarea,.field select,.account-dialog input,.settings-row select{font-size:16px}
|
|
38
|
-
.mode-banner{font-size:12px}.demo-badge{font-size:11px}.eyebrow{font-size:10px}
|
|
39
|
-
}
|
|
1
|
+
/* Product-only states around the unchanged original demo shell. */
|
|
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}}
|
|
4
|
+
/* Language choice, just above the account row in the sidebar. */
|
|
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
|
+
#sidebar .zx-language option{color:#202020;background:#fff}
|
|
40
7
|
|
|
41
|
-
/*
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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{mergeApps,safeAuthorizationUrl,safeAuthorizationImage}from"./app-model.js";import{appIdentity,featuredApps,modCatalog,lightMonochromeIconPaths}from"./app-catalog.js";import{createConnectionClient,runConnectionAction}from"./connection-client.js";import{setupFor,setupRequest}from"./connection-forms.js";import{syncFacts,syncSummary,syncNotes,engineSyncLine}from"./sync-model.js";const $=id=>document.getElementById(id),root=document.documentElement;const esc=value=>String(value??"").replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c]);const paths={search:'<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4 4"/>',check:'<path d="m5 12 4 4L19 6"/>',arrow:'<path d="M5 12h14m-6-6 6 6-6 6"/>',back:'<path d="M19 12H5m6-6-6 6 6 6"/>',link:'<path d="m10 14 4-4m-6 6-2 2a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0m2-2 2-2a4 4 0 0 1 6 6l-5 5a4 4 0 0 1-6 0" transform="translate(1 1)"/>',info:'<circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-10v.1"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',refresh:'<path d="M20 7v5h-5M4 17v-5h5M6 6a8 8 0 0 1 13 3M5 15a8 8 0 0 0 13 3"/>',grid:'<rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="3" width="7" height="7" rx="2"/><rect x="3" y="14" width="7" height="7" rx="2"/><rect x="14" y="14" width="7" height="7" rx="2"/>',orbit:'<ellipse cx="12" cy="12" rx="10" ry="5" transform="rotate(-35 12 12)"/><circle cx="12" cy="12" r="2.4"/>',lock:'<rect x="5" y="10" width="14" height="11" rx="3"/><path d="M8 10V7a4 4 0 0 1 8 0v3m-4 5v2"/>',qr:'<path d="M3 3h6v6H3zM15 3h6v6h-6zM3 15h6v6H3zM15 15h2v2h-2zM19 17h2v4h-4v-2h-2"/>'};const svg=(name,cls="")=>'<svg class="'+cls+'" viewBox="0 0 24 24" aria-hidden="true">'+(paths[name]||paths.grid)+"</svg>";const integer=n=>Number.isSafeInteger(n)?n.toLocaleString():"Not available";const state={runtime:null,snapshot:null,abilities:{apps:[]},report:null,apps:[],filter:"all",query:"",busy:new Set,errors:new Map,setup:new Set,forms:new Map,pairings:new Map,notice:"",route:"",account:{state:"signed_out"},accountRequested:"",theme:"system"};let demo,demoScenarios=[],request,refreshing,pollTimer,toastTimer,disposed=false;const lifetime=new AbortController;const media=matchMedia("(max-width:700px)");function theme(value){state.theme=value;root.dataset.theme=value==="system"?matchMedia("(prefers-color-scheme:dark)").matches?"dark":"light":value;try{localStorage.setItem("zortex-ui-theme",value)}catch{}}try{theme(localStorage.getItem("zortex-ui-theme")||"system")}catch{theme("system")}matchMedia("(prefers-color-scheme:dark)").addEventListener("change",()=>{if(state.theme==="system")theme("system")});function nav(open){$("sidebar").toggleAttribute("data-open",open);$("nav-scrim").hidden=!open;const drawer=media.matches;$("sidebar").inert=drawer&&!open;$("main-content").inert=drawer&&open;$("mobile-menu").setAttribute("aria-expanded",String(open));if(drawer&&open){$("sidebar").setAttribute("role","dialog");$("sidebar").setAttribute("aria-modal","true");$("sidebar").querySelector("a")?.focus()}else{$("sidebar").removeAttribute("role");$("sidebar").removeAttribute("aria-modal")}}media.addEventListener("change",()=>nav(false));nav(false);$("mobile-menu").onclick=()=>nav(!$("sidebar").hasAttribute("data-open"));$("nav-scrim").onclick=()=>{nav(false);$("mobile-menu").focus()};function toast(text){clearTimeout(toastTimer);$("toast").textContent=text;$("toast").hidden=false;toastTimer=setTimeout(()=>$("toast").hidden=true,5e3)}function route(){let value;try{value=decodeURIComponent(location.hash.slice(1))}catch{value="apps"}if(value==="main-content")return state.route||"apps";const[page,id]=value.split("/");const aliases={home:"overview",engine:"apps",store:"mods",about:"settings",ais:"settings"};const clean=aliases[page]||page||"apps";return["apps","mods","galaxy","overview","settings"].includes(clean)?clean+(id&&/^[a-z0-9._-]+$/i.test(id)?"/"+id:""):"apps"}function go(path){if(location.hash==="#"+path)render(true);else location.hash=path}function icon(app,large=false){const id=appIdentity(app.id,app).icon;if(id==="galaxy")return'<span class="app-icon '+(large?"large":"")+'">'+svg("orbit")+"</span>";let path=state.abilities.localIconPaths?.[id]||state.abilities.localIconPaths?.[app.id];if(!path){const alias=state.abilities.iconAliases?.[id]||id,kind=state.abilities.iconSources?.[alias];if(kind)path="icons/"+alias+(kind==="s"?".svg":".png")}if(path&&!/^(?:icons\/(?:local\/)?[a-z0-9-]+\.(?:svg|png))$/.test(path))path=null;return'<span class="app-icon '+(large?"large ":"")+(!path?"letter":lightMonochromeIconPaths.has(path)?"monochrome":"")+'">'+(path?'<img src="'+esc(path)+'" alt="" loading="lazy">':esc(appIdentity(app.id,app).name.charAt(0)))+"</span>"}function status(view){return'<span class="status-label" data-tone="'+esc(view.tone)+'">'+esc(view.status)+"</span>"}function button(label,action,source,kind="primary",extras=""){return'<button type="button" class="button '+kind+'" data-action="'+esc(action)+'" data-source="'+esc(source)+'" '+(state.busy.has(source)?'disabled aria-busy="true"':"")+" "+extras+">"+esc(state.busy.has(source)?"Working\u2026":label)+"</button>"}function heading(title,description,eyebrow="YOUR WORKSPACE"){return'<div class="page-heading"><span class="eyebrow">'+esc(eyebrow)+'</span><h1 tabindex="-1">'+esc(title)+"</h1><p>"+esc(description)+"</p></div>"}function actionLabel(app){return!state.runtime?.canConnect&&!demo&&!["open","refresh"].includes(app.view.action)?"View setup":app.view.actionLabel}function appCard(app){const identity=appIdentity(app.id,app),view=app.view;return'<article class="app-card" data-app-id="'+esc(app.id)+'"><a class="app-card-top" href="#apps/'+esc(app.id)+'">'+icon(app)+'<div class="app-card-name"><h3 data-no-translate>'+esc(identity.name)+"</h3><span>"+esc(identity.category)+'</span></div></a><p class="app-description">'+esc(identity.description)+'</p><div class="app-card-bottom">'+status(view)+button(actionLabel(app),"primary",app.id,"compact",view.attention?"data-urgent":"")+"</div></article>"}function featured(){return'<div class="feature-grid">'+featuredApps.map(id=>state.apps.find(app=>app.id===id)).filter(Boolean).map(app=>{const identity=appIdentity(app.id,app);return'<a class="feature-card" data-app="'+esc(app.id)+'" href="#apps/'+esc(app.id)+'"><div class="feature-top">'+icon(app)+'<span class="feature-category">'+esc(identity.category.toUpperCase())+'</span><span class="feature-arrow" aria-hidden="true">'+svg("arrow","outbound-arrow")+"</span></div><h3 data-no-translate>"+esc(identity.name)+"</h3><p>"+esc(identity.description)+"</p></a>"}).join("")+"</div>"}function matches(app){const id=appIdentity(app.id,app);return(state.filter==="all"||state.filter==="connected"&&app.view.connected||state.filter==="attention"&&app.view.attention)&&(!state.query||(id.name+" "+id.description+" "+id.category).toLowerCase().includes(state.query.toLowerCase().trim()))}function catalog(){const connected=state.apps.filter(a=>a.view.connected).length,attention=state.apps.filter(a=>a.view.attention).length;return heading("Apps","Everything you use, a little more connected.")+featured()+'<div class="toolbar"><div class="filters" aria-label="Filter apps">'+[["all","All apps",state.apps.length],["connected","Connected",connected],["attention","Needs attention",attention]].map(([id,label,count])=>'<button type="button" class="filter" data-filter="'+id+'" aria-pressed="'+(state.filter===id)+'">'+label+"<span>"+count+"</span></button>").join("")+'</div><label class="search">'+svg("search")+'<input id="app-search" type="search" placeholder="Search apps" aria-label="Search apps" autocomplete="off" value="'+esc(state.query)+'"><kbd aria-hidden="true">/</kbd></label></div><div id="catalog-content">'+catalogContent()+"</div>"}function catalogContent(){const apps=state.apps.filter(matches);return apps.length?'<p class="catalog-label">'+(state.query?apps.length+" matching apps":state.filter==="connected"?"Your connected apps":state.filter==="attention"?"A little attention goes a long way":"Find your next connection")+'</p><div class="app-grid">'+apps.map(appCard).join("")+"</div>":empty("No apps found",state.query?"Try another name or clear your filters.":state.filter==="connected"?"Connect your first app to bring its context into your workspace.":state.filter==="attention"?"Your apps don\u2019t need any attention right now.":"The app catalog is unavailable. Refresh to try again.",button("Show all apps","clear","","secondary"))}function empty(title,description,actions=""){return'<div class="empty-state"><div class="stage-icon">'+svg("grid")+"</div><h2>"+esc(title)+"</h2><p>"+esc(description)+"</p>"+actions+"</div>"}function fact(label,value){return'<div class="fact"><dt>'+esc(label)+"</dt><dd>"+esc(value)+"</dd></div>"}function commonFacts(app){const c=app.coverage,r=app.report,view=app.view;let check="Not checked yet";if(r?.read==="empty"||!r?.read&&c.readEvidence?.returned===0)check="Succeeded \xB7 no items returned";else if(r?.read==="first-record"||!r?.read&&c.readEvidence?.state==="succeeded")check="Succeeded"+(Number.isSafeInteger(r?.returned)?" \xB7 "+integer(r.returned)+" items returned":"");else if(r?.operation==="succeeded")check="Action succeeded";else if(r?.read==="failed")check="Needs another check";const actions=r?.actions??c.readiness?.actions;return'<dl class="connection-facts">'+fact("Connection",view.connected?"Connected":view.status)+(demo?fact("Workspace","Alex\u2019s sample workspace"):"")+fact("Saved records",integer(view.items))+(Number.isSafeInteger(actions)?fact("Available actions",integer(actions)):"")+fact("Latest check",check)+(c.sync?.state?fact("Sync",String(c.sync.state).replaceAll("-"," ")):"")+"</dl>"}function syncDetail(app){const sync=app.coverage.sync;if(!sync)return"";return'<section class="detail-section"><details class="sync-details"><summary>Full sync'+(syncSummary(sync)?"<span>"+esc(syncSummary(sync))+"</span>":"")+'</summary><dl class="connection-facts">'+syncFacts(sync,state.snapshot?.sync||{}).map(([label,value])=>fact(label,value)).join("")+'</dl><div class="sync-notes">'+syncNotes(state.snapshot?.sync).map(note=>"<p>"+esc(note)+"</p>").join("")+"</div></details></section>"}function formFields(definition,source){const values=state.forms.get(source)||{};return definition.fields.map(field=>{const value=values[field.name]??field.value??"",id="setup-"+field.name,attrs=' id="'+id+'" name="'+esc(field.name)+'"'+(field.required===false?"":" required")+(field.maxLength?' maxlength="'+field.maxLength+'"':"")+(field.pattern?' pattern="'+esc(field.pattern)+'"':"");const input=field.type==="select"?"<select"+attrs+">"+field.options.map(([v,label])=>'<option value="'+esc(v)+'" '+(String(value)===v?"selected":"")+">"+esc(label)+"</option>").join("")+"</select>":field.type==="textarea"?"<textarea"+attrs+' placeholder="'+esc(field.placeholder||"")+'">'+esc(value)+"</textarea>":"<input"+attrs+' type="'+field.type+'" placeholder="'+esc(field.placeholder||"")+'" value="'+esc(value)+'"'+(field.min?' min="'+field.min+'" max="'+field.max+'"':"")+">";return'<div class="field"><label for="'+id+'">'+esc(field.label)+"</label>"+input+(field.help?"<small>"+esc(field.help)+"</small>":"")+"</div>"}).join("")}function setupForm(app,definition){if(!definition)return'<div class="help-note">'+svg("info")+"<span>"+esc(app.report?.support?.nextStep||app.coverage.support?.nextStep||"This app has no manual setup form available on this computer.")+"</span></div>";if(definition.pairing)return pairingForm(app);return'<form class="setup-form" id="setup-form" data-source="'+esc(app.id)+'">'+formFields(definition,app.id)+'<p class="form-caption">Sign-in details are entered in the app\u2019s secure authorization page after setup.</p><div class="button-row"><button class="button primary" type="submit" '+(state.busy.has(app.id)?"disabled":"")+">Save and continue</button>"+button("Cancel","hide-setup",app.id,"secondary")+(app.id==="obsidian"?button("Find my vaults","discover-native-vault",app.id,"secondary"):"")+"</div></form>"}function pairingForm(app){const pair=state.pairings.get(app.id),draft=state.forms.get(app.id)||{};if(!pair)return'<p class="help-note">Open the Indra plugin in Joplin, then start pairing here. Both apps will show a fingerprint for you to compare.</p><div class="button-row">'+button("Start pairing","pair-start",app.id)+"</div>";if(pair.state!=="configured"&&pair.expiresAt&&Date.now()>=pair.expiresAt)return'<p class="form-error">This pairing code expired. Start again to get a fresh code.</p>'+button("Start again","pair-start",app.id);if(pair.state==="configured")return'<p class="help-note">Joplin is paired. Continue to verify the connection.</p>'+button("Verify note access","read",app.id);return'<div class="setup-form">'+(pair.zortexPublicKey?'<p>Paste this public key into the Indra plugin in Joplin.</p><code class="pairing-code" data-no-translate>'+esc(pair.zortexPublicKey)+"</code>":"")+(pair.fingerprint?'<p>Compare this fingerprint with Joplin. Continue only when both match.</p><code class="pairing-code" data-no-translate>'+esc(pair.fingerprint)+'</code><form id="pair-confirm" data-source="'+esc(app.id)+'"><div class="field"><label for="pair-port">Joplin port</label><input id="pair-port" name="port" type="number" min="1024" max="65535" value="'+esc(draft.port||41184)+'" required></div><div class="button-row"><button class="button primary" type="submit">Fingerprints match \xB7 Pair</button>'+button("Cancel pairing","pair-cancel",app.id,"secondary")+"</div></form>":'<form id="pair-inspect" data-source="'+esc(app.id)+'"><div class="field"><label for="plugin-key">Public key from Joplin</label><input id="plugin-key" name="pluginPublicKey" value="'+esc(draft.pluginPublicKey||"")+'" required pattern="[a-fA-F0-9]{88}" maxlength="88" autocomplete="off"></div><div class="button-row"><button class="button primary" type="submit">Compare fingerprints</button>'+button("Cancel pairing","pair-cancel",app.id,"secondary")+"</div></form>")+"</div>"}function waiting(app){const r=app.view.report||app.report||{},isQr=app.view.kind==="qr",url=safeAuthorizationUrl(r.authorizationUrl||r.signInUrl,app.id),image=safeAuthorizationImage(r.authorizationImage);let html="";if(isQr){html='<div class="qr-panel"><div class="qr-frame">'+(demo?'<div class="demo-qr" aria-hidden="true"></div><span class="demo-qr-label">Demo QR preview</span>':image?'<img src="'+esc(image)+'" alt="Scan this QR code to connect '+esc(appIdentity(app.id,app).name)+'">':"<span>Preparing your code\u2026</span>")+"</div><ol><li>Open WhatsApp on your phone.</li><li>Go to <strong>Settings \u2192 Linked devices</strong>.</li><li>Tap <strong>Link a device</strong> and scan this code.</li></ol></div>"}if(r.deviceUserCode)html+='<div class="device-code" data-no-translate aria-label="Device sign-in code">'+esc(r.deviceUserCode)+"</div>";if(url)html+='<div class="button-row"><a class="button primary" href="'+esc(url)+'" target="_blank" rel="noopener noreferrer">Continue in '+esc(appIdentity(app.id,app).name)+" "+svg("arrow")+"</a>"+button("Check connection","refresh",app.id,"secondary")+"</div>";else if(!isQr&&!demo)html+='<p class="help-note">Finish sign-in in the window that opened. You can return here at any time to check progress.</p>';if(demo)html+='<div class="button-row">'+button("Complete demo connection","demo-complete",app.id)+button("Cancel","cancel",app.id,"secondary")+'</div><p class="demo-explanation">Sample preview. No QR code or account is connected.</p>';else html+='<div class="manage-actions">'+button("Cancel connection","cancel",app.id,"text")+(isQr?button("Get a new code","restart",app.id,"text"):"")+"</div>";return html}function detail(app){const identity=appIdentity(app.id,app),v=app.view,r=app.report,c=app.coverage,definition=setupFor(app.id,r),editing=state.setup.has(app.id)||v.kind==="setup",isRemote=!state.runtime.canConnect&&!demo;const title=v.kind==="success"?identity.name+" is connected":v.title;let actions="";if(isRemote&&!["success","empty"].includes(v.kind))actions='<p class="help-note">'+svg("info")+"<span>This connection needs the app on your computer. Open Zortex there and choose Apps \u2192 "+esc(identity.name)+". Your existing data remains available here.</span></p>";else if(editing&&v.kind!=="working")actions=setupForm(app,definition);else if(["qr","waiting"].includes(v.kind))actions=waiting(app);else if(v.kind==="working")actions='<div class="button-row">'+button("Check progress","refresh",app.id,"secondary")+button("Connect manually instead","manual",app.id,"secondary")+'</div><div class="manage-actions">'+button("Cancel connection","cancel",app.id,"text")+"</div>";else if(v.connected&&!v.attention)actions='<div class="button-row">'+button("Check connection",isRemote?"refresh":"read",app.id)+'<a class="button secondary" href="#apps">Browse apps</a></div>';else actions='<div class="button-row">'+button(v.actionLabel,v.action,app.id)+(v.kind==="attention"?button("Refresh status","refresh",app.id,"secondary"):"")+"</div>";const key=v.kind==="working"?"refresh":v.kind==="qr"?"qr":v.connected&&!v.attention?"check":v.attention?"info":"link";const caps=r?.availability==="actions"||c.readiness?.basis==="actions"?"Use the actions this app makes available to your connected AI.":r?.availability==="read"||c.readEvidence?"Read connected information through your AI.":"Connect this app to make supported information and actions available to your AI.";const authorizationAvailable=r?.authorizationAvailable===true||demo&&!["joplin","google-chrome","microsoft-edge"].includes(app.id);const manageActions=(authorizationAvailable?button("Reconnect or choose an account","authorize",app.id,"text"):"")+(definition?button("Connection settings","show-setup",app.id,"text"):"")+(r?.gmailWriteAvailable?button("Enable Gmail write access","authorize-gmail-write",app.id,"text"):"")+(r?.readwiseMcpWriteAvailable?button("Enable Readwise write access","authorize-readwise-mcp",app.id,"text"):"")+(r?.reconnectSavedAvailable?button("Reconnect saved account","reconnect-saved",app.id,"text"):"");const manage=isRemote||!manageActions?"":'<section class="detail-section"><h2>Manage connection</h2><div class="manage-actions">'+manageActions+"</div></section>";const explanation=["setup","reload","attention","working","unavailable"].includes(v.kind)?[r?.message,r?.nextStep||r?.support?.nextStep].filter((text,index,all)=>typeof text==="string"&&text.trim()&&text!==v.description&&all.indexOf(text)===index).map(text=>"<p>"+esc(text)+"</p>").join(""):"";const evidence={connection:r?.connection||c.connectionState,stage:r?.state||c.progress?.stage,errorCode:r?.errorCode||c.progress?.errorCode,read:r?.read,availability:r?.availability,storedRecords:v.items};return'<a class="back-link" href="#apps">'+svg("back")+'All apps</a><header class="app-detail-head">'+icon(app,true)+'<div><h1 tabindex="-1" data-no-translate>'+esc(identity.name)+"</h1><p>"+esc(identity.description)+'</p><div class="detail-meta">'+status(v)+"<span>"+esc(identity.category)+'</span></div></div></header><div class="detail-grid"><div><section class="connection-card" aria-label="Connection status"><div class="connection-stage" data-tone="'+v.tone+'"><div class="stage-icon">'+svg(key,v.kind==="working"?"spinner":"")+"</div><h2>"+esc(title)+"</h2><p>"+esc(v.description)+"</p>"+(explanation?'<div class="connection-guidance">'+explanation+"</div>":"")+actions+(state.errors.has(app.id)?'<p class="form-error" role="alert">'+esc(state.errors.get(app.id))+"</p>":"")+"</div>"+commonFacts(app)+"</section>"+(v.kind==="empty"?'<div class="help-note">'+svg("check")+"<span>The connection worked. An empty result means this check returned no items; it doesn\u2019t require signing in again.</span></div>":"")+syncDetail(app)+manage+'<details class="diagnostics"><summary>Connection details</summary><pre data-no-translate>'+esc(JSON.stringify(evidence,null,2))+"</pre></details>"+(demo?'<div class="demo-controls"><label for="demo-scenario">Preview a state</label><select id="demo-scenario" data-source="'+esc(app.id)+'">'+demoScenarios.map(([id,label])=>'<option value="'+id+'" '+(demo.scenario(app.id)===id?"selected":"")+">"+esc(label)+"</option>").join("")+"</select><span>Sample data only</span></div>":"")+'</div><aside class="detail-aside"><div><h3>Make it part of your day</h3><p>'+esc(caps)+'</p><ul><li>Keep this app\u2019s context close.</li><li>Check connection status here.</li><li>Continue setup whenever you need.</li></ul></div><hr class="divider"><div><h3>Your account, your control</h3><p>Review the permissions on the provider\u2019s sign-in page. Only the account you authorize is connected.</p><a class="button text" href="https://zortex.me/docs/vision/connectors/connect" target="_blank" rel="noopener noreferrer">Connection guide '+svg("arrow","outbound-arrow")+"</a></div></aside></div>"}function overview(){const connected=state.apps.filter(a=>a.view.connected),attention=state.apps.filter(a=>a.view.attention);const syncLine=engineSyncLine(state.snapshot?.coverage||[]);return heading(demo?"A little more connected.":"Your workspace, together.",demo?"Welcome to Alex\u2019s sample workspace. Make yourself at home.":"Bring your apps together and keep your connections in view.")+'<section class="overview-hero"><div><span class="eyebrow">BUILT AROUND YOU</span><h2>Your everyday tools.<br>One connected workspace.</h2><p>Connect the apps you know. Give your AI the context to help with the work ahead.</p><a class="button primary" href="#apps">Explore apps '+svg("arrow")+'</a></div><div class="orbit-art">'+svg("orbit")+'</div></section><div class="stats"><div class="stat"><strong>'+connected.length+'</strong><span>Connected apps</span></div><div class="stat"><strong>'+attention.length+'</strong><span>Need attention</span></div><div class="stat"><strong>'+integer(state.snapshot?.inventory?.storedRecords??state.snapshot?.totalItems)+"</strong><span>"+(demo?"Sample records":"Saved records")+"</span></div></div>"+(syncLine?'<p class="workspace-status">'+esc(syncLine)+"</p>":"")+(attention.length?'<div class="section-heading"><h2>Pick up where you left off</h2><a href="#apps" data-attention-link>View all apps \u2192</a></div><div class="attention-list">'+attention.slice(0,3).map(app=>'<div class="attention-row">'+icon(app)+"<div><h3>"+esc(appIdentity(app.id,app).name)+"</h3><p>"+esc(app.view.status)+"</p></div>"+button(actionLabel(app),"primary",app.id,"secondary")+"</div>").join("")+"</div>":"")+'<div class="section-heading"><h2>Your connected apps</h2><a href="#apps">Manage apps \u2192</a></div>'+(connected.length?'<div class="app-grid">'+connected.slice(0,6).map(appCard).join("")+"</div>":empty("Your first connection starts here","Choose an app to bring its information and supported actions into your workspace.",'<a class="button primary" href="#apps">Explore apps</a>'))}function mods(id){const mod=modCatalog.find(m=>m.id===id);if(id&&!mod)return empty("Mod not found","This mod is not available in this workspace.",'<a class="button secondary" href="#mods">View mods</a>');if(mod)return'<a class="back-link" href="#mods">'+svg("back")+'All mods</a><header class="app-detail-head">'+icon(mod,true)+'<div><h1 tabindex="-1">Galaxy</h1><p>'+esc(mod.description)+'</p><div class="detail-meta"><span class="status-label" data-tone="success">Included</span></div></div></header><div class="connection-card"><div class="connection-stage" data-tone="success"><div class="stage-icon">'+svg("orbit")+'</div><h2>A different view of your context.</h2><p>Galaxy brings your saved records into a visual map. It uses the information already in your workspace.</p><a class="button primary" href="#galaxy">Open Galaxy '+svg("arrow")+"</a></div></div>";return heading("Mods","A few more possibilities for your workspace.")+'<div class="app-grid">'+modCatalog.map(mod2=>'<article class="app-card"><a class="app-card-top" href="#mods/'+mod2.id+'">'+icon(mod2)+'<div class="app-card-name"><h3>'+mod2.name+'</h3><span>Made by Zortex</span></div></a><p class="app-description">'+mod2.description+'</p><div class="app-card-bottom"><span class="status-label" data-tone="success">Included</span><a class="button compact" href="#mods/'+mod2.id+'">Open mod</a></div></article>').join("")+'</div><div class="help-note">'+svg("info")+"<span>Galaxy is included in this version. More mods will appear here when they are available.</span></div>"}function galaxy(){if(demo)return heading("Galaxy","Your context, seen from a different angle.")+'<section class="overview-hero"><div><span class="eyebrow">YOUR CONNECTED CONTEXT</span><h2>There\u2019s a whole world<br>in what you know.</h2><p>The live Galaxy maps records from your connected apps. This demo keeps your real data untouched.</p><a class="button primary" href="#apps">Explore sample apps '+svg("arrow")+'</a></div><div class="orbit-art">'+svg("orbit")+"</div></section>"+empty("Your real Galaxy starts with your apps","Connect an app on your computer to begin building your own record map.",'<a class="button secondary" href="https://zortex.me/install" target="_blank" rel="noopener noreferrer">Get Zortex</a>');return heading("Galaxy","A map of the context saved in your workspace.")+'<iframe class="galaxy-frame" id="galaxy-frame" title="Your Galaxy record map" src="star-graph.html"></iframe>'}function settings(){return heading("Settings","Make this workspace yours.")+'<div class="settings-group"><div class="settings-row"><div><h3>Appearance</h3><p>A familiar workspace in every light.</p></div><select id="theme" aria-label="Appearance">'+[["system","System"],["light","Light"],["dark","Dark"]].map(([id,label])=>'<option value="'+id+'" '+(state.theme===id?"selected":"")+">"+label+"</option>").join("")+'</select></div><div class="settings-row"><div><h3>Account</h3><p>'+esc(demo?"You\u2019re exploring a sample account.":state.account.email||"Sign in to your Zortex account.")+'</p></div><button class="button secondary" data-open-account type="button">'+(demo?"Leave demo":"Manage")+'</button></div><div class="settings-row"><div><h3>Workspace</h3><p>'+esc(demo?"Sample data. No accounts connected.":state.runtime.mode==="remote"?"Connected to your computer.":"Running on this computer.")+"</p></div><span>"+esc(state.snapshot?.productVersion||"Zortex")+'</span></div></div><section class="detail-section"><h2>Using Zortex with your AI</h2><p>Connect Zortex to a supported AI, then ask it to work with your connected apps.</p><a class="button text" href="https://zortex.me/docs/vision" target="_blank" rel="noopener noreferrer">Open the guide '+svg("arrow","outbound-arrow")+"</a></section>"}function updateChrome(){const demoMode=!!demo;$("demo-badge").hidden=!demoMode;$("account-label").textContent=demoMode?"Alex Morgan":state.account.email||state.runtime?.accountLabel||"Your workspace";$("avatar").textContent=demoMode?"AM":"Z";$("account-context").textContent=demoMode?"Demo account":state.runtime?.mode==="remote"?"Connected computer":"This computer";$("apps-count").textContent=state.apps.filter(a=>a.view.connected).length||"";$("connection-indicator").querySelector("span").textContent=demoMode?"Sample workspace":state.notice?"Status unavailable":state.runtime?.mode==="remote"?"Connected computer":"On this computer";$("connection-indicator").toggleAttribute("data-unavailable",!!state.notice);$("load-notice").hidden=!state.notice;$("load-notice").innerHTML=esc(state.notice)+(state.notice?'<button data-refresh type="button">Try again</button>':"");$("mode-banner").hidden=!demoMode;if(demoMode)$("mode-banner").innerHTML='<span>You\u2019re exploring a demo. Sample data, with nothing to install.</span><a href="'+esc(state.runtime.exitDemoUrl||"/account")+'">Leave demo</a>'}function render(focus=false){if(!state.runtime)return;const next=route(),changed=state.route!==next;if(!changed&&!focus&&document.activeElement?.closest(".setup-form,.account-dialog")){updateChrome();return}state.route=next;const[page,id]=next.split("/"),app=state.apps.find(a=>a.id===id);const previous=document.activeElement,selection=previous?.id==="app-search"?previous.selectionStart:null;const openedDetails=[...$("workspace").querySelectorAll("details[open]")].map(element=>element.className);const previousScroll=scrollY;$("breadcrumb").textContent=id&&app?appIdentity(id,app).name:{apps:"Apps",mods:"Mods",galaxy:"Galaxy",overview:"Overview",settings:"Settings"}[page];document.title=$("breadcrumb").textContent+" \xB7 Zortex";document.querySelectorAll("[data-nav]").forEach(link=>{if(link.dataset.nav===page)link.setAttribute("aria-current","page");else link.removeAttribute("aria-current")});if(page==="galaxy"&&!changed&&$("galaxy-frame")){updateChrome();return}$("workspace").innerHTML=page==="apps"?id?app?detail(app):empty("App not found","This app is not in the current catalog.",'<a class="button secondary" href="#apps">Browse apps</a>'):catalog():page==="overview"?overview():page==="mods"?mods(id):page==="galaxy"?galaxy():settings();$("workspace").setAttribute("aria-busy","false");updateChrome();if(changed){scrollTo(0,0);nav(false);$("workspace").querySelector("h1")?.focus({preventScroll:true})}else{for(const name of openedDetails)$("workspace").querySelector("details."+CSS.escape(name))?.setAttribute("open","");scrollTo(0,previousScroll);const focusTarget=previous?.id?$(previous.id):previous?.dataset.action?$("workspace").querySelector('[data-action="'+CSS.escape(previous.dataset.action)+'"][data-source="'+CSS.escape(previous.dataset.source||"")+'"]'):null;focusTarget?.focus({preventScroll:true});if(selection!==null&&$("app-search")?.type==="text")$("app-search").setSelectionRange(selection,selection)}}function applyData(value){if(value.snapshot)state.snapshot=value.snapshot;if(value.abilities)state.abilities=value.abilities;if(value.report)state.report=value.report;state.apps=mergeApps(state.snapshot,state.report,state.abilities.apps||[]);const priority=["gmail","google-drive","slack","notion","whatsapp-web","google-calendar","github","linear","figma"];state.apps.sort((a,b)=>(priority.indexOf(a.id)<0?100:priority.indexOf(a.id))-(priority.indexOf(b.id)<0?100:priority.indexOf(b.id))||appIdentity(a.id,a).name.localeCompare(appIdentity(b.id,b).name))}async function json(path){const res=await fetch(path,{cache:"no-store",signal:AbortSignal.any([lifetime.signal,AbortSignal.timeout(15e3)])});if(!res.ok)throw Error("This workspace is unavailable. Please refresh to try again.");return res.json()}async function refresh(draw=true){if(refreshing)return refreshing;refreshing=(async()=>{try{if(demo){applyData(await demo.read());state.notice=""}else{const jobs=[json("snapshot.json"),json("abilities.json"),state.runtime.canConnect?request({action:"status"},{signal:lifetime.signal}):Promise.resolve(null)];const results=await Promise.allSettled(jobs);const value={};if(results[0].status==="fulfilled")value.snapshot=results[0].value;if(results[1].status==="fulfilled")value.abilities=results[1].value;if(results[2].status==="fulfilled")value.report=results[2].value;applyData(value);state.notice=results.some(r=>r.status==="rejected")?"We couldn\u2019t refresh part of your workspace. Last displayed information may be out of date.":""}}catch(error){if(!disposed)state.notice="We couldn\u2019t refresh your workspace. Your existing connections are safe."}finally{refreshing=null;if(!disposed&&draw)render()}})();return refreshing}async function perform(source,action,extra={}){if(state.busy.has(source)||disposed)return;if(!demo&&!state.runtime.canConnect){go("apps/"+source);return}state.busy.add(source);state.errors.delete(source);render(true);try{const result=await runConnectionAction(request,{action,source,...extra},{signal:lifetime.signal});if(result?.pairing)state.pairings.set(source,result.pairing);if(Array.isArray(result?.sources)){state.report=result;applyData({report:result})}if(action.startsWith("configure-")&&!result?.pairing){state.setup.delete(source);toast("Setup submitted. Follow the connection progress here.")}if(action==="discover-native-vault"){const candidates=result.candidates||result.vaults||result.suggestions||[];const first=candidates.find(item=>typeof item==="string"||typeof item?.path==="string");if(first){state.forms.set(source,{roots:typeof first==="string"?first:first.path});toast("Found a notes folder. Review it before saving.")}else toast("No folder was found. Enter your folder path to continue.")}await refresh(false);if(action==="demo-complete")toast("Demo connection complete.");return result}catch(error){state.errors.set(source,error.message||"This step could not finish. Please try again.")}finally{state.busy.delete(source);render(true)}}async function primary(source){const app=state.apps.find(a=>a.id===source);if(!app)return;go("apps/"+source);const action=app.view.action;if(action==="setup"){state.setup.add(source);render();return}if(["open","continue"].includes(action)||!state.runtime.canConnect&&!demo)return;if(action==="refresh"){await refresh();return}await perform(source,action)}document.addEventListener("click",event=>{const target=event.target.closest("button,a");if(!target||target.disabled)return;if(target.dataset.nav)nav(false);if(target.hasAttribute("data-open-account")){showAccount();return}if(target.hasAttribute("data-close-account")){$("account-dialog").close();return}if(target.hasAttribute("data-refresh")){void refresh();return}const filter=target.dataset.filter;if(filter){state.filter=filter;render(true);return}if(target.hasAttribute("data-attention-link"))state.filter="attention";const{action,source=""}=target.dataset;if(!action)return;if(action==="primary"){void primary(source);return}if(action==="clear"){state.filter="all";state.query="";render(true);return}if(action==="refresh"){void refresh();return}if(action==="show-setup"||action==="setup"){state.setup.add(source);render(true);return}if(action==="hide-setup"){state.setup.delete(source);state.forms.delete(source);go("apps");return}if(action==="pair-start"){void perform(source,"configure-joplin",{selection:{phase:"start"}});return}if(action==="pair-cancel"){const p=state.pairings.get(source);if(p)void perform(source,"configure-joplin",{selection:{phase:"cancel",pairingId:p.pairingId}}).then(result=>{if(result){state.pairings.delete(source);state.forms.delete(source);render(true)}});return}void perform(source,action)});function rememberSetup(target){const form=target.closest("form");if(form&&["setup-form","pair-inspect","pair-confirm"].includes(form.id))state.forms.set(form.dataset.source,Object.fromEntries(new FormData(form)))}document.addEventListener("input",event=>{rememberSetup(event.target);if(event.target.id==="app-search"){state.query=event.target.value;const panel=$("catalog-content");if(panel)panel.innerHTML=catalogContent()}});document.addEventListener("change",event=>{rememberSetup(event.target);if(event.target.id==="theme")theme(event.target.value);if(event.target.id==="demo-scenario"&&demo){demo.preview(event.target.dataset.source,event.target.value);state.errors.delete(event.target.dataset.source);state.setup.delete(event.target.dataset.source);void refresh()}});document.addEventListener("submit",event=>{const form=event.target,source=form.dataset.source;if(form.id==="setup-form"){event.preventDefault();const app=state.apps.find(a=>a.id===source),definition=setupFor(source,app?.report);if(!definition)return;const values=Object.fromEntries(new FormData(form));state.forms.set(source,values);try{const body=setupRequest(definition,values);void perform(source,body.action,body)}catch(error){state.errors.set(source,error.message);render(true)}}if(form.id==="pair-inspect"||form.id==="pair-confirm"){event.preventDefault();const pair=state.pairings.get(source);if(!pair)return;const values=Object.fromEntries(new FormData(form));const selection=form.id==="pair-inspect"?{phase:"inspect",pairingId:pair.pairingId,pluginPublicKey:String(values.pluginPublicKey).toLowerCase()}:{phase:"confirm",pairingId:pair.pairingId,port:Number(values.port),fingerprint:pair.fingerprint};void perform(source,"configure-joplin",{selection})}});$("refresh").onclick=()=>void refresh();addEventListener("hashchange",()=>render(true));addEventListener("keydown",event=>{if(event.key==="Escape"&&$("sidebar").hasAttribute("data-open")){nav(false);$("mobile-menu").focus()}if(event.key==="/"&&!event.target.closest("input,textarea,select")){const search=$("app-search");if(search){event.preventDefault();search.focus()}}if(event.key==="Tab"&&media.matches&&$("sidebar").hasAttribute("data-open")){const items=[...$("sidebar").querySelectorAll("a,button,select")];if(event.shiftKey&&document.activeElement===items[0]){event.preventDefault();items.at(-1).focus()}else if(!event.shiftKey&&document.activeElement===items.at(-1)){event.preventDefault();items[0].focus()}}});async function accountApi(path,body){const response=await fetch("account/"+path,{method:body===void 0?"GET":"POST",headers:body===void 0?{}:{"Content-Type":"application/json","X-Zortex-Galaxy":document.querySelector('meta[name="zortex-galaxy-token"]')?.content||""},...body===void 0?{}:{body:JSON.stringify(body)},cache:"no-store",signal:lifetime.signal});const data=await response.json();if(!response.ok)throw Error("Sign-in could not finish. Please try again.");return data}function accountRender(){const signed=state.account.state==="signed_in";$("account-title").textContent=signed?"Your Zortex account":"Sign in to Zortex";$("account-description").textContent=signed?state.account.email:"Use the same account across your devices.";$("account-fields").hidden=signed;$("verify-code").hidden=signed;$("sign-out").hidden=!signed;$("verify-code").disabled=state.accountRequested!==$("account-email").value.trim()||!state.accountRequested;updateChrome()}function showAccount(){if(demo){location.href=state.runtime.exitDemoUrl||"/account";return}if(state.runtime.mode==="remote"){location.href=state.runtime.loginUrl||"https://zortex.me/account";return}accountRender();$("account-dialog").showModal()}$("account-button").onclick=showAccount;$("account-email").addEventListener("input",accountRender);$("send-code").onclick=async()=>{if(!$("account-email").reportValidity()||!$("account-email").value)return;$("send-code").disabled=true;try{const email=$("account-email").value.trim();await accountApi("request",{email});state.accountRequested=email;$("account-message").textContent="Code sent. Check your email and enter the eight digits.";accountRender();$("account-code").focus();setTimeout(()=>$("send-code").disabled=false,6e4)}catch(error){$("account-message").textContent=error.message;$("send-code").disabled=false}};$("account-form").onsubmit=async event=>{event.preventDefault();if(state.accountRequested!==$("account-email").value.trim()||!/^\d{8}$/.test($("account-code").value)){$("account-message").textContent="Request a code, then enter its eight digits.";return}$("verify-code").disabled=true;try{state.account=await accountApi("verify",{code:$("account-code").value});$("account-code").value="";$("account-message").textContent="You\u2019re signed in.";state.accountRequested="";accountRender()}catch(error){$("account-message").textContent=error.message;$("verify-code").disabled=false}};$("sign-out").onclick=async()=>{try{await accountApi("logout",{});state.account=await accountApi("status");$("account-message").textContent="You\u2019re signed out.";state.accountRequested="";accountRender()}catch(error){$("account-message").textContent=error.message}};async function boot(){try{state.runtime=await json("runtime.json");if(!["local","remote","demo"].includes(state.runtime.mode))throw Error("This app host is not available.");if(state.runtime.mode==="demo"){const module=await import("./demo.js");demo=module.createDemoWorkspace();demoScenarios=module.demoScenarios;request=demo.request}else request=createConnectionClient({token:document.querySelector('meta[name="zortex-galaxy-token"]')?.content});await refresh(false);render(true);if(state.runtime.mode==="local")void accountApi("status").then(value=>{state.account=value;updateChrome()}).catch(()=>{});const schedule=()=>{if(disposed)return;pollTimer=setTimeout(async()=>{if(!document.hidden&&!demo)await refresh();schedule()},state.apps.some(a=>["working","waiting","qr"].includes(a.view.kind))?2500:7e3)};schedule()}catch(error){$("workspace").innerHTML=empty("Your workspace couldn\u2019t open","Refresh to try again, or explore the demo while this workspace is unavailable.",'<button class="button primary" type="button" id="reload-app">Refresh workspace</button> <a class="button secondary" href="https://zortex.me/app/demo/">Try demo</a>');$("workspace").setAttribute("aria-busy","false");$("reload-app").onclick=()=>location.reload()}}addEventListener("pagehide",()=>{disposed=true;lifetime.abort();clearTimeout(pollTimer);clearTimeout(toastTimer)});void boot();
|
|
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"&¤t!=="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 @@
|
|
|
1
|
+
export const ANALYTICS_CONTRACT_VERSION="indra-activity-v1";const activities={search:["vault.search","Search local data"],context:["vault.context","Build context from local data"],sql:["vault.query","Query local data"],action:["connector.action","Run a product action"],actions:["connector.actions_list","Browse available actions"],action_result:["agent.action_result","Report an action result"],append:["vault.append","Append local data"],feedback:["agent.feedback","Report agent feedback"],manage:["product.manage","Manage the product"],done:["agent.turn_finished","Finish an agent turn"],instruction:["product.instructions","Read product instructions"],handbook:["product.handbook","Read the product handbook"],"mcp.call":["tool.call","Call a product tool"],"product.first_start":["installation.first_observed","Observe an installation for the first time"],"product.started":["product.started","Start the product"],"product.account_signed_in":["account.signed_in","Sign in to a product account"],"product.galaxy_opened":["product.galaxy_opened","Open Galaxy"],"product.feedback":["product.feedback_submitted","Submit feedback about an operation"],"product.trace":["operation.step","Observe an operational step"],"product.resources":["diagnostics.resources","Measure local resource usage"],"product.collection":["diagnostics.collection","Measure telemetry collection health"],"connector.trace":["connector.connection_step","Observe a connector step"],"connector.read":["connector.read","Read connector data"],"connector.invoke":["connector.invoke","Run a connector action"],"connector.connect":["connector.connect_requested","Request a source connection"],"connector.authorization":["connector.authorization_finished","Finish source authorization"],"connector.fabricate":["connector.fabricate","Build a connector"],"connector.usable":["connector.availability","Observe connector availability"],"connector.sync":["connector.sync","Synchronize connector data"],"connector.inventory":["diagnostics.data_inventory","Observe stored data counts"],"connector.connection":["diagnostics.connection_inventory","Observe saved connection permissions"],"flywheel.start":["automation.started","Start an automation run"],"flywheel.run":["automation.finished","Finish an automation run"]};const connectorStepLabels={source_selected:"Observe a source selection",authorization_started:"Observe source authorization",browser_opened:"Observe an authorization browser",waiting_for_user:"Observe authorization waiting for input",callback_received:"Observe an authorization callback",token_exchange:"Observe an authorization token exchange",identity_verified:"Observe source identity verification",credentials_saved:"Observe source credential storage",page_observed:"Observe an authorization page",action_selected:"Observe an authorization action selection",action_executed:"Observe an authorization action result",manual_required:"Observe an authorization handoff",automation_finished:"Observe authorization automation results",authorization_finished:"Observe a source authorization result",read_started:"Start reading connector data",read_verified:"Observe a connector read result",invoke_started:"Start a connector action",invoke_finished:"Observe a connector action result",vault_saved:"Observe local data storage",startup_failed:"Observe a product startup failure"};const primary=new Set(["search","context","sql","action","actions","append","manage","instruction","handbook","mcp.call","connector.fabricate"]);const connectorOperations=new Set(["connector.read","connector.invoke","connector.sync"]);const lifecycle=new Set(["product.first_start","product.started","product.account_signed_in","product.galaxy_opened","connector.connect","connector.authorization","flywheel.start","flywheel.run"]);export function activityProperties(operation,event,trace){const activity=Object.hasOwn(activities,operation)?activities[operation]:void 0;if(!activity)return{};const role=event==="zortex call timing"?"operation_timing":primary.has(operation)?"primary_operation":connectorOperations.has(operation)?"connector_operation":lifecycle.has(operation)?"lifecycle":"diagnostic";const label=operation==="connector.trace"&&trace&&Object.hasOwn(connectorStepLabels,trace.stage)?connectorStepLabels[trace.stage]:activity[1];return{analytics_contract_version:ANALYTICS_CONTRACT_VERSION,analytics_activity:activity[0],analytics_activity_label:label,analytics_event_role:role}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{AUTHORIZATION_REASON_CODES,TELEMETRY_OPERATIONS,FEEDBACK_OPERATIONS,FEEDBACK_RATINGS,FEEDBACK_REASONS,FEEDBACK_CHANNELS,USAGE_ERROR_CATEGORIES,isFlowId,isUsageTrace}from"@zortexhq/plugin-telemetry/api";import{Original}from"@zortexhq/plugin-connector-framework/api";import{measurementSource,SOURCE_TAXONOMY_VERSION}from"./source-taxonomy.js";import{invocationProperties,invocationTool,observationProjection}from"./observations.js";import{executionProperties,operationalProperties}from"./operational.js";import{resourceProperties}from"./resources.js";import{collectionStatusProperties}from"./collection-status.js";const tools=new Set(["search","context","sql","actions","action","manage","instruction","handbook","mcp.call"]);const outcomes=new Set(["ok","empty","fault","auth-blocked","cancelled","invalid"]);export const NORTHSTAR_LOCAL_ONLY_OPERATIONS=[];const operationalOnly=new Set(["action_result","append","feedback","done","connector.fabricate","flywheel.start","flywheel.run"]);const connectorOutcomes={x:{id:"connector-x",version:"connector-x-v1",owner:"Raven",authorLogin:"ngsanchong0801"},instagram:{id:"connector-instagram",version:"connector-instagram-v1",owner:"Raven",authorLogin:"ngsanchong0801"},linkedin:{id:"connector-linkedin",version:"connector-linkedin-v1",owner:"Raven",authorLogin:"ngsanchong0801"},whatsapp:{id:"connector-whatsapp",version:"connector-whatsapp-v1",owner:"Raven",authorLogin:"ngsanchong0801"},gmail:{id:"autopilot-gmail",version:"autopilot-gmail-v1",owner:"Raven",authorLogin:"ngsanchong0801"},"google-drive":{id:"autopilot-google-drive",version:"autopilot-google-drive-v1",owner:"Raven",authorLogin:"ngsanchong0801"}};const vaultOutcome={id:"vault-search-local",version:"vault-search-local-v1",owner:"\u4E66\u4FCA",authorLogin:"cao-unix"};const jevOutcome={id:"jev-auto-login",version:"jev-auto-login-v1",owner:"\u6D77\u6D32",authorLogin:"hhz200"};const feedbackOutcome={id:"posthog-product-feedback",version:"posthog-product-feedback-v1",owner:"\u6C9B\u9716",authorLogin:"jpl302e2"};function scoreOutcomes(row,outcome){const scored=[],success=outcome==="ok";const source=row.source==="whatsapp-web"?"whatsapp":row.source;const connectorOutcome=source&&Object.hasOwn(connectorOutcomes,source)?connectorOutcomes[source]:void 0;if(row.operation==="connector.read"&&connectorOutcome)scored.push({definition:connectorOutcome,success});if(["search","context","sql"].includes(row.operation))scored.push({definition:vaultOutcome,success});if(row.operation==="connector.authorization"){if(row.trace?.driver==="jev"&&row.trace.mode==="automatic")scored.push({definition:jevOutcome,success});const traceComplete=isUsageTrace(row.trace)&&row.trace.stage==="authorization_finished"&&["completed","failed","cancelled","unknown"].includes(row.trace.state??"");scored.push({definition:feedbackOutcome,success:traceComplete})}return scored}export function hasScoredOutcome(row){return scoreOutcomes(row,outcomes.has(row.outcome)?row.outcome:"unknown").length>0}const platforms=new Set(["darwin","win32","linux","unknown"]);const executionLocations=new Set(["local","cloud","unknown"]);const errorCategories=new Set(USAGE_ERROR_CATEGORIES);const feedbackRatings=new Set(FEEDBACK_RATINGS);const feedbackReasons=new Set(FEEDBACK_REASONS);const feedbackChannels=new Set(FEEDBACK_CHANNELS);const feedbackOperations=new Set(FEEDBACK_OPERATIONS);const version=value=>typeof value==="string"&&value.length<=64&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value);const isoTimestamp=value=>typeof value==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)&&Number.isFinite(Date.parse(value));function invocationMetadata(row,operational){const invocation=invocationProperties(row);return invocation.entrypoint==="unknown"&&typeof operational?.entrypoint==="string"?{...invocation,entrypoint:operational.entrypoint}:invocation}function contextProperties(context,prefix=""){const productVersion=version(context?.productVersion)?context.productVersion:"unknown";const platform=platforms.has(context?.platform??"")?context.platform:"unknown";const executionLocation=executionLocations.has(context?.executionLocation??"")?context.executionLocation:"unknown";const traffic=context?.trafficClass;return{[prefix+"product_version"]:productVersion,[prefix+"platform"]:platform,[prefix+"execution_location"]:executionLocation,[prefix+"capture_context_known"]:!!context&&(context.productVersion===void 0||version(context.productVersion))&&platforms.has(context.platform??"")&&executionLocations.has(context.executionLocation??""),[prefix+"capture_traffic_class"]:traffic==="usage"||traffic==="internal_test"||traffic==="simulation"?traffic:"unknown"}}function resultProperties(result,prefix=""){const count=result?.count,known=Number.isSafeInteger(count)&&count!==void 0&&count>=0&&count<=1e8;return{[prefix+"result_count_known"]:known,...known?{[prefix+"result_count"]:count,[prefix+"result_nonempty"]:count>0}:{},...typeof result?.truncated==="boolean"?{[prefix+"result_truncated"]:result.truncated}:{}}}function correlationProperties(row){const correlation=row.correlation??(isUsageTrace(row.trace)?row.trace:void 0);if(!isFlowId(correlation?.flowId))return{};return{flow_id:correlation.flowId,...isFlowId(correlation.connectionFlowId)?{connection_flow_id:correlation.connectionFlowId}:{}}}function feedbackProperties(row){const f=row.feedback,t=f?.target;if(!f||!isFlowId(f.targetReceiptId)||!feedbackRatings.has(f.rating)||!feedbackChannels.has(f.submissionChannel)||!t||!feedbackOperations.has(t.operation)||!(outcomes.has(t.outcome)||t.outcome==="unknown")||!isoTimestamp(t.at))return;const source=measurementSource(t.source);return{feedback_measurement:"receipt_usefulness_v1",target_receipt_id:f.targetReceiptId,target_at:t.at,target_operation:t.operation,target_outcome:t.outcome,target_connector:source,target_connector_known:source!=="other",rating:f.rating,feedback_reason:f.reason===void 0?"not_provided":feedbackReasons.has(f.reason)?f.reason:"unknown",submission_channel:f.submissionChannel,...contextProperties(t.context,"target_"),...resultProperties(t.result,"target_")}}const galaxyStates=new Set(["live_local","empty","vault_unavailable"]);export function northstarEvents(row,installId,verifiedGithubLogin,account,processPersonProfile=true){const projected=[],outcome=outcomes.has(row.outcome)?row.outcome:"unknown";const duration=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=6e5?Math.round(row.durationMs):void 0;const connector=measurementSource(row.source),sourceProperties={connector,connector_known:connector!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION};if(row.operation==="product.collection"){const properties=collectionStatusProperties(row);if(!properties)return[];projected.push(["zortex collection status",properties])}else if(row.operation==="product.resources"){const properties=resourceProperties(row);if(!properties)return[];projected.push(["zortex resource snapshot",properties])}else if(row.operation==="product.trace"){const properties=operationalProperties(row);if(!properties)return[];projected.push(["zortex operation step",{...sourceProperties,...properties}])}else if(row.operation==="product.feedback"){const feedback=feedbackProperties(row);if(feedback)projected.push(["zortex product feedback",feedback])}else if(row.operation==="product.account_signed_in"){projected.push(["zortex account signed in",{outcome,identity_scope:"installation"}])}else if(row.operation==="product.first_start"||row.operation==="product.started"){projected.push([row.operation==="product.first_start"?"zortex first start":"zortex started",{identity_scope:"installation",...row.operation==="product.first_start"?{new_install_known:["new_install","first_observed"].includes(row.code??""),is_new_install:row.code==="new_install"}:{}}])}else if(row.operation==="product.galaxy_opened"){projected.push(["zortex galaxy opened",{identity_scope:"installation",outcome,galaxy_state:galaxyStates.has(row.code??"")?row.code:"unknown"}])}else if(row.operation==="connector.trace"&&isUsageTrace(row.trace)){const t=row.trace;projected.push(["zortex connection step",{...sourceProperties,flow_id:t.flowId,...t.connectionFlowId?{connection_flow_id:t.connectionFlowId}:{},duration_known:t.durationKnown===true&&duration!==void 0,stage:t.stage,state:t.state??"unknown",mode:t.mode??"unknown",trigger:t.trigger??"unknown",outcome,...t.page?{page:t.page}:{},...t.action?{action:t.action}:{},...t.reason?{reason:t.reason}:{},...t.error?{error_category:t.error}:{},...t.statusCode!==void 0?{status_code:t.statusCode}:{},...t.count!==void 0?{record_count:t.count}:{},...t.elapsedMs!==void 0?{elapsed_ms:Math.round(t.elapsedMs)}:{},...t.durationKnown===true&&duration!==void 0?{duration_ms:duration}:{}}])}else if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)){const observation=observationProjection(row);if(observation)projected.push([observation.event,{...sourceProperties,...observation.properties}])}else if(tools.has(row.operation)){const tool="indra."+(invocationTool(row)??(row.operation==="mcp.call"?"unknown":row.operation)),error=!["ok","empty"].includes(outcome);const detail={...correlationProperties(row),...row.source!==void 0?sourceProperties:{},error_category:errorCategories.has(row.errorCategory??"")?row.errorCategory:"unknown"};projected.push([outcome==="auth-blocked"?"zortex refused":row.operation==="search"?"zortex delivery":"zortex call",{tool,client:"indra-v2",error,...detail}]);projected.push(["zortex call timing",{tool,error,...detail,duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{}}])}else if(row.operation==="connector.authorization"){const phase=row.outcome==="ok"?"completed":row.outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(row.outcome)?"failed":"unresolved";const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex auth journey",{...sourceProperties,phase,final:true,outcome:phase==="unresolved"?"unknown":outcome,...isUsageTrace(row.trace)?{flow_id:row.trace.flowId,connection_flow_id:row.trace.connectionFlowId??row.trace.flowId,mode:row.trace.mode??"unknown",trigger:row.trace.trigger??"unknown",...row.trace.driver?{driver:row.trace.driver}:{}}:{},...row.code?{reason:AUTHORIZATION_REASON_CODES.some(code=>code===row.code)?row.code:"provider_error"}:{},duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{}}])}else if(row.operation==="connector.connect"){projected.push(["zortex auth journey",{...sourceProperties,phase:"request_returned",outcome,...correlationProperties(row)}])}else if(["connector.read","connector.invoke","connector.usable"].includes(row.operation)){const observedOperation=row.operation!=="connector.usable",elapsed=observedOperation&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;const errorCategory=errorCategories.has(row.errorCategory??"")?row.errorCategory:isUsageTrace(row.trace)&&row.trace.error?row.trace.error:"unknown";projected.push(["zortex connector health",{...sourceProperties,plane:"query",operation:row.operation,outcome,evidence_kind:observedOperation?"operation_receipt":"query_availability",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},error_category:errorCategory,...correlationProperties(row)}])}else if(operationalOnly.has(row.operation)){const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex product operation",{...sourceProperties,evidence_kind:"operation_receipt",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},...correlationProperties(row)}])}const definitions=verifiedGithubLogin?scoreOutcomes(row,outcome):[];for(const{definition,success}of definitions){const score={score_outcome_id:definition.id,score_outcome_version:definition.version,score_owner:definition.owner,score_author_login:definition.authorLogin,score_success:success,identity_scope:"verified_human",identity_scheme:"github_api_user_v1"};projected.push(["zortex outcome attempted",score]);if(success)projected.push(["zortex outcome succeeded",score])}return projected.map(([event,properties])=>{const scoreEvent=event.startsWith("zortex outcome ");const scoreIdentity=scoreEvent?":"+String(properties.score_outcome_id):"";const hex=createHash("sha256").update("indra-v2-northstar:1:"+installId+":"+row.id+":"+event+scoreIdentity).digest("hex");const usageProperties=!scoreEvent?{install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",operation:row.operation,outcome,internal:row.internal??false,effective_usage:!row.internal&&row.outcome==="ok"&&(["search","context","sql"].includes(row.operation)||row.operation==="action"&&row.code==="effective_invoke")&&["zortex delivery","zortex call"].includes(event),usage_measurement:"successful_tool_receipt_v1",...isFlowId(row.id)?{receipt_id:row.id}:{},...contextProperties(row.context),...resultProperties(row.result),...invocationMetadata(row,event==="zortex operation step"?properties:void 0),...executionProperties(row)}:{};const eventAccount=row.operation==="product.feedback"?void 0:account;const accountProperties=eventAccount&&!scoreEvent?{distinct_id:`zortex-account:${eventAccount.id}`,identity_scope:"verified_email_account",identity_scheme:"zortex_email_v1",account_registered_at:new Date(eventAccount.registeredAt*1e3).toISOString()}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{product:"indra-v2",identity_scope:eventAccount?"verified_email_account":"installation",identity_scheme:eventAccount?"zortex_email_v1":"random_install_v1"}}:{};return{event,uuid:`${hex.slice(0,8)}-${hex.slice(8,12)}-5${hex.slice(13,16)}-a${hex.slice(17,20)}-${hex.slice(20,32)}`,timestamp:row.at,properties:{distinct_id:scoreEvent?`github:${verifiedGithubLogin}`:installId,$process_person_profile:profileEnabled,$geoip_disable:true,product:"indra-v2",schema_version:scoreEvent?2:1,...properties,...usageProperties,...accountProperties,...profileProperties}}})}const rawCodes=new Set([...AUTHORIZATION_REASON_CODES,...Original.ERROR_CODES,"effective_invoke","new_install","first_observed",...galaxyStates]);export function rawUsageEvents(row,installId){if(!TELEMETRY_OPERATIONS.includes(row.operation))return[];const operational=row.operation==="product.trace"?operationalProperties(row):void 0;if(row.operation==="product.trace"&&!operational)return[];const resource=row.operation==="product.resources"?resourceProperties(row):void 0;if(row.operation==="product.resources"&&!resource)return[];const collectionStatus=row.operation==="product.collection"?collectionStatusProperties(row):void 0;if(row.operation==="product.collection"&&!collectionStatus)return[];const observation=["connector.sync","connector.inventory","connector.connection"].includes(row.operation)?observationProjection(row):void 0;if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)&&!observation)return[];const duration=(!operational||operational.duration_known===true)&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?row.durationMs:void 0;return[{event:"zortex."+row.operation,uuid:row.id,timestamp:row.at,properties:{distinct_id:installId,install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",$process_person_profile:false,$geoip_disable:true,operation:row.operation,outcome:outcomes.has(row.outcome)?row.outcome:"unknown",duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{},internal:row.internal??false,...row.source!==void 0?{source:measurementSource(row.source),source_known:measurementSource(row.source)!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION}:{},...row.code!==void 0?{code:rawCodes.has(row.code)?row.code:"unknown",code_known:rawCodes.has(row.code)}:{},...contextProperties(row.context),...resultProperties(row.result),...correlationProperties(row),...executionProperties(row),...observation?.properties??{},...operational??{},...resource??{},...collectionStatus??{},...invocationMetadata(row,operational)}}]}
|
|
1
|
+
import{createHash}from"node:crypto";import{AUTHORIZATION_REASON_CODES,TELEMETRY_OPERATIONS,FEEDBACK_OPERATIONS,FEEDBACK_RATINGS,FEEDBACK_REASONS,FEEDBACK_CHANNELS,USAGE_ERROR_CATEGORIES,isFlowId,isUsageTrace}from"@zortexhq/plugin-telemetry/api";import{Original}from"@zortexhq/plugin-connector-framework/api";import{measurementSource,SOURCE_TAXONOMY_VERSION}from"./source-taxonomy.js";import{invocationProperties,invocationTool,observationProjection}from"./observations.js";import{executionProperties,operationalProperties}from"./operational.js";import{resourceProperties}from"./resources.js";import{collectionStatusProperties}from"./collection-status.js";import{activityProperties}from"./activity.js";const tools=new Set(["search","context","sql","actions","action","manage","instruction","handbook","mcp.call"]);const outcomes=new Set(["ok","empty","fault","auth-blocked","cancelled","invalid"]);export const NORTHSTAR_LOCAL_ONLY_OPERATIONS=[];const operationalOnly=new Set(["action_result","append","feedback","done","connector.fabricate","flywheel.start","flywheel.run"]);const connectorOutcomes={x:{id:"connector-x",version:"connector-x-v1",owner:"Raven",authorLogin:"ngsanchong0801"},instagram:{id:"connector-instagram",version:"connector-instagram-v1",owner:"Raven",authorLogin:"ngsanchong0801"},linkedin:{id:"connector-linkedin",version:"connector-linkedin-v1",owner:"Raven",authorLogin:"ngsanchong0801"},whatsapp:{id:"connector-whatsapp",version:"connector-whatsapp-v1",owner:"Raven",authorLogin:"ngsanchong0801"},gmail:{id:"autopilot-gmail",version:"autopilot-gmail-v1",owner:"Raven",authorLogin:"ngsanchong0801"},"google-drive":{id:"autopilot-google-drive",version:"autopilot-google-drive-v1",owner:"Raven",authorLogin:"ngsanchong0801"}};const vaultOutcome={id:"vault-search-local",version:"vault-search-local-v1",owner:"\u4E66\u4FCA",authorLogin:"cao-unix"};const jevOutcome={id:"jev-auto-login",version:"jev-auto-login-v1",owner:"\u6D77\u6D32",authorLogin:"hhz200"};const feedbackOutcome={id:"posthog-product-feedback",version:"posthog-product-feedback-v1",owner:"\u6C9B\u9716",authorLogin:"jpl302e2"};function scoreOutcomes(row,outcome){const scored=[],success=outcome==="ok";const source=row.source==="whatsapp-web"?"whatsapp":row.source;const connectorOutcome=source&&Object.hasOwn(connectorOutcomes,source)?connectorOutcomes[source]:void 0;if(row.operation==="connector.read"&&connectorOutcome)scored.push({definition:connectorOutcome,success});if(["search","context","sql"].includes(row.operation))scored.push({definition:vaultOutcome,success});if(row.operation==="connector.authorization"){if(row.trace?.driver==="jev"&&row.trace.mode==="automatic")scored.push({definition:jevOutcome,success});const traceComplete=isUsageTrace(row.trace)&&row.trace.stage==="authorization_finished"&&["completed","failed","cancelled","unknown"].includes(row.trace.state??"");scored.push({definition:feedbackOutcome,success:traceComplete})}return scored}export function hasScoredOutcome(row){return scoreOutcomes(row,outcomes.has(row.outcome)?row.outcome:"unknown").length>0}const platforms=new Set(["darwin","win32","linux","unknown"]);const executionLocations=new Set(["local","cloud","unknown"]);const errorCategories=new Set(USAGE_ERROR_CATEGORIES);const feedbackRatings=new Set(FEEDBACK_RATINGS);const feedbackReasons=new Set(FEEDBACK_REASONS);const feedbackChannels=new Set(FEEDBACK_CHANNELS);const feedbackOperations=new Set(FEEDBACK_OPERATIONS);const version=value=>typeof value==="string"&&value.length<=64&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value);const isoTimestamp=value=>typeof value==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)&&Number.isFinite(Date.parse(value));const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function eventAccountIdentity(account,at){if(!account||typeof account.id!=="string"||!accountIdPattern.test(account.id)||!Number.isSafeInteger(account.registeredAt)||account.registeredAt<0)return;const registered=account.registeredAt*1e3,eventTime=Date.parse(at);if(!Number.isSafeInteger(registered)||!Number.isFinite(eventTime)||registered>eventTime)return;return{id:account.id,registeredAt:account.registeredAt}}const profileName=(kind,id)=>typeof id==="string"&&isFlowId(id.toLowerCase())?`${kind} ${id.slice(0,8)}`:kind;function invocationMetadata(row,operational){const invocation=invocationProperties(row);return invocation.entrypoint==="unknown"&&typeof operational?.entrypoint==="string"?{...invocation,entrypoint:operational.entrypoint}:invocation}function contextProperties(context,prefix=""){const productVersion=version(context?.productVersion)?context.productVersion:"unknown";const platform=platforms.has(context?.platform??"")?context.platform:"unknown";const executionLocation=executionLocations.has(context?.executionLocation??"")?context.executionLocation:"unknown";const traffic=context?.trafficClass;const deviceId=typeof context?.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(context.deviceId)?context.deviceId:void 0;const deviceKind=platform==="darwin"?"Mac":platform==="win32"?"Windows PC":platform==="linux"?"Linux PC":"Device";return{[prefix+"product_version"]:productVersion,[prefix+"platform"]:platform,[prefix+"execution_location"]:executionLocation,[prefix+"capture_context_known"]:!!context&&(context.productVersion===void 0||version(context.productVersion))&&platforms.has(context.platform??"")&&executionLocations.has(context.executionLocation??""),[prefix+"capture_traffic_class"]:traffic==="usage"||traffic==="internal_test"||traffic==="simulation"?traffic:"unknown",...traffic==="internal_test"||traffic==="simulation"?{}:{[prefix+"device_identity_known"]:!!deviceId,...deviceId?{[prefix+"device_id"]:deviceId,[prefix+"device_alias"]:deviceKind+" "+deviceId.slice(0,8),[prefix+"device_identity_scheme"]:"random_app_user_device_v1"}:{}}}}function resultProperties(result,prefix=""){const count=result?.count,known=Number.isSafeInteger(count)&&count!==void 0&&count>=0&&count<=1e8;return{[prefix+"result_count_known"]:known,...known?{[prefix+"result_count"]:count,[prefix+"result_nonempty"]:count>0}:{},...typeof result?.truncated==="boolean"?{[prefix+"result_truncated"]:result.truncated}:{}}}function correlationProperties(row){const correlation=row.correlation??(isUsageTrace(row.trace)?row.trace:void 0);if(!isFlowId(correlation?.flowId))return{};return{flow_id:correlation.flowId,...isFlowId(correlation.connectionFlowId)?{connection_flow_id:correlation.connectionFlowId}:{}}}function feedbackProperties(row){const f=row.feedback,t=f?.target;if(!f||!isFlowId(f.targetReceiptId)||!feedbackRatings.has(f.rating)||!feedbackChannels.has(f.submissionChannel)||!t||!feedbackOperations.has(t.operation)||!(outcomes.has(t.outcome)||t.outcome==="unknown")||!isoTimestamp(t.at))return;const source=measurementSource(t.source);return{feedback_measurement:"receipt_usefulness_v1",target_receipt_id:f.targetReceiptId,target_at:t.at,target_operation:t.operation,target_outcome:t.outcome,target_connector:source,target_connector_known:source!=="other",rating:f.rating,feedback_reason:f.reason===void 0?"not_provided":feedbackReasons.has(f.reason)?f.reason:"unknown",submission_channel:f.submissionChannel,...contextProperties(t.context,"target_"),...resultProperties(t.result,"target_")}}const galaxyStates=new Set(["live_local","empty","vault_unavailable"]);export function northstarEvents(row,installId,verifiedGithubLogin,account,processPersonProfile=true){const projected=[],outcome=outcomes.has(row.outcome)?row.outcome:"unknown";const duration=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=6e5?Math.round(row.durationMs):void 0;const connector=measurementSource(row.source),sourceProperties={connector,connector_known:connector!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION};if(row.operation==="product.collection"){const properties=collectionStatusProperties(row);if(!properties)return[];projected.push(["zortex collection status",properties])}else if(row.operation==="product.resources"){const properties=resourceProperties(row);if(!properties)return[];projected.push(["zortex resource snapshot",properties])}else if(row.operation==="product.trace"){const properties=operationalProperties(row);if(!properties)return[];projected.push(["zortex operation step",{...sourceProperties,...properties}])}else if(row.operation==="product.feedback"){const feedback=feedbackProperties(row);if(feedback)projected.push(["zortex product feedback",feedback])}else if(row.operation==="product.account_signed_in"){projected.push(["zortex account signed in",{outcome,identity_scope:"installation"}])}else if(row.operation==="product.first_start"||row.operation==="product.started"){projected.push([row.operation==="product.first_start"?"zortex first start":"zortex started",{identity_scope:"installation",...row.operation==="product.first_start"?{new_install_known:["new_install","first_observed"].includes(row.code??""),is_new_install:row.code==="new_install"}:{}}])}else if(row.operation==="product.galaxy_opened"){projected.push(["zortex galaxy opened",{identity_scope:"installation",outcome,galaxy_state:galaxyStates.has(row.code??"")?row.code:"unknown"}])}else if(row.operation==="connector.trace"&&isUsageTrace(row.trace)){const t=row.trace;projected.push(["zortex connection step",{...sourceProperties,flow_id:t.flowId,...t.connectionFlowId?{connection_flow_id:t.connectionFlowId}:{},duration_known:t.durationKnown===true&&duration!==void 0,stage:t.stage,state:t.state??"unknown",mode:t.mode??"unknown",trigger:t.trigger??"unknown",outcome,...t.page?{page:t.page}:{},...t.action?{action:t.action}:{},...t.reason?{reason:t.reason}:{},...t.error?{error_category:t.error}:{},...t.statusCode!==void 0?{status_code:t.statusCode}:{},...t.count!==void 0?{record_count:t.count}:{},...t.elapsedMs!==void 0?{elapsed_ms:Math.round(t.elapsedMs)}:{},...t.durationKnown===true&&duration!==void 0?{duration_ms:duration}:{}}])}else if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)){const observation=observationProjection(row);if(observation)projected.push([observation.event,{...sourceProperties,...observation.properties}])}else if(tools.has(row.operation)){const tool="indra."+(invocationTool(row)??(row.operation==="mcp.call"?"unknown":row.operation)),error=!["ok","empty"].includes(outcome);const detail={...correlationProperties(row),...row.source!==void 0?sourceProperties:{},error_category:errorCategories.has(row.errorCategory??"")?row.errorCategory:"unknown"};projected.push([outcome==="auth-blocked"?"zortex refused":row.operation==="search"?"zortex delivery":"zortex call",{tool,client:"indra-v2",error,...detail}]);projected.push(["zortex call timing",{tool,error,...detail,duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{}}])}else if(row.operation==="connector.authorization"){const phase=row.outcome==="ok"?"completed":row.outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(row.outcome)?"failed":"unresolved";const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex auth journey",{...sourceProperties,phase,final:true,outcome:phase==="unresolved"?"unknown":outcome,...isUsageTrace(row.trace)?{flow_id:row.trace.flowId,connection_flow_id:row.trace.connectionFlowId??row.trace.flowId,mode:row.trace.mode??"unknown",trigger:row.trace.trigger??"unknown",...row.trace.driver?{driver:row.trace.driver}:{}}:{},...row.code?{reason:AUTHORIZATION_REASON_CODES.some(code=>code===row.code)?row.code:"provider_error"}:{},duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{}}])}else if(row.operation==="connector.connect"){projected.push(["zortex auth journey",{...sourceProperties,phase:"request_returned",outcome,...correlationProperties(row)}])}else if(["connector.read","connector.invoke","connector.usable"].includes(row.operation)){const observedOperation=row.operation!=="connector.usable",elapsed=observedOperation&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;const errorCategory=errorCategories.has(row.errorCategory??"")?row.errorCategory:isUsageTrace(row.trace)&&row.trace.error?row.trace.error:"unknown";projected.push(["zortex connector health",{...sourceProperties,plane:"query",operation:row.operation,outcome,evidence_kind:observedOperation?"operation_receipt":"query_availability",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},error_category:errorCategory,...correlationProperties(row)}])}else if(operationalOnly.has(row.operation)){const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex product operation",{...sourceProperties,evidence_kind:"operation_receipt",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},...correlationProperties(row)}])}const definitions=verifiedGithubLogin?scoreOutcomes(row,outcome):[];for(const{definition,success}of definitions){const score={score_outcome_id:definition.id,score_outcome_version:definition.version,score_owner:definition.owner,score_author_login:definition.authorLogin,score_success:success,identity_scope:"verified_human",identity_scheme:"github_api_user_v1"};projected.push(["zortex outcome attempted",score]);if(success)projected.push(["zortex outcome succeeded",score])}return projected.map(([event,properties])=>{const scoreEvent=event.startsWith("zortex outcome ");const scoreIdentity=scoreEvent?":"+String(properties.score_outcome_id):"";const hex=createHash("sha256").update("indra-v2-northstar:1:"+installId+":"+row.id+":"+event+scoreIdentity).digest("hex");const usageProperties=!scoreEvent?{install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",operation:row.operation,outcome,internal:row.internal??false,effective_usage:!row.internal&&row.outcome==="ok"&&(["search","context","sql"].includes(row.operation)||row.operation==="action"&&row.code==="effective_invoke")&&["zortex delivery","zortex call"].includes(event),usage_measurement:"successful_tool_receipt_v1",...isFlowId(row.id)?{receipt_id:row.id}:{},...contextProperties(row.context),...resultProperties(row.result),...invocationMetadata(row,event==="zortex operation step"?properties:void 0),...executionProperties(row)}:{};const eventAccount=row.operation==="product.feedback"?void 0:eventAccountIdentity(account,row.at);const accountProperties=!scoreEvent?{account_known:!!eventAccount,...eventAccount?{account_id:eventAccount.id,distinct_id:`zortex-account:${eventAccount.id}`,identity_scope:"verified_email_account",identity_scheme:"zortex_email_v1",account_registered_at:new Date(eventAccount.registeredAt*1e3).toISOString()}:{},...activityProperties(row.operation,event,row.trace)}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{name:profileName(eventAccount?"Account":"Installation",eventAccount?.id??installId),product:"indra-v2",identity_scope:eventAccount?"verified_email_account":"installation",identity_scheme:eventAccount?"zortex_email_v1":"random_install_v1"}}:{};return{event,uuid:`${hex.slice(0,8)}-${hex.slice(8,12)}-5${hex.slice(13,16)}-a${hex.slice(17,20)}-${hex.slice(20,32)}`,timestamp:row.at,properties:{distinct_id:scoreEvent?`github:${verifiedGithubLogin}`:installId,$process_person_profile:profileEnabled,$geoip_disable:true,product:"indra-v2",schema_version:scoreEvent?2:1,...properties,...usageProperties,...accountProperties,...profileProperties}}})}const rawCodes=new Set([...AUTHORIZATION_REASON_CODES,...Original.ERROR_CODES,"effective_invoke","new_install","first_observed",...galaxyStates]);export function rawUsageEvents(row,installId){if(!TELEMETRY_OPERATIONS.includes(row.operation))return[];const operational=row.operation==="product.trace"?operationalProperties(row):void 0;if(row.operation==="product.trace"&&!operational)return[];const resource=row.operation==="product.resources"?resourceProperties(row):void 0;if(row.operation==="product.resources"&&!resource)return[];const collectionStatus=row.operation==="product.collection"?collectionStatusProperties(row):void 0;if(row.operation==="product.collection"&&!collectionStatus)return[];const observation=["connector.sync","connector.inventory","connector.connection"].includes(row.operation)?observationProjection(row):void 0;if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)&&!observation)return[];const duration=(!operational||operational.duration_known===true)&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?row.durationMs:void 0;return[{event:"zortex."+row.operation,uuid:row.id,timestamp:row.at,properties:{distinct_id:installId,install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",account_known:false,...activityProperties(row.operation,"zortex."+row.operation,row.trace),$process_person_profile:false,$geoip_disable:true,operation:row.operation,outcome:outcomes.has(row.outcome)?row.outcome:"unknown",duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{},internal:row.internal??false,...row.source!==void 0?{source:measurementSource(row.source),source_known:measurementSource(row.source)!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION}:{},...row.code!==void 0?{code:rawCodes.has(row.code)?row.code:"unknown",code_known:rawCodes.has(row.code)}:{},...contextProperties(row.context),...resultProperties(row.result),...correlationProperties(row),...executionProperties(row),...observation?.properties??{},...operational??{},...resource??{},...collectionStatus??{},...invocationMetadata(row,operational)}}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage}from"node:async_hooks";import{TELEMETRY_OPERATIONS,TELEMETRY_OUTCOMES}from"./telemetry.js";import{isFlowId,isUsageTrace}from"./trace.js";import{isUsageInvocation,isUsageObservationFacts,isUsageObservationStats,snapshotUsageObservation}from"./observations.js";import{isOperationalContext,isUsageOperationalTrace}from"./operational.js";import{isTelemetrySourceId}from"./source-ids.js";import{isUsageResourceSnapshot,snapshotResourceMetadata}from"./resources.js";import{isUsageCollectionStatus,snapshotCollectionStatus}from"./collection.js";export const USAGE_TRAFFIC_CLASSES=["usage","internal_test","simulation"];export const USAGE_ERROR_CATEGORIES=["timeout","denied","network","provider","storage","identity","unknown"];export const FEEDBACK_OPERATIONS=["search","context","sql","action","connector.read","connector.invoke"];export const FEEDBACK_RATINGS=["useful","partly_useful","not_useful","cannot_judge"];export const FEEDBACK_REASONS=["saved_time","answered_question","incomplete","wrong_result","no_result","too_slow","connection_problem","unclear"];export const FEEDBACK_CHANNELS=["interactive_cli","programmatic_cli"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const id=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);export function isUsageContext(value){if(!object(value)||!closed(value,["productVersion","platform","executionLocation","trafficClass"]))return false;return(value.productVersion===void 0||typeof value.productVersion==="string"&&value.productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.productVersion))&&(value.platform===void 0||typeof value.platform==="string"&&["darwin","win32","linux","unknown"].includes(value.platform))&&(value.executionLocation===void 0||typeof value.executionLocation==="string"&&["local","cloud","unknown"].includes(value.executionLocation))&&(value.trafficClass===void 0||typeof value.trafficClass==="string"&&USAGE_TRAFFIC_CLASSES.includes(value.trafficClass))}export function isUsageResultSummary(value){return object(value)&&closed(value,["count","truncated"])&&(value.count===void 0||Number.isSafeInteger(value.count)&&Number(value.count)>=0&&Number(value.count)<=1e8)&&(value.truncated===void 0||typeof value.truncated==="boolean")}export function isUsageCorrelation(value){return object(value)&&closed(value,["flowId","connectionFlowId"])&&isFlowId(value.flowId)&&(value.connectionFlowId===void 0||isFlowId(value.connectionFlowId))}export function isUsageFeedbackInput(value){return object(value)&&closed(value,["receiptId","rating","reason"])&&isFlowId(value.receiptId)&&FEEDBACK_RATINGS.includes(value.rating)&&(value.reason===void 0||FEEDBACK_REASONS.includes(value.reason))}export function isUsageFeedback(value){if(!object(value)||!closed(value,["targetReceiptId","rating","reason","submissionChannel","target"])||!isUsageFeedbackInput({receiptId:value.targetReceiptId,rating:value.rating,...value.reason!==void 0?{reason:value.reason}:{}})||!FEEDBACK_CHANNELS.includes(value.submissionChannel)||!object(value.target))return false;const target=value.target;return closed(target,["operation","source","outcome","at","context","result"])&&FEEDBACK_OPERATIONS.includes(target.operation)&&TELEMETRY_OUTCOMES.includes(target.outcome)&&typeof target.at==="string"&&Number.isFinite(Date.parse(target.at))&&(target.source===void 0||id(target.source))&&(target.context===void 0||isUsageContext(target.context))&&(target.result===void 0||isUsageResultSummary(target.result))}export function isUsageEvent(value,record=false){if(!object(value)||!closed(value,["operation","outcome","durationMs","source","code","internal","trace","operational","resource","collectionStatus","result","correlation","errorCategory",...record?["id","at","context","feedback","invocation","observation","execution"]:[]]))return false;const event=value;return TELEMETRY_OPERATIONS.includes(event.operation)&&TELEMETRY_OUTCOMES.includes(event.outcome)&&Number.isFinite(event.durationMs)&&event.durationMs>=0&&event.durationMs<=864e5&&(event.source===void 0||id(event.source))&&(event.code===void 0||typeof event.code==="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(event.code))&&(event.internal===void 0||typeof event.internal==="boolean")&&(event.trace===void 0||isUsageTrace(event.trace))&&(event.operation!=="connector.trace"||event.trace!==void 0)&&(event.operation==="product.trace"?isUsageOperationalTrace(event.operational)&&event.internal===true&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&(event.source===void 0||isTelemetrySourceId(event.source)):event.operational===void 0)&&(event.operation==="product.resources"?isUsageResourceSnapshot(event.resource)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0:event.resource===void 0)&&(event.operation==="product.collection"?isUsageCollectionStatus(event.collectionStatus)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0&&event.errorCategory===void 0&&event.execution===void 0&&event.invocation===void 0:event.collectionStatus===void 0)&&(event.result===void 0||isUsageResultSummary(event.result))&&(event.correlation===void 0||isUsageCorrelation(event.correlation))&&(event.errorCategory===void 0||USAGE_ERROR_CATEGORIES.includes(event.errorCategory))&&(!record||isFlowId(event.id)&&typeof event.at==="string"&&Number.isFinite(Date.parse(event.at))&&(event.context===void 0||isUsageContext(event.context))&&(event.feedback===void 0||isUsageFeedback(event.feedback))&&(event.invocation===void 0||isUsageInvocation(event.invocation))&&(event.observation===void 0||isUsageObservationFacts(event.observation))&&(event.execution===void 0||isOperationalContext(event.execution)))&&(event.operation==="product.feedback"?record&&event.feedback!==void 0&&event.internal===true:event.feedback===void 0)&&(["connector.sync","connector.inventory","connector.connection"].includes(event.operation)?record&&event.internal===true&&event.observation!==void 0&&event.operation==="connector."+event.observation.kind:event.observation===void 0)}export function feedbackEligible(event){return FEEDBACK_OPERATIONS.includes(event.operation)&&(event.operation!=="action"||event.code==="effective_invoke")&&(!event.internal||event.operation==="connector.read"||event.operation==="connector.invoke")}export function snapshotUsageRecord(value){if(!object(value))return value;const copy={...value};for(const key of["trace","operational","execution","context","result","correlation","invocation"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.observation))copy.observation=snapshotUsageObservation(copy.observation);if(object(copy.resource))copy.resource=snapshotResourceMetadata(copy.resource);if(object(copy.collectionStatus))copy.collectionStatus=snapshotCollectionStatus(copy.collectionStatus);if(object(copy.feedback)){const feedback={...copy.feedback};if(object(feedback.target)){const target={...feedback.target};for(const key of["context","result"])if(object(target[key]))target[key]={...target[key]};feedback.target=target}copy.feedback=feedback}return copy}export function isUsageCollection(value){if(!object(value)||!closed(value,["retainedEvents","prunedEvents","retentionFloor","limited","retentionDays","maxEvents","oldestAvailableAt","observations"]))return false;return["retainedEvents","prunedEvents","retentionFloor","retentionDays","maxEvents"].every(key=>Number.isSafeInteger(value[key])&&Number(value[key])>=0)&&typeof value.limited==="boolean"&&(value.oldestAvailableAt===null||typeof value.oldestAvailableAt==="string"&&Number.isFinite(Date.parse(value.oldestAvailableAt)))&&(value.observations===void 0||isUsageObservationStats(value.observations))}export function usageResultSummary(reply){if(!("ok"in reply)||!object(reply.ok))return void 0;const value=reply.ok;const count=Number.isSafeInteger(value.returned)&&Number(value.returned)>=0&&Number(value.returned)<=1e8?Number(value.returned):Array.isArray(value.rows)?value.rows.length:Array.isArray(value.items)?value.items.length:void 0;const truncated=typeof value.truncated==="boolean"?value.truncated:void 0;return count===void 0&&truncated===void 0?void 0:{...count!==void 0?{count}:{},...truncated!==void 0?{truncated}:{}}}export function usageErrorCategory(reply){if(!("err"in reply))return void 0;if(reply.err.code==="deadline_exceeded")return"timeout";if(reply.err.code==="permission_denied")return"denied";if(reply.err.code==="unauthenticated")return"identity";if(reply.err.layer==="storage")return"storage";return"unknown"}const hostContext=new AsyncLocalStorage;export function withTelemetryContext(context,run){const captured=Object.freeze({...context});if(!isUsageContext(captured))throw Error("Invalid telemetry runtime context.");return hostContext.run(captured,run)}export const currentTelemetryContext=()=>hostContext.getStore();
|
|
1
|
+
import{AsyncLocalStorage}from"node:async_hooks";import{TELEMETRY_OPERATIONS,TELEMETRY_OUTCOMES}from"./telemetry.js";import{isFlowId,isUsageTrace}from"./trace.js";import{isUsageInvocation,isUsageObservationFacts,isUsageObservationStats,snapshotUsageObservation}from"./observations.js";import{isOperationalContext,isUsageOperationalTrace}from"./operational.js";import{isTelemetrySourceId}from"./source-ids.js";import{isUsageResourceSnapshot,snapshotResourceMetadata}from"./resources.js";import{isUsageCollectionStatus,snapshotCollectionStatus}from"./collection.js";export const USAGE_TRAFFIC_CLASSES=["usage","internal_test","simulation"];export const USAGE_ERROR_CATEGORIES=["timeout","denied","network","provider","storage","identity","unknown"];export const FEEDBACK_OPERATIONS=["search","context","sql","action","connector.read","connector.invoke"];export const FEEDBACK_RATINGS=["useful","partly_useful","not_useful","cannot_judge"];export const FEEDBACK_REASONS=["saved_time","answered_question","incomplete","wrong_result","no_result","too_slow","connection_problem","unclear"];export const FEEDBACK_CHANNELS=["interactive_cli","programmatic_cli"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const id=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);export function isUsageContext(value){if(!object(value)||!closed(value,["productVersion","platform","executionLocation","deviceId","trafficClass"]))return false;return(value.productVersion===void 0||typeof value.productVersion==="string"&&value.productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.productVersion))&&(value.platform===void 0||typeof value.platform==="string"&&["darwin","win32","linux","unknown"].includes(value.platform))&&(value.deviceId===void 0||typeof value.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.deviceId))&&(value.executionLocation===void 0||typeof value.executionLocation==="string"&&["local","cloud","unknown"].includes(value.executionLocation))&&(value.trafficClass===void 0||typeof value.trafficClass==="string"&&USAGE_TRAFFIC_CLASSES.includes(value.trafficClass))}export function isUsageResultSummary(value){return object(value)&&closed(value,["count","truncated"])&&(value.count===void 0||Number.isSafeInteger(value.count)&&Number(value.count)>=0&&Number(value.count)<=1e8)&&(value.truncated===void 0||typeof value.truncated==="boolean")}export function isUsageCorrelation(value){return object(value)&&closed(value,["flowId","connectionFlowId"])&&isFlowId(value.flowId)&&(value.connectionFlowId===void 0||isFlowId(value.connectionFlowId))}export function isUsageFeedbackInput(value){return object(value)&&closed(value,["receiptId","rating","reason"])&&isFlowId(value.receiptId)&&FEEDBACK_RATINGS.includes(value.rating)&&(value.reason===void 0||FEEDBACK_REASONS.includes(value.reason))}export function isUsageFeedback(value){if(!object(value)||!closed(value,["targetReceiptId","rating","reason","submissionChannel","target"])||!isUsageFeedbackInput({receiptId:value.targetReceiptId,rating:value.rating,...value.reason!==void 0?{reason:value.reason}:{}})||!FEEDBACK_CHANNELS.includes(value.submissionChannel)||!object(value.target))return false;const target=value.target;return closed(target,["operation","source","outcome","at","context","result"])&&FEEDBACK_OPERATIONS.includes(target.operation)&&TELEMETRY_OUTCOMES.includes(target.outcome)&&typeof target.at==="string"&&Number.isFinite(Date.parse(target.at))&&(target.source===void 0||id(target.source))&&(target.context===void 0||isUsageContext(target.context))&&(target.result===void 0||isUsageResultSummary(target.result))}export function isUsageEvent(value,record=false){if(!object(value)||!closed(value,["operation","outcome","durationMs","source","code","internal","trace","operational","resource","collectionStatus","result","correlation","errorCategory",...record?["id","at","context","feedback","invocation","observation","execution"]:[]]))return false;const event=value;return TELEMETRY_OPERATIONS.includes(event.operation)&&TELEMETRY_OUTCOMES.includes(event.outcome)&&Number.isFinite(event.durationMs)&&event.durationMs>=0&&event.durationMs<=864e5&&(event.source===void 0||id(event.source))&&(event.code===void 0||typeof event.code==="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(event.code))&&(event.internal===void 0||typeof event.internal==="boolean")&&(event.trace===void 0||isUsageTrace(event.trace))&&(event.operation!=="connector.trace"||event.trace!==void 0)&&(event.operation==="product.trace"?isUsageOperationalTrace(event.operational)&&event.internal===true&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&(event.source===void 0||isTelemetrySourceId(event.source)):event.operational===void 0)&&(event.operation==="product.resources"?isUsageResourceSnapshot(event.resource)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0:event.resource===void 0)&&(event.operation==="product.collection"?isUsageCollectionStatus(event.collectionStatus)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0&&event.errorCategory===void 0&&event.execution===void 0&&event.invocation===void 0:event.collectionStatus===void 0)&&(event.result===void 0||isUsageResultSummary(event.result))&&(event.correlation===void 0||isUsageCorrelation(event.correlation))&&(event.errorCategory===void 0||USAGE_ERROR_CATEGORIES.includes(event.errorCategory))&&(!record||isFlowId(event.id)&&typeof event.at==="string"&&Number.isFinite(Date.parse(event.at))&&(event.context===void 0||isUsageContext(event.context))&&(event.feedback===void 0||isUsageFeedback(event.feedback))&&(event.invocation===void 0||isUsageInvocation(event.invocation))&&(event.observation===void 0||isUsageObservationFacts(event.observation))&&(event.execution===void 0||isOperationalContext(event.execution)))&&(event.operation==="product.feedback"?record&&event.feedback!==void 0&&event.internal===true:event.feedback===void 0)&&(["connector.sync","connector.inventory","connector.connection"].includes(event.operation)?record&&event.internal===true&&event.observation!==void 0&&event.operation==="connector."+event.observation.kind:event.observation===void 0)}export function feedbackEligible(event){return FEEDBACK_OPERATIONS.includes(event.operation)&&(event.operation!=="action"||event.code==="effective_invoke")&&(!event.internal||event.operation==="connector.read"||event.operation==="connector.invoke")}export function snapshotUsageRecord(value){if(!object(value))return value;const copy={...value};for(const key of["trace","operational","execution","context","result","correlation","invocation"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.observation))copy.observation=snapshotUsageObservation(copy.observation);if(object(copy.resource))copy.resource=snapshotResourceMetadata(copy.resource);if(object(copy.collectionStatus))copy.collectionStatus=snapshotCollectionStatus(copy.collectionStatus);if(object(copy.feedback)){const feedback={...copy.feedback};if(object(feedback.target)){const target={...feedback.target};for(const key of["context","result"])if(object(target[key]))target[key]={...target[key]};feedback.target=target}copy.feedback=feedback}return copy}export function isUsageCollection(value){if(!object(value)||!closed(value,["retainedEvents","prunedEvents","retentionFloor","limited","retentionDays","maxEvents","oldestAvailableAt","observations"]))return false;return["retainedEvents","prunedEvents","retentionFloor","retentionDays","maxEvents"].every(key=>Number.isSafeInteger(value[key])&&Number(value[key])>=0)&&typeof value.limited==="boolean"&&(value.oldestAvailableAt===null||typeof value.oldestAvailableAt==="string"&&Number.isFinite(Date.parse(value.oldestAvailableAt)))&&(value.observations===void 0||isUsageObservationStats(value.observations))}export function usageResultSummary(reply){if(!("ok"in reply)||!object(reply.ok))return void 0;const value=reply.ok;const count=Number.isSafeInteger(value.returned)&&Number(value.returned)>=0&&Number(value.returned)<=1e8?Number(value.returned):Array.isArray(value.rows)?value.rows.length:Array.isArray(value.items)?value.items.length:void 0;const truncated=typeof value.truncated==="boolean"?value.truncated:void 0;return count===void 0&&truncated===void 0?void 0:{...count!==void 0?{count}:{},...truncated!==void 0?{truncated}:{}}}export function usageErrorCategory(reply){if(!("err"in reply))return void 0;if(reply.err.code==="deadline_exceeded")return"timeout";if(reply.err.code==="permission_denied")return"denied";if(reply.err.code==="unauthenticated")return"identity";if(reply.err.layer==="storage")return"storage";return"unknown"}const hostContext=new AsyncLocalStorage;export function withTelemetryContext(context,run){const captured=Object.freeze({...context});if(!isUsageContext(captured))throw Error("Invalid telemetry runtime context.");return hostContext.run(captured,run)}export const currentTelemetryContext=()=>hostContext.getStore();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const TELEMETRY_OPERATIONS=["search","context","action","actions","action_result","append","feedback","manage","sql","done","instruction","handbook","mcp.call","product.first_start","product.started","product.account_signed_in","product.galaxy_opened","product.feedback","product.trace","product.resources","product.collection","connector.trace","connector.read","connector.invoke","connector.connect","connector.authorization","connector.fabricate","connector.usable","connector.sync","connector.inventory","connector.connection","flywheel.start","flywheel.run"];export const TELEMETRY_OUTCOMES=["ok","empty","fault","auth-blocked","cancelled","invalid","unknown"];export const AUTHORIZATION_REASON_CODES=["authorization_timeout","authorization_denied","browser_open_failed","connection_failed","google_connection_failed","provider_error","local_directory_unavailable","source_disabled","observation_timeout","job_unavailable","job_mismatch","host_closed","account_selection_required","browser_session_unavailable","browser_session_limit","browser_agent_continuation","consent_app_unverified","account_chooser_unavailable","chooser_rows_unavailable","grant_review_required","observation_failed","click_failed","stale_control","oauth_page_changed","unknown_google_page","cancelled","cancelled_or_timed_out","browser_cleanup_failed","jev_unavailable","invalid_jev_choice","driver_error","step_limit","unknown","invalid_authorization_request","notion_page_selection_required","login_required","task_expired","callback_mismatch","untrusted_origin","transaction_mismatch","transaction_mismatch_client_id","transaction_mismatch_state","transaction_mismatch_redirect_uri","transaction_mismatch_resource","transaction_mismatch_scope","transaction_mismatch_response_type","transaction_mismatch_code_challenge","transaction_mismatch_code_challenge_method","transaction_mismatch_iss","transaction_mismatch_user_scope","human_required","human_secure_control","human_textbox","human_challenge","human_unverified_warning","planner_human_handoff","account_not_found","ambiguous_accounts","account_chooser_skipped","app_identity_unconfirmed","browser_renderer_unavailable","no_safe_controls","too_many_controls","model_budget_exhausted","invalid_plan","planner_low_confidence","admin_approval_required","grounder_invalid_control","already_selected","repeated_action","untrusted_target","planner_aborted","planner_invalid_response","planner_missing_content","planner_output_too_large","planner_json_invalid","planner_step_invalid","planner_model_not_configured","provider_missing_key","jev_invalid_response","jev_low_confidence","jev_model_not_configured"];export function usageOutcome(result){if("err"in result){const code=result.err.code;return code==="failed_precondition"||code==="permission_denied"||code==="unauthenticated"?"auth-blocked":code==="aborted"?"cancelled":code==="invalid_argument"?"invalid":"fault"}if("empty"in result)return"empty";const value=result.ok;if(value&&typeof value==="object"){const
|
|
1
|
+
export const TELEMETRY_OPERATIONS=["search","context","action","actions","action_result","append","feedback","manage","sql","done","instruction","handbook","mcp.call","product.first_start","product.started","product.account_signed_in","product.galaxy_opened","product.feedback","product.trace","product.resources","product.collection","connector.trace","connector.read","connector.invoke","connector.connect","connector.authorization","connector.fabricate","connector.usable","connector.sync","connector.inventory","connector.connection","flywheel.start","flywheel.run"];export const TELEMETRY_OUTCOMES=["ok","empty","fault","auth-blocked","cancelled","invalid","unknown"];export const AUTHORIZATION_REASON_CODES=["authorization_timeout","authorization_denied","browser_open_failed","connection_failed","google_connection_failed","provider_error","local_directory_unavailable","source_disabled","observation_timeout","job_unavailable","job_mismatch","host_closed","account_selection_required","browser_session_unavailable","browser_session_limit","browser_agent_continuation","consent_app_unverified","account_chooser_unavailable","chooser_rows_unavailable","grant_review_required","observation_failed","click_failed","stale_control","oauth_page_changed","unknown_google_page","cancelled","cancelled_or_timed_out","browser_cleanup_failed","jev_unavailable","invalid_jev_choice","driver_error","step_limit","unknown","invalid_authorization_request","notion_page_selection_required","login_required","task_expired","callback_mismatch","untrusted_origin","transaction_mismatch","transaction_mismatch_client_id","transaction_mismatch_state","transaction_mismatch_redirect_uri","transaction_mismatch_resource","transaction_mismatch_scope","transaction_mismatch_response_type","transaction_mismatch_code_challenge","transaction_mismatch_code_challenge_method","transaction_mismatch_iss","transaction_mismatch_user_scope","human_required","human_secure_control","human_textbox","human_challenge","human_unverified_warning","planner_human_handoff","account_not_found","ambiguous_accounts","account_chooser_skipped","app_identity_unconfirmed","browser_renderer_unavailable","no_safe_controls","too_many_controls","model_budget_exhausted","invalid_plan","planner_low_confidence","admin_approval_required","grounder_invalid_control","already_selected","repeated_action","untrusted_target","planner_aborted","planner_invalid_response","planner_missing_content","planner_output_too_large","planner_json_invalid","planner_step_invalid","planner_model_not_configured","provider_missing_key","jev_invalid_response","jev_low_confidence","jev_model_not_configured"];export function usageOutcome(result){if("err"in result){const code=result.err.code;return code==="failed_precondition"||code==="permission_denied"||code==="unauthenticated"?"auth-blocked":code==="aborted"?"cancelled":code==="invalid_argument"?"invalid":"fault"}if("empty"in result)return"empty";const value=result.ok;if(value&&typeof value==="object"){if("result"in value&&value.result&&typeof value.result==="object"&&"isError"in value.result&&value.result.isError===true)return"fault";const status="status"in value?value.status:void 0;const state=("state"in value?value.state:void 0)??(status&&typeof status==="object"&&"state"in status?status.state:status);if(state==="failed"||state==="FAILED")return"fault";if(state==="cancelled")return"cancelled";if(typeof state==="string"&&["needs-user","needs_user","needs_you","waiting-user","AUTH_BLOCKED"].includes(state))return"auth-blocked";if(typeof state==="string"&&["pending","queued","running","waiting","unknown"].includes(state))return"unknown";if("returned"in value&&value.returned===0||"items"in value&&Array.isArray(value.items)&&!value.items.length)return"empty"}return"ok"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{constants}from"node:fs";import{open,lstat,mkdir,rm}from"node:fs/promises";import{randomUUID}from"node:crypto";import{dirname,isAbsolute}from"node:path";const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;export async function localDeviceIdentity(file){if(!isAbsolute(file))throw Error("Device identity file must be absolute.");const directory=dirname(file);await mkdir(directory,{recursive:true,mode:448});const folder=await lstat(directory);if(!folder.isDirectory()||folder.isSymbolicLink()||process.platform!=="win32"&&((folder.mode&63)!==0||folder.uid!==process.getuid?.()))throw Error("DEVICE_IDENTITY_DIRECTORY_UNSAFE");const read=async()=>{const handle2=await open(file,constants.O_RDONLY|(process.platform==="win32"?0:constants.O_NOFOLLOW));try{const stat=await handle2.stat();if(!stat.isFile()||process.platform!=="win32"&&((stat.mode&63)!==0||stat.uid!==process.getuid?.()))throw Error("DEVICE_IDENTITY_FILE_UNSAFE");const source=await handle2.readFile("utf8");if(Buffer.byteLength(source)>256)throw Error("DEVICE_IDENTITY_INVALID");let parsed;try{parsed=JSON.parse(source)}catch{throw Error("DEVICE_IDENTITY_INVALID")}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)||Object.keys(parsed).sort().join(",")!=="deviceId,version"||parsed.version!==1||typeof parsed.deviceId!=="string"||!uuid.test(parsed.deviceId))throw Error("DEVICE_IDENTITY_INVALID");return parsed.deviceId}finally{await handle2.close()}};try{return await read()}catch(error){if(error.code!=="ENOENT")throw error}const deviceId=randomUUID();let handle;try{handle=await open(file,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,384)}catch(error){if(error.code!=="EEXIST")throw error;for(let attempt=0;attempt<5;attempt++){try{return await read()}catch(readError){if(attempt===4)throw readError;await new Promise(resolve=>setTimeout(resolve,20))}}throw Error("DEVICE_IDENTITY_UNAVAILABLE")}try{await handle.writeFile(JSON.stringify({version:1,deviceId})+"\n");await handle.sync()}catch(error){await handle.close();await rm(file,{force:true});throw error}await handle.close();return deviceId}
|