Compare commits

...
12 Commits
Author SHA1 Message Date
Hanzo AI 86bc401545 feat(consent): insights + opt-in training contribution, account-canonical
publish / publish (push) Failing after 32s
ci / build (push) Successful in 27s
ci / test (push) Successful in 28s
- shared/consent.ts: ONE consent value. Signed in → the Hanzo account is the
  source of truth (GET/PUT /v1/iam/consent); signed out → local, pushed on next
  sign-in. Two switches: anonymous usage insights (default on, no query text) +
  opt-in training contribution (share your own searches/answers; off until asked).
- Onboarding on new install (background onInstalled → onboarding.html) explicitly
  ASKS consent; settings toggles in the popup mirror the same value.
- Answer engine instrumented: anonymous answer_search/answer_shown events +
  contributeTrainingSample (no-op unless opted in). All fail-soft.
- release: browser-extension 1.9.36
2026-07-26 11:12:06 -07:00
Hanzo AI a4fd6b1557 release: browser-extension 1.9.35 — answer engine (fixed build path)
ci / build (push) Successful in 26s
publish / publish (push) Failing after 1m11s
ci / test (push) Successful in 41s
Ships the Hanzo AI answer engine (new-tab landing + address-bar search over the
@hanzo/ai search primitive) with the newtab out()-path fix. v1.9.34 was the
pre-fix tag; this is the buildable release.
2026-07-26 10:35:24 -07:00
Hanzo AI a5a8a79a17 fix(build): newtab.js compiles to the out() root, matching the copy step
The answer-engine's esbuild wrote newtab.js to a literal dist/browser-extension/
path while every other bundle + the copy step use out() (=<root>/dist), so the
per-browser copy would miss it. Unify on out('newtab.js'). Build verified: Chrome/
Firefox/Safari bundles + newtab.js produced.
2026-07-26 10:34:30 -07:00
Hanzo AI 9a9b1cacfe fix(build): resolve @hanzo/ai + @hanzo/usage from npm, not sibling paths → 1.9.34
The @hanzo/usage sibling-path alias pointed at /…/usage that doesn't exist on
CI, breaking every release build. Both are now published deps resolved from
node_modules — CI build works. Bump 1.9.33→1.9.34 (1.9.33 store build failed here).
2026-07-26 10:32:50 -07:00
Hanzo AI 054dbd8ae8 feat(answer-engine): Hanzo AI answer engine — new-tab landing + address-bar search
New-tab landing + omnibox/address-bar search + default search provider,
streaming source-cited answers via @hanzo/ai search primitive (api.hanzo.ai),
live news, model switcher from /v1/models, popup embedded search. v1.9.33.

- src/answer/: AnswerEngine (React18) + news + model-catalog + markdown
- newtab.{html,css,ts}; chrome_url_overrides.newtab + search_provider (Chrome);
  omnibox 'hanzo' + background handler (Firefox); popup embedded search
- @hanzo/ai@0.2.3 resolved from npm (lockfile updated)
2026-07-26 10:32:50 -07:00
zeekayandClaude Opus 5 7461549cd6 browser/kms: talk to /v1/kms — the SPA had been lying about the path
This client spoke Infisical under an /api/v3 prefix, and its header comment
explained why: "verified: kms.hanzo.ai/api/v3/secrets/raw -> 401 JSON,
/v1/kms/... -> SPA HTML", so /api/v3 was pinned as the live path and a gateway
rewrite was awaited.

The observation was real and the conclusion was backwards. The KMS binary
embedded a console SPA under a root catch-all and answered EVERY unmatched path
with 200 text/html — the HTML was the 404. So the path that worked looked broken
and the path that did not looked fine. luxfi/kms 1.12.8 removed the catch-all;
the same probe now reads the other way round (/v1/kms/... -> JSON,
/api/v3/... -> JSON 404). There is no rewrite to wait for.

  GET    /v1/kms/orgs/{org}/secrets?path=&env=          -> {"names": []}
  GET    /v1/kms/orgs/{org}/secrets/{path}/{name}?env=  -> {"secret":{"value"}}
  POST   /v1/kms/orgs/{org}/secrets                     {path,name,env,value}
  DELETE /v1/kms/orgs/{org}/secrets/{path}/{name}?env=

Create and update collapse into one kmsPutSecret, because the server has one
upsert rather than two endpoints. Listing is a real call now — the HTTP surface
had no list until luxfi/kms 1.12.9, which is a large part of why the Infisical
prefix looked necessary in the first place.

Params move from Infisical vocabulary (workspaceId/environment/secretPath/
secretName) to the server-s own: KmsRef {org, env, path} and KmsSecretRef adding
name. Only the tests consumed this module, so nothing downstream breaks.

Path segments are escaped one at a time: the server splits {rest...} at its LAST
slash into (path, name), and escaping the joined string would encode the
separators into a single long name. A test pins that, and another asserts no
request may contain /api/ again.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 01:07:35 -07:00
Hanzo AI 69310a0445 ci: .gitea/workflows -> .hanzo/workflows
ci / test (push) Successful in 41s
ci / build (push) Failing after 20s
De-brand the native-CI dir to the Hanzo convention. .hanzo is the highest-
priority WORKFLOW_DIR on git.hanzo.ai and GitHub ignores it exactly as it
ignored .gitea, so this is behavior-neutral on GitHub and canonical on the
native runner.
2026-07-25 18:39:56 -07:00
z 54375ec428 docs: stop describing Hanzo as LiteLLM/OpenRouter-compatible
Standing brand rule: we are not LiteLLM and do not position ourselves as one.
This file did it four times — a heading 'Complete Model Catalog (OpenRouter +
LiteLLM Compatible)', 'every model available through OpenRouter and LiteLLM',
'OpenRouter + LiteLLM = access to every AI model', and '200+ LLMs
(OpenRouter/LiteLLM compatible)' — framing our catalog as someone else's reach
rather than our own API.

Fixed HERE rather than in hanzoai/docs: that repo's content/docs/projects/ tree
is gitignored because it is synced from source repos, so an edit there is
reverted on the next sync. This file is the source.
2026-07-25 18:16:46 -07:00
Hanzo AI 6edd326615 ci: align to Hanzo native forge — Gitea CI/CD + KMS secrets, GitHub → mirror
Git of record moves to git.hanzo.ai; GitHub becomes a mirror.

- .gitea/workflows/{ci,publish}.yml — native pipeline on hanzo-build-linux-amd64
  act_runners. publish.yml pulls Chrome Web Store + Firefox AMO + npm creds from
  KMS via the machine identity (no store cred in any Actions secret store).
- deploy/kms/extension-publish-kms-sync.yaml — KMSSecret CR; canonical KMS path
  hanzo:/extension-publish (env prod) for the store creds.
- .github/workflows/sync.yml — mirror main+tags to git.hanzo.ai (the only thing
  GitHub does as system of record; no-op until HANZO_GIT_TOKEN seeded).
- .github/workflows/publish.yml — remove store-publish steps (CWS/AMO/VSCE/OVSX/
  JetBrains — all no-ops today, those secrets never existed on GitHub). Keep the
  live npm publish (interim) + the downloadable GitHub Release.
- docs: PUBLISHING.md + LLM.md rewritten to the native topology.

Non-breaking: npm publish (@hanzo/browser-extension) untouched. No store publish
in this pass. Gated on operator: seed KMS store values, Gitea secrets, mirror.
2026-07-24 23:33:15 -07:00
hanzo-dev 763e6b8eb0 build(browser): ONE stable output root at <extension-root>/dist
Derive OUT from __dirname (../../../dist) so `node src/build.js` and `pnpm
build` both land bundles at the repo-root dist/ regardless of invocation cwd.
install-linux.sh consumes dist/{firefox,chrome} at that fixed path — the
permanent non-snap dev install (Firefox ESR force-install + Brave
--load-extension) points at it.
2026-07-15 10:01:46 -07:00
hanzo-dev bee346de71 extension: install-linux.sh — permanent non-snap dev install (Firefox ESR policy force-install + Brave --load-extension)
aarch64 has no Google-Chrome build and apt ships only snap redirects for
firefox/chromium, so the reliable non-snap browsers are Firefox ESR (Mozilla
arm64 tarball) and Brave (arm64 apt). Firefox ESR gets an enterprise policy that
force-installs the unsigned XPI into every profile with signature enforcement
disabled — permanent + launch-independent. Brave loads the live dist/chrome via
a --load-extension launcher + desktop entry (rebuild → relaunch = new code, the
correct dev loop). Verified: FF addon active (unsigned), Brave MV3 SW live.
2026-07-15 10:01:46 -07:00
Hanzo Dev c258e74b95 browser: legacy CDP opt-in + gentle native-zap poll
Firefox no longer dials the dead ws://:9223/cdp bridge by default (it
error-looped); it's opt-in via globalThis.HANZO_LEGACY_CDP, matching
Chrome's native-ZAP-only default. And the ZAP native-host reconnect goes
3s -> 30s: with no MCP client there's no router, so hammering (and
re-launching the host) every 3s was pure noise — a live consumer is still
picked up within one interval. Pairs with zapd host connect-only.
2026-07-08 13:12:34 -07:00
33 changed files with 2382 additions and 402 deletions
+11 -67
View File
@@ -1,5 +1,12 @@
name: Publish
# Store-publish (Chrome Web Store, Firefox AMO, VS Code, Open VSX, JetBrains) and
# every store credential have moved to the native pipeline on Hanzo Git:
# .gitea/workflows/publish.yml — reads creds from KMS (deploy/kms/…), NOT GitHub.
# GitHub retains only: build + the downloadable GitHub Release (mirror
# distribution), and the live npm publish (interim — migrates to native once the
# KMS NPM_TOKEN is seeded and the native run is verified green).
on:
push:
tags:
@@ -17,25 +24,16 @@ permissions:
contents: write
jobs:
# ─── Check available secrets ───
# ─── npm publish gate (the one store credential still on GitHub) ───
secrets:
name: Load KMS Secrets
name: Check npm token
runs-on: hanzo-build-linux-amd64
outputs:
has-chrome: ${{ steps.check.outputs.has-chrome }}
has-firefox: ${{ steps.check.outputs.has-firefox }}
has-vsce: ${{ steps.check.outputs.has-vsce }}
has-npm: ${{ steps.check.outputs.has-npm }}
has-jetbrains: ${{ steps.check.outputs.has-jetbrains }}
steps:
- name: Check available secrets
- name: Check npm token
id: check
run: |
echo "has-chrome=${{ secrets.CHROME_EXTENSION_ID != '' }}" >> $GITHUB_OUTPUT
echo "has-firefox=${{ secrets.AMO_API_KEY != '' }}" >> $GITHUB_OUTPUT
echo "has-vsce=${{ secrets.VSCE_PAT != '' }}" >> $GITHUB_OUTPUT
echo "has-npm=${{ secrets.NPM_TOKEN != '' }}" >> $GITHUB_OUTPUT
echo "has-jetbrains=${{ secrets.JETBRAINS_TOKEN != '' }}" >> $GITHUB_OUTPUT
run: echo "has-npm=${{ secrets.NPM_TOKEN != '' }}" >> $GITHUB_OUTPUT
# ─── Chrome + Firefox ───
browser:
@@ -84,40 +82,6 @@ jobs:
run: npx web-ext lint --source-dir dist/browser-extension/firefox
continue-on-error: true
- name: Publish to Chrome Web Store
if: needs.secrets.outputs.has-chrome == 'true'
working-directory: packages/browser
run: |
ACCESS_TOKEN=$(curl -s -X POST "https://oauth2.googleapis.com/token" \
-d "client_id=${{ secrets.CHROME_CLIENT_ID }}" \
-d "client_secret=${{ secrets.CHROME_CLIENT_SECRET }}" \
-d "refresh_token=${{ secrets.CHROME_REFRESH_TOKEN }}" \
-d "grant_type=refresh_token" | jq -r '.access_token')
VERSION=$(node -p "require('./package.json').version")
curl -sf -X PUT \
"https://www.googleapis.com/upload/chromewebstore/v1.1/items/${{ secrets.CHROME_EXTENSION_ID }}" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "x-goog-api-version: 2" \
-T dist/hanzo-ai-chrome-v${VERSION}.zip
curl -sf -X POST \
"https://www.googleapis.com/chromewebstore/v1.1/items/${{ secrets.CHROME_EXTENSION_ID }}/publish" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "x-goog-api-version: 2" \
-H "Content-Length: 0"
continue-on-error: true
- name: Publish to Firefox Add-ons
if: needs.secrets.outputs.has-firefox == 'true'
working-directory: packages/browser
run: |
npx web-ext sign \
--source-dir dist/browser-extension/firefox \
--api-key "${{ secrets.AMO_API_KEY }}" \
--api-secret "${{ secrets.AMO_API_SECRET }}" \
--channel listed \
--id "hanzo-ai@hanzo.ai"
continue-on-error: true
# ─── Safari (macOS + iOS) ───
safari:
name: Safari (macOS + iOS)
@@ -228,18 +192,6 @@ jobs:
name: hanzo-ai-ide
path: packages/vscode/release-assets/*
- name: Publish to VS Code Marketplace
if: needs.secrets.outputs.has-vsce == 'true'
working-directory: packages/vscode
run: vsce publish -p ${{ secrets.VSCE_PAT }}
continue-on-error: true
- name: Publish to Open VSX
if: needs.secrets.outputs.has-vsce == 'true'
working-directory: packages/vscode
run: ovsx publish *.vsix -p ${{ secrets.OVSX_PAT }}
continue-on-error: true
# ─── npm (all @hanzo/* workspace packages) ───
npm:
name: npm
@@ -318,14 +270,6 @@ jobs:
name: hanzo-ai-jetbrains
path: /tmp/hanzo-ai-jetbrains-v*.zip
- name: Publish to JetBrains Marketplace
if: needs.secrets.outputs.has-jetbrains == 'true'
working-directory: packages/jetbrains
run: ./gradlew publishPlugin
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_TOKEN }}
continue-on-error: true
# ─── Microsoft Office add-in (Word / Excel / PowerPoint) ───
office:
name: Office Add-in
+35
View File
@@ -0,0 +1,35 @@
# Mirror GitHub → Hanzo Git (git.hanzo.ai) — the ONLY thing GitHub does as a
# system of record. Hanzo Git is the source forge; its act_runners fire the
# native pipeline (.gitea/workflows/*). GitHub is a public mirror.
#
# Credential: HANZO_GIT_TOKEN — a low-privilege Hanzo-Git push token, the ONE
# secret GitHub still holds. It is NOT a store/publish credential (those live in
# KMS only). Absent the token this no-ops with a warning, so it never blocks a
# push before the operator seeds it. Alternatively the operator enables Gitea's
# native pull-mirror server-side and this workflow becomes unnecessary.
name: sync
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
jobs:
mirror:
runs-on: hanzo-build-linux-amd64
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push to git.hanzo.ai
env:
HANZO_GIT_TOKEN: ${{ secrets.HANZO_GIT_TOKEN }}
run: |
if [ -z "$HANZO_GIT_TOKEN" ]; then
echo "::warning::HANZO_GIT_TOKEN unset — mirror skipped. Seed it (or enable Gitea pull-mirror) to activate the native forge."
exit 0
fi
git push --prune "https://x-access-token:${HANZO_GIT_TOKEN}@git.hanzo.ai/hanzoai/extension.git" \
"+refs/remotes/origin/main:refs/heads/main" "+refs/tags/*:refs/tags/*"
+49
View File
@@ -0,0 +1,49 @@
# Native CI — Hanzo Git act_runners (label hanzo-build-linux-amd64).
# amd64 test + build gate; mirrors the amd64 lanes of .github/workflows/ci.yml.
# The macOS (Safari) and cross-platform Playwright matrix stay on GitHub-hosted
# runners until native macOS/Windows act_runners are green
# (runners-act-migration.md Phase 2). act_runner reads this unmodified;
# GitHub.com ignores .hanzo/workflows, so the GitHub release lanes are untouched.
name: ci
on:
push:
branches: [main, dev]
tags: ['v*']
pull_request:
branches: [main]
jobs:
test:
runs-on: hanzo-build-linux-amd64
container: node:22-bookworm
steps:
- uses: actions/checkout@v4
- run: corepack enable
- run: pnpm install --frozen-lockfile
# Shared workspace lib first — consumers import its built dist/.
- run: pnpm --filter @hanzo/cards build
- run: pnpm --filter @hanzo/browser-extension test
- run: pnpm --filter @hanzo/aci test
- run: pnpm --filter @hanzo/auth test
build:
runs-on: hanzo-build-linux-amd64
container: node:22-bookworm
needs: [test]
steps:
- uses: actions/checkout@v4
- run: corepack enable
- run: pnpm install --frozen-lockfile
- name: Build browser extension
working-directory: packages/browser
run: node src/build.js
- name: Check bundle budgets
working-directory: packages/browser
run: |
[ -f dist/browser-extension/background.js ] || node src/build.js
pnpm run check:bundle-budget
continue-on-error: true
+102
View File
@@ -0,0 +1,102 @@
# Native store-publish — Hanzo Git act_runner (label hanzo-build-linux-amd64).
# This is the SYSTEM OF RECORD for publishing the browser extension to the
# Chrome Web Store + Firefox AMO, and for the npm package. GitHub only mirrors.
#
# Secrets model — KMS ONLY. The single bootstrap credential is the KMS machine
# identity (KMS_CLIENT_ID / KMS_CLIENT_SECRET, a git.hanzo.ai Actions secret).
# Every store credential is pulled from KMS at publish time
# (org `hanzo`, env `prod`, path `/extension-publish` — see
# deploy/kms/extension-publish-kms-sync.yaml). No CWS/AMO/npm secret is ever
# stored in GitHub or Gitea Actions secrets.
#
# amd64/Linux only. Safari (macOS) + Windows desktop stay on GitHub-hosted
# runners until native macOS/Windows act_runners are green
# (runners-act-migration.md Phase 2).
name: publish
on:
push:
tags: ['v*']
workflow_dispatch:
jobs:
publish:
runs-on: hanzo-build-linux-amd64
container: node:22-bookworm
steps:
- uses: actions/checkout@v4
- name: Tools (jq, pnpm)
run: |
apt-get update && apt-get install -y --no-install-recommends jq curl
corepack enable
- run: pnpm install --frozen-lockfile
# ── The ONE secret hop: KMS machine identity → store creds ──
# Login once, read each key from hanzo:/extension-publish, mask + export.
# A missing key exports empty; each publish step below gates on its creds,
# so partial provisioning publishes exactly what KMS has.
- name: Load publish secrets from KMS
env:
KMS_CLIENT_ID: ${{ secrets.KMS_CLIENT_ID }}
KMS_CLIENT_SECRET: ${{ secrets.KMS_CLIENT_SECRET }}
run: |
if [ -z "$KMS_CLIENT_ID" ] || [ -z "$KMS_CLIENT_SECRET" ]; then
echo "::warning::KMS machine identity absent — cannot pull publish creds. Seed KMS_CLIENT_ID/SECRET as git.hanzo.ai Actions secrets."
exit 0
fi
KMS=https://kms.hanzo.ai; ORG=hanzo; ENVN=prod; P=extension-publish
TOKEN=$(curl -sf "$KMS/v1/kms/auth/login" -H 'Content-Type: application/json' \
-d "{\"clientId\":\"$KMS_CLIENT_ID\",\"clientSecret\":\"$KMS_CLIENT_SECRET\"}" | jq -r .accessToken)
[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || { echo "::error::KMS login failed"; exit 1; }
for KEY in CHROME_EXTENSION_ID CHROME_CLIENT_ID CHROME_CLIENT_SECRET CHROME_REFRESH_TOKEN AMO_API_KEY AMO_API_SECRET NPM_TOKEN; do
VAL=$(curl -sf "$KMS/v1/kms/orgs/$ORG/secrets/$P/$KEY?env=$ENVN" \
-H "Authorization: Bearer $TOKEN" | jq -r '.secret.value // empty')
if [ -n "$VAL" ]; then echo "::add-mask::$VAL"; fi
echo "$KEY=$VAL" >> "$GITHUB_ENV"
done
- name: Build browser extension
working-directory: packages/browser
run: node src/build.js
- name: Package (web-ext — no zip binary on the runner)
working-directory: packages/browser
run: |
VERSION=$(node -p "require('./package.json').version")
npx web-ext build --source-dir dist/browser-extension/chrome --artifacts-dir dist --filename hanzo-ai-chrome-v${VERSION}.zip --overwrite-dest
npx web-ext build --source-dir dist/browser-extension/firefox --artifacts-dir dist --filename hanzo-ai-firefox-v${VERSION}.zip --overwrite-dest
- name: Publish to Chrome Web Store
if: env.CHROME_EXTENSION_ID != ''
working-directory: packages/browser
run: |
ACCESS_TOKEN=$(curl -s -X POST "https://oauth2.googleapis.com/token" \
-d "client_id=$CHROME_CLIENT_ID" -d "client_secret=$CHROME_CLIENT_SECRET" \
-d "refresh_token=$CHROME_REFRESH_TOKEN" -d "grant_type=refresh_token" | jq -r '.access_token')
VERSION=$(node -p "require('./package.json').version")
curl -sf -X PUT "https://www.googleapis.com/upload/chromewebstore/v1.1/items/$CHROME_EXTENSION_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" -H "x-goog-api-version: 2" \
-T dist/hanzo-ai-chrome-v${VERSION}.zip
curl -sf -X POST "https://www.googleapis.com/chromewebstore/v1.1/items/$CHROME_EXTENSION_ID/publish" \
-H "Authorization: Bearer $ACCESS_TOKEN" -H "x-goog-api-version: 2" -H "Content-Length: 0"
- name: Publish to Firefox Add-ons
if: env.AMO_API_KEY != ''
working-directory: packages/browser
run: |
npx web-ext sign --source-dir dist/browser-extension/firefox \
--api-key "$AMO_API_KEY" --api-secret "$AMO_API_SECRET" \
--channel listed --id "hanzo-ai@hanzo.ai"
# npm — canonical home is here. The .github npm job stays live until this
# runs green (KMS NPM_TOKEN seeded), then it is deleted. pnpm publish skips
# versions already on npm, so any transition overlap is idempotent.
- name: Publish @hanzo/* to npm
if: env.NPM_TOKEN != ''
run: |
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> .npmrc
echo "@hanzo:registry=https://registry.npmjs.org/" >> .npmrc
pnpm --filter @hanzo/cards build
pnpm -r --if-present run build || true
pnpm -r publish --access public --no-git-checks --ignore-scripts --report-summary || true
+13
View File
@@ -30,6 +30,19 @@ per-browser manifests come from `zapd install-host` (`zap-proto/zapd`).
Patch only (X.Y.Z+1), never major. `package.json` is the source of truth; `build.js`
stamps it into every manifest (chrome/firefox/safari).
## CI/CD (native — Hanzo Git, KMS, act_runner)
Git of record is `git.hanzo.ai/hanzoai/extension`; GitHub is a mirror.
- `.gitea/workflows/*` — native pipeline on `hanzo-build-linux-amd64` act_runners:
`ci.yml` (amd64 test + build), `publish.yml` (Chrome Web Store + Firefox AMO + npm).
- Secrets are **KMS only**. The pipeline logs in with the KMS machine identity
(`KMS_CLIENT_ID`/`KMS_CLIENT_SECRET`) and pulls store creds from `hanzo:/extension-publish`
(env `prod`). CR: `deploy/kms/extension-publish-kms-sync.yaml`. No store cred in
any Actions secret store.
- `.github/workflows/` mirrors + degrades gracefully: `sync.yml` pushes main+tags to
Hanzo Git; `ci.yml`/`cross-platform-e2e.yml` keep the macOS(Safari)/Windows/matrix
lanes that still need GitHub-hosted runners; `publish.yml` keeps only the GitHub
Release + the interim npm publish (store-publish removed → native). See PUBLISHING.md.
## Cross-platform — WXT migration (canonical plan, not yet executed)
One WebExtension codebase, every engine. **WXT** = build/SDK layer (build matrix,
+32 -17
View File
@@ -1,33 +1,48 @@
# Publishing Hanzo Extensions
This document describes how to publish Hanzo extensions to various marketplaces.
Publishing is NATIVE: it runs on Hanzo Git (`git.hanzo.ai`) act_runners, and
every store credential lives in Hanzo KMS. GitHub only mirrors the repo.
## Required Secrets
## Topology (one way)
Add these secrets to your GitHub repository settings:
- **Git of record:** `git.hanzo.ai/hanzoai/extension`. GitHub is a public
mirror; `.github/workflows/sync.yml` pushes `main` + tags to Hanzo Git.
- **CI/CD:** `.gitea/workflows/*` on `hanzo-build-linux-amd64` act_runners —
`ci.yml` (test + build) and `publish.yml` (Chrome Web Store + Firefox AMO + npm).
- **Secrets — KMS ONLY.** The native pipeline logs in with the KMS machine
identity (`KMS_CLIENT_ID` / `KMS_CLIENT_SECRET`) and pulls store creds from
org `hanzo`, env `prod`, path `/extension-publish`
(see `deploy/kms/extension-publish-kms-sync.yaml`). No store credential is
ever a GitHub or Gitea Actions secret.
- **amd64/Linux publishes natively.** Safari (macOS) + desktop (Windows) stay on
GitHub-hosted runners until native macOS/Windows act_runners are green
(`universe/docs/architecture/runners-act-migration.md`).
| Secret | Description | How to Get |
|--------|-------------|------------|
| `VSCE_PAT` | VS Code Marketplace token | [Create PAT](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#get-a-personal-access-token) |
| `OVSX_PAT` | Open VSX Registry token | [Create token](https://open-vsx.org/user-settings/tokens) |
| `NPM_TOKEN` | npm publish token | `npm token create` or [npm.js tokens](https://www.npmjs.com/settings/~/tokens) |
| `JETBRAINS_TOKEN` | JetBrains Marketplace token | [Generate token](https://plugins.jetbrains.com/author/me/tokens) |
| `CERTIFICATE_CHAIN` | JetBrains plugin signing cert | [Plugin signing](https://plugins.jetbrains.com/docs/intellij/plugin-signing.html) |
| `PRIVATE_KEY` | JetBrains plugin signing key | See above |
| `PRIVATE_KEY_PASSWORD` | JetBrains key password | See above |
## KMS keys the operator seeds (path `hanzo:/extension-publish`, env `prod`)
| Key(s) | Store |
|--------|-------|
| `CHROME_EXTENSION_ID`, `CHROME_CLIENT_ID`, `CHROME_CLIENT_SECRET`, `CHROME_REFRESH_TOKEN` | Chrome Web Store |
| `AMO_API_KEY`, `AMO_API_SECRET` | Firefox Add-ons |
| `NPM_TOKEN` | npm (`@hanzo/*`) |
## Publishing Methods
### Automatic (GitHub Actions)
### Automatic (native)
1. Create a GitHub release with a version tag (e.g., `v1.6.0`)
2. The `publish.yml` workflow will automatically publish to all marketplaces
Push a `vX.Y.Z` tag. GitHub mirrors it to Hanzo Git, which fires
`.gitea/workflows/publish.yml`. Or run `workflow_dispatch` on Hanzo Git.
Or manually trigger:
```bash
gh workflow run publish.yml
# version lives in packages/browser/package.json (patch only, never major)
git tag v1.9.35 && git push origin v1.9.35
```
> Interim: the live npm publish still also runs from `.github/workflows/publish.yml`
> until the KMS `NPM_TOKEN` is seeded and one native `publish.yml` run is verified
> green; then the GitHub npm job is deleted. `pnpm publish` skips versions already
> on npm, so the overlap is idempotent.
### Manual Publishing
#### VS Code Marketplace
@@ -0,0 +1,68 @@
# Store-publish credentials for the Hanzo browser extension — KMS is the ONLY home.
#
# The native publish pipeline (.gitea/workflows/publish.yml, act_runner on
# git.hanzo.ai) reads these at publish time. No store credential lives in a
# GitHub or Gitea Actions secret — the ONLY bootstrap credential is the KMS
# machine identity (KMS_CLIENT_ID / KMS_CLIENT_SECRET), already provisioned.
#
# ── Operator steps (the VALUES are the store-account owner's; not in git) ──
# 1. KMS (kms.hanzo.ai) → org `hanzo`, env `prod`, project path `/extension-publish`.
# Add the keys below. These are the Chrome Web Store + Firefox AMO
# credentials — the store-account owner drops the real values here:
# CHROME_EXTENSION_ID Chrome Web Store item id
# CHROME_CLIENT_ID Google OAuth client id (CWS API)
# CHROME_CLIENT_SECRET Google OAuth client secret
# CHROME_REFRESH_TOKEN Google OAuth refresh token
# AMO_API_KEY addons.mozilla.org JWT issuer
# AMO_API_SECRET addons.mozilla.org JWT secret
# Optional (same path, if these stores are moved off GitHub too):
# VSCE_PAT OVSX_PAT JETBRAINS_TOKEN NPM_TOKEN
# kms secret set --project hanzo --env prod --path /extension-publish \
# CHROME_EXTENSION_ID "<value>" # …repeat per key
# 2. Grant the extension repo's KMS machine identity (the KMS_CLIENT_ID it
# already uses) READ on project `hanzo`, path `/extension-publish`.
# 3. Re-provision KMS_CLIENT_ID / KMS_CLIENT_SECRET as git.hanzo.ai Actions
# secrets so the native runner can log in (they exist on GitHub today —
# runners-act-migration.md Phase 1.2).
#
# Canonical GitOps home is universe/infra/k8s/kms-canonical-crs/hanzo/ (generated
# by scripts/kms-canonical-v1alpha1-gen.py). This in-repo copy is the extension's
# declared secret contract — reflect it into universe, do not diverge.
---
apiVersion: secrets.lux.network/v1alpha1
kind: KMSSecret
metadata:
name: extension-publish-kms-sync
namespace: hanzo
labels:
app.kubernetes.io/name: extension
app.kubernetes.io/component: kms-secret
app.kubernetes.io/part-of: hanzo-universe
kms.hanzo.ai/org: hanzo
kms.hanzo.ai/env: prod
spec:
hostAPI: http://kms.hanzo.svc
resyncInterval: 60
authentication:
universalAuth:
# Shared platform machine identity (same as the other hanzo CRs). The
# operator scopes it to read /extension-publish.
credentialsRef:
secretName: hanzo-platform-iam-creds
secretNamespace: hanzo
secretsScope:
projectSlug: hanzo
envSlug: prod
secretsPath: /extension-publish
keys:
- CHROME_EXTENSION_ID
- CHROME_CLIENT_ID
- CHROME_CLIENT_SECRET
- CHROME_REFRESH_TOKEN
- AMO_API_KEY
- AMO_API_SECRET
managedSecretReference:
secretName: extension-publish-secrets
secretNamespace: hanzo
secretType: Opaque
creationPolicy: Orphan
+4 -4
View File
@@ -53,9 +53,9 @@ The Hanzo agent automatically detects and uses available LLM providers in this o
- Access to all models with credits
- Managed API keys in Hanzo Cloud
## Complete Model Catalog (OpenRouter + LiteLLM Compatible)
## Complete Model Catalog
Hanzo AI provides access to every model available through OpenRouter and LiteLLM, including:
Hanzo AI provides access to every major model through one API, including:
- **OpenAI**: O3-Pro, O3, GPT-4o, GPT-4 Turbo, GPT-4, GPT-3.5 Turbo
- **Anthropic**: Claude 4, Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Sonnet, Claude 3 Haiku
@@ -159,7 +159,7 @@ export OLLAMA_BASE_URL=http://localhost:11434
## Why AI Engineers Choose Hanzo AI
### 🎯 **The Complete Toolkit**
- **Every Model**: OpenRouter + LiteLLM = access to every AI model
- **Every Model**: one API across every major provider and our own Zen family
- **Every Tool**: 4000+ MCP servers for specialized capabilities
- **Every Provider**: OpenAI, Anthropic, Google, Meta, Mistral, and 50+ more
@@ -300,6 +300,6 @@ Error: Model xyz not available through Hanzo AI
- **Dashboard**: [iam.hanzo.ai](https://iam.hanzo.ai)
- **Support**: support@hanzo.ai
**Hanzo AI is the unified platform for building AI-powered companies.** Access 200+ LLMs (OpenRouter/LiteLLM compatible), 4000+ MCP servers, legendary programmer modes, unlimited memory with vector/graph/relational search, browser automation, and everything you need to supercharge AI development.
**Hanzo AI is the unified platform for building AI-powered companies.** Access 200+ models through one API, 4000+ MCP servers, legendary programmer modes, unlimited memory with vector/graph/relational search, browser automation, and everything you need to supercharge AI development.
🚀 **[Get Started](https://iam.hanzo.ai)** | 📖 **[View Modes & Features](./HANZO_MODES.md)** | 💬 **[Join Discord](https://discord.gg/hanzoai)**
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/extension",
"version": "1.9.32",
"version": "1.9.36",
"private": true,
"description": "Hanzo AI Extension",
"license": "MIT",
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# Permanent local-dev install of the Hanzo browser extension on Linux — NO snap,
# NO web store, NO signing service. Builds from source and installs into:
#
# • Firefox ESR (/opt/firefox-esr) via an enterprise policy that
# force-installs the unsigned XPI into EVERY profile (signatures disabled).
# Truly permanent + launch-independent: any launch of that Firefox has it.
#
# • Brave (Chromium-family; arm64 has no Google-Chrome build) via a
# --load-extension launcher (/usr/local/bin/hanzo-brave + a desktop entry).
# The extension loads from the live dist dir, so a rebuild + relaunch picks
# up new code — the correct dev loop (no re-pack per change).
#
# Why these two: on this box (aarch64) apt ships ONLY snap redirects for
# firefox/chromium, and Google Chrome has no Linux arm64 build. Firefox ESR and
# Brave are the reliable non-snap arm64 browsers. On x86_64 the same script
# works; swap Brave for google-chrome if preferred.
#
# Re-run after any `node src/build.js` to redeploy. Idempotent.
set -euo pipefail
REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
EXT_ROOT="$(cd "$REPO_DIR/../.." && pwd)" # ~/work/hanzo/extension
DIST="$EXT_ROOT/dist"
STABLE=/opt/hanzo-ext # stable install location
FF=/opt/firefox-esr
echo "==> building extension from source"
( cd "$REPO_DIR" && node src/build.js )
[ -d "$DIST/firefox" ] && [ -d "$DIST/chrome" ] || { echo "build did not produce dist/{firefox,chrome}"; exit 1; }
echo "==> packaging Firefox XPI"
XPI=/tmp/hanzo-ai.xpi
( cd "$DIST/firefox" && rm -f "$XPI" && zip -qr -X "$XPI" . )
GECKO_ID=$(python3 -c 'import json;m=json.load(open("'"$DIST"'/firefox/manifest.json"));print((m.get("browser_specific_settings") or m.get("applications") or {}).get("gecko",{}).get("id",""))')
[ -n "$GECKO_ID" ] || { echo "firefox manifest has no gecko id"; exit 1; }
echo "==> staging stable copies under $STABLE (needs sudo)"
sudo mkdir -p "$STABLE"
sudo cp "$XPI" "$STABLE/hanzo-ai.xpi"
sudo rm -rf "$STABLE/chrome" && sudo cp -r "$DIST/chrome" "$STABLE/chrome"
if [ -x "$FF/firefox" ]; then
echo "==> Firefox ESR enterprise policy (force-install + signatures off)"
sudo mkdir -p "$FF/distribution"
sudo tee "$FF/distribution/policies.json" >/dev/null <<JSON
{
"policies": {
"ExtensionSettings": {
"$GECKO_ID": { "installation_mode": "force_installed", "install_url": "file://$STABLE/hanzo-ai.xpi" }
},
"Preferences": { "xpinstall.signatures.required": { "Value": false, "Status": "locked" } },
"DisableAppUpdate": true
}
}
JSON
else
echo "!! Firefox ESR not at $FF — install it (Mozilla arm64 ESR tarball) then re-run"
fi
if command -v brave-browser >/dev/null 2>&1; then
echo "==> Brave --load-extension launcher + desktop entry"
sudo tee /usr/local/bin/hanzo-brave >/dev/null <<'SH'
#!/bin/bash
exec /usr/bin/brave-browser --load-extension=/opt/hanzo-ext/chrome "$@"
SH
sudo chmod +x /usr/local/bin/hanzo-brave
sudo tee /usr/share/applications/brave-hanzo-dev.desktop >/dev/null <<'DESK'
[Desktop Entry]
Version=1.0
Name=Brave (Hanzo Dev)
Comment=Brave with the local Hanzo browser extension
Exec=/usr/local/bin/hanzo-brave %U
Terminal=false
Type=Application
Icon=brave-browser
Categories=Network;WebBrowser;
DESK
else
echo "!! brave-browser not found — install it, then re-run"
fi
CHROME_ID=$(python3 - <<PY
import json,base64,hashlib
m=json.load(open("$DIST/chrome/manifest.json")); k=m.get("key")
if k:
h=hashlib.sha256(base64.b64decode(k)).hexdigest()[:32]
print(''.join(chr(ord('a')+int(c,16)) for c in h))
PY
)
echo
echo "DONE."
echo " Firefox: launch $FF/firefox (extension $GECKO_ID force-installed, every profile)"
echo " Brave: launch hanzo-brave (extension ${CHROME_ID:-<key-derived>} via --load-extension)"
echo " Rebuild loop: node src/build.js && ./install-linux.sh (then relaunch the browser)"
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/browser-extension",
"version": "1.9.32",
"version": "1.9.36",
"description": "Hanzo AI Browser Extension",
"main": "dist/background.js",
"scripts": {
@@ -12,6 +12,8 @@
"check:bundle-budget": "node scripts/check-bundle-budgets.mjs"
},
"dependencies": {
"@hanzo/ai": "^0.2.3",
"@hanzo/usage": "^0.1.6",
"@supabase/supabase-js": "^2.50.3",
"axios": "^1.10.0",
"chalk": "^4.1.2",
@@ -0,0 +1,561 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createAiClient, type SearchEvent, type SearchMode, type SearchSource } from '@hanzo/ai';
import { fetchNews, type NewsItem } from './news.js';
import { AUTO_MODEL, fetchModelCatalog, type ChatModel, type ModelGroup } from './model-catalog.js';
import { renderMarkdown } from './markdown.js';
import { capture, contributeTrainingSample } from '../shared/consent.js';
/**
* Hanzo Answer Engine — the shared AI-answer surface (query → streamed answer +
* inline citations + sources + live news). Backend = api.hanzo.ai ONLY, reached
* through the @hanzo/ai `search`/`deepResearch` primitive (the one place the
* capability is defined). Rendered on the @hanzo/gui primitive surface; strict
* monochrome per the Hanzo brand.
*/
export interface AnswerEngineProps {
apiBase: string;
/** Resolves the current IAM bearer, or null when signed out. */
getToken: () => Promise<string | null>;
/** Kicks off IAM sign-in (opens the OAuth tab). */
signIn: () => void;
/** Optional initial query (from the omnibox / address bar `?q=`). */
initialQuery?: string;
}
const MODES: { id: SearchMode; label: string; hint: string }[] = [
{ id: 'search', label: 'Search', hint: 'Fast grounded answer' },
{ id: 'news', label: 'News', hint: 'Recency-biased' },
{ id: 'research', label: 'Research', hint: 'Multi-source synthesis' },
{ id: 'deep', label: 'Deep', hint: 'Plan + wide research' },
];
const SOURCE_CHIPS = ['web', 'news', 'academic', 'github', 'reddit', 'x'];
// Hanzo tiers mirror @hanzo/plans (the SoT for pricing); shown in the picker's
// upgrade banner. Full plan detail lives at console.hanzo.ai/pricing.
const PLAN_TIERS = [
{ name: 'Pro', price: '$20' },
{ name: 'Max', price: '$100' },
{ name: 'Ultra', price: '$200' },
];
function HanzoMark({ size = 28 }: { size?: number }) {
return (
<svg viewBox="0 0 67 67" width={size} height={size} xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M22.21 67V44.6369H0V67H22.21Z" fill="currentColor" />
<path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z" fill="currentColor" />
<path d="M22.21 0H0V22.3184H22.21V0Z" fill="currentColor" />
<path d="M66.7198 0H44.5098V22.3184H66.7198V0Z" fill="currentColor" />
<path d="M66.7198 67V44.6369H44.5098V67H66.7198Z" fill="currentColor" />
</svg>
);
}
function ModelPicker({
groups,
current,
onPick,
}: {
groups: ModelGroup[];
current: ChatModel;
onPick: (m: ChatModel) => void;
}) {
const [open, setOpen] = useState(false);
const [filter, setFilter] = useState('');
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', onDoc);
return () => document.removeEventListener('mousedown', onDoc);
}, [open]);
const q = filter.trim().toLowerCase();
const shown = useMemo(
() =>
groups
.map((g) => ({
...g,
models: g.models.filter(
(m) => !q || m.name.toLowerCase().includes(q) || m.id.toLowerCase().includes(q),
),
}))
.filter((g) => g.models.length),
[groups, q],
);
return (
<div className="ae-picker" ref={ref}>
<button className="ae-picker-btn" onClick={() => setOpen((v) => !v)} title="Choose model">
<span className="ae-dot" />
{current.name}
<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
<path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="1.5" />
</svg>
</button>
{open && (
<div className="ae-picker-menu">
<input
className="ae-picker-filter"
placeholder="Search models…"
value={filter}
autoFocus
onChange={(e) => setFilter(e.target.value)}
/>
<div className="ae-picker-list">
<button
className={'ae-model-row' + (current.id === AUTO_MODEL.id ? ' active' : '')}
onClick={() => {
onPick(AUTO_MODEL);
setOpen(false);
}}
>
<span className="ae-model-name">Auto</span>
<span className="ae-model-desc">Routes to the best model</span>
</button>
{shown.map((g) => (
<div key={g.family} className="ae-model-group">
<div className="ae-model-group-label">{g.label}</div>
{g.models.map((m) => (
<button
key={m.id}
className={'ae-model-row' + (current.id === m.id ? ' active' : '')}
onClick={() => {
onPick(m);
setOpen(false);
}}
>
<span className="ae-model-name">
{m.name}
{m.tier && <span className="ae-badge">{m.tier}</span>}
</span>
{m.description && <span className="ae-model-desc">{m.description}</span>}
</button>
))}
</div>
))}
</div>
<a className="ae-plan-banner" href="https://console.hanzo.ai/pricing" target="_blank" rel="noreferrer">
<span>Unlock every model</span>
<span className="ae-plan-tiers">
{PLAN_TIERS.map((t) => (
<span key={t.name} className="ae-plan-tier">
{t.name} <b>{t.price}</b>
</span>
))}
</span>
</a>
</div>
)}
</div>
);
}
function SourceCard({ s, index }: { s: SearchSource; index: number }) {
let host = '';
try {
host = new URL(s.url).hostname.replace(/^www\./, '');
} catch {
host = s.url;
}
return (
<a className="ae-source" href={s.url} target="_blank" rel="noreferrer" title={s.title}>
<span className="ae-source-head">
{s.favicon ? <img src={s.favicon} alt="" width="14" height="14" /> : <span className="ae-dot" />}
<span className="ae-source-host">{host}</span>
<span className="ae-source-idx">{index + 1}</span>
</span>
<span className="ae-source-title">{s.title}</span>
</a>
);
}
function InputCard({
value,
onChange,
onSubmit,
mode,
setMode,
sources,
toggleSource,
models,
model,
setModel,
busy,
}: {
value: string;
onChange: (v: string) => void;
onSubmit: () => void;
mode: SearchMode;
setMode: (m: SearchMode) => void;
sources: Set<string>;
toggleSource: (s: string) => void;
models: ModelGroup[];
model: ChatModel;
setModel: (m: ChatModel) => void;
busy: boolean;
}) {
const taRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
const ta = taRef.current;
if (!ta) return;
ta.style.height = 'auto';
ta.style.height = Math.min(ta.scrollHeight, 200) + 'px';
}, [value]);
return (
<div className="ae-card">
<textarea
ref={taRef}
className="ae-input"
placeholder="Type @ for sources or / for modes"
value={value}
rows={1}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
onSubmit();
}
}}
/>
<div className="ae-card-row">
<div className="ae-chips">
{SOURCE_CHIPS.map((s) => (
<button
key={s}
className={'ae-chip' + (sources.has(s) ? ' on' : '')}
onClick={() => toggleSource(s)}
title={`@${s}`}
>
@{s}
</button>
))}
</div>
<div className="ae-card-right">
<div className="ae-modes">
{MODES.map((m) => (
<button
key={m.id}
className={'ae-mode' + (mode === m.id ? ' on' : '')}
onClick={() => setMode(m.id)}
title={m.hint}
>
{m.label}
</button>
))}
</div>
<ModelPicker groups={models} current={model} onPick={setModel} />
<button className="ae-send" onClick={onSubmit} disabled={busy || !value.trim()} title="Search (Enter)">
{busy ? (
<span className="ae-spinner" />
) : (
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
<path d="M3 13V3l10 5-10 5z" fill="currentColor" />
</svg>
)}
</button>
</div>
</div>
</div>
);
}
export function AnswerEngine({ apiBase, getToken, signIn, initialQuery }: AnswerEngineProps) {
const [collapsed, setCollapsed] = useState(false);
const [query, setQuery] = useState('');
const [submitted, setSubmitted] = useState('');
const [mode, setMode] = useState<SearchMode>('search');
const [sources, setSources] = useState<Set<string>>(new Set());
const [modelGroups, setModelGroups] = useState<ModelGroup[]>([]);
const [model, setModel] = useState<ChatModel>(AUTO_MODEL);
const [news, setNews] = useState<NewsItem[]>([]);
const [phase, setPhase] = useState<'idle' | 'running' | 'done'>('idle');
const [status, setStatus] = useState('');
const [answer, setAnswer] = useState('');
const [answerSources, setAnswerSources] = useState<SearchSource[]>([]);
const [followUps, setFollowUps] = useState<string[]>([]);
const [error, setError] = useState('');
const [needAuth, setNeedAuth] = useState(false);
const abortRef = useRef<AbortController | null>(null);
// Load real model catalog + live news (both public — work signed out).
// Default stays on Auto ("routes to the best model"); the picker changes it.
useEffect(() => {
fetchModelCatalog(apiBase)
.then(({ groups }) => setModelGroups(groups))
.catch(() => {});
fetchNews().then(setNews).catch(() => {});
}, [apiBase]);
const client = useMemo(
() =>
createAiClient({
baseUrl: apiBase,
getToken: async () => {
const t = await getToken();
if (!t) throw new Error('__NO_TOKEN__');
return t;
},
}),
[apiBase, getToken],
);
const run = useCallback(
async (q: string) => {
const question = q.trim();
if (!question) return;
abortRef.current?.abort();
const ctrl = new AbortController();
abortRef.current = ctrl;
setSubmitted(question);
setPhase('running');
setStatus('Searching the web');
setAnswer('');
setAnswerSources([]);
setFollowUps([]);
setError('');
setNeedAuth(false);
void capture('answer_search', { mode, model: model.id });
let fullAnswer = '';
const opts = {
mode,
model: model.id,
sources: [...sources],
signal: ctrl.signal,
};
try {
for await (const ev of client.search(question, opts) as AsyncGenerator<SearchEvent>) {
switch (ev.type) {
case 'status':
setStatus(
ev.stage === 'planning'
? 'Planning research'
: ev.stage === 'searching'
? 'Searching the web' + (ev.detail ? `: ${ev.detail}` : '')
: ev.stage === 'reading'
? 'Reading sources'
: 'Writing the answer',
);
break;
case 'sources':
setAnswerSources(ev.sources);
break;
case 'text':
fullAnswer += ev.delta;
setAnswer((a) => a + ev.delta);
break;
case 'follow_ups':
setFollowUps(ev.questions);
break;
case 'done':
setPhase('done');
void capture('answer_shown', { mode, model: model.id });
// Opt-in only: no-ops unless the user turned on training
// contribution (the consent module gates the send).
void contributeTrainingSample({ query: question, answer: fullAnswer, model: model.id });
break;
case 'error':
if (ev.error.includes('__NO_TOKEN__') || /401|invalid api key/i.test(ev.error)) {
setNeedAuth(true);
} else {
setError(ev.error);
}
setPhase('done');
break;
}
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (msg.includes('__NO_TOKEN__') || /401|invalid api key/i.test(msg)) setNeedAuth(true);
else setError(msg);
setPhase('done');
}
},
[client, mode, model, sources],
);
// Fire the initial (address-bar) query once models are ready enough.
const didInit = useRef(false);
useEffect(() => {
if (didInit.current || !initialQuery) return;
didInit.current = true;
setQuery(initialQuery);
void run(initialQuery);
}, [initialQuery, run]);
const submit = useCallback(() => void run(query), [query, run]);
const toggleSource = useCallback((s: string) => {
setSources((prev) => {
const next = new Set(prev);
next.has(s) ? next.delete(s) : next.add(s);
return next;
});
}, []);
const newThread = useCallback(() => {
abortRef.current?.abort();
setPhase('idle');
setQuery('');
setSubmitted('');
setAnswer('');
setAnswerSources([]);
setFollowUps([]);
setError('');
setNeedAuth(false);
}, []);
return (
<div className={'ae-root' + (collapsed ? ' collapsed' : '')}>
<aside className="ae-sidebar">
<div className="ae-side-top">
<button className="ae-brand" onClick={newThread} title="Hanzo">
<HanzoMark size={22} />
{!collapsed && <span>Hanzo</span>}
</button>
<button className="ae-collapse" onClick={() => setCollapsed((v) => !v)} title="Toggle sidebar">
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<path d="M6 3v10M3 3h10v10H3z" fill="none" stroke="currentColor" strokeWidth="1.3" />
</svg>
</button>
</div>
<button className="ae-new" onClick={newThread}>
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
<path d="M8 3v10M3 8h10" fill="none" stroke="currentColor" strokeWidth="1.5" />
</svg>
{!collapsed && <span>New thread</span>}
</button>
<nav className="ae-nav">
<a href="https://hanzo.chat" target="_blank" rel="noreferrer">Threads</a>
<a href="https://docs.hanzo.ai" target="_blank" rel="noreferrer">Docs</a>
<a href="https://hanzo.ai" target="_blank" rel="noreferrer">About</a>
</nav>
<div className="ae-side-bottom">
<button className="ae-signin" onClick={signIn}>
{collapsed ? '↪' : 'Sign in — free to start'}
</button>
</div>
</aside>
<main className="ae-main">
{phase === 'idle' ? (
<div className="ae-hero">
<div className="ae-wordmark">
<HanzoMark size={44} />
<span>Hanzo</span>
</div>
<div className="ae-hero-card">
<InputCard
value={query}
onChange={setQuery}
onSubmit={submit}
mode={mode}
setMode={setMode}
sources={sources}
toggleSource={toggleSource}
models={modelGroups}
model={model}
setModel={setModel}
busy={false}
/>
</div>
{news.length > 0 && (
<div className="ae-news">
<div className="ae-news-head">Top stories</div>
<div className="ae-news-grid">
{news.slice(0, 6).map((n) => (
<a key={n.url} className="ae-news-item" href={n.url} target="_blank" rel="noreferrer">
<span className="ae-news-title">{n.title}</span>
<span className="ae-news-meta">
{n.source}
{typeof n.points === 'number' ? ` · ${n.points} pts` : ''}
</span>
</a>
))}
</div>
</div>
)}
</div>
) : (
<div className="ae-answer-wrap">
<div className="ae-answer-scroll">
<h1 className="ae-question">{submitted}</h1>
{answerSources.length > 0 && (
<div className="ae-sources">
{answerSources.map((s, i) => (
<SourceCard key={s.url} s={s} index={i} />
))}
</div>
)}
{phase === 'running' && !answer && (
<div className="ae-status">
<span className="ae-spinner" /> {status}
</div>
)}
{needAuth ? (
<div className="ae-auth">
<p>Sign in with Hanzo to get AI answers.</p>
<button className="ae-signin big" onClick={signIn}>
Sign in free to start
</button>
</div>
) : error ? (
<div className="ae-error">{error}</div>
) : (
<div
className="ae-answer markdown"
dangerouslySetInnerHTML={{ __html: renderMarkdown(answer) }}
/>
)}
{followUps.length > 0 && (
<div className="ae-followups">
<div className="ae-followups-head">Follow-up</div>
{followUps.map((f) => (
<button
key={f}
className="ae-followup"
onClick={() => {
setQuery(f);
void run(f);
}}
>
{f}
<span className="ae-followup-arrow"></span>
</button>
))}
</div>
)}
</div>
<div className="ae-answer-composer">
<InputCard
value={query}
onChange={setQuery}
onSubmit={submit}
mode={mode}
setMode={setMode}
sources={sources}
toggleSource={toggleSource}
models={modelGroups}
model={model}
setModel={setModel}
busy={phase === 'running'}
/>
</div>
</div>
)}
</main>
</div>
);
}
+80
View File
@@ -0,0 +1,80 @@
/**
* Minimal, XSS-safe Markdown → HTML for the streamed answer. Escapes first,
* then applies a small whitelist of inline/block transforms. Only http(s) links
* are emitted. No dependency — the answer only needs headings, bold/italic,
* code, inline `[text](url)` citations, and bullet/number lists.
*/
function escapeHtml(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function inline(s: string): string {
let out = escapeHtml(s);
// Inline code first so its contents aren't further transformed.
out = out.replace(/`([^`]+)`/g, (_m, c) => `<code>${c}</code>`);
// [text](url) — only http(s) URLs; text keeps prior transforms applied after.
out = out.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (_m, text, url) => {
const safeUrl = url.replace(/"/g, '%22');
return `<a href="${safeUrl}" target="_blank" rel="noreferrer">${text}</a>`;
});
out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
out = out.replace(/(^|[^*])\*([^*]+)\*/g, '$1<em>$2</em>');
return out;
}
export function renderMarkdown(md: string): string {
const lines = md.replace(/\r\n/g, '\n').split('\n');
const html: string[] = [];
let listType: 'ul' | 'ol' | null = null;
const closeList = () => {
if (listType) {
html.push(`</${listType}>`);
listType = null;
}
};
for (const raw of lines) {
const line = raw.trimEnd();
if (!line.trim()) {
closeList();
continue;
}
const heading = /^(#{1,4})\s+(.*)$/.exec(line);
if (heading) {
closeList();
const level = heading[1].length + 1; // h2..h5
html.push(`<h${level}>${inline(heading[2])}</h${level}>`);
continue;
}
const bullet = /^[-*]\s+(.*)$/.exec(line);
if (bullet) {
if (listType !== 'ul') {
closeList();
html.push('<ul>');
listType = 'ul';
}
html.push(`<li>${inline(bullet[1])}</li>`);
continue;
}
const numbered = /^\d+\.\s+(.*)$/.exec(line);
if (numbered) {
if (listType !== 'ol') {
closeList();
html.push('<ol>');
listType = 'ol';
}
html.push(`<li>${inline(numbered[1])}</li>`);
continue;
}
closeList();
html.push(`<p>${inline(line)}</p>`);
}
closeList();
return html.join('\n');
}
@@ -0,0 +1,88 @@
/**
* Hanzo model catalog for the answer-engine model picker. Reads the REAL
* catalog from `GET api.hanzo.ai/v1/models` (public, no auth) and keeps the
* text/chat families — never a hardcoded or fabricated list. Switching the
* picker actually changes the `model` passed to the @hanzo/ai search primitive.
*/
export interface ChatModel {
id: string;
name: string;
description: string;
tier: string;
family: string;
context: number | null;
}
export interface ModelGroup {
family: string;
label: string;
models: ChatModel[];
}
interface ModelRow {
id: string;
name?: string;
fullName?: string;
description?: string;
tier?: string;
context?: number | null;
}
interface FamilyRow {
id: string;
name?: string;
description?: string;
models?: string[];
}
interface ModelsResponse {
data?: ModelRow[];
families?: FamilyRow[];
}
/** Text/chat families to surface in the picker (embedding/image/audio excluded). */
const CHAT_FAMILIES = ["enso", "zen5", "zen3"];
/** The "let the gateway route" option — mirrors Scira's Auto. */
export const AUTO_MODEL: ChatModel = {
id: "auto",
name: "Auto",
description: "Routes to the best model",
tier: "",
family: "auto",
context: null,
};
export async function fetchModelCatalog(
apiBase: string,
signal?: AbortSignal,
): Promise<{ groups: ModelGroup[]; flat: ChatModel[] }> {
const res = await fetch(`${apiBase}/v1/models`, signal ? { signal } : {});
if (!res.ok) throw new Error(`models ${res.status}`);
const body = (await res.json()) as ModelsResponse;
const byId = new Map<string, ModelRow>();
for (const row of body.data ?? []) byId.set(row.id, row);
const groups: ModelGroup[] = [];
for (const fam of body.families ?? []) {
if (!CHAT_FAMILIES.includes(fam.id)) continue;
const models: ChatModel[] = [];
for (const id of fam.models ?? []) {
const row = byId.get(id);
models.push({
id,
name: row?.name || row?.fullName || id,
description: row?.description || "",
tier: row?.tier || "",
family: fam.id,
context: row?.context ?? null,
});
}
if (models.length) {
groups.push({ family: fam.id, label: fam.name || fam.id, models });
}
}
const flat = groups.flatMap((g) => g.models);
return { groups, flat };
}
+83
View File
@@ -0,0 +1,83 @@
/**
* Realtime news / world feed for the Hanzo answer engine.
*
* ONE provider interface, two implementations:
* - `hanzo` — the Hanzo cloud feed (api.hanzo.ai). This is the intended
* source; the cloud endpoint does not exist yet (see the Scira→clients/ai
* capability-port plan), so it is the clearly-marked SEAM. When cloud ships
* a news endpoint, set DEFAULT_FEED = 'hanzo' and nothing else changes.
* - `hackernews` — a real, keyless, CORS-open live feed (Hacker News via the
* Algolia API). The working default today. NOT a fabricated feed.
*/
export interface NewsItem {
title: string;
url: string;
source: string;
points?: number;
comments?: number;
author?: string;
}
export interface FeedProvider {
id: string;
label: string;
fetch(signal?: AbortSignal): Promise<NewsItem[]>;
}
/** Real live feed — Hacker News front page (keyless, `access-control-allow-origin: *`). */
const hackerNews: FeedProvider = {
id: "hackernews",
label: "Top stories",
async fetch(signal) {
const res = await fetch(
"https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=12",
signal ? { signal } : {},
);
if (!res.ok) throw new Error(`news ${res.status}`);
const data = (await res.json()) as { hits?: Array<Record<string, unknown>> };
return (data.hits ?? [])
.map((h) => ({
title: String(h.title ?? ""),
url: String(h.url ?? ""),
source: "Hacker News",
points: typeof h.points === "number" ? h.points : undefined,
comments: typeof h.num_comments === "number" ? h.num_comments : undefined,
author: typeof h.author === "string" ? h.author : undefined,
}))
.filter((n) => n.title && n.url);
},
};
/**
* The Hanzo cloud feed SEAM. Wire to `GET api.hanzo.ai/v1/news` once the cloud
* capability port lands; until then it throws so callers fall back to the real
* feed above. Kept here so the swap is one line (DEFAULT_FEED = 'hanzo').
*/
export function hanzoFeed(apiBase: string, getToken: () => Promise<string | null>): FeedProvider {
return {
id: "hanzo",
label: "Hanzo News",
async fetch(signal) {
const token = await getToken();
const res = await fetch(`${apiBase}/v1/news`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
...(signal ? { signal } : {}),
});
if (!res.ok) throw new Error(`hanzo news ${res.status}`);
const data = (await res.json()) as { items?: NewsItem[] };
return data.items ?? [];
},
};
}
/** Active feed. Flip to 'hanzo' when the cloud news endpoint ships. */
export const DEFAULT_FEED = "hackernews";
export async function fetchNews(signal?: AbortSignal): Promise<NewsItem[]> {
try {
return await hackerNews.fetch(signal);
} catch {
return [];
}
}
+33 -1
View File
@@ -110,7 +110,11 @@ class HanzoFirefoxExtension {
constructor() {
console.log('[Hanzo] Firefox extension initializing...');
this.connect();
// Legacy ws://:9223 CDP bridge is OPT-IN (globalThis.HANZO_LEGACY_CDP). The
// default (and only) transport is the ZAP native host — see
// discoverZapServers() at EOF — matching Chrome. Without a bridge server the
// WS just error-looped, so it no longer runs unless explicitly enabled.
if ((globalThis as { HANZO_LEGACY_CDP?: boolean }).HANZO_LEGACY_CDP) this.connect();
}
private connect(): void {
@@ -3084,4 +3088,32 @@ browser.tabs.onRemoved.addListener((tabId) => {
}
});
// ── Omnibox → Hanzo answer engine ────────────────────────────────────────
// Firefox's address bar can't be silently hijacked (a security boundary), and
// `chrome_settings_overrides.search_provider` default-engine takeover is policy
// gated. The WebExtension mechanism that DOES work without opt-in is the
// omnibox keyword: type `hanzo <query>` in the address bar → the query loads
// the Hanzo answer engine (AI answer + sources + news) with ?q=. Same surface
// as the new-tab landing.
try {
const omnibox = (browser as any).omnibox;
if (omnibox) {
omnibox.setDefaultSuggestion({
description: 'Search Hanzo AI — AI answers with sources and realtime news',
});
omnibox.onInputEntered.addListener((text: string, disposition: string) => {
const url = browser.runtime.getURL('newtab.html') + '?q=' + encodeURIComponent(text);
if (disposition === 'newForegroundTab') {
void browser.tabs.create({ url });
} else if (disposition === 'newBackgroundTab') {
void browser.tabs.create({ url, active: false });
} else {
void browser.tabs.update({ url });
}
});
}
} catch (e) {
console.warn('[Hanzo] omnibox unavailable:', e);
}
console.log('[Hanzo] Firefox background script loaded');
+10 -1
View File
@@ -283,9 +283,18 @@ async function stopControlSession(): Promise<void> {
void loadDebugFlagFromStorage();
// Initialize WebGPU, Ollama, and CDP on install
chrome.runtime.onInstalled.addListener(async () => {
chrome.runtime.onInstalled.addListener(async (details) => {
debugLog('[Hanzo] Extension installed, initializing...');
// First install → open the consent onboarding once (insights + opt-in training).
if (details?.reason === 'install') {
try {
await chrome.tabs.create({ url: chrome.runtime.getURL('onboarding.html') });
} catch {
/* non-fatal — settings still reachable from the popup */
}
}
// WebGPU init
const gpuAvailable = await webgpuAI.initialize();
if (gpuAvailable) {
+82 -64
View File
@@ -5,8 +5,18 @@ const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// ONE output root: the extension repo root's `dist/` (NOT packages/browser/dist),
// so every build lands at a short, stable path — `<extension-root>/dist/chrome`
// is the Load-unpacked / native-messaging target, regardless of where `node
// src/build.js` (or `pnpm build`) is invoked from. Derived from __dirname
// (packages/browser/src → ../../../) so it's cwd-independent. Per-browser bundles
// sit directly under OUT; the shared staging bundles + npm files sit at OUT root.
const OUT = path.resolve(__dirname, '..', '..', '..', 'dist');
const out = (...p) => path.join(OUT, ...p);
async function build() {
console.log('Building browser extension...');
console.log('Output root:', OUT);
// The extension does NOT depend on `@hanzo/ui`. Primitives are served by
// a small local shim aliased as `@hanzo/gui` so call-sites read like the
@@ -17,24 +27,26 @@ async function build() {
console.log('Using @hanzo/gui local primitives shim:', hanzoGuiShim);
// The Usage panel runs the headless @hanzo/usage engine in the background
// context. The package lives in the sibling repo (hanzoai/usage); alias its
// built ESM entry so esbuild bundles it into the background scripts. Same
// pattern as the @hanzo/gui shim above — one specifier, one source of truth.
const hanzoUsage = path.join(__dirname, '..', '..', '..', '..', 'usage', 'packages', 'core', 'dist', 'index.js');
const backgroundAliases = { '@hanzo/usage': hanzoUsage };
console.log('Using @hanzo/usage engine:', hanzoUsage);
// context. It's a published npm dependency (^0.1.6) — esbuild resolves it
// from node_modules like any package, so the build works identically locally
// and on CI (no sibling-repo path assumption).
// The answer engine (new-tab landing) consumes the @hanzo/ai SDK's `search`
// primitive — the ONE place the search/deep-research capability is defined.
// It's a published npm dependency (^0.2.3), so esbuild resolves it from
// node_modules like any other package — works identically locally and on CI
// (no sibling-repo path assumption).
// Ensure dist directories exist
fs.mkdirSync('dist/browser-extension', { recursive: true });
fs.mkdirSync('dist/browser-extension/chrome', { recursive: true });
fs.mkdirSync('dist/browser-extension/firefox', { recursive: true });
fs.mkdirSync('dist/browser-extension/safari', { recursive: true });
for (const d of ['', 'chrome', 'firefox', 'safari']) {
fs.mkdirSync(out(d), { recursive: true });
}
// Build content script
await esbuild.build({
entryPoints: ['src/content-script.ts'],
bundle: true,
outfile: 'dist/browser-extension/content-script.js',
outfile: out('content-script.js'),
platform: 'browser',
target: ['chrome90', 'firefox91', 'safari14'],
sourcemap: 'inline'
@@ -44,31 +56,29 @@ async function build() {
await esbuild.build({
entryPoints: ['src/background.ts'],
bundle: true,
outfile: 'dist/browser-extension/background.js',
outfile: out('background.js'),
platform: 'browser',
target: ['chrome90', 'safari14'],
format: 'esm',
external: ['chrome', 'browser'],
alias: backgroundAliases
});
// Build Firefox-specific background script (no ESM export, uses browser.* APIs)
await esbuild.build({
entryPoints: ['src/background-firefox.ts'],
bundle: true,
outfile: 'dist/browser-extension/background-firefox.js',
outfile: out('background-firefox.js'),
platform: 'browser',
target: ['firefox91'],
format: 'iife', // Immediately-invoked function expression (no exports)
external: ['browser'],
alias: backgroundAliases
});
// Build WebGPU AI module
await esbuild.build({
entryPoints: ['src/webgpu-ai.ts'],
bundle: true,
outfile: 'dist/browser-extension/webgpu-ai.js',
outfile: out('webgpu-ai.js'),
platform: 'browser',
target: 'es2020',
format: 'esm'
@@ -83,7 +93,7 @@ async function build() {
await esbuild.build({
entryPoints: [fs.existsSync('src/sidebar.ts') ? 'src/sidebar.ts' : 'src/sidebar.js'],
bundle: true,
outfile: 'dist/browser-extension/sidebar.js',
outfile: out('sidebar.js'),
platform: 'browser',
target: ['chrome90', 'firefox91', 'safari14'],
sourcemap: 'inline',
@@ -93,17 +103,41 @@ async function build() {
await esbuild.build({
entryPoints: [fs.existsSync('src/popup.ts') ? 'src/popup.ts' : 'src/popup.js'],
bundle: true,
outfile: 'dist/browser-extension/popup.js',
outfile: out('popup.js'),
platform: 'browser',
target: ['chrome90', 'firefox91', 'safari14'],
sourcemap: 'inline',
});
// Answer engine (new-tab landing + omnibox/address-bar search target).
// React 18 surface consuming the @hanzo/ai `search` primitive; monochrome.
await esbuild.build({
entryPoints: ['src/newtab.ts'],
bundle: true,
outfile: out('newtab.js'),
platform: 'browser',
target: ['chrome90', 'firefox91', 'safari14'],
// New-tab page loads on every tab — ship it lean (minified, no inline map).
minify: true,
sourcemap: false,
});
// Onboarding (new-install consent ask: insights + opt-in training).
await esbuild.build({
entryPoints: ['src/onboarding.ts'],
bundle: true,
outfile: out('onboarding.js'),
platform: 'browser',
target: ['chrome90', 'firefox91', 'safari14'],
minify: true,
sourcemap: false,
});
// Build browser control module
await esbuild.build({
entryPoints: ['src/browser-control.ts'],
bundle: true,
outfile: 'dist/browser-extension/browser-control.js',
outfile: out('browser-control.js'),
platform: 'browser',
target: 'es2020',
format: 'esm'
@@ -113,7 +147,7 @@ async function build() {
await esbuild.build({
entryPoints: ['src/cli.ts'],
bundle: true,
outfile: 'dist/browser-extension/cli.js',
outfile: out('cli.js'),
platform: 'node',
target: 'node16',
packages: 'external'
@@ -121,16 +155,9 @@ async function build() {
// Make CLI executable
if (process.platform !== 'win32') {
execSync('chmod +x dist/browser-extension/cli.js');
fs.chmodSync(out('cli.js'), 0o755);
}
// Build TypeScript declarations
console.log('Building TypeScript declarations...');
// Check if we should run tsc in root or src, based on where tsconfig is.
// Assuming root tsconfig covers src, or src has one.
// There is a tsconfig in src.
// execSync('cd src && npx tsc --noEmit', { stdio: 'inherit' });
// Copy manifests for different browsers. package.json is the SINGLE source of
// truth for the version — stamp it into every manifest so the three can never
// drift apart (the "must agree" rule, enforced by the build instead of by hand).
@@ -140,12 +167,12 @@ async function build() {
m.version = pkgVersion;
fs.writeFileSync(destPath, JSON.stringify(m, null, 2));
};
writeManifest('src/manifest.json', 'dist/browser-extension/manifest.json');
writeManifest('src/manifest.json', 'dist/browser-extension/chrome/manifest.json');
writeManifest('src/manifest-firefox.json', 'dist/browser-extension/firefox/manifest.json');
writeManifest('src/manifest.json', out('manifest.json'));
writeManifest('src/manifest.json', out('chrome', 'manifest.json'));
writeManifest('src/manifest-firefox.json', out('firefox', 'manifest.json'));
// Safari needs special handling — write Info.plist for Xcode project
fs.writeFileSync('dist/browser-extension/safari/Info.plist', `<?xml version="1.0" encoding="UTF-8"?>
fs.writeFileSync(out('safari', 'Info.plist'), `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
@@ -169,36 +196,29 @@ async function build() {
// Copy common files to each browser directory
['chrome', 'firefox', 'safari'].forEach(browserName => {
const dir = `dist/browser-extension/${browserName}`;
const dir = out(browserName);
fs.copyFileSync(
'dist/browser-extension/content-script.js',
`${dir}/content-script.js`
);
fs.copyFileSync(out('content-script.js'), path.join(dir, 'content-script.js'));
// Firefox uses IIFE background (no ESM service workers); Chrome/Safari use ESM
if (browserName === 'firefox') {
fs.copyFileSync(
'dist/browser-extension/background-firefox.js',
`${dir}/background.js`
);
fs.copyFileSync(out('background-firefox.js'), path.join(dir, 'background.js'));
} else {
fs.copyFileSync(
'dist/browser-extension/background.js',
`${dir}/background.js`
);
fs.copyFileSync(out('background.js'), path.join(dir, 'background.js'));
}
// Copy popup + sidebar HTML/CSS
for (const f of ['popup.html', 'popup.css', 'sidebar.html', 'sidebar.css', 'callback.html', 'ai-worker.js']) {
// Copy popup + sidebar + answer-engine HTML/CSS
for (const f of ['popup.html', 'popup.css', 'sidebar.html', 'sidebar.css', 'newtab.html', 'newtab.css', 'onboarding.html', 'onboarding.css', 'callback.html', 'ai-worker.js']) {
const src = path.join('src', f);
if (fs.existsSync(src)) {
fs.copyFileSync(src, path.join(dir, f));
}
}
// Copy compiled popup/sidebar scripts
fs.copyFileSync('dist/browser-extension/popup.js', path.join(dir, 'popup.js'));
fs.copyFileSync('dist/browser-extension/sidebar.js', path.join(dir, 'sidebar.js'));
// Copy compiled popup/sidebar/newtab scripts
fs.copyFileSync(out('popup.js'), path.join(dir, 'popup.js'));
fs.copyFileSync(out('sidebar.js'), path.join(dir, 'sidebar.js'));
fs.copyFileSync(out('newtab.js'), path.join(dir, 'newtab.js'));
fs.copyFileSync(out('onboarding.js'), path.join(dir, 'onboarding.js'));
// Copy icons into each browser directory
for (const icon of ['icon16.png', 'icon48.png', 'icon128.png']) {
@@ -212,13 +232,10 @@ async function build() {
// Copy package.json for npm
const pkg = JSON.parse(fs.readFileSync('src/package.json', 'utf8'));
pkg.main = 'cli.js';
fs.writeFileSync(
'dist/browser-extension/package.json',
JSON.stringify(pkg, null, 2)
);
fs.writeFileSync(out('package.json'), JSON.stringify(pkg, null, 2));
// Create README for npm package
fs.writeFileSync('dist/browser-extension/README.md', `# Hanzo Browser DevTools
fs.writeFileSync(out('README.md'), `# Hanzo Browser DevTools
Click-to-code navigation for web developers with MCP integration.
@@ -267,32 +284,33 @@ server.on('elementSelected', (data) => {
['icon16.png', 'icon48.png', 'icon128.png'].forEach(icon => {
const iconPath = path.join('images', icon);
if (fs.existsSync(iconPath)) {
fs.copyFileSync(iconPath, path.join('dist/browser-extension', icon));
fs.copyFileSync(iconPath, out(icon));
}
});
// Generate Safari Xcode project (macOS + iOS) if safari-web-extension-converter exists
// Generate Safari Xcode project (macOS + iOS) if safari-web-extension-converter exists.
// Project goes to dist/safari-xcode/ so it never collides with the dist/safari/ web-ext dir.
try {
execSync('xcrun --find safari-web-extension-converter', { stdio: 'ignore' });
console.log('Generating Safari Xcode project (macOS + iOS)...');
execSync(
`xcrun safari-web-extension-converter dist/browser-extension/chrome/ ` +
`--project-location dist/safari ` +
`xcrun safari-web-extension-converter ${out('chrome')}/ ` +
`--project-location ${out('safari-xcode')} ` +
`--app-name "Hanzo AI" ` +
`--bundle-identifier ai.hanzo.browser-extension ` +
`--no-prompt --no-open --force`,
{ stdio: 'inherit' }
);
console.log('📦 Safari: dist/safari/ (macOS + iOS Xcode project)');
console.log(`📦 Safari: ${out('safari-xcode')} (macOS + iOS Xcode project)`);
} catch {
console.log('⚠️ Safari: skipped (Xcode not available)');
}
console.log('✅ Browser extension built successfully!');
console.log('📦 Chrome: dist/browser-extension/chrome/');
console.log('📦 Firefox: dist/browser-extension/firefox/');
console.log('📦 NPM package ready in: dist/browser-extension/');
console.log('\nTo publish to npm: cd dist/browser-extension && npm publish');
console.log(`📦 Chrome: ${out('chrome')}/`);
console.log(`📦 Firefox: ${out('firefox')}/`);
console.log(`📦 NPM package ready in: ${OUT}/`);
console.log(`\nTo publish to npm: cd ${OUT} && npm publish`);
}
build().catch((error) => {
+8 -2
View File
@@ -1,8 +1,8 @@
{
"manifest_version": 3,
"name": "Hanzo AI",
"version": "1.9.22",
"description": "AI-powered dev assistant — click-to-code navigation, source maps, WebGPU AI, and MCP integration for Claude Code.",
"version": "1.9.34",
"description": "AI answer engine, search, and dev assistant — Hanzo AI in a new tab, address-bar search, source-cited answers, realtime news, WebGPU AI, and MCP.",
"permissions": [
"activeTab",
"identity",
@@ -49,6 +49,12 @@
"128": "icon128.png"
}
},
"chrome_url_overrides": {
"newtab": "newtab.html"
},
"omnibox": {
"keyword": "hanzo"
},
"sidebar_action": {
"default_title": "Hanzo AI",
"default_panel": "sidebar.html",
+15 -2
View File
@@ -1,8 +1,8 @@
{
"manifest_version": 3,
"name": "Hanzo AI",
"version": "1.9.25",
"description": "AI-powered dev assistant — click-to-code navigation, source maps, WebGPU AI, and MCP integration for Claude Code.",
"version": "1.9.34",
"description": "AI answer engine, search, and dev assistant — Hanzo AI in a new tab, address-bar search, source-cited answers, realtime news, WebGPU AI, and MCP.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfXGh0lPUT5m04GKfjUwrLsV6pLaK3VcZuFRPogqAir2tzyLYnQPRtHynue9yvDyguIVnlkwvcwfDOYZrvH76zbw4s6onPBG8HqTKO6LQ9K3kdO1qBBkMMjdOgULQ1MrWThEbpU7NSTiwLYpEta/jAvrKRCAeKIlQE8p6htZmPy9aRUZuae66JgLcAlzD2vviX9sVB1asFABJVswL1RgZ55/8IzZaUrFjzOo9OHK4hmEOtudzkML+5silsAYdC+1BZugph2x94ai17YmZTCL1XyUa5Ke4q80cj+i9rOTgzhZs+mruyhL/AvNVOXilsgqCdNqSz77naWzC3pVGbxOewIDAQAB",
"permissions": [
"activeTab",
@@ -54,6 +54,19 @@
"48": "icon48.png",
"128": "icon128.png"
},
"chrome_url_overrides": {
"newtab": "newtab.html"
},
"chrome_settings_overrides": {
"search_provider": {
"name": "Hanzo",
"keyword": "hanzo",
"search_url": "https://hanzo.chat/c/new?q={searchTerms}&submit=true",
"favicon_url": "https://hanzo.ai/favicon.ico",
"encoding": "UTF-8",
"is_default": true
}
},
"web_accessible_resources": [
{
"resources": [
+277
View File
@@ -0,0 +1,277 @@
/* Hanzo Answer Engine strict monochrome (brand primaryColor #FFFFFF).
Shared tokens mirror popup.css / sidebar.css. */
:root {
--bg: #0a0a0a;
--surface: #0f0f0f;
--surface-2: #171717;
--surface-3: #1e1e1e;
--text: #fafafa;
--text-2: #a3a3a3;
--text-3: #666666;
--border: rgba(255, 255, 255, 0.10);
--border-2: rgba(255, 255, 255, 0.16);
--glass: rgba(255, 255, 255, 0.04);
--glass-2: rgba(255, 255, 255, 0.07);
--radius: 12px;
--radius-sm: 8px;
--radius-xs: 6px;
--sidebar-w: 232px;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: 'Geist Sans', -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; text-decoration: none; }
.ae-root {
display: grid;
grid-template-columns: var(--sidebar-w) 1fr;
height: 100vh;
transition: grid-template-columns 0.18s ease;
}
.ae-root.collapsed { grid-template-columns: 60px 1fr; }
/* ── Sidebar ─────────────────────────────────────────────── */
.ae-sidebar {
display: flex;
flex-direction: column;
gap: 6px;
padding: 14px 12px;
border-right: 1px solid var(--border);
background: var(--surface);
min-width: 0;
}
.ae-side-top { display: flex; align-items: center; justify-content: space-between; }
.ae-brand {
display: flex; align-items: center; gap: 9px;
background: none; border: none; color: var(--text);
font-size: 15px; font-weight: 600; letter-spacing: -0.01em;
cursor: pointer; padding: 4px; min-width: 0;
}
.ae-brand span { white-space: nowrap; overflow: hidden; }
.ae-collapse, .ae-new, .ae-signin {
cursor: pointer; font-family: inherit;
}
.ae-collapse {
background: none; border: none; color: var(--text-3);
padding: 4px; border-radius: var(--radius-xs); display: flex;
}
.ae-collapse:hover { color: var(--text); background: var(--glass); }
.ae-new {
display: flex; align-items: center; gap: 8px;
margin-top: 8px; padding: 9px 12px;
background: var(--text); color: #000; border: none;
border-radius: var(--radius-sm); font-size: 13px; font-weight: 600;
white-space: nowrap; overflow: hidden;
}
.ae-new:hover { background: #fff; }
.ae-nav { display: flex; flex-direction: column; margin-top: 12px; gap: 1px; }
.ae-nav a {
padding: 8px 10px; border-radius: var(--radius-xs);
color: var(--text-2); font-size: 13px; white-space: nowrap;
}
.ae-nav a:hover { background: var(--glass); color: var(--text); }
.ae-side-bottom { margin-top: auto; }
.ae-signin {
width: 100%; padding: 9px 12px;
background: var(--glass-2); border: 1px solid var(--border);
color: var(--text); border-radius: var(--radius-sm);
font-size: 12.5px; font-weight: 500; white-space: nowrap; overflow: hidden;
}
.ae-signin:hover { border-color: var(--border-2); background: var(--surface-2); }
.ae-signin.big { width: auto; padding: 10px 18px; font-size: 14px; }
.collapsed .ae-brand span, .collapsed .ae-new span, .collapsed .ae-nav { display: none; }
/* ── Main ────────────────────────────────────────────────── */
.ae-main { min-width: 0; overflow: hidden; display: flex; flex-direction: column; }
/* Hero (empty state) */
.ae-hero {
flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 26px; padding: 24px; overflow-y: auto;
}
.ae-wordmark {
display: flex; align-items: center; gap: 14px;
font-size: 46px; font-weight: 600; letter-spacing: -0.03em; color: var(--text);
}
.ae-hero-card { width: 100%; max-width: 720px; }
.ae-news { width: 100%; max-width: 720px; }
.ae-news-head, .ae-followups-head, .ae-model-group-label {
font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;
color: var(--text-3); margin-bottom: 10px;
}
.ae-news-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.ae-news-item {
display: flex; flex-direction: column; gap: 4px;
padding: 11px 13px; border: 1px solid var(--border);
border-radius: var(--radius-sm); background: var(--surface);
}
.ae-news-item:hover { border-color: var(--border-2); background: var(--surface-2); }
.ae-news-title { font-size: 13px; color: var(--text); line-height: 1.35; }
.ae-news-meta { font-size: 11px; color: var(--text-3); }
/* ── Input card ──────────────────────────────────────────── */
.ae-card {
background: var(--surface-2);
border: 1px solid var(--border-2);
border-radius: var(--radius);
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(255, 255, 255, 0.02);
overflow: hidden;
}
.ae-input {
display: block; width: 100%; resize: none;
padding: 16px 18px 6px; min-height: 30px; max-height: 200px;
background: transparent; border: none; outline: none;
color: var(--text); font-family: inherit; font-size: 15px; line-height: 1.5;
}
.ae-input::placeholder { color: var(--text-3); }
.ae-card-row {
display: flex; align-items: center; justify-content: space-between;
gap: 8px; padding: 8px 10px 10px; flex-wrap: wrap;
}
.ae-chips { display: flex; gap: 4px; flex-wrap: wrap; }
.ae-chip {
padding: 4px 9px; border-radius: 999px; cursor: pointer;
background: var(--glass); border: 1px solid var(--border);
color: var(--text-3); font-size: 11px; font-family: inherit;
}
.ae-chip:hover { color: var(--text-2); }
.ae-chip.on { background: var(--text); color: #000; border-color: var(--text); }
.ae-card-right { display: flex; align-items: center; gap: 6px; }
.ae-modes { display: flex; gap: 2px; background: var(--glass); border-radius: var(--radius-xs); padding: 2px; }
.ae-mode {
padding: 4px 9px; border: none; background: none; cursor: pointer;
color: var(--text-3); font-size: 11.5px; font-family: inherit; border-radius: 5px;
}
.ae-mode:hover { color: var(--text-2); }
.ae-mode.on { background: var(--surface-3); color: var(--text); }
.ae-send {
width: 34px; height: 34px; flex-shrink: 0; cursor: pointer;
display: flex; align-items: center; justify-content: center;
background: var(--text); color: #000; border: none; border-radius: 50%;
}
.ae-send:disabled { opacity: 0.4; cursor: default; }
/* ── Model picker ────────────────────────────────────────── */
.ae-picker { position: relative; }
.ae-picker-btn {
display: flex; align-items: center; gap: 6px; cursor: pointer;
padding: 6px 10px; background: var(--glass); border: 1px solid var(--border);
border-radius: var(--radius-xs); color: var(--text-2); font-size: 12px; font-family: inherit;
}
.ae-picker-btn:hover { color: var(--text); border-color: var(--border-2); }
.ae-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--text-2); }
.ae-picker-menu {
position: absolute; bottom: calc(100% + 6px); right: 0; z-index: 40;
width: 320px; max-height: 420px; display: flex; flex-direction: column;
background: var(--surface-2); border: 1px solid var(--border-2);
border-radius: var(--radius-sm); box-shadow: 0 12px 48px rgba(0, 0, 0, 0.6); overflow: hidden;
}
.ae-picker-filter {
margin: 8px; padding: 8px 10px; background: var(--bg);
border: 1px solid var(--border); border-radius: var(--radius-xs);
color: var(--text); font-family: inherit; font-size: 13px; outline: none;
}
.ae-picker-list { overflow-y: auto; padding: 0 6px 6px; }
.ae-model-group-label { padding: 8px 8px 4px; margin: 0; }
.ae-model-row {
display: flex; flex-direction: column; gap: 2px; width: 100%; text-align: left;
padding: 8px 10px; background: none; border: none; cursor: pointer;
border-radius: var(--radius-xs); color: var(--text); font-family: inherit;
}
.ae-model-row:hover { background: var(--glass); }
.ae-model-row.active { background: var(--glass-2); }
.ae-model-name { font-size: 13px; display: flex; align-items: center; gap: 7px; }
.ae-model-desc { font-size: 11px; color: var(--text-3); line-height: 1.3; }
.ae-badge {
font-size: 9px; text-transform: uppercase; letter-spacing: 0.04em;
padding: 1px 5px; border-radius: 4px; background: var(--glass-2); color: var(--text-2);
}
.ae-plan-banner {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
padding: 10px 12px; border-top: 1px solid var(--border);
font-size: 11.5px; color: var(--text-2); background: var(--surface);
}
.ae-plan-tiers { display: flex; gap: 8px; }
.ae-plan-tier b { color: var(--text); }
/* ── Answer view ─────────────────────────────────────────── */
.ae-answer-wrap { flex: 1; display: flex; flex-direction: column; min-height: 0; }
.ae-answer-scroll { flex: 1; overflow-y: auto; padding: 32px 28px 20px; }
.ae-answer-scroll > * { max-width: 760px; margin-left: auto; margin-right: auto; }
.ae-question { font-size: 26px; font-weight: 600; letter-spacing: -0.02em; margin: 0 0 20px; }
.ae-sources { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 16px; margin-bottom: 8px; }
.ae-source {
flex: 0 0 190px; display: flex; flex-direction: column; gap: 6px;
padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm);
background: var(--surface);
}
.ae-source:hover { border-color: var(--border-2); background: var(--surface-2); }
.ae-source-head { display: flex; align-items: center; gap: 6px; }
.ae-source-head img { border-radius: 3px; }
.ae-source-host { font-size: 11px; color: var(--text-3); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ae-source-idx { font-size: 10px; color: var(--text-3); border: 1px solid var(--border); border-radius: 4px; padding: 0 5px; }
.ae-source-title { font-size: 12.5px; line-height: 1.35; color: var(--text); display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.ae-status { display: flex; align-items: center; gap: 10px; color: var(--text-2); font-size: 14px; padding: 8px 0; }
.ae-answer.markdown { font-size: 15px; line-height: 1.65; color: var(--text); }
.markdown h2 { font-size: 20px; margin: 22px 0 10px; font-weight: 600; }
.markdown h3 { font-size: 17px; margin: 18px 0 8px; font-weight: 600; }
.markdown h4, .markdown h5 { font-size: 15px; margin: 14px 0 6px; font-weight: 600; }
.markdown p { margin: 0 0 12px; }
.markdown ul, .markdown ol { margin: 0 0 12px; padding-left: 22px; }
.markdown li { margin: 4px 0; }
.markdown a { color: var(--text); text-decoration: underline; text-decoration-color: var(--text-3); text-underline-offset: 2px; }
.markdown a:hover { text-decoration-color: var(--text); }
.markdown code { background: var(--surface-2); padding: 1px 5px; border-radius: 4px; font-size: 0.9em; font-family: 'Geist Mono', ui-monospace, monospace; }
.ae-followups { margin-top: 26px; border-top: 1px solid var(--border); padding-top: 16px; }
.ae-followup {
display: flex; align-items: center; justify-content: space-between; width: 100%;
padding: 12px 4px; background: none; border: none; border-bottom: 1px solid var(--border);
color: var(--text); font-family: inherit; font-size: 14px; text-align: left; cursor: pointer;
}
.ae-followup:hover { color: var(--text); }
.ae-followup:hover .ae-followup-arrow { color: var(--text); transform: translateX(2px); }
.ae-followup-arrow { color: var(--text-3); transition: transform 0.12s ease; }
.ae-error { color: var(--text-2); padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); }
.ae-auth { display: flex; flex-direction: column; align-items: flex-start; gap: 12px; padding: 8px 0; }
.ae-auth p { margin: 0; color: var(--text-2); font-size: 15px; }
.ae-answer-composer { padding: 12px 28px 20px; border-top: 1px solid var(--border); background: var(--bg); }
.ae-answer-composer > .ae-card { max-width: 760px; margin: 0 auto; }
/* ── Spinner ─────────────────────────────────────────────── */
.ae-spinner {
width: 14px; height: 14px; border-radius: 50%; display: inline-block;
border: 2px solid var(--border-2); border-top-color: var(--text);
animation: ae-spin 0.7s linear infinite;
}
@keyframes ae-spin { to { transform: rotate(360deg); } }
@media (max-width: 720px) {
.ae-root, .ae-root.collapsed { grid-template-columns: 1fr; }
.ae-sidebar { display: none; }
.ae-news-grid { grid-template-columns: 1fr; }
.ae-hero { gap: 20px; padding: 20px 16px; justify-content: flex-start; padding-top: 48px; }
.ae-wordmark { font-size: 34px; }
.ae-answer-scroll { padding: 20px 16px 16px; }
.ae-answer-composer { padding: 10px 16px 16px; }
.ae-question { font-size: 21px; }
/* Input card: let the control row wrap so the model picker + send stay
reachable at narrow widths (mobile-first). */
.ae-card-row { flex-direction: column; align-items: stretch; gap: 10px; }
.ae-card-right { justify-content: space-between; }
.ae-modes { flex: 1; justify-content: space-between; }
.ae-source { flex-basis: 150px; }
}
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hanzo</title>
<link rel="stylesheet" href="newtab.css" />
</head>
<body>
<div id="root"></div>
<script src="newtab.js"></script>
</body>
</html>
+48
View File
@@ -0,0 +1,48 @@
// Hanzo Answer Engine — new-tab landing + omnibox / address-bar search target.
// Mounts the shared AnswerEngine React surface; talks to api.hanzo.ai ONLY,
// through the @hanzo/ai `search` primitive. Auth is brokered by the background
// (same bridge the popup/sidebar use) so the token never lives in the page.
import 'webextension-polyfill';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { AnswerEngine } from './answer/AnswerEngine.js';
import { API_BASE_URL } from './shared/config.js';
declare const browser: typeof chrome;
const runtime: typeof chrome = (globalThis as any).browser ?? (globalThis as any).chrome;
/** Resolve the IAM bearer via the background broker (null when signed out). */
async function getToken(): Promise<string | null> {
try {
const resp: any = await runtime.runtime.sendMessage({ action: 'auth.getToken' });
return resp?.token ?? null;
} catch {
return null;
}
}
function signIn(): void {
runtime.runtime.sendMessage({ action: 'auth.login' }).catch(() => {});
}
function boot() {
const params = new URLSearchParams(location.search);
const initialQuery = params.get('q') ?? undefined;
const el = document.getElementById('root');
if (!el) return;
createRoot(el).render(
React.createElement(AnswerEngine, {
apiBase: API_BASE_URL,
getToken,
signIn,
...(initialQuery ? { initialQuery } : {}),
}),
);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot);
} else {
boot();
}
+78
View File
@@ -0,0 +1,78 @@
:root {
--bg: #0b0b0c;
--card: #131315;
--line: #26262a;
--text: #f4f4f5;
--muted: #9a9aa2;
--accent: #f4f4f5;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
body { display: grid; place-items: center; padding: 32px; }
.card {
width: 100%;
max-width: 520px;
background: var(--card);
border: 1px solid var(--line);
border-radius: 16px;
padding: 32px;
}
.brand { font-weight: 700; letter-spacing: 0.02em; opacity: 0.7; margin-bottom: 20px; }
h1 { font-size: 24px; margin: 0 0 8px; }
.lede { color: var(--muted); margin: 0 0 24px; }
.row {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 0;
border-top: 1px solid var(--line);
cursor: pointer;
}
.row input { position: absolute; opacity: 0; width: 0; height: 0; }
.switch {
flex: 0 0 auto;
width: 38px;
height: 22px;
border-radius: 999px;
background: #3a3a40;
position: relative;
transition: background 0.15s;
margin-top: 2px;
}
.switch::after {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
border-radius: 50%;
background: #fff;
transition: transform 0.15s;
}
.row input:checked + .switch { background: var(--accent); }
.row input:checked + .switch::after { transform: translateX(16px); background: #0b0b0c; }
.text { display: flex; flex-direction: column; gap: 2px; }
.text strong { font-weight: 600; }
.text small { color: var(--muted); }
.cta {
width: 100%;
margin-top: 24px;
padding: 12px;
border: 0;
border-radius: 10px;
background: var(--accent);
color: #0b0b0c;
font-weight: 600;
font-size: 15px;
cursor: pointer;
}
.cta:active { transform: translateY(1px); }
.fine { color: var(--muted); font-size: 12px; text-align: center; margin: 16px 0 0; }
.fine a { color: var(--text); }
+45
View File
@@ -0,0 +1,45 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to Hanzo</title>
<link rel="stylesheet" href="onboarding.css" />
</head>
<body>
<main class="card">
<div class="brand">Hanzo</div>
<h1>Welcome to Hanzo AI</h1>
<p class="lede">
Search, research and browse with Hanzo's own models. Before you start,
choose what you'd like to share — you can change this anytime in settings
or on your Hanzo account.
</p>
<label class="row">
<input type="checkbox" id="ob-insights" checked />
<span class="switch"></span>
<span class="text">
<strong>Anonymous usage insights</strong>
<small>Helps us improve Hanzo. No search text, no personal data — just a random per-install id.</small>
</span>
</label>
<label class="row">
<input type="checkbox" id="ob-training" />
<span class="switch"></span>
<span class="text">
<strong>Contribute to training Hanzo's open models</strong>
<small>Share your own searches &amp; answers so Hanzo's open models get better. Opt in — off unless you turn it on.</small>
</span>
</label>
<button id="ob-continue" class="cta">Get started</button>
<p class="fine">
Signed in? These choices save to your Hanzo account and stay in sync
everywhere. <a href="https://hanzo.ai/privacy" target="_blank" rel="noopener">Privacy</a>
</p>
</main>
<script src="onboarding.js"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
// onboarding.ts — the new-install consent ask. Opened once by the background on
// install. Records the user's choice as their consent (account-canonical when
// signed in — setConsent write-throughs to /v1/iam/consent), marks onboarding
// done so it never reopens, and closes.
import 'webextension-polyfill';
import { setConsent, markOnboarded, capture } from './shared/consent.js';
const runtime: typeof chrome = (globalThis as any).browser ?? (globalThis as any).chrome;
const insights = document.getElementById('ob-insights') as HTMLInputElement | null;
const training = document.getElementById('ob-training') as HTMLInputElement | null;
const cta = document.getElementById('ob-continue') as HTMLButtonElement | null;
cta?.addEventListener('click', async () => {
const consent = {
insights: insights?.checked ?? true,
shareTraining: training?.checked ?? false,
};
await setConsent(consent);
await markOnboarded();
await capture('onboarding_complete', { shareTraining: consent.shareTraining });
try {
const tab = await runtime.tabs.getCurrent();
if (tab?.id) await runtime.tabs.remove(tab.id);
else window.close();
} catch {
window.close();
}
});
+40
View File
@@ -57,6 +57,18 @@
<div class="divider"></div>
</div>
<!-- Embedded search: run a query through the Hanzo answer engine. -->
<form id="search-form" style="display:flex;gap:6px;margin-bottom:10px;">
<input id="search-input" type="text" placeholder="Search Hanzo AI…" autocomplete="off"
style="flex:1;min-width:0;padding:9px 12px;background:var(--surface-light,#171717);border:1px solid var(--border,rgba(255,255,255,0.12));border-radius:8px;color:var(--text,#fafafa);font-size:13px;font-family:inherit;outline:none;">
<button id="search-btn" type="submit" title="Search" aria-label="Search"
style="width:36px;height:36px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:var(--primary,#fafafa);border:none;border-radius:8px;color:#000;cursor:pointer;">
<svg viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8">
<circle cx="7" cy="7" r="4.5"/><path d="M11 11l3.5 3.5" stroke-linecap="round"/>
</svg>
</button>
</form>
<!-- Actions: single Open Chat button + on-page surface settings. -->
<button id="open-panel" class="btn btn-secondary" style="margin-bottom: 8px;">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
@@ -210,6 +222,34 @@
<div class="divider"></div>
<!-- Privacy & data -->
<h3>Privacy &amp; data</h3>
<div class="features">
<div class="feature-toggle">
<label>
<input type="checkbox" id="insights-enabled" checked>
<span class="toggle"></span>
<div class="feature-info">
<strong>Usage insights</strong>
<small>Anonymous, helps improve Hanzo. Never your search text.</small>
</div>
</label>
</div>
<div class="feature-toggle">
<label>
<input type="checkbox" id="share-training">
<span class="toggle"></span>
<div class="feature-info">
<strong>Contribute to training</strong>
<small>Opt in to share your searches &amp; answers to train Hanzo's open models. Off by default.</small>
</div>
</label>
</div>
</div>
<div class="divider"></div>
<!-- Browser Backend -->
<div class="setting-group backend-picker">
<h3>Backend</h3>
+29
View File
@@ -14,6 +14,7 @@ import {
shortcutFromEvent,
type Shortcut,
} from './shared/shortcut.js';
import { getConsent, setConsent, capture } from './shared/consent.js';
declare const browser: typeof chrome & {
sidebarAction?: {
@@ -134,6 +135,19 @@ document.addEventListener('DOMContentLoaded', () => {
});
});
// --- Embedded search (feature: query → Hanzo answer engine) ---
const searchForm = document.getElementById('search-form') as HTMLFormElement | null;
const searchInput = document.getElementById('search-input') as HTMLInputElement | null;
searchForm?.addEventListener('submit', (e) => {
e.preventDefault();
const q = searchInput?.value.trim();
const target = q
? chrome.runtime.getURL('newtab.html') + '?q=' + encodeURIComponent(q)
: chrome.runtime.getURL('newtab.html');
chrome.tabs.create({ url: target });
window.close();
});
// --- Open chat ---
// Default surface: in-page edge-pinned overlay (content-script). Honours
// the user's `overlayEnabled`, `overlaySide`, and `overlayWidth` prefs.
@@ -216,6 +230,21 @@ document.addEventListener('DOMContentLoaded', () => {
syncSettingsUi(enabled, side, width);
});
// Privacy & data toggles — reflect stored consent, persist on change.
const insightsCheckbox = document.getElementById('insights-enabled') as HTMLInputElement | null;
const shareTrainingCheckbox = document.getElementById('share-training') as HTMLInputElement | null;
getConsent().then((c) => {
if (insightsCheckbox) insightsCheckbox.checked = c.insights;
if (shareTrainingCheckbox) shareTrainingCheckbox.checked = c.shareTraining;
});
insightsCheckbox?.addEventListener('change', (e) => {
void setConsent({ insights: (e.target as HTMLInputElement).checked });
});
shareTrainingCheckbox?.addEventListener('change', (e) => {
void setConsent({ shareTraining: (e.target as HTMLInputElement).checked });
});
void capture('popup_opened');
function isInjectableTab(tab: chrome.tabs.Tab | undefined): boolean {
if (!tab || !tab.id) return false;
const url = tab.url || '';
+185
View File
@@ -0,0 +1,185 @@
// consent.ts — ONE data-consent value, one source of truth.
//
// The user's data-sharing consent lives on their Hanzo ACCOUNT (asked at
// hanzo.id signup, editable in the extension + on hanzo.ai). This module keeps
// the extension in lockstep with that one value:
// • Signed in → the account is canonical. getConsent() reads it from
// GET /v1/iam/consent; setConsent() writes it with PUT /v1/iam/consent.
// The local copy is just a cache so the UI paints instantly.
// • Signed out → the local copy (from onboarding) is used, and is pushed to
// the account on next sign-in so nothing is lost or duplicated.
//
// TWO switches:
// • insights (default ON) — anonymous product events. No query/answer
// text, no PII: only which surface fired, under a random per-install id.
// • shareTraining (OPT-IN) — contribute the user's OWN searches + answers
// to train Hanzo's open models. Asked explicitly at signup/onboarding.
//
// Everything is fail-soft: a network error NEVER breaks a user action, and
// nothing is sent for a switch that is off.
import { API_BASE_URL } from './config.js';
const KEYS = {
insights: 'hanzo_insights_enabled',
training: 'hanzo_share_training',
onboarded: 'hanzo_onboarded',
anonId: 'hanzo_anon_id',
} as const;
export interface Consent {
insights: boolean;
shareTraining: boolean;
}
const runtime: typeof chrome | undefined =
(globalThis as any).browser ?? (globalThis as any).chrome;
function area(): chrome.storage.StorageArea | undefined {
return (globalThis as any).chrome?.storage?.local ?? (globalThis as any).browser?.storage?.local;
}
function getLocal(keys: string[]): Promise<Record<string, any>> {
return new Promise((resolve) => {
const s = area();
if (!s) return resolve({});
try {
s.get(keys, (v) => resolve(v || {}));
} catch {
resolve({});
}
});
}
function setLocal(obj: Record<string, any>): Promise<void> {
return new Promise((resolve) => {
const s = area();
if (!s) return resolve();
try {
s.set(obj, () => resolve());
} catch {
resolve();
}
});
}
/** Bearer for the signed-in user, brokered by the background (null when out). */
async function token(): Promise<string | null> {
try {
const resp: any = await runtime?.runtime?.sendMessage?.({ action: 'auth.getToken' });
return resp?.token ?? null;
} catch {
return null;
}
}
function localConsent(v: Record<string, any>): Consent {
return { insights: v[KEYS.insights] !== false, shareTraining: v[KEYS.training] === true };
}
/** Read consent: the account is canonical when signed in; local otherwise. */
export async function getConsent(): Promise<Consent> {
const local = localConsent(await getLocal([KEYS.insights, KEYS.training]));
const tok = await token();
if (!tok) return local;
try {
const res = await fetch(`${API_BASE_URL}/v1/iam/consent`, {
headers: { authorization: `Bearer ${tok}` },
});
if (res.ok) {
const a = await res.json();
const acct: Consent = { insights: a.insights !== false, shareTraining: a.shareTraining === true };
// Cache so the UI paints instantly next time, keeping one value in sync.
await setLocal({ [KEYS.insights]: acct.insights, [KEYS.training]: acct.shareTraining });
return acct;
}
} catch {
/* fall through to local */
}
return local;
}
/** Write consent: local cache + the account (when signed in) — one value. */
export async function setConsent(c: Partial<Consent>): Promise<void> {
const cur = localConsent(await getLocal([KEYS.insights, KEYS.training]));
const next: Consent = {
insights: c.insights ?? cur.insights,
shareTraining: c.shareTraining ?? cur.shareTraining,
};
await setLocal({ [KEYS.insights]: next.insights, [KEYS.training]: next.shareTraining });
const tok = await token();
if (!tok) return;
try {
await fetch(`${API_BASE_URL}/v1/iam/consent`, {
method: 'PUT',
headers: { 'content-type': 'application/json', authorization: `Bearer ${tok}` },
body: JSON.stringify(next),
keepalive: true,
}).catch(() => {});
} catch {
/* fail-soft */
}
}
export async function isOnboarded(): Promise<boolean> {
const v = await getLocal([KEYS.onboarded]);
return v[KEYS.onboarded] === true;
}
export async function markOnboarded(): Promise<void> {
await setLocal({ [KEYS.onboarded]: true });
}
async function anonId(): Promise<string> {
const v = await getLocal([KEYS.anonId]);
if (typeof v[KEYS.anonId] === 'string') return v[KEYS.anonId];
const id =
globalThis.crypto?.randomUUID?.() ??
`a-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
await setLocal({ [KEYS.anonId]: id });
return id;
}
/** Anonymous product-usage event. No query/answer text, no PII. No-op when
* insights is off. Never throws. */
export async function capture(event: string, props?: Record<string, unknown>): Promise<void> {
try {
const c = await getConsent();
if (!c.insights) return;
const anon_id = await anonId();
await fetch(`${API_BASE_URL}/v1/insights`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ event, props: props ?? {}, anon_id, ts: Date.now(), source: 'extension' }),
keepalive: true,
}).catch(() => {});
} catch {
/* fail-soft */
}
}
/** Contribute one search+answer sample to train Hanzo's open models. No-op
* unless the user opted in. Sent with the IAM bearer so it's the user's own,
* attributable data. Never throws. */
export async function contributeTrainingSample(sample: {
query: string;
answer: string;
model?: string;
sources?: string[];
}): Promise<void> {
try {
const c = await getConsent();
if (!c.shareTraining) return;
if (!sample.query || !sample.answer) return;
const tok = await token();
await fetch(`${API_BASE_URL}/v1/training/contributions`, {
method: 'POST',
headers: {
'content-type': 'application/json',
...(tok ? { authorization: `Bearer ${tok}` } : {}),
},
body: JSON.stringify({ ...sample, source: 'extension:answer-engine', ts: Date.now() }),
keepalive: true,
}).catch(() => {});
} catch {
/* fail-soft */
}
}
+90 -115
View File
@@ -1,47 +1,49 @@
/**
* KMS (Key Management / Secrets) client shared across all browser targets.
*
* Lightweight fetch-based client for Hanzo KMS (kms.hanzo.ai).
* Uses IAM bearer tokens for auth no separate KMS credentials needed.
* Lightweight fetch-based client for Hanzo KMS. Uses IAM bearer tokens for
* auth no separate KMS credentials needed.
*
* API path. Hanzo convention is `/v1/<service>/<endpoint>` but the KMS
* upstream publishes its v3 API under the root
* `${KMS_PATH_PREFIX}/secrets/raw`. The kms.hanzo.ai gateway currently passes that
* through unchanged (verified: `kms.hanzo.ai/api/v3/secrets/raw` 401 JSON,
* `/v1/kms/...` SPA HTML). We centralise the path in `KMS_PATH_PREFIX`
* so the day the gateway adds the rewrite we update one constant.
* Every path is `/v1/kms/...`, which is the Hanzo `/v1/<service>/<endpoint>`
* convention and, more importantly, what the server actually serves:
*
* GET {KMS_PATH_PREFIX}/secrets/raw list
* GET {KMS_PATH_PREFIX}/secrets/raw/:name get
* POST {KMS_PATH_PREFIX}/secrets/raw/:name create
* PATCH {KMS_PATH_PREFIX}/secrets/raw/:name update
* DELETE {KMS_PATH_PREFIX}/secrets/raw/:name delete
* GET /v1/kms/orgs/{org}/secrets?path=&env= list names
* GET /v1/kms/orgs/{org}/secrets/{path}/{name}?env= read one value
* POST /v1/kms/orgs/{org}/secrets create or replace
* DELETE /v1/kms/orgs/{org}/secrets/{path}/{name}?env= delete
*
* This file used to speak Infisical's shape under an `/api/v3` prefix, with a
* header comment reporting that `/v1/kms/...` had been *verified* to return SPA
* HTML while `/api/v3/secrets/raw` returned JSON so `/api/v3` was pinned as
* the working path and a rewrite was awaited. The observation was real and the
* conclusion was backwards: the KMS binary embedded a console SPA under a root
* catch-all, so it answered EVERY unmatched path with 200 text/html. The HTML
* was the 404. luxfi/kms 1.12.8 removed the catch-all, and the same probe now
* reads the other way round `/v1/kms/...` answers JSON, `/api/v3/...` is a
* JSON 404. There is no gateway rewrite to wait for.
*
* Create and update are ONE call because the server has one upsert, not two
* endpoints. Listing arrived in luxfi/kms 1.12.9; before that the HTTP surface
* had no list at all, which is what made the Infisical prefix look necessary.
*/
import { KMS_API_URL } from './config.js';
/** Prefix for every KMS request. See file header. */
const KMS_PATH_PREFIX = '/api/v3';
// ── Types ───────────────────────────────────────────────────────────────
export interface KmsSecret {
secretKey: string;
secretValue?: string;
version?: number;
type?: string;
environment?: string;
secretPath?: string;
/** Where a secret lives. `path` groups secrets; `name` identifies one. */
export interface KmsRef {
/** Org scope — also the scope of the bearer token that reads it. */
org: string;
/** Environment slug (`dev` / `test` / `main`). Defaults to `default`. */
env?: string;
/** Grouping path, e.g. `gateway`. Omit to address the org root. */
path?: string;
}
export interface KmsListParams {
workspaceId: string;
environment: string;
secretPath?: string;
}
export interface KmsSecretParams extends KmsListParams {
secretName: string;
/** A ref plus the name of a single secret. */
export interface KmsSecretRef extends KmsRef {
name: string;
}
// ── Helpers ─────────────────────────────────────────────────────────────
@@ -57,121 +59,94 @@ function kmsUrl(path: string, baseUrl?: string): string {
return `${baseUrl || KMS_API_URL}${path}`;
}
function buildQuery(params: Record<string, string | undefined>): string {
const entries = Object.entries(params).filter(([, v]) => v !== undefined) as [string, string][];
if (!entries.length) return '';
return '?' + new URLSearchParams(entries).toString();
/** The collection URL for an org, with `path`/`env` as query. */
function collectionUrl(ref: KmsRef, baseUrl?: string): string {
const q = new URLSearchParams();
if (ref.path) q.set('path', ref.path);
q.set('env', ref.env || 'default');
return kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets?${q}`, baseUrl);
}
/**
* The URL of one secret. The server splits the trailing `{rest...}` at its LAST
* slash into (path, name), so each segment is escaped on its own escaping the
* joined string would encode the separators and the server would read one long
* name.
*/
function secretUrl(ref: KmsSecretRef, baseUrl?: string): string {
const segs = [...(ref.path ? ref.path.split('/') : []), ref.name]
.filter((s) => s.length > 0)
.map(encodeURIComponent)
.join('/');
const q = new URLSearchParams({ env: ref.env || 'default' });
return kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets/${segs}?${q}`, baseUrl);
}
async function fail(op: string, resp: Response): Promise<never> {
throw new Error(`KMS ${op} failed: ${resp.status} ${await resp.text()}`);
}
// ── API Functions ───────────────────────────────────────────────────────
/** List secrets in a workspace/environment */
/** List the names of the secrets under a path. */
export async function kmsListSecrets(
token: string,
params: KmsListParams,
ref: KmsRef,
baseUrl?: string,
): Promise<KmsSecret[]> {
const query = buildQuery({
workspaceId: params.workspaceId,
environment: params.environment,
secretPath: params.secretPath,
});
const resp = await fetch(kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw${query}`, baseUrl), {
headers: kmsHeaders(token),
});
if (!resp.ok) throw new Error(`KMS list failed: ${resp.status} ${await resp.text()}`);
): Promise<string[]> {
const resp = await fetch(collectionUrl(ref, baseUrl), { headers: kmsHeaders(token) });
if (!resp.ok) return fail('list', resp);
const data = await resp.json();
return data.secrets || data;
return data.names ?? [];
}
/** Get a single secret by name */
/** Read one secret's value. */
export async function kmsGetSecret(
token: string,
params: KmsSecretParams,
ref: KmsSecretRef,
baseUrl?: string,
): Promise<KmsSecret> {
const query = buildQuery({
workspaceId: params.workspaceId,
environment: params.environment,
secretPath: params.secretPath,
});
const resp = await fetch(
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}${query}`, baseUrl),
{ headers: kmsHeaders(token) },
);
if (!resp.ok) throw new Error(`KMS get failed: ${resp.status} ${await resp.text()}`);
): Promise<string> {
const resp = await fetch(secretUrl(ref, baseUrl), { headers: kmsHeaders(token) });
if (!resp.ok) return fail('get', resp);
const data = await resp.json();
return data.secret || data;
return data.secret?.value ?? '';
}
/** Create a new secret */
export async function kmsCreateSecret(
/**
* Create a secret, or replace it if the name already exists. One call, because
* the server has one upsert there is no separate create and update.
*/
export async function kmsPutSecret(
token: string,
params: KmsSecretParams,
ref: KmsSecretRef,
value: string,
baseUrl?: string,
): Promise<KmsSecret> {
): Promise<void> {
const resp = await fetch(
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets`, baseUrl),
{
method: 'POST',
headers: kmsHeaders(token),
body: JSON.stringify({
workspaceId: params.workspaceId,
environment: params.environment,
secretPath: params.secretPath,
secretValue: value,
type: 'shared',
path: ref.path ?? '',
name: ref.name,
env: ref.env || 'default',
value,
}),
},
);
if (!resp.ok) throw new Error(`KMS create failed: ${resp.status} ${await resp.text()}`);
const data = await resp.json();
return data.secret || data;
if (!resp.ok) return fail('put', resp);
}
/** Update an existing secret */
export async function kmsUpdateSecret(
token: string,
params: KmsSecretParams,
value: string,
baseUrl?: string,
): Promise<KmsSecret> {
const resp = await fetch(
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
{
method: 'PATCH',
headers: kmsHeaders(token),
body: JSON.stringify({
workspaceId: params.workspaceId,
environment: params.environment,
secretPath: params.secretPath,
secretValue: value,
}),
},
);
if (!resp.ok) throw new Error(`KMS update failed: ${resp.status} ${await resp.text()}`);
const data = await resp.json();
return data.secret || data;
}
/** Delete a secret */
/** Delete a secret. */
export async function kmsDeleteSecret(
token: string,
params: KmsSecretParams,
ref: KmsSecretRef,
baseUrl?: string,
): Promise<void> {
const resp = await fetch(
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
{
method: 'DELETE',
headers: kmsHeaders(token),
body: JSON.stringify({
workspaceId: params.workspaceId,
environment: params.environment,
secretPath: params.secretPath,
}),
},
);
if (!resp.ok) throw new Error(`KMS delete failed: ${resp.status} ${await resp.text()}`);
const resp = await fetch(secretUrl(ref, baseUrl), {
method: 'DELETE',
headers: kmsHeaders(token),
});
if (!resp.ok) return fail('delete', resp);
}
+5 -1
View File
@@ -63,7 +63,11 @@ export interface NativeZapState {
export type Dispatch = (method: string, params: any) => Promise<any> | any;
const RECONNECT_MS = 3000;
// Gentle safe poll: with no MCP client running there is no router to reach, so
// the host connects-then-exits; probe every 30s instead of hammering (and
// re-launching the native host) every 3s. A live consumer is picked up within
// one interval.
const RECONNECT_MS = 30_000;
/** Connect to zapd via the native host, register as a browser provider, and
* dispatch inbound ROUTE commands to the browser. Self-heals on disconnect. */
+119 -110
View File
@@ -2,8 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
kmsListSecrets,
kmsGetSecret,
kmsCreateSecret,
kmsUpdateSecret,
kmsPutSecret,
kmsDeleteSecret,
} from '../src/shared/kms';
@@ -24,49 +23,95 @@ function mockResponse(data: any, ok = true, status = 200) {
}
const TOKEN = 'test-bearer-token';
const PARAMS = {
workspaceId: 'ws-123',
environment: 'production',
secretPath: '/app',
};
const REF = { org: 'hanzo', env: 'production', path: 'app' };
const SECRET = { ...REF, name: 'API_KEY' };
function calledUrl(): string {
return mockFetch.mock.calls[0][0] as string;
}
function calledInit(): any {
return mockFetch.mock.calls[0][1];
}
beforeEach(() => {
mockFetch.mockReset();
});
// ---------------------------------------------------------------------------
// Path shape — the regression that actually happened
// ---------------------------------------------------------------------------
describe('KMS paths', () => {
it('never emits an /api/ prefix', async () => {
// This client used to speak /api/v3/secrets/raw, because the KMS binary
// embedded a console SPA under a root catch-all and answered every
// unmatched path with 200 text/html — so the wrong path looked alive and
// the right one looked broken. Nothing may drift back to it.
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
await kmsListSecrets(TOKEN, REF);
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
await kmsGetSecret(TOKEN, SECRET);
mockFetch.mockResolvedValue(mockResponse({}));
await kmsPutSecret(TOKEN, SECRET, 'v');
mockFetch.mockResolvedValue(mockResponse({}));
await kmsDeleteSecret(TOKEN, SECRET);
expect(mockFetch.mock.calls).toHaveLength(4);
for (const [url] of mockFetch.mock.calls) {
expect(url).not.toContain('/api/');
expect(url).toContain('/v1/kms/');
}
});
it('escapes path segments individually so separators survive', async () => {
// The server splits {rest...} at its LAST slash into (path, name). Escaping
// the joined string would encode the separators into one long name.
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
await kmsGetSecret(TOKEN, { org: 'hanzo', env: 'main', path: 'a/b', name: 'C D' });
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/a/b/C%20D');
});
});
// ---------------------------------------------------------------------------
// kmsListSecrets
// ---------------------------------------------------------------------------
describe('kmsListSecrets', () => {
it('sends GET with correct URL and query params', async () => {
mockFetch.mockResolvedValue(mockResponse({ secrets: [{ secretKey: 'API_KEY' }] }));
const result = await kmsListSecrets(TOKEN, PARAMS);
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, opts] = mockFetch.mock.calls[0];
expect(url).toContain('kms.hanzo.ai/api/v3/secrets/raw?');
expect(url).toContain('workspaceId=ws-123');
expect(url).toContain('environment=production');
expect(url).toContain('secretPath=%2Fapp');
expect(opts.headers.Authorization).toBe(`Bearer ${TOKEN}`);
expect(result).toEqual([{ secretKey: 'API_KEY' }]);
it('returns the names array', async () => {
mockFetch.mockResolvedValue(mockResponse({ names: ['API_KEY', 'DB_URL'] }));
await expect(kmsListSecrets(TOKEN, REF)).resolves.toEqual(['API_KEY', 'DB_URL']);
});
it('uses custom baseUrl when provided', async () => {
mockFetch.mockResolvedValue(mockResponse({ secrets: [] }));
await kmsListSecrets(TOKEN, PARAMS, 'https://custom-kms.example.com');
const [url] = mockFetch.mock.calls[0];
expect(url).toContain('custom-kms.example.com/api/v3/secrets/raw');
it('addresses the collection with path and env as query, and sends the bearer', async () => {
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
await kmsListSecrets(TOKEN, REF);
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets?');
expect(calledUrl()).toContain('path=app');
expect(calledUrl()).toContain('env=production');
expect(calledInit().headers.Authorization).toBe(`Bearer ${TOKEN}`);
});
it('throws on non-ok response', async () => {
it('defaults env when the ref omits it', async () => {
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
await kmsListSecrets(TOKEN, { org: 'hanzo' });
expect(calledUrl()).toContain('env=default');
});
it('yields an empty array when the server omits names', async () => {
mockFetch.mockResolvedValue(mockResponse({}));
await expect(kmsListSecrets(TOKEN, REF)).resolves.toEqual([]);
});
it('uses a custom baseUrl when provided', async () => {
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
await kmsListSecrets(TOKEN, REF, 'https://custom-kms.example.com');
expect(calledUrl()).toContain('custom-kms.example.com/v1/kms/orgs/hanzo/secrets');
});
it('throws with the status on failure', async () => {
mockFetch.mockResolvedValue(mockResponse('Not found', false, 404));
await expect(kmsListSecrets(TOKEN, PARAMS)).rejects.toThrow('KMS list failed: 404');
await expect(kmsListSecrets(TOKEN, REF)).rejects.toThrow('KMS list failed: 404');
});
});
@@ -75,78 +120,47 @@ describe('kmsListSecrets', () => {
// ---------------------------------------------------------------------------
describe('kmsGetSecret', () => {
it('sends GET with encoded secret name', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'DB_URL', secretValue: 'postgres://...' } }));
const result = await kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'DB_URL' });
const [url] = mockFetch.mock.calls[0];
expect(url).toContain('/api/v3/secrets/raw/DB_URL');
expect(result.secretKey).toBe('DB_URL');
it('unwraps secret.value', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'postgres://...' } }));
await expect(kmsGetSecret(TOKEN, SECRET)).resolves.toBe('postgres://...');
});
it('URL-encodes special characters in secret name', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'app/key' } }));
await kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'app/key' });
const [url] = mockFetch.mock.calls[0];
expect(url).toContain('app%2Fkey');
it('addresses the secret and carries env', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
await kmsGetSecret(TOKEN, SECRET);
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/app/API_KEY');
expect(calledUrl()).toContain('env=production');
});
it('throws on non-ok response', async () => {
it('throws with the status on failure', async () => {
mockFetch.mockResolvedValue(mockResponse('Not found', false, 404));
await expect(kmsGetSecret(TOKEN, SECRET)).rejects.toThrow('KMS get failed: 404');
});
});
// ---------------------------------------------------------------------------
// kmsPutSecret — create and replace are one call, because the server has one
// ---------------------------------------------------------------------------
describe('kmsPutSecret', () => {
it('POSTs to the collection with the flat body the server takes', async () => {
mockFetch.mockResolvedValue(mockResponse({}));
await kmsPutSecret(TOKEN, SECRET, 'sk-live-123');
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets');
expect(calledUrl()).not.toContain('API_KEY'); // name is in the body, not the URL
expect(calledInit().method).toBe('POST');
expect(JSON.parse(calledInit().body)).toEqual({
path: 'app',
name: 'API_KEY',
env: 'production',
value: 'sk-live-123',
});
});
it('throws with the status on failure', async () => {
mockFetch.mockResolvedValue(mockResponse('Forbidden', false, 403));
await expect(kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'X' })).rejects.toThrow('KMS get failed: 403');
});
});
// ---------------------------------------------------------------------------
// kmsCreateSecret
// ---------------------------------------------------------------------------
describe('kmsCreateSecret', () => {
it('sends POST with correct body', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'NEW_KEY' } }));
await kmsCreateSecret(TOKEN, { ...PARAMS, secretName: 'NEW_KEY' }, 'secret-value');
const [url, opts] = mockFetch.mock.calls[0];
expect(url).toContain('/api/v3/secrets/raw/NEW_KEY');
expect(opts.method).toBe('POST');
const body = JSON.parse(opts.body);
expect(body.secretValue).toBe('secret-value');
expect(body.workspaceId).toBe('ws-123');
expect(body.environment).toBe('production');
expect(body.type).toBe('shared');
});
it('includes Authorization header', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: {} }));
await kmsCreateSecret(TOKEN, { ...PARAMS, secretName: 'X' }, 'val');
const [, opts] = mockFetch.mock.calls[0];
expect(opts.headers.Authorization).toBe(`Bearer ${TOKEN}`);
expect(opts.headers['Content-Type']).toBe('application/json');
});
});
// ---------------------------------------------------------------------------
// kmsUpdateSecret
// ---------------------------------------------------------------------------
describe('kmsUpdateSecret', () => {
it('sends PATCH with correct body', async () => {
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'KEY' } }));
await kmsUpdateSecret(TOKEN, { ...PARAMS, secretName: 'KEY' }, 'new-value');
const [url, opts] = mockFetch.mock.calls[0];
expect(url).toContain('/api/v3/secrets/raw/KEY');
expect(opts.method).toBe('PATCH');
const body = JSON.parse(opts.body);
expect(body.secretValue).toBe('new-value');
await expect(kmsPutSecret(TOKEN, SECRET, 'v')).rejects.toThrow('KMS put failed: 403');
});
});
@@ -155,21 +169,16 @@ describe('kmsUpdateSecret', () => {
// ---------------------------------------------------------------------------
describe('kmsDeleteSecret', () => {
it('sends DELETE with correct body', async () => {
it('DELETEs the secret URL', async () => {
mockFetch.mockResolvedValue(mockResponse({}));
await kmsDeleteSecret(TOKEN, { ...PARAMS, secretName: 'OLD_KEY' });
const [url, opts] = mockFetch.mock.calls[0];
expect(url).toContain('/api/v3/secrets/raw/OLD_KEY');
expect(opts.method).toBe('DELETE');
const body = JSON.parse(opts.body);
expect(body.workspaceId).toBe('ws-123');
await kmsDeleteSecret(TOKEN, SECRET);
expect(calledInit().method).toBe('DELETE');
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/app/API_KEY');
expect(calledUrl()).toContain('env=production');
});
it('throws on non-ok response', async () => {
mockFetch.mockResolvedValue(mockResponse('Server Error', false, 500));
await expect(kmsDeleteSecret(TOKEN, { ...PARAMS, secretName: 'X' })).rejects.toThrow('KMS delete failed: 500');
it('throws with the status on failure', async () => {
mockFetch.mockResolvedValue(mockResponse('Forbidden', false, 403));
await expect(kmsDeleteSecret(TOKEN, SECRET)).rejects.toThrow('KMS delete failed: 403');
});
});
+51 -16
View File
@@ -147,6 +147,12 @@ importers:
packages/browser:
dependencies:
'@hanzo/ai':
specifier: ^0.2.3
version: 0.2.3
'@hanzo/usage':
specifier: ^0.1.6
version: 0.1.6(react@18.3.1)
'@supabase/supabase-js':
specifier: ^2.50.3
version: 2.50.3
@@ -591,22 +597,6 @@ importers:
zod-to-json-schema:
specifier: ^3.22.4
version: 3.24.6(zod@3.25.71)
optionalDependencies:
'@lancedb/lancedb':
specifier: ^0.13.0
version: 0.13.0(apache-arrow@18.1.0)
'@xenova/transformers':
specifier: ^2.17.2
version: 2.17.2
jsautogui:
specifier: ^1.0.0
version: 1.0.6
playwright:
specifier: 1.55.1
version: 1.55.1
playwright-core:
specifier: ^1.47.0
version: 1.54.1
devDependencies:
'@jest/globals':
specifier: ^30.1.2
@@ -638,6 +628,22 @@ importers:
typescript:
specifier: ^5.3.3
version: 5.8.3
optionalDependencies:
'@lancedb/lancedb':
specifier: ^0.13.0
version: 0.13.0(apache-arrow@18.1.0)
'@xenova/transformers':
specifier: ^2.17.2
version: 2.17.2
jsautogui:
specifier: ^1.0.0
version: 1.0.6
playwright:
specifier: 1.55.1
version: 1.55.1
playwright-core:
specifier: ^1.47.0
version: 1.54.1
packages/meetings:
dependencies:
@@ -2876,6 +2882,10 @@ packages:
resolution: {integrity: sha512-2LZWEZug7qPmnOzXQ2HdvAxPPVRql//34StpJ41hS5x5sA+9dxsMAuLOYP9swFwTic1rPKcCrdprsEfdlpkpnQ==}
engines: {node: '>=18'}
'@hanzo/ai@0.2.3':
resolution: {integrity: sha512-vL042sYaVzmWUTrjcCrx3Gay/a+oa9Mgv1cVetapeyikSS4wKOw9lMdSbxw2OD8puJK/Ozew7cglL43MYI9L3Q==}
engines: {node: '>=18'}
'@hanzo/iam@0.13.2':
resolution: {integrity: sha512-BYywnIznlcA3sQK4VQzKM+InvyCsdP67F5e4eO3muGjBotF1Zo3hqBRD7VIc9159plrlWzPJqPT4rN/1GuZmuA==}
engines: {node: '>=18'}
@@ -2885,6 +2895,20 @@ packages:
react:
optional: true
'@hanzo/usage@0.1.6':
resolution: {integrity: sha512-0gr4ZJ5qTH1hRt706uMciAevFPXG/08Xd5zbyZBlAi1o4k4EdKHTqLm/pRnbhv6jZbWTIOUtRQSysGyeJfOQMQ==}
peerDependencies:
'@hanzo/gui': '>=7.2.2'
'@hanzogui/lucide-icons-2': '>=7.2.2'
react: '>=18'
peerDependenciesMeta:
'@hanzo/gui':
optional: true
'@hanzogui/lucide-icons-2':
optional: true
react:
optional: true
'@hono/node-server@1.19.14':
resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}
engines: {node: '>=18.14.1'}
@@ -3685,6 +3709,7 @@ packages:
'@lancedb/lancedb@0.21.0':
resolution: {integrity: sha512-3c65DfAsTzGb3/Y2WtpJeqPFb2BgoTsYweg3gj9zP6t8CCaKQSeVWEGE8Nowtdj5Jkj9/nmHUoKPv4jCsds2yQ==}
engines: {node: '>= 18'}
cpu: [x64, arm64]
os: [darwin, linux, win32]
peerDependencies:
apache-arrow: '>=15.0.0 <=18.1.0'
@@ -3915,16 +3940,19 @@ packages:
'@nut-tree-fork/libnut-darwin@2.7.5':
resolution: {integrity: sha512-LbqtPtMPTJUcg4XoPP2jsU1wc8flBcGyKTerKsIfK9cD7nBHROnO0QksbrsbSWEpLym8T8fRtuU7XEY83l6Z2Q==}
engines: {node: '>=10.15.3'}
cpu: [x64, arm64]
os: [darwin, linux, win32]
'@nut-tree-fork/libnut-linux@2.7.5':
resolution: {integrity: sha512-uxaXEcRKnFObAljsoR6tLOBUU1dJ2sctloG6gFgCBGN7+k6Jdv6jZfOuNjd/fpdq2C5WPMm0rtn9EE7h5J3Jcg==}
engines: {node: '>=10.15.3'}
cpu: [x64, arm64]
os: [darwin, linux, win32]
'@nut-tree-fork/libnut-win32@2.7.5':
resolution: {integrity: sha512-yqC87zvmFcDPwFrRU40DYhN0xmEVM3aSkOuyF0IX+y1x+HWSu/i0PNklATpPBhGid3QVb/TOHuVoaraMrUFCNw==}
engines: {node: '>=10.15.3'}
cpu: [x64, arm64]
os: [darwin, linux, win32]
'@nut-tree-fork/libnut@4.2.6':
@@ -3938,6 +3966,7 @@ packages:
'@nut-tree-fork/nut-js@4.2.6':
resolution: {integrity: sha512-aI/WCX7gE1HFGPH3EZP/UWqpNMM1NMoM/EkXqp7pKMgXFCi8e5+o5p+jd/QOYpmALv9bQg7+s69nI7FONbMqDg==}
engines: {node: '>=16'}
cpu: [x64, arm64]
os: [linux, darwin, win32]
'@nut-tree-fork/provider-interfaces@4.2.6':
@@ -13420,6 +13449,8 @@ snapshots:
'@hanzo/ai@0.2.0': {}
'@hanzo/ai@0.2.3': {}
'@hanzo/iam@0.13.2(react@18.3.1)':
dependencies:
jose: 6.2.3
@@ -13436,6 +13467,10 @@ snapshots:
optionalDependencies:
react: 19.2.7
'@hanzo/usage@0.1.6(react@18.3.1)':
optionalDependencies:
react: 18.3.1
'@hono/node-server@1.19.14(hono@4.12.27)':
dependencies:
hono: 4.12.27