Compare commits

...
28 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
Hanzo AI 967297f2dc Usage panel: Claude + Codex session/weekly usage in popup
Add an AI Usage card to the action popup showing Claude and Codex
session/weekly % used + reset time, a refresh button, and a link to
console.hanzo.ai/ai-accounts.

- shared/usage.ts: browser UsageHost (fetch with credentials:'include',
  no-op fs) running the @hanzo/usage engine in the background context,
  where host permissions attach live claude.ai/chatgpt.com cookies and
  bypass CORS. Claude via the package web strategy (empty cookieHeader
  passes its gate; real cookie rides credentials:'include'); Codex via a
  local fetch to /backend-api/wham/usage mapped onto the package's public
  UsageSnapshot/RateWindow types (its provider only ships an auth.json
  OAuth lane, unusable without disk).
- background.ts + background-firefox.ts: usage.fetch message handler.
- popup: AI Usage card + renderer, refresh, accounts link.
- build.js: alias @hanzo/usage to the sibling repo's built ESM for both
  background bundles (same pattern as the @hanzo/gui shim).
- manifests: host_permissions for claude.ai + chatgpt.com (Chrome MV3 +
  Firefox).
- version 1.9.31 -> 1.9.32 (patch).
2026-07-07 15:14:45 -07:00
Hanzo Dev 300337a57b chore(npm): mark hanzo-ai (raycast) + hanzo-ide (vscode) npm-private
npm rejects the unscoped 'hanzo-ai' name (too similar to existing 'hanzoai'), and
both publish to their OWN stores (Raycast Store / VS Marketplace) via dedicated
jobs — they don't belong on npm. Setting private so pnpm -r publish skips them.
2026-07-04 03:45:58 -07:00
Hanzo Dev 8e722f22fe fix(npm): write authToken to .npmrc explicitly for pnpm publish
The recursive publish 404'd on every package (npm's obscured 'unauthenticated'):
setup-node's ${NODE_AUTH_TOKEN}-templated .npmrc is read by npm but not reliably
by pnpm publish. Write the token literally into .npmrc + set @hanzo:registry, and
add npm whoami as an auth diagnostic. .npmrc gitignored.
2026-07-04 03:38:11 -07:00
Hanzo Dev 5a55ce029f chore(npm): publish all workspace packages to public npm at 1.0.0
Normalize every packages/* package for public npm publish:
- version: pre-1.0 (0.x) → 1.0.0; already-≥1.0 kept (mcp 2.4.1,
  cli-tools 1.8.0, dxt 1.8.1, browser/hanzo-ide/office/outlook 1.9.31,
  gworkspace 1.9.30, aci/auth 1.0.0)
- remove "private" from all 22 gated packages/* (apps/site + repo root
  stay private — site is a deployed website, not an npm library)
- add publishConfig.access=public everywhere (scoped @hanzo/* need it)
- add files[] + valid main pointing at built output so no empty tarballs;
  no-build packages ship src+README

CI npm job now publishes the whole workspace:
- build @hanzo/cards first (slack/teams import its dist), then
  pnpm -r --if-present run build || true
- pnpm -r publish --access public --no-git-checks --ignore-scripts
  --ignore-scripts prevents raycast/vscode `publish` lifecycle scripts
  (Raycast Store / VS Marketplace) from hijacking and aborting the run.
  workspace:* (auth, cards) is rewritten to the real version at publish.
2026-07-04 03:26:04 -07:00
Hanzo Dev abb2ad56cb feat(verticals): iManage (@hanzo/imanage) — legal DMS — Wave 5 COMPLETE
iManage Work OAuth2 + Work API (workspaces/documents/search) + content extraction,
AI actions (summarize doc / extract clauses-dates-parties / search-synthesize);
server-side tokens, never logs content, grounded extraction, 'not legal advice'.
121 tests. On published @hanzo/ai@0.2.0.

All 6 Wave 5 verticals now on main: epic(109) procore(102) quickbooks(91)
canvas-lms(119) workday(113) imanage(121). CI step added.
2026-07-04 02:02:39 -07:00
Hanzo Dev 4193d4889e Merge remote-tracking branch 'origin/feat/imanage' 2026-07-04 02:02:14 -07:00
Hanzo Dev 8de63fa05f feat(imanage): Hanzo AI for iManage Work — legal DMS panel + OAuth/Work-API proxy
New package @hanzo/imanage: an embedded-app panel over @hanzo/ai for iManage
Work (the dominant legal document management system), mirroring the
packages/procore OAuth + API-proxy + pure-core shape.

- OAuth2 Authorization Code against the iManage Control Center
  (/auth/oauth2/authorize + /token); server-side token exchange + refresh, the
  client secret never reaches the browser.
- Work API v2 wrappers (workspaces, folder children, document profile +
  content, search, gated profile write-back) scoped by customer + library in
  the path, X-Auth-Token auth, envelope/offset-limit pagination. Pure.
- Pure legal document-context assembly with text extraction (binary/OCR out of
  scope, reported honestly) and one truncation-honest windowing algorithm.
- Four AI actions — summarize document, extract key clauses/dates/parties,
  search-and-synthesize a matter, compare a document set — plus freeform ask,
  over a single grounded ask() path.
- Same-origin proxy keeps tokens + secret server-side; NEVER logs document
  content. Legal confidentiality posture documented in the README.
- 121 vitest tests (config/oauth/api/parse/documents/hanzo/actions/panel),
  tsc --noEmit clean, node build.js green.

Registers packages/imanage in pnpm-workspace.yaml (one line).
2026-07-04 02:01:19 -07:00
Hanzo Dev 02b447d027 feat(verticals): Workday (@hanzo/workday) — HR/HCM
Workday OAuth2 (HTTP Basic client auth, non-rotating refresh) + REST (staffing/
recruiting/absence) + RaaS custom reports, AI actions (summarize worker/team/org,
draft requisition); read-only proxy (405 on writes). 113 tests. On published
@hanzo/ai@0.2.0. CI step added.
2026-07-04 01:56:42 -07:00
Hanzo Dev 96807b05cf Merge remote-tracking branch 'origin/feat/workday' 2026-07-04 01:56:20 -07:00
Hanzo Dev 05a35ac763 feat(workday): Hanzo AI for Workday — read-only HCM app
@hanzo/workday: an embedded-app panel + read-only OAuth + API-proxy service
over Workday people data, built on @hanzo/ai + @hanzo/iam via api.hanzo.ai.
Mirrors packages/procore's pure-core shape.

- OAuth2 Authorization Code + refresh against the tenant token endpoint
  (…/ccx/oauth2/{tenant}/token) with HTTP Basic client auth (secret in the
  header, never the body); non-rotating refresh carried forward.
- Workday REST wrappers (staffing v6 workers/orgs/directReports, recruiting v4
  requisitions, absenceManagement v1 absence types) with limit/offset + the
  { total, data } envelope, plus RaaS custom-report reads ({ Report_Entry }).
- Pure people-context assembly with honest budget/truncation windowing.
- Five HR-guardrailed AI actions: summarize worker, draft job description,
  org & headcount, answer HR question, draft review feedback.
- Read-only by design: the proxy is GET-only (405 otherwise); write-back is
  documented as a gated future addition.
- 113 vitest tests; tsc --noEmit clean; esbuild build green.

Registers packages/workday in pnpm-workspace.yaml.
2026-07-04 01:55:15 -07:00
Hanzo Dev a164395d4a feat(verticals): Canvas LMS (@hanzo/canvas-lms) — education
Canvas OAuth2 (per-institution host, non-rotating refresh) + REST v1 (courses/
assignments/submissions/pages) w/ Link-header pagination, AI actions (summarize
course/draft feedback/generate questions), write-back submission comments +
announcements. 119 tests. On published @hanzo/ai@0.2.0. CI step added.
2026-07-04 01:55:03 -07:00
Hanzo Dev 4670a9ee91 Merge remote-tracking branch 'origin/feat/canvas-lms' 2026-07-04 01:54:36 -07:00
Hanzo Dev a2c014b777 feat(canvas-lms): Hanzo AI for Canvas LMS — OAuth + API-proxy app
@hanzo/canvas-lms: an embedded-app panel + OAuth/API-proxy service over the
Canvas REST API, built on @hanzo/ai (api.hanzo.ai /v1) and @hanzo/iam, mirroring
packages/procore.

- Canvas OAuth2 Authorization-Code (server-side secret + non-rotating refresh)
- Pure Canvas REST v1 wrappers (courses/assignments/submissions/discussions/
  pages/modules/enrollments) + RFC 5988 Link-header pagination + HTML->text
- Course-context windowing with honest truncation
- Five AI actions: summarize course, draft feedback, generate questions,
  summarize submissions, draft announcement; gated write-backs (submission
  comment via PUT, announcement via POST)
- 119 vitest tests; tsc --noEmit clean; esbuild build green
- Registered in pnpm-workspace.yaml
2026-07-04 01:53:47 -07:00
Hanzo Dev fc6d9bb805 feat(verticals): Epic SMART-on-FHIR (@hanzo/epic) — healthcare
SMART-on-FHIR app: EHR/standalone launch, PKCE + server-side token exchange,
FHIR R4 read (Patient/Condition/MedicationRequest/AllergyIntolerance/Observation/
DocumentReference) w/ Bundle pagination, 4 AI actions (summarize patient / draft
note / extract problems&meds / ask). PHI stays server-side, never logged,
read-only. 109 tests. On published @hanzo/ai@0.2.0. CI step added.
2026-07-04 01:48:28 -07:00
Hanzo Dev ad6af1fd72 Merge remote-tracking branch 'origin/feat/epic' 2026-07-04 01:48:09 -07:00
Hanzo Dev 73370ce288 feat(epic): Hanzo AI for Epic (SMART on FHIR)
Read+assist clinical copilot embedded in the EHR via SMART on FHIR. Loads the
launched patient's chart over FHIR R4 (problems, meds, allergies, labs/vitals,
notes) and runs four actions — summarize patient, draft SOAP note, extract
problems & meds, ask — through the api.hanzo.ai gateway via @hanzo/ai@^0.2.0.

PHI posture: the FHIR/PHI access token is confined server-side (server.ts);
the browser holds only an opaque HttpOnly session cookie and a Hanzo gateway
key. No PHI is ever logged; SMART is auth-code + PKCE (S256) with the
confidential secret read from the environment; the proxy is scoped to the six
read resources and the session's own FHIR base (SSRF/cross-tenant guards).
Read + assist only — no clinical write-back, no *.write scope.

Tests: 109 vitest across config/smart-oauth/fhir-client/chart/hanzo/auth/server.
Workspace-wired like every sibling: test/ dir, root pnpm-lock importer, no
package-level lock.
2026-07-04 01:45:59 -07:00
168 changed files with 17940 additions and 476 deletions
+12
View File
@@ -99,6 +99,18 @@ jobs:
- name: Test QuickBooks (finance)
run: pnpm --filter @hanzo/quickbooks test
- name: Test Epic (SMART-on-FHIR)
run: pnpm --filter @hanzo/epic test
- name: Test Canvas LMS (education)
run: pnpm --filter @hanzo/canvas-lms test
- name: Test Workday (HR)
run: pnpm --filter @hanzo/workday test
- name: Test iManage (legal DMS)
run: pnpm --filter @hanzo/imanage test
- name: Test cards (shared card-builder)
run: pnpm --filter @hanzo/cards test
+41 -73
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,19 +192,7 @@ 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 (@hanzo/mcp) ───
# ─── npm (all @hanzo/* workspace packages) ───
npm:
name: npm
runs-on: hanzo-build-linux-amd64
@@ -255,13 +207,37 @@ jobs:
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @hanzo/mcp run build
- name: Publish @hanzo/mcp
working-directory: packages/mcp
run: npm publish --access public
# Shared libraries first: their consumers (slack, teams) import the built
# dist at publish time, so @hanzo/cards must exist before the rest build.
- name: Build shared libraries
run: pnpm --filter @hanzo/cards build
# Build everything with a build script. Guarded with `|| true` so a package
# whose toolchain is absent on the runner (jupyter→jupyterlab, desktop→cargo)
# cannot abort the publish of the rest.
- name: Build all packages
run: pnpm -r --if-present run build || true
# Recursive publish: skips private (root, apps/site), skips versions already
# on npm (e.g. @hanzo/mcp), rewrites workspace:* → the real version, and
# publishes in topological order so @hanzo/cards lands before its consumers.
# --ignore-scripts is required: raycast (hanzo-ai) and vscode (hanzo-ide)
# define a `publish` lifecycle script targeting their own stores (Raycast /
# VS Marketplace); without this flag those scripts run mid-publish, fail, and
# abort every package after them. Builds already ran above, so no publish-time
# script is needed. `|| true` keeps one bad package from blocking the rest.
- name: Publish all
run: |
# setup-node writes a ${NODE_AUTH_TOKEN}-templated .npmrc that `npm` expands
# but `pnpm publish` does not reliably read — write the token literally so
# pnpm authenticates (a 404 on PUT is npm's obscured "unauthenticated").
echo "//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}" >> .npmrc
echo "@hanzo:registry=https://registry.npmjs.org/" >> .npmrc
npm whoami || echo "::warning::npm whoami failed — NPM_TOKEN invalid or lacks @hanzo publish rights"
pnpm -r publish --access public --no-git-checks --ignore-scripts --report-summary || true
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
continue-on-error: true
# ─── JetBrains Marketplace ───
jetbrains:
@@ -294,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/*"
+1
View File
@@ -65,3 +65,4 @@ build/
.next/
*.log
tmp/
.npmrc
+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.31",
"version": "1.9.36",
"private": true,
"description": "Hanzo AI Extension",
"license": "MIT",
+8 -1
View File
@@ -47,5 +47,12 @@
"homepage": "https://hanzo.ai",
"bugs": {
"url": "https://github.com/hanzoai/aci/issues"
}
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"README.md"
]
}
+7 -1
View File
@@ -16,5 +16,11 @@
"typescript": "^5.8.3",
"vitest": "^3.2.6"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"src"
]
}
+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)"
+13 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/browser-extension",
"version": "1.9.31",
"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",
@@ -36,5 +38,14 @@
"engines": {
"node": ">=18.0.0"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"images",
"manifest.json"
]
}
@@ -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 [];
}
}
+45 -1
View File
@@ -27,6 +27,7 @@ import {
type ZapManager,
} from './shared/zap.js';
import { connectNativeZap, type NativeZapState } from './shared/native-zap.js';
import { fetchAllUsage } from './shared/usage.js';
import { pickEvaluable, wrapEvaluable } from './shared/evaluable.js';
import {
getRagConfig,
@@ -109,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 {
@@ -3000,6 +3005,17 @@ browser.runtime.onMessage.addListener((request: any, sender: any, sendResponse:
sendResponse({ success: false, error: 'Tab filesystem requires CDP bridge.' });
break;
// AI provider usage (Claude + Codex, via @hanzo/usage)
case 'usage.fetch': {
try {
const providers = await fetchAllUsage();
sendResponse({ success: true, providers });
} catch (e: any) {
sendResponse({ success: false, error: e.message });
}
break;
}
default:
sendResponse({ success: false, error: `Unknown action: ${request.action}` });
break;
@@ -3072,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');
+24 -1
View File
@@ -38,6 +38,7 @@ import { BrowserControl } from './browser-control';
import { WebGPUAI } from './webgpu-ai';
import { getCDPBridge, CDPBridge } from './browser-dispatch';
import * as auth from './auth';
import { fetchAllUsage } from './shared/usage.js';
import { listModels, chatCompletion, ChatMessage } from './chat-client';
import { PageMonitor } from './page-monitor';
import {
@@ -282,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) {
@@ -1787,6 +1797,19 @@ async function handleMessage(request: any, sender: chrome.runtime.MessageSender,
break;
}
// --- AI provider usage (Claude + Codex, via @hanzo/usage) ---
case 'usage.fetch': {
(async () => {
try {
const providers = await fetchAllUsage();
sendResponse({ success: true, providers });
} catch (e: any) {
sendResponse({ success: false, error: e.message });
}
})();
break;
}
}
}
+86 -58
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
@@ -16,17 +26,27 @@ async function build() {
const hanzoGuiShim = path.join(__dirname, 'gui-primitives.tsx');
console.log('Using @hanzo/gui local primitives shim:', hanzoGuiShim);
// The Usage panel runs the headless @hanzo/usage engine in the background
// 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'
@@ -36,29 +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']
external: ['chrome', 'browser'],
});
// 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']
external: ['browser'],
});
// 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'
@@ -73,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',
@@ -83,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'
@@ -103,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'
@@ -111,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).
@@ -130,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>
@@ -159,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']) {
@@ -202,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.
@@ -257,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) => {
+10 -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",
@@ -17,6 +17,8 @@
"host_permissions": [
"http://localhost/*",
"https://localhost/*",
"https://claude.ai/*",
"https://chatgpt.com/*",
"<all_urls>"
],
"content_security_policy": {
@@ -47,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",
+17 -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",
@@ -19,6 +19,8 @@
"host_permissions": [
"http://localhost/*",
"https://localhost/*",
"https://claude.ai/*",
"https://chatgpt.com/*",
"<all_urls>"
],
"content_security_policy": {
@@ -52,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();
}
});
+56
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">
@@ -96,6 +108,22 @@
<div class="divider"></div>
<!-- AI Usage (Claude + Codex, from the current browser session) -->
<div class="usage-header" style="display:flex;align-items:center;justify-content:space-between;">
<h3>AI Usage</h3>
<button id="usage-refresh" class="btn-icon" title="Refresh usage">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M23 4v6h-6M1 20v-6h6"/>
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
</svg>
</button>
</div>
<div id="usage-list" class="usage-list" style="display:flex;flex-direction:column;gap:8px;"></div>
<a href="https://console.hanzo.ai/ai-accounts" target="_blank"
style="display:inline-block;margin-top:8px;font-size:11px;color:var(--text-muted,#888);">Manage AI accounts →</a>
<div class="divider"></div>
<!-- Tools -->
<h3>Tools</h3>
<div class="tools-grid">
@@ -194,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>
+113
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 || '';
@@ -693,6 +722,90 @@ document.addEventListener('DOMContentLoaded', () => {
});
});
// --- AI Usage (Claude + Codex) — data fetched by the background context
// where host permissions attach the live claude.ai / chatgpt.com cookies. ---
const usageList = document.getElementById('usage-list');
const usageRefresh = document.getElementById('usage-refresh');
interface UsageWindow { usedPercent: number; resetsAt?: string }
interface UsageSnapshotLite {
primary?: UsageWindow;
secondary?: UsageWindow;
identity?: { plan?: string };
}
interface ProviderUsageLite {
providerId: string;
displayName: string;
color?: string;
snapshot?: UsageSnapshotLite;
error?: string;
}
const esc = (s: string) =>
s.replace(/[&<>"]/g, (c) => (({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }) as Record<string, string>)[c]);
function resetLabel(iso?: string): string {
if (!iso) return '';
const ms = new Date(iso).getTime() - Date.now();
if (!Number.isFinite(ms)) return '';
if (ms <= 0) return 'resets now';
const m = Math.round(ms / 60000);
if (m < 60) return `resets in ${m}m`;
const h = Math.round(m / 60);
if (h < 24) return `resets in ${h}h`;
return `resets in ${Math.round(h / 24)}d`;
}
function lane(label: string, w: UsageWindow | undefined, color?: string): string {
if (!w || typeof w.usedPercent !== 'number') return '';
const pct = Math.max(0, Math.min(100, Math.round(w.usedPercent)));
return `
<div class="usage-lane" style="display:flex;align-items:center;gap:8px;font-size:11px;margin-top:4px;">
<span style="width:52px;color:var(--text-muted,#888);">${label}</span>
<span style="flex:1;height:6px;border-radius:3px;background:var(--surface-2,#222);overflow:hidden;">
<span style="display:block;height:100%;width:${pct}%;background:${color || 'var(--accent,#d97757)'};"></span>
</span>
<span style="width:34px;text-align:right;">${pct}%</span>
</div>`;
}
function renderUsage(providers: ProviderUsageLite[]) {
if (!usageList) return;
usageList.innerHTML = providers
.map((p) => {
const body = p.error
? `<div style="font-size:11px;color:var(--text-muted,#888);margin-top:4px;">${esc(p.error)}</div>`
: `${lane('Session', p.snapshot?.primary, p.color)}${lane('Weekly', p.snapshot?.secondary, p.color)}
<div style="font-size:10px;color:var(--text-muted,#888);margin-top:3px;">${esc(resetLabel(p.snapshot?.primary?.resetsAt))}</div>`;
const plan = p.snapshot?.identity?.plan;
return `
<div class="usage-row" style="padding:8px;border:1px solid var(--border,#2a2a2a);border-radius:8px;">
<div style="display:flex;align-items:center;gap:6px;">
<span style="width:8px;height:8px;border-radius:50%;background:${p.color || '#888'};"></span>
<strong style="font-size:12px;">${esc(p.displayName)}</strong>
${plan ? `<span style="font-size:10px;color:var(--text-muted,#888);">${esc(plan)}</span>` : ''}
</div>
${body}
</div>`;
})
.join('');
}
function loadUsage() {
if (!usageList) return;
usageList.innerHTML = '<div style="font-size:11px;color:var(--text-muted,#888);">Loading…</div>';
chrome.runtime.sendMessage({ action: 'usage.fetch' }, (resp) => {
if (chrome.runtime.lastError || !resp?.success) {
usageList.innerHTML = '<div style="font-size:11px;color:var(--text-muted,#888);">Usage unavailable</div>';
return;
}
renderUsage(resp.providers as ProviderUsageLite[]);
});
}
usageRefresh?.addEventListener('click', loadUsage);
loadUsage();
// Init
checkAuth();
});
+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. */
+148
View File
@@ -0,0 +1,148 @@
// Usage engine bridge — runs the @hanzo/usage providers inside the extension
// background context, where host permissions let fetch() attach the user's
// claude.ai / chatgpt.com session cookies (credentials: 'include') and bypass
// CORS. There is no filesystem in a browser, so file ops are no-ops and the
// OAuth/CLI strategies simply report "unavailable": the web strategy carries
// Claude, and a small local fetch carries Codex (whose provider only ships an
// auth.json OAuth lane, unusable without disk access).
import {
runPipeline,
claudeProvider,
codexProvider,
type UsageHost,
type HttpRequest,
type HttpResponse,
type UsageSnapshot,
type RateWindow,
type ProviderFetchOutcome,
} from '@hanzo/usage';
/** Serialisable per-provider result sent to the popup. */
export interface ProviderUsage {
providerId: string;
displayName: string;
color?: string;
dashboardUrl?: string;
snapshot?: UsageSnapshot;
/** User-facing failure reason (e.g. "Open chatgpt.com to sign in"). */
error?: string;
}
const http = async (req: HttpRequest): Promise<HttpResponse> => {
const controller = new AbortController();
const timeout = req.timeoutMs
? setTimeout(() => controller.abort(), req.timeoutMs)
: undefined;
try {
const res = await fetch(req.url, {
method: req.method ?? 'GET',
headers: req.headers,
body: req.body,
credentials: 'include',
signal: controller.signal,
});
const headers: Record<string, string> = {};
res.headers.forEach((v, k) => {
headers[k] = v;
});
return { status: res.status, headers, text: await res.text() };
} finally {
if (timeout) clearTimeout(timeout);
}
};
/** Browser host: network only; no fs, env, or home directory in an extension. */
const browserHost: UsageHost = {
readTextFile: async () => undefined,
listDir: async () => [],
writeTextFile: async () => {},
http,
env: () => undefined,
homeDir: () => '',
now: () => new Date(),
};
const isAuthError = (text: string): boolean => /\b(401|403)\b/.test(text);
const outcomeError = (providerHost: string, outcome: ProviderFetchOutcome): string => {
const attempt = [...outcome.attempts].reverse().find((a) => a.error);
const detail = attempt?.error ?? 'no data';
return isAuthError(detail) ? `Open ${providerHost} to sign in` : detail;
};
const fetchClaude = async (): Promise<ProviderUsage> => {
const { displayName, color, dashboardUrl } = claudeProvider.metadata;
const base: ProviderUsage = { providerId: 'claude', displayName, color, dashboardUrl };
try {
// Empty cookieHeader passes the web strategy's `typeof === 'string'` gate;
// the real session cookie is attached by credentials: 'include'.
const outcome = await runPipeline(claudeProvider, {
host: browserHost,
sourceMode: 'web',
settings: { cookieHeader: '' },
});
if (outcome.result) return { ...base, snapshot: outcome.result.usage };
return { ...base, error: outcomeError('claude.ai', outcome) };
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : String(e) };
}
};
// Codex wire shape (chatgpt.com/backend-api/wham/usage) — mirrors the private
// interface in @hanzo/usage's codex provider, mapped onto the package's public
// UsageSnapshot / RateWindow types.
interface CodexWindow {
used_percent?: number;
reset_at?: number;
limit_window_seconds?: number;
}
interface CodexUsageResponse {
plan_type?: string;
rate_limit?: { primary_window?: CodexWindow; secondary_window?: CodexWindow };
}
const toWindow = (w: CodexWindow | undefined): RateWindow | undefined => {
if (!w || typeof w.used_percent !== 'number') return undefined;
return {
usedPercent: w.used_percent,
windowMinutes: w.limit_window_seconds ? Math.round(w.limit_window_seconds / 60) : undefined,
resetsAt: w.reset_at ? new Date(w.reset_at * 1000).toISOString() : undefined,
};
};
const fetchCodex = async (): Promise<ProviderUsage> => {
const { displayName, color, dashboardUrl } = codexProvider.metadata;
const base: ProviderUsage = { providerId: 'codex', displayName, color, dashboardUrl };
try {
const res = await http({
url: 'https://chatgpt.com/backend-api/wham/usage',
headers: { Accept: 'application/json' },
timeoutMs: 30_000,
});
if (res.status !== 200) {
return {
...base,
error: isAuthError(String(res.status))
? 'Open chatgpt.com to sign in'
: `HTTP ${res.status}`,
};
}
const body = JSON.parse(res.text) as CodexUsageResponse;
const snapshot: UsageSnapshot = {
providerId: 'codex',
primary: toWindow(body.rate_limit?.primary_window),
secondary: toWindow(body.rate_limit?.secondary_window),
identity: { providerId: 'codex', plan: body.plan_type, loginMethod: 'web' },
dataConfidence: 'percentOnly',
updatedAt: browserHost.now().toISOString(),
};
return { ...base, snapshot };
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : String(e) };
}
};
/** Fetch Claude + Codex usage in parallel from the current browser session. */
export const fetchAllUsage = async (): Promise<ProviderUsage[]> =>
Promise.all([fetchClaude(), fetchCodex()]);
+4
View File
@@ -9,6 +9,10 @@
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"@hanzo/usage": ["../../../../usage/packages/core/dist/index.d.ts"]
},
"declaration": true,
"declarationMap": true,
"sourceMap": true,
+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');
});
});
+11 -3
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/canva",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI for Canva — a side-panel Apps SDK app: generate marketing copy, rewrite the selected text, translate, brainstorm content ideas, and ask about the design. An @canva/app-ui-kit React panel that reads the selection/page via @canva/design and adds/replaces text elements, running the model gateway through the published @hanzo/ai over api.hanzo.ai.",
"private": true,
"type": "module",
"scripts": {
"build": "node build.js",
@@ -52,5 +51,14 @@
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/canva"
}
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/app.js"
}
+236
View File
@@ -0,0 +1,236 @@
# Hanzo AI for Canvas LMS
AI over your Canvas course — **summarize a course**, **draft assignment feedback**,
**generate quiz/discussion questions**, **summarize student submissions**, and
**draft an announcement**, plus a freeform "ask about the course" box. An
embedded-app **panel** you host at `canvas.hanzo.ai`, backed by a small **OAuth +
API-proxy service** that keeps the Canvas client secret and access tokens
server-side.
Built on the published Hanzo SDK:
- **[`@hanzo/ai`](https://www.npmjs.com/package/@hanzo/ai)** — the headless client.
`createAiClient({ baseUrl, token }).chat.completions.create({ model, messages })`
and `.models.list()`. All model calls go to `https://api.hanzo.ai` on `/v1/...`
(never an `/api/` prefix). We import it; we do not reimplement the transport.
- **[`@hanzo/iam`](https://www.npmjs.com/package/@hanzo/iam)** — Hanzo identity /
the `hk-…` API key the panel uses as its gateway bearer.
Canvas is the dominant higher-ed / K12 LMS: courses, syllabi, modules, assignments,
pages, discussions, and student submissions. This app reads those records through
the Canvas REST API and grounds every AI draft in them. Everything it produces —
feedback, questions, announcements, summaries — is a **draft for an educator to
review**, not an authoritative grade or decision.
> **Package name:** `@hanzo/canvas-lms` (directory `packages/canvas-lms`) — named to
> avoid colliding with the design-tool package `packages/canva`.
---
## Architecture
```
Browser panel (dist/index.html, app.js) Server service (dist/server.js)
───────────────────────────────────── ──────────────────────────────
reads Canvas via ──► /proxy/* ──────────► injects OAuth Bearer + refresh,
same-origin proxy (cookie) forwards to {canvas-host}/api/v1
(never sees a Canvas token) with the user's access token
└── calls api.hanzo.ai /v1 directly with the pasted hk-… Hanzo key
(@hanzo/ai headless client)
```
- The **panel** never holds a Canvas token or the client secret. It reaches Canvas
only through the same-origin `/proxy/*` endpoint (with an HttpOnly session
cookie). It talks to `api.hanzo.ai` directly with the user's pasted Hanzo key.
- The **service** is the only place `CANVAS_CLIENT_SECRET` and the OAuth tokens
exist. It runs the install flow, holds the session, refreshes the token
transparently, and proxies REST calls.
### Source layout (all pure logic is unit-tested)
| File | Responsibility |
| --- | --- |
| `src/config.ts` | Canvas host normalization, REST version, gateway URL, server-secret config (`readServerConfig` fails fast). |
| `src/canvas-oauth.ts` | OAuth2 Authorization-Code shaping: `authorizeUrl`, `tokenExchange`, `refreshExchange`, token parsing, non-rotating-refresh carry + expiry math. Pure. |
| `src/canvas-api.ts` | REST v1 request wrappers (`listCourses`, `getCourse`, `listAssignments`, `listSubmissions`, `postSubmissionComment`, `createAnnouncement`, …) with pagination + `Link`-header parsing, and response parsers. Pure. |
| `src/course.ts` | Course/assignment/submission/page/module JSON → windowed context text, HTML→text, honest truncation. Pure. |
| `src/hanzo.ts` | Thin over `@hanzo/ai`: prompt assembly + the single `ask` path + `listModels`. |
| `src/actions.ts` | The five AI actions (id → prompt) over `ask`. One code path to the model. |
| `src/panel.ts` | Browser proxy-client request shaping + launch-context parsing. Pure. |
| `src/app.ts` | The DOM glue for the panel (the one impure browser entry). |
| `src/server.ts` | Node http service: OAuth install/callback + `/proxy/*`. |
---
## 1. Create a Canvas Developer Key
Canvas OAuth apps authenticate with a **Developer Key** (an OAuth2
client-id/secret). An account admin creates it in **Admin → Developer Keys → +
Developer Key → API Key**:
1. **Key Name**: `Hanzo AI for Canvas` (any label).
2. **Redirect URIs** — exactly the URL your service serves the callback at:
```
https://canvas.hanzo.ai/oauth/callback
```
(For local development, add `http://localhost:8791/oauth/callback` too.)
3. **Scopes** — leave **Enforce Scopes** *off* for the simplest setup (permissions
then follow the authorizing user's Canvas role). If you enable enforcement, add
the granular URL-scopes exported as `RECOMMENDED_SCOPES` in `src/config.ts`
(the read surface plus `PUT …/submissions/:user_id` and
`POST …/discussion_topics` for the two write-backs).
4. **Save**, then **ON** the key's state, and copy the **Client ID** (the numeric
key id) and **Client Secret** (the "Key" / secret value).
5. Note your institution's **Canvas host** (e.g. `school.instructure.com` or your
custom Canvas domain) — the app builds every OAuth + API URL from it.
Because Canvas is self-hosted per institution, the host is a required deployment
value (`CANVAS_HOST`); there is no fixed host list.
---
## 2. OAuth flow
Standard **Authorization Code** grant (server-side secret):
1. `GET /oauth/install` → 302 to
`https://{canvas-host}/login/oauth2/auth?client_id=…&response_type=code&redirect_uri=…&state=…`.
2. The user consents; Canvas redirects back to `GET /oauth/callback?code=…&state=…`.
3. The service verifies `state`, then POSTs to `/login/oauth2/token` with
`grant_type=authorization_code`, the `code`, the `client_id` + `client_secret`
(**in the body, server-side only**), and the same `redirect_uri`.
4. It opens a session, sets an HttpOnly cookie, and the panel is authenticated.
5. Access tokens are short-lived (~1h). The service refreshes with
`grant_type=refresh_token` **before** each proxied call when the token has
expired. Canvas does **not** rotate the refresh token (the refresh response omits
it), so the original refresh token is carried forward.
> In-memory sessions here are for a single instance. For a multi-instance
> deployment behind `hanzoai/ingress`, persist sessions + the OAuth `state` set to
> `hanzoai/kv` (Valkey), and read `CANVAS_CLIENT_SECRET` from KMS (`kms.hanzo.ai`) —
> never from a committed env file.
---
## 3. Canvas REST API
All reads/writes go through `https://{canvas-host}/api/v1/...` with the user's
`Authorization: Bearer {token}`. Canvas's own path is `/api/v1` — this is unrelated
to the Hanzo gateway (which is always `api.hanzo.ai/v1/...`, never `/api/`).
| Resource | Endpoint (relative to `/api/v1`) |
| --- | --- |
| Courses | `GET /courses`, `GET /courses/{id}?include[]=syllabus_body` |
| Assignments | `GET /courses/{id}/assignments`, `GET /courses/{id}/assignments/{id}` |
| Submissions | `GET /courses/{id}/assignments/{aid}/submissions`, `GET …/submissions/{user_id}` |
| **Submission comment** (write) | `PUT /courses/{id}/assignments/{aid}/submissions/{user_id}` — body `{ "comment": { "text_comment": "…" } }` |
| Discussions | `GET /courses/{id}/discussion_topics` |
| **Announcement** (write) | `POST /courses/{id}/discussion_topics` — body `{ "title", "message", "is_announcement": true }` |
| Pages | `GET /courses/{id}/pages`, `GET /courses/{id}/pages/{url_or_id}` |
| Modules | `GET /courses/{id}/modules?include[]=items` |
| Enrollments | `GET /courses/{id}/enrollments` |
> Canvas models a submission comment as an **update to the submission** (a `PUT`
> with `comment[text_comment]`), not a separate comments collection — there is no
> `POST …/submissions/{id}/comments`. This app uses the correct `PUT` shape.
List endpoints paginate with `page` (1-based) + `per_page` (max 100) and return the
page relations in the **RFC 5988 `Link`** response header
(`<…?page=2…>; rel="next"`), parsed by `parseLinkHeader` / `nextPage`.
---
## 4. The summarize-course / draft-feedback flow
1. Connect the app (`/oauth/install`) so the service holds a Canvas token.
2. Open the panel and **Load** a course (the picker lists the courses the connected
user can see). The panel pulls the course's syllabus, modules, assignments,
pages, and discussions through the proxy and assembles a windowed,
truncation-honest context (Canvas HTML is stripped to plain text).
3. **Summarize course** — the model writes a course overview from the syllabus and
module structure, grounded only in the records.
4. **Draft feedback** — pick an assignment and **Load submissions**; the model
drafts specific, constructive feedback for a student submission, grounded in what
the student actually wrote and the assignment's requirements. The result lands in
the Result box.
5. Optional write-backs (gated, behind a confirm):
- **Post as submission comment** posts the Result back via
`PUT …/submissions/{user_id}` with `comment[text_comment]`, targeting the first
submitted student on the loaded assignment.
- **Post as announcement** posts the Result as a course announcement via
`POST …/discussion_topics` (`is_announcement: true`), first line as the subject.
The other actions — **Generate questions** (quiz + discussion prompts from a
page/module), **Summarize submissions** (submitted/missing/late, score spread,
common strengths and problems), and **Draft announcement** — run the same way.
---
## Build & run
```bash
pnpm install
pnpm --filter @hanzo/canvas-lms build # → dist/ (panel + server)
pnpm --filter @hanzo/canvas-lms test # vitest
pnpm --filter @hanzo/canvas-lms typecheck # tsc --noEmit
# run the service
CANVAS_HOST=school.instructure.com \
CANVAS_CLIENT_ID=… \
CANVAS_CLIENT_SECRET=… \
CANVAS_REDIRECT_URI=https://canvas.hanzo.ai/oauth/callback \
node packages/canvas-lms/dist/server.js
```
### Required environment (service)
| Var | Notes |
| --- | --- |
| `CANVAS_HOST` | Institution Canvas host, e.g. `school.instructure.com`. Normalized (scheme/path stripped). |
| `CANVAS_CLIENT_ID` | Developer Key client id (public). |
| `CANVAS_CLIENT_SECRET` | **Server only.** From KMS in production. |
| `CANVAS_REDIRECT_URI` | Must match the key's registered redirect. |
| `PORT` | Listen port (default `8791`). |
`readServerConfig` throws on a missing value — the service refuses to start rather
than pretend it can complete an OAuth exchange or reach an unknown Canvas host.
---
## Deploy over hanzoai/ingress
Host the static panel (`dist/index.html`, `app.js`, `styles.css`) with the
**hanzoai/static** plugin and run `dist/server.js` as a small service, both behind
**hanzoai/ingress** at `canvas.hanzo.ai` (no nginx, no caddy):
- `/` and the static assets → the panel.
- `/oauth/*`, `/proxy/*`, `/healthz` → the service.
Secrets come from **KMS** as `KMSSecret`-synced env; sessions from **Valkey**
(`hanzoai/kv`) for multi-instance. Image published to
`ghcr.io/hanzoai/canvas-lms:<tag>` by CI/CD (platform.hanzo.ai / Tekton) — never
built locally.
---
## Alternative embed path: LTI 1.3
This package ships the **OAuth2 + REST API** app (an external app the instructor
connects, ideal for a standalone panel at `canvas.hanzo.ai`). Canvas also supports
**LTI 1.3 / Advantage** as an in-Canvas launch: Canvas issues a signed OIDC launch
JWT and the tool calls the same REST API (or LTI Advantage services — Names & Roles,
Assignment & Grade Services). LTI is the better fit for a deep in-course placement
(course navigation, assignment menu) and passes the course context (`custom_canvas_course_id`)
in the launch — which `parseLaunchContext` already reads. The AI + context modules
(`course.ts`, `hanzo.ts`, `actions.ts`, `canvas-api.ts`) are transport-agnostic and
would be reused unchanged behind an LTI launch; only the auth front-door differs.
This build ships the OAuth+API app.
---
*Routed through `api.hanzo.ai`. Answers are grounded in your Canvas course records —
a draft for an educator to review, not an authoritative grade, decision, or the
final word to a student.*
+86
View File
@@ -0,0 +1,86 @@
// Build @hanzo/canvas-lms into dist/: bundle the web panel (app.ts) as ESM for the
// browser, copy index.html (with its entry script stamped) + styles.css, and bundle
// the OAuth + API-proxy server for Node. No framework — esbuild + Node stdlib only.
// @hanzo/ai is bundled into both outputs (it is the headless client the panel and
// server both call).
//
// node build.js → production build
// node build.js --watch → rebuild on change
// HANZO_CANVAS_BASE=https://localhost:8443 node build.js → dev base (informational)
//
// Output layout:
// dist/index.html dist/app.js dist/styles.css (panel)
// dist/server.js (service)
//
// The panel is HOSTED over hanzoai/static behind hanzoai/ingress at canvas.hanzo.ai;
// the server runs as a small service (OAuth callback + API proxy). All model calls go
// to api.hanzo.ai regardless of the host base.
import esbuild from 'esbuild';
import { rmSync, mkdirSync, copyFileSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE = (process.env.HANZO_CANVAS_BASE || 'https://canvas.hanzo.ai').replace(/\/+$/, '');
const watch = process.argv.includes('--watch');
const src = join(__dirname, 'src');
const dist = join(__dirname, 'dist');
async function build() {
rmSync(dist, { recursive: true, force: true });
mkdirSync(dist, { recursive: true });
// Bundle the panel as ESM for the browser.
const panelCtx = await esbuild.context({
entryPoints: { app: join(src, 'app.ts') },
outdir: dist,
bundle: true,
format: 'esm',
platform: 'browser',
target: ['chrome90', 'edge90', 'firefox90', 'safari15'],
sourcemap: true,
minify: !watch,
logLevel: 'info',
});
await panelCtx.rebuild();
// Copy index.html (stamp __ENTRY__ + base) and styles.css.
const html = readFileSync(join(src, 'index.html'), 'utf8')
.split('__ENTRY__').join('app.js')
.replace('</head>', ` <meta name="hanzo:base" content="${BASE}" />\n</head>`);
writeFileSync(join(dist, 'index.html'), html);
copyFileSync(join(src, 'styles.css'), join(dist, 'styles.css'));
// Bundle the server as a Node ESM binary — our pure stdlib code + @hanzo/ai.
const serverCtx = await esbuild.context({
entryPoints: [join(src, 'server.ts')],
outfile: join(dist, 'server.js'),
bundle: true,
format: 'esm',
platform: 'node',
target: ['node18'],
sourcemap: true,
minify: !watch,
banner: { js: "import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);" },
logLevel: 'info',
});
await serverCtx.rebuild();
console.log(`Hanzo AI for Canvas built -> dist/ (base ${BASE})`);
console.log(' Panel: dist/index.html · Service: dist/server.js');
if (watch) {
await panelCtx.watch();
await serverCtx.watch();
console.log('watching...');
} else {
await panelCtx.dispose();
await serverCtx.dispose();
}
}
build().catch((e) => {
console.error(e);
process.exit(1);
});
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@hanzo/canvas-lms",
"version": "1.0.0",
"description": "Hanzo AI for Canvas LMS — AI over your course: summarize a course, draft assignment feedback, generate quiz/discussion questions, summarize student submissions, and draft an announcement. An embedded-app panel plus an OAuth + API-proxy service, built on @hanzo/ai and @hanzo/iam over the api.hanzo.ai gateway.",
"type": "module",
"scripts": {
"build": "node build.js",
"watch": "node build.js --watch",
"start": "node dist/server.js",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@hanzo/ai": "^0.2.0",
"@hanzo/iam": "^0.13.2"
},
"devDependencies": {
"@types/node": "^20.14.0",
"esbuild": "^0.25.8",
"typescript": "^5.8.3",
"vitest": "^3.2.6"
},
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"hanzo",
"canvas",
"lms",
"education",
"instructure",
"ai",
"oauth"
],
"author": "Hanzo AI",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/canvas-lms"
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/server.js"
}
+109
View File
@@ -0,0 +1,109 @@
// The AI actions over a Canvas course — summarize the course, draft assignment
// feedback, generate quiz/discussion questions, summarize student submissions, and
// draft an announcement. Each is a prompt template applied to the windowed course
// context via the single `ask` primitive in hanzo.ts. There is exactly ONE code path
// to the model: an action is (id → prompt), and the panel and any server-side caller
// resolve an id here and call `ask`. No action speaks to the gateway directly. (A
// freeform "ask about the course" is `ask` directly, not an action — it has no fixed
// prompt.)
import { ask, type AskOptions, type CourseMeta } from './hanzo.js';
import type { CourseContext } from './course.js';
// The action catalog. `id` is the stable key the panel's chips use; `label` is the
// button text; `prompt` is the instruction handed to the model as the task, over the
// fenced course records. Prompts are specific and output-shaped (bullets, structured
// lists) so results are consistent and parseable.
export const ACTIONS = {
summarizeCourse: {
label: 'Summarize course',
prompt:
'Write a clear overview of this course for a student or a colleague, grounded ' +
'in the syllabus and module structure in these records. Cover: what the course ' +
'is about, how it is organised (the modules and their sequence), the major ' +
'assignments and how grading works if the records say, and any key policies. ' +
'Use a short headline followed by grouped bullets. Base every statement on the ' +
'records; if the syllabus or modules look incomplete, say so plainly.',
},
draftFeedback: {
label: 'Draft feedback',
prompt:
'Draft constructive, specific feedback for the student submission in these ' +
'records, addressed to the student. Ground every point in what the submission ' +
'actually contains and in the assignments stated requirements; do not invent ' +
'content the student did not write or a grade the records do not show. Lead with ' +
'what was done well, then give concrete, actionable suggestions for improvement, ' +
'and close with an encouraging next step. Keep the tone supportive and ' +
'professional. Return only the feedback text, ready to paste as a submission ' +
'comment for the instructor to review.',
},
generateQuestions: {
label: 'Generate questions',
prompt:
'From the course content in these records (a page, module, or assignment), ' +
'generate assessment questions. Produce two groups. First, "Quiz questions": 5 ' +
'to 8 questions that check understanding of the material, a mix of ' +
'multiple-choice (with options and the correct answer marked) and short-answer, ' +
'each tied to a specific idea in the records. Second, "Discussion prompts": 3 ' +
'open-ended prompts that invite analysis or application. Base every question ' +
'strictly on the provided content; do not test material that is not present.',
},
summarizeSubmissions: {
label: 'Summarize submissions',
prompt:
'Summarize the student submissions in these records for the instructor. Cover: ' +
'how many submitted vs are missing or late, the range of scores or grades if the ' +
'records show them, common strengths and common problems across the responses, ' +
'and any submissions that stand out (exemplary or struggling) — referenced by ' +
'user id, not invented names. Structure as a one-line headline followed by ' +
'grouped bullets. Do not fabricate scores or content the records do not contain.',
},
draftAnnouncement: {
label: 'Draft announcement',
prompt:
'Draft a course announcement for the students, grounded in these course records ' +
'(upcoming assignments, due dates, module content). Write a short, clear ' +
'announcement with a specific subject line on the first line, then the body: what ' +
'is happening, what students need to do, and any relevant due date drawn from the ' +
'records. Keep it warm and concise. Do not invent dates or requirements that are ' +
'not in the records. Return the subject line and body, ready for the instructor ' +
'to review and post.',
},
} as const;
// An action id from the catalog.
export type ActionId = keyof typeof ACTIONS;
// isActionId narrows an arbitrary string to a known action id. Boundary guard — the
// panel and the server validate an inbound id here before running it.
export function isActionId(id: string): id is ActionId {
return Object.prototype.hasOwnProperty.call(ACTIONS, id);
}
// actionPrompt resolves an action id to its prompt template. Throws on an unknown id
// (a boundary error, surfaced to the caller) rather than silently running a default.
// Pure.
export function actionPrompt(id: string): string {
if (!isActionId(id)) throw new Error(`Unknown action: ${id}`);
return ACTIONS[id].prompt;
}
// actionList is the ordered catalog for building the UI (chips) — id + label,
// derived from ACTIONS so the panel and the catalog can never drift. Pure.
export function actionList(): Array<{ id: ActionId; label: string }> {
return (Object.keys(ACTIONS) as ActionId[]).map((id) => ({ id, label: ACTIONS[id].label }));
}
// runAction is the single entry point every surface calls: resolve the action's
// prompt and run it over the windowed course context via `ask`. This is the one code
// path from an action id to the model. Async so an unknown id surfaces as a rejected
// promise (not a synchronous throw), giving callers ONE way to handle failure:
// `await`/`.catch`. A gateway error rejects via `ask`.
export async function runAction(
id: string,
ctx: CourseContext,
meta?: CourseMeta,
opts: AskOptions = {},
): Promise<string> {
return ask(actionPrompt(id), ctx, meta, opts);
}
+375
View File
@@ -0,0 +1,375 @@
// The Canvas panel glue: the embedded/linked-app page that opens with a course in
// context and drives the AI actions over the course's live records. All the
// logic-heavy work (action prompts, context windowing, chat shaping, proxy request
// shaping, auth) lives in its own tested modules; this file binds them to the DOM. It
// is the one impure, browser-only entry point.
//
// Data flow: the panel reads Canvas ONLY through the same-origin server proxy
// (createProxyClient), which holds the OAuth token server-side. It pulls the course's
// syllabus / modules / assignments / pages / discussions, assembles a windowed context
// (buildCourseContext), and runs an action or a freeform question against api.hanzo.ai
// with the pasted Hanzo key. The optional write-backs (submission comment, course
// announcement) post back through the same proxy, behind explicit buttons.
import { actionList, isActionId, runAction } from './actions.js';
import { ask as askHanzo, listModels, type CourseMeta } from './hanzo.js';
import {
buildCourseContext,
contextNote,
courseSection,
moduleSection,
assignmentSection,
pageSection,
discussionSection,
submissionSection,
type CourseContext,
type Section,
} from './course.js';
import { DEFAULT_MODEL } from './config.js';
import { getApiKey, setApiKey, hasApiKey, bearer, validateKey } from './auth.js';
import { createProxyClient, parseLaunchContext, type ProxyClient } from './panel.js';
import type { Course, Assignment, Submission } from './canvas-api.js';
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
let controller: AbortController | null = null;
window.addEventListener('DOMContentLoaded', () => {
const launch = parseLaunchContext(window.location.search);
const courseEl = $<HTMLSelectElement>('course');
const assignmentEl = $<HTMLSelectElement>('assignment');
const loadBtn = $<HTMLButtonElement>('load');
const loadSubsBtn = $<HTMLButtonElement>('loadsubs');
const recordsEl = $('records');
const outputEl = $<HTMLTextAreaElement>('output');
const statusEl = $('status');
const modelEl = $<HTMLSelectElement>('model');
const chipRow = $('chips');
const runBtn = $<HTMLButtonElement>('run');
const stopBtn = $<HTMLButtonElement>('stop');
const promptEl = $<HTMLTextAreaElement>('prompt');
const apiKeyEl = $<HTMLInputElement>('apikey');
const saveKeyBtn = $<HTMLButtonElement>('savekey');
const authHint = $('authhint');
const commentBtn = $<HTMLButtonElement>('comment');
const announceBtn = $<HTMLButtonElement>('announce');
apiKeyEl.value = getApiKey();
reflectAuth();
void populateModels();
void populateCourses();
const client: ProxyClient = createProxyClient();
// Loaded state: the course-overview sections, the loaded submissions (a separate
// section appended on demand), and the ids the write-backs target.
let overview: Section[] = [];
let submissions: Submission[] = [];
let ctx: CourseContext | null = null;
let meta: CourseMeta = {};
let currentCourseId = '';
let currentAssignmentId = '';
let assignments: Assignment[] = [];
// Action chips — derived from the catalog so UI and logic never drift.
for (const a of actionList()) {
const b = document.createElement('button');
b.className = 'chip';
b.textContent = a.label;
b.dataset.action = a.id;
b.onclick = () => void run(a.id);
chipRow.appendChild(b);
}
loadBtn.onclick = () => void loadCourse();
loadSubsBtn.onclick = () => void loadSubmissions();
courseEl.onchange = () => {
currentCourseId = courseEl.value;
};
assignmentEl.onchange = () => {
currentAssignmentId = assignmentEl.value;
};
runBtn.onclick = () => {
const prompt = promptEl.value.trim();
if (prompt) void ask(prompt);
};
stopBtn.onclick = () => controller?.abort();
commentBtn.onclick = () => void postComment();
announceBtn.onclick = () => void postAnnouncement();
saveKeyBtn.onclick = async () => {
const key = apiKeyEl.value.trim();
setStatus('Checking key…');
try {
const models = await validateKey(key);
setApiKey(key);
fillModels(models);
reflectAuth();
setStatus('Key saved.', 'ok');
} catch (e: any) {
setStatus(e?.message || 'Key rejected.', 'error');
}
};
// If we launched already scoped to a course, load it straight away.
if (launch.courseId) {
void populateCourses().then(() => {
courseEl.value = launch.courseId;
currentCourseId = launch.courseId;
void loadCourse();
});
}
// populateCourses fills the course picker from the proxy. An auth failure leaves the
// picker empty with a status hint pointing at the connect flow.
async function populateCourses(): Promise<void> {
setStatus('Loading courses…');
try {
const { items } = await client.listCourses({ perPage: 100 });
fillCourses(items);
setStatus(
items.length ? `Loaded ${items.length} courses.` : 'No courses visible.',
items.length ? 'ok' : 'warn',
);
} catch (e: any) {
setStatus(
e?.message || 'Could not load courses — is the app connected? (Connect on canvas.hanzo.ai)',
'error',
);
}
}
// loadCourse pulls the scoped course's records and assembles the overview context
// the actions run over. The course/syllabus, modules, assignments, pages, and
// discussions are fetched in parallel; each failure is tolerated so a course missing
// one area still yields a usable context.
async function loadCourse(): Promise<void> {
const courseId = courseEl.value || currentCourseId;
if (!courseId) {
setStatus('Pick a course first.', 'warn');
return;
}
currentCourseId = courseId;
setStatus('Loading course records…');
const [course, modules, assigns, pages, discussions] = await Promise.all([
client.getCourse(courseId).catch(() => null),
client.listModules(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
client.listAssignments(courseId, { perPage: 100 }).then((r) => r.items).catch(() => [] as Assignment[]),
client.listPages(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
client.listDiscussions(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
]);
assignments = assigns;
submissions = [];
fillAssignments(assigns);
overview = [
...(course ? [courseSection(course)] : []),
moduleSection(modules),
assignmentSection(assigns),
pageSection(pages),
discussionSection(discussions),
];
meta = course ? courseMetaOf(course) : {};
rebuildContext();
recordsEl.textContent =
`${modules.length} modules · ${assigns.length} assignments · ${pages.length} pages · ${discussions.length} discussions`;
announceBtn.disabled = false;
announceBtn.title = 'Post the result as a course announcement';
loadSubsBtn.disabled = assigns.length === 0;
setStatus(contextNote(ctx!));
}
// loadSubmissions pulls the selected assignment's submissions and appends them to the
// context so the feedback / summarize-submissions actions have student work. Enables
// the submission-comment write-back against the first submission.
async function loadSubmissions(): Promise<void> {
const assignmentId = assignmentEl.value || currentAssignmentId;
if (!currentCourseId || !assignmentId) {
setStatus('Load a course and pick an assignment first.', 'warn');
return;
}
currentAssignmentId = assignmentId;
setBusy(true);
setStatus('Loading submissions…');
try {
const { items } = await client.listSubmissions(currentCourseId, assignmentId, { perPage: 100 });
submissions = items;
rebuildContext();
const withWork = submissions.filter((s) => s.workflowState && s.workflowState !== 'unsubmitted');
commentBtn.disabled = withWork.length === 0;
commentBtn.title = withWork.length
? `Post the result as a comment on user ${withWork[0].userId}'s submission`
: 'No submitted work to comment on';
recordsEl.textContent += ` · ${submissions.length} submissions`;
setStatus(contextNote(ctx!));
} catch (e: any) {
setStatus(e?.message || 'Could not load submissions.', 'error');
} finally {
setBusy(false);
}
}
// rebuildContext re-windows the overview + any loaded submissions into one context.
function rebuildContext(): void {
ctx = buildCourseContext([...overview, ...(submissions.length ? [submissionSection(submissions)] : [])]);
}
// run executes one of the named actions over the loaded course context.
async function run(actionId: string): Promise<void> {
if (!isActionId(actionId)) return;
await execute((c, m, opts) => runAction(actionId, c, m, opts));
}
// ask executes a freeform question over the loaded course context.
async function ask(prompt: string): Promise<void> {
await execute((c, m, opts) => askHanzo(prompt, c, m, opts));
}
// execute is the shared runner: require a loaded context, call the model, show the
// result. Both the chips and freeform ask funnel through here (one path).
async function execute(
call: (
c: CourseContext,
m: CourseMeta,
opts: { token: string; model: string; signal: AbortSignal },
) => Promise<string>,
): Promise<void> {
if (!ctx || ctx.totalBlocks === 0) {
setStatus('Load a course first (pick one and press Load).', 'warn');
return;
}
controller?.abort();
controller = new AbortController();
setBusy(true);
setStatus(contextNote(ctx));
outputEl.value = '';
try {
const text = await call(ctx, meta, {
token: bearer(),
model: modelEl.value || DEFAULT_MODEL,
signal: controller.signal,
});
outputEl.value = text;
setStatus('Done.', 'ok');
} catch (e: any) {
if (e?.name === 'AbortError') setStatus('Stopped.');
else setStatus(e?.message || 'Request failed.', 'error');
} finally {
setBusy(false);
}
}
// postComment writes the current output back to Canvas as a comment on the first
// submitted student's submission — an explicit, documented write-back. Guarded: it
// never posts an empty body and always confirms who it targeted.
async function postComment(): Promise<void> {
const body = outputEl.value.trim();
const target = submissions.find((s) => s.workflowState && s.workflowState !== 'unsubmitted');
if (!target) return setStatus('No submitted work to comment on.', 'warn');
if (!body) return setStatus('Nothing to post — run an action or write feedback first.', 'warn');
if (!confirm(`Post this as a comment on user ${target.userId}'s submission?`)) return;
setBusy(true);
setStatus('Posting comment to Canvas…');
try {
await client.postSubmissionComment(currentCourseId, currentAssignmentId, target.userId, body);
setStatus(`Comment posted on user ${target.userId}'s submission.`, 'ok');
} catch (e: any) {
setStatus(e?.message || 'Comment failed.', 'error');
} finally {
setBusy(false);
}
}
// postAnnouncement writes the current output back as a course announcement. Canvas
// needs a title + body; we take the first line of the result as the title and the
// rest as the body, so a "subject line then body" draft posts cleanly.
async function postAnnouncement(): Promise<void> {
const text = outputEl.value.trim();
if (!currentCourseId) return setStatus('Load a course first.', 'warn');
if (!text) return setStatus('Nothing to post — draft an announcement first.', 'warn');
const nl = text.indexOf('\n');
const title = (nl === -1 ? text : text.slice(0, nl)).trim().slice(0, 200);
const message = (nl === -1 ? text : text.slice(nl + 1)).trim() || text;
if (!confirm(`Post a course announcement titled “${title}”?`)) return;
setBusy(true);
setStatus('Posting announcement to Canvas…');
try {
await client.createAnnouncement(currentCourseId, title, message);
setStatus('Announcement posted.', 'ok');
} catch (e: any) {
setStatus(e?.message || 'Announcement failed.', 'error');
} finally {
setBusy(false);
}
}
// ---- small DOM helpers ----------------------------------------------------
let courses: Course[] = [];
function courseMetaOf(course: Course): CourseMeta {
return { name: course.name || undefined, courseCode: course.courseCode || undefined, term: course.termName || undefined };
}
function fillCourses(items: Course[]): void {
courses = items;
courseEl.innerHTML = '';
for (const c of items) {
const opt = document.createElement('option');
opt.value = String(c.id);
opt.textContent = c.name || c.courseCode || `Course ${c.id}`;
courseEl.appendChild(opt);
}
if (items.length && !currentCourseId) currentCourseId = String(items[0].id);
}
function fillAssignments(items: Assignment[]): void {
assignmentEl.innerHTML = '';
for (const a of items) {
const opt = document.createElement('option');
opt.value = String(a.id);
opt.textContent = a.name || `Assignment ${a.id}`;
assignmentEl.appendChild(opt);
}
currentAssignmentId = items.length ? String(items[0].id) : '';
}
async function populateModels(): Promise<void> {
try {
fillModels(await listModels({ token: bearer() }));
} catch {
fillModels([DEFAULT_MODEL]);
}
}
function fillModels(ids: string[]): void {
const list = ids.length ? ids : [DEFAULT_MODEL];
modelEl.innerHTML = '';
for (const id of list) {
const opt = document.createElement('option');
opt.value = id;
opt.textContent = id;
modelEl.appendChild(opt);
}
if (list.includes(DEFAULT_MODEL)) modelEl.value = DEFAULT_MODEL;
}
function reflectAuth(): void {
authHint.textContent = hasApiKey()
? 'Using your saved Hanzo key.'
: 'No key saved — using public models. Paste an hk-… key for your org models.';
}
function setBusy(b: boolean): void {
runBtn.disabled = b;
stopBtn.disabled = !b;
loadBtn.disabled = b;
loadSubsBtn.disabled = b || assignments.length === 0;
for (const c of Array.from(chipRow.querySelectorAll('button'))) (c as HTMLButtonElement).disabled = b;
announceBtn.disabled = b || !currentCourseId;
commentBtn.disabled = b || submissions.length === 0;
}
function setStatus(msg: string, kind: '' | 'ok' | 'warn' | 'error' = ''): void {
statusEl.textContent = msg;
statusEl.className = `status${kind ? ' ' + kind : ''}`;
}
});
+55
View File
@@ -0,0 +1,55 @@
// Auth for the web panel: the zero-setup pasted-key path for the Hanzo gateway. The
// Canvas panel is a static web page (iframe), so the Hanzo credential lives in
// localStorage and is validated by a real /v1/models call — a key that can't list
// models is rejected before it's saved, so the user learns at paste time, not at
// first action. Mirrors @hanzo/procore exactly (one way to hold a key).
//
// The Canvas access token (for reading courses/assignments/submissions) is a SEPARATE
// credential minted server-side by the OAuth flow and held by server.ts; the panel
// reaches Canvas only through the server proxy (with its session cookie), so it never
// holds the Canvas token or secret. This module is only the Hanzo-gateway bearer.
import { APIKEY_STORAGE_KEY, pickBearer } from './config.js';
import { listModels } from './hanzo.js';
export function getApiKey(): string {
try {
return localStorage.getItem(APIKEY_STORAGE_KEY) || '';
} catch {
return '';
}
}
export function setApiKey(key: string): void {
try {
const k = key.trim();
if (k) localStorage.setItem(APIKEY_STORAGE_KEY, k);
else localStorage.removeItem(APIKEY_STORAGE_KEY);
} catch {
/* private-mode / storage disabled — the in-memory key still works this session */
}
}
export function clearApiKey(): void {
setApiKey('');
}
export function hasApiKey(): boolean {
return !!getApiKey();
}
// bearer is the credential the chat call sends: the pasted key (or empty for
// anonymous public models). When Hanzo OAuth lands it slots in as the second argument
// to pickBearer with no change to callers.
export function bearer(): string {
return pickBearer(getApiKey(), '');
}
// validateKey confirms a pasted key actually works by listing models with it. Returns
// the models on success so the caller populates the picker in one round-trip; throws
// with the gateway's message on failure.
export async function validateKey(key: string): Promise<string[]> {
const k = key.trim();
if (!k) throw new Error('Enter a Hanzo API key (hk-…).');
return listModels({ token: k });
}
+582
View File
@@ -0,0 +1,582 @@
// Canvas REST API v1 — pure request shaping + response parsing. Every function
// returns a PreparedRequest (url + headers [+ body]) or parses a response body;
// none opens a socket, so the whole API surface is unit-testable without a
// network. server.ts is the thin glue that fetches these shapes with the OAuth
// Bearer access token.
//
// The REST root is `https://{host}/api/v1` (see config.apiBaseUrl). Canvas scopes
// reads/writes by the authorizing user's Bearer token; course-scoped resources
// take the course id in the path (…/courses/{id}/…). Docs:
// canvas.instructure.com/doc/api/courses.html, assignments.html, submissions.html,
// discussion_topics.html, pages.html, modules.html, enrollments.html.
// A prepared GET: url + headers a single fetch needs (Bearer only).
export interface PreparedGet {
url: string;
headers: Record<string, string>;
}
// A prepared write (POST/PUT): adds the JSON body and Content-Type. Canvas accepts
// a JSON body (Content-Type: application/json) for these endpoints; we use it so
// nested params stay structured rather than form-bracket-encoded.
export interface PreparedWrite extends PreparedGet {
method: 'POST' | 'PUT';
body: string;
}
// headers builds the auth header set common to every request.
function headers(accessToken: string): Record<string, string> {
return { Authorization: `Bearer ${accessToken}` };
}
// jsonHeaders adds Content-Type for a write body on top of the auth header.
function jsonHeaders(accessToken: string): Record<string, string> {
return { ...headers(accessToken), 'Content-Type': 'application/json' };
}
// The scope every request carries: which REST root and which bearer. Grouping them
// keeps every wrapper's signature small.
export interface Scope {
apiBase: string;
accessToken: string;
}
// Pagination controls. Canvas paginates with page (1-based) + per_page and returns
// the page relations (next/prev/first/last) in the RFC 5988 `Link` response header
// (parsed by the caller with parseLinkHeader). We attach these as query params on
// list endpoints.
export interface Page {
page?: number;
perPage?: number;
}
// DEFAULT_PER_PAGE is Canvas's documented maximum page size; 100 minimises
// round-trips (Canvas's own default is only 10).
export const DEFAULT_PER_PAGE = 100;
// pageParams renders pagination into query pairs, clamping per_page to the
// documented maximum. Only emits params that are set, so an unpaginated call stays
// clean. Pure — unit-tested.
export function pageParams(page: Page | undefined): Record<string, string> {
const out: Record<string, string> = {};
if (!page) return out;
if (typeof page.page === 'number' && page.page > 0) out.page = String(Math.floor(page.page));
if (typeof page.perPage === 'number' && page.perPage > 0) {
out.per_page = String(Math.min(Math.floor(page.perPage), DEFAULT_PER_PAGE));
}
return out;
}
// A repeated query param, e.g. Canvas's `include[]=syllabus_body`. buildUrl expands
// an array value into one pair per element with a trailing `[]` on the key.
type Query = Record<string, string | string[] | undefined>;
// buildUrl joins the REST root + path and appends a query string, dropping
// undefined/empty values and expanding arrays into Canvas's `key[]=v` repetition.
// One place builds every URL so scoping/pagination params are applied
// consistently. Pure.
function buildUrl(apiBase: string, path: string, query: Query = {}): string {
const base = `${apiBase.replace(/\/+$/, '')}${path}`;
const q = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) {
for (const item of v) if (item !== undefined && item !== '') q.append(`${k}[]`, item);
} else if (v !== undefined && v !== '') {
q.set(k, v);
}
}
const qs = q.toString();
return qs ? `${base}?${qs}` : base;
}
// enc encodes a single path segment (ids are integers and page urls are slugs, but
// we encode defensively so a stray value can never break — or traverse — the path).
function enc(segment: number | string): string {
return encodeURIComponent(String(segment));
}
// ---- Courses --------------------------------------------------------------
// listCourses — the courses the authorizing user can see. Bearer scope only (no
// course in the path). The panel's picker uses this to choose which course to run
// against.
export function listCourses(scope: Scope, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, '/courses', pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getCourse — one course. `includes` maps to Canvas `include[]` associations; we
// default to `syllabus_body` (an HTML syllabus) since the summarize-course action
// grounds on it. Pass `[]` to fetch the bare course.
export function getCourse(
scope: Scope,
courseId: number | string,
includes: readonly string[] = ['syllabus_body'],
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}`, {
include: includes.length ? [...includes] : undefined,
}),
headers: headers(scope.accessToken),
};
}
// ---- Assignments ----------------------------------------------------------
// listAssignments — the assignments in a course. Course-scoped path.
export function listAssignments(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/assignments`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getAssignment — one assignment in full (description, due date, points, submission
// types). This is what the feedback/question actions read.
export function getAssignment(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/assignments/${enc(assignmentId)}`),
headers: headers(scope.accessToken),
};
}
// ---- Submissions ----------------------------------------------------------
// listSubmissions — the submissions for an assignment. Course + assignment scoped
// path; `include[]=submission_comments` so existing comments come along for the
// summarize/feedback context.
export function listSubmissions(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
page?: Page,
): PreparedGet {
return {
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions`,
{ include: ['submission_comments'], ...pageParams(page) },
),
headers: headers(scope.accessToken),
};
}
// getSubmission — one student's submission (by user id) with its comment thread.
export function getSubmission(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
userId: number | string,
): PreparedGet {
return {
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
{ include: ['submission_comments'] },
),
headers: headers(scope.accessToken),
};
}
// postSubmissionComment — add a text comment to a student's submission. Canvas
// models a submission comment as an UPDATE to the submission (PUT
// …/submissions/{user_id} with a `comment[text_comment]`), not a separate comments
// collection — this is the ONE feedback write path, behind an explicit action.
// Returns a PreparedWrite (PUT + JSON body).
export function postSubmissionComment(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
userId: number | string,
text: string,
): PreparedWrite {
return {
method: 'PUT',
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
),
headers: jsonHeaders(scope.accessToken),
body: JSON.stringify({ comment: { text_comment: text } }),
};
}
// ---- Discussions ----------------------------------------------------------
// listDiscussions — the discussion topics in a course (announcements included when
// they are discussion-backed). Course-scoped path.
export function listDiscussions(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/discussion_topics`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// createAnnouncement — post a course announcement. In Canvas an announcement is a
// discussion topic with `is_announcement: true` (POST …/discussion_topics) — the
// second gated write path. Returns a PreparedWrite (POST + JSON body).
export function createAnnouncement(
scope: Scope,
courseId: number | string,
title: string,
message: string,
): PreparedWrite {
return {
method: 'POST',
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/discussion_topics`),
headers: jsonHeaders(scope.accessToken),
body: JSON.stringify({ title, message, is_announcement: true }),
};
}
// ---- Pages ----------------------------------------------------------------
// listPages — the wiki pages in a course. Course-scoped path.
export function listPages(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/pages`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getPage — one wiki page in full (its HTML body). Canvas addresses a page by its
// url slug or page id.
export function getPage(
scope: Scope,
courseId: number | string,
urlOrId: number | string,
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/pages/${enc(urlOrId)}`),
headers: headers(scope.accessToken),
};
}
// ---- Modules --------------------------------------------------------------
// listModules — the modules in a course, with their items inlined
// (`include[]=items`) so the course-overview context sees the module structure.
export function listModules(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/modules`, {
include: ['items'],
...pageParams(page),
}),
headers: headers(scope.accessToken),
};
}
// ---- Enrollments ----------------------------------------------------------
// listEnrollments — the enrollments in a course (who is a student / teacher / TA).
export function listEnrollments(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/enrollments`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// ---- Pagination header (RFC 5988 Link) ------------------------------------
// The page relations Canvas returns in the `Link` header — each an absolute URL.
export interface CanvasLinks {
current?: string;
next?: string;
prev?: string;
first?: string;
last?: string;
}
// parseLinkHeader reads Canvas's RFC 5988 `Link` header into the page relations.
// Canvas returns entries like `<https://host/api/v1/courses?page=2&per_page=100>;
// rel="next"`. Accepts a Headers instance or a plain header map so it works against
// fetch Responses and test fixtures alike. Returns {} for a missing header. Pure.
export function parseLinkHeader(
h: Headers | Record<string, string | string[] | undefined>,
): CanvasLinks {
const raw =
typeof (h as Headers)?.get === 'function'
? (h as Headers).get('Link') ?? (h as Headers).get('link')
: (h as Record<string, string | string[] | undefined>).Link ??
(h as Record<string, string | string[] | undefined>).link;
const val = Array.isArray(raw) ? raw.join(', ') : raw;
const links: CanvasLinks = {};
if (!val) return links;
for (const part of String(val).split(',')) {
const m = part.match(/<([^>]+)>\s*;\s*rel="?([^"\s;]+)"?/i);
if (!m) continue;
const rel = m[2].toLowerCase();
if (rel === 'current' || rel === 'next' || rel === 'prev' || rel === 'first' || rel === 'last') {
links[rel] = m[1];
}
}
return links;
}
// pageOfUrl extracts the 1-based `page` query param from a Canvas pagination URL
// (the relations in parseLinkHeader carry absolute URLs). Returns undefined when
// absent/unparseable. Pure — lets a same-origin proxy client re-request the next
// page by number without following Canvas's absolute URL directly.
export function pageOfUrl(url: string | undefined): number | undefined {
if (!url) return undefined;
const m = url.match(/[?&]page=([^&]+)/);
if (!m) return undefined;
const n = Number.parseInt(decodeURIComponent(m[1]), 10);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
// nextPage is the page number to request for the next page, or undefined when
// there is no `next` relation (the last page). Pure — the ONE way the panel decides
// whether to keep paginating.
export function nextPage(links: CanvasLinks): number | undefined {
return pageOfUrl(links.next);
}
// ---- Response parsing -----------------------------------------------------
//
// Canvas list endpoints return a bare JSON array of records; detail endpoints
// return one object. We normalize the snake_case wire fields we surface into small
// typed shapes at this boundary so nothing downstream touches the wire. Text bodies
// (syllabus, page body, assignment description, discussion message) are Canvas HTML;
// we keep them raw here and strip to plain text in course.ts (htmlToText) at render.
function arrayOf(data: any, key?: string): any[] {
if (Array.isArray(data)) return data;
if (key && Array.isArray(data?.[key])) return data[key];
return [];
}
// One course as it appears in listCourses / getCourse.
export interface Course {
id: number;
name: string;
courseCode: string;
workflowState: string;
syllabusBody: string;
termName: string;
}
export function parseCourse(data: any): Course {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
courseCode: String(data?.course_code ?? ''),
workflowState: String(data?.workflow_state ?? ''),
syllabusBody: String(data?.syllabus_body ?? ''),
termName: String(data?.term?.name ?? data?.enrollment_term_id ?? ''),
};
}
export function parseCourses(data: any): Course[] {
return arrayOf(data, 'courses')
.map(parseCourse)
.filter((c) => c.id > 0);
}
// One assignment.
export interface Assignment {
id: number;
name: string;
description: string;
dueAt: string;
pointsPossible: number;
submissionTypes: string[];
}
export function parseAssignment(data: any): Assignment {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
description: String(data?.description ?? ''),
dueAt: String(data?.due_at ?? ''),
pointsPossible: Number(data?.points_possible ?? 0),
submissionTypes: Array.isArray(data?.submission_types)
? data.submission_types.map((s: any) => String(s))
: [],
};
}
export function parseAssignments(data: any): Assignment[] {
return arrayOf(data, 'assignments')
.map(parseAssignment)
.filter((a) => a.id > 0);
}
// One comment within a submission's thread.
export interface SubmissionComment {
id: number;
authorName: string;
comment: string;
createdAt: string;
}
function parseSubmissionComment(c: any): SubmissionComment {
return {
id: Number(c?.id ?? 0),
authorName: String(c?.author_name ?? c?.author?.display_name ?? ''),
comment: String(c?.comment ?? ''),
createdAt: String(c?.created_at ?? ''),
};
}
// One student submission.
export interface Submission {
id: number;
userId: number;
assignmentId: number;
body: string;
submittedAt: string;
workflowState: string;
score: number | null;
grade: string;
late: boolean;
missing: boolean;
comments: SubmissionComment[];
}
export function parseSubmission(data: any): Submission {
return {
id: Number(data?.id ?? 0),
userId: Number(data?.user_id ?? 0),
assignmentId: Number(data?.assignment_id ?? 0),
body: String(data?.body ?? ''),
submittedAt: String(data?.submitted_at ?? ''),
workflowState: String(data?.workflow_state ?? ''),
score: typeof data?.score === 'number' ? data.score : null,
grade: data?.grade === null || data?.grade === undefined ? '' : String(data.grade),
late: data?.late === true,
missing: data?.missing === true,
comments: Array.isArray(data?.submission_comments)
? data.submission_comments.map(parseSubmissionComment)
: [],
};
}
export function parseSubmissions(data: any): Submission[] {
return arrayOf(data, 'submissions')
.map(parseSubmission)
.filter((s) => s.id > 0 || s.userId > 0);
}
// One discussion topic.
export interface Discussion {
id: number;
title: string;
message: string;
postedAt: string;
isAnnouncement: boolean;
}
export function parseDiscussion(data: any): Discussion {
return {
id: Number(data?.id ?? 0),
title: String(data?.title ?? ''),
message: String(data?.message ?? ''),
postedAt: String(data?.posted_at ?? ''),
isAnnouncement: data?.is_announcement === true,
};
}
export function parseDiscussions(data: any): Discussion[] {
return arrayOf(data, 'discussion_topics')
.map(parseDiscussion)
.filter((d) => d.id > 0);
}
// One wiki page. The list omits the body; the detail (getPage) carries it.
export interface Page_ {
pageId: number;
url: string;
title: string;
body: string;
updatedAt: string;
}
export function parsePage(data: any): Page_ {
return {
pageId: Number(data?.page_id ?? 0),
url: String(data?.url ?? ''),
title: String(data?.title ?? ''),
body: String(data?.body ?? ''),
updatedAt: String(data?.updated_at ?? ''),
};
}
export function parsePages(data: any): Page_[] {
return arrayOf(data, 'pages')
.map(parsePage)
.filter((p) => p.pageId > 0 || p.url.length > 0);
}
// One module item (a page, assignment, quiz, file, external link, …).
export interface ModuleItem {
id: number;
title: string;
type: string;
position: number;
}
// One course module, with its items when Canvas inlined them.
export interface Module {
id: number;
name: string;
position: number;
items: ModuleItem[];
}
function parseModuleItem(i: any): ModuleItem {
return {
id: Number(i?.id ?? 0),
title: String(i?.title ?? ''),
type: String(i?.type ?? ''),
position: Number(i?.position ?? 0),
};
}
export function parseModule(data: any): Module {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
position: Number(data?.position ?? 0),
items: Array.isArray(data?.items) ? data.items.map(parseModuleItem) : [],
};
}
export function parseModules(data: any): Module[] {
return arrayOf(data, 'modules')
.map(parseModule)
.filter((m) => m.id > 0);
}
// One enrollment (a person's role in the course).
export interface Enrollment {
id: number;
userId: number;
userName: string;
type: string;
role: string;
state: string;
}
export function parseEnrollment(data: any): Enrollment {
return {
id: Number(data?.id ?? 0),
userId: Number(data?.user_id ?? 0),
userName: String(data?.user?.name ?? data?.user?.short_name ?? ''),
type: String(data?.type ?? ''),
role: String(data?.role ?? ''),
state: String(data?.enrollment_state ?? ''),
};
}
export function parseEnrollments(data: any): Enrollment[] {
return arrayOf(data, 'enrollments')
.map(parseEnrollment)
.filter((e) => e.id > 0);
}
+167
View File
@@ -0,0 +1,167 @@
// Canvas OAuth 2.0 (Authorization Code Grant) — pure request shaping. The client
// secret is held by the server (server.ts) and never reaches the browser; these
// functions build the exact URL/body of each OAuth call so the wire shape is
// unit-testable without a network round-trip. The token exchange and refresh are
// each one fetch in the server.
//
// Canvas uses form-encoded bodies with client_id + client_secret IN THE BODY (not
// HTTP Basic) and requires the redirect_uri on the code exchange — the standard
// OAuth2 web-server shape, documented at
// canvas.instructure.com/doc/api/file.oauth_endpoints.html. The login host is the
// institution's own Canvas host (see config.authBase): authorize at
// /login/oauth2/auth, token at /login/oauth2/token.
import { authBase } from './config.js';
// authorizeUrl is where the install flow sends the user's browser to grant the
// app. `state` is the CSRF token the server generates and re-checks on callback.
// Canvas's Authorization Code grant takes response_type=code + client_id +
// redirect_uri + state; scope is optional (only enforced when the Developer Key
// enables scope enforcement), so it is only appended when non-empty.
export function authorizeUrl(args: {
host: string;
clientId: string;
redirectUri: string;
scopes?: readonly string[];
state: string;
}): string {
const params: Record<string, string> = {
client_id: args.clientId,
response_type: 'code',
redirect_uri: args.redirectUri,
state: args.state,
};
if (args.scopes && args.scopes.length > 0) params.scope = args.scopes.join(' ');
const q = new URLSearchParams(params);
return `${authBase(args.host)}/login/oauth2/auth?${q.toString()}`;
}
// A prepared HTTP request: the pieces a single fetch needs. Pure output so a test
// asserts the form body without opening a socket. Canvas's token endpoint takes
// application/x-www-form-urlencoded.
export interface PreparedRequest {
url: string;
headers: Record<string, string>;
body: string;
}
// tokenUrl is the OAuth token endpoint for a host.
export function tokenUrl(host: string): string {
return `${authBase(host)}/login/oauth2/token`;
}
// tokenExchange builds the code→token request against the host's
// /login/oauth2/token. grant_type=authorization_code with the code, the key's
// credentials, and the SAME redirect_uri that was used on /login/oauth2/auth
// (Canvas requires it to match). The secret rides only in this server-side body.
export function tokenExchange(args: {
host: string;
clientId: string;
clientSecret: string;
code: string;
redirectUri: string;
}): PreparedRequest {
return {
url: tokenUrl(args.host),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: args.clientId,
client_secret: args.clientSecret,
redirect_uri: args.redirectUri,
code: args.code,
}).toString(),
};
}
// refreshExchange builds the refresh-token→token request. Canvas access tokens are
// short-lived (~1h); a refresh returns a fresh access_token but — unlike Procore —
// Canvas does NOT rotate the refresh token (it returns none), so the server keeps
// the original refresh token. No redirect_uri on refresh.
export function refreshExchange(args: {
host: string;
clientId: string;
clientSecret: string;
refreshToken: string;
}): PreparedRequest {
return {
url: tokenUrl(args.host),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: args.clientId,
client_secret: args.clientSecret,
refresh_token: args.refreshToken,
}).toString(),
};
}
// The Canvas person sub-object returned alongside a token (the authorizing user).
export interface CanvasUser {
id: number;
name: string;
}
// The token response we care about. Canvas returns access_token (+ token_type,
// user, expires_in, and refresh_token ONLY on the initial code exchange).
// parseTokenResponse validates the one field we must have and surfaces Canvas's
// own error otherwise.
export interface CanvasTokenSet {
access_token: string;
refresh_token?: string;
expires_in?: number;
token_type?: string;
user?: CanvasUser;
}
export function parseTokenResponse(data: any): CanvasTokenSet {
if (!data || typeof data !== 'object') throw new Error('empty token response');
if (data.error) {
const reason = data.error_description || data.message || data.error;
throw new Error(`Canvas OAuth error: ${reason}`);
}
if (typeof data.access_token !== 'string' || data.access_token.length === 0) {
throw new Error('Canvas OAuth response missing access_token');
}
const user =
data.user && typeof data.user === 'object'
? { id: Number(data.user.id ?? 0), name: String(data.user.name ?? '') }
: undefined;
return {
access_token: data.access_token,
refresh_token: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
expires_in: typeof data.expires_in === 'number' ? data.expires_in : undefined,
token_type: typeof data.token_type === 'string' ? data.token_type : undefined,
user,
};
}
// carryRefreshToken applies Canvas's non-rotating refresh semantics: a refresh
// response omits the refresh token, so the new token set inherits the previous
// refresh token. Pure — the server calls this after every refresh so the session
// never loses the ability to refresh again.
export function carryRefreshToken(next: CanvasTokenSet, previous: CanvasTokenSet): CanvasTokenSet {
return next.refresh_token ? next : { ...next, refresh_token: previous.refresh_token };
}
// tokenExpiresAt computes the absolute epoch-seconds expiry from a token set and
// the wall-clock second it was minted, applying a safety skew so a request is never
// sent with a token about to expire mid-flight. Canvas does not return a mint
// timestamp, so the caller supplies `mintedAt` (recorded when the token was
// stored). Pure.
export function tokenExpiresAt(token: CanvasTokenSet, mintedAt: number, skewSeconds = 60): number {
const ttl = typeof token.expires_in === 'number' ? token.expires_in : 0;
return mintedAt + ttl - skewSeconds;
}
// isExpired reports whether a token set is at/past its (skew-adjusted) expiry as of
// `now`, given when it was minted. The server checks this before each API call and
// refreshes when true. Pure.
export function isExpired(
token: CanvasTokenSet,
mintedAt: number,
now: number,
skewSeconds = 60,
): boolean {
return now >= tokenExpiresAt(token, mintedAt, skewSeconds);
}
+166
View File
@@ -0,0 +1,166 @@
// Canvas LMS config — the institution's Canvas host, the Canvas REST API version
// segment, the api.hanzo.ai model gateway, and the server-side secret set (Canvas
// OAuth). Endpoints and the bearer choice mirror @hanzo/procore and @hanzo/docusign
// so the productivity suite stays DRY; the education-specific pieces
// (course-context windowing, the AI actions) live in course.ts / hanzo.ts /
// actions.ts, not here.
// ---- Hanzo model gateway --------------------------------------------------
// Where the Hanzo model gateway lives. `@hanzo/ai` defaults here too. /v1 only,
// never an /api/ prefix (api.hanzo.ai IS the api host).
export const HANZO_API_BASE_URL = 'https://api.hanzo.ai';
// Default model. A Zen model (qwen3+). Overridable per-request via the picker;
// the gateway routes it.
export const DEFAULT_MODEL = 'zen5';
// Public IAM origin that mints Hanzo user tokens, and the OAuth client id an
// inbound Hanzo token is audienced to (owner-scoping validation via @hanzo/iam).
export const DEFAULT_IAM_SERVER_URL = 'https://hanzo.id';
export const DEFAULT_IAM_CLIENT_ID = 'hanzo-canvas';
// localStorage key for the pasted Hanzo API key (`hk-…`) in the web panel. The
// panel is a static web page (iframe), not a host with roamingSettings, so the
// zero-setup credential lives in localStorage — same as @hanzo/procore.
export const APIKEY_STORAGE_KEY = 'hanzo.canvas.apiKey';
// Course text budget. A busy course has many assignments, pages, discussions, and
// submissions; the whole corpus won't fit a model window and shouldn't be sent.
// This caps the characters of course text we attach to any one request — chosen so
// it fits comfortably inside a modern context window alongside the reply, and is
// honest rather than optimal (we truncate visibly, never drop silently).
export const COURSE_CHAR_BUDGET = 60_000;
// pickBearer chooses the credential to send to the Hanzo gateway: a pasted API key
// wins over an OAuth token (an explicit key is a deliberate override), else the
// token, else empty (anonymous — the gateway still serves public models). Pure —
// unit-tested.
export function pickBearer(apiKey: string, oauthToken: string): string {
return (apiKey && apiKey.trim()) || (oauthToken && oauthToken.trim()) || '';
}
// chatCompletionsURL / modelsURL — the model gateway endpoints.
export function chatCompletionsURL(): string {
return `${HANZO_API_BASE_URL}/v1/chat/completions`;
}
export function modelsURL(): string {
return `${HANZO_API_BASE_URL}/v1/models`;
}
// ---- Canvas host + API ----------------------------------------------------
//
// Canvas LMS is self-hosted per institution: each school runs its own Canvas at
// its own host (e.g. `school.instructure.com` or a custom domain). There is no
// fixed host list — the host is a deployment value, so every Canvas URL (OAuth
// login + REST API) is built from the configured host. We never hard-code an
// institution host inline.
//
// Docs: canvas.instructure.com/doc/api/file.oauth.html and
// canvas.instructure.com/doc/api/index.html (REST API).
// normalizeHost strips a scheme, a trailing slash, and any path/query so a raw
// value like `https://school.instructure.com/` or `school.instructure.com`
// resolves to the bare host `school.instructure.com`. Pure — the ONE place a host
// is cleaned, so every URL builder gets a canonical host. Boundary guard.
export function normalizeHost(raw: string): string {
return raw
.trim()
.replace(/^https?:\/\//i, '')
.replace(/\/.*$/, '')
.replace(/\/+$/, '');
}
// authBase turns a host into the OAuth login origin — `/login/oauth2/auth` and
// `/login/oauth2/token` live here. Pure.
export function authBase(host: string): string {
return `https://${normalizeHost(host)}`;
}
// The REST API version segment. v1 is Canvas's current (and only) REST version;
// we never bump to a speculative v2 — one version, forward only. This is Canvas's
// OWN `/api/v1` path, not a Hanzo gateway path (the /api/ ban is only for
// api.hanzo.ai, which uses /v1).
export const REST_API_VERSION = 'v1';
// apiBaseUrl turns a host into the REST root: `https://{host}/api/v1`. Every Canvas
// API call is built on top of this. Pure — the request wrappers in canvas-api.ts
// take this string.
export function apiBaseUrl(host: string): string {
return `${authBase(host)}/api/${REST_API_VERSION}`;
}
// The OAuth scopes the app requests. Canvas only enforces scopes when the
// Developer Key has "Enforce Scopes" enabled; a standard key ignores the `scope`
// parameter (permissions follow the authorizing user's Canvas role). We default to
// none so the app installs against either key type, and document the granular
// URL-scopes to add (see RECOMMENDED_SCOPES) when enforcement is on. The authorize
// URL only appends `scope` when this is non-empty.
export const OAUTH_SCOPES = [] as const;
// RECOMMENDED_SCOPES documents the exact Canvas URL-scopes to request when the
// Developer Key enforces scopes — the read surface this app uses plus the two
// gated writes. Not sent by default (see OAUTH_SCOPES); referenced by the README
// and available for a deployment that opts into scope enforcement.
export const RECOMMENDED_SCOPES = [
'url:GET|/api/v1/courses',
'url:GET|/api/v1/courses/:id',
'url:GET|/api/v1/courses/:course_id/assignments',
'url:GET|/api/v1/courses/:course_id/assignments/:id',
'url:GET|/api/v1/courses/:course_id/assignments/:assignment_id/submissions',
'url:GET|/api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id',
'url:GET|/api/v1/courses/:course_id/discussion_topics',
'url:GET|/api/v1/courses/:course_id/pages',
'url:GET|/api/v1/courses/:course_id/pages/:url_or_id',
'url:GET|/api/v1/courses/:course_id/modules',
'url:GET|/api/v1/courses/:course_id/enrollments',
'url:PUT|/api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id',
'url:POST|/api/v1/courses/:course_id/discussion_topics',
] as const;
// ---- Server-side configuration (Canvas OAuth) -----------------------------
//
// These are read from the environment by src/server.ts. They NEVER reach the
// browser bundle: the client id and host are public, but the client secret is
// server-only and is validated to be present before the server will start
// (readServerConfig throws on a missing secret). This is the ONLY place the secret
// exists.
export interface ServerConfig {
/** Canvas institution host, e.g. `school.instructure.com` (bare, normalized). */
canvasHost: string;
/** Canvas Developer Key client id (public). */
canvasClientId: string;
/** Canvas Developer Key client secret (SERVER ONLY — token exchange + refresh). */
canvasClientSecret: string;
/** OAuth redirect registered on the key (e.g. https://canvas.hanzo.ai/oauth/callback). */
canvasRedirectUri: string;
/** Listen port. */
port: number;
}
// readServerConfig fails fast (throws) if a required Canvas value is missing — a
// server that cannot exchange OAuth codes (or does not know which Canvas host to
// call) must not pretend to start. Pure given an env map, so it is unit-tested
// without touching process.env. The host is normalized at this one boundary.
export function readServerConfig(env: Record<string, string | undefined>): ServerConfig {
const canvasHost = env.CANVAS_HOST;
const canvasClientId = env.CANVAS_CLIENT_ID;
const canvasClientSecret = env.CANVAS_CLIENT_SECRET;
const canvasRedirectUri = env.CANVAS_REDIRECT_URI;
const missing: string[] = [];
if (!canvasHost) missing.push('CANVAS_HOST');
if (!canvasClientId) missing.push('CANVAS_CLIENT_ID');
if (!canvasClientSecret) missing.push('CANVAS_CLIENT_SECRET');
if (!canvasRedirectUri) missing.push('CANVAS_REDIRECT_URI');
if (missing.length > 0) {
throw new Error(`Missing required environment: ${missing.join(', ')}`);
}
return {
canvasHost: normalizeHost(canvasHost!),
canvasClientId: canvasClientId!,
canvasClientSecret: canvasClientSecret!,
canvasRedirectUri: canvasRedirectUri!,
port: Number(env.PORT) || 8791,
};
}
+251
View File
@@ -0,0 +1,251 @@
// Course-context assembly — PURE, host-agnostic, fully unit-testable. Turns the
// typed Canvas records (course/syllabus, modules, assignments, pages, discussions,
// submissions, enrollments) into the plain text an AI action reads, windowed to a
// character budget so a busy course never overflows the model or gets sent silently
// truncated.
//
// There is ONE windowing contract, identical in spirit to @hanzo/procore's project
// windowing: render ordered blocks, walk them in order, stop at the budget, always
// include at least the first block, and report `truncated` honestly. The only
// education-specific parts are how a record renders to a block and the HTML→text
// step (Canvas content — syllabus, page bodies, assignment descriptions, discussion
// messages — is HTML).
import type {
Assignment,
Course,
Discussion,
Enrollment,
Module,
Page_,
Submission,
} from './canvas-api.js';
import { COURSE_CHAR_BUDGET } from './config.js';
// ---- HTML → text ----------------------------------------------------------
// htmlToText reduces Canvas rich-text HTML to readable plain text: block elements
// become line breaks, tags are stripped, the common named/numeric entities are
// decoded, and whitespace is collapsed. Deliberately small and dependency-free (no
// DOM) — Canvas bodies are trusted-institution content we only need to READ, not
// render, so a full sanitizer/ parser would be over-engineering. Pure.
export function htmlToText(html: string): string {
if (!html) return '';
return html
.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*\/?\s*>/gi, '\n')
.replace(/<\s*li[^>]*>/gi, '• ')
.replace(/<[^>]+>/g, '')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/&quot;/gi, '"')
.replace(/&#39;/gi, "'")
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
.replace(/[ \t]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.split('\n')
.map((line) => line.trim())
.join('\n')
.trim();
}
// clamp trims a rendered body to a maximum length with an ellipsis so one giant
// page/syllabus can't dominate the budget before windowing even runs. Pure.
function clamp(text: string, max: number): string {
return text.length > max ? `${text.slice(0, max).trimEnd()}` : text;
}
// Per-body cap: a single HTML body is trimmed to this before it becomes a block, so
// the windowing budget sees comparable blocks rather than one 40k-char page.
const BODY_CAP = 4_000;
// ---- Record → text block --------------------------------------------------
// renderCourseOverview turns the course + its syllabus into the lead block: the
// course identity and the (HTML-stripped, clamped) syllabus text.
export function renderCourseOverview(course: Course): string {
const lines: string[] = [];
const head = `${course.name}${course.courseCode ? ` (${course.courseCode})` : ''}`.trim();
lines.push(head);
const meta: string[] = [];
if (course.termName) meta.push(`Term: ${course.termName}`);
if (course.workflowState) meta.push(`State: ${course.workflowState}`);
if (meta.length) lines.push(meta.join(' · '));
const syllabus = htmlToText(course.syllabusBody);
if (syllabus) lines.push(`Syllabus:\n${clamp(syllabus, BODY_CAP)}`);
return lines.join('\n');
}
// renderAssignment turns one assignment into a labelled block.
export function renderAssignment(a: Assignment): string {
const head = `Assignment: ${a.name}`.trim();
const meta: string[] = [];
if (a.dueAt) meta.push(`Due: ${a.dueAt}`);
if (a.pointsPossible) meta.push(`Points: ${a.pointsPossible}`);
if (a.submissionTypes.length) meta.push(`Submit: ${a.submissionTypes.join(', ')}`);
const lines = [meta.length ? `${head}\n${meta.join(' · ')}` : head];
const desc = htmlToText(a.description);
if (desc) lines.push(clamp(desc, BODY_CAP));
return lines.join('\n');
}
// renderSubmission turns one student submission into a labelled block, including
// the score/status and any existing comment thread (order preserved).
export function renderSubmission(s: Submission): string {
const lines: string[] = [];
const flags = [s.late ? 'late' : '', s.missing ? 'missing' : ''].filter(Boolean).join(', ');
const head = `Submission (user ${s.userId})${flags ? ` [${flags}]` : ''}`;
lines.push(head);
const meta: string[] = [];
if (s.workflowState) meta.push(`Status: ${s.workflowState}`);
if (s.score !== null) meta.push(`Score: ${s.score}`);
if (s.grade) meta.push(`Grade: ${s.grade}`);
if (s.submittedAt) meta.push(`Submitted: ${s.submittedAt}`);
if (meta.length) lines.push(meta.join(' · '));
const body = htmlToText(s.body);
if (body) lines.push(`Response: ${clamp(body, BODY_CAP)}`);
for (const c of s.comments) {
const who = c.authorName ? ` (${c.authorName})` : '';
if (c.comment) lines.push(`Comment${who}: ${c.comment.trim()}`);
}
return lines.join('\n');
}
// renderDiscussion turns one discussion topic into a labelled block.
export function renderDiscussion(d: Discussion): string {
const kind = d.isAnnouncement ? 'Announcement' : 'Discussion';
const head = `${kind}: ${d.title}`.trim();
const body = htmlToText(d.message);
return body ? `${head}\n${clamp(body, BODY_CAP)}` : head;
}
// renderPage turns one wiki page into a labelled block (title + stripped body).
export function renderPage(p: Page_): string {
const head = `Page: ${p.title || p.url}`.trim();
const body = htmlToText(p.body);
return body ? `${head}\n${clamp(body, BODY_CAP)}` : head;
}
// renderModule turns one module + its items into a labelled block.
export function renderModule(m: Module): string {
const head = `Module: ${m.name}`.trim();
const items = m.items.map((i) => ` - ${i.title}${i.type ? ` [${i.type}]` : ''}`).filter(Boolean);
return items.length ? `${head}\n${items.join('\n')}` : head;
}
// renderEnrollment turns one enrollment into a single labelled line.
export function renderEnrollment(e: Enrollment): string {
const who = e.userName || `user ${e.userId}`;
const role = e.role || e.type;
return `${who}${role ? `${role}` : ''}${e.state ? ` (${e.state})` : ''}`;
}
// ---- Windowing to a budget ------------------------------------------------
// A named group of rendered blocks — a section of the course context (e.g.
// "Assignments", "Modules"). The assembler concatenates sections in the order given
// and windows the whole thing to the budget.
export interface Section {
title: string;
blocks: string[];
}
// The windowed course context: the rendered text, how many blocks were available vs
// included, and whether anything was dropped (so the prompt and UI can say so
// honestly).
export interface CourseContext {
text: string;
totalBlocks: number;
includedBlocks: number;
truncated: boolean;
}
// buildCourseContext concatenates sections IN ORDER and caps the rendered text at
// `budget` characters. It walks blocks in order (across sections) and stops when
// adding the next block would exceed the budget — always including at least the
// first block (hard-cut to the budget if that one block alone is over). `truncated`
// is true whenever not every available block made it in. Pure and total:
// deterministic, no I/O. This is the ONE windowing algorithm for the package — the
// same "fit ordered text to a budget" contract as @hanzo/procore.
export function buildCourseContext(
sections: Section[],
budget: number = COURSE_CHAR_BUDGET,
): CourseContext {
const totalBlocks = sections.reduce((n, s) => n + s.blocks.length, 0);
if (totalBlocks === 0) {
return { text: '', totalBlocks: 0, includedBlocks: 0, truncated: false };
}
const parts: string[] = [];
let used = 0;
let included = 0;
let hardCut = false;
outer: for (const section of sections) {
if (section.blocks.length === 0) continue;
// The section header is charged to the first block that fits under it.
let headerPending = `## ${section.title}\n`;
for (const block of section.blocks) {
const prefix = parts.length === 0 ? '' : '\n\n';
const addition = prefix + headerPending + block;
if (used + addition.length > budget) {
if (parts.length === 0) {
// First block alone overflows — hard-cut it to the budget so we always
// send something rather than an empty context.
const solo = (headerPending + block).slice(0, budget);
parts.push(solo);
used = solo.length;
included = 1;
hardCut = true;
}
break outer;
}
parts.push(addition);
used += addition.length;
included += 1;
headerPending = ''; // header only precedes the first block of the section
}
}
const truncated = included < totalBlocks || hardCut;
return { text: parts.join(''), totalBlocks, includedBlocks: included, truncated };
}
// contextNote is the one honest sentence prepended to the course text so the model
// (and, echoed in the panel, the user) knows the scope of what it sees. Never claim
// the whole course was sent when it wasn't. Pure.
export function contextNote(ctx: CourseContext): string {
if (ctx.totalBlocks === 0) return 'No course records were available.';
return ctx.truncated
? `Course records: ${ctx.includedBlocks} of ${ctx.totalBlocks} items (truncated to fit — answer only from what is shown and say so if the omitted part is needed).`
: `Course records: all ${ctx.totalBlocks} item${ctx.totalBlocks === 1 ? '' : 's'}.`;
}
// ---- Convenience section builders -----------------------------------------
//
// These turn a typed record list into a Section, so a caller (server or panel)
// assembles a course context in a couple of lines. Kept here (pure) so the same
// section shapes feed both surfaces and the tests.
export function courseSection(course: Course, title = 'Course'): Section {
return { title, blocks: [renderCourseOverview(course)] };
}
export function moduleSection(modules: Module[], title = 'Modules'): Section {
return { title, blocks: modules.map(renderModule) };
}
export function assignmentSection(assignments: Assignment[], title = 'Assignments'): Section {
return { title, blocks: assignments.map(renderAssignment) };
}
export function pageSection(pages: Page_[], title = 'Pages'): Section {
return { title, blocks: pages.map(renderPage) };
}
export function discussionSection(discussions: Discussion[], title = 'Discussions'): Section {
return { title, blocks: discussions.map(renderDiscussion) };
}
export function submissionSection(submissions: Submission[], title = 'Submissions'): Section {
return { title, blocks: submissions.map(renderSubmission) };
}
export function enrollmentSection(enrollments: Enrollment[], title = 'Enrollments'): Section {
return { title, blocks: enrollments.map(renderEnrollment) };
}
+145
View File
@@ -0,0 +1,145 @@
// The Hanzo call and its request/response shaping over a COURSE — thin over the
// published `@hanzo/ai` headless client, host-agnostic, and fully unit-testable (no
// Canvas SDK, no DOM). The panel and the server are the glue that read a course's
// records and hand them here. Speaks the OpenAI-compatible /v1 wire protocol the
// whole Hanzo suite uses (identical to @hanzo/procore) so the gateway sees one shape
// from every surface.
//
// @hanzo/ai@^0.2.0 IS the headless client: createAiClient({ baseUrl, token }) →
// .chat.completions.create({ model, messages }) + .models.list(). We import it and
// do NOT reimplement the transport. This module adds only the course-aware prompt
// assembly + the single `ask` primitive the actions layer on.
import {
createAiClient,
type AiClient,
type ChatCompletion,
type ChatCompletionMessage,
} from '@hanzo/ai';
import { DEFAULT_MODEL, HANZO_API_BASE_URL } from './config.js';
import { contextNote, type CourseContext } from './course.js';
// SYSTEM_PROMPT grounds every answer in the course records. It forbids inventing
// facts nobody recorded (the failure mode that makes a teaching assistant
// untrustworthy), keeps student data handled respectfully, and stays honest about
// truncated context. It states plainly that the output is a DRAFT for an educator to
// review — not an authoritative grade, decision, or the final word to a student.
export const SYSTEM_PROMPT =
'You are Hanzo AI, an assistant that helps instructors and teaching staff work ' +
'with their Canvas course — the syllabus, modules, assignments, pages, ' +
'discussions, and student submissions. Work ONLY from the course records provided ' +
'below — never invent assignments, due dates, grades, submissions, or facts that ' +
'are not supported by the text. Be concise, precise, and constructive; when you ' +
'reference student work, be specific and fair. If the records are marked truncated ' +
'and a complete answer needs the omitted part, say so plainly rather than guessing. ' +
'Everything you produce — feedback, questions, announcements, summaries — is a ' +
'DRAFT for an educator to review and edit before it reaches a student; it is not an ' +
'authoritative grade or decision.';
// ---- Prompt assembly ------------------------------------------------------
// Optional structured context about the course (name, code, term) the Canvas API
// supplies. Attached as a short header above the records so answers can reference the
// course without the model guessing.
export interface CourseMeta {
name?: string;
courseCode?: string;
term?: string;
}
function courseHeader(meta: CourseMeta | undefined): string {
if (!meta) return '';
const parts: string[] = [];
if (meta.name) parts.push(`Course: ${meta.name}`);
if (meta.courseCode) parts.push(`Code: ${meta.courseCode}`);
if (meta.term) parts.push(`Term: ${meta.term}`);
return parts.length > 0 ? parts.join('\n') + '\n\n' : '';
}
// buildMessages turns a task (the user's question, or one of the action prompts)
// plus the windowed course context + optional metadata into the OpenAI-compatible
// message list. The records are fenced so the model treats them as data, not
// instructions, and the honest context note rides inside the user turn so it is never
// lost. Pure — unit-tested.
export function buildMessages(
task: string,
ctx: CourseContext,
meta?: CourseMeta,
): ChatCompletionMessage[] {
const system: ChatCompletionMessage = { role: 'system', content: SYSTEM_PROMPT };
const header = courseHeader(meta);
const user: ChatCompletionMessage = {
role: 'user',
content:
`${header}${contextNote(ctx)}\n\n` +
`---- course records ----\n${ctx.text}\n---- end course records ----\n\n` +
`---- task ----\n${task}`,
};
return [system, user];
}
// extractContent pulls the assistant text out of a @hanzo/ai ChatCompletion,
// tolerating the string-or-parts content shape the OpenAI schema allows. Throws on
// empty content so callers surface the real gateway state. Pure — unit-tested.
export function extractContent(res: ChatCompletion): string {
const msg = res?.choices?.[0]?.message;
const content = msg?.content;
let text = '';
if (typeof content === 'string') {
text = content;
} else if (Array.isArray(content)) {
text = content.map((part) => (part?.type === 'text' ? part.text : '')).join('');
}
if (text.length === 0) throw new Error('Hanzo API returned no content');
return text;
}
// ---- The single call path -------------------------------------------------
export interface AskOptions {
model?: string;
temperature?: number;
token?: string;
baseURL?: string;
/** Injected client (tests). Defaults to a real createAiClient. */
client?: AiClient;
signal?: AbortSignal;
}
// client resolves the @hanzo/ai client for a call: an injected one (tests) or a fresh
// createAiClient pointed at the gateway with the caller's bearer.
function client(opts: AskOptions): AiClient {
return (
opts.client ?? createAiClient({ token: opts.token, baseUrl: opts.baseURL ?? HANZO_API_BASE_URL })
);
}
// ask runs ONE non-streaming completion over a course and returns the answer. This
// is the single path from every Canvas surface to the model — the actions, a freeform
// question, and any server-side call all funnel here. token may be empty (the gateway
// serves anonymous/limited models).
export async function ask(
task: string,
ctx: CourseContext,
meta: CourseMeta | undefined,
opts: AskOptions = {},
): Promise<string> {
const res = await client(opts).chat.completions.create(
{
model: opts.model ?? DEFAULT_MODEL,
messages: buildMessages(task, ctx, meta),
stream: false,
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
},
{ signal: opts.signal },
);
return extractContent(res);
}
// listModels returns the model ids the caller may route to, from /v1/models via the
// headless client. The endpoint is org-scoped by the bearer; an empty token lists
// public models.
export async function listModels(opts: AskOptions = {}): Promise<string[]> {
const models = await client(opts).models.list({ signal: opts.signal });
return models.map((m) => m.id);
}
+58
View File
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hanzo AI for Canvas</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header>
<span class="title">Hanzo AI</span>
<select id="model" aria-label="Model"></select>
<span class="host">Canvas</span>
</header>
<div class="row scope">
<select id="course" aria-label="Course"></select>
<button id="load" class="secondary">Load</button>
</div>
<div class="row scope">
<select id="assignment" aria-label="Assignment"></select>
<button id="loadsubs" class="secondary" disabled>Load submissions</button>
</div>
<div class="records" id="records"></div>
<!-- One-click actions over the loaded course. Chips are built from the catalog. -->
<div class="chips" id="chips"></div>
<label for="prompt">Ask about this course</label>
<textarea id="prompt" placeholder="e.g. Which assignments are due next week? · Summarize what module 3 covers. · What are the common themes in the discussion posts?"></textarea>
<div class="row">
<button id="run">Ask Hanzo</button>
<button id="stop" class="secondary" disabled>Stop</button>
<span class="spacer"></span>
<button id="comment" class="secondary" disabled title="Load an assignment's submissions to enable">Post as submission comment</button>
<button id="announce" class="secondary" disabled title="Load a course to enable">Post as announcement</button>
</div>
<details>
<summary>Hanzo API key</summary>
<div class="row">
<input id="apikey" type="password" placeholder="hk-…" autocomplete="off" />
<button id="savekey" class="secondary">Save</button>
</div>
<div id="authhint" class="hint"></div>
</details>
<div class="status" id="status"></div>
<label for="output">Result</label>
<textarea id="output" placeholder="Hanzo's draft appears here."></textarea>
<footer>Routed through api.hanzo.ai · grounded in your Canvas course records · a draft for an educator to review, not an authoritative grade or decision.</footer>
<script type="module" src="__ENTRY__"></script>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
// Public surface of @hanzo/canvas-lms: the pure, host-agnostic modules. The browser
// panel (app.ts) and the Node service (server.ts) are entry points, not re-exported
// here. A consumer embedding the course-analysis pipeline in their own service imports
// from here.
export * from './config.js';
export * from './canvas-oauth.js';
export * from './canvas-api.js';
export * from './course.js';
export * from './hanzo.js';
export * from './actions.js';
+241
View File
@@ -0,0 +1,241 @@
// Browser-side panel helpers — PURE where it counts (launch-context parsing +
// proxy-request shaping), so the impure DOM wiring in app.ts stays thin and the logic
// is unit-tested. The panel reaches Canvas ONLY through the server proxy (config:
// same-origin /proxy/*), which injects the OAuth Bearer + refreshes it; the browser
// never holds a Canvas token.
import {
parseCourses,
parseCourse,
parseAssignments,
parseAssignment,
parseSubmissions,
parseSubmission,
parseDiscussions,
parsePages,
parsePage,
parseModules,
parseEnrollments,
parseLinkHeader,
nextPage,
pageParams,
type Course,
type Assignment,
type Submission,
type Discussion,
type Page_,
type Module,
type Enrollment,
type Page,
} from './canvas-api.js';
// The launch context: when Canvas embeds this app (via LTI or a course-nav link) it
// passes the course in the URL query. The panel reads it so it opens already scoped.
// Optional — without it the user picks from the course list.
export interface LaunchContext {
courseId: string;
}
// parseLaunchContext reads a course id from a location search string, accepting the
// plain `course_id` and Canvas's LTI custom-variable spellings. Pure — unit-tested
// with plain strings.
export function parseLaunchContext(search: string): LaunchContext {
const q = new URLSearchParams(search);
return {
courseId:
q.get('course_id') ??
q.get('canvas_course_id') ??
q.get('custom_canvas_course_id') ??
q.get('courseId') ??
'',
};
}
// A parsed list result: the typed items plus the page number to request next (from
// the Link header's `rel="next"`), or undefined on the last page.
export interface ListResult<T> {
items: T[];
next?: number;
}
// The panel's Canvas client: reads through the same-origin server proxy. Every call
// rides the session cookie (credentials: 'include'); the proxy injects the Bearer.
// Pure over an injected fetch + base, so request shaping is unit-testable.
export interface ProxyClient {
listCourses(page?: Page): Promise<ListResult<Course>>;
getCourse(courseId: number | string): Promise<Course>;
listAssignments(courseId: number | string, page?: Page): Promise<ListResult<Assignment>>;
getAssignment(courseId: number | string, assignmentId: number | string): Promise<Assignment>;
listSubmissions(
courseId: number | string,
assignmentId: number | string,
page?: Page,
): Promise<ListResult<Submission>>;
getSubmission(
courseId: number | string,
assignmentId: number | string,
userId: number | string,
): Promise<Submission>;
listDiscussions(courseId: number | string, page?: Page): Promise<ListResult<Discussion>>;
listPages(courseId: number | string, page?: Page): Promise<ListResult<Page_>>;
getPage(courseId: number | string, urlOrId: number | string): Promise<Page_>;
listModules(courseId: number | string, page?: Page): Promise<ListResult<Module>>;
listEnrollments(courseId: number | string, page?: Page): Promise<ListResult<Enrollment>>;
postSubmissionComment(
courseId: number | string,
assignmentId: number | string,
userId: number | string,
text: string,
): Promise<void>;
createAnnouncement(courseId: number | string, title: string, message: string): Promise<void>;
}
export interface ProxyClientOptions {
/** Proxy base (defaults to same-origin ''). The REST path is appended after /proxy. */
base?: string;
/** Injected fetch (tests). Defaults to global fetch. */
fetch?: typeof fetch;
}
// proxyUrl builds a same-origin proxy URL for a REST path + query, expanding array
// values into Canvas's `key[]=v` repetition. Normalizes the base (drops a trailing
// slash) so this is the ONE place base+path joining happens. Pure so tests assert the
// exact shape (…/proxy/courses?per_page=100).
export function proxyUrl(
base: string,
restPath: string,
query: Record<string, string | string[] | undefined> = {},
): string {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) {
for (const item of v) if (item !== undefined && item !== '') q.append(`${k}[]`, item);
} else if (v !== undefined && v !== '') {
q.set(k, v);
}
}
const qs = q.toString();
return `${base.replace(/\/+$/, '')}/proxy${restPath}${qs ? `?${qs}` : ''}`;
}
// createProxyClient returns a ProxyClient. The cookie credentials are attached once
// here so every method stays a one-liner. List methods parse the Link header into the
// next page number so a caller can page through the proxy without following Canvas's
// absolute URLs.
export function createProxyClient(opts: ProxyClientOptions = {}): ProxyClient {
const base = opts.base ?? ''; // proxyUrl normalizes the trailing slash
const doFetch = opts.fetch ?? fetch;
async function getJson(
restPath: string,
query: Record<string, string | string[] | undefined>,
): Promise<{ data: any; next?: number }> {
const resp = await doFetch(proxyUrl(base, restPath, query), { credentials: 'include' });
if (!resp.ok) throw new Error(await proxyError(resp));
return { data: await resp.json(), next: nextPage(parseLinkHeader(resp.headers)) };
}
async function write(restPath: string, method: 'POST' | 'PUT', body: unknown): Promise<void> {
const resp = await doFetch(proxyUrl(base, restPath), {
method,
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
if (!resp.ok) throw new Error(await proxyError(resp));
}
return {
async listCourses(page?) {
const { data, next } = await getJson('/courses', pageParams(page));
return { items: parseCourses(data), next };
},
async getCourse(courseId) {
const { data } = await getJson(`/courses/${enc(courseId)}`, { include: ['syllabus_body'] });
return parseCourse(data);
},
async listAssignments(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/assignments`, pageParams(page));
return { items: parseAssignments(data), next };
},
async getAssignment(courseId, assignmentId) {
const { data } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}`,
{},
);
return parseAssignment(data);
},
async listSubmissions(courseId, assignmentId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions`,
{ include: ['submission_comments'], ...pageParams(page) },
);
return { items: parseSubmissions(data), next };
},
async getSubmission(courseId, assignmentId, userId) {
const { data } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
{ include: ['submission_comments'] },
);
return parseSubmission(data);
},
async listDiscussions(courseId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/discussion_topics`,
pageParams(page),
);
return { items: parseDiscussions(data), next };
},
async listPages(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/pages`, pageParams(page));
return { items: parsePages(data), next };
},
async getPage(courseId, urlOrId) {
const { data } = await getJson(`/courses/${enc(courseId)}/pages/${enc(urlOrId)}`, {});
return parsePage(data);
},
async listModules(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/modules`, {
include: ['items'],
...pageParams(page),
});
return { items: parseModules(data), next };
},
async listEnrollments(courseId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/enrollments`,
pageParams(page),
);
return { items: parseEnrollments(data), next };
},
async postSubmissionComment(courseId, assignmentId, userId, text) {
await write(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
'PUT',
{ comment: { text_comment: text } },
);
},
async createAnnouncement(courseId, title, message) {
await write(`/courses/${enc(courseId)}/discussion_topics`, 'POST', {
title,
message,
is_announcement: true,
});
},
};
}
// proxyError extracts a readable message from a non-2xx proxy response.
async function proxyError(resp: Response): Promise<string> {
const text = await resp.text().catch(() => '');
try {
const j = JSON.parse(text);
return `Canvas proxy ${resp.status}: ${j?.error || j?.message || text.slice(0, 200)}`;
} catch {
return `Canvas proxy ${resp.status}: ${text.slice(0, 200) || 'request failed'}`;
}
}
function enc(segment: number | string): string {
return encodeURIComponent(String(segment));
}
+252
View File
@@ -0,0 +1,252 @@
// The Canvas install + API-proxy service. This is the ONLY place the Canvas client
// secret and the OAuth tokens exist — the secret is read from the environment (never
// bundled, never sent to the browser); tokens are minted by the OAuth flow and kept
// server-side, refreshed transparently on expiry. It:
//
// GET /oauth/install → redirect the user to Canvas's OAuth consent
// GET /oauth/callback → exchange the code for a token, open a session, and hand
// the browser a session cookie
// ALL /proxy/* → forward a browser request to the Canvas REST API with
// the session's Bearer token, refreshing the token first
// if it has expired. The browser never sees the token or
// the secret.
// GET /healthz → readiness
//
// It is a dependency-free Node http handler built on the pure modules (config,
// canvas-oauth, canvas-api) so it is deployable behind hanzoai/ingress as a small
// service at canvas.hanzo.ai. The pure logic it wraps is what the tests cover; the
// http server is an integration concern.
//
// node dist/server.js (after build.js bundles it)
//
// Required environment (see config.readServerConfig):
// CANVAS_HOST, CANVAS_CLIENT_ID, CANVAS_CLIENT_SECRET, CANVAS_REDIRECT_URI
// PORT (default 8791)
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { randomUUID } from 'node:crypto';
import { apiBaseUrl, readServerConfig, OAUTH_SCOPES, type ServerConfig } from './config.js';
import {
authorizeUrl,
tokenExchange,
refreshExchange,
parseTokenResponse,
carryRefreshToken,
isExpired,
type CanvasTokenSet,
} from './canvas-oauth.js';
// A server-side session: the tokens for one authorized user + when the token was
// minted (Canvas does not return a mint timestamp, so we record wall-clock at
// mint/refresh to compute expiry). In-memory here keyed by an opaque session id
// carried in an HttpOnly cookie; a production deployment persists this to hanzoai/kv
// (Valkey) so sessions survive a restart.
interface Session {
token: CanvasTokenSet;
/** Wall-clock epoch seconds when the token was last minted/refreshed. */
mintedAt: number;
}
const sessions = new Map<string, Session>();
const SESSION_COOKIE = 'canvas_sid';
// A pending OAuth `state` (CSRF token) minted at /oauth/install and consumed at
// /oauth/callback. A production deployment persists these (Valkey, short TTL); a Set
// is enough for a single instance.
const pendingStates = new Set<string>();
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
function json(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
function log(fields: Record<string, unknown>): void {
console.log(JSON.stringify(fields));
}
// sessionIdFromCookie reads the session id from the Cookie header. Minimal parser — we
// only need our one cookie.
function sessionIdFromCookie(req: IncomingMessage): string | undefined {
const raw = req.headers.cookie;
if (!raw) return undefined;
for (const part of raw.split(';')) {
const [k, ...v] = part.trim().split('=');
if (k === SESSION_COOKIE) return decodeURIComponent(v.join('='));
}
return undefined;
}
// GET /oauth/install → 302 to Canvas's consent screen. `state` is a fresh CSRF token
// re-checked on callback.
function handleInstall(cfg: ServerConfig, res: ServerResponse): void {
const state = randomUUID();
pendingStates.add(state);
const url = authorizeUrl({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
redirectUri: cfg.canvasRedirectUri,
scopes: OAUTH_SCOPES,
state,
});
res.writeHead(302, { Location: url });
res.end();
}
// GET /oauth/callback?code=…&state=… → verify state, exchange the code for a token
// (secret in the server-side body), open a session, and set the cookie.
async function handleOAuthCallback(
cfg: ServerConfig,
url: URL,
res: ServerResponse,
): Promise<void> {
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
if (!code) return json(res, 400, { error: 'missing code' });
if (!state || !pendingStates.delete(state)) return json(res, 400, { error: 'invalid state' });
const exReq = tokenExchange({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
clientSecret: cfg.canvasClientSecret,
code,
redirectUri: cfg.canvasRedirectUri,
});
let token: CanvasTokenSet;
try {
const resp = await fetch(exReq.url, {
method: 'POST',
headers: exReq.headers,
body: exReq.body,
});
token = parseTokenResponse(await resp.json().catch(() => ({})));
} catch (e: any) {
return json(res, 400, { error: e?.message || 'token exchange failed' });
}
const sid = randomUUID();
sessions.set(sid, { token, mintedAt: nowSeconds() });
log({ msg: 'oauth: session opened', sid });
res.writeHead(200, {
'Content-Type': 'application/json',
'Set-Cookie': `${SESSION_COOKIE}=${sid}; HttpOnly; Secure; SameSite=Lax; Path=/`,
});
res.end(JSON.stringify({ ok: true, installed: true }));
}
// freshToken returns a session's access token, refreshing first if it has expired.
// Canvas does not rotate the refresh token (the refresh response omits it), so we
// carry the previous one forward via carryRefreshToken. Throws if the refresh fails
// (the caller returns 401 and the user re-installs).
async function freshToken(cfg: ServerConfig, sid: string, session: Session): Promise<string> {
if (!isExpired(session.token, session.mintedAt, nowSeconds())) return session.token.access_token;
const refreshToken = session.token.refresh_token;
if (!refreshToken) throw new Error('session expired and no refresh token');
const rReq = refreshExchange({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
clientSecret: cfg.canvasClientSecret,
refreshToken,
});
const resp = await fetch(rReq.url, { method: 'POST', headers: rReq.headers, body: rReq.body });
const next = carryRefreshToken(parseTokenResponse(await resp.json().catch(() => ({}))), session.token);
sessions.set(sid, { token: next, mintedAt: nowSeconds() });
log({ msg: 'oauth: token refreshed', sid });
return next.access_token;
}
// ALL /proxy/* → forward to the Canvas REST API. The browser sends the REST path
// (after /proxy); the server injects the Bearer token (never exposed to the browser)
// and forwards the method, query, and body. This is the API proxy that keeps the
// secret + tokens server-side while letting the panel read Courses/Assignments/…and
// post a comment or announcement.
async function handleProxy(
cfg: ServerConfig,
req: IncomingMessage,
res: ServerResponse,
url: URL,
): Promise<void> {
const sid = sessionIdFromCookie(req);
const session = sid ? sessions.get(sid) : undefined;
if (!sid || !session) return json(res, 401, { error: 'not authenticated' });
let accessToken: string;
try {
accessToken = await freshToken(cfg, sid, session);
} catch (e: any) {
return json(res, 401, { error: e?.message || 'token refresh failed' });
}
// The path after /proxy is the REST path relative to /api/v1, e.g.
// /proxy/courses → ${apiBase}/courses. We forbid absolute/scheme-bearing targets so
// the proxy can only ever reach the configured Canvas REST host.
const restPath = url.pathname.replace(/^\/proxy/, '') || '/';
const target = `${apiBaseUrl(cfg.canvasHost)}${restPath}${url.search}`;
const method = req.method || 'GET';
const body = method === 'GET' || method === 'HEAD' ? undefined : await readRawBody(req);
try {
const upstream = await fetch(target, {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body,
});
// Pass Canvas's Link header through so the panel can paginate.
const link = upstream.headers.get('Link');
const text = await upstream.text();
const outHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
if (link) outHeaders.Link = link;
res.writeHead(upstream.status, outHeaders);
res.end(text);
} catch (e: any) {
log({ msg: 'proxy: upstream error', error: e?.message, target });
return json(res, 502, { error: 'upstream request failed' });
}
}
// readRawBody collects the raw request bytes as a utf8 string.
async function readRawBody(req: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
return Buffer.concat(chunks).toString('utf8');
}
// createHandler is the request router. Everything is a small handler over the pure
// modules. Exported so a test can drive it with a mock req/res if desired.
export function createHandler(cfg: ServerConfig) {
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
const url = new URL(req.url || '/', `http://localhost:${cfg.port}`);
try {
if (req.method === 'GET' && url.pathname === '/oauth/install') return handleInstall(cfg, res);
if (req.method === 'GET' && url.pathname === '/oauth/callback')
return await handleOAuthCallback(cfg, url, res);
if (url.pathname === '/proxy' || url.pathname.startsWith('/proxy/'))
return await handleProxy(cfg, req, res, url);
if (req.method === 'GET' && url.pathname === '/healthz') return json(res, 200, { ok: true });
return json(res, 404, { error: 'not found' });
} catch (e: any) {
log({ msg: 'unhandled error', error: e?.message });
return json(res, 500, { error: 'internal error' });
}
};
}
// main boots the server when run directly. Import-safe: only the direct entry
// listens, so tests import the handlers without opening a port.
export function main(): void {
const cfg = readServerConfig(process.env);
const server = createServer(createHandler(cfg));
server.listen(cfg.port, () => {
log({ msg: 'hanzo canvas service up', port: cfg.port, host: cfg.canvasHost });
});
}
if (process.argv[1] && process.argv[1].endsWith('server.js')) {
main();
}
+50
View File
@@ -0,0 +1,50 @@
:root {
color-scheme: light dark;
--fg: #1a1a1a; --muted: #666; --bg: #fff; --line: #e3e3e3; --accent: #111;
--ok: #1a7f37; --warn: #9a6700; --error: #cf222e;
}
@media (prefers-color-scheme: dark) {
:root {
--fg: #eaeaea; --muted: #9a9a9a; --bg: #1e1e1e; --line: #333; --accent: #fff;
--ok: #3fb950; --warn: #d29922; --error: #f85149;
}
}
* { box-sizing: border-box; }
body {
font: 14px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif;
color: var(--fg); background: var(--bg); margin: 0 auto; padding: 14px;
max-width: 720px;
}
header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
header .title { font-weight: 600; font-size: 15px; }
header .host { color: var(--muted); font-size: 12px; margin-left: auto; }
label { display: block; font-size: 12px; color: var(--muted); margin: 10px 0 4px; }
textarea, select, input {
width: 100%; font: inherit; color: var(--fg); background: var(--bg);
border: 1px solid var(--line); border-radius: 6px; padding: 8px;
}
textarea#prompt { min-height: 56px; resize: vertical; }
textarea#output { min-height: 220px; resize: vertical; }
.row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
.row.scope { margin-top: 4px; }
.row.scope select { flex: 1; min-width: 160px; }
button {
font: inherit; border: 1px solid var(--line); background: var(--accent);
color: var(--bg); border-radius: 6px; padding: 8px 14px; cursor: pointer;
}
button.secondary { background: transparent; color: var(--fg); }
button:disabled { opacity: .5; cursor: default; }
.spacer { flex: 1; }
.records { font-size: 11px; color: var(--muted); margin-top: 6px; min-height: 14px; }
.status { min-height: 18px; font-size: 12px; margin-top: 10px; color: var(--muted); }
.status.ok { color: var(--ok); } .status.warn { color: var(--warn); } .status.error { color: var(--error); }
.hint { font-size: 11px; color: var(--muted); margin-top: 4px; }
footer { margin-top: 12px; font-size: 11px; color: var(--muted); }
select#model { width: auto; max-width: 150px; padding: 4px 8px; font-size: 12px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
.chip {
padding: 5px 10px; border-radius: 999px; font-size: 13px;
background: transparent; color: var(--fg); border: 1px solid var(--line);
}
.chip:hover:not(:disabled) { border-color: var(--accent); }
details summary { cursor: pointer; font-size: 12px; color: var(--muted); margin-top: 10px; }
+89
View File
@@ -0,0 +1,89 @@
import { describe, it, expect, vi } from 'vitest';
import type { AiClient, ChatCompletion, ChatCompletionCreateParams } from '@hanzo/ai';
import { ACTIONS, actionList, actionPrompt, isActionId, runAction } from '../src/actions.js';
import { buildCourseContext } from '../src/course.js';
const ctx = buildCourseContext([{ title: 'Assignments', blocks: ['Assignment: Lab Report 1'] }]);
function mockClient(text: string) {
const reply: ChatCompletion = {
id: 'c', object: 'chat.completion', created: 0, model: 'zen5',
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
};
const create = vi.fn(async (_p: ChatCompletionCreateParams) => reply);
return { client: { chat: { completions: { create } }, models: { list: vi.fn() } } as unknown as AiClient, create };
}
describe('actions: catalog', () => {
it('exposes exactly the five documented actions', () => {
expect(Object.keys(ACTIONS).sort()).toEqual(
['draftAnnouncement', 'draftFeedback', 'generateQuestions', 'summarizeCourse', 'summarizeSubmissions'].sort(),
);
});
it('every action has a non-empty label and prompt', () => {
for (const [id, a] of Object.entries(ACTIONS)) {
expect(a.label.length, id).toBeGreaterThan(0);
expect(a.prompt.length, id).toBeGreaterThan(20);
}
});
it('actionList mirrors the catalog order and shape', () => {
const list = actionList();
expect(list.map((a) => a.id)).toEqual(Object.keys(ACTIONS));
expect(list[0]).toEqual({ id: 'summarizeCourse', label: ACTIONS.summarizeCourse.label });
});
});
describe('actions: prompt intent', () => {
it('summarizeCourse grounds on the syllabus and modules', () => {
const p = actionPrompt('summarizeCourse');
expect(p).toMatch(/syllabus/i);
expect(p).toMatch(/module/i);
});
it('draftFeedback stays grounded and returns paste-ready comment text', () => {
const p = actionPrompt('draftFeedback');
expect(p).toMatch(/do not invent/i);
expect(p).toMatch(/submission comment/i);
});
it('generateQuestions asks for quiz questions and discussion prompts', () => {
const p = actionPrompt('generateQuestions');
expect(p).toMatch(/quiz questions/i);
expect(p).toMatch(/discussion prompts/i);
});
it('summarizeSubmissions asks for submitted/missing/late and scores', () => {
const p = actionPrompt('summarizeSubmissions');
expect(p).toMatch(/missing or late/i);
expect(p).toMatch(/scores or grades/i);
});
it('draftAnnouncement asks for a subject line and stays grounded on dates', () => {
const p = actionPrompt('draftAnnouncement');
expect(p).toMatch(/subject line/i);
expect(p).toMatch(/do not invent dates/i);
});
});
describe('actions: isActionId / actionPrompt guards', () => {
it('narrows known ids and rejects unknown', () => {
expect(isActionId('summarizeCourse')).toBe(true);
expect(isActionId('nope')).toBe(false);
});
it('actionPrompt throws on an unknown id', () => {
expect(() => actionPrompt('nope')).toThrow(/Unknown action/);
});
});
describe('actions: runAction', () => {
it('routes the resolved prompt through ask (one code path to the model)', async () => {
const { client, create } = mockClient('overview');
const out = await runAction('summarizeCourse', ctx, { name: 'BIO-101' }, { client });
expect(out).toBe('overview');
const user = String(create.mock.calls[0][0].messages[1].content);
expect(user).toContain(ACTIONS.summarizeCourse.prompt);
expect(user).toContain('Assignment: Lab Report 1');
});
it('rejects (not synchronously throws) on an unknown id', async () => {
await expect(runAction('nope', ctx)).rejects.toThrow(/Unknown action/);
});
});
+202
View File
@@ -0,0 +1,202 @@
import { describe, it, expect } from 'vitest';
import {
DEFAULT_PER_PAGE,
pageParams,
parseLinkHeader,
pageOfUrl,
nextPage,
listCourses,
getCourse,
listAssignments,
getAssignment,
listSubmissions,
getSubmission,
postSubmissionComment,
listDiscussions,
createAnnouncement,
listPages,
getPage,
listModules,
listEnrollments,
type Scope,
} from '../src/canvas-api.js';
import { apiBaseUrl } from '../src/config.js';
const scope: Scope = {
apiBase: apiBaseUrl('school.instructure.com'),
accessToken: 'at-123',
};
function q(url: string): URLSearchParams {
return new URL(url).searchParams;
}
describe('api: pageParams', () => {
it('emits nothing for no page', () => {
expect(pageParams(undefined)).toEqual({});
});
it('emits page + per_page when set', () => {
expect(pageParams({ page: 2, perPage: 50 })).toEqual({ page: '2', per_page: '50' });
});
it('clamps per_page to the documented max', () => {
expect(pageParams({ perPage: 500 }).per_page).toBe(String(DEFAULT_PER_PAGE));
});
it('ignores non-positive values', () => {
expect(pageParams({ page: 0, perPage: -5 })).toEqual({});
});
});
describe('api: bearer scoping', () => {
it('every read carries the Bearer token and no company header', () => {
for (const req of [
listCourses(scope),
getCourse(scope, 7),
listAssignments(scope, 7),
getAssignment(scope, 7, 9),
listSubmissions(scope, 7, 9),
getSubmission(scope, 7, 9, 11),
listDiscussions(scope, 7),
listPages(scope, 7),
getPage(scope, 7, 'intro'),
listModules(scope, 7),
listEnrollments(scope, 7),
]) {
expect(req.headers.Authorization).toBe('Bearer at-123');
expect(req.headers).not.toHaveProperty('Procore-Company-Id');
}
});
});
describe('api: courses', () => {
it('lists courses with pagination and no course in the path', () => {
const req = listCourses(scope, { page: 3, perPage: 25 });
const url = new URL(req.url);
expect(url.pathname).toBe('/api/v1/courses');
expect(q(req.url).get('page')).toBe('3');
expect(q(req.url).get('per_page')).toBe('25');
});
it('gets one course defaulting to include[]=syllabus_body', () => {
const req = getCourse(scope, 100);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100');
expect(q(req.url).getAll('include[]')).toEqual(['syllabus_body']);
});
it('gets a bare course when includes are empty', () => {
const req = getCourse(scope, 100, []);
expect(q(req.url).has('include[]')).toBe(false);
});
});
describe('api: assignments + submissions', () => {
it('lists assignments on a course path', () => {
expect(new URL(listAssignments(scope, 100).url).pathname).toBe('/api/v1/courses/100/assignments');
});
it('gets one assignment by id', () => {
expect(new URL(getAssignment(scope, 100, 55).url).pathname).toBe('/api/v1/courses/100/assignments/55');
});
it('lists submissions with submission_comments included', () => {
const req = listSubmissions(scope, 100, 55, { perPage: 50 });
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions');
expect(q(req.url).getAll('include[]')).toEqual(['submission_comments']);
expect(q(req.url).get('per_page')).toBe('50');
});
it('gets one submission by user id', () => {
const req = getSubmission(scope, 100, 55, 900);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions/900');
});
});
describe('api: postSubmissionComment (the feedback write path)', () => {
it('PUTs a comment[text_comment] JSON body on the submission', () => {
const req = postSubmissionComment(scope, 100, 55, 900, 'Great analysis of the data.');
expect(req.method).toBe('PUT');
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions/900');
expect(req.headers['Content-Type']).toBe('application/json');
expect(req.headers.Authorization).toBe('Bearer at-123');
expect(JSON.parse(req.body)).toEqual({ comment: { text_comment: 'Great analysis of the data.' } });
});
});
describe('api: createAnnouncement (the announcement write path)', () => {
it('POSTs a discussion topic flagged is_announcement', () => {
const req = createAnnouncement(scope, 100, 'Midterm moved', 'The midterm is now next Friday.');
expect(req.method).toBe('POST');
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/discussion_topics');
expect(JSON.parse(req.body)).toEqual({
title: 'Midterm moved',
message: 'The midterm is now next Friday.',
is_announcement: true,
});
});
});
describe('api: discussions / pages / modules / enrollments', () => {
it('lists discussions on a course path', () => {
expect(new URL(listDiscussions(scope, 100).url).pathname).toBe('/api/v1/courses/100/discussion_topics');
});
it('lists pages and gets one page by url slug', () => {
expect(new URL(listPages(scope, 100).url).pathname).toBe('/api/v1/courses/100/pages');
expect(new URL(getPage(scope, 100, 'week-1-intro').url).pathname).toBe('/api/v1/courses/100/pages/week-1-intro');
});
it('lists modules with items included', () => {
const req = listModules(scope, 100);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/modules');
expect(q(req.url).getAll('include[]')).toEqual(['items']);
});
it('lists enrollments on a course path', () => {
expect(new URL(listEnrollments(scope, 100).url).pathname).toBe('/api/v1/courses/100/enrollments');
});
});
describe('api: path segment encoding', () => {
it('encodes ids/slugs defensively so a stray value cannot traverse the path', () => {
const req = getPage(scope, 'a/b', 'c d');
expect(req.url).toContain('/courses/a%2Fb/pages/c%20d');
});
});
describe('api: parseLinkHeader (RFC 5988)', () => {
const header =
'<https://school.instructure.com/api/v1/courses?page=1&per_page=10>; rel="current", ' +
'<https://school.instructure.com/api/v1/courses?page=2&per_page=10>; rel="next", ' +
'<https://school.instructure.com/api/v1/courses?page=1&per_page=10>; rel="first", ' +
'<https://school.instructure.com/api/v1/courses?page=17&per_page=10>; rel="last"';
it('parses each relation URL from a Headers instance', () => {
const links = parseLinkHeader(new Headers({ Link: header }));
expect(links.current).toContain('page=1');
expect(links.next).toBe('https://school.instructure.com/api/v1/courses?page=2&per_page=10');
expect(links.first).toContain('page=1');
expect(links.last).toContain('page=17');
});
it('parses from a plain header map (either case)', () => {
expect(parseLinkHeader({ Link: header }).next).toContain('page=2');
expect(parseLinkHeader({ link: header }).last).toContain('page=17');
});
it('returns {} for a missing/blank header', () => {
expect(parseLinkHeader({})).toEqual({});
expect(parseLinkHeader(new Headers())).toEqual({});
});
it('tolerates a last-page header with no next relation', () => {
const last =
'<https://school.instructure.com/api/v1/courses?page=16&per_page=10>; rel="prev", ' +
'<https://school.instructure.com/api/v1/courses?page=17&per_page=10>; rel="current"';
const links = parseLinkHeader({ Link: last });
expect(links.next).toBeUndefined();
expect(links.prev).toContain('page=16');
});
});
describe('api: pageOfUrl + nextPage', () => {
it('extracts the page number from a pagination URL', () => {
expect(pageOfUrl('https://h/api/v1/courses?page=2&per_page=10')).toBe(2);
expect(pageOfUrl('https://h/api/v1/courses?per_page=10')).toBeUndefined();
expect(pageOfUrl(undefined)).toBeUndefined();
});
it('nextPage reads the next relation into a page number', () => {
expect(nextPage({ next: 'https://h/api/v1/courses?page=3' })).toBe(3);
expect(nextPage({})).toBeUndefined();
});
});
+108
View File
@@ -0,0 +1,108 @@
import { describe, it, expect } from 'vitest';
import {
HANZO_API_BASE_URL,
DEFAULT_MODEL,
APIKEY_STORAGE_KEY,
COURSE_CHAR_BUDGET,
pickBearer,
chatCompletionsURL,
modelsURL,
normalizeHost,
authBase,
apiBaseUrl,
readServerConfig,
OAUTH_SCOPES,
RECOMMENDED_SCOPES,
} from '../src/config.js';
describe('config: gateway constants', () => {
it('points at api.hanzo.ai with /v1 paths and never /api/', () => {
expect(HANZO_API_BASE_URL).toBe('https://api.hanzo.ai');
expect(chatCompletionsURL()).toBe('https://api.hanzo.ai/v1/chat/completions');
expect(modelsURL()).toBe('https://api.hanzo.ai/v1/models');
expect(chatCompletionsURL()).not.toContain('/api/');
});
it('defaults to a zen model and a sane budget', () => {
expect(DEFAULT_MODEL).toBe('zen5');
expect(COURSE_CHAR_BUDGET).toBeGreaterThan(10_000);
expect(APIKEY_STORAGE_KEY).toContain('canvas');
});
});
describe('config: pickBearer', () => {
it('prefers a pasted key over an oauth token', () => {
expect(pickBearer('hk-abc', 'oauth-xyz')).toBe('hk-abc');
});
it('falls back to the oauth token, trimming whitespace', () => {
expect(pickBearer(' ', ' tok ')).toBe('tok');
});
it('returns empty when both are blank (anonymous)', () => {
expect(pickBearer('', '')).toBe('');
expect(pickBearer(' ', '')).toBe('');
});
});
describe('config: normalizeHost', () => {
it('strips a scheme, path, and trailing slash to a bare host', () => {
expect(normalizeHost('https://school.instructure.com/')).toBe('school.instructure.com');
expect(normalizeHost('http://canvas.school.edu/courses/1')).toBe('canvas.school.edu');
expect(normalizeHost('school.instructure.com')).toBe('school.instructure.com');
expect(normalizeHost(' school.instructure.com ')).toBe('school.instructure.com');
});
});
describe('config: authBase + apiBaseUrl', () => {
it('builds the OAuth login origin from a host', () => {
expect(authBase('school.instructure.com')).toBe('https://school.instructure.com');
expect(authBase('https://school.instructure.com/')).toBe('https://school.instructure.com');
});
it('builds the /api/v1 REST root from a host', () => {
expect(apiBaseUrl('school.instructure.com')).toBe('https://school.instructure.com/api/v1');
expect(apiBaseUrl('canvas.school.edu')).toBe('https://canvas.school.edu/api/v1');
});
});
describe('config: scopes', () => {
it('requests no scopes by default (works with or without scope enforcement)', () => {
expect(OAUTH_SCOPES).toEqual([]);
});
it('documents the granular read + write scopes for enforcement', () => {
expect(RECOMMENDED_SCOPES.length).toBeGreaterThan(5);
expect(RECOMMENDED_SCOPES).toContain('url:GET|/api/v1/courses');
expect(RECOMMENDED_SCOPES.some((s) => s.startsWith('url:PUT|'))).toBe(true);
expect(RECOMMENDED_SCOPES.some((s) => s.startsWith('url:POST|'))).toBe(true);
});
});
describe('config: readServerConfig', () => {
const base = {
CANVAS_HOST: 'school.instructure.com',
CANVAS_CLIENT_ID: 'cid',
CANVAS_CLIENT_SECRET: 'secret',
CANVAS_REDIRECT_URI: 'https://canvas.hanzo.ai/oauth/callback',
};
it('reads a full config, normalizing the host and defaulting the port to 8791', () => {
const cfg = readServerConfig({ ...base, CANVAS_HOST: 'https://school.instructure.com/' });
expect(cfg.canvasHost).toBe('school.instructure.com');
expect(cfg.canvasClientId).toBe('cid');
expect(cfg.canvasClientSecret).toBe('secret');
expect(cfg.canvasRedirectUri).toBe('https://canvas.hanzo.ai/oauth/callback');
expect(cfg.port).toBe(8791);
});
it('honours PORT', () => {
expect(readServerConfig({ ...base, PORT: '9002' }).port).toBe(9002);
});
it('throws listing every missing required value', () => {
expect(() => readServerConfig({})).toThrow(/CANVAS_HOST/);
expect(() => readServerConfig({})).toThrow(/CANVAS_CLIENT_ID/);
expect(() => readServerConfig({})).toThrow(/CANVAS_CLIENT_SECRET/);
expect(() => readServerConfig({})).toThrow(/CANVAS_REDIRECT_URI/);
expect(() => readServerConfig({ CANVAS_HOST: 'h' })).toThrow(
/CANVAS_CLIENT_ID, CANVAS_CLIENT_SECRET, CANVAS_REDIRECT_URI/,
);
});
});
+217
View File
@@ -0,0 +1,217 @@
import { describe, it, expect } from 'vitest';
import {
htmlToText,
renderCourseOverview,
renderAssignment,
renderSubmission,
renderDiscussion,
renderPage,
renderModule,
renderEnrollment,
buildCourseContext,
contextNote,
courseSection,
moduleSection,
assignmentSection,
pageSection,
discussionSection,
submissionSection,
enrollmentSection,
} from '../src/course.js';
import type {
Course,
Assignment,
Submission,
Discussion,
Page_,
Module,
Enrollment,
} from '../src/canvas-api.js';
describe('course: htmlToText', () => {
it('strips tags, breaks blocks, and decodes entities', () => {
const html = '<h2>Syllabus</h2><p>Read &amp; annotate ch.&nbsp;1.</p><ul><li>Quiz</li><li>Lab</li></ul>';
const text = htmlToText(html);
expect(text).toContain('Syllabus');
expect(text).toContain('Read & annotate ch. 1.');
expect(text).toContain('• Quiz');
expect(text).toContain('• Lab');
expect(text).not.toContain('<');
});
it('decodes numeric entities and collapses whitespace', () => {
expect(htmlToText('a&#39;b')).toBe("a'b");
expect(htmlToText('x y')).toBe('x y');
});
it('returns empty for empty/whitespace input', () => {
expect(htmlToText('')).toBe('');
expect(htmlToText('<p> </p>')).toBe('');
});
});
const course: Course = {
id: 1,
name: 'Introduction to Biology',
courseCode: 'BIO-101',
workflowState: 'available',
syllabusBody: '<p>Welcome to <strong>BIO-101</strong>. Weekly labs.</p>',
termName: 'Fall 2026',
};
describe('course: record rendering', () => {
it('renders a course overview with the stripped syllabus', () => {
const text = renderCourseOverview(course);
expect(text).toContain('Introduction to Biology (BIO-101)');
expect(text).toContain('Term: Fall 2026');
expect(text).toContain('Syllabus:');
expect(text).toContain('Welcome to BIO-101. Weekly labs.');
expect(text).not.toContain('<strong>');
});
it('renders an assignment with meta and stripped description', () => {
const a: Assignment = {
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
dueAt: '2026-09-15',
pointsPossible: 25,
submissionTypes: ['online_upload'],
};
const text = renderAssignment(a);
expect(text).toContain('Assignment: Lab Report 1');
expect(text).toContain('Due: 2026-09-15 · Points: 25 · Submit: online_upload');
expect(text).toContain('Write up the osmosis lab.');
});
it('renders a submission with score, flags, and comments', () => {
const s: Submission = {
id: 5001,
userId: 900,
assignmentId: 1,
body: '<p>Water moves across the membrane.</p>',
submittedAt: '2026-09-14',
workflowState: 'submitted',
score: 22,
grade: '22',
late: true,
missing: false,
comments: [{ id: 1, authorName: 'Prof. Ada', comment: 'Good start.', createdAt: '2026-09-15' }],
};
const text = renderSubmission(s);
expect(text).toContain('Submission (user 900) [late]');
expect(text).toContain('Status: submitted · Score: 22 · Grade: 22');
expect(text).toContain('Response: Water moves across the membrane.');
expect(text).toContain('Comment (Prof. Ada): Good start.');
});
it('renders a discussion, page, module, and enrollment compactly', () => {
const d: Discussion = { id: 10, title: 'Week 1', message: '<p>Introduce yourself.</p>', postedAt: '', isAnnouncement: false };
expect(renderDiscussion(d)).toContain('Discussion: Week 1');
expect(renderDiscussion(d)).toContain('Introduce yourself.');
const ann: Discussion = { ...d, isAnnouncement: true, title: 'Welcome' };
expect(renderDiscussion(ann)).toContain('Announcement: Welcome');
const p: Page_ = { pageId: 7, url: 'intro', title: 'Week 1 Intro', body: '<p>Read ch. 1.</p>', updatedAt: '' };
expect(renderPage(p)).toContain('Page: Week 1 Intro');
expect(renderPage(p)).toContain('Read ch. 1.');
const m: Module = {
id: 20,
name: 'Cells',
position: 1,
items: [{ id: 1, title: 'Intro page', type: 'Page', position: 1 }],
};
expect(renderModule(m)).toContain('Module: Cells');
expect(renderModule(m)).toContain('- Intro page [Page]');
const e: Enrollment = { id: 30, userId: 900, userName: 'Sam Student', type: 'StudentEnrollment', role: 'StudentEnrollment', state: 'active' };
expect(renderEnrollment(e)).toBe('Sam Student — StudentEnrollment (active)');
});
});
describe('course: buildCourseContext', () => {
it('returns empty for no blocks', () => {
const ctx = buildCourseContext([{ title: 'Assignments', blocks: [] }]);
expect(ctx).toEqual({ text: '', totalBlocks: 0, includedBlocks: 0, truncated: false });
});
it('includes all blocks under section headers when within budget', () => {
const ctx = buildCourseContext([
{ title: 'Modules', blocks: ['a', 'b'] },
{ title: 'Pages', blocks: ['c'] },
]);
expect(ctx.totalBlocks).toBe(3);
expect(ctx.includedBlocks).toBe(3);
expect(ctx.truncated).toBe(false);
expect(ctx.text).toContain('## Modules');
expect(ctx.text).toContain('## Pages');
expect(ctx.text.indexOf('## Modules')).toBeLessThan(ctx.text.indexOf('## Pages'));
});
it('windows in order and reports truncation when the budget is exceeded', () => {
const blocks = ['x'.repeat(30), 'y'.repeat(30), 'z'.repeat(30)];
const ctx = buildCourseContext([{ title: 'Pages', blocks }], 60);
expect(ctx.totalBlocks).toBe(3);
expect(ctx.includedBlocks).toBeLessThan(3);
expect(ctx.truncated).toBe(true);
expect(ctx.text).toContain('xxx');
expect(ctx.text).not.toContain('zzz');
expect(ctx.text.length).toBeLessThanOrEqual(60);
});
it('always includes at least the first block, hard-cutting it if it alone overflows', () => {
const huge = 'q'.repeat(500);
const ctx = buildCourseContext([{ title: 'Pages', blocks: [huge, 'next'] }], 50);
expect(ctx.includedBlocks).toBe(1);
expect(ctx.truncated).toBe(true);
expect(ctx.text.length).toBe(50);
expect(ctx.text.startsWith('## Pages')).toBe(true);
});
it('skips empty sections without charging a header', () => {
const ctx = buildCourseContext([
{ title: 'Empty', blocks: [] },
{ title: 'Pages', blocks: ['a'] },
]);
expect(ctx.text).not.toContain('## Empty');
expect(ctx.text).toContain('## Pages');
expect(ctx.includedBlocks).toBe(1);
});
});
describe('course: contextNote', () => {
it('is honest about no records', () => {
expect(contextNote({ text: '', totalBlocks: 0, includedBlocks: 0, truncated: false })).toMatch(/No course records/);
});
it('reports full coverage', () => {
expect(contextNote({ text: 'x', totalBlocks: 3, includedBlocks: 3, truncated: false })).toMatch(/all 3 items/);
});
it('reports truncation with the counts', () => {
expect(contextNote({ text: 'x', totalBlocks: 10, includedBlocks: 4, truncated: true })).toMatch(/4 of 10 items/);
});
});
describe('course: section builders assemble a real context', () => {
it('turns typed records into a windowed context end to end', () => {
const ctx = buildCourseContext([
courseSection(course),
moduleSection([{ id: 20, name: 'Cells', position: 1, items: [] }]),
assignmentSection([{ id: 1, name: 'Lab 1', description: '', dueAt: '', pointsPossible: 25, submissionTypes: [] }]),
pageSection([{ pageId: 7, url: 'intro', title: 'Intro', body: '', updatedAt: '' }]),
discussionSection([{ id: 10, title: 'Week 1', message: '', postedAt: '', isAnnouncement: false }]),
submissionSection([
{ id: 1, userId: 900, assignmentId: 1, body: '', submittedAt: '', workflowState: 'submitted', score: 22, grade: '22', late: false, missing: false, comments: [] },
]),
enrollmentSection([{ id: 30, userId: 900, userName: 'Sam', type: 'StudentEnrollment', role: 'StudentEnrollment', state: 'active' }]),
]);
expect(ctx.totalBlocks).toBe(7);
expect(ctx.truncated).toBe(false);
expect(ctx.text).toContain('## Course');
expect(ctx.text).toContain('Introduction to Biology');
expect(ctx.text).toContain('## Modules');
expect(ctx.text).toContain('## Assignments');
expect(ctx.text).toContain('## Pages');
expect(ctx.text).toContain('## Discussions');
expect(ctx.text).toContain('## Submissions');
expect(ctx.text).toContain('## Enrollments');
});
});
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi } from 'vitest';
import type { AiClient, ChatCompletion, ChatCompletionCreateParams, Model } from '@hanzo/ai';
import {
SYSTEM_PROMPT,
buildMessages,
extractContent,
ask,
listModels,
type CourseMeta,
} from '../src/hanzo.js';
import { buildCourseContext, type CourseContext } from '../src/course.js';
const ctx: CourseContext = buildCourseContext([{ title: 'Assignments', blocks: ['Assignment: Lab Report 1'] }]);
const meta: CourseMeta = { name: 'Intro to Biology', courseCode: 'BIO-101', term: 'Fall 2026' };
// completion builds a minimal @hanzo/ai ChatCompletion with the given content.
function completion(content: ChatCompletion['choices'][number]['message']['content']): ChatCompletion {
return {
id: 'c1',
object: 'chat.completion',
created: 0,
model: 'zen5',
choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }],
};
}
// mockClient captures the params the code sends and returns a canned completion.
function mockClient(reply: ChatCompletion, models: Model[] = []) {
const create = vi.fn(async (_p: ChatCompletionCreateParams, _o?: { signal?: AbortSignal }) => reply);
const list = vi.fn(async (_o?: { signal?: AbortSignal }) => models);
const client = { chat: { completions: { create } }, models: { list } } as unknown as AiClient;
return { client, create, list };
}
describe('hanzo: buildMessages', () => {
it('produces a grounded system prompt + a fenced user turn with meta + context note', () => {
const msgs = buildMessages('What is due next week?', ctx, meta);
expect(msgs).toHaveLength(2);
expect(msgs[0].role).toBe('system');
expect(msgs[0].content).toBe(SYSTEM_PROMPT);
const user = String(msgs[1].content);
expect(user).toContain('Course: Intro to Biology');
expect(user).toContain('Code: BIO-101');
expect(user).toContain('Term: Fall 2026');
expect(user).toContain('---- course records ----');
expect(user).toContain('Assignment: Lab Report 1');
expect(user).toContain('---- task ----');
expect(user).toContain('What is due next week?');
});
it('omits the header block entirely when meta is undefined', () => {
const user = String(buildMessages('q', ctx).at(1)!.content);
expect(user).not.toContain('Course:');
expect(user).toContain('---- task ----');
});
it('SYSTEM_PROMPT forbids inventing records and marks output a draft', () => {
expect(SYSTEM_PROMPT).toMatch(/never invent/i);
expect(SYSTEM_PROMPT).toMatch(/draft/i);
expect(SYSTEM_PROMPT).toMatch(/not an authoritative grade/i);
});
});
describe('hanzo: extractContent', () => {
it('reads a plain string content', () => {
expect(extractContent(completion('hello'))).toBe('hello');
});
it('concatenates text parts of an array content', () => {
const parts = [
{ type: 'text', text: 'a' },
{ type: 'image_url', image_url: { url: 'x' } },
{ type: 'text', text: 'b' },
] as any;
expect(extractContent(completion(parts))).toBe('ab');
});
it('throws on empty content', () => {
expect(() => extractContent(completion(''))).toThrow(/no content/);
expect(() => extractContent(completion(undefined))).toThrow(/no content/);
});
});
describe('hanzo: ask', () => {
it('sends model + messages non-streaming through the injected client and returns the text', async () => {
const { client, create } = mockClient(completion('due: Lab Report 1'));
const out = await ask('What is due?', ctx, meta, { client, model: 'zen5', temperature: 0.2 });
expect(out).toBe('due: Lab Report 1');
expect(create).toHaveBeenCalledOnce();
const [params, options] = create.mock.calls[0];
expect(params.model).toBe('zen5');
expect(params.stream).toBe(false);
expect(params.temperature).toBe(0.2);
expect(params.messages[0].role).toBe('system');
expect(options).toBeDefined();
});
it('omits temperature from the wire when not provided', async () => {
const { client, create } = mockClient(completion('ok'));
await ask('q', ctx, undefined, { client });
expect('temperature' in create.mock.calls[0][0]).toBe(false);
});
it('defaults the model to zen5', async () => {
const { client, create } = mockClient(completion('ok'));
await ask('q', ctx, undefined, { client });
expect(create.mock.calls[0][0].model).toBe('zen5');
});
it('propagates an abort signal to the client', async () => {
const { client, create } = mockClient(completion('ok'));
const controller = new AbortController();
await ask('q', ctx, undefined, { client, signal: controller.signal });
expect(create.mock.calls[0][1]?.signal).toBe(controller.signal);
});
});
describe('hanzo: listModels', () => {
it('maps the model catalog to ids', async () => {
const models: Model[] = [
{ id: 'zen5', object: 'model' },
{ id: 'zen5-pro', object: 'model' },
];
const { client } = mockClient(completion('x'), models);
expect(await listModels({ client })).toEqual(['zen5', 'zen5-pro']);
});
});
+166
View File
@@ -0,0 +1,166 @@
import { describe, it, expect } from 'vitest';
import {
authorizeUrl,
tokenUrl,
tokenExchange,
refreshExchange,
parseTokenResponse,
carryRefreshToken,
tokenExpiresAt,
isExpired,
} from '../src/canvas-oauth.js';
const HOST = 'school.instructure.com';
describe('oauth: authorizeUrl', () => {
it('builds the consent URL with the standard Canvas params', () => {
const url = new URL(
authorizeUrl({
host: HOST,
clientId: 'cid',
redirectUri: 'https://canvas.hanzo.ai/oauth/callback',
state: 'st-1',
}),
);
expect(url.origin).toBe('https://school.instructure.com');
expect(url.pathname).toBe('/login/oauth2/auth');
expect(url.searchParams.get('response_type')).toBe('code');
expect(url.searchParams.get('client_id')).toBe('cid');
expect(url.searchParams.get('redirect_uri')).toBe('https://canvas.hanzo.ai/oauth/callback');
expect(url.searchParams.get('state')).toBe('st-1');
});
it('omits scope when empty and normalizes a host with a scheme', () => {
const url = new URL(
authorizeUrl({ host: 'https://school.instructure.com/', clientId: 'c', redirectUri: 'https://x/cb', state: 's', scopes: [] }),
);
expect(url.origin).toBe('https://school.instructure.com');
expect(url.searchParams.has('scope')).toBe(false);
});
it('space-joins scopes when present', () => {
const url = new URL(
authorizeUrl({
host: HOST,
clientId: 'c',
redirectUri: 'https://x/cb',
state: 's',
scopes: ['url:GET|/api/v1/courses', 'url:GET|/api/v1/courses/:id'],
}),
);
expect(url.searchParams.get('scope')).toBe('url:GET|/api/v1/courses url:GET|/api/v1/courses/:id');
});
});
describe('oauth: token endpoints', () => {
it('resolves the token URL per host', () => {
expect(tokenUrl(HOST)).toBe('https://school.instructure.com/login/oauth2/token');
expect(tokenUrl('canvas.school.edu')).toBe('https://canvas.school.edu/login/oauth2/token');
});
});
describe('oauth: tokenExchange', () => {
it('form-encodes the code grant with client credentials + redirect_uri in the body', () => {
const req = tokenExchange({
host: HOST,
clientId: 'cid',
clientSecret: 'sec',
code: 'the-code',
redirectUri: 'https://canvas.hanzo.ai/oauth/callback',
});
expect(req.url).toBe('https://school.instructure.com/login/oauth2/token');
expect(req.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('authorization_code');
expect(body.get('code')).toBe('the-code');
expect(body.get('client_id')).toBe('cid');
expect(body.get('client_secret')).toBe('sec');
expect(body.get('redirect_uri')).toBe('https://canvas.hanzo.ai/oauth/callback');
});
it('never puts the secret in the URL', () => {
const req = tokenExchange({ host: HOST, clientId: 'c', clientSecret: 'SUPER', code: 'x', redirectUri: 'https://x/cb' });
expect(req.url).not.toContain('SUPER');
});
});
describe('oauth: refreshExchange', () => {
it('form-encodes the refresh grant with client credentials and no redirect_uri', () => {
const req = refreshExchange({ host: HOST, clientId: 'cid', clientSecret: 'sec', refreshToken: 'r-1' });
expect(req.url).toBe('https://school.instructure.com/login/oauth2/token');
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('refresh_token');
expect(body.get('refresh_token')).toBe('r-1');
expect(body.get('client_id')).toBe('cid');
expect(body.get('client_secret')).toBe('sec');
expect(body.has('code')).toBe(false);
expect(body.has('redirect_uri')).toBe(false);
});
});
describe('oauth: parseTokenResponse', () => {
it('parses a full token set including the Canvas user', () => {
const t = parseTokenResponse({
access_token: 'at',
refresh_token: 'rt',
expires_in: 3600,
token_type: 'Bearer',
user: { id: 7, name: 'Prof. Ada' },
});
expect(t.access_token).toBe('at');
expect(t.refresh_token).toBe('rt');
expect(t.expires_in).toBe(3600);
expect(t.user).toEqual({ id: 7, name: 'Prof. Ada' });
});
it('throws on a Canvas error payload with the description', () => {
expect(() => parseTokenResponse({ error: 'invalid_grant', error_description: 'code used' })).toThrow(/code used/);
});
it('throws when access_token is missing or empty', () => {
expect(() => parseTokenResponse({})).toThrow(/missing access_token/);
expect(() => parseTokenResponse({ access_token: '' })).toThrow(/missing access_token/);
expect(() => parseTokenResponse(null)).toThrow(/empty token response/);
});
it('drops non-string/non-number optional fields defensively', () => {
const t = parseTokenResponse({ access_token: 'at', refresh_token: 123, expires_in: 'soon' });
expect(t.refresh_token).toBeUndefined();
expect(t.expires_in).toBeUndefined();
expect(t.user).toBeUndefined();
});
});
describe('oauth: carryRefreshToken (Canvas does not rotate)', () => {
it('keeps the previous refresh token when the refresh response omits it', () => {
const prev = { access_token: 'a0', refresh_token: 'rt-keep' };
const next = { access_token: 'a1' };
expect(carryRefreshToken(next, prev).refresh_token).toBe('rt-keep');
});
it('uses a new refresh token if one is returned', () => {
const prev = { access_token: 'a0', refresh_token: 'old' };
const next = { access_token: 'a1', refresh_token: 'new' };
expect(carryRefreshToken(next, prev).refresh_token).toBe('new');
});
});
describe('oauth: expiry math', () => {
it('computes expiry from mintedAt + expires_in minus skew', () => {
const t = { access_token: 'a', expires_in: 3600 };
expect(tokenExpiresAt(t, 1000, 60)).toBe(1000 + 3600 - 60);
});
it('treats a token with no expires_in as immediately (skew-)expired', () => {
const t = { access_token: 'a' };
expect(tokenExpiresAt(t, 5000, 0)).toBe(5000);
});
it('reports not-expired before, expired at/after the skewed boundary', () => {
const t = { access_token: 'a', expires_in: 3600 };
const minted = 1000;
const boundary = minted + 3600 - 60;
expect(isExpired(t, minted, boundary - 1, 60)).toBe(false);
expect(isExpired(t, minted, boundary, 60)).toBe(true);
expect(isExpired(t, minted, boundary + 100, 60)).toBe(true);
});
});
+111
View File
@@ -0,0 +1,111 @@
import { describe, it, expect, vi } from 'vitest';
import { parseLaunchContext, proxyUrl, createProxyClient } from '../src/panel.js';
describe('panel: parseLaunchContext', () => {
it('reads a plain course_id', () => {
expect(parseLaunchContext('?course_id=370663')).toEqual({ courseId: '370663' });
});
it('accepts Canvas LTI custom-variable spellings and defaults to empty', () => {
expect(parseLaunchContext('?custom_canvas_course_id=7')).toEqual({ courseId: '7' });
expect(parseLaunchContext('?canvas_course_id=9')).toEqual({ courseId: '9' });
expect(parseLaunchContext('')).toEqual({ courseId: '' });
});
});
describe('panel: proxyUrl', () => {
it('prefixes /proxy and appends a query, dropping empties', () => {
expect(proxyUrl('', '/courses', { page: '', per_page: '100' })).toBe('/proxy/courses?per_page=100');
});
it('expands array values into Canvas key[]=v repetition', () => {
expect(proxyUrl('', '/courses/1', { include: ['syllabus_body'] })).toBe(
'/proxy/courses/1?include%5B%5D=syllabus_body',
);
});
it('strips a trailing slash from the base', () => {
expect(proxyUrl('https://canvas.hanzo.ai/', '/x')).toBe('https://canvas.hanzo.ai/proxy/x');
});
});
// jsonResponse builds a fetch Response-like with an optional Link header.
function jsonResponse(body: unknown, link?: string): Response {
const headers = new Headers({ 'Content-Type': 'application/json' });
if (link) headers.set('Link', link);
return new Response(JSON.stringify(body), { status: 200, headers });
}
// fetchMockOf wraps a responder in a fetch-typed mock so calls[i] carries the
// (url, init) arg tuple TypeScript expects.
function fetchMockOf(responder: () => Response) {
return vi.fn((_url: RequestInfo | URL, _init?: RequestInit) => Promise.resolve(responder()));
}
describe('panel: createProxyClient — scoping + shaping', () => {
it('sends credentials and returns parsed items with the next page from the Link header', async () => {
const link = '<https://school.instructure.com/api/v1/courses?page=2&per_page=100>; rel="next"';
const fetchMock = fetchMockOf(() => jsonResponse([{ id: 1, name: 'Biology' }], link));
const client = createProxyClient({ fetch: fetchMock as any });
const { items, next } = await client.listCourses({ perPage: 100 });
expect(items).toEqual([
{ id: 1, name: 'Biology', courseCode: '', workflowState: '', syllabusBody: '', termName: '' },
]);
expect(next).toBe(2);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses?per_page=100');
expect((init as RequestInit).credentials).toBe('include');
});
it('has no next page when the Link header omits a next relation', async () => {
const fetchMock = fetchMockOf(() => jsonResponse([]));
const client = createProxyClient({ fetch: fetchMock as any });
const { next } = await client.listCourses();
expect(next).toBeUndefined();
});
it('gets a course with include[]=syllabus_body', async () => {
const fetchMock = fetchMockOf(() => jsonResponse({ id: 1, name: 'Biology', syllabus_body: '<p>Hi</p>' }));
const client = createProxyClient({ fetch: fetchMock as any });
const course = await client.getCourse(1);
expect(course.syllabusBody).toBe('<p>Hi</p>');
expect(String(fetchMock.mock.calls[0][0])).toBe('/proxy/courses/1?include%5B%5D=syllabus_body');
});
it('lists submissions on the assignment path with comments included', async () => {
const fetchMock = fetchMockOf(() => jsonResponse([]));
const client = createProxyClient({ fetch: fetchMock as any });
await client.listSubmissions(100, 55, { page: 2 });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'/proxy/courses/100/assignments/55/submissions?include%5B%5D=submission_comments&page=2',
);
});
it('postSubmissionComment PUTs the comment[text_comment] JSON body', async () => {
const fetchMock = fetchMockOf(() => new Response('{}', { status: 200 }));
const client = createProxyClient({ fetch: fetchMock as any });
await client.postSubmissionComment(100, 55, 900, 'Nice work.');
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses/100/assignments/55/submissions/900');
expect((init as RequestInit).method).toBe('PUT');
expect(JSON.parse(String((init as RequestInit).body))).toEqual({ comment: { text_comment: 'Nice work.' } });
});
it('createAnnouncement POSTs a discussion topic flagged is_announcement', async () => {
const fetchMock = fetchMockOf(() => new Response('{}', { status: 201 }));
const client = createProxyClient({ fetch: fetchMock as any });
await client.createAnnouncement(100, 'Heads up', 'Class is online Friday.');
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses/100/discussion_topics');
expect((init as RequestInit).method).toBe('POST');
expect(JSON.parse(String((init as RequestInit).body))).toEqual({
title: 'Heads up',
message: 'Class is online Friday.',
is_announcement: true,
});
});
it('surfaces a proxy error with status + message', async () => {
const fetchMock = fetchMockOf(() => new Response(JSON.stringify({ error: 'not authenticated' }), { status: 401 }));
const client = createProxyClient({ fetch: fetchMock as any });
await expect(client.listCourses()).rejects.toThrow(/401.*not authenticated/);
});
});
+180
View File
@@ -0,0 +1,180 @@
import { describe, it, expect } from 'vitest';
import {
parseCourse,
parseCourses,
parseAssignment,
parseAssignments,
parseSubmission,
parseSubmissions,
parseDiscussions,
parsePage,
parsePages,
parseModules,
parseEnrollments,
} from '../src/canvas-api.js';
// A realistic Canvas course detail payload (trimmed to fields we surface).
const courseFixture = {
id: 370663,
name: 'Introduction to Biology',
course_code: 'BIO-101',
workflow_state: 'available',
syllabus_body: '<p>Welcome to <strong>BIO-101</strong>.</p>',
term: { id: 5, name: 'Fall 2026' },
};
describe('parse: course', () => {
it('reads name, code, state, syllabus, and term name', () => {
const c = parseCourse(courseFixture);
expect(c.id).toBe(370663);
expect(c.name).toBe('Introduction to Biology');
expect(c.courseCode).toBe('BIO-101');
expect(c.workflowState).toBe('available');
expect(c.syllabusBody).toContain('<strong>BIO-101</strong>');
expect(c.termName).toBe('Fall 2026');
});
it('normalizes a bare array and drops rows without an id', () => {
const rows = parseCourses([courseFixture, { name: 'no id' }, { id: 0, name: 'bad' }]);
expect(rows).toHaveLength(1);
expect(rows[0].courseCode).toBe('BIO-101');
});
it('reads a wrapped { courses } shape and defaults a missing term', () => {
const rows = parseCourses({ courses: [{ id: 2, name: 'Annex' }] });
expect(rows[0].termName).toBe('');
expect(rows[0].syllabusBody).toBe('');
});
});
describe('parse: assignments', () => {
it('reads name, description, due date, points, and submission types', () => {
const a = parseAssignment({
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
due_at: '2026-09-15T23:59:00Z',
points_possible: 25,
submission_types: ['online_text_entry', 'online_upload'],
});
expect(a).toEqual({
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
dueAt: '2026-09-15T23:59:00Z',
pointsPossible: 25,
submissionTypes: ['online_text_entry', 'online_upload'],
});
});
it('parses an array and drops idless rows', () => {
const rows = parseAssignments([{ id: 1, name: 'A' }, { name: 'no id' }]);
expect(rows).toHaveLength(1);
expect(rows[0].submissionTypes).toEqual([]);
});
});
describe('parse: submissions', () => {
const submissionFixture = {
id: 5001,
user_id: 900,
assignment_id: 1,
body: '<p>Osmosis moves water across a membrane.</p>',
submitted_at: '2026-09-14T10:00:00Z',
workflow_state: 'submitted',
score: 22,
grade: '22',
late: true,
missing: false,
submission_comments: [
{ id: 1, author_name: 'Prof. Ada', comment: 'Good start.', created_at: '2026-09-15T09:00:00Z' },
],
};
it('reads score, grade, flags, body, and the comment thread', () => {
const s = parseSubmission(submissionFixture);
expect(s.userId).toBe(900);
expect(s.workflowState).toBe('submitted');
expect(s.score).toBe(22);
expect(s.grade).toBe('22');
expect(s.late).toBe(true);
expect(s.missing).toBe(false);
expect(s.body).toContain('Osmosis');
expect(s.comments).toHaveLength(1);
expect(s.comments[0].authorName).toBe('Prof. Ada');
expect(s.comments[0].comment).toBe('Good start.');
});
it('treats a null score/grade as null/empty and no comments as []', () => {
const s = parseSubmission({ id: 1, user_id: 2, score: null, grade: null, workflow_state: 'unsubmitted' });
expect(s.score).toBeNull();
expect(s.grade).toBe('');
expect(s.comments).toEqual([]);
});
it('keeps a row that has a user id even without a submission id', () => {
const rows = parseSubmissions([{ user_id: 900, workflow_state: 'unsubmitted' }, {}]);
expect(rows).toHaveLength(1);
expect(rows[0].userId).toBe(900);
});
});
describe('parse: discussions', () => {
it('reads title, message, and the announcement flag', () => {
const rows = parseDiscussions([
{ id: 10, title: 'Week 1 discussion', message: '<p>Introduce yourself.</p>', posted_at: '2026-09-01T00:00:00Z' },
{ id: 11, title: 'Welcome', message: '<p>Hi all</p>', is_announcement: true },
]);
expect(rows).toHaveLength(2);
expect(rows[0].title).toBe('Week 1 discussion');
expect(rows[0].isAnnouncement).toBe(false);
expect(rows[1].isAnnouncement).toBe(true);
});
});
describe('parse: pages', () => {
it('reads a page detail with its body', () => {
const p = parsePage({ page_id: 7, url: 'week-1-intro', title: 'Week 1 Intro', body: '<p>Read chapter 1.</p>', updated_at: '2026-09-01T00:00:00Z' });
expect(p).toEqual({ pageId: 7, url: 'week-1-intro', title: 'Week 1 Intro', body: '<p>Read chapter 1.</p>', updatedAt: '2026-09-01T00:00:00Z' });
});
it('keeps a list row with a url even without a page_id', () => {
const rows = parsePages([{ url: 'syllabus', title: 'Syllabus' }, { title: 'no url or id' }]);
expect(rows).toHaveLength(1);
expect(rows[0].url).toBe('syllabus');
});
});
describe('parse: modules', () => {
it('reads modules with inlined items', () => {
const mods = parseModules([
{
id: 20,
name: 'Cells',
position: 1,
items: [
{ id: 1, title: 'Intro page', type: 'Page', position: 1 },
{ id: 2, title: 'Lab Report 1', type: 'Assignment', position: 2 },
],
},
]);
expect(mods[0].name).toBe('Cells');
expect(mods[0].items).toHaveLength(2);
expect(mods[0].items[1]).toEqual({ id: 2, title: 'Lab Report 1', type: 'Assignment', position: 2 });
});
it('tolerates a module with no items', () => {
expect(parseModules([{ id: 1, name: 'Empty' }])[0].items).toEqual([]);
});
});
describe('parse: enrollments', () => {
it('reads the person, role, type, and state', () => {
const rows = parseEnrollments([
{ id: 30, user_id: 900, user: { name: 'Sam Student' }, type: 'StudentEnrollment', role: 'StudentEnrollment', enrollment_state: 'active' },
]);
expect(rows[0]).toEqual({
id: 30,
userId: 900,
userName: 'Sam Student',
type: 'StudentEnrollment',
role: 'StudentEnrollment',
state: 'active',
});
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node"],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/**/*.test.ts'],
environment: 'node',
},
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/cards",
"version": "0.1.0",
"version": "1.0.0",
"description": "One canonical panel spec, three host card formats — Slack Block Kit, Microsoft Teams Adaptive Cards, and Google Workspace CardService — for Hanzo card-host chat surfaces.",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
+11 -3
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/clio",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI inside Clio — summarize matters, draft correspondence, extract key dates & obligations, and write the output back as a Clio note or activity. Model calls route through the api.hanzo.ai gateway; Clio access via OAuth2 + REST v4.",
"private": true,
"type": "module",
"scripts": {
"build": "node build.js",
@@ -20,5 +19,14 @@
"engines": {
"node": ">=18.0.0"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/app.js"
}
+11 -3
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/desktop",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI desktop app — the ambient omnipresence layer. A cross-platform (macOS/Windows/Linux) menubar/tray app with a global hotkey that pops a Hanzo assistant over any app: ask, summarize the clipboard, rewrite, explain, translate, and fix grammar, wired to the api.hanzo.ai gateway via the published @hanzo/ai. Built on Tauri v2.",
"private": true,
"type": "module",
"scripts": {
"build": "node build.js",
@@ -46,5 +45,14 @@
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/desktop"
}
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/app.js"
}
+12 -4
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/docusign",
"version": "0.1.0",
"description": "Hanzo AI for DocuSign \u2014 AI over agreements and envelopes: summarize, extract key terms, risk-flag clauses, and draft memos. An Extension App panel plus a Connect webhook that auto-summarizes completed envelopes, built on @hanzo/ai and @hanzo/iam over the api.hanzo.ai gateway.",
"private": true,
"version": "1.0.0",
"description": "Hanzo AI for DocuSign AI over agreements and envelopes: summarize, extract key terms, risk-flag clauses, and draft memos. An Extension App panel plus a Connect webhook that auto-summarizes completed envelopes, built on @hanzo/ai and @hanzo/iam over the api.hanzo.ai gateway.",
"type": "module",
"scripts": {
"build": "node build.js",
@@ -40,5 +39,14 @@
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/docusign"
}
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/server.js"
}
+9 -1
View File
@@ -10,5 +10,13 @@
"devDependencies": {
"archiver": "^7.0.1"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"server.js",
"manifest.json",
"icon.png"
]
}
+105
View File
@@ -0,0 +1,105 @@
// Build the Epic SMART-on-FHIR app into dist/: bundle the SPA (app.ts, browser)
// and the OAuth + FHIR-proxy service (server.ts, node), copy the static
// HTML/CSS/assets.
//
// node build.js → production (base https://epic.hanzo.ai)
// HANZO_EPIC_BASE=http://localhost:8791 node build.js → local dev
//
// The SMART app's PUBLIC client_id + redirect + a default FHIR base (for
// standalone launch) are stamped into the SPA via esbuild `define`. The
// client_id is public; the SECRET (confidential apps) is read from the
// environment by the running server, NEVER bundled — a bundled secret would ship
// to every browser.
import esbuild from 'esbuild';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const BASE = (process.env.HANZO_EPIC_BASE || 'https://epic.hanzo.ai').replace(/\/+$/, '');
const SMART_CLIENT_ID = process.env.SMART_CLIENT_ID || '';
const SMART_REDIRECT_URI = process.env.SMART_REDIRECT_URI || `${BASE}/oauth/callback`;
// Optional default FHIR base for STANDALONE launch (e.g. Epic's public sandbox).
// In an EHR launch the real `iss` arrives in the URL and overrides this.
const SMART_DEFAULT_ISS = process.env.SMART_DEFAULT_ISS || '';
const watch = process.argv.includes('--watch');
const root = path.dirname(fileURLToPath(import.meta.url));
const src = path.join(root, 'src');
const dist = path.join(root, 'dist');
async function build() {
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist, { recursive: true });
// The browser SPA — public client_id/redirect/default-iss stamped via define.
// Secrets are NOT define-able here; server.ts reads them from process.env.
const spa = await esbuild.context({
entryPoints: [path.join(src, 'app.ts')],
outfile: path.join(dist, 'app.js'),
bundle: true,
format: 'iife',
platform: 'browser',
target: ['chrome90', 'edge90', 'safari14', 'firefox90'],
sourcemap: true,
minify: !watch,
define: {
SMART_CLIENT_ID: JSON.stringify(SMART_CLIENT_ID),
SMART_REDIRECT_URI: JSON.stringify(SMART_REDIRECT_URI),
SMART_DEFAULT_ISS: JSON.stringify(SMART_DEFAULT_ISS),
},
logLevel: 'info',
});
await spa.rebuild();
// The OAuth + FHIR-proxy service — a Node ESM bundle. No secrets baked in; it
// reads SMART_CLIENT_SECRET etc. from the environment when it runs.
const server = await esbuild.context({
entryPoints: [path.join(src, 'server.ts')],
outfile: path.join(dist, 'server.js'),
bundle: true,
format: 'esm',
platform: 'node',
target: ['node18'],
sourcemap: true,
minify: !watch,
banner: { js: '// Hanzo Epic SMART-on-FHIR service — run: node server.js' },
logLevel: 'info',
});
await server.rebuild();
// Static files.
for (const f of ['index.html', 'styles.css']) {
fs.copyFileSync(path.join(src, f), path.join(dist, f));
}
// assets/ (icons) — create the dir even if empty.
const assetsSrc = path.join(root, 'assets');
const assetsDst = path.join(dist, 'assets');
fs.mkdirSync(assetsDst, { recursive: true });
if (fs.existsSync(assetsSrc)) {
for (const f of fs.readdirSync(assetsSrc)) {
fs.copyFileSync(path.join(assetsSrc, f), path.join(assetsDst, f));
}
}
console.log(`✅ Epic SMART-on-FHIR app built → dist/ (base ${BASE})`);
console.log(' Serve dist/{index.html,app.js,styles.css,assets} as static; run dist/server.js for /oauth/* + /fhir.');
if (!SMART_CLIENT_ID) {
console.log(' ⚠ SMART_CLIENT_ID not set — set it (and SMART_CLIENT_SECRET on the server for a confidential app) before deploy.');
}
if (watch) {
await spa.watch();
await server.watch();
console.log('👀 watching…');
} else {
await spa.dispose();
await server.dispose();
}
}
build().catch((e) => {
console.error(e);
process.exit(1);
});
+53
View File
@@ -0,0 +1,53 @@
{
"name": "@hanzo/epic",
"version": "1.0.0",
"description": "Hanzo AI for Epic (SMART on FHIR) — brings Hanzo AI into the clinician's EHR workflow. Reads the launched patient's chart over FHIR R4 (problems, meds, allergies, labs, notes) and assists: summarize the patient, draft a SOAP note, extract problems & meds, and ask about the patient. Read + assist only (no clinical write-back in v1). Model calls route through the api.hanzo.ai gateway via @hanzo/ai; SMART-on-FHIR OAuth2 (auth-code + PKCE) with server-side token exchange; PHI-bearing tokens stay server-side.",
"type": "module",
"scripts": {
"build": "node build.js",
"watch": "node build.js --watch",
"serve": "node dist/server.js",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@hanzo/ai": "^0.2.0",
"@hanzo/iam": "0.13.2"
},
"devDependencies": {
"@types/node": "^20.14.0",
"esbuild": "^0.25.8",
"typescript": "^5.8.3",
"vitest": "^3.2.6"
},
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"hanzo",
"epic",
"smart-on-fhir",
"fhir",
"ehr",
"healthcare",
"clinical",
"ai",
"hipaa"
],
"author": "Hanzo AI",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/epic"
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/app.js"
}
+343
View File
@@ -0,0 +1,343 @@
// The SMART app panel glue: the browser page that launches from Epic with a
// patient in context, loads that patient's chart through the server-side FHIR
// proxy (so no PHI token touches the browser), and drives the four Hanzo AI
// actions over the assembled chart. All the logic-heavy work — SMART/PKCE
// shaping, FHIR request wrappers, chart assembly, action prompts — lives in its
// own tested pure modules; this file is the one impure, browser-only entry point
// that binds them to the DOM.
//
// The launch dance (see README for the full flow):
// 1. EHR launch: Epic opens this page with `iss` + `launch`. Standalone: the
// page is opened with an `iss` (or the sandbox default) and no `launch`.
// 2. The page mints PKCE + state, asks the server (/oauth/prepare) to discover
// Epic's authorize/token endpoints, then redirects the browser to authorize.
// 3. Epic redirects back to /oauth/callback?code&state; the page posts them to
// the server, which exchanges (secret + PKCE server-side) and sets an opaque
// session cookie. The browser learns only the patient id + granted scope.
// 4. The page loads the chart via /fhir?path=… (proxied), assembles the
// context, and runs actions against api.hanzo.ai with the pasted Hanzo key.
//
// These build-time constants are stamped by build.js (the client id + redirect
// are PUBLIC; the secret is server-only and never bundled).
declare const SMART_CLIENT_ID: string;
declare const SMART_REDIRECT_URI: string;
declare const SMART_DEFAULT_ISS: string;
import {
createPkce,
authorizeUrl,
parseLaunch,
parseCallback,
} from './smart-oauth.js';
import {
getPatient,
searchConditions,
searchMedicationRequests,
searchAllergyIntolerances,
searchObservations,
searchDocumentReferences,
bundleEntries,
fetchAllPages,
type FhirResource,
type FhirRequest,
} from './fhir-client.js';
import { assembleChartContext, chartIsEmpty, emptyChart, type Chart } from './chart.js';
import { ACTIONS, isActionId, runAction, listModels } from './hanzo.js';
import { scopeString } from './config.js';
import { getApiKey, setApiKey, bearer, validateKey } from './auth.js';
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const STATE_KEY = 'hanzo.epic.oauthState';
const VERIFIER_KEY = 'hanzo.epic.pkceVerifier';
// The panel's live SMART context (non-PHI parts) once authenticated.
interface Session {
patient: string;
scope: string;
}
let controller: AbortController | null = null;
let session: Session | null = null;
let chartContext = '';
window.addEventListener('DOMContentLoaded', () => void boot());
// boot decides which phase of the launch we are in: a callback (we have a code),
// a launch (we have iss/launch — start authorize), or a cold open (show the
// standalone launcher). Then wires the UI.
async function boot(): Promise<void> {
wireApiKey();
wireActions();
void populateModels();
const search = window.location.search;
const cb = parseCallback(search);
const launch = parseLaunch(search);
if (cb.error) {
status(`Launch declined: ${cb.errorDescription || cb.error}`, 'error');
return;
}
if (cb.code) {
await completeCallback(cb.code, cb.state);
return;
}
if (launch.iss || SMART_DEFAULT_ISS) {
await beginAuthorize(launch.iss || SMART_DEFAULT_ISS, launch.launch);
return;
}
status('Open this app from Epic, or configure a FHIR server to launch standalone.', 'warn');
}
// beginAuthorize mints PKCE + state, asks the server to discover Epic's
// endpoints, stores the verifier/state, and redirects the browser to authorize.
async function beginAuthorize(iss: string, launchToken: string): Promise<void> {
status('Connecting to the EHR…');
const pkce = await createPkce();
const state = crypto.randomUUID();
sessionStorage.setItem(STATE_KEY, state);
sessionStorage.setItem(VERIFIER_KEY, pkce.verifier);
const prep = await postJson('/oauth/prepare', { iss, state, codeVerifier: pkce.verifier });
if (!prep.authorizationEndpoint) {
status('Could not discover the EHR OAuth endpoints.', 'error');
return;
}
window.location.href = authorizeUrl({
authorizationEndpoint: prep.authorizationEndpoint,
clientId: SMART_CLIENT_ID,
redirectUri: SMART_REDIRECT_URI,
aud: iss,
scope: scopeString(),
state,
codeChallenge: pkce.challenge,
launch: launchToken || undefined,
});
}
// completeCallback verifies state, posts code+state to the server (which does
// the secret+PKCE exchange and sets the session cookie), then loads the chart.
async function completeCallback(code: string, returnedState: string): Promise<void> {
const expected = sessionStorage.getItem(STATE_KEY) || '';
if (!expected || returnedState !== expected) {
status('OAuth state mismatch — refusing to continue.', 'error');
return;
}
sessionStorage.removeItem(STATE_KEY);
sessionStorage.removeItem(VERIFIER_KEY);
status('Completing sign-in…');
const out = await postJson('/oauth/callback', { code, state: returnedState });
if (out.error || !out.patient) {
status(`Sign-in failed: ${out.error || 'no patient context'}`, 'error');
return;
}
// Clean the code/state out of the URL bar (never leave an auth code in history).
window.history.replaceState({}, document.title, window.location.pathname);
session = { patient: out.patient, scope: out.scope || '' };
await loadChart();
}
// loadChart pulls the launched patient's chart through the proxy and assembles
// the clinical context. Every FHIR read goes through /fhir — the browser never
// holds the FHIR token. Reads run concurrently; each is independent.
async function loadChart(): Promise<void> {
if (!session) return;
status('Loading patient chart…');
const patientId = session.patient;
// The FHIR base/token live server-side; the request wrappers here shape a
// RELATIVE path the proxy resolves. token/base are placeholders the proxy
// replaces, so we pass empty strings and send only the resolved path.
const rel = (req: FhirRequest) => proxyPath(req.url);
const chart: Chart = emptyChart();
try {
const [patient, conditions, meds, allergies, obs, docs] = await Promise.all([
proxyGet(rel(getPatient('', '', patientId))),
proxyGetAll(searchConditions(sp(patientId))),
proxyGetAll(searchMedicationRequests(sp(patientId))),
proxyGetAll(searchAllergyIntolerances(sp(patientId))),
proxyGetAll(searchObservations(sp(patientId))),
proxyGetAll(searchDocumentReferences(sp(patientId))),
]);
chart.patient = (patient as FhirResource)?.resourceType === 'Patient' ? (patient as FhirResource) : undefined;
chart.conditions = conditions;
chart.medications = meds;
chart.allergies = allergies;
chart.observations = obs;
chart.documents = docs;
} catch (e: unknown) {
status(`Could not load the chart: ${(e as Error).message}`, 'error');
return;
}
chartContext = assembleChartContext(chart);
const label = chart.patient
? summarizeHeader(chart.patient)
: `Patient ${patientId}`;
$('patient-title').textContent = label;
status(chartIsEmpty(chart) ? 'Chart loaded (no clinical data recorded).' : 'Chart loaded.', 'ok');
setActionsEnabled(true);
}
// sp builds a patient-scoped SearchParams with empty base/token — the proxy
// supplies both. Only the relative path matters here.
function sp(patientId: string) {
return { base: '', token: '', patientId };
}
// proxyPath turns a FHIR request URL (which the wrappers built with an empty
// base, so it is like `/Condition?patient=…`) into the proxy query. The wrappers
// prepend the normalized base; with an empty base the URL is just the path.
function proxyPath(fhirUrl: string): string {
const path = fhirUrl.replace(/^\/+/, '');
return `/fhir?path=${encodeURIComponent(path)}`;
}
// proxyGet does one proxied FHIR read and returns the parsed resource/Bundle.
async function proxyGet(path: string): Promise<unknown> {
const resp = await fetch(path, { credentials: 'same-origin' });
if (!resp.ok) throw new Error(`FHIR proxy ${resp.status}`);
return resp.json();
}
// proxyGetAll pages a search to completion through the proxy, following the
// Bundle `next` links (rewritten as proxy paths). Returns the flattened
// resources. Uses fetchAllPages' Bundle logic via a proxy-backed fetch.
async function proxyGetAll(first: FhirRequest): Promise<FhirResource[]> {
const doFetch: typeof fetch = async (input) => {
const raw = typeof input === 'string' ? input : (input as Request).url;
// `raw` is either our first relative path or an absolute FHIR `next` URL;
// both go through the proxy by path.
return fetch(proxyPath(raw), { credentials: 'same-origin' }) as Promise<Response>;
};
return fetchAllPages({ ...first, url: first.url.replace(/^\/+/, '') }, '', { doFetch });
}
// summarizeHeader renders a short patient label for the panel header from a
// Patient resource (name only — the sensitive detail stays in the chart body).
function summarizeHeader(patient: FhirResource): string {
const p = patient as { name?: Array<{ text?: string; given?: string[]; family?: string }> };
const n = Array.isArray(p.name) ? p.name[0] : undefined;
if (n?.text) return n.text;
const given = Array.isArray(n?.given) ? n!.given!.join(' ') : '';
return `${given} ${n?.family ?? ''}`.trim() || 'Patient';
}
// ── Actions ────────────────────────────────────────────────────────────────
function wireActions(): void {
const chipRow = $('chips');
for (const a of ACTIONS) {
const b = document.createElement('button');
b.className = 'chip';
b.textContent = a.label;
b.dataset.action = a.id;
b.disabled = true;
b.onclick = () => void run(a.id);
chipRow.appendChild(b);
}
$<HTMLButtonElement>('stop').onclick = () => controller?.abort();
}
function setActionsEnabled(on: boolean): void {
for (const el of document.querySelectorAll<HTMLButtonElement>('.chip')) el.disabled = !on;
}
// run executes one action over the assembled chart context. Requires a loaded
// chart; a prompt-taking action reads the detail box.
async function run(id: string): Promise<void> {
if (!isActionId(id)) return;
if (!chartContext) {
status('Load a patient chart first (launch from Epic).', 'warn');
return;
}
const def = ACTIONS.find((a) => a.id === id)!;
const detail = $<HTMLTextAreaElement>('prompt').value.trim();
if (def.needsPrompt && id === 'ask' && !detail) {
status('Type a question about this patient.', 'warn');
return;
}
controller?.abort();
controller = new AbortController();
const outputEl = $<HTMLTextAreaElement>('output');
outputEl.value = '';
status(`Running “${def.label}”…`);
$<HTMLButtonElement>('stop').disabled = false;
setActionsEnabled(false);
const model = $<HTMLSelectElement>('model').value || undefined;
try {
const text = await runAction({
id,
detail,
chartContext,
opts: { token: bearer(), model, signal: controller.signal },
});
outputEl.value = text;
status('Done. Review before use — decision support, not a diagnosis.', 'ok');
} catch (e: unknown) {
if ((e as Error).name === 'AbortError') status('Stopped.', 'warn');
else status(`Error: ${(e as Error).message}`, 'error');
} finally {
$<HTMLButtonElement>('stop').disabled = true;
setActionsEnabled(true);
}
}
// ── Hanzo key + models ─────────────────────────────────────────────────────
function wireApiKey(): void {
const apiKeyEl = $<HTMLInputElement>('apikey');
apiKeyEl.value = getApiKey();
$<HTMLButtonElement>('savekey').onclick = async () => {
const key = apiKeyEl.value.trim();
try {
const models = await validateKey(key);
setApiKey(key);
fillModels(models);
status('Hanzo API key saved.', 'ok');
} catch (e: unknown) {
status(`Key rejected: ${(e as Error).message}`, 'error');
}
};
}
async function populateModels(): Promise<void> {
try {
fillModels(await listModels({ token: bearer() }));
} catch {
/* anonymous / offline — the picker stays with its default option */
}
}
function fillModels(ids: string[]): void {
const sel = $<HTMLSelectElement>('model');
const current = sel.value;
sel.innerHTML = '';
for (const id of ids) {
const o = document.createElement('option');
o.value = id;
o.textContent = id;
sel.appendChild(o);
}
if (current && ids.includes(current)) sel.value = current;
}
// ── Small helpers ──────────────────────────────────────────────────────────
async function postJson(path: string, body: unknown): Promise<any> {
const resp = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(body),
});
return resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
}
function status(msg: string, kind: '' | 'ok' | 'warn' | 'error' = ''): void {
const el = $('status');
el.textContent = msg;
el.className = `status${kind ? ` ${kind}` : ''}`;
}
// Re-export a couple of pure helpers the panel uses so the module boundary is
// explicit (and so a smoke test can import this file under a DOM shim if needed).
export { bundleEntries };
+51
View File
@@ -0,0 +1,51 @@
// The HANZO-gateway credential for the web panel — the zero-setup pasted-key
// path. This is ONLY the Hanzo model-gateway bearer (an `hk-…` key or an IAM
// token); it is emphatically NOT the FHIR/PHI token. The FHIR access token lives
// server-side (server.ts) and is never handled here — the panel holds only the
// opaque server session cookie for FHIR reads. So a leaked localStorage key
// exposes a Hanzo gateway key, never PHI.
//
// Mirrors @hanzo/docusign / @hanzo/pdf exactly (one way to hold a Hanzo key): a
// key pasted into the panel, validated by a real /v1/models call so a bad key is
// rejected at paste time.
import { APIKEY_STORAGE_KEY, pickBearer } from './config.js';
import { listModels } from './hanzo.js';
export function getApiKey(): string {
try {
return localStorage.getItem(APIKEY_STORAGE_KEY) || '';
} catch {
return '';
}
}
export function setApiKey(key: string): void {
try {
const k = key.trim();
if (k) localStorage.setItem(APIKEY_STORAGE_KEY, k);
else localStorage.removeItem(APIKEY_STORAGE_KEY);
} catch {
/* private-mode / storage disabled — the in-memory key still works this session */
}
}
export function hasApiKey(): boolean {
return !!getApiKey();
}
// bearer is the credential the chat call sends to the HANZO gateway: the pasted
// key, else empty (anonymous public models). When Hanzo IAM OAuth lands it slots
// in as the second argument to pickBearer with no change to callers.
export function bearer(): string {
return pickBearer(getApiKey(), '');
}
// validateKey confirms a pasted key works by listing models with it. Returns the
// model ids on success so the caller populates the picker in one round-trip;
// throws with the gateway's message on failure. Empty key → clear message.
export async function validateKey(key: string): Promise<string[]> {
const k = key.trim();
if (!k) throw new Error('Enter a Hanzo API key (hk-…).');
return listModels({ token: k });
}
+290
View File
@@ -0,0 +1,290 @@
// Turning raw FHIR R4 resources into the clinical-context TEXT handed to Hanzo —
// PURE and fully unit-tested (no network, no DOM, no @hanzo/ai). This is the
// clinical-reasoning core: it reads the messy, deeply-nested FHIR shapes
// (CodeableConcepts, references, effective[x] polymorphism) and renders a
// compact, honest, human-readable chart that a model can reason over and a
// clinician can eyeball.
//
// Two responsibilities, kept separate:
// 1. per-resource extraction — one small pure function per resource type that
// pulls the clinically-relevant fields into a flat, display-ready row.
// 2. assembly + windowing — compose the sections into a single string capped
// at a character budget, truncating VISIBLY (never silently) and section by
// section so the most important sections (problems, meds, allergies)
// survive when a chart is huge.
//
// The model's context window is finite and a real chart can be enormous, so we
// window honestly: cap each section's row count and the whole assembled text,
// and mark every truncation so the model — and the reviewing clinician — know
// what was elided.
import type { FhirResource } from './fhir-client.js';
// ── FHIR primitive extractors (pure) ───────────────────────────────────────
// codeableText renders a FHIR CodeableConcept to a display string: prefer its
// `text`, else the first coding's `display`, else the first coding's `code`.
// This is the single place the CodeableConcept shape is decoded, so every
// section reads a code the same way. Pure.
export function codeableText(concept: unknown): string {
const c = concept as {
text?: unknown;
coding?: Array<{ display?: unknown; code?: unknown }>;
};
if (typeof c?.text === 'string' && c.text.trim()) return c.text.trim();
const coding = Array.isArray(c?.coding) ? c.coding[0] : undefined;
if (typeof coding?.display === 'string' && coding.display.trim()) return coding.display.trim();
if (typeof coding?.code === 'string' && coding.code.trim()) return coding.code.trim();
return '';
}
// effectiveDate pulls the clinically-relevant date off a resource's polymorphic
// effective[x]/onset[x]/authoredOn/recordedDate, tolerating the several field
// names FHIR uses across resource types. Returns '' when none is present. Pure.
export function effectiveDate(res: FhirResource): string {
const r = res as Record<string, unknown>;
const period = r.effectivePeriod as { start?: unknown } | undefined;
const candidates = [
r.effectiveDateTime,
period?.start,
r.onsetDateTime,
r.authoredOn,
r.recordedDate,
r.issued,
];
for (const v of candidates) {
if (typeof v === 'string' && v.trim()) return v.trim();
}
return '';
}
// ── Per-resource rows (pure) ───────────────────────────────────────────────
// summarizePatient renders a Patient into the demographic header lines. Reads
// the R4 name/gender/birthDate. Uses the FIRST official/usual name. Pure.
export function summarizePatient(patient: FhirResource | undefined): string[] {
if (!patient) return [];
const p = patient as {
name?: Array<{ text?: string; given?: string[]; family?: string; use?: string }>;
gender?: string;
birthDate?: string;
};
const lines: string[] = [];
const name = pickName(p.name);
if (name) lines.push(`Name: ${name}`);
if (typeof p.gender === 'string' && p.gender) lines.push(`Sex: ${p.gender}`);
if (typeof p.birthDate === 'string' && p.birthDate) lines.push(`DOB: ${p.birthDate}`);
return lines;
}
// pickName renders a HumanName[]: prefer a `text`, else "Given Family" from the
// first name that has parts. Pure.
function pickName(names: Array<{ text?: string; given?: string[]; family?: string }> | undefined): string {
if (!Array.isArray(names)) return '';
for (const n of names) {
if (typeof n.text === 'string' && n.text.trim()) return n.text.trim();
const given = Array.isArray(n.given) ? n.given.join(' ') : '';
const full = `${given} ${n.family ?? ''}`.trim();
if (full) return full;
}
return '';
}
// conditionRow renders a Condition (problem) to one line: its name, clinical
// status, and onset date. Pure.
export function conditionRow(res: FhirResource): string {
const r = res as { clinicalStatus?: unknown };
const name = codeableText((res as { code?: unknown }).code) || 'Unnamed condition';
const status = codeableText(r.clinicalStatus);
const onset = effectiveDate(res);
return joinRow([name, status && `(${status})`, onset && `onset ${onset}`]);
}
// medicationRow renders a MedicationRequest to one line: the drug (from
// medicationCodeableConcept, or the display of a contained/referenced
// Medication), status, and dosage text when present. Pure.
export function medicationRow(res: FhirResource): string {
const r = res as {
medicationCodeableConcept?: unknown;
medicationReference?: { display?: string };
status?: string;
dosageInstruction?: Array<{ text?: string }>;
};
const drug =
codeableText(r.medicationCodeableConcept) ||
(typeof r.medicationReference?.display === 'string' ? r.medicationReference.display : '') ||
'Unnamed medication';
const status = typeof r.status === 'string' ? r.status : '';
const dosage = Array.isArray(r.dosageInstruction)
? (r.dosageInstruction.find((d) => typeof d.text === 'string' && d.text)?.text ?? '')
: '';
return joinRow([drug, dosage && `${dosage}`, status && `(${status})`]);
}
// allergyRow renders an AllergyIntolerance to one line: the substance, clinical
// status, criticality, and the first reaction's manifestation when present.
// Pure.
export function allergyRow(res: FhirResource): string {
const r = res as {
clinicalStatus?: unknown;
criticality?: string;
reaction?: Array<{ manifestation?: unknown[] }>;
};
const substance = codeableText((res as { code?: unknown }).code) || 'Unknown allergen';
const status = codeableText(r.clinicalStatus);
const criticality = typeof r.criticality === 'string' ? r.criticality : '';
const manifestation =
Array.isArray(r.reaction) && Array.isArray(r.reaction[0]?.manifestation)
? codeableText(r.reaction[0]!.manifestation![0])
: '';
return joinRow([
substance,
manifestation && `${manifestation}`,
criticality && `[${criticality}]`,
status && `(${status})`,
]);
}
// observationRow renders an Observation (lab/vital) to one line: the test name,
// the value (valueQuantity with unit, or valueCodeableConcept / valueString),
// and the date. Pure.
export function observationRow(res: FhirResource): string {
const name = codeableText((res as { code?: unknown }).code) || 'Observation';
const value = observationValue(res);
const date = effectiveDate(res);
return joinRow([name, value && `= ${value}`, date && `(${date})`]);
}
// observationValue decodes an Observation's polymorphic value[x]: a
// valueQuantity ("7.2 mg/dL"), a valueCodeableConcept, or a valueString. Pure.
export function observationValue(res: FhirResource): string {
const r = res as {
valueQuantity?: { value?: unknown; unit?: unknown };
valueCodeableConcept?: unknown;
valueString?: unknown;
};
if (r.valueQuantity && r.valueQuantity.value !== undefined) {
const v = r.valueQuantity.value;
const unit = typeof r.valueQuantity.unit === 'string' ? r.valueQuantity.unit : '';
return unit ? `${v} ${unit}` : String(v);
}
const coded = codeableText(r.valueCodeableConcept);
if (coded) return coded;
if (typeof r.valueString === 'string' && r.valueString.trim()) return r.valueString.trim();
return '';
}
// documentRow renders a DocumentReference to one line: its type/description and
// date. The note BYTES are not inlined here (they may be large binaries or
// attachments requiring a separate fetch); the model gets the note's existence,
// type, and date so it can reference it honestly. Pure.
export function documentRow(res: FhirResource): string {
const r = res as { type?: unknown; description?: string; date?: string };
const type = codeableText(r.type) || (typeof r.description === 'string' ? r.description : '') || 'Clinical note';
const date = typeof r.date === 'string' ? r.date : effectiveDate(res);
return joinRow([type, date && `(${date})`]);
}
// joinRow joins the non-empty cells of a row with single spaces. Pure — the
// per-resource rows all funnel through it so falsy cells never leave gaps.
function joinRow(cells: Array<string | false | undefined>): string {
return cells.filter((c): c is string => typeof c === 'string' && c.length > 0).join(' ');
}
// ── The assembled chart ────────────────────────────────────────────────────
// A patient's chart as this app consumes it — the Patient plus the four/five
// resource lists pulled via the FHIR client. Any list may be empty.
export interface Chart {
patient?: FhirResource;
conditions: FhirResource[];
medications: FhirResource[];
allergies: FhirResource[];
observations: FhirResource[];
documents: FhirResource[];
}
// emptyChart — a zero-value Chart, so callers can build incrementally. Pure.
export function emptyChart(): Chart {
return { conditions: [], medications: [], allergies: [], observations: [], documents: [] };
}
// Windowing budgets. Per-section row caps keep any one section (e.g. hundreds of
// lab results) from crowding out the problem list; the total char cap fits the
// assembled chart into a model window alongside the response. Chosen honest, not
// optimal — we truncate VISIBLY.
export const MAX_ROWS_PER_SECTION = 40;
export const MAX_CONTEXT_CHARS = 48_000;
// A section: a heading, the resources, and the row renderer. Ordered most- to
// least- clinically-critical so truncation drops the least important first.
interface Section {
heading: string;
resources: FhirResource[];
row: (r: FhirResource) => string;
}
// renderSection renders one section's heading + capped rows. When the section has
// more resources than the cap, it appends a visible "…N more" line so the model
// knows the list was truncated. Empty sections render a single "none recorded"
// line so their ABSENCE is explicit (a blank problem list is clinically
// meaningful — don't let the model assume data was withheld). Pure.
export function renderSection(s: Section, maxRows = MAX_ROWS_PER_SECTION): string {
const lines: string[] = [`## ${s.heading}`];
if (s.resources.length === 0) {
lines.push('(none recorded)');
return lines.join('\n');
}
const shown = s.resources.slice(0, maxRows);
for (const r of shown) {
const row = s.row(r);
if (row) lines.push(`- ${row}`);
}
const extra = s.resources.length - shown.length;
if (extra > 0) lines.push(`- …and ${extra} more not shown`);
return lines.join('\n');
}
// assembleChartContext renders a Chart into the single clinical-context string
// handed to Hanzo. Demographics first, then the sections in clinical priority
// order; the whole thing is capped at `maxChars` with a VISIBLE truncation
// marker. Pure and deterministic — the exact text a test asserts is the exact
// text sent to the model. Contains PHI: it is assembled in memory and sent ONLY
// to api.hanzo.ai (never logged).
export function assembleChartContext(chart: Chart, maxChars = MAX_CONTEXT_CHARS): string {
const blocks: string[] = [];
const demo = summarizePatient(chart.patient);
blocks.push(['# Patient', ...(demo.length ? demo : ['(no demographics available)'])].join('\n'));
const sections: Section[] = [
{ heading: 'Problems', resources: chart.conditions, row: conditionRow },
{ heading: 'Medications', resources: chart.medications, row: medicationRow },
{ heading: 'Allergies', resources: chart.allergies, row: allergyRow },
{ heading: 'Recent labs & vitals', resources: chart.observations, row: observationRow },
{ heading: 'Clinical notes', resources: chart.documents, row: documentRow },
];
for (const s of sections) blocks.push(renderSection(s));
return truncate(blocks.join('\n\n'), maxChars);
}
// truncate cuts text to a max length, appending a visible marker so the model
// (and a reviewing clinician) know content was elided. Pure.
export function truncate(text: string, max: number): string {
if (text.length <= max) return text;
return text.slice(0, max) + `\n…[chart truncated: ${text.length - max} chars omitted]`;
}
// chartIsEmpty reports whether a chart has NOTHING beyond possibly a Patient —
// so the UI can say "no clinical data for this patient" instead of asking the
// model to summarize a blank chart. Pure.
export function chartIsEmpty(chart: Chart): boolean {
return (
chart.conditions.length === 0 &&
chart.medications.length === 0 &&
chart.allergies.length === 0 &&
chart.observations.length === 0 &&
chart.documents.length === 0
);
}
+106
View File
@@ -0,0 +1,106 @@
// Epic / SMART-on-FHIR config — the two backends this app talks to and nothing
// else. Hanzo (the model gateway, api.hanzo.ai/v1, via @hanzo/ai) and the FHIR
// server (Epic or any SMART-on-FHIR EHR), whose OAuth + REST endpoints are
// DISCOVERED at runtime from the launch `iss` — never hard-coded, because a
// SMART app must run against whatever FHIR server launched it (an Epic org, the
// fhir.epic.com sandbox, or a non-Epic EHR).
//
// Rule: no `/api/` prefix on Hanzo (it IS api.hanzo.ai); the FHIR base comes
// from `iss`, appended with `/Patient`, `/Condition`, etc. Secrets never live
// here — the SMART app's client_secret (confidential apps) is read from the
// environment by server.ts, never bundled and never sent to the browser.
// ── Hanzo model gateway ───────────────────────────────────────────────────
// Where the Hanzo model gateway lives. `@hanzo/ai` defaults here too. /v1 only,
// never an /api/ prefix (api.hanzo.ai IS the api host).
export const HANZO_API_BASE_URL = 'https://api.hanzo.ai';
// Default model. A Zen model (qwen3+). Overridable per-request via the picker;
// the gateway routes it.
export const DEFAULT_MODEL = 'zen5';
// localStorage key for the pasted Hanzo API key (`hk-…`) in the web panel. The
// SMART app launches as a static web page (iframe/browser), not an EHR host with
// server-side storage, so the zero-setup Hanzo credential lives in localStorage —
// same as @hanzo/pdf and @hanzo/docusign. NOTE: this is the HANZO gateway key,
// NOT the FHIR/PHI token — the FHIR token stays server-side (see server.ts).
export const APIKEY_STORAGE_KEY = 'hanzo.epic.apiKey';
// pickBearer chooses the credential to send to the Hanzo gateway: a pasted API
// key wins over an IAM token (an explicit key is a deliberate override), else
// the token, else empty (anonymous — the gateway still serves public models).
// Pure — unit-tested.
export function pickBearer(apiKey: string, iamToken: string): string {
return (apiKey && apiKey.trim()) || (iamToken && iamToken.trim()) || '';
}
// ── SMART on FHIR ──────────────────────────────────────────────────────────
//
// SMART scopes this app requests. It is READ + ASSIST ONLY in v1 — there is NO
// `*.write` scope, so a bug can never mutate a patient's chart. `launch` is for
// the EHR-launch flow (Epic passes a `launch` token that carries the patient
// context); `launch/patient` is the standalone-launch equivalent that asks the
// user to pick a patient. `openid`+`fhirUser` identify the launching clinician;
// `patient/<Resource>.read` grants read of the launched patient's chart only.
//
// Kept as an ordered array so the scope string is deterministic (stable tests,
// stable authorize URLs). `offline_access` requests a refresh_token so a long
// review session survives the access token's ~1h lifetime.
export const SMART_SCOPES = [
'launch',
'launch/patient',
'openid',
'fhirUser',
'offline_access',
'patient/Patient.read',
'patient/Condition.read',
'patient/MedicationRequest.read',
'patient/Observation.read',
'patient/AllergyIntolerance.read',
'patient/DocumentReference.read',
] as const;
// scopeString renders the requested scopes into the space-delimited form the
// SMART authorize endpoint expects. Pure.
export function scopeString(scopes: readonly string[] = SMART_SCOPES): string {
return scopes.join(' ');
}
// The SMART discovery document path. A conformant SMART-on-FHIR server publishes
// its authorize/token endpoints (and capabilities) at
// `<iss>/.well-known/smart-configuration`. We NEVER guess these; we read them.
export const SMART_CONFIG_PATH = '.well-known/smart-configuration';
// smartConfigUrl derives the discovery URL from the FHIR base (`iss`). Trailing
// slashes on `iss` are normalized so the join is exact. Pure.
export function smartConfigUrl(iss: string): string {
return `${normalizeBase(iss)}/${SMART_CONFIG_PATH}`;
}
// normalizeBase strips trailing slashes from a base/iss so callers append
// `/<Resource>` or `/.well-known/...` without doubling the separator. Pure.
export function normalizeBase(base: string): string {
return base.replace(/\/+$/, '');
}
// The Epic App Orchard / sandbox FHIR bases, for documentation + a default in
// standalone launch. In an EHR launch the real `iss` arrives in the URL and
// overrides any default — this table is only a convenience for standalone
// testing against Epic's public sandbox.
export const EPIC_SANDBOX_FHIR_BASE =
'https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4';
// FHIR resource path segments this app reads. Named so the FHIR client and the
// tests reference ONE set of names (no drift between the request builder and the
// scope list above).
export const FHIR_RESOURCES = {
Patient: 'Patient',
Condition: 'Condition',
MedicationRequest: 'MedicationRequest',
Observation: 'Observation',
AllergyIntolerance: 'AllergyIntolerance',
DocumentReference: 'DocumentReference',
} as const;
export type FhirResourceType = keyof typeof FHIR_RESOURCES;
+253
View File
@@ -0,0 +1,253 @@
// FHIR R4 client. Every wrapper is PURE request-shaping — it returns the
// { url, method, headers } a caller will fetch, so the wire contract (path,
// `patient=` scoping, `_count`, category filters) is unit-testable without a
// network. `fhirFetch` at the bottom is the one thin place that actually hits
// the FHIR server; `bundleEntries` / `nextPageUrl` are the pure Bundle helpers
// that drive pagination.
//
// FHIR R4 conventions this encodes:
// - Bearer token auth; Accept: application/fhir+json.
// - A patient-context read scopes EVERY search with `patient=<id>` so the app
// can only ever see the launched patient (defence-in-depth over the
// `patient/*.read` scope — the server enforces it too).
// - A search returns a `Bundle`; its resources are `entry[].resource`, and the
// NEXT page is the `link` whose `relation` is `next` (a full, absolute URL).
// - `_count` caps page size; we never over-fetch.
import { FHIR_RESOURCES, normalizeBase, type FhirResourceType } from './config.js';
export interface FhirRequest {
url: string;
method: 'GET';
headers: Record<string, string>;
}
// baseHeaders — auth + the FHIR JSON accept on every read. Reads only, so no
// content-type. Pure.
function baseHeaders(token: string): Record<string, string> {
return {
Authorization: `Bearer ${token}`,
Accept: 'application/fhir+json',
};
}
// buildQuery renders a query string from a params object, dropping undefined /
// empty values and joining array-valued params with commas (the form FHIR wants
// for multi-valued search params like `category`). Deterministic key order for
// stable tests. Pure.
function buildQuery(params: Record<string, string | number | string[] | undefined>): string {
const q = new URLSearchParams();
for (const key of Object.keys(params)) {
const v = params[key];
if (v === undefined || v === '') continue;
q.set(key, Array.isArray(v) ? v.join(',') : String(v));
}
const s = q.toString();
return s ? `?${s}` : '';
}
// resourceUrl builds `<base>/<ResourceType>` (a search root) or, with an id,
// `<base>/<ResourceType>/<id>` (a single-resource read). Pure.
export function resourceUrl(base: string, type: FhirResourceType, id?: string): string {
const root = `${normalizeBase(base)}/${FHIR_RESOURCES[type]}`;
return id ? `${root}/${encodeURIComponent(id)}` : root;
}
// A sensible default page size. The chart-review actions want breadth, not
// depth; a page of 50 with pagination covers a real patient without a giant
// single response.
export const DEFAULT_COUNT = 50;
// ── Single-patient read ────────────────────────────────────────────────────
// getPatient reads the launched patient by id — `Patient/<id>`. The one FHIR
// read that is NOT a search (it targets the resource directly). Pure.
export function getPatient(base: string, token: string, patientId: string): FhirRequest {
return {
url: resourceUrl(base, 'Patient', patientId),
method: 'GET',
headers: baseHeaders(token),
};
}
// ── Patient-scoped searches ────────────────────────────────────────────────
export interface SearchParams {
base: string;
token: string;
patientId: string;
count?: number;
// A cursor: the full `next` URL from a previous Bundle. When present it is
// used VERBATIM (it already carries the server's opaque paging state) and the
// other params are ignored — that is how FHIR pagination works.
pageUrl?: string;
// Optional resource-specific filters (e.g. Observation category). Merged into
// the query. Values are strings or string[] (comma-joined).
extra?: Record<string, string | string[] | undefined>;
}
// searchRequest is the shared shaper for every patient-scoped search: either the
// verbatim `pageUrl` (pagination) or `<base>/<Type>?patient=<id>&_count=…&…`.
// Every search is scoped by `patient=` — the app cannot search across patients.
// Pure.
function searchRequest(type: FhirResourceType, p: SearchParams): FhirRequest {
if (p.pageUrl) {
return { url: p.pageUrl, method: 'GET', headers: baseHeaders(p.token) };
}
const query = buildQuery({
patient: p.patientId,
_count: p.count ?? DEFAULT_COUNT,
...(p.extra ?? {}),
});
return {
url: `${resourceUrl(p.base, type)}${query}`,
method: 'GET',
headers: baseHeaders(p.token),
};
}
// searchConditions reads the patient's problem list (Condition). Pure.
export function searchConditions(p: SearchParams): FhirRequest {
return searchRequest('Condition', p);
}
// searchMedicationRequests reads the patient's medications (MedicationRequest).
// Pure.
export function searchMedicationRequests(p: SearchParams): FhirRequest {
return searchRequest('MedicationRequest', p);
}
// searchAllergyIntolerances reads the patient's allergies (AllergyIntolerance).
// Pure.
export function searchAllergyIntolerances(p: SearchParams): FhirRequest {
return searchRequest('AllergyIntolerance', p);
}
// searchObservations reads the patient's Observations (labs/vitals). `category`
// (e.g. 'laboratory', 'vital-signs') narrows the set — Epic wants a category on
// an Observation search, so it defaults to laboratory+vital-signs unless the
// caller overrides. Pure.
export function searchObservations(
p: SearchParams & { category?: string | string[] },
): FhirRequest {
const category = p.category ?? ['laboratory', 'vital-signs'];
return searchRequest('Observation', {
...p,
extra: { ...(p.extra ?? {}), category },
});
}
// searchDocumentReferences reads the patient's clinical notes (DocumentReference).
// Pure.
export function searchDocumentReferences(p: SearchParams): FhirRequest {
return searchRequest('DocumentReference', p);
}
// ── Bundle helpers (pure) ──────────────────────────────────────────────────
// A minimal FHIR R4 resource — everything carries `resourceType`; the rest is
// resource-specific and read by chart.ts.
export interface FhirResource {
resourceType: string;
id?: string;
[key: string]: unknown;
}
// A FHIR searchset Bundle (only the fields we read).
export interface FhirBundle {
resourceType: 'Bundle';
type?: string;
total?: number;
entry?: Array<{ resource?: FhirResource; fullUrl?: string }>;
link?: Array<{ relation?: string; url?: string }>;
}
// isOperationOutcome reports whether a payload is a FHIR error (OperationOutcome)
// rather than the expected resource/Bundle. Used to surface the server's real
// diagnostics. Pure.
export function isOperationOutcome(payload: unknown): boolean {
return (payload as { resourceType?: string })?.resourceType === 'OperationOutcome';
}
// operationOutcomeMessage renders an OperationOutcome's issues into one line so a
// failure is diagnosable. Pure.
export function operationOutcomeMessage(payload: unknown): string {
const issues = (payload as { issue?: Array<{ diagnostics?: string; details?: { text?: string }; code?: string }> })
?.issue;
if (!Array.isArray(issues) || issues.length === 0) return 'FHIR OperationOutcome';
return issues
.map((i) => i.diagnostics || i.details?.text || i.code || 'issue')
.join('; ');
}
// bundleEntries pulls the resources out of a searchset Bundle's `entry[]`,
// dropping entries without a resource. Returns [] for a non-Bundle (e.g. a
// single-resource read passes through unchanged via readResource, not here).
// Pure.
export function bundleEntries(bundle: unknown): FhirResource[] {
const b = bundle as FhirBundle;
if (!Array.isArray(b?.entry)) return [];
return b.entry
.map((e) => e.resource)
.filter((r): r is FhirResource => !!r && typeof r.resourceType === 'string');
}
// nextPageUrl returns the absolute URL of the Bundle's next page — the `link`
// whose relation is `next` — or '' when this is the last page. This is the ONLY
// correct pagination cursor in FHIR (never construct it by hand). Pure.
export function nextPageUrl(bundle: unknown): string {
const links = (bundle as FhirBundle)?.link;
if (!Array.isArray(links)) return '';
const next = links.find((l) => l?.relation === 'next');
return typeof next?.url === 'string' ? next.url : '';
}
// ── The one thin network place ─────────────────────────────────────────────
// fhirFetch executes a shaped FhirRequest and returns the parsed JSON (a Bundle
// or a resource). Throws on an OperationOutcome or a non-2xx with the server's
// diagnostics, so failures are diagnosable — WITHOUT logging the body (it is
// PHI). `doFetch` is injectable (tests / non-global-fetch runtimes). NEVER logs
// the response.
export async function fhirFetch(req: FhirRequest, doFetch: typeof fetch = fetch): Promise<unknown> {
const resp = await doFetch(req.url, { method: req.method, headers: req.headers });
const text = await resp.text();
let data: unknown;
try {
data = text ? JSON.parse(text) : {};
} catch {
// Do NOT echo the body — it may be PHI. Status + a length hint only.
throw new Error(`FHIR ${resp.status}: non-JSON response (${text.length} bytes)`);
}
if (isOperationOutcome(data)) {
throw new Error(`FHIR ${resp.status}: ${operationOutcomeMessage(data)}`);
}
if (!resp.ok) {
throw new Error(`FHIR ${resp.status}: request failed`);
}
return data;
}
// fetchAllPages walks a patient-scoped search to completion, following the
// Bundle `next` links, and returns the flattened resources. `firstRequest` is
// the initial FhirRequest (from a search* wrapper); each subsequent page reuses
// the same bearer via `token`. A `maxPages` guard (default 20) bounds a runaway
// or hostile server. `doFetch` is injectable. Returns resources only — the
// caller never touches Bundle plumbing.
export async function fetchAllPages(
firstRequest: FhirRequest,
token: string,
opts: { maxPages?: number; doFetch?: typeof fetch } = {},
): Promise<FhirResource[]> {
const maxPages = opts.maxPages ?? 20;
const doFetch = opts.doFetch ?? fetch;
const out: FhirResource[] = [];
let req: FhirRequest | null = firstRequest;
for (let page = 0; page < maxPages && req; page++) {
const bundle = await fhirFetch(req, doFetch);
for (const r of bundleEntries(bundle)) out.push(r);
const next = nextPageUrl(bundle);
req = next ? { url: next, method: 'GET', headers: baseHeaders(token) } : null;
}
return out;
}
+201
View File
@@ -0,0 +1,201 @@
// The Hanzo call over a patient's CHART, and the four clinical AI actions — pure
// prompt/response shaping plus one thin async edge (the @hanzo/ai client). No
// DOM, no FHIR SDK, so the prompt builders and the response extraction are fully
// unit-testable without a network.
//
// This layers on the published headless SDK: `@hanzo/ai`'s `createAiClient`
// gives ONE call shape across every Hanzo surface —
// const ai = createAiClient({ token });
// const res = await ai.chat.completions.create({ model, messages });
// We import it directly (do NOT reimplement); the SDK defaults to
// https://api.hanzo.ai and `/v1/...`. `ai` is injectable so the four actions and
// their prompt builders are tested against a fake client with zero network.
//
// PHI posture: the assembled chart context (chart.ts) is PHI. It is sent ONLY to
// api.hanzo.ai as the model input and is NEVER logged here. There is no
// write-back to the EHR — these actions read the chart and return assistant text
// for the clinician to review.
import {
createAiClient,
type AiClient,
type ChatCompletion,
type ChatCompletionMessage,
} from '@hanzo/ai';
import { DEFAULT_MODEL, HANZO_API_BASE_URL } from './config.js';
// ── System prompt ──────────────────────────────────────────────────────────
// CLINICAL_SYSTEM_PROMPT frames Hanzo as a clinician's assistant working over a
// FHIR-derived chart. It FORBIDS inventing findings the chart doesn't support
// (the failure mode that makes a clinical assistant dangerous), demands honesty
// about a truncated chart, and states plainly that the output is decision
// SUPPORT the clinician reviews — not a diagnosis or an order.
export const CLINICAL_SYSTEM_PROMPT =
'You are Hanzo AI, a clinical assistant embedded in the clinician\'s EHR via ' +
'SMART on FHIR. You are given the launched patient\'s chart (problems, ' +
'medications, allergies, recent labs/vitals, and notes) as structured data. ' +
'Work ONLY from the chart provided — never invent diagnoses, medications, ' +
'allergies, lab values, or history that the chart does not support. When the ' +
'chart is marked truncated and a complete answer needs the omitted part, say ' +
'so plainly rather than guessing. Be precise, concise, and neutral, and use ' +
'standard clinical terminology. This is decision SUPPORT that the clinician ' +
'reviews and is responsible for — it is not a diagnosis, a treatment ' +
'recommendation to act on unreviewed, or a substitute for clinical judgment.';
// ── The four actions ───────────────────────────────────────────────────────
export type ActionId = 'summarize' | 'note' | 'extract' | 'ask';
// The action catalog — the single source of truth the UI chips and the prompt
// builder both read, so they never drift. `needsPrompt` flags the actions that
// take clinician-supplied detail (the note's reason-for-visit / the question).
export interface ActionDef {
id: ActionId;
label: string;
needsPrompt: boolean;
}
export const ACTIONS: readonly ActionDef[] = [
{ id: 'summarize', label: 'Summarize patient', needsPrompt: false },
{ id: 'note', label: 'Draft clinical note', needsPrompt: true },
{ id: 'extract', label: 'Extract problems & meds', needsPrompt: false },
{ id: 'ask', label: 'Ask about this patient', needsPrompt: true },
] as const;
// isActionId narrows an arbitrary string to an ActionId. Boundary guard. Pure.
export function isActionId(v: string): v is ActionId {
return ACTIONS.some((a) => a.id === v);
}
// actionTask renders an action's task instruction. `detail` is the
// clinician-supplied text for the two actions that need it (the note's
// reason-for-visit, the free-text question); the other two are fixed. Pure — the
// exact instruction a test asserts is the exact instruction sent to the model.
export function actionTask(id: ActionId, detail = ''): string {
const d = detail.trim();
switch (id) {
case 'summarize':
return (
'Write a concise clinical summary of this patient for a clinician ' +
'picking up their care. Cover the active problems, current medications, ' +
'allergies, and the most relevant recent labs/vitals, and flag anything ' +
'that stands out (e.g. an abnormal value, a high-risk allergy, a ' +
'medicationproblem mismatch). Do not invent anything not in the chart.'
);
case 'note':
return (
`Draft a clinical note in SOAP format (Subjective, Objective, ` +
`Assessment, Plan) for this encounter${
d ? `. Reason for visit / clinician input: ${d}` : ''
}. Populate Objective from the chart's labs, vitals, and active ` +
'problems; base the Assessment and Plan on the charted problems and ' +
'medications. Where the chart lacks information a real note needs (e.g. ' +
'the subjective history), write a clear placeholder for the clinician to ' +
'complete rather than fabricating it. The clinician reviews and signs ' +
'this note.'
);
case 'extract':
return (
'Extract this patient\'s active problems and current medications as two ' +
'structured lists. Problems: the condition and its status. Medications: ' +
'the drug, dose/route/frequency if stated, and status. Include only what ' +
'the chart contains; if a list is empty, say so plainly.'
);
case 'ask':
return d || 'What is the most important thing to know about this patient right now?';
}
}
// ── Message assembly (pure) ────────────────────────────────────────────────
// buildMessages composes the clinical system frame, the fenced chart context,
// and the task instruction into the OpenAI-compatible message list. The chart is
// FENCED so the model treats a patient's data as data, never as instructions
// (prompt-injection boundary — a note in the chart cannot redirect the model).
// Pure.
export function buildMessages(
task: string,
chartContext: string,
systemPrompt = CLINICAL_SYSTEM_PROMPT,
): ChatCompletionMessage[] {
const context = chartContext.trim();
const user: ChatCompletionMessage = {
role: 'user',
content: context
? `---- patient chart ----\n${context}\n---- end patient chart ----\n\n---- task ----\n${task}`
: task,
};
return [{ role: 'system', content: systemPrompt }, user];
}
// extractContent pulls the assistant text out of a ChatCompletion, tolerating an
// empty/odd shape. Throws on empty content so the caller surfaces a real failure
// rather than rendering a blank result. Pure.
export function extractContent(res: ChatCompletion): string {
const content = res?.choices?.[0]?.message?.content;
const text = typeof content === 'string' ? content : '';
if (!text) throw new Error('Hanzo API returned no content');
return text;
}
// ── The single call path ───────────────────────────────────────────────────
export interface AskOptions {
model?: string;
temperature?: number;
token?: string; // hk- key or IAM token; empty → anonymous/public models
baseUrl?: string;
/** Injected @hanzo/ai client (tests). Defaults to a real createAiClient. */
client?: AiClient;
signal?: AbortSignal;
system?: string;
}
// makeClient builds (or reuses an injected) @hanzo/ai client. One place decides
// how the SDK is configured, so every call is consistent. Pure but for the SDK
// construction.
function makeClient(opts: AskOptions): AiClient {
return (
opts.client ??
createAiClient({ token: opts.token, baseUrl: opts.baseUrl ?? HANZO_API_BASE_URL })
);
}
// ask runs ONE non-streaming completion over a chart and returns the assistant
// text. This is the single path from every Epic surface to the model — all four
// actions funnel through runAction → ask. Pure over the injected client.
export async function ask(task: string, chartContext: string, opts: AskOptions = {}): Promise<string> {
const client = makeClient(opts);
const res = await client.chat.completions.create({
model: opts.model ?? DEFAULT_MODEL,
messages: buildMessages(task, chartContext, opts.system),
stream: false,
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
}, { signal: opts.signal });
return extractContent(res);
}
export interface RunActionParams {
id: ActionId;
detail?: string; // note reason-for-visit / question
chartContext: string; // assembled by chart.assembleChartContext
opts?: AskOptions;
}
// runAction forms the task for an action and asks Hanzo over the chart. Returns
// the raw assistant text — there is NO write-back to the EHR (v1 is read +
// assist only), so the clinician reviews the output before it is used.
export async function runAction(p: RunActionParams): Promise<string> {
const task = actionTask(p.id, p.detail);
return ask(task, p.chartContext, p.opts);
}
// listModels returns the model ids the caller may route to, via the SDK's
// /v1/models. The catalog is org-scoped by the bearer; an empty token lists
// public models. Thin over the injected client.
export async function listModels(opts: AskOptions = {}): Promise<string[]> {
const client = makeClient(opts);
const models = await client.models.list({ signal: opts.signal });
return models.map((m) => m.id).filter((id): id is string => typeof id === 'string' && id.length > 0);
}
+46
View File
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hanzo AI for Epic</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header>
<span class="title">Hanzo AI</span>
<select id="model" aria-label="Model"><option value="">default</option></select>
<span class="host" id="patient-title">Patient</span>
</header>
<!-- One-click clinical actions over the launched patient's chart. Chips are
built from the action catalog and enabled once the chart loads. -->
<div class="chips" id="chips"></div>
<label for="prompt">Ask about this patient · or add a reason-for-visit for the note</label>
<textarea id="prompt" placeholder="e.g. What are the abnormal recent labs? · 72yo for HTN follow-up · Any drug interactions to watch?"></textarea>
<div class="row">
<button id="stop" class="secondary" disabled>Stop</button>
<span class="spacer"></span>
</div>
<details>
<summary>Hanzo API key</summary>
<div class="row">
<input id="apikey" type="password" placeholder="hk-…" autocomplete="off" />
<button id="savekey" class="secondary">Save</button>
</div>
<div class="hint">The Hanzo model-gateway key. Not the FHIR token — patient data is read server-side and never leaves this app except to api.hanzo.ai.</div>
</details>
<div class="status" id="status">Launch this app from Epic to load a patient.</div>
<label for="output">Result</label>
<textarea id="output" placeholder="Hanzo's clinical assistance appears here." readonly></textarea>
<footer>Routed through api.hanzo.ai · grounded in the FHIR chart · decision support the clinician reviews — not a diagnosis. Read + assist only; no write-back to the EHR.</footer>
<script type="module" src="app.js"></script>
</body>
</html>
+368
View File
@@ -0,0 +1,368 @@
// The SMART OAuth token-exchange + FHIR-proxy service. This is the ONLY place
// the confidential-app client_secret exists — it is read from the environment
// (never bundled, never sent to the browser). It is also where the PHI-bearing
// FHIR access token lives: the browser NEVER receives the FHIR token, so a PHI
// token can never leak into localStorage, a screenshot, or a browser log. The
// SPA holds only an opaque server session id; every FHIR read goes through the
// proxy here, which attaches the token server-side.
//
// A dependency-free Node http handler built on the pure modules (config,
// smart-oauth, fhir-client) so it deploys behind hanzoai/ingress as a small
// service at epic.hanzo.ai. Documented here; the PURE logic it wraps is what the
// tests cover (an http server is an integration concern, not a unit).
//
// node dist/server.js (after build.js bundles it)
//
// Required environment:
// SMART_CLIENT_ID — the SMART app's client id (public; also stamped into the SPA)
// SMART_REDIRECT_URI — e.g. https://epic.hanzo.ai/oauth/callback
// PORT — listen port (default 8791)
// Optional:
// SMART_CLIENT_SECRET — the confidential-app secret (SERVER ONLY). Omit for a
// public app (PKCE-only). Never bundled.
// SESSION_TTL_SECONDS — how long a server session lives (default 3600)
//
// PHI: this service NEVER logs a FHIR response body, an access token, a patient
// id, or any resource. It logs only non-PHI operational facts (a session id, a
// resource type, a status code).
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { randomUUID } from 'node:crypto';
import { normalizeBase, smartConfigUrl } from './config.js';
import {
parseSmartConfiguration,
tokenExchange,
tokenRefresh,
parseTokenResponse,
isExpired,
type SmartContext,
type SmartConfiguration,
} from './smart-oauth.js';
// ── Environment ────────────────────────────────────────────────────────────
export interface ServerConfig {
/** SMART app client id (public). */
clientId: string;
/** Confidential-app secret (SERVER ONLY). Empty → public app (PKCE-only). */
clientSecret: string;
/** OAuth redirect registered on the app. */
redirectUri: string;
/** Server-session lifetime (ms). */
sessionTtlMs: number;
/** Listen port. */
port: number;
}
// readServerConfig fails fast (throws) if a required value is missing — a server
// that cannot exchange codes must not pretend to start. The client_secret is the
// one OPTIONAL field (a public app has none). Pure given an env map, so it is
// unit-tested without touching process.env.
export function readServerConfig(env: Record<string, string | undefined>): ServerConfig {
const clientId = env.SMART_CLIENT_ID;
const redirectUri = env.SMART_REDIRECT_URI;
const missing: string[] = [];
if (!clientId) missing.push('SMART_CLIENT_ID');
if (!redirectUri) missing.push('SMART_REDIRECT_URI');
if (missing.length > 0) {
throw new Error(`Missing required environment: ${missing.join(', ')}`);
}
return {
clientId: clientId!,
clientSecret: env.SMART_CLIENT_SECRET || '',
redirectUri: redirectUri!,
sessionTtlMs: (Number(env.SESSION_TTL_SECONDS) || 3600) * 1000,
port: Number(env.PORT) || 8791,
};
}
// ── Server sessions (PHI lives here, never in the browser) ────────────────
//
// A session binds the browser to a SMART context server-side. The browser holds
// ONLY the opaque `sid`; the FHIR access token + patient id stay in this map.
// In-memory is correct for a single-instance service; a multi-instance
// deployment swaps this for hanzoai/kv (Valkey) with the SAME interface, no call
// site changes. Kept behind a tiny interface so that swap is one file.
// A pending auth: the PKCE verifier + discovered token endpoint + FHIR base,
// stashed under `state` between the authorize redirect and the callback.
interface PendingAuth {
state: string;
codeVerifier: string;
tokenEndpoint: string;
fhirBase: string;
}
export interface SessionStore {
putPending(p: PendingAuth): void;
takePending(state: string): PendingAuth | undefined;
putSession(sid: string, ctx: SmartContext, fhirBase: string, tokenEndpoint: string): void;
getSession(sid: string): ServerSession | undefined;
updateSession(sid: string, ctx: SmartContext): void;
}
export interface ServerSession {
ctx: SmartContext;
fhirBase: string;
tokenEndpoint: string;
}
// memoryStore is the default in-memory SessionStore. One place; swap for Valkey
// in production by implementing the same interface.
export function memoryStore(): SessionStore {
const pending = new Map<string, PendingAuth>();
const sessions = new Map<string, ServerSession>();
return {
putPending: (p) => void pending.set(p.state, p),
takePending: (state) => {
const p = pending.get(state);
if (p) pending.delete(state);
return p;
},
putSession: (sid, ctx, fhirBase, tokenEndpoint) =>
void sessions.set(sid, { ctx, fhirBase, tokenEndpoint }),
getSession: (sid) => sessions.get(sid),
updateSession: (sid, ctx) => {
const s = sessions.get(sid);
if (s) sessions.set(sid, { ...s, ctx });
},
};
}
// ── Discovery + token exchange (server-side) ──────────────────────────────
// discoverSmart fetches and parses `<iss>/.well-known/smart-configuration`.
// `doFetch` is injectable for tests. The FHIR base is validated to be an http(s)
// URL before we ever talk to it (SSRF boundary guard — a hostile `iss` cannot
// point us at an internal host over a non-http scheme).
export async function discoverSmart(iss: string, doFetch: typeof fetch = fetch): Promise<SmartConfiguration> {
assertHttpUrl(iss, 'iss');
const resp = await doFetch(smartConfigUrl(iss), { headers: { Accept: 'application/json' } });
if (!resp.ok) throw new Error(`SMART discovery ${resp.status}`);
return parseSmartConfiguration(await resp.json());
}
// assertHttpUrl throws unless `u` is an absolute http(s) URL. Guards the two
// externally-influenced URLs (the launch `iss` and a FHIR request path) against
// scheme-based SSRF. Boundary guard.
function assertHttpUrl(u: string, label: string): void {
let parsed: URL;
try {
parsed = new URL(u);
} catch {
throw new Error(`${label} is not a valid URL`);
}
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
throw new Error(`${label} must be http(s)`);
}
}
// exchangeCode runs the server-side code→token exchange with the confidential
// secret and the PKCE verifier, returning the parsed SmartContext. `doFetch` is
// injectable. NEVER logs the code, the tokens, or the patient id.
export async function exchangeCode(
cfg: ServerConfig,
pending: PendingAuth,
code: string,
doFetch: typeof fetch = fetch,
): Promise<SmartContext> {
const shape = tokenExchange({
tokenEndpoint: pending.tokenEndpoint,
clientId: cfg.clientId,
redirectUri: cfg.redirectUri,
code,
codeVerifier: pending.codeVerifier,
clientSecret: cfg.clientSecret || undefined,
});
const resp = await doFetch(shape.url, { method: 'POST', headers: shape.headers, body: shape.body });
const data = await resp.json().catch(() => ({}));
return parseTokenResponse(data);
}
// ensureFreshToken refreshes a session's access token when it is at/near expiry
// and a refresh_token is available, persisting the new context. Returns the live
// access token. Never logs it.
export async function ensureFreshToken(
cfg: ServerConfig,
store: SessionStore,
sid: string,
session: ServerSession,
doFetch: typeof fetch = fetch,
): Promise<string> {
if (!isExpired(session.ctx) || !session.ctx.refreshToken) return session.ctx.accessToken;
const shape = tokenRefresh({
tokenEndpoint: session.tokenEndpoint,
clientId: cfg.clientId,
refreshToken: session.ctx.refreshToken,
clientSecret: cfg.clientSecret || undefined,
});
const resp = await doFetch(shape.url, { method: 'POST', headers: shape.headers, body: shape.body });
const data = await resp.json().catch(() => ({}));
const refreshed = parseTokenResponse(data);
// A refresh may omit a new refresh_token — keep the old one.
const merged: SmartContext = {
...refreshed,
refreshToken: refreshed.refreshToken || session.ctx.refreshToken,
patient: refreshed.patient || session.ctx.patient,
};
store.updateSession(sid, merged);
return merged.accessToken;
}
// ── FHIR proxy path guard (pure) ──────────────────────────────────────────
// The resource types the proxy will forward — exactly the read scopes this app
// holds. A request for anything else is refused BEFORE a token is attached, so
// the proxy can never be turned into a general-purpose FHIR gateway.
const PROXY_ALLOWED = new Set([
'Patient',
'Condition',
'MedicationRequest',
'Observation',
'AllergyIntolerance',
'DocumentReference',
]);
// resolveProxyTarget validates a proxied FHIR path and returns the absolute URL
// to call, or throws. The SPA sends a RELATIVE FHIR path (e.g.
// `Condition?patient=123&_count=50`) OR a full same-origin `next` page URL; both
// must resolve under the session's FHIR base and hit an allowed resource type.
// This is the defence that a session can only ever read its own patient's
// allowed resources. Pure.
export function resolveProxyTarget(fhirBase: string, requestedPath: string): string {
const base = normalizeBase(fhirBase);
// Absolute URL (a pagination `next` link) must be under the same FHIR base.
const absolute = /^https?:\/\//i.test(requestedPath);
const url = absolute ? requestedPath : `${base}/${requestedPath.replace(/^\/+/, '')}`;
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error('invalid FHIR path');
}
if (!url.startsWith(base)) throw new Error('FHIR path escapes the session base');
const segment = parsed.pathname.slice(base.length ? new URL(base).pathname.length : 0);
const resourceType = segment.replace(/^\/+/, '').split(/[/?]/)[0];
if (!PROXY_ALLOWED.has(resourceType)) {
throw new Error(`resource ${resourceType || '(none)'} not permitted`);
}
return url;
}
// ── HTTP glue ──────────────────────────────────────────────────────────────
async function readBody(req: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
return Buffer.concat(chunks).toString('utf8');
}
function json(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
// sessionCookie / readSid — the browser holds ONLY the opaque session id, in an
// HttpOnly, Secure, SameSite=Lax cookie so client JS (and any injected script)
// cannot read it and it is not exposed to localStorage.
function sessionCookie(sid: string, ttlMs: number): string {
const maxAge = Math.floor(ttlMs / 1000);
return `epic_sid=${sid}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAge}`;
}
export function readSid(cookieHeader: string | undefined): string {
if (!cookieHeader) return '';
for (const part of cookieHeader.split(';')) {
const [k, v] = part.split('=');
if (k?.trim() === 'epic_sid') return (v ?? '').trim();
}
return '';
}
// The request router. Each handler is a thin wrapper over the pure modules; the
// service state is the session store. NO PHI is ever logged.
export function createHandler(cfg: ServerConfig, store: SessionStore = memoryStore()) {
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
const url = new URL(req.url || '/', `http://localhost:${cfg.port}`);
try {
// POST /oauth/prepare { iss, state, codeVerifier } → discover endpoints,
// stash the pending auth, return { authorizationEndpoint, tokenEndpoint }.
if (req.method === 'POST' && url.pathname === '/oauth/prepare') {
const { iss, state, codeVerifier } = JSON.parse((await readBody(req)) || '{}');
if (!iss || !state || !codeVerifier) return json(res, 400, { error: 'missing iss/state/codeVerifier' });
const smart = await discoverSmart(iss);
store.putPending({ state, codeVerifier, tokenEndpoint: smart.tokenEndpoint, fhirBase: normalizeBase(iss) });
return json(res, 200, { authorizationEndpoint: smart.authorizationEndpoint, tokenEndpoint: smart.tokenEndpoint });
}
// POST /oauth/callback { code, state } → exchange (secret + PKCE server-
// side), mint a server session, set the opaque cookie. The browser gets
// back ONLY the non-PHI context it needs to render (patient id + scope),
// never the FHIR token.
if (req.method === 'POST' && url.pathname === '/oauth/callback') {
const { code, state } = JSON.parse((await readBody(req)) || '{}');
if (!code || !state) return json(res, 400, { error: 'missing code/state' });
const pending = store.takePending(state);
if (!pending) return json(res, 400, { error: 'unknown or replayed state' });
const ctx = await exchangeCode(cfg, pending, code);
const sid = randomUUID();
const fhirBase = ctx.fhirBase || pending.fhirBase;
store.putSession(sid, ctx, fhirBase, pending.tokenEndpoint);
res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': sessionCookie(sid, cfg.sessionTtlMs) });
res.end(JSON.stringify({ patient: ctx.patient, scope: ctx.scope }));
return;
}
// GET /fhir?path=<relative-or-next-url> → the PHI proxy. Reads the session
// from the cookie, refreshes the token if needed, attaches it server-side,
// and streams the FHIR JSON back. The token never touches the browser.
if (req.method === 'GET' && url.pathname === '/fhir') {
const sid = readSid(req.headers.cookie);
const session = sid ? store.getSession(sid) : undefined;
if (!session) return json(res, 401, { error: 'no session' });
const path = url.searchParams.get('path') || '';
let target: string;
try {
target = resolveProxyTarget(session.fhirBase, path);
} catch (e: unknown) {
return json(res, 400, { error: (e as Error).message });
}
const token = await ensureFreshToken(cfg, store, sid, session);
const upstream = await fetch(target, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/fhir+json' },
});
const text = await upstream.text();
// Pass through the FHIR JSON verbatim; do NOT log it (PHI).
res.writeHead(upstream.status, { 'Content-Type': 'application/fhir+json' });
res.end(text);
return;
}
if (req.method === 'GET' && url.pathname === '/healthz') return json(res, 200, { ok: true });
return json(res, 404, { error: 'not found' });
} catch (e: unknown) {
// Operational error only — never include a response body (may be PHI).
return json(res, 500, { error: (e as Error)?.message || 'internal error' });
}
};
}
// main boots the http server when run directly. Import-safe: only the direct
// entry starts listening, so tests import the pure handlers without a port.
export function main(): void {
const cfg = readServerConfig(process.env);
const server = createServer(createHandler(cfg));
server.listen(cfg.port, () => {
console.log(
JSON.stringify({
msg: 'epic smart-on-fhir service up',
port: cfg.port,
confidential: !!cfg.clientSecret,
}),
);
});
}
// ESM entry check: run main() only when this file is the process entry.
if (process.argv[1] && process.argv[1].endsWith('server.js')) {
main();
}
+350
View File
@@ -0,0 +1,350 @@
// SMART-on-FHIR launch: discovery, PKCE, the authorize URL, the code→token
// exchange/refresh shaping, and pulling the patient context out of the token
// response. PURE request-shaping only — this module never does a network call
// and never sources the client_secret (server.ts holds it, from the
// environment), so it is trivially unit-testable and free of secrets.
//
// SMART App Launch (http://hl7.org/fhir/smart-app-launch): the app is launched
// EITHER by the EHR (Epic) with `iss` (the FHIR base) + `launch` (an opaque
// launch token carrying the patient/encounter context) in the URL, OR
// standalone (the app supplies its own `iss` and asks the user to pick a
// patient via the `launch/patient` scope). Both paths then:
// 1. discover authorize/token endpoints from `<iss>/.well-known/smart-configuration`
// 2. redirect the browser to `authorize` with auth-code + PKCE (+ the `launch`
// token and `aud=<iss>` — Epic REQUIRES `aud`)
// 3. exchange the returned `code` for tokens, which for a patient-context
// launch carry a `patient` id (the launched patient) alongside the tokens.
// Confidential apps (server-side secret) also send client_secret at step 3;
// public apps rely on PKCE alone. This module shapes 13; server.ts runs them.
// ── SMART discovery ────────────────────────────────────────────────────────
// The subset of `.well-known/smart-configuration` this app needs: the two OAuth
// endpoints and (informational) the capabilities/scopes the server advertises.
// Epic publishes the full document; we read only what we use.
export interface SmartConfiguration {
authorizationEndpoint: string;
tokenEndpoint: string;
// Optional, informational: what the server says it supports.
capabilities?: string[];
scopesSupported?: string[];
}
// parseSmartConfiguration validates the discovery document and extracts the two
// endpoints. Throws when either endpoint is missing — a SMART app that cannot
// find the authorize/token URLs must fail loudly, not guess Epic-specific paths.
// Pure — the fetch is server.ts's job. Boundary guard on an external response.
export function parseSmartConfiguration(data: unknown): SmartConfiguration {
const d = data as {
authorization_endpoint?: unknown;
token_endpoint?: unknown;
capabilities?: unknown;
scopes_supported?: unknown;
};
const authorizationEndpoint = d?.authorization_endpoint;
const tokenEndpoint = d?.token_endpoint;
if (typeof authorizationEndpoint !== 'string' || !authorizationEndpoint) {
throw new Error('SMART discovery: no authorization_endpoint');
}
if (typeof tokenEndpoint !== 'string' || !tokenEndpoint) {
throw new Error('SMART discovery: no token_endpoint');
}
return {
authorizationEndpoint,
tokenEndpoint,
capabilities: Array.isArray(d?.capabilities)
? (d.capabilities.filter((c) => typeof c === 'string') as string[])
: undefined,
scopesSupported: Array.isArray(d?.scopes_supported)
? (d.scopes_supported.filter((s) => typeof s === 'string') as string[])
: undefined,
};
}
// ── PKCE ───────────────────────────────────────────────────────────────────
//
// PKCE (RFC 7636) protects the auth-code exchange: the app sends a random
// `code_verifier`'s SHA-256 hash (`code_challenge`) at authorize time, then the
// raw verifier at token time — an intercepted code is useless without it. Epic
// requires PKCE (S256) for public apps and supports it for confidential ones.
// base64url encodes bytes without padding, per RFC 7636. Pure.
export function base64urlEncode(bytes: Uint8Array): string {
let bin = '';
for (const b of bytes) bin += String.fromCharCode(b);
// btoa in the browser; Buffer in node — both reachable here, prefer btoa.
const b64 =
typeof btoa === 'function'
? btoa(bin)
: Buffer.from(bytes).toString('base64');
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// A PKCE pair: the secret verifier (kept by the app across the redirect) and the
// challenge (sent to authorize). `method` is always S256 — the only method Epic
// and the SMART spec want; `plain` is never used.
export interface PkcePair {
verifier: string;
challenge: string;
method: 'S256';
}
// randomVerifier makes a high-entropy code_verifier: 32 random bytes → 43-char
// base64url (within the RFC's 43128 range). `random` is injectable so a test
// gets a deterministic verifier; it defaults to Web Crypto's CSPRNG.
export function randomVerifier(
random: (n: number) => Uint8Array = cryptoRandom,
): string {
return base64urlEncode(random(32));
}
// cryptoRandom fills n bytes from the platform CSPRNG (Web Crypto in the browser
// and in node ≥18). Never Math.random — this is security material.
function cryptoRandom(n: number): Uint8Array {
const out = new Uint8Array(n);
crypto.getRandomValues(out);
return out;
}
// challengeFromVerifier derives the S256 code_challenge = base64url(sha256(
// verifier)). `sha256` is injectable for tests; defaults to Web Crypto's
// subtle.digest (async). Returns the challenge string.
export async function challengeFromVerifier(
verifier: string,
sha256: (input: string) => Promise<Uint8Array> = subtleSha256,
): Promise<string> {
return base64urlEncode(await sha256(verifier));
}
async function subtleSha256(input: string): Promise<Uint8Array> {
const data = new TextEncoder().encode(input);
const digest = await crypto.subtle.digest('SHA-256', data);
return new Uint8Array(digest);
}
// createPkce mints a full PKCE pair (verifier + S256 challenge). The app stores
// `verifier` alongside the CSRF `state` before the redirect and replays it at
// token exchange. `random`/`sha256` are injectable for deterministic tests.
export async function createPkce(
random: (n: number) => Uint8Array = cryptoRandom,
sha256: (input: string) => Promise<Uint8Array> = subtleSha256,
): Promise<PkcePair> {
const verifier = randomVerifier(random);
const challenge = await challengeFromVerifier(verifier, sha256);
return { verifier, challenge, method: 'S256' };
}
// ── The authorize redirect ───────────────────────────────────────────────
export interface AuthorizeParams {
authorizationEndpoint: string; // discovered from smart-configuration
clientId: string;
redirectUri: string;
// The FHIR base (`iss`) — SMART/Epic REQUIRE it as `aud` so the token is
// audienced to the FHIR server the app will call.
aud: string;
scope: string;
state: string; // CSRF state the caller mints and verifies on the callback
codeChallenge: string; // PKCE S256 challenge
// The opaque `launch` token from an EHR launch. Present for EHR launch,
// absent (and omitted) for standalone launch.
launch?: string;
}
// authorizeUrl builds the exact URL to redirect the browser to. SMART's
// authorization request: response_type=code, client_id, redirect_uri, scope,
// state, aud, code_challenge(+method=S256), and `launch` when present. Pure.
export function authorizeUrl(p: AuthorizeParams): string {
const params = new URLSearchParams({
response_type: 'code',
client_id: p.clientId,
redirect_uri: p.redirectUri,
scope: p.scope,
state: p.state,
aud: p.aud,
code_challenge: p.codeChallenge,
code_challenge_method: 'S256',
});
if (p.launch) params.set('launch', p.launch);
return `${p.authorizationEndpoint}?${params.toString()}`;
}
// ── Token exchange / refresh shaping ──────────────────────────────────────
// The shape of the POST server.ts will make — separated from fetch so a test
// asserts URL, headers, and form body without a network call. Confidential apps
// authenticate with client_secret (in the body here — Epic accepts
// client_secret_post); public apps omit it and rely on PKCE.
export interface TokenRequest {
url: string;
headers: Record<string, string>;
body: string; // urlencoded form
}
export interface ExchangeParams {
tokenEndpoint: string; // discovered
clientId: string;
redirectUri: string;
code: string; // the authorization code from the callback
codeVerifier: string; // the PKCE verifier stored before the redirect
// Confidential-app secret (server-only). Omit for a public app.
clientSecret?: string;
}
// tokenExchange shapes the code→token POST. SMART/OAuth2:
// grant_type=authorization_code with code, redirect_uri, client_id,
// code_verifier, and client_secret for confidential apps. Pure.
export function tokenExchange(p: ExchangeParams): TokenRequest {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code: p.code,
redirect_uri: p.redirectUri,
client_id: p.clientId,
code_verifier: p.codeVerifier,
});
if (p.clientSecret) body.set('client_secret', p.clientSecret);
return {
url: p.tokenEndpoint,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body: body.toString(),
};
}
export interface RefreshParams {
tokenEndpoint: string;
clientId: string;
refreshToken: string;
clientSecret?: string;
// A refresh MAY narrow scope; omit to keep the granted scopes.
scope?: string;
}
// tokenRefresh shapes the refresh POST. grant_type=refresh_token with the stored
// refresh_token (+ client_secret for confidential apps). Same endpoint/content
// type as exchange. Pure.
export function tokenRefresh(p: RefreshParams): TokenRequest {
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: p.refreshToken,
client_id: p.clientId,
});
if (p.clientSecret) body.set('client_secret', p.clientSecret);
if (p.scope) body.set('scope', p.scope);
return {
url: p.tokenEndpoint,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body: body.toString(),
};
}
// ── The token response → SMART context ────────────────────────────────────
// A parsed SMART token response: the OAuth tokens PLUS the SMART launch context
// that rides in the token payload (`patient`, `encounter`, `id_token`, the
// granted `scope`, and the FHIR base to call). The `patient` id is what every
// subsequent FHIR read scopes to.
export interface SmartContext {
accessToken: string;
refreshToken: string;
tokenType: string;
// Absolute expiry (epoch ms) computed from expires_in at parse time, so
// callers compare against Date.now() without re-deriving.
expiresAt: number;
// The launched patient's FHIR id — present for a patient-context launch.
patient: string;
// The encounter id when the launch carries one (optional).
encounter: string;
// The granted scopes (may be narrower than requested).
scope: string;
// OpenID id_token identifying the clinician (`fhirUser`), when present.
idToken: string;
// Some servers echo the FHIR base in the token response; kept when present so
// the caller can prefer it over the launch `iss`.
fhirBase: string;
}
// parseTokenResponse turns a SMART token payload into a SmartContext, computing
// the absolute expiry. `now` is injectable so the derivation is unit-testable.
// Throws on an OAuth error payload so the caller surfaces the server's real
// reason. Boundary guard on an external response.
export function parseTokenResponse(data: unknown, now: number = Date.now()): SmartContext {
const d = data as Record<string, unknown>;
if (d && d.error) {
const desc = (d.error_description as string) || (d.error as string);
throw new Error(`SMART OAuth error: ${desc}`);
}
const accessToken = d?.access_token;
if (typeof accessToken !== 'string' || !accessToken) {
throw new Error('SMART OAuth: no access_token in response');
}
const expiresIn = Number(d?.expires_in ?? 0);
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
return {
accessToken,
refreshToken: str(d?.refresh_token),
tokenType: str(d?.token_type) || 'Bearer',
expiresAt: now + expiresIn * 1000,
patient: str(d?.patient),
encounter: str(d?.encounter),
scope: str(d?.scope),
idToken: str(d?.id_token),
fhirBase: str(d?.fhirBase) || str((d as { serverUrl?: unknown })?.serverUrl),
};
}
// isExpired reports whether a context's access token is at/near expiry. A skew
// (default 60s) refreshes slightly early so an in-flight FHIR read never races
// the boundary. Pure.
export function isExpired(ctx: Pick<SmartContext, 'expiresAt'>, now: number = Date.now(), skewMs = 60_000): boolean {
return now >= ctx.expiresAt - skewMs;
}
// ── Launch-URL parsing (pure) ─────────────────────────────────────────────
// The launch parameters SMART puts on the app's launch URL. EHR launch carries
// `iss` (FHIR base) + `launch` (opaque token); standalone launch carries
// neither (the app supplies its own `iss`). Both may be absent when the page is
// opened cold.
export interface LaunchParams {
iss: string; // FHIR base from the EHR
launch: string; // opaque launch token
}
// parseLaunch reads the launch URL query into a LaunchParams. Pure — takes a
// query string so it is unit-tested without a DOM. Values are trimmed; absence
// is represented as ''.
export function parseLaunch(search: string): LaunchParams {
const q = new URLSearchParams(search);
return {
iss: (q.get('iss') || '').trim(),
launch: (q.get('launch') || '').trim(),
};
}
// The callback parameters SMART returns to redirect_uri: the auth `code` and the
// `state` (to verify against the mint), or an `error`(+description) when the
// user declines / the server rejects.
export interface CallbackParams {
code: string;
state: string;
error: string;
errorDescription: string;
}
// parseCallback reads the callback URL query. Pure. An `error` present means the
// grant failed — the caller surfaces errorDescription and does NOT exchange.
export function parseCallback(search: string): CallbackParams {
const q = new URLSearchParams(search);
return {
code: (q.get('code') || '').trim(),
state: (q.get('state') || '').trim(),
error: (q.get('error') || '').trim(),
errorDescription: (q.get('error_description') || '').trim(),
};
}
+48
View File
@@ -0,0 +1,48 @@
:root {
color-scheme: light dark;
--fg: #1a1a1a; --muted: #666; --bg: #fff; --line: #e3e3e3; --accent: #111;
--ok: #1a7f37; --warn: #9a6700; --error: #cf222e;
}
@media (prefers-color-scheme: dark) {
:root {
--fg: #eaeaea; --muted: #9a9a9a; --bg: #1e1e1e; --line: #333; --accent: #fff;
--ok: #3fb950; --warn: #d29922; --error: #f85149;
}
}
* { box-sizing: border-box; }
body {
font: 14px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif;
color: var(--fg); background: var(--bg); margin: 0 auto; padding: 14px;
max-width: 720px;
}
header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
header .title { font-weight: 600; font-size: 15px; }
header .host { color: var(--muted); font-size: 12px; margin-left: auto; max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
label { display: block; font-size: 12px; color: var(--muted); margin: 10px 0 4px; }
textarea, select, input {
width: 100%; font: inherit; color: var(--fg); background: var(--bg);
border: 1px solid var(--line); border-radius: 6px; padding: 8px;
}
textarea#prompt { min-height: 56px; resize: vertical; }
textarea#output { min-height: 260px; resize: vertical; }
.row { display: flex; gap: 8px; align-items: center; margin-top: 8px; }
button {
font: inherit; border: 1px solid var(--line); background: var(--accent);
color: var(--bg); border-radius: 6px; padding: 8px 14px; cursor: pointer;
}
button.secondary { background: transparent; color: var(--fg); }
button:disabled { opacity: .5; cursor: default; }
.spacer { flex: 1; }
.status { min-height: 18px; font-size: 12px; margin-top: 10px; color: var(--muted); }
.status.ok { color: var(--ok); } .status.warn { color: var(--warn); } .status.error { color: var(--error); }
.hint { font-size: 11px; color: var(--muted); margin-top: 4px; }
footer { margin-top: 12px; font-size: 11px; color: var(--muted); }
select#model { width: auto; max-width: 150px; padding: 4px 8px; font-size: 12px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
.chip {
padding: 5px 10px; border-radius: 999px; font-size: 13px; cursor: pointer;
background: transparent; color: var(--fg); border: 1px solid var(--line);
}
.chip:hover:not(:disabled) { border-color: var(--accent); }
.chip:disabled { opacity: .5; cursor: default; }
details summary { cursor: pointer; font-size: 12px; color: var(--muted); margin-top: 10px; }
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
// A minimal localStorage stub so the browser-only auth module is testable in
// node. Installed before importing the module under test.
class MemStorage {
private m = new Map<string, string>();
getItem(k: string) {
return this.m.has(k) ? this.m.get(k)! : null;
}
setItem(k: string, v: string) {
this.m.set(k, v);
}
removeItem(k: string) {
this.m.delete(k);
}
}
beforeEach(() => {
(globalThis as { localStorage?: unknown }).localStorage = new MemStorage();
vi.resetModules();
});
describe('auth: pasted Hanzo key (NOT the FHIR/PHI token)', () => {
it('stores, reads, and clears the key', async () => {
const { getApiKey, setApiKey, hasApiKey, bearer } = await import('../src/auth.js');
expect(getApiKey()).toBe('');
expect(hasApiKey()).toBe(false);
setApiKey(' hk-abc ');
expect(getApiKey()).toBe('hk-abc'); // trimmed
expect(hasApiKey()).toBe(true);
expect(bearer()).toBe('hk-abc');
setApiKey('');
expect(getApiKey()).toBe('');
expect(hasApiKey()).toBe(false);
});
it('validateKey rejects an empty key before any network call', async () => {
const { validateKey } = await import('../src/auth.js');
await expect(validateKey(' ')).rejects.toThrow(/Hanzo API key/);
});
it('does not touch the FHIR/PHI storage — only the Hanzo gateway key', async () => {
const { setApiKey } = await import('../src/auth.js');
const { APIKEY_STORAGE_KEY } = await import('../src/config.js');
setApiKey('hk-x');
// The one and only key it writes is the Hanzo gateway key.
expect(localStorage.getItem(APIKEY_STORAGE_KEY)).toBe('hk-x');
});
});
+241
View File
@@ -0,0 +1,241 @@
import { describe, it, expect } from 'vitest';
import {
codeableText,
effectiveDate,
summarizePatient,
conditionRow,
medicationRow,
allergyRow,
observationRow,
observationValue,
documentRow,
renderSection,
assembleChartContext,
truncate,
chartIsEmpty,
emptyChart,
MAX_ROWS_PER_SECTION,
type Chart,
} from '../src/chart.js';
import type { FhirResource } from '../src/fhir-client.js';
// ── Realistic R4 fixtures ──────────────────────────────────────────────────
const patient: FhirResource = {
resourceType: 'Patient',
id: 'p1',
name: [{ use: 'official', given: ['Jane', 'Q'], family: 'Doe' }],
gender: 'female',
birthDate: '1958-03-11',
};
const hypertension: FhirResource = {
resourceType: 'Condition',
id: 'c1',
clinicalStatus: { coding: [{ code: 'active', display: 'Active' }] },
code: { text: 'Essential hypertension', coding: [{ system: 'http://snomed.info/sct', code: '59621000' }] },
onsetDateTime: '2015-06-01',
};
const diabetes: FhirResource = {
resourceType: 'Condition',
id: 'c2',
clinicalStatus: { coding: [{ code: 'active' }] },
code: { coding: [{ display: 'Type 2 diabetes mellitus' }] },
};
const lisinopril: FhirResource = {
resourceType: 'MedicationRequest',
id: 'm1',
status: 'active',
medicationCodeableConcept: { text: 'Lisinopril 10 mg oral tablet' },
dosageInstruction: [{ text: 'Take 1 tablet by mouth once daily' }],
};
const metforminByRef: FhirResource = {
resourceType: 'MedicationRequest',
id: 'm2',
status: 'active',
medicationReference: { display: 'Metformin 500 mg' },
};
const penicillinAllergy: FhirResource = {
resourceType: 'AllergyIntolerance',
id: 'a1',
clinicalStatus: { coding: [{ code: 'active' }] },
criticality: 'high',
code: { text: 'Penicillin' },
reaction: [{ manifestation: [{ text: 'Anaphylaxis' }] }],
};
const a1c: FhirResource = {
resourceType: 'Observation',
id: 'o1',
code: { text: 'Hemoglobin A1c' },
valueQuantity: { value: 8.2, unit: '%' },
effectiveDateTime: '2026-05-20',
};
const bp: FhirResource = {
resourceType: 'Observation',
id: 'o2',
code: { text: 'Systolic blood pressure' },
valueQuantity: { value: 148, unit: 'mmHg' },
effectivePeriod: { start: '2026-06-01' },
};
const progressNote: FhirResource = {
resourceType: 'DocumentReference',
id: 'd1',
type: { text: 'Progress note' },
date: '2026-06-15',
};
describe('CodeableConcept decoding', () => {
it('prefers text, then coding.display, then coding.code', () => {
expect(codeableText({ text: 'Foo' })).toBe('Foo');
expect(codeableText({ coding: [{ display: 'Bar' }] })).toBe('Bar');
expect(codeableText({ coding: [{ code: 'baz' }] })).toBe('baz');
expect(codeableText({})).toBe('');
expect(codeableText(undefined)).toBe('');
});
});
describe('effectiveDate polymorphism', () => {
it('reads effectiveDateTime, effectivePeriod.start, onset, authoredOn', () => {
expect(effectiveDate({ resourceType: 'X', effectiveDateTime: '2026-01-01' })).toBe('2026-01-01');
expect(effectiveDate({ resourceType: 'X', effectivePeriod: { start: '2026-02-02' } })).toBe('2026-02-02');
expect(effectiveDate({ resourceType: 'X', onsetDateTime: '2026-03-03' })).toBe('2026-03-03');
expect(effectiveDate({ resourceType: 'X', authoredOn: '2026-04-04' })).toBe('2026-04-04');
expect(effectiveDate({ resourceType: 'X' })).toBe('');
});
});
describe('patient demographics', () => {
it('renders name, sex, DOB from a HumanName', () => {
expect(summarizePatient(patient)).toEqual(['Name: Jane Q Doe', 'Sex: female', 'DOB: 1958-03-11']);
});
it('prefers name.text when present', () => {
expect(summarizePatient({ resourceType: 'Patient', name: [{ text: 'John Smith' }] })).toEqual([
'Name: John Smith',
]);
});
it('is empty for no patient', () => {
expect(summarizePatient(undefined)).toEqual([]);
});
});
describe('per-resource rows', () => {
it('conditionRow — name, status, onset', () => {
expect(conditionRow(hypertension)).toBe('Essential hypertension (Active) onset 2015-06-01');
expect(conditionRow(diabetes)).toBe('Type 2 diabetes mellitus (active)');
});
it('medicationRow — from codeableConcept with dosage, and from a reference', () => {
expect(medicationRow(lisinopril)).toBe(
'Lisinopril 10 mg oral tablet — Take 1 tablet by mouth once daily (active)',
);
expect(medicationRow(metforminByRef)).toBe('Metformin 500 mg (active)');
});
it('allergyRow — substance, manifestation, criticality, status', () => {
expect(allergyRow(penicillinAllergy)).toBe('Penicillin → Anaphylaxis [high] (active)');
});
it('observationRow / observationValue — quantity with unit + date', () => {
expect(observationValue(a1c)).toBe('8.2 %');
expect(observationRow(a1c)).toBe('Hemoglobin A1c = 8.2 % (2026-05-20)');
expect(observationRow(bp)).toBe('Systolic blood pressure = 148 mmHg (2026-06-01)');
});
it('observationValue — codeable and string variants', () => {
expect(observationValue({ resourceType: 'Observation', valueCodeableConcept: { text: 'Positive' } })).toBe(
'Positive',
);
expect(observationValue({ resourceType: 'Observation', valueString: 'see report' })).toBe('see report');
expect(observationValue({ resourceType: 'Observation' })).toBe('');
});
it('documentRow — type and date, no bytes inlined', () => {
expect(documentRow(progressNote)).toBe('Progress note (2026-06-15)');
});
});
describe('renderSection', () => {
it('renders a heading + bulleted rows', () => {
const out = renderSection({ heading: 'Problems', resources: [hypertension, diabetes], row: conditionRow });
expect(out).toContain('## Problems');
expect(out).toContain('- Essential hypertension (Active) onset 2015-06-01');
expect(out).toContain('- Type 2 diabetes mellitus (active)');
});
it('marks an empty section explicitly (absence is meaningful)', () => {
expect(renderSection({ heading: 'Allergies', resources: [], row: allergyRow })).toBe(
'## Allergies\n(none recorded)',
);
});
it('caps rows and shows a visible "N more" marker', () => {
const many = Array.from({ length: MAX_ROWS_PER_SECTION + 5 }, (_, i) => ({
...diabetes,
code: { text: `Condition ${i}` },
}));
const out = renderSection({ heading: 'Problems', resources: many, row: conditionRow });
expect(out).toContain('- …and 5 more not shown');
// exactly MAX_ROWS_PER_SECTION data rows + heading + the "more" line
expect(out.split('\n').filter((l) => l.startsWith('- ')).length).toBe(MAX_ROWS_PER_SECTION + 1);
});
});
describe('assembleChartContext', () => {
const chart: Chart = {
patient,
conditions: [hypertension, diabetes],
medications: [lisinopril, metforminByRef],
allergies: [penicillinAllergy],
observations: [a1c, bp],
documents: [progressNote],
};
it('assembles demographics + all five sections in clinical priority order', () => {
const ctx = assembleChartContext(chart);
expect(ctx.indexOf('# Patient')).toBeLessThan(ctx.indexOf('## Problems'));
expect(ctx.indexOf('## Problems')).toBeLessThan(ctx.indexOf('## Medications'));
expect(ctx.indexOf('## Medications')).toBeLessThan(ctx.indexOf('## Allergies'));
expect(ctx.indexOf('## Allergies')).toBeLessThan(ctx.indexOf('## Recent labs & vitals'));
expect(ctx.indexOf('## Recent labs & vitals')).toBeLessThan(ctx.indexOf('## Clinical notes'));
expect(ctx).toContain('Jane Q Doe');
expect(ctx).toContain('Penicillin → Anaphylaxis [high]');
expect(ctx).toContain('Hemoglobin A1c = 8.2 %');
});
it('renders a usable chart even with no demographics', () => {
const ctx = assembleChartContext({ ...emptyChart(), conditions: [hypertension] });
expect(ctx).toContain('(no demographics available)');
expect(ctx).toContain('Essential hypertension');
});
it('caps the whole context and marks truncation visibly', () => {
const bigDoc: FhirResource = {
resourceType: 'DocumentReference',
type: { text: 'x'.repeat(2000) },
date: '2026-01-01',
};
const chartBig: Chart = { ...emptyChart(), documents: Array.from({ length: 50 }, () => bigDoc) };
const ctx = assembleChartContext(chartBig, 500);
expect(ctx.length).toBeLessThanOrEqual(500 + 60);
expect(ctx).toMatch(/chart truncated: \d+ chars omitted/);
});
});
describe('truncate + chartIsEmpty', () => {
it('truncate marks elision and passes short text through', () => {
expect(truncate('short', 100)).toBe('short');
expect(truncate('abcdef', 3)).toMatch(/^abc\n…\[chart truncated: 3 chars omitted\]$/);
});
it('chartIsEmpty is true only when all clinical lists are empty', () => {
expect(chartIsEmpty(emptyChart())).toBe(true);
expect(chartIsEmpty({ ...emptyChart(), patient })).toBe(true); // patient alone still empty
expect(chartIsEmpty({ ...emptyChart(), conditions: [hypertension] })).toBe(false);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import {
HANZO_API_BASE_URL,
DEFAULT_MODEL,
pickBearer,
SMART_SCOPES,
scopeString,
smartConfigUrl,
normalizeBase,
FHIR_RESOURCES,
} from '../src/config.js';
describe('config: Hanzo gateway', () => {
it('points at api.hanzo.ai with no /api/ prefix', () => {
expect(HANZO_API_BASE_URL).toBe('https://api.hanzo.ai');
expect(HANZO_API_BASE_URL).not.toContain('/api/');
});
it('default model is a zen model', () => {
expect(DEFAULT_MODEL).toMatch(/^zen/);
});
});
describe('config: pickBearer', () => {
it('prefers the pasted key over the IAM token', () => {
expect(pickBearer('hk-key', 'iam-token')).toBe('hk-key');
});
it('falls back to the IAM token when no key', () => {
expect(pickBearer('', 'iam-token')).toBe('iam-token');
expect(pickBearer(' ', 'iam-token')).toBe('iam-token');
});
it('is empty (anonymous) when neither is present', () => {
expect(pickBearer('', '')).toBe('');
});
});
describe('config: SMART scopes', () => {
it('requests launch + patient read scopes and NO write scope', () => {
const s = scopeString();
expect(s).toContain('launch');
expect(s).toContain('openid');
expect(s).toContain('fhirUser');
expect(s).toContain('patient/Patient.read');
expect(s).toContain('patient/Condition.read');
expect(s).toContain('patient/MedicationRequest.read');
expect(s).toContain('patient/Observation.read');
expect(s).toContain('patient/AllergyIntolerance.read');
expect(s).toContain('patient/DocumentReference.read');
// Read + assist only — a write scope must never be requested in v1.
expect(s).not.toMatch(/\.write/);
expect(s).not.toMatch(/\*\/\*/);
});
it('scopeString is space-delimited and deterministic', () => {
expect(scopeString(['a', 'b', 'c'])).toBe('a b c');
expect(scopeString()).toBe(SMART_SCOPES.join(' '));
});
});
describe('config: discovery URL', () => {
it('derives the well-known discovery URL from iss', () => {
expect(smartConfigUrl('https://fhir.example.org/r4')).toBe(
'https://fhir.example.org/r4/.well-known/smart-configuration',
);
});
it('normalizes a trailing slash on iss', () => {
expect(smartConfigUrl('https://fhir.example.org/r4/')).toBe(
'https://fhir.example.org/r4/.well-known/smart-configuration',
);
expect(normalizeBase('https://x/')).toBe('https://x');
expect(normalizeBase('https://x///')).toBe('https://x');
});
});
describe('config: FHIR resource names', () => {
it('names the six read resources', () => {
expect(Object.keys(FHIR_RESOURCES).sort()).toEqual([
'AllergyIntolerance',
'Condition',
'DocumentReference',
'MedicationRequest',
'Observation',
'Patient',
]);
});
});
+225
View File
@@ -0,0 +1,225 @@
import { describe, it, expect, vi } from 'vitest';
import {
resourceUrl,
getPatient,
searchConditions,
searchMedicationRequests,
searchAllergyIntolerances,
searchObservations,
searchDocumentReferences,
bundleEntries,
nextPageUrl,
isOperationOutcome,
operationOutcomeMessage,
fhirFetch,
fetchAllPages,
DEFAULT_COUNT,
type FhirRequest,
} from '../src/fhir-client.js';
const BASE = 'https://fhir.example.org/r4';
const TOKEN = 'AT-secret';
const PID = 'Patient-123';
function res(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/fhir+json' } });
}
describe('resourceUrl', () => {
it('builds a search root and a single-resource URL', () => {
expect(resourceUrl(BASE, 'Condition')).toBe(`${BASE}/Condition`);
expect(resourceUrl(BASE, 'Patient', PID)).toBe(`${BASE}/Patient/Patient-123`);
});
it('normalizes a trailing slash and encodes the id', () => {
expect(resourceUrl(`${BASE}/`, 'Patient', 'a/b')).toBe(`${BASE}/Patient/a%2Fb`);
});
});
describe('single-patient read', () => {
it('getPatient targets Patient/<id> with a bearer + fhir accept', () => {
const r = getPatient(BASE, TOKEN, PID);
expect(r.method).toBe('GET');
expect(r.url).toBe(`${BASE}/Patient/Patient-123`);
expect(r.headers.Authorization).toBe(`Bearer ${TOKEN}`);
expect(r.headers.Accept).toBe('application/fhir+json');
});
});
describe('patient-scoped searches', () => {
const sp = { base: BASE, token: TOKEN, patientId: PID };
it('scopes every search with patient=<id> and a default _count', () => {
for (const req of [
searchConditions(sp),
searchMedicationRequests(sp),
searchAllergyIntolerances(sp),
searchDocumentReferences(sp),
]) {
const u = new URL(req.url);
expect(u.searchParams.get('patient')).toBe(PID);
expect(u.searchParams.get('_count')).toBe(String(DEFAULT_COUNT));
}
});
it('hits the right resource path for each search', () => {
expect(new URL(searchConditions(sp).url).pathname).toMatch(/\/Condition$/);
expect(new URL(searchMedicationRequests(sp).url).pathname).toMatch(/\/MedicationRequest$/);
expect(new URL(searchAllergyIntolerances(sp).url).pathname).toMatch(/\/AllergyIntolerance$/);
expect(new URL(searchDocumentReferences(sp).url).pathname).toMatch(/\/DocumentReference$/);
});
it('observation search defaults to laboratory + vital-signs categories', () => {
const u = new URL(searchObservations(sp).url);
expect(u.pathname).toMatch(/\/Observation$/);
expect(u.searchParams.get('category')).toBe('laboratory,vital-signs');
});
it('observation category is overridable', () => {
const u = new URL(searchObservations({ ...sp, category: 'laboratory' }).url);
expect(u.searchParams.get('category')).toBe('laboratory');
});
it('a custom _count is honored', () => {
expect(new URL(searchConditions({ ...sp, count: 10 }).url).searchParams.get('_count')).toBe('10');
});
it('a pageUrl cursor is used verbatim (pagination), ignoring other params', () => {
const next = `${BASE}/Condition?patient=${PID}&_count=50&_getpages=abc&_getpagesoffset=50`;
const r = searchConditions({ ...sp, pageUrl: next, count: 999 });
expect(r.url).toBe(next);
expect(r.headers.Authorization).toBe(`Bearer ${TOKEN}`);
});
});
describe('Bundle helpers', () => {
const bundle = {
resourceType: 'Bundle',
type: 'searchset',
entry: [
{ resource: { resourceType: 'Condition', id: 'c1' } },
{ resource: { resourceType: 'Condition', id: 'c2' } },
{ fullUrl: 'no-resource-here' }, // dropped
],
link: [
{ relation: 'self', url: `${BASE}/Condition?patient=${PID}` },
{ relation: 'next', url: `${BASE}/Condition?_getpages=abc` },
],
};
it('bundleEntries returns only entries with a resource', () => {
const rs = bundleEntries(bundle);
expect(rs.map((r) => r.id)).toEqual(['c1', 'c2']);
});
it('bundleEntries returns [] for a non-Bundle', () => {
expect(bundleEntries({ resourceType: 'Condition' })).toEqual([]);
expect(bundleEntries(null)).toEqual([]);
});
it('nextPageUrl returns the next link, or empty on the last page', () => {
expect(nextPageUrl(bundle)).toBe(`${BASE}/Condition?_getpages=abc`);
expect(nextPageUrl({ resourceType: 'Bundle', link: [{ relation: 'self', url: 'x' }] })).toBe('');
expect(nextPageUrl({ resourceType: 'Bundle' })).toBe('');
});
});
describe('OperationOutcome handling', () => {
const oo = {
resourceType: 'OperationOutcome',
issue: [{ severity: 'error', code: 'forbidden', diagnostics: 'not authorized for this patient' }],
};
it('detects an OperationOutcome and renders its message', () => {
expect(isOperationOutcome(oo)).toBe(true);
expect(isOperationOutcome({ resourceType: 'Bundle' })).toBe(false);
expect(operationOutcomeMessage(oo)).toBe('not authorized for this patient');
});
});
describe('fhirFetch', () => {
it('returns the parsed Bundle on success', async () => {
const doFetch = vi.fn().mockResolvedValue(res(200, { resourceType: 'Bundle', entry: [] }));
const out = (await fhirFetch(getPatient(BASE, TOKEN, PID) as FhirRequest, doFetch)) as {
resourceType: string;
};
expect(out.resourceType).toBe('Bundle');
expect(doFetch).toHaveBeenCalledWith(`${BASE}/Patient/Patient-123`, {
method: 'GET',
headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'application/fhir+json' },
});
});
it('throws the OperationOutcome diagnostics (not the raw body)', async () => {
const doFetch = vi.fn().mockResolvedValue(
res(403, { resourceType: 'OperationOutcome', issue: [{ diagnostics: 'access denied' }] }),
);
await expect(fhirFetch(getPatient(BASE, TOKEN, PID), doFetch)).rejects.toThrow(/access denied/);
});
it('throws on a non-2xx without echoing a PHI body', async () => {
const doFetch = vi.fn().mockResolvedValue(res(500, { resourceType: 'Bundle' }));
await expect(fhirFetch(getPatient(BASE, TOKEN, PID), doFetch)).rejects.toThrow(/FHIR 500/);
});
it('throws a length-only hint on non-JSON', async () => {
const doFetch = vi.fn().mockResolvedValue(new Response('<html>PHI leak</html>', { status: 502 }));
const err = await fhirFetch(getPatient(BASE, TOKEN, PID), doFetch).then(
() => new Error('expected a throw'),
(e: unknown) => e as Error,
);
expect(err.message).toMatch(/non-JSON/);
expect(err.message).not.toContain('PHI leak');
});
});
describe('fetchAllPages', () => {
it('walks Bundle next links and flattens resources', async () => {
const page1 = {
resourceType: 'Bundle',
entry: [{ resource: { resourceType: 'Condition', id: 'c1' } }],
link: [{ relation: 'next', url: `${BASE}/Condition?page=2` }],
};
const page2 = {
resourceType: 'Bundle',
entry: [{ resource: { resourceType: 'Condition', id: 'c2' } }],
link: [{ relation: 'self', url: `${BASE}/Condition?page=2` }],
};
const doFetch = vi
.fn()
.mockResolvedValueOnce(res(200, page1))
.mockResolvedValueOnce(res(200, page2));
const first = searchConditions({ base: BASE, token: TOKEN, patientId: PID });
const all = await fetchAllPages(first, TOKEN, { doFetch });
expect(all.map((r) => r.id)).toEqual(['c1', 'c2']);
expect(doFetch).toHaveBeenCalledTimes(2);
// The second call used the exact `next` URL, with the bearer re-attached.
expect(doFetch.mock.calls[1][0]).toBe(`${BASE}/Condition?page=2`);
expect(doFetch.mock.calls[1][1].headers.Authorization).toBe(`Bearer ${TOKEN}`);
});
it('stops at maxPages against an infinite pager', async () => {
const loop = {
resourceType: 'Bundle',
entry: [{ resource: { resourceType: 'Condition', id: 'c' } }],
link: [{ relation: 'next', url: `${BASE}/Condition?loop` }],
};
// A fresh Response per call — a Response body is single-use, so the same
// object cannot be returned twice (fhirFetch consumes it with .text()).
const doFetch = vi.fn().mockImplementation(async () => res(200, loop));
const first = searchConditions({ base: BASE, token: TOKEN, patientId: PID });
const all = await fetchAllPages(first, TOKEN, { doFetch, maxPages: 3 });
expect(doFetch).toHaveBeenCalledTimes(3);
expect(all).toHaveLength(3);
});
it('returns a single page when there is no next link', async () => {
const only = {
resourceType: 'Bundle',
entry: [{ resource: { resourceType: 'Condition', id: 'x' } }],
link: [{ relation: 'self', url: 'self' }],
};
const doFetch = vi.fn().mockResolvedValue(res(200, only));
const all = await fetchAllPages(searchConditions({ base: BASE, token: TOKEN, patientId: PID }), TOKEN, {
doFetch,
});
expect(all).toHaveLength(1);
expect(doFetch).toHaveBeenCalledTimes(1);
});
});
+195
View File
@@ -0,0 +1,195 @@
import { describe, it, expect, vi } from 'vitest';
import type { AiClient, ChatCompletion, ChatCompletionCreateParams } from '@hanzo/ai';
import {
CLINICAL_SYSTEM_PROMPT,
ACTIONS,
isActionId,
actionTask,
buildMessages,
extractContent,
ask,
runAction,
listModels,
} from '../src/hanzo.js';
import { DEFAULT_MODEL } from '../src/config.js';
// A fake @hanzo/ai client that records the create() params and returns a canned
// completion, so we assert request shaping with zero network.
function fakeClient(text = 'AI OUTPUT') {
const create = vi.fn(
async (
_params: ChatCompletionCreateParams,
_options?: { signal?: AbortSignal },
): Promise<ChatCompletion> => ({
id: 'x',
object: 'chat.completion',
created: 0,
model: 'zen5',
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
}),
);
const list = vi.fn(async (_options?: { signal?: AbortSignal }) => [
{ id: 'zen5', object: 'model' as const },
{ id: 'zen-eco', object: 'model' as const },
]);
const client = {
chat: { completions: { create } },
models: { list },
} as unknown as AiClient;
return { client, create, list };
}
describe('system prompt', () => {
it('grounds in the chart, forbids fabrication, and disclaims diagnosis', () => {
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/SMART on FHIR/);
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/never invent/i);
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/not a diagnosis/i);
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/clinician reviews/i);
});
});
describe('action catalog', () => {
it('exposes the four actions with prompt flags', () => {
expect(ACTIONS.map((a) => a.id)).toEqual(['summarize', 'note', 'extract', 'ask']);
expect(ACTIONS.find((a) => a.id === 'note')!.needsPrompt).toBe(true);
expect(ACTIONS.find((a) => a.id === 'ask')!.needsPrompt).toBe(true);
expect(ACTIONS.find((a) => a.id === 'summarize')!.needsPrompt).toBe(false);
expect(ACTIONS.find((a) => a.id === 'extract')!.needsPrompt).toBe(false);
});
it('isActionId is a strict boundary guard', () => {
expect(isActionId('summarize')).toBe(true);
expect(isActionId('delete')).toBe(false);
expect(isActionId('')).toBe(false);
});
});
describe('action prompt builders', () => {
it('summarize covers problems/meds/allergies/labs and forbids invention', () => {
const t = actionTask('summarize');
expect(t).toMatch(/active problems/i);
expect(t).toMatch(/medications/i);
expect(t).toMatch(/allergies/i);
expect(t).toMatch(/labs\/vitals/i);
expect(t).toMatch(/not in the chart/i);
});
it('note asks for SOAP and folds in the reason-for-visit', () => {
const t = actionTask('note', '72yo HTN follow-up');
expect(t).toMatch(/SOAP/);
expect(t).toMatch(/Subjective, Objective, Assessment, Plan/);
expect(t).toContain('72yo HTN follow-up');
// Without detail it still asks for SOAP but omits the input clause.
const bare = actionTask('note');
expect(bare).toMatch(/SOAP/);
expect(bare).not.toMatch(/clinician input:/);
});
it('extract asks for two structured lists (problems + meds)', () => {
const t = actionTask('extract');
expect(t).toMatch(/active problems/i);
expect(t).toMatch(/current medications/i);
expect(t).toMatch(/structured lists/i);
});
it('ask uses the question, or a sensible default', () => {
expect(actionTask('ask', 'Any drug interactions?')).toBe('Any drug interactions?');
expect(actionTask('ask')).toMatch(/most important thing/i);
});
});
describe('message assembly', () => {
it('fences the chart as data with a system + user turn', () => {
const msgs = buildMessages('SUMMARIZE', 'CHART TEXT');
expect(msgs).toHaveLength(2);
expect(msgs[0]).toEqual({ role: 'system', content: CLINICAL_SYSTEM_PROMPT });
expect(msgs[1].role).toBe('user');
const content = msgs[1].content as string;
expect(content).toContain('---- patient chart ----');
expect(content).toContain('CHART TEXT');
expect(content).toContain('---- end patient chart ----');
expect(content).toContain('---- task ----');
expect(content).toContain('SUMMARIZE');
});
it('with no chart, sends just the task', () => {
const content = buildMessages('ASK', '')[1].content as string;
expect(content).toBe('ASK');
});
it('honors a custom system prompt', () => {
expect(buildMessages('t', 'c', 'SYS')[0].content).toBe('SYS');
});
});
describe('extractContent', () => {
it('pulls the assistant message text', () => {
expect(
extractContent({
id: 'x',
object: 'chat.completion',
created: 0,
model: 'm',
choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],
}),
).toBe('hi');
});
it('throws on empty content', () => {
expect(() =>
extractContent({
id: 'x',
object: 'chat.completion',
created: 0,
model: 'm',
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
}),
).toThrow(/no content/);
});
});
describe('ask over the SDK client', () => {
it('sends model + fenced messages, non-streaming, and returns the text', async () => {
const { client, create } = fakeClient('SUMMARY');
const out = await ask('SUMMARIZE', 'CHART', { client });
expect(out).toBe('SUMMARY');
const params = create.mock.calls[0][0];
expect(params.model).toBe(DEFAULT_MODEL);
expect(params.stream).toBe(false);
expect(params.messages[0].role).toBe('system');
expect((params.messages[1].content as string)).toContain('CHART');
});
it('passes a model override + temperature + abort signal', async () => {
const { client, create } = fakeClient();
const signal = new AbortController().signal;
await ask('t', 'c', { client, model: 'zen-eco', temperature: 0.2, signal });
expect(create.mock.calls[0][0].model).toBe('zen-eco');
expect(create.mock.calls[0][0].temperature).toBe(0.2);
expect(create.mock.calls[0][1]).toEqual({ signal });
});
it('omits temperature from the wire when unset', async () => {
const { client, create } = fakeClient();
await ask('t', 'c', { client });
expect('temperature' in create.mock.calls[0][0]).toBe(false);
});
});
describe('runAction', () => {
it('forms the action task and asks over the chart', async () => {
const { client, create } = fakeClient('NOTE');
const out = await runAction({ id: 'note', detail: 'HTN f/u', chartContext: 'CHART', opts: { client } });
expect(out).toBe('NOTE');
const userMsg = create.mock.calls[0][0].messages[1].content as string;
expect(userMsg).toContain('SOAP');
expect(userMsg).toContain('HTN f/u');
expect(userMsg).toContain('CHART');
});
});
describe('listModels', () => {
it('returns model ids from the SDK', async () => {
const { client, list } = fakeClient();
expect(await listModels({ client })).toEqual(['zen5', 'zen-eco']);
expect(list).toHaveBeenCalled();
});
});
+185
View File
@@ -0,0 +1,185 @@
import { describe, it, expect, vi } from 'vitest';
import {
readServerConfig,
memoryStore,
discoverSmart,
exchangeCode,
ensureFreshToken,
resolveProxyTarget,
readSid,
type ServerConfig,
} from '../src/server.js';
import type { SmartContext } from '../src/smart-oauth.js';
function res(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
}
const CFG: ServerConfig = {
clientId: 'my-client',
clientSecret: 'shh',
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
sessionTtlMs: 3_600_000,
port: 8791,
};
const BASE = 'https://fhir.example.org/r4';
describe('readServerConfig', () => {
it('requires client id + redirect, secret optional', () => {
const cfg = readServerConfig({
SMART_CLIENT_ID: 'id',
SMART_REDIRECT_URI: 'https://x/cb',
});
expect(cfg.clientId).toBe('id');
expect(cfg.clientSecret).toBe(''); // public app
expect(cfg.port).toBe(8791);
});
it('reads the confidential secret when present', () => {
const cfg = readServerConfig({
SMART_CLIENT_ID: 'id',
SMART_REDIRECT_URI: 'https://x/cb',
SMART_CLIENT_SECRET: 's',
PORT: '9000',
SESSION_TTL_SECONDS: '600',
});
expect(cfg.clientSecret).toBe('s');
expect(cfg.port).toBe(9000);
expect(cfg.sessionTtlMs).toBe(600_000);
});
it('throws listing every missing required var', () => {
expect(() => readServerConfig({})).toThrow(/SMART_CLIENT_ID.*SMART_REDIRECT_URI/);
});
});
describe('discoverSmart', () => {
it('fetches the well-known and returns the endpoints', async () => {
const doFetch = vi.fn().mockResolvedValue(
res(200, { authorization_endpoint: `${BASE}/auth`, token_endpoint: `${BASE}/token` }),
);
const cfg = await discoverSmart(BASE, doFetch);
expect(cfg.authorizationEndpoint).toBe(`${BASE}/auth`);
expect(doFetch.mock.calls[0][0]).toBe(`${BASE}/.well-known/smart-configuration`);
});
it('rejects a non-http(s) iss (SSRF guard)', async () => {
await expect(discoverSmart('file:///etc/passwd')).rejects.toThrow(/http/);
await expect(discoverSmart('not-a-url')).rejects.toThrow(/valid URL/);
});
it('surfaces a discovery failure', async () => {
const doFetch = vi.fn().mockResolvedValue(res(404, {}));
await expect(discoverSmart(BASE, doFetch)).rejects.toThrow(/discovery 404/);
});
});
describe('exchangeCode (server-side secret + PKCE)', () => {
it('POSTs the exchange and parses the SMART context', async () => {
const doFetch = vi.fn().mockResolvedValue(
res(200, { access_token: 'AT', refresh_token: 'RT', expires_in: 3600, patient: 'P-1', scope: 's' }),
);
const pending = { state: 'st', codeVerifier: 'ver', tokenEndpoint: `${BASE}/token`, fhirBase: BASE };
const ctx = await exchangeCode(CFG, pending, 'the-code', doFetch);
expect(ctx.accessToken).toBe('AT');
expect(ctx.patient).toBe('P-1');
const [url, init] = doFetch.mock.calls[0];
expect(url).toBe(`${BASE}/token`);
const body = new URLSearchParams(init.body);
expect(body.get('code')).toBe('the-code');
expect(body.get('code_verifier')).toBe('ver');
expect(body.get('client_secret')).toBe('shh'); // confidential
});
it('surfaces an OAuth error from the token endpoint', async () => {
const doFetch = vi.fn().mockResolvedValue(res(400, { error: 'invalid_grant', error_description: 'bad code' }));
const pending = { state: 'st', codeVerifier: 'ver', tokenEndpoint: `${BASE}/token`, fhirBase: BASE };
await expect(exchangeCode(CFG, pending, 'x', doFetch)).rejects.toThrow(/bad code/);
});
});
describe('ensureFreshToken', () => {
const base = (expiresAt: number, refresh = 'RT'): SmartContext => ({
accessToken: 'OLD',
refreshToken: refresh,
tokenType: 'Bearer',
expiresAt,
patient: 'P-1',
encounter: '',
scope: 's',
idToken: '',
fhirBase: '',
});
it('returns the live token when not near expiry', async () => {
const store = memoryStore();
const sess = { ctx: base(Date.now() + 3_600_000), fhirBase: BASE, tokenEndpoint: `${BASE}/token` };
const doFetch = vi.fn();
expect(await ensureFreshToken(CFG, store, 'sid', sess, doFetch)).toBe('OLD');
expect(doFetch).not.toHaveBeenCalled();
});
it('refreshes an expired token and keeps the old refresh_token/patient', async () => {
const store = memoryStore();
store.putSession('sid', base(0), BASE, `${BASE}/token`);
const sess = store.getSession('sid')!;
const doFetch = vi.fn().mockResolvedValue(res(200, { access_token: 'NEW', expires_in: 3600 }));
const token = await ensureFreshToken(CFG, store, 'sid', sess, doFetch);
expect(token).toBe('NEW');
const updated = store.getSession('sid')!;
expect(updated.ctx.accessToken).toBe('NEW');
expect(updated.ctx.refreshToken).toBe('RT'); // preserved
expect(updated.ctx.patient).toBe('P-1'); // preserved
});
it('does not refresh when there is no refresh_token', async () => {
const store = memoryStore();
const sess = { ctx: base(0, ''), fhirBase: BASE, tokenEndpoint: `${BASE}/token` };
const doFetch = vi.fn();
expect(await ensureFreshToken(CFG, store, 'sid', sess, doFetch)).toBe('OLD');
expect(doFetch).not.toHaveBeenCalled();
});
});
describe('resolveProxyTarget (the PHI proxy guard)', () => {
it('resolves a relative allowed resource under the session base', () => {
expect(resolveProxyTarget(BASE, `Condition?patient=P-1&_count=50`)).toBe(
`${BASE}/Condition?patient=P-1&_count=50`,
);
expect(resolveProxyTarget(BASE, 'Patient/P-1')).toBe(`${BASE}/Patient/P-1`);
});
it('accepts an absolute next-page URL under the same base', () => {
const next = `${BASE}/Observation?patient=P-1&_getpages=abc`;
expect(resolveProxyTarget(BASE, next)).toBe(next);
});
it('refuses a resource type outside the read scopes', () => {
expect(() => resolveProxyTarget(BASE, 'Appointment?patient=P-1')).toThrow(/not permitted/);
expect(() => resolveProxyTarget(BASE, 'metadata')).toThrow(/not permitted/);
});
it('refuses a path that escapes the session FHIR base (SSRF / cross-tenant)', () => {
expect(() => resolveProxyTarget(BASE, 'https://evil.example.com/Condition')).toThrow(/escapes/);
expect(() => resolveProxyTarget(BASE, 'https://fhir.example.org/OTHER/Condition')).toThrow(/escapes/);
});
it('refuses a malformed path', () => {
expect(() => resolveProxyTarget(BASE, 'http://')).toThrow();
});
});
describe('session store + cookie', () => {
it('takePending is single-use (defends against state replay)', () => {
const store = memoryStore();
store.putPending({ state: 'st', codeVerifier: 'v', tokenEndpoint: 't', fhirBase: BASE });
expect(store.takePending('st')).toBeDefined();
expect(store.takePending('st')).toBeUndefined(); // replay yields nothing
});
it('readSid extracts the opaque session id from the cookie header', () => {
expect(readSid('foo=bar; epic_sid=abc123; baz=qux')).toBe('abc123');
expect(readSid('epic_sid=only')).toBe('only');
expect(readSid(undefined)).toBe('');
expect(readSid('no_session_here=1')).toBe('');
});
});
+256
View File
@@ -0,0 +1,256 @@
import { describe, it, expect } from 'vitest';
import { createHash, createHmac } from 'node:crypto';
import {
parseSmartConfiguration,
base64urlEncode,
randomVerifier,
challengeFromVerifier,
createPkce,
authorizeUrl,
tokenExchange,
tokenRefresh,
parseTokenResponse,
isExpired,
parseLaunch,
parseCallback,
} from '../src/smart-oauth.js';
// A deterministic SHA-256 that matches the browser subtle.digest contract, so
// the PKCE challenge is verifiable in a plain node test.
const nodeSha256 = async (input: string): Promise<Uint8Array> =>
new Uint8Array(createHash('sha256').update(input, 'utf8').digest());
describe('smart discovery', () => {
it('extracts authorize + token endpoints', () => {
const cfg = parseSmartConfiguration({
authorization_endpoint: 'https://ehr/auth',
token_endpoint: 'https://ehr/token',
capabilities: ['launch-ehr', 'client-confidential-symmetric'],
scopes_supported: ['openid', 'patient/Patient.read'],
});
expect(cfg.authorizationEndpoint).toBe('https://ehr/auth');
expect(cfg.tokenEndpoint).toBe('https://ehr/token');
expect(cfg.capabilities).toContain('launch-ehr');
expect(cfg.scopesSupported).toContain('patient/Patient.read');
});
it('throws when the authorize endpoint is missing', () => {
expect(() => parseSmartConfiguration({ token_endpoint: 'https://ehr/token' })).toThrow(
/authorization_endpoint/,
);
});
it('throws when the token endpoint is missing', () => {
expect(() => parseSmartConfiguration({ authorization_endpoint: 'https://ehr/auth' })).toThrow(
/token_endpoint/,
);
});
});
describe('PKCE', () => {
it('base64url has no +/= characters', () => {
const enc = base64urlEncode(new Uint8Array([251, 255, 191, 0, 62, 63]));
expect(enc).not.toMatch(/[+/=]/);
});
it('randomVerifier uses the injected randomness and is base64url', () => {
const bytes = new Uint8Array(32).fill(7);
const v = randomVerifier(() => bytes);
expect(v).toBe(base64urlEncode(bytes));
expect(v).not.toMatch(/[+/=]/);
// 32 bytes → 43 base64url chars (within the RFC 7636 43..128 range).
expect(v.length).toBe(43);
});
it('challenge = base64url(sha256(verifier)) — S256', async () => {
const verifier = 'test-verifier-value';
const challenge = await challengeFromVerifier(verifier, nodeSha256);
const expected = base64urlEncode(await nodeSha256(verifier));
expect(challenge).toBe(expected);
// Cross-check against the RFC 7636 canonical construction.
const rfc = createHash('sha256')
.update(verifier)
.digest('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
expect(challenge).toBe(rfc);
});
it('createPkce returns a verifier + matching S256 challenge', async () => {
const bytes = new Uint8Array(32).fill(9);
const pkce = await createPkce(() => bytes, nodeSha256);
expect(pkce.method).toBe('S256');
expect(pkce.verifier).toBe(base64urlEncode(bytes));
expect(pkce.challenge).toBe(await challengeFromVerifier(pkce.verifier, nodeSha256));
});
});
describe('authorize URL', () => {
const base = {
authorizationEndpoint: 'https://ehr/auth',
clientId: 'my-client',
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
aud: 'https://fhir/r4',
scope: 'launch openid patient/Patient.read',
state: 'st-123',
codeChallenge: 'chal-abc',
};
it('carries response_type, PKCE, aud and scope', () => {
const u = new URL(authorizeUrl(base));
expect(u.origin + u.pathname).toBe('https://ehr/auth');
const p = u.searchParams;
expect(p.get('response_type')).toBe('code');
expect(p.get('client_id')).toBe('my-client');
expect(p.get('redirect_uri')).toBe('https://epic.hanzo.ai/oauth/callback');
expect(p.get('aud')).toBe('https://fhir/r4');
expect(p.get('scope')).toBe('launch openid patient/Patient.read');
expect(p.get('state')).toBe('st-123');
expect(p.get('code_challenge')).toBe('chal-abc');
expect(p.get('code_challenge_method')).toBe('S256');
});
it('includes launch for an EHR launch and omits it standalone', () => {
expect(new URL(authorizeUrl({ ...base, launch: 'lt-9' })).searchParams.get('launch')).toBe('lt-9');
expect(new URL(authorizeUrl(base)).searchParams.has('launch')).toBe(false);
});
});
describe('token exchange shaping', () => {
it('shapes a confidential auth-code exchange with PKCE verifier + secret', () => {
const req = tokenExchange({
tokenEndpoint: 'https://ehr/token',
clientId: 'my-client',
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
code: 'auth-code',
codeVerifier: 'the-verifier',
clientSecret: 'shh',
});
expect(req.url).toBe('https://ehr/token');
expect(req.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('authorization_code');
expect(body.get('code')).toBe('auth-code');
expect(body.get('redirect_uri')).toBe('https://epic.hanzo.ai/oauth/callback');
expect(body.get('client_id')).toBe('my-client');
expect(body.get('code_verifier')).toBe('the-verifier');
expect(body.get('client_secret')).toBe('shh');
});
it('omits client_secret for a public (PKCE-only) app', () => {
const req = tokenExchange({
tokenEndpoint: 'https://ehr/token',
clientId: 'pub',
redirectUri: 'https://x/cb',
code: 'c',
codeVerifier: 'v',
});
expect(new URLSearchParams(req.body).has('client_secret')).toBe(false);
// PKCE verifier is ALWAYS present — a public app depends on it.
expect(new URLSearchParams(req.body).get('code_verifier')).toBe('v');
});
it('shapes a refresh with the stored refresh_token', () => {
const req = tokenRefresh({
tokenEndpoint: 'https://ehr/token',
clientId: 'my-client',
refreshToken: 'rt-1',
clientSecret: 'shh',
});
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('refresh_token');
expect(body.get('refresh_token')).toBe('rt-1');
expect(body.get('client_id')).toBe('my-client');
expect(body.get('client_secret')).toBe('shh');
});
});
describe('token response → SMART context', () => {
it('parses tokens + patient context and computes absolute expiry', () => {
const now = 1_000_000;
const ctx = parseTokenResponse(
{
access_token: 'AT',
refresh_token: 'RT',
token_type: 'Bearer',
expires_in: 3600,
scope: 'launch patient/Patient.read',
patient: 'Patient-42',
encounter: 'Enc-7',
id_token: 'IDT',
},
now,
);
expect(ctx.accessToken).toBe('AT');
expect(ctx.refreshToken).toBe('RT');
expect(ctx.tokenType).toBe('Bearer');
expect(ctx.expiresAt).toBe(now + 3600 * 1000);
expect(ctx.patient).toBe('Patient-42');
expect(ctx.encounter).toBe('Enc-7');
expect(ctx.scope).toBe('launch patient/Patient.read');
expect(ctx.idToken).toBe('IDT');
});
it('defaults missing optionals to empty strings', () => {
const ctx = parseTokenResponse({ access_token: 'AT', expires_in: 300 }, 0);
expect(ctx.refreshToken).toBe('');
expect(ctx.patient).toBe('');
expect(ctx.encounter).toBe('');
expect(ctx.tokenType).toBe('Bearer');
});
it('throws on an OAuth error payload with the real reason', () => {
expect(() =>
parseTokenResponse({ error: 'invalid_grant', error_description: 'code expired' }),
).toThrow(/code expired/);
});
it('throws when there is no access_token', () => {
expect(() => parseTokenResponse({ token_type: 'Bearer' })).toThrow(/no access_token/);
});
});
describe('isExpired', () => {
it('is true at/after expiry (minus skew) and false before', () => {
expect(isExpired({ expiresAt: 100_000 }, 0, 60_000)).toBe(false); // well before
expect(isExpired({ expiresAt: 100_000 }, 50_000, 60_000)).toBe(true); // within skew window
expect(isExpired({ expiresAt: 100_000 }, 100_001, 60_000)).toBe(true); // past expiry
expect(isExpired({ expiresAt: 100_000 }, 39_999, 60_000)).toBe(false); // just before the skew window
});
});
describe('launch + callback parsing', () => {
it('parses an EHR launch (iss + launch)', () => {
const l = parseLaunch('?iss=https%3A%2F%2Ffhir%2Fr4&launch=xyz');
expect(l.iss).toBe('https://fhir/r4');
expect(l.launch).toBe('xyz');
});
it('tolerates a cold open (no params)', () => {
const l = parseLaunch('');
expect(l.iss).toBe('');
expect(l.launch).toBe('');
});
it('parses a success callback', () => {
const c = parseCallback('?code=abc&state=st');
expect(c.code).toBe('abc');
expect(c.state).toBe('st');
expect(c.error).toBe('');
});
it('parses a declined callback with a reason', () => {
const c = parseCallback('?error=access_denied&error_description=user%20declined');
expect(c.error).toBe('access_denied');
expect(c.errorDescription).toBe('user declined');
expect(c.code).toBe('');
});
});
// Guard: the module must not accidentally depend on hmac/secret material for
// PKCE (a common wrong turn). PKCE is a plain hash — this asserts the intent.
describe('PKCE is a plain SHA-256, not an HMAC', () => {
it('challenge does not match an HMAC construction', async () => {
const verifier = 'v';
const challenge = await challengeFromVerifier(verifier, nodeSha256);
const hmac = createHmac('sha256', 'anykey').update(verifier).digest('base64url');
expect(challenge).not.toBe(hmac);
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node"],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/**/*.test.ts'],
environment: 'node',
},
});
+11 -3
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/figma",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI for Figma — a plugin that rewrites, translates, content-fills, critiques (with accessibility notes), renames, and generates copy variants for the selected layers, built on the published @hanzo/ai headless client against api.hanzo.ai. The AI call runs in the plugin iframe; the main thread reads the selection and writes results back onto the canvas.",
"private": true,
"type": "module",
"scripts": {
"build": "node build.js",
@@ -24,5 +23,14 @@
"engines": {
"node": ">=18.0.0"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/code.js"
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/github",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI on GitHub — a GitHub App that reviews pull requests, triages issues, and answers @hanzo mentions, built on @hanzo/ai and @hanzo/iam.",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hanzo/gitlab",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI on GitLab — a webhook service that reviews merge requests, triages issues, and answers @hanzo mentions, built on @hanzo/ai and @hanzo/iam.",
"type": "module",
"main": "./dist/index.js",
+9 -3
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/gworkspace-addon",
"version": "1.9.30",
"description": "Hanzo AI for Google Workspace \u2014 a Google Docs, Sheets, Slides, and Gmail add-on (Apps Script + CardService). AI over your document, wired to the same api.hanzo.ai gateway as the browser extension and the Office add-in.",
"private": true,
"description": "Hanzo AI for Google Workspace a Google Docs, Sheets, Slides, and Gmail add-on (Apps Script + CardService). AI over your document, wired to the same api.hanzo.ai gateway as the browser extension and the Office add-in.",
"type": "module",
"scripts": {
"test": "vitest run",
@@ -20,5 +19,12 @@
"engines": {
"node": ">=18.0.0"
},
"license": "MIT"
"license": "MIT",
"publishConfig": {
"access": "public"
},
"files": [
"src",
"README.md"
]
}
+4 -2
View File
@@ -1,8 +1,7 @@
{
"name": "@hanzo/hubspot",
"version": "0.1.0",
"version": "1.0.0",
"description": "Hanzo AI for HubSpot — AI over your CRM records: summarize a contact/company/deal, draft an email, suggest next steps, and ask anything, with one-click write-back as a Note or Task. A CRM card UI extension plus a serverless backend that holds the Hanzo key and calls @hanzo/ai over the api.hanzo.ai gateway; the key never reaches the browser.",
"private": true,
"type": "module",
"main": "./dist/cjs/index.js",
"module": "./dist/index.js",
@@ -64,5 +63,8 @@
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/hubspot"
},
"publishConfig": {
"access": "public"
}
}
+262
View File
@@ -0,0 +1,262 @@
# Hanzo AI for iManage
AI over your iManage Work matter — **summarize a document**, **extract key clauses,
dates & parties** (contract review), **search & synthesize** across a matter, and
**compare a document set**, plus a freeform "ask about this matter" box. An
embedded-app **panel** you host at `imanage.hanzo.ai`, backed by a small **OAuth +
Work-API-proxy service** that keeps the iManage client secret and access tokens
server-side.
iManage Work is the dominant document management system (DMS) in legal and
professional services. This app reads workspaces, folders, documents (metadata +
content), and search results through the iManage Work API and grounds every AI
answer in them.
Built on the published Hanzo SDK:
- **[`@hanzo/ai`](https://www.npmjs.com/package/@hanzo/ai)** — the headless client.
`createAiClient({ baseUrl, token }).chat.completions.create({ model, messages })`
and `.models.list()`. All model calls go to `https://api.hanzo.ai` on `/v1/...`
(never an `/api/` prefix). We import it; we do not reimplement the transport.
- **[`@hanzo/iam`](https://www.npmjs.com/package/@hanzo/iam)** — Hanzo identity /
the `hk-…` API key the panel uses as its gateway bearer.
> **Note on `/api/`.** The `/api/` ban is a **Hanzo gateway** rule (`api.hanzo.ai`
> IS the api host, so paths are `/v1/...`). iManage's **own** Work API path is
> `/api/v2/...` — that is iManage's host, and it is correct to use it verbatim.
---
## Architecture
```
Browser panel (dist/index.html, app.js) Server service (dist/server.js)
───────────────────────────────────── ──────────────────────────────
reads iManage via ──► /proxy/* ──────────► injects the access token
same-origin proxy (cookie) (X-Auth-Token) + refresh, forwards
(never sees an iManage token) to {host}/api/v2/customers/…
└── calls api.hanzo.ai /v1 directly with the pasted hk-… Hanzo key
(@hanzo/ai headless client)
```
- The **panel** never holds an iManage token or the client secret. It reaches
iManage only through the same-origin `/proxy/*` endpoint (with an HttpOnly
session cookie). It talks to `api.hanzo.ai` directly with the user's pasted Hanzo
key. The customer + library scope lives in the request **path**
(`/customers/{cid}/libraries/{lib}/…`), so the proxy just prepends the Work API
base and forwards.
- The **service** is the only place `IMANAGE_CLIENT_SECRET` and the OAuth tokens
exist. It runs the install flow, holds the session, refreshes the token
transparently, and proxies Work API calls.
### Source layout (all pure logic is unit-tested)
| File | Responsibility |
| --- | --- |
| `src/config.ts` | Host resolution (normalize/validate a per-customer iManage host), the `/api/v2` Work API root, the gateway URL, server-secret config (`readServerConfig` fails fast). |
| `src/imanage-oauth.ts` | OAuth2 Authorization-Code shaping: `authorizeUrl`, `tokenExchange`, `refreshExchange`, token parsing + expiry math. Pure. |
| `src/imanage-api.ts` | Work API v2 request wrappers (`listWorkspaces`, `listFolderChildren`, `getDocument`, `getDocumentContent`, `search`, `updateDocumentProfile`) with customer/library scoping + offset/limit pagination, and envelope-aware response parsers. Pure. |
| `src/documents.ts` | Document profile + extracted content + workspace/folder/search JSON → windowed context text + honest truncation, and text extraction (`extractText`, binary/OCR out of scope). Pure. |
| `src/hanzo.ts` | Thin over `@hanzo/ai`: legal-grounded prompt assembly + the single `ask` path + `listModels`. |
| `src/actions.ts` | The four AI actions (id → prompt) over `ask`. One code path to the model. |
| `src/panel.ts` | Browser proxy-client request shaping + launch-context parsing. Pure. |
| `src/app.ts` | The DOM glue for the panel (the one impure browser entry). |
| `src/server.ts` | Node http service: OAuth install/callback + `/config` + `/proxy/*`. Never logs document content. |
---
## 1. Register an app in the iManage Control Center
In the **iManage Control Center** for your customer:
1. Go to **Applications****Add** and register a new OAuth2 application. This
yields a **Client ID** and **Client Secret**.
2. Set the **grant type** to **Authorization Code** and add the **redirect URI**
exactly the URL your service serves the callback at:
```
https://imanage.hanzo.ai/oauth/callback
```
(For local development, add `http://localhost:8793/oauth/callback` too.)
3. Scope is optional for the Authorization-Code app — access is governed by the
signed-in user's own Work permissions. (If your Control Center offers scopes,
grant read access to documents/workspaces and, for the optional write-back,
document profile update.)
4. Note your **iManage host**, your **customer id**, and the **library id(s)** you
work in (e.g. `ACTIVE_US`). The host is per-customer:
| Deployment | Host |
| --- | --- |
| iManage Cloud (US) | `https://cloudimanage.com` |
| Regional cloud | `https://<region>.imanage.work` |
| On-prem Work server | `https://work.<firm>.com` |
The OAuth control-center endpoints and the Work API are served from this host
(set `IMANAGE_API_HOST` if your Work API is fronted separately).
---
## 2. OAuth flow
Standard **Authorization Code** grant (server-side secret):
1. `GET /oauth/install` → 302 to
`https://{host}/auth/oauth2/authorize?response_type=code&client_id=…&redirect_uri=…&state=…`.
2. The user signs in and consents; iManage redirects back to
`GET /oauth/callback?code=…&state=…`.
3. The service verifies `state`, then POSTs to `/auth/oauth2/token` with
`grant_type=authorization_code`, the `code`, the `client_id` + `client_secret`
(**in the body, server-side only**), and the same `redirect_uri`.
4. It opens a session, sets an HttpOnly cookie, and the panel is authenticated.
5. Access tokens are short-lived. The service refreshes with
`grant_type=refresh_token` **before** each proxied call when the token has
expired, storing whatever refresh token comes back.
> In-memory sessions here are for a single instance. For a multi-instance
> deployment behind `hanzoai/ingress`, persist sessions + the OAuth `state` set to
> `hanzoai/kv` (Valkey), and read `IMANAGE_CLIENT_SECRET` from KMS
> (`kms.hanzo.ai`) — never from a committed env file.
---
## 3. iManage Work API
All reads/writes go through `https://{host}/api/v2/...`, scoped by customer +
library in the path. The access token rides in the **`X-Auth-Token`** header
(iManage's Work API convention).
| Capability | Endpoint (relative to `/api/v2`) |
| --- | --- |
| Libraries | `GET /customers/{cid}/libraries` |
| Workspaces | `GET /customers/{cid}/libraries/{lib}/workspaces` |
| Workspace (detail) | `GET …/workspaces/{id}` |
| Folder / workspace contents | `GET …/folders/{folderId}/children` (folders + documents) |
| Document (profile) | `GET …/documents/{id}` |
| Document content | `GET …/documents/{id}/download` |
| Search | `GET …/documents/search?q=…` |
| **Profile write-back** (optional) | `PATCH …/documents/{id}` — body `{ "data": { "comment": "…" } }` |
Responses are wrapped in an iManage `{ "data": … }` envelope; list/search endpoints
paginate with **`offset` + `limit`** and report totals/overflow in the body
(surfaced by `parsePaging`). All of this is normalized at the parser boundary.
### Document content & text extraction
`getDocumentContent` fetches `…/documents/{id}/download`. This app assumes **text or
server-exported text**; `extractText` cleans it for the model. **Binary formats**
(native `.docx`/`.pdf`, images) and **OCR are out of scope** — such content is
reported honestly (`extracted: false` with a reason) and the actions summarize from
the **profile metadata** alone rather than feeding the model garbage.
---
## 4. The summarize-document / extract-clauses flow
1. Connect the app (`/oauth/install`) so the service holds an iManage token.
2. Open the panel, enter your **customer id** + **library id** (or arrive
pre-scoped via the launch-context query / a single-tenant `/config`), and
**Browse** a workspace. Pick a document and **Load doc** — the panel pulls the
document's profile + content through the proxy and assembles a windowed,
truncation-honest context.
3. **Summarize document** — the model summarizes the document type, purpose,
parties, key terms, and anything needing attention, grounded only in the text
(or the profile, when content isn't extractable).
4. **Key clauses, dates & parties** — a contract-review extraction returning four
grounded lists: **Parties**, **Key dates**, **Key clauses** (governing law,
indemnity, limitation of liability, confidentiality, termination — quoting the
operative language), and **Dollar amounts**. Anything not written is reported as
"None found in the text" — never inferred.
5. **Search & synthesize** — enter a query, **Search** the library, and run the
action to synthesize across the result set, attributing each point to its
document.
6. **Compare document set** — over a search result set (or a matter), lists the
material differences side by side.
### Optional write-back (gated + documented)
**Save to comment** writes the current result into the loaded document's **`comment`
profile field** via `PATCH …/documents/{id}` — behind an explicit button **and** a
confirm dialog, targeting only the single loaded document (disabled for a search
result set). It never touches document content. This is the only write path; leave
it unused for a strictly read-only deployment.
---
## Confidentiality posture (legal)
This app handles **confidential, potentially privileged** legal documents. The
design keeps that boundary tight:
- **Tokens + secret are server-side only.** The browser never receives the iManage
access token or the client secret; it reaches iManage exclusively through the
same-origin proxy with an HttpOnly session cookie.
- **No document content is ever logged.** The proxy logs only non-content
bookkeeping (a session id, a status, a target path) — never request/response
bodies, document text, profiles, or search terms.
- **The model is told the material is confidential** and instructed to reveal no
more of the text than the task requires, to never invent clauses/dates/parties,
and that its output is **informational document review, not legal advice** (no
attorney-client relationship).
- **Grounded, truncation-honest context.** Answers are built only from the windowed
records actually sent; when the budget truncates, the context note says so and the
model is told to flag it rather than guess.
- **Least privilege.** Read-and-assist is the default; the one write path is gated
behind an explicit action + confirm and updates only a profile comment.
---
## Build & run
```bash
pnpm install
pnpm --filter @hanzo/imanage build # → dist/ (panel + server)
pnpm --filter @hanzo/imanage test # vitest
pnpm --filter @hanzo/imanage typecheck # tsc --noEmit
# run the service
IMANAGE_CLIENT_ID=… \
IMANAGE_CLIENT_SECRET=… \
IMANAGE_REDIRECT_URI=https://imanage.hanzo.ai/oauth/callback \
IMANAGE_HOST=https://cloudimanage.com \
node packages/imanage/dist/server.js
```
### Required / optional environment (service)
| Var | Notes |
| --- | --- |
| `IMANAGE_CLIENT_ID` | App client id (public). |
| `IMANAGE_CLIENT_SECRET` | **Server only.** From KMS in production. |
| `IMANAGE_REDIRECT_URI` | Must match the app's registered redirect. |
| `IMANAGE_HOST` | The customer's iManage host (auth + Work API). |
| `IMANAGE_API_HOST` | Optional — a distinct Work API host (defaults to `IMANAGE_HOST`). |
| `IMANAGE_CUSTOMER_ID` | Optional — panel scoping default (served at `/config`). |
| `IMANAGE_LIBRARY_ID` | Optional — panel scoping default (served at `/config`). |
| `PORT` | Listen port (default `8793`). |
`readServerConfig` throws on a missing secret or a malformed host — the service
refuses to start rather than pretend it can complete an OAuth exchange.
---
## Deploy over hanzoai/ingress
Host the static panel (`dist/index.html`, `app.js`, `styles.css`) with the
**hanzoai/static** plugin and run `dist/server.js` as a small service, both behind
**hanzoai/ingress** at `imanage.hanzo.ai` (no nginx, no caddy):
- `/` and the static assets → the panel.
- `/oauth/*`, `/config`, `/proxy/*`, `/healthz` → the service.
Secrets come from **KMS** as `KMSSecret`-synced env; sessions from **Valkey**
(`hanzoai/kv`) for multi-instance. Image published to
`ghcr.io/hanzoai/imanage:<tag>` by CI/CD (platform.hanzo.ai / Tekton) — never built
locally.
---
*Routed through `api.hanzo.ai`. Answers are grounded in your iManage document
records — informational document review support, not legal advice, and no
attorney-client relationship is created.*
+86
View File
@@ -0,0 +1,86 @@
// Build @hanzo/imanage into dist/: bundle the web panel (app.ts) as ESM for the
// browser, copy index.html (with its entry script stamped) + styles.css, and
// bundle the OAuth + Work-API-proxy server for Node. No framework — esbuild + Node
// stdlib only. @hanzo/ai is bundled into both outputs (it is the headless client
// the panel and server both call).
//
// node build.js → production build
// node build.js --watch → rebuild on change
// HANZO_IMANAGE_BASE=https://localhost:8443 node build.js → dev base (informational)
//
// Output layout:
// dist/index.html dist/app.js dist/styles.css (panel)
// dist/server.js (service)
//
// The panel is HOSTED over hanzoai/static behind hanzoai/ingress at
// imanage.hanzo.ai; the server runs as a small service (OAuth callback + Work API
// proxy). All model calls go to api.hanzo.ai regardless of the host base.
import esbuild from 'esbuild';
import { rmSync, mkdirSync, copyFileSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE = (process.env.HANZO_IMANAGE_BASE || 'https://imanage.hanzo.ai').replace(/\/+$/, '');
const watch = process.argv.includes('--watch');
const src = join(__dirname, 'src');
const dist = join(__dirname, 'dist');
async function build() {
rmSync(dist, { recursive: true, force: true });
mkdirSync(dist, { recursive: true });
// Bundle the panel as ESM for the browser.
const panelCtx = await esbuild.context({
entryPoints: { app: join(src, 'app.ts') },
outdir: dist,
bundle: true,
format: 'esm',
platform: 'browser',
target: ['chrome90', 'edge90', 'firefox90', 'safari15'],
sourcemap: true,
minify: !watch,
logLevel: 'info',
});
await panelCtx.rebuild();
// Copy index.html (stamp __ENTRY__ + base) and styles.css.
const html = readFileSync(join(src, 'index.html'), 'utf8')
.split('__ENTRY__').join('app.js')
.replace('</head>', ` <meta name="hanzo:base" content="${BASE}" />\n</head>`);
writeFileSync(join(dist, 'index.html'), html);
copyFileSync(join(src, 'styles.css'), join(dist, 'styles.css'));
// Bundle the server as a Node ESM binary — our pure stdlib code + @hanzo/ai.
const serverCtx = await esbuild.context({
entryPoints: [join(src, 'server.ts')],
outfile: join(dist, 'server.js'),
bundle: true,
format: 'esm',
platform: 'node',
target: ['node18'],
sourcemap: true,
minify: !watch,
banner: { js: "import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);" },
logLevel: 'info',
});
await serverCtx.rebuild();
console.log(`Hanzo AI for iManage built -> dist/ (base ${BASE})`);
console.log(' Panel: dist/index.html · Service: dist/server.js');
if (watch) {
await panelCtx.watch();
await serverCtx.watch();
console.log('watching...');
} else {
await panelCtx.dispose();
await serverCtx.dispose();
}
}
build().catch((e) => {
console.error(e);
process.exit(1);
});
+52
View File
@@ -0,0 +1,52 @@
{
"name": "@hanzo/imanage",
"version": "1.0.0",
"description": "Hanzo AI for iManage Work — AI over your legal document management system: summarize a document, extract key clauses / dates / parties, search-and-synthesize a matter/workspace, and compare a document set. An embedded-app panel plus an OAuth + Work-API-proxy service, built on @hanzo/ai and @hanzo/iam over the api.hanzo.ai gateway.",
"type": "module",
"scripts": {
"build": "node build.js",
"watch": "node build.js --watch",
"start": "node dist/server.js",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@hanzo/ai": "^0.2.0",
"@hanzo/iam": "^0.13.2"
},
"devDependencies": {
"@types/node": "^20.14.0",
"esbuild": "^0.25.8",
"typescript": "^5.8.3",
"vitest": "^3.2.6"
},
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"hanzo",
"imanage",
"legal",
"dms",
"document-management",
"contract-review",
"ai",
"oauth"
],
"author": "Hanzo AI",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/imanage"
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"README.md"
],
"main": "dist/server.js"
}
+99
View File
@@ -0,0 +1,99 @@
// The AI actions over an iManage document / matter — summarize a document, extract
// key clauses / dates / parties (contract review), search-and-synthesize a matter,
// and compare a document set. Each is a prompt template applied to the windowed
// document context via the single `ask` primitive in hanzo.ts. There is exactly
// ONE code path to the model: an action is (id → prompt), and the panel and any
// server-side caller resolve an id here and call `ask`. No action speaks to the
// gateway directly. (A freeform "ask about the matter" is `ask` directly, not an
// action — it has no fixed prompt.)
import { ask, type AskOptions, type MatterMeta } from './hanzo.js';
import type { DocumentContext } from './documents.js';
// The action catalog. `id` is the stable key the panel's chips use; `label` is the
// button text; `prompt` is the instruction handed to the model as the task, over
// the fenced document records. Prompts are specific and output-shaped (bullets,
// structured lists) so results are consistent and parseable.
export const ACTIONS = {
summarizeDocument: {
label: 'Summarize document',
prompt:
'Summarize the document in these records for a lawyer skimming the matter. ' +
'Cover: what kind of document it is, its purpose, the parties, the key terms ' +
'or obligations, and anything unusual or that needs attention. Reference the ' +
'document name. Use short bullets. No preamble. Ground every statement in the ' +
'text; if the content was not extractable and you only have the profile, say ' +
'so and summarize from the metadata alone.',
},
extractClauses: {
label: 'Key clauses, dates & parties',
prompt:
'Perform a contract-review extraction over the document in these records. ' +
'Return four labelled lists, each grounded strictly in the text: "Parties" ' +
'(every named party and their role); "Key dates" (effective date, term, ' +
'renewal, termination, and any deadline, each with what it governs); "Key ' +
'clauses" (governing law, indemnity, limitation of liability, confidentiality, ' +
'assignment, termination, and any other material clause — quote the operative ' +
'language); and "Dollar amounts / figures" (fees, caps, penalties). If a list ' +
'has no entries in the text, write "None found in the text." Never infer a ' +
'term that is not written.',
},
synthesizeMatter: {
label: 'Search & synthesize',
prompt:
'You are given a set of documents (or search results) from one matter. ' +
'Synthesize an answer to the matter question or, if none is posed, a short ' +
'briefing across the set: what the documents collectively establish, where ' +
'they agree, where they conflict, and what is missing. Attribute each point to ' +
'the document it comes from by name or number. Base every statement on the ' +
'records; if the set is marked truncated, note that the synthesis covers only ' +
'the shown documents.',
},
compareDocuments: {
label: 'Compare document set',
prompt:
'Compare the documents in these records. Produce: a one-line statement of what ' +
'they have in common; then a table-style list of the material differences ' +
'(term, obligation, date, amount, or clause) with each document\'s position ' +
'side by side; then any provision present in one document but absent in ' +
'another. Reference each document by name or number. Compare only what the ' +
'text supports — do not assume a standard or a missing term.',
},
} as const;
// An action id from the catalog.
export type ActionId = keyof typeof ACTIONS;
// isActionId narrows an arbitrary string to a known action id. Boundary guard —
// the panel and the server validate an inbound id here before running it.
export function isActionId(id: string): id is ActionId {
return Object.prototype.hasOwnProperty.call(ACTIONS, id);
}
// actionPrompt resolves an action id to its prompt template. Throws on an unknown
// id (a boundary error, surfaced to the caller) rather than silently running a
// default. Pure.
export function actionPrompt(id: string): string {
if (!isActionId(id)) throw new Error(`Unknown action: ${id}`);
return ACTIONS[id].prompt;
}
// actionList is the ordered catalog for building the UI (chips) — id + label,
// derived from ACTIONS so the panel and the catalog can never drift. Pure.
export function actionList(): Array<{ id: ActionId; label: string }> {
return (Object.keys(ACTIONS) as ActionId[]).map((id) => ({ id, label: ACTIONS[id].label }));
}
// runAction is the single entry point every surface calls: resolve the action's
// prompt and run it over the windowed document context via `ask`. This is the one
// code path from an action id to the model. Async so an unknown id surfaces as a
// rejected promise (not a synchronous throw), giving callers ONE way to handle
// failure: `await`/`.catch`. A gateway error rejects via `ask`.
export async function runAction(
id: string,
ctx: DocumentContext,
meta?: MatterMeta,
opts: AskOptions = {},
): Promise<string> {
return ask(actionPrompt(id), ctx, meta, opts);
}

Some files were not shown because too many files have changed in this diff Show More