auto-model-router 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,14 +7,14 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "auto-model-router: a local cost/complexity-aware model router for Oh My Pi, backed by OpenRouter",
10
- "version": "0.15.0",
10
+ "version": "0.17.0",
11
11
  "pluginRoot": "."
12
12
  },
13
13
  "plugins": [
14
14
  {
15
15
  "name": "auto-model-router",
16
16
  "description": "Local cost/complexity-aware model router for Oh My Pi, backed by OpenRouter. Runs in-process, routes per turn by price and task complexity, with budget caps, mid-stream escalation, and cache-aware hysteresis.",
17
- "version": "0.15.0",
17
+ "version": "0.17.0",
18
18
  "author": {
19
19
  "name": "drewappling",
20
20
  "email": "drewappling@gmail.com"
package/README.md CHANGED
@@ -1343,6 +1343,9 @@ the embed extension sets it from the workspace as it loads. If the variable is u
1343
1343
  sends the name itself, which the router does not accept as a scope (a scope is a
1344
1344
  lowercase slug) and falls back to its default. `--scope <slug>` pins one project for the
1345
1345
  whole machine instead; a refresh keeps a pin, and `connect --scope ""` removes it.
1346
+ `X-Agentdox-Origin` rides the same way under `AUTO_MODEL_ROUTER_ORIGIN`, set from the
1347
+ workspace's git remote; a pinned scope does not pin it, because the repository a turn
1348
+ came from is still the workspace's. See [the origin fingerprint](#the-origin-fingerprint).
1346
1349
 
1347
1350
  ### One file to install
1348
1351
 
@@ -1519,6 +1522,45 @@ them, injecting one project's context into another's work. A single configured t
1519
1522
  grants only the scopes it was minted for; for any other project the bridge degrades to inert
1520
1523
  rather than writing somewhere wrong.
1521
1524
 
1525
+ ### Layers a team names around the project scope
1526
+
1527
+ A front door such as the team edition can wrap the project scope in two more
1528
+ layers, named per request in headers next to `X-Agentdox-Scope`:
1529
+
1530
+ | Header | What agentdox renders |
1531
+ | --- | --- |
1532
+ | `X-Agentdox-Group` | the group's context — its brief and top memory — **first**, as `# Group context: <group>` |
1533
+ | `X-Agentdox-Personal` | the member's own thread in the project — the entry tagged `handoff` whole, then the rest — **last**, as `# Your thread in <scope>` |
1534
+
1535
+ Both go through the same slug rule as the scope (absent or invalid ⇒ empty ⇒ not
1536
+ sent). The member is the harness id (`X-Omp-Harness`, which the team sets from the
1537
+ authenticated key): when either layer is named it is sent as `user` too, and agentdox
1538
+ keeps the project layer's recent tail to that member's own turns. It is never sent on
1539
+ its own — a router without a team still has a harness id (Claude Code's is derived,
1540
+ omp's is configured) and must not have its tail filtered to one harness. Every
1541
+ recorded message carries a `user:<harness id>` ref alongside `model:` and `tier:`
1542
+ whenever there is a harness id, team or not; it is just another ref. A router without
1543
+ a team posts exactly what it always did, so its block is byte-identical; an older
1544
+ agentdox ignores the keys it does not know. `context.layers: false` is the kill
1545
+ switch — the headers are still parsed but nothing new goes to agentdox.
1546
+
1547
+ ### The origin fingerprint
1548
+
1549
+ The scope is the folder's name, and folder names collide: two unrelated repositories
1550
+ checked out as `api` would share one project, and one repository cloned into `~/work/api`
1551
+ and `~/src/backend-api` would split into two. So the embed extension also sends
1552
+ `X-Agentdox-Origin`: the workspace's git remote `origin`, normalised to `<host>/<path>` —
1553
+ lowercase, no scheme, credentials, port, `.git` or trailing slash — so
1554
+ `https://github.com/DrewAppling/omp-router.git` and `git@github.com:drewappling/omp-router.git`
1555
+ are both `github.com/drewappling/omp-router`. It is read from `.git/config` (or through a
1556
+ worktree's `.git` file) with the filesystem alone, never by running git, and a workspace
1557
+ outside a repository or with a local-path remote sends none. Like the scope it reaches the
1558
+ main model through an environment variable, `AUTO_MODEL_ROUTER_ORIGIN`, that the managed
1559
+ `models.yml` entry names and the extension sets. A team edition uses it to find the
1560
+ project a workspace belongs to whatever the folder is called; a router on its own has no
1561
+ project registry and ignores it — the header is parsed and validated (a raw URL or the
1562
+ variable's name is dropped) and nothing else changes.
1563
+
1522
1564
  ### It does not cost you a cache miss per turn
1523
1565
 
1524
1566
  The context block sits at the front of the prompt, so re-fetching it every turn
@@ -1549,7 +1591,8 @@ block lands inside the prefix `planCacheBreakpoints` already marks.
1549
1591
  ### Turns are recorded back, attributed to the model that served them
1550
1592
 
1551
1593
  With `context.recordTurns` (default on), each settled turn is written to an
1552
- agentdox session tagged `model:<slug>` and `tier:<tier>` a transcript that
1594
+ agentdox session tagged `model:<slug>` and `tier:<tier>` (plus `user:<harness id>`
1595
+ when the request carried one) — a transcript that
1553
1596
  shows which model produced which turn. Those messages feed back into the next
1554
1597
  `context_assemble`, so the model you switch *to* inherits what the model you
1555
1598
  switched *from* actually did.
@@ -32,7 +32,8 @@ unchanged re-assembly keeps the same bytes and the cache survives.
32
32
  | `src/context/store.ts` | `context_blocks` (content-addressed) + `agentdox_sessions` |
33
33
  | `src/context/index.ts` | `createBridgeFromConfig` — returns an inert bridge when unconfigured |
34
34
  | `src/server/turn.ts` | Resolve → inject → pin → record. Two `log.debug("agentdox …")` lines |
35
- | `src/wire/openai/request.ts` | `injectContextBlock` + `x-agentdox-scope` header parsing |
35
+ | `src/wire/openai/request.ts` | `injectContextBlock` + the `x-agentdox-*` header parsing (the Anthropic path delegates to it) |
36
+ | `src/context/scope.ts` | The slug and origin rules, and the env-var names the managed provider entries carry |
36
37
  | `src/util/sqlite.ts` | `USER_VERSION` 11, `MIGRATE_V11` |
37
38
  | `test/context-bridge.test.ts` | 14 tests: every refresh trigger, restart survival, degradation |
38
39
  | `tools/agentdox-e2e.ts` | Live check against a running agentdox server |
@@ -41,6 +42,22 @@ Injection appends to the **last system message** rather than inserting one — i
41
42
  shift every `cacheBreakpointMessageIndices` entry the core computed, and appending lands the
42
43
  block inside the prefix `planCacheBreakpoints` already marks.
43
44
 
45
+ ### The request headers
46
+
47
+ Every one is optional; absent or invalid ⇒ empty, and an empty value sends nothing new to
48
+ agentdox, so a router without a front door behaves as it always did.
49
+
50
+ | Header | Since | Value | Who sends it | What the router does |
51
+ | --- | --- | --- | --- | --- |
52
+ | `X-Agentdox-Scope` | 0.2 | a project slug (`isScopeSlug`) | the embed extension, from the workspace folder; the managed `models.yml` entry names `AUTO_MODEL_ROUTER_SCOPE` and the extension sets it | selects the project whose context is injected and whose sessions the turn is recorded into; empty ⇒ `context.defaultScope` |
53
+ | `X-Agentdox-Group` | 0.16.0 | a slug | a front door (the team edition), per request | the group's brief and top memory render **first**; sent to `assemble` as `group` |
54
+ | `X-Agentdox-Personal` | 0.16.0 | a slug | a front door, per request | the member's own thread renders **last**; sent as `personal`. When either layer is named the harness id goes as `user` too |
55
+ | `X-Agentdox-Origin` | 0.17.0 | `<host>/<path>` of the git remote (`isOrigin`) | the embed extension, from `.git/config`; `models.yml` names `AUTO_MODEL_ROUTER_ORIGIN` | parsed and validated only (`NormRequest.agentdoxOrigin`); the bridge never reads it — a front door with a project registry resolves the project from it |
56
+
57
+ omp resolves a header value that names an environment variable per request, and sends the
58
+ literal name when the variable is unset. Both names are uppercase and neither rule accepts
59
+ uppercase, so a sentinel can never become a project or a fingerprint.
60
+
44
61
  ## 3. Running it
45
62
 
46
63
  ```bash
@@ -13,7 +13,9 @@
13
13
  */
14
14
 
15
15
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
- import { dirname, join } from "node:path";
16
+ import { dirname, join, resolve } from "node:path";
17
+
18
+ import { normalizeOrigin } from "../src/context/scope.ts";
17
19
 
18
20
  /**
19
21
  * The provider id registered into omp. Kept stable so a `models.yml` that
@@ -58,6 +60,13 @@ export interface EmbedConfig {
58
60
  * models never loses the project's memory/docs/brief.
59
61
  */
60
62
  agentdoxScope?: string;
63
+ /**
64
+ * The workspace's repository fingerprint (its git remote `origin`,
65
+ * normalised) sent as `X-Agentdox-Origin`. A front door with a project
66
+ * registry uses it to find the project whatever the folder is called; a
67
+ * router alone ignores it.
68
+ */
69
+ agentdoxOrigin?: string;
61
70
  }
62
71
 
63
72
  /**
@@ -79,6 +88,81 @@ export function deriveAgentdoxScope(cwd: string): string {
79
88
  .replace(/^-+|-+$/g, "");
80
89
  }
81
90
 
91
+ /** The first `url` under `[remote "origin"]` in a git config, or "" when there is none. */
92
+ function originUrlOf(config: string): string {
93
+ let inOrigin = false;
94
+ for (const line of config.split(/\r?\n/)) {
95
+ const t = line.trim();
96
+ if (t.startsWith("[")) {
97
+ inOrigin = /^\[remote\s+"origin"\]$/i.test(t);
98
+ continue;
99
+ }
100
+ if (!inOrigin) continue;
101
+ const m = /^url\s*=\s*(.+)$/i.exec(t);
102
+ if (m !== null) return m[1]!.trim().replace(/^"(.*)"$/, "$1");
103
+ }
104
+ return "";
105
+ }
106
+
107
+ /**
108
+ * Derives the workspace's repository fingerprint: the git remote `origin` of
109
+ * the repository holding `cwd`, normalised by `normalizeOrigin`.
110
+ *
111
+ * The scope (`deriveAgentdoxScope`) is the FOLDER's name, which two unrelated
112
+ * repositories can share and one repository cloned twice does not. The origin
113
+ * is what a project registry needs to tell them apart, so it travels beside
114
+ * the scope; the scope itself is untouched by this.
115
+ *
116
+ * Walks up from `cwd` to the filesystem root looking for `.git`. A directory
117
+ * holds `config` directly; a file (a worktree or a submodule) names the real
118
+ * git dir with `gitdir: <path>`, relative to the folder holding the file, and
119
+ * a worktree's own dir keeps the shared config one hop further in `commondir`.
120
+ * Read with the filesystem only — never git itself, which may be absent, slow,
121
+ * or prompt — and total: any failure, including no repository at all, is "".
122
+ * `readFile` is injectable so the walk can be tested on hand-built files.
123
+ */
124
+ export function deriveWorkspaceOrigin(cwd: string, readFile: (path: string) => string = (p) => readFileSync(p, "utf8")): string {
125
+ const read = (path: string): string | null => {
126
+ try {
127
+ return readFile(path);
128
+ } catch {
129
+ return null;
130
+ }
131
+ };
132
+ try {
133
+ if (cwd.trim() === "") return "";
134
+ let dir = resolve(cwd);
135
+ for (;;) {
136
+ const dotGit = join(dir, ".git");
137
+ // A directory: the config sits inside it. (Reading a directory throws.)
138
+ let config = read(join(dotGit, "config"));
139
+ if (config === null) {
140
+ // A file: `gitdir: <path>`; that dir has its own config (a
141
+ // submodule) or points at the shared one through `commondir`.
142
+ const pointer = read(dotGit);
143
+ const m = pointer === null ? null : /^gitdir:\s*(.+?)\s*$/m.exec(pointer);
144
+ if (m !== null) {
145
+ const gitDir = resolve(dir, m[1]!);
146
+ config = read(join(gitDir, "config"));
147
+ if (config === null) {
148
+ const common = read(join(gitDir, "commondir"));
149
+ if (common !== null) config = read(join(resolve(gitDir, common.trim()), "config"));
150
+ }
151
+ // A `.git` file that leads nowhere is still the repository's
152
+ // boundary: nothing above it is this workspace's origin.
153
+ return config === null ? "" : normalizeOrigin(originUrlOf(config));
154
+ }
155
+ }
156
+ if (config !== null) return normalizeOrigin(originUrlOf(config));
157
+ const parent = dirname(dir);
158
+ if (parent === dir) return "";
159
+ dir = parent;
160
+ }
161
+ } catch {
162
+ return "";
163
+ }
164
+ }
165
+
82
166
  /**
83
167
  * Resolves the desired bind port: an explicit `AUTO_MODEL_ROUTER_PORT` when set
84
168
  * and valid, else 0 so the OS assigns a free ephemeral port.
@@ -189,6 +273,8 @@ export function buildProviderConfig(
189
273
  },
190
274
  /** omp's workspace directory, used to derive a scope when none is configured. */
191
275
  cwd?: string,
276
+ /** The workspace's repository fingerprint (`deriveWorkspaceOrigin`); "" or absent sends none. */
277
+ origin?: string,
192
278
  ): EmbedConfig {
193
279
  const host = cfg.server.host === "0.0.0.0" || cfg.server.host === "::" ? "127.0.0.1" : cfg.server.host;
194
280
  const round = (v: number): number => Math.round(v * 1e4) / 1e4;
@@ -224,6 +310,10 @@ export function buildProviderConfig(
224
310
  const derived = deriveAgentdoxScope(cwd ?? "");
225
311
  const scope = derived !== "" ? derived : cfg.context.defaultScope;
226
312
  if (scope !== "") out.agentdoxScope = scope;
313
+ // The repository beside the folder: one value for every clone of it,
314
+ // whatever each is called. Only a registry can use it, so it is sent
315
+ // only where the scope is.
316
+ if (origin !== undefined && origin !== "") out.agentdoxOrigin = origin;
227
317
  }
228
318
  return out;
229
319
  }
@@ -112,7 +112,7 @@ export const REMOTE_MODELS: readonly { id: string; name: string }[] = [
112
112
  * the session and subagent tags, and the virtual models. Costs are USD per
113
113
  * million tokens, like the embedded config.
114
114
  */
115
- export function remoteProviderRegistration(remote: RemoteRouter, sessionId: string, subagent: boolean, blend: { inputPerMtok: number; outputPerMtok: number }, agentdoxScope = ""): {
115
+ export function remoteProviderRegistration(remote: RemoteRouter, sessionId: string, subagent: boolean, blend: { inputPerMtok: number; outputPerMtok: number }, agentdoxScope = "", agentdoxOrigin = ""): {
116
116
  baseUrl: string;
117
117
  api: string;
118
118
  apiKey: string;
@@ -126,6 +126,9 @@ export function remoteProviderRegistration(remote: RemoteRouter, sessionId: stri
126
126
  // router, so this is sent whatever the local config says; the remote decides what to do with
127
127
  // it (a team that pins a scope for the group overrides it, and one that pins none follows it).
128
128
  if (agentdoxScope !== "") headers["X-Agentdox-Scope"] = agentdoxScope;
129
+ // The repository behind that folder: the same value from every clone, so a remote with a
130
+ // project registry finds the project when two folders share a name or one repo has two.
131
+ if (agentdoxOrigin !== "") headers["X-Agentdox-Origin"] = agentdoxOrigin;
129
132
  const round = (v: number): number => Math.round(v * 1e4) / 1e4;
130
133
  return {
131
134
  baseUrl: `${remote.url}/v1`,
@@ -33,8 +33,8 @@ import type { RouterConfig } from "../src/config/types.ts";
33
33
 
34
34
  import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
35
35
 
36
- import { EMBED_DUMMY_API_KEY, EMBED_PROVIDER_ID, buildProviderConfig, deriveAgentdoxScope, embedPortPath, modelsYmlPort, probeEmbed, readEmbedPort, resolveEmbedPort, writeEmbedPort } from "./embed-logic.ts";
37
- import { SCOPE_ENV } from "../src/context/scope.ts";
36
+ import { EMBED_DUMMY_API_KEY, EMBED_PROVIDER_ID, buildProviderConfig, deriveAgentdoxScope, deriveWorkspaceOrigin, embedPortPath, modelsYmlPort, probeEmbed, readEmbedPort, resolveEmbedPort, writeEmbedPort } from "./embed-logic.ts";
37
+ import { ORIGIN_ENV, SCOPE_ENV } from "../src/context/scope.ts";
38
38
 
39
39
  // The workspace's scope for the MAIN model. omp builds that handle from
40
40
  // models.yml before this file loads, so its X-Agentdox-Scope cannot come from
@@ -43,9 +43,17 @@ import { SCOPE_ENV } from "../src/context/scope.ts";
43
43
  // and this module runs inside omp's process — so setting it here reaches
44
44
  // every turn of this session, main and side roles alike. A workspace that
45
45
  // derives no scope (no folder name) leaves whatever the shell set.
46
+ //
47
+ // The workspace's ORIGIN (its git remote, normalised) rides the same way under
48
+ // ORIGIN_ENV: the folder name is the scope, the repository is the fingerprint
49
+ // a team uses to find the project when folder names collide. Read once — the
50
+ // remote does not change during a session — and shared with the providers
51
+ // registered below. A workspace outside a repository sets nothing.
52
+ const workspaceOrigin = deriveWorkspaceOrigin(process.cwd());
46
53
  {
47
54
  const workspaceScope = deriveAgentdoxScope(process.cwd());
48
55
  if (workspaceScope !== "") process.env[SCOPE_ENV] = workspaceScope;
56
+ if (workspaceOrigin !== "") process.env[ORIGIN_ENV] = workspaceOrigin;
49
57
  }
50
58
 
51
59
  /** omp's models.yml as text, or "" when it does not exist / cannot be read. */
@@ -97,7 +105,7 @@ function trackProcessExit(): void {
97
105
  function registerRouterProvider(pi: ExtensionAPI, port: number, cfg: RouterConfig, sessionId: string, subagent: boolean): void {
98
106
  // cwd is omp's workspace, which is what the agentdox scope is derived from
99
107
  // when none is configured explicitly.
100
- const providerConfig = buildProviderConfig(port, cfg, process.cwd());
108
+ const providerConfig = buildProviderConfig(port, cfg, process.cwd(), workspaceOrigin);
101
109
  const headers: Record<string, string> = {};
102
110
  if (providerConfig.harnessId !== undefined && providerConfig.harnessId !== "") {
103
111
  headers["X-Omp-Harness"] = providerConfig.harnessId;
@@ -112,6 +120,10 @@ function registerRouterProvider(pi: ExtensionAPI, port: number, cfg: RouterConfi
112
120
  if (providerConfig.agentdoxScope !== undefined && providerConfig.agentdoxScope !== "") {
113
121
  headers["X-Agentdox-Scope"] = providerConfig.agentdoxScope;
114
122
  }
123
+ // The repository behind that folder, for a front door that keeps a registry.
124
+ if (providerConfig.agentdoxOrigin !== undefined && providerConfig.agentdoxOrigin !== "") {
125
+ headers["X-Agentdox-Origin"] = providerConfig.agentdoxOrigin;
126
+ }
115
127
  pi.registerProvider(EMBED_PROVIDER_ID, {
116
128
  baseUrl: providerConfig.baseUrl,
117
129
  api: "openai-completions",
@@ -190,7 +202,7 @@ export default function (pi: ExtensionAPI): void {
190
202
  writeEmbedLog(`remote credential refresh failed: ${err instanceof Error ? err.message : String(err)}`);
191
203
  }
192
204
  }
193
- pi.registerProvider(EMBED_PROVIDER_ID, remoteProviderRegistration(remote, sessionId, !ctx.hasUI, cfg.ledger.fallbackBlend, deriveAgentdoxScope(process.cwd())));
205
+ pi.registerProvider(EMBED_PROVIDER_ID, remoteProviderRegistration(remote, sessionId, !ctx.hasUI, cfg.ledger.fallbackBlend, deriveAgentdoxScope(process.cwd()), workspaceOrigin));
194
206
  pi.setLabel(`auto-model-router remote (${remote.url.replace(/^https?:\/\//, "")})`);
195
207
  writeEmbedLog(`remote mode url=${remote.url} user=${remote.userId} session=${sessionId}`);
196
208
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-model-router",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "private": false,
5
5
  "description": "Local cost/complexity-aware model router for Oh My Pi, backed by OpenRouter",
6
6
  "type": "module",
@@ -15,7 +15,7 @@
15
15
  * keys survive.
16
16
  */
17
17
 
18
- import { SCOPE_ENV } from "../context/scope.ts";
18
+ import { ORIGIN_ENV, SCOPE_ENV } from "../context/scope.ts";
19
19
  import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
20
20
  import { homedir } from "node:os";
21
21
  import { dirname, join } from "node:path";
@@ -65,7 +65,9 @@ export interface SpliceResult {
65
65
  * the embed extension sets from the workspace folder, so the MAIN model's turns
66
66
  * carry the repository's own scope rather than one for the whole machine. When
67
67
  * the variable is unset the router ignores the literal and falls back to its
68
- * own `context.defaultScope`.
68
+ * own `context.defaultScope`. The origin (`ORIGIN_ENV`, set by the extension
69
+ * from the workspace's git remote) rides the same way; a router on its own
70
+ * ignores it, a front door with a project registry does not.
69
71
  */
70
72
  function providerHeaders(cfg: RouterConfig): Record<string, string> {
71
73
  const headers: Record<string, string> = {};
@@ -74,6 +76,7 @@ function providerHeaders(cfg: RouterConfig): Record<string, string> {
74
76
  }
75
77
  if (cfg.context.enabled) {
76
78
  headers["X-Agentdox-Scope"] = SCOPE_ENV;
79
+ headers["X-Agentdox-Origin"] = ORIGIN_ENV;
77
80
  }
78
81
  return headers;
79
82
  }
@@ -300,6 +300,7 @@ export const WIZARD_SECTIONS: readonly SectionSpec[] = [
300
300
  { path: "context.docsLimit", label: "Doc items", kind: "number", min: 0 },
301
301
  { path: "context.sessionLimit", label: "Session items", kind: "number", min: 0 },
302
302
  { path: "context.briefChars", label: "Brief chars", kind: "number", min: 0 },
303
+ { path: "context.layers", label: "Send team context layers", kind: "boolean" },
303
304
  { path: "context.recordTurns", label: "Record turns back", kind: "boolean" },
304
305
  { path: "context.injectWithoutTools", label: "Inject into tool-less calls", kind: "boolean" },
305
306
  { path: "context.maxQueue", label: "Write-back queue", kind: "number", min: 1 },
@@ -29,7 +29,7 @@ import { homedir, hostname } from "node:os";
29
29
  import { dirname, join, resolve } from "node:path";
30
30
  import { fileURLToPath } from "node:url";
31
31
  import { refreshAccountOf, remoteFilePath } from "../../omp-extension/remote-logic.ts";
32
- import { SCOPE_ENV } from "../context/scope.ts";
32
+ import { ORIGIN_ENV, SCOPE_ENV } from "../context/scope.ts";
33
33
  import { executablePath, materializePackage, readEmbeddedPackage } from "./embedded.ts";
34
34
  import { fetchSkills, installSkills, type SkillsBundle, type SkillsInstallReport, type SkillsTarget } from "./skills.ts";
35
35
  import { pickStore, saveRefreshToken, type StoreDeps, type StoreKind } from "./credential-store.ts";
@@ -200,6 +200,10 @@ const MODELS_YML_END = " # END auto-model-router (remote)";
200
200
  * `SCOPE_ENV`, which omp resolves from its environment per request, and the
201
201
  * embed extension sets that variable from the workspace folder as it loads.
202
202
  * `scope` pins a literal slug instead, for a single-project machine.
203
+ *
204
+ * `X-Agentdox-Origin` always names `ORIGIN_ENV`, which the extension sets from
205
+ * the workspace's git remote: a pinned scope says which project's context to
206
+ * draw on, and the origin still says which repository the turn came from.
203
207
  */
204
208
  export function renderRemoteModelsYml(url: string, key: string, blend: { inputPerMtok: number; outputPerMtok: number }, scope = ""): string {
205
209
  const round = (v: number): number => Math.round(v * 1e4) / 1e4;
@@ -217,7 +221,7 @@ export function renderRemoteModelsYml(url: string, key: string, blend: { inputPe
217
221
  " api: openai-completions",
218
222
  ` apiKey: ${key}`,
219
223
  ];
220
- lines.push(" headers:", ` X-Agentdox-Scope: ${scope !== "" ? scope : SCOPE_ENV}`);
224
+ lines.push(" headers:", ` X-Agentdox-Scope: ${scope !== "" ? scope : SCOPE_ENV}`, ` X-Agentdox-Origin: ${ORIGIN_ENV}`);
221
225
  lines.push(" models:");
222
226
  for (const m of REMOTE_MODEL_ROWS) {
223
227
  lines.push(
@@ -265,6 +265,10 @@ export const DEFAULT_CONFIG: RouterConfig = {
265
265
  // statics + all 14 decisions) inside a 24k block while leaving ~15k for
266
266
  // the query-relevant memory/docs tail. 0 omits the brief.
267
267
  briefChars: 12_000,
268
+ // Group / personal / user layers named by a team front door. On, because
269
+ // a router that is not behind one has no layer names to send and posts
270
+ // exactly what it did before; off only sends none when a team does.
271
+ layers: true,
268
272
  recordTurns: true,
269
273
  // A request with no tool schemas is a harness utility call — omp asks for
270
274
  // a session title or a complexity rating through the same provider — and
@@ -228,6 +228,7 @@ const context = z.strictObject({
228
228
  docsLimit: z.number().int().nonnegative().optional(),
229
229
  sessionLimit: z.number().int().nonnegative().optional(),
230
230
  briefChars: z.number().int().nonnegative().optional(),
231
+ layers: z.boolean().optional(),
231
232
  recordTurns: z.boolean().optional(),
232
233
  injectWithoutTools: z.boolean().optional(),
233
234
  maxQueue: z.number().int().positive().optional(),
@@ -767,6 +767,15 @@ export interface ContextConfig {
767
767
  * query-relevant tail always fits too.
768
768
  */
769
769
  briefChars: number;
770
+ /**
771
+ * Send the context layers a front door names on the request — the group
772
+ * scope (`X-Agentdox-Group`, rendered first), the personal scope
773
+ * (`X-Agentdox-Personal`, rendered last) and the member (the harness id,
774
+ * which filters the project's recent tail and tags recorded turns). A
775
+ * router without a team has none to send and its block is unchanged; this
776
+ * is the kill switch for a team that wants single-scope blocks back.
777
+ */
778
+ layers: boolean;
770
779
  /** Write settled turns back to agentdox sessions, tagged with the served model. */
771
780
  recordTurns: boolean;
772
781
  /**
@@ -24,13 +24,29 @@ export interface AssembleLimits {
24
24
  briefChars: number;
25
25
  }
26
26
 
27
+ /**
28
+ * The layers around the project scope (project memory, phase one). Each is a
29
+ * name the team derives; empty means "not present" and is NOT sent, so a lone
30
+ * router's request body — and therefore its block — is byte-identical to
31
+ * before. An agentdox that predates layers ignores the keys it does not know.
32
+ */
33
+ export interface AssembleLayers {
34
+ /** Scope whose brief and top memory render first, as group context. */
35
+ group: string;
36
+ /** Scope whose memory (handoff note first) renders last, as the member's own thread. */
37
+ personal: string;
38
+ /** The member: the project layer's recent tail is filtered to messages tagged `user:<user>`. */
39
+ user: string;
40
+ }
41
+
27
42
  export interface AgentDoxClient {
28
43
  /**
29
44
  * Assembles a context slice for `scope`, biased by `query`. Falls back to
30
45
  * the server's pre-assembled baseline when assembly is unavailable (older
31
- * server, or no query-relevant content).
46
+ * server, or no query-relevant content). `layers` adds the group and
47
+ * personal scopes around it; absent or all-empty sends nothing extra.
32
48
  */
33
- assemble(scope: string, query: string, limits: AssembleLimits): Promise<string | null>;
49
+ assemble(scope: string, query: string, limits: AssembleLimits, layers?: AssembleLayers): Promise<string | null>;
34
50
  createSession(scope: string, title: string): Promise<string | null>;
35
51
  append(sessionId: string, role: "user" | "assistant", content: string, refs: string[]): Promise<boolean>;
36
52
  }
@@ -84,11 +100,13 @@ export function createAgentDoxClient(opts: AgentDoxClientOptions): AgentDoxClien
84
100
  };
85
101
 
86
102
  return {
87
- async assemble(scope, query, limits) {
103
+ async assemble(scope, query, limits, layers) {
88
104
  // camelCase: the REST endpoint ignores snake_case limit keys entirely,
89
105
  // which silently reads as "unbounded". briefChars is sent even when 0:
90
106
  // an older server ignores the unknown key, and 0 is the documented
91
- // "no brief" value there.
107
+ // "no brief" value there. The layer keys are the opposite: only sent
108
+ // when non-empty, so a router without a team posts exactly what it
109
+ // always did.
92
110
  const res = await request("POST", "/context/assemble", {
93
111
  scope,
94
112
  query,
@@ -96,6 +114,9 @@ export function createAgentDoxClient(opts: AgentDoxClientOptions): AgentDoxClien
96
114
  docsLimit: limits.docsLimit,
97
115
  sessionLimit: limits.sessionLimit,
98
116
  briefChars: limits.briefChars,
117
+ ...(layers === undefined || layers.group === "" ? {} : { group: layers.group }),
118
+ ...(layers === undefined || layers.personal === "" ? {} : { personal: layers.personal }),
119
+ ...(layers === undefined || layers.user === "" ? {} : { user: layers.user }),
99
120
  });
100
121
  if (res !== null && res.status === 200) {
101
122
  const prompt = promptOf(res.json);
@@ -40,6 +40,12 @@ export interface BridgeOptions {
40
40
  sessionLimit: number;
41
41
  /** Character budget for the project brief rendered first in the block; 0 omits it. */
42
42
  briefChars: number;
43
+ /**
44
+ * Send the group / personal / user layers a front door names (project
45
+ * memory, phase one). False is the kill switch: none of the new assemble
46
+ * fields go out, whatever the request headers say.
47
+ */
48
+ layers: boolean;
43
49
  /** Record settled turns back into agentdox sessions. */
44
50
  recordTurns: boolean;
45
51
  /** Bound on queued write-backs; excess is dropped rather than grown unbounded. */
@@ -83,7 +89,7 @@ function appendFragment(prior: string, next: string): string {
83
89
  }
84
90
 
85
91
  export function createContextBridge(opts: BridgeOptions): ContextBridge {
86
- const { client, store, log, maxStalenessMs, maxBlockChars, memoryLimit, docsLimit, sessionLimit, briefChars, recordTurns, maxQueue } = opts;
92
+ const { client, store, log, maxStalenessMs, maxBlockChars, memoryLimit, docsLimit, sessionLimit, briefChars, layers, recordTurns, maxQueue } = opts;
87
93
 
88
94
  // Serialized write-back queue. Session appends for one conversation must
89
95
  // stay ordered, and agentdox is a local service — one worker is plenty.
@@ -124,12 +130,26 @@ export function createContextBridge(opts: BridgeOptions): ContextBridge {
124
130
  // Recent sessions only on a conversation's first block: after that they
125
131
  // are this conversation's own recorded turns, duplicating the prompt
126
132
  // and changing on every refresh (measured 1.4-1.9k chars per block).
127
- const raw = await client.assemble(input.scope, input.query, {
128
- memoryLimit,
129
- docsLimit,
130
- sessionLimit: input.firstFetch ? sessionLimit : 0,
131
- briefChars,
132
- });
133
+ // The layers around the project scope ride along only while enabled.
134
+ // The block's version is a hash of its content, so a personal layer
135
+ // pins a different block per member and never shares one across them.
136
+ // `user` goes only behind a front door that named a layer: a router
137
+ // on its own still has a harness id (Claude Code's is derived, omp's
138
+ // is configured), and against a new agentdox that would filter the
139
+ // project's recent tail to that harness — a change the lone install
140
+ // never asked for.
141
+ const fronted = input.group !== "" || input.personal !== "";
142
+ const raw = await client.assemble(
143
+ input.scope,
144
+ input.query,
145
+ {
146
+ memoryLimit,
147
+ docsLimit,
148
+ sessionLimit: input.firstFetch ? sessionLimit : 0,
149
+ briefChars,
150
+ },
151
+ layers ? { group: input.group, personal: input.personal, user: fronted ? input.user : "" } : undefined,
152
+ );
133
153
  if (raw === null) {
134
154
  // agentdox unreachable or empty. Keep serving the pinned block if we
135
155
  // have one: stale shared context beats none, and re-using it also
@@ -204,8 +224,13 @@ export function createContextBridge(opts: BridgeOptions): ContextBridge {
204
224
  // Model attribution rides on refs, which agentdox already carries
205
225
  // per message. This is what makes the transcript newly useful:
206
226
  // every turn shows WHICH model produced it.
207
- const refs = [`model:${rec.slug}`, `tier:${rec.tier}`];
208
- if (rec.userText !== "") await client.append(sessionId, "user", rec.userText, []);
227
+ // The member rides on refs too, on BOTH messages: agentdox filters
228
+ // a project's recent tail to `user:<id>`, and a tail is user and
229
+ // assistant turns alike. A lone router has no harness id and
230
+ // adds nothing.
231
+ const who = rec.harnessId === "" ? [] : [`user:${rec.harnessId}`];
232
+ const refs = [`model:${rec.slug}`, `tier:${rec.tier}`, ...who];
233
+ if (rec.userText !== "") await client.append(sessionId, "user", rec.userText, who);
209
234
  if (assistantText !== "") await client.append(sessionId, "assistant", assistantText, refs);
210
235
  })
211
236
  .catch((err: unknown) => {
@@ -72,6 +72,7 @@ function buildBridge(cfg: RouterConfig, db: Database): ContextBridge {
72
72
  docsLimit: c.docsLimit,
73
73
  sessionLimit: c.sessionLimit,
74
74
  briefChars: c.briefChars,
75
+ layers: c.layers,
75
76
  recordTurns: c.recordTurns,
76
77
  maxQueue: c.maxQueue,
77
78
  });
@@ -27,3 +27,66 @@ export function acceptScope(raw: string | null | undefined): string {
27
27
  const s = (raw ?? "").trim();
28
28
  return isScopeSlug(s) ? s : "";
29
29
  }
30
+
31
+ /**
32
+ * The workspace's ORIGIN travels the same road as the scope: `connect` and
33
+ * `config --write` put this NAME in the managed provider entry, the embed
34
+ * extension sets the variable from the workspace's git remote as it loads, and
35
+ * omp resolves it per request. Where the scope names a FOLDER, the origin
36
+ * names the REPOSITORY, so a front door with a project registry (the team
37
+ * edition) can tell two unrelated `api` folders apart and recognise one repo
38
+ * cloned into two differently named folders. A router on its own has no such
39
+ * registry and ignores it.
40
+ */
41
+ export const ORIGIN_ENV = "AUTO_MODEL_ROUTER_ORIGIN";
42
+
43
+ /**
44
+ * A repository fingerprint: `<host>/<path>` — lowercase, no scheme, no
45
+ * credentials, no port, no trailing `.git`, no trailing slash — so the same
46
+ * repository cloned over https and over ssh yields one value. Uppercase never
47
+ * passes, so `ORIGIN_ENV` itself, which omp sends verbatim when the variable is
48
+ * unset, can never become a fingerprint.
49
+ */
50
+ export function isOrigin(value: string): boolean {
51
+ return /^[a-z0-9][a-z0-9.-]{0,127}(\/[a-z0-9._~-]{1,64}){1,8}$/.test(value);
52
+ }
53
+
54
+ /**
55
+ * Reduces a git remote URL to its fingerprint, or "" when it names no host —
56
+ * a local path (`/srv/repo`, `C:\repo`) or `file://` — or does not reduce to a
57
+ * valid origin. Every form git accepts for `origin` is covered: `scheme://`
58
+ * with optional credentials and port, and the scp-like `[user@]host:path`.
59
+ */
60
+ export function normalizeOrigin(url: string): string {
61
+ const raw = url.trim();
62
+ let host: string;
63
+ let path: string;
64
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(raw);
65
+ if (scheme !== null) {
66
+ if (scheme[1]!.toLowerCase() === "file") return "";
67
+ const rest = raw.slice(scheme[0].length);
68
+ const slash = rest.search(/[/\\]/);
69
+ host = slash < 0 ? rest : rest.slice(0, slash);
70
+ path = slash < 0 ? "" : rest.slice(slash + 1);
71
+ } else {
72
+ // scp-like `[user@]host:path`. A Windows drive (`C:\repo`, `C:/repo`)
73
+ // has the same shape with a one-letter "host" and is a local path.
74
+ const scp = /^(?:[^@/\\:]+@)?([^/\\:]+):(.*)$/.exec(raw);
75
+ if (scp === null || /^[a-z]$/i.test(scp[1]!)) return "";
76
+ host = scp[1]!;
77
+ path = scp[2]!;
78
+ }
79
+ // Credentials first (a password may contain digits and a colon), then the port.
80
+ host = host.slice(host.lastIndexOf("@") + 1).replace(/:\d+$/, "");
81
+ const segments = path.split(/[/\\]/).filter((s) => s !== "");
82
+ const last = segments.length - 1;
83
+ if (last >= 0) segments[last] = segments[last]!.replace(/\.git$/i, "");
84
+ const value = [host, ...segments.filter((s) => s !== "")].join("/").toLowerCase();
85
+ return isOrigin(value) ? value : "";
86
+ }
87
+
88
+ /** The origin to trust from a request header: a fingerprint, or "" for anything else. */
89
+ export function acceptOrigin(raw: string | null | undefined): string {
90
+ const s = (raw ?? "").trim();
91
+ return isOrigin(s) ? s : "";
92
+ }