@mupt-ai/dari-gateway 1.0.369 → 1.0.371

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +1 -0
  2. package/dist/harnesses/claude_code.d.ts +11 -0
  3. package/dist/{ingress/claude_code/request_context.js → harnesses/claude_code.js} +40 -1
  4. package/dist/harnesses/codex.d.ts +9 -0
  5. package/dist/harnesses/codex.js +112 -0
  6. package/dist/harnesses/hermes.d.ts +4 -0
  7. package/dist/harnesses/hermes.js +6 -0
  8. package/dist/harnesses/index.d.ts +34 -0
  9. package/dist/harnesses/index.js +13 -0
  10. package/dist/harnesses/muse_code.d.ts +9 -0
  11. package/dist/harnesses/muse_code.js +22 -0
  12. package/dist/harnesses/openclaw.d.ts +4 -0
  13. package/dist/harnesses/openclaw.js +6 -0
  14. package/dist/harnesses/opencode.d.ts +7 -0
  15. package/dist/harnesses/opencode.js +40 -0
  16. package/dist/harnesses/pi.d.ts +6 -0
  17. package/dist/harnesses/pi.js +23 -0
  18. package/dist/ingress/client_harness.d.ts +1 -2
  19. package/dist/ingress/client_harness.js +4 -39
  20. package/dist/ingress/harness_request.js +6 -3
  21. package/dist/ingress/models.js +2 -1
  22. package/dist/link/endpoints.js +5 -5
  23. package/dist/providers/execution.d.ts +1 -0
  24. package/dist/providers/execution.js +27 -7
  25. package/dist/runtime/harness_identity/extract.d.ts +0 -8
  26. package/dist/runtime/harness_identity/extract.js +2 -201
  27. package/dist/runtime/harness_identity/ids.d.ts +2 -0
  28. package/dist/runtime/harness_identity/ids.js +26 -0
  29. package/dist/runtime/harness_identity/index.d.ts +1 -1
  30. package/dist/runtime/harness_identity/index.js +1 -1
  31. package/dist/runtime/routed_completion.js +2 -1
  32. package/dist/self_host/activity_store.d.ts +7 -0
  33. package/dist/self_host/activity_store.js +24 -0
  34. package/dist/self_host/config.js +1 -1
  35. package/dist/self_host/hosted_sync.d.ts +2 -0
  36. package/dist/self_host/hosted_sync.js +4 -0
  37. package/dist/self_host/main.d.ts +2 -0
  38. package/dist/self_host/main.js +38 -0
  39. package/dist/self_host/router_models.js +1 -1
  40. package/dist/types.d.ts +1 -1
  41. package/package.json +2 -2
  42. package/src/{ingress/claude_code/request_context.ts → harnesses/claude_code.ts} +56 -2
  43. package/src/harnesses/codex.ts +156 -0
  44. package/src/harnesses/hermes.ts +8 -0
  45. package/src/harnesses/index.ts +29 -0
  46. package/src/harnesses/muse_code.ts +30 -0
  47. package/src/harnesses/openclaw.ts +8 -0
  48. package/src/harnesses/opencode.ts +51 -0
  49. package/src/harnesses/pi.ts +28 -0
  50. package/src/ingress/client_harness.ts +4 -41
  51. package/src/ingress/harness_request.ts +9 -9
  52. package/src/ingress/models.ts +2 -1
  53. package/src/link/endpoints.ts +5 -5
  54. package/src/providers/execution.ts +34 -7
  55. package/src/runtime/harness_identity/extract.ts +2 -284
  56. package/src/runtime/harness_identity/ids.ts +41 -0
  57. package/src/runtime/harness_identity/index.ts +1 -10
  58. package/src/runtime/routed_completion.ts +2 -1
  59. package/src/self_host/activity_store.ts +28 -0
  60. package/src/self_host/config.ts +1 -1
  61. package/src/self_host/hosted_sync.ts +5 -0
  62. package/src/self_host/main.ts +37 -0
  63. package/src/self_host/router_models.ts +1 -1
  64. package/src/types.ts +2 -10
  65. package/dist/ingress/claude_code/request_context.d.ts +0 -4
  66. package/dist/ingress/muse_code.d.ts +0 -2
  67. package/dist/ingress/muse_code.js +0 -8
  68. package/src/ingress/muse_code.ts +0 -9
@@ -0,0 +1,156 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { HttpError } from "../http/errors.js";
4
+ import type { AgentRequestContext, InteractionRequestPurpose } from "../interaction/types.js";
5
+ import { boundedIdentity, uuidIdentity } from "../runtime/harness_identity/ids.js";
6
+ import type { HarnessConversationIdentity } from "../runtime/harness_identity/conversation.js";
7
+ import type { Harness } from "./index.js";
8
+
9
+ export const codex = {
10
+ id: "codex",
11
+ headers: ["x-codex-turn-metadata", "thread-id"],
12
+ } as const satisfies Harness;
13
+
14
+ export function codexConversationIdentity(
15
+ headers: Headers,
16
+ payload: Record<string, unknown>,
17
+ ): HarnessConversationIdentity | undefined {
18
+ const clientMetadata = isRecord(payload.client_metadata)
19
+ ? payload.client_metadata
20
+ : undefined;
21
+ const turnMetadata = codexTurnMetadataCollection(headers, payload);
22
+ if (turnMetadata.length === 0) {
23
+ return undefined;
24
+ }
25
+ // Clients can carry a stale projection after a resume or fork. Conflicts
26
+ // must not fail the request, and fields must not mix across projections:
27
+ // take thread, turn, and parent from one turn metadata projection, header
28
+ // first, falling back to the standalone thread fields only for the thread.
29
+ const entry = turnMetadata.find((metadata) => metadata.thread_id !== undefined)
30
+ ?? turnMetadata[0]!;
31
+ const threadId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id")
32
+ ?? uuidIdentity(headers.get("thread-id"), "thread-id")
33
+ ?? uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id");
34
+ if (threadId === undefined) {
35
+ return undefined;
36
+ }
37
+ const userTurnId = uuidIdentity(entry.turn_id, "x-codex-turn-metadata.turn_id");
38
+ const parentThreadId = uuidIdentity(entry.parent_thread_id,
39
+ "x-codex-turn-metadata.parent_thread_id");
40
+ return {
41
+ kind: "codex_thread",
42
+ value: threadId,
43
+ ...(parentThreadId === undefined ? {} : { parentThreadId }),
44
+ ...(userTurnId === undefined ? {} : { userTurnId }),
45
+ };
46
+ }
47
+
48
+ export function codexRequestPurpose(
49
+ headers: Headers,
50
+ payload: Record<string, unknown>,
51
+ ): InteractionRequestPurpose | undefined {
52
+ const turnMetadata = codexTurnMetadataCollection(headers, payload);
53
+ return turnMetadata.length > 0 && turnMetadata.every(isCodexMemoryExtraction)
54
+ ? "memory_extraction"
55
+ : undefined;
56
+ }
57
+
58
+ export function codexRequestContext(
59
+ headers: Headers,
60
+ payload: Record<string, unknown>,
61
+ ): AgentRequestContext | undefined {
62
+ const metadata = codexTurnMetadataCollection(headers, payload);
63
+ if (metadata.length === 0) return undefined;
64
+ // Classify from one projection, header first, skipping one that omits the
65
+ // request kind so a partial header falls back to a complete body.
66
+ const entry = metadata.find((candidate) => candidate.request_kind !== undefined)
67
+ ?? metadata[0]!;
68
+ const kind = entry.request_kind;
69
+ const agentKind = entry.subagent_kind;
70
+ const agentId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id");
71
+ const requestClass = kind === "compaction" ? "compaction"
72
+ : kind === "memory" || kind === "prewarm" ? "auxiliary"
73
+ : kind === "turn" && agentKind === "memory_consolidation" ? "auxiliary"
74
+ : kind === "turn" && agentKind === "compact" ? "compaction"
75
+ : kind === "turn" && agentKind !== undefined ? "subagent"
76
+ : kind === "turn" ? "main" : "unknown";
77
+ return {
78
+ requestClass,
79
+ ...(requestClass === "subagent" && agentId !== undefined ? { agentId } : {}),
80
+ parentAgentId: uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id"),
81
+ agentType: boundedIdentity(agentKind, "x-codex-turn-metadata.subagent_kind"),
82
+ };
83
+ }
84
+
85
+ // Muse Code sends its thread on every Responses request. The main agent's
86
+ // thread is its session, and each subagent has its own thread, so each keeps
87
+ // its own conversation and lease.
88
+
89
+ function isCodexMemoryExtraction(
90
+ metadata: Record<string, unknown>,
91
+ ): boolean {
92
+ if (
93
+ metadata.request_kind !== "memory" ||
94
+ metadata.thread_source !== "memory_consolidation"
95
+ ) {
96
+ return false;
97
+ }
98
+ // Codex deliberately omits canonical turn identity for detached phase-1
99
+ // memory jobs, while compatibility projections still carry the live root
100
+ // thread UUID. Phase-2 consolidation agents use ordinary turn metadata and
101
+ // their own thread identities, so they do not match this shape.
102
+ return [
103
+ "session_id",
104
+ "thread_id",
105
+ "turn_id",
106
+ "root_turn_id",
107
+ "window_id",
108
+ "forked_from_thread_id",
109
+ ].every((field) => metadata[field] === undefined);
110
+ }
111
+
112
+ function codexTurnMetadataCollection(
113
+ headers: Headers,
114
+ payload: Record<string, unknown>,
115
+ ): Record<string, unknown>[] {
116
+ const clientMetadata = isRecord(payload.client_metadata)
117
+ ? payload.client_metadata
118
+ : undefined;
119
+ return [
120
+ codexTurnMetadata(
121
+ headers.get("x-codex-turn-metadata"),
122
+ "x-codex-turn-metadata",
123
+ ),
124
+ codexTurnMetadata(
125
+ clientMetadata?.["x-codex-turn-metadata"],
126
+ "client_metadata.x-codex-turn-metadata",
127
+ ),
128
+ ].filter((value): value is Record<string, unknown> => value !== undefined);
129
+ }
130
+
131
+ function codexTurnMetadata(
132
+ raw: unknown,
133
+ field: string,
134
+ ): Record<string, unknown> | undefined {
135
+ if (raw === undefined || raw === null) return undefined;
136
+ if (typeof raw !== "string") {
137
+ throw new HttpError(
138
+ 400,
139
+ `${field} must be a JSON string.`,
140
+ "invalid_request_error",
141
+ field,
142
+ );
143
+ }
144
+ try {
145
+ const parsed: unknown = JSON.parse(raw);
146
+ if (!isRecord(parsed)) throw new Error("not an object");
147
+ return parsed;
148
+ } catch {
149
+ throw new HttpError(
150
+ 400,
151
+ `${field} must contain a JSON object.`,
152
+ "invalid_request_error",
153
+ field,
154
+ );
155
+ }
156
+ }
@@ -0,0 +1,8 @@
1
+ import type { Harness } from "./index.js";
2
+
3
+ // Sends nothing of its own that tells it apart, so the Dari CLI sets it up to
4
+ // name itself in x-dari-client-harness.
5
+ export const hermes = {
6
+ id: "hermes",
7
+ headers: [],
8
+ } as const satisfies Harness;
@@ -0,0 +1,29 @@
1
+ import { claudeCode } from "./claude_code.js";
2
+ import { codex } from "./codex.js";
3
+ import { hermes } from "./hermes.js";
4
+ import { museCode } from "./muse_code.js";
5
+ import { openclaw } from "./openclaw.js";
6
+ import { opencode } from "./opencode.js";
7
+ import { pi } from "./pi.js";
8
+
9
+ /** A coding agent the gateway serves. */
10
+ export type Harness = {
11
+ id: string;
12
+ // The headers it describes itself and each request with: which agent it
13
+ // is, its session, and what the request is for. A connected gateway passes
14
+ // them on to hosted Dari.
15
+ headers: readonly string[];
16
+ // Its own plan serves only it, so only its own headers name it.
17
+ ownPlanOnly?: true;
18
+ };
19
+
20
+ export const HARNESSES = [claudeCode, codex, museCode, opencode, pi, openclaw, hermes] as const;
21
+
22
+ export type ClientHarness = (typeof HARNESSES)[number]["id"];
23
+
24
+ export const CLIENT_HARNESSES: readonly string[] = HARNESSES.map((harness) => harness.id);
25
+
26
+ /** The agents whose own plan serves only them. */
27
+ export const OWN_PLAN_HARNESSES: readonly ClientHarness[] = HARNESSES
28
+ .filter((harness) => "ownPlanOnly" in harness)
29
+ .map((harness) => harness.id);
@@ -0,0 +1,30 @@
1
+ import { boundedIdentity } from "../runtime/harness_identity/ids.js";
2
+ import type { HarnessConversationIdentity } from "../runtime/harness_identity/conversation.js";
3
+ import type { Harness } from "./index.js";
4
+
5
+ export const museCode = {
6
+ id: "muse_code",
7
+ headers: ["x-client-id", "x-tbh-thread-id"],
8
+ // A Muse Code plan serves only Muse Code.
9
+ ownPlanOnly: true,
10
+ } as const satisfies Harness;
11
+
12
+ // Muse Code names its surface (TUI, `muse exec`, desktop, `muse serve`) in
13
+ // x-client-id on every model request.
14
+ const MUSE_CODE_CLIENT_IDS = new Set(["tbh:tui", "tbh:exec", "tbh:desktop", "tbh:serve"]);
15
+
16
+ /** Muse Code's x-client-id when the request comes from Muse Code. */
17
+ export function museCodeClientId(headers: Headers): string | undefined {
18
+ const clientId = headers.get("x-client-id")?.trim().toLowerCase();
19
+ return clientId !== undefined && MUSE_CODE_CLIENT_IDS.has(clientId) ? clientId : undefined;
20
+ }
21
+
22
+ // Muse Code sends its thread on every Responses request. The main agent's
23
+ // thread is its session, and each subagent has its own thread, so each keeps
24
+ // its own conversation and lease.
25
+ export function museCodeConversationIdentity(
26
+ headers: Headers,
27
+ ): HarnessConversationIdentity | undefined {
28
+ const threadId = boundedIdentity(headers.get("x-tbh-thread-id"), "x-tbh-thread-id");
29
+ return threadId === undefined ? undefined : { kind: "muse_code_thread", value: threadId };
30
+ }
@@ -0,0 +1,8 @@
1
+ import type { Harness } from "./index.js";
2
+
3
+ // Sends nothing of its own that tells it apart, so the Dari CLI sets it up to
4
+ // name itself in x-dari-client-harness.
5
+ export const openclaw = {
6
+ id: "openclaw",
7
+ headers: [],
8
+ } as const satisfies Harness;
@@ -0,0 +1,51 @@
1
+ import type { AgentRequestClass, AgentRequestContext } from "../interaction/types.js";
2
+ import { boundedIdentity } from "../runtime/harness_identity/ids.js";
3
+ import type { Harness } from "./index.js";
4
+
5
+ export const opencode = {
6
+ id: "opencode",
7
+ // With the `dari opencode` plugin's request kind and agent.
8
+ headers: [
9
+ "x-opencode-session-id",
10
+ "x-opencode-parent-session-id",
11
+ "x-opencode-request-kind",
12
+ "x-opencode-agent",
13
+ "x-session-affinity",
14
+ ],
15
+ } as const satisfies Harness;
16
+
17
+ // OpenCode names the session behind every request, and a subagent's parent
18
+ // session too. The `dari opencode` plugin adds the request kind and agent,
19
+ // which OpenCode does not send itself. Like Claude Code's headers, these are
20
+ // client-supplied routing hints, never inferred from prompt text.
21
+ export function openCodeRequestContext(headers: Headers): AgentRequestContext | undefined {
22
+ if (boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id") === undefined) {
23
+ return undefined;
24
+ }
25
+ const kind = headers.get("x-opencode-request-kind")?.trim();
26
+ const subagentId = openCodeSubagentId(headers);
27
+ const requestClass: AgentRequestClass = kind === "compaction" ? "compaction"
28
+ : kind === "title" || kind === "generate" ? "auxiliary"
29
+ : subagentId === undefined ? "main" : "subagent";
30
+ return {
31
+ requestClass,
32
+ ...(subagentId === undefined ? {} : {
33
+ agentId: subagentId,
34
+ parentAgentId: boundedIdentity(
35
+ headers.get("x-opencode-parent-session-id"),
36
+ "x-opencode-parent-session-id",
37
+ ),
38
+ }),
39
+ agentType: boundedIdentity(headers.get("x-opencode-agent"), "x-opencode-agent"),
40
+ };
41
+ }
42
+
43
+ export function openCodeSubagentId(headers: Headers): string | undefined {
44
+ const parent = boundedIdentity(
45
+ headers.get("x-opencode-parent-session-id"),
46
+ "x-opencode-parent-session-id",
47
+ );
48
+ return parent === undefined
49
+ ? undefined
50
+ : boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id");
51
+ }
@@ -0,0 +1,28 @@
1
+ import type { AgentRequestContext } from "../interaction/types.js";
2
+ import { boundedIdentity } from "../runtime/harness_identity/ids.js";
3
+ import type { Harness } from "./index.js";
4
+
5
+ export const pi = {
6
+ id: "pi",
7
+ headers: ["x-pi-session-id", "x-pi-request-kind"],
8
+ } as const satisfies Harness;
9
+
10
+ export function piRequestContext(headers: Headers): AgentRequestContext | undefined {
11
+ if (boundedIdentity(headers.get("x-pi-session-id"), "x-pi-session-id") === undefined) {
12
+ return undefined;
13
+ }
14
+ const kind = headers.get("x-pi-request-kind")?.trim();
15
+ return {
16
+ requestClass: kind === "turn" ? "main"
17
+ : kind === "compaction" ? "compaction"
18
+ // The Dari extension's web search tool: one request beside the turn,
19
+ // served as background work like Claude Code's own search.
20
+ : kind === "search" ? "auxiliary"
21
+ : "unknown",
22
+ };
23
+ }
24
+
25
+ // OpenCode names the session behind every request, and a subagent's parent
26
+ // session too. The `dari opencode` plugin adds the request kind and agent,
27
+ // which OpenCode does not send itself. Like Claude Code's headers, these are
28
+ // client-supplied routing hints, never inferred from prompt text.
@@ -1,46 +1,9 @@
1
- import type { ClientHarness } from "../types.js";
1
+ import { CLIENT_HARNESSES, HARNESSES, OWN_PLAN_HARNESSES, type ClientHarness } from "../harnesses/index.js";
2
2
 
3
3
  export const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
4
4
 
5
- export const CLIENT_HARNESSES: readonly string[] = [
6
- "claude_code",
7
- "codex",
8
- "muse_code",
9
- "opencode",
10
- "pi",
11
- "openclaw",
12
- "hermes",
13
- ] satisfies ClientHarness[];
14
-
15
- // The headers a coding agent describes itself and each request with: which
16
- // agent it is, its session, and what the request is for. harness_request.ts
17
- // reads every one of them.
18
- const CLIENT_HEADERS = [
19
- // Claude Code
20
- "user-agent",
21
- "x-app",
22
- "anthropic-beta",
23
- "x-claude-code-session-id",
24
- "x-claude-code-request-class",
25
- "x-claude-code-agent-id",
26
- "x-claude-code-parent-agent-id",
27
- "x-claude-code-agent-type",
28
- // Codex
29
- "x-codex-turn-metadata",
30
- "thread-id",
31
- // Muse Code
32
- "x-client-id",
33
- "x-tbh-thread-id",
34
- // OpenCode, with the `dari opencode` plugin's request kind and agent
35
- "x-opencode-session-id",
36
- "x-opencode-parent-session-id",
37
- "x-opencode-request-kind",
38
- "x-opencode-agent",
39
- "x-session-affinity",
40
- // Pi
41
- "x-pi-session-id",
42
- "x-pi-request-kind",
43
- ];
5
+ // Every coding agent's own headers. harness_request.ts reads every one of them.
6
+ const CLIENT_HEADERS = HARNESSES.flatMap((harness) => harness.headers);
44
7
 
45
8
  /**
46
9
  * The headers of `CLIENT_HEADERS` the request carries, as the client sent
@@ -72,5 +35,5 @@ export function namedClientHarness(headers: Headers): ClientHarness | undefined
72
35
  */
73
36
  export function claimedClientHarness(headers: Headers): ClientHarness | undefined {
74
37
  const named = namedClientHarness(headers);
75
- return named === "claude_code" || named === "muse_code" ? undefined : named;
38
+ return named === undefined || OWN_PLAN_HARNESSES.includes(named) ? undefined : named;
76
39
  }
@@ -4,20 +4,20 @@ import type {
4
4
  SourceProtocol,
5
5
  } from "../interaction/types.js";
6
6
  import {
7
- chatCompletionsConversationIdentity,
8
7
  claudeCodeConversationIdentity,
9
- codexConversationIdentity,
10
- codexRequestContext,
11
- codexRequestPurpose,
12
- museCodeConversationIdentity,
13
- openCodeRequestContext,
14
- piRequestContext,
8
+ claudeCodeRequestContext,
9
+ isClaudeCodeRequest,
10
+ } from "../harnesses/claude_code.js";
11
+ import { codexConversationIdentity, codexRequestContext, codexRequestPurpose } from "../harnesses/codex.js";
12
+ import { museCodeClientId, museCodeConversationIdentity } from "../harnesses/muse_code.js";
13
+ import { openCodeRequestContext } from "../harnesses/opencode.js";
14
+ import { piRequestContext } from "../harnesses/pi.js";
15
+ import {
16
+ chatCompletionsConversationIdentity,
15
17
  type HarnessConversationIdentity,
16
18
  } from "../runtime/harness_identity/index.js";
17
19
  import type { ClientHarness } from "../types.js";
18
- import { claudeCodeRequestContext, isClaudeCodeRequest } from "./claude_code/request_context.js";
19
20
  import { claimedClientHarness } from "./client_harness.js";
20
- import { museCodeClientId } from "./muse_code.js";
21
21
 
22
22
  /** The coding agent a request comes from, and what the agent says of it. */
23
23
  export type HarnessRequest = {
@@ -16,6 +16,7 @@ import { modelSupportsImageInput, modelSupportsNativeCompaction } from "../provi
16
16
  import { modelMetadataLookup } from "../providers/pi.js";
17
17
  import { resolveRouter } from "../strategies/routing.js";
18
18
  import { anthropicModelsResponse } from "./anthropic_models.js";
19
+ import { OWN_PLAN_HARNESSES } from "../harnesses/index.js";
19
20
  import { namedClientHarness } from "./client_harness.js";
20
21
  import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
21
22
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
@@ -101,7 +102,7 @@ export async function handleModels(request: Request, routerId: string): Promise<
101
102
  // A child token's one model, when it serves only Claude Code or Muse Code.
102
103
  async function childTokenModels(routerId: string, apiKey: string): Promise<string[]> {
103
104
  if (!apiKey.startsWith(LINK_CHILD_TOKEN_PREFIX)) return [];
104
- for (const clientHarness of ["claude_code", "muse_code"] as const) {
105
+ for (const clientHarness of OWN_PLAN_HARNESSES) {
105
106
  try {
106
107
  const router = await resolveRouter({ routerId, apiKey, clientHarness, provisional: true });
107
108
  return router.link_models ?? router.enabled_models;
@@ -94,6 +94,7 @@ import { catalogModelFor } from "./grant_access.js";
94
94
  import { registeredRedirect } from "./grants.js";
95
95
  import { requestTags } from "../runtime/request_tags.js";
96
96
  import type { ClientHarness, ResolvedRouter, SubscriptionKind } from "../types.js";
97
+ import { CLIENT_HARNESSES } from "../harnesses/index.js";
97
98
  import { parseJsonRequest } from "../ingress/json.js";
98
99
  import { DARI_MARK, ICONS, linkLogo } from "./assets.js";
99
100
  import { GEIST_WOFF2 } from "./font.js";
@@ -155,9 +156,6 @@ const CHILD_TOKEN_MAX_SECONDS = 12 * 60 * 60;
155
156
  const MAX_MODEL_CHARS = 200;
156
157
  const MAX_PURPOSE_CHARS = 200;
157
158
  const MAX_CHILD_MODELS = 16;
158
- // Clients an app can say it runs with `client` on the authorize request.
159
- // Claude Code and Muse Code plans serve only an app that runs those.
160
- const CLIENTS: readonly ClientHarness[] = ["claude_code", "codex", "muse_code", "opencode", "pi", "openclaw", "hermes"];
161
159
  const PLAN_KINDS = Object.keys(SUBSCRIPTION_PLAN_LABELS) as SubscriptionKind[];
162
160
  // An API key, as a kind an app asks for in `plans` and reads on a grant.
163
161
  const API_KEY = "api_key";
@@ -1270,8 +1268,10 @@ async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Pr
1270
1268
  return badRequest(`The only scope is ${LINK_SCOPE}.`);
1271
1269
  }
1272
1270
  const clients = listParam(params.get("client"));
1273
- if (!clients.every((client) => (CLIENTS as readonly string[]).includes(client))) {
1274
- return badRequest(`client lists the clients the app runs: ${CLIENTS.join(", ")}.`);
1271
+ // The clients an app can say it runs. Claude Code and Muse Code plans serve
1272
+ // only an app that runs those.
1273
+ if (!clients.every((client) => CLIENT_HARNESSES.includes(client))) {
1274
+ return badRequest(`client lists the clients the app runs: ${CLIENT_HARNESSES.join(", ")}.`);
1275
1275
  }
1276
1276
  const plans = [...new Set(listParam(params.get("plans")).flatMap((plan): string[] => plan === SUPPORTED ? [...SUPPORTED_KINDS] : [plan]))];
1277
1277
  if (!plans.every((plan) => (OFFER_KINDS as readonly string[]).includes(plan))) {
@@ -25,6 +25,7 @@ import {
25
25
  import type { RoutedProtocol } from "../runtime/routed_protocol.js";
26
26
  import { trackBackgroundTelemetry } from "../telemetry/background.js";
27
27
  import { gatewayPlatform, type SubscriptionHold } from "../platform/platform.js";
28
+ import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
28
29
  import { reportRoutingUsage } from "../telemetry/usage.js";
29
30
  import {
30
31
  prepareProviderExecution,
@@ -86,6 +87,8 @@ export type PreparedStreamExecution = {
86
87
 
87
88
  export type CompletedNonStreamingExecution = {
88
89
  choice: ProviderChoice;
90
+ // The request the client is told it made; see servedRequestId.
91
+ requestId: string;
89
92
  output: ReturnType<typeof piMessageToInteractionOutput>;
90
93
  responseBody: Record<string, unknown>;
91
94
  reportBarrierError?: unknown;
@@ -93,6 +96,7 @@ export type CompletedNonStreamingExecution = {
93
96
 
94
97
  type CompletedNonStreamingAttempt = {
95
98
  completion: CompletedProviderCall;
99
+ responseCapture?: ProviderResponseCapture;
96
100
  };
97
101
 
98
102
  export async function executeNonStreaming(args: {
@@ -116,7 +120,11 @@ export async function executeNonStreaming(args: {
116
120
  });
117
121
  }
118
122
  return Response.json(result.responseBody, {
119
- headers: { ...result.choice.execution.headers, ...linkUsageHeaders(result) },
123
+ headers: {
124
+ ...result.choice.execution.headers,
125
+ ...linkUsageHeaders(result),
126
+ "X-Request-Id": result.requestId,
127
+ },
120
128
  });
121
129
  }
122
130
 
@@ -170,9 +178,10 @@ export async function completeNonStreaming(args: {
170
178
  }
171
179
 
172
180
  const {
173
- value: { completion },
181
+ value: { completion, responseCapture },
174
182
  choice,
175
183
  } = result;
184
+ const requestId = servedRequestId(args.requestId, choice.execution, responseCapture);
176
185
  let output: ReturnType<typeof piMessageToInteractionOutput>;
177
186
  let responseBody: Record<string, unknown>;
178
187
  try {
@@ -182,7 +191,7 @@ export async function completeNonStreaming(args: {
182
191
  args.interaction,
183
192
  );
184
193
  responseBody = args.protocol.responseBody({
185
- id: args.requestId,
194
+ id: requestId,
186
195
  model: choice.execution.model,
187
196
  output,
188
197
  modelCost: args.reporter.modelCost({
@@ -247,6 +256,7 @@ export async function completeNonStreaming(args: {
247
256
  await args.reporter.waitForPrefixEntryWrite();
248
257
  return {
249
258
  choice,
259
+ requestId,
250
260
  output,
251
261
  responseBody,
252
262
  ...(reportBarrierError === undefined ? {} : { reportBarrierError }),
@@ -329,7 +339,7 @@ async function runCompletionAttempt(args: {
329
339
  }
330
340
  return {
331
341
  kind: "succeeded",
332
- value: { completion },
342
+ value: { completion, responseCapture: started.responseCapture },
333
343
  latencyMs: completion.providerLatencyMs,
334
344
  };
335
345
  } catch (error) {
@@ -613,6 +623,7 @@ async function runStreamSetupAttempt(args: {
613
623
  source: started.providerStream.source,
614
624
  },
615
625
  customerAbort: started.customerAbort,
626
+ responseCapture: started.responseCapture,
616
627
  },
617
628
  latencyMs: 0,
618
629
  };
@@ -653,6 +664,7 @@ export async function executeStreaming(args: {
653
664
  }): Promise<Response> {
654
665
  const { execution } = args.choice;
655
666
  const started = args.startedStream;
667
+ const requestId = servedRequestId(args.requestId, execution, started.responseCapture);
656
668
  args.reporter.attachServingDecision(args.choice.decision);
657
669
  const observed = observeDeliveredOutput(started.providerStream.events);
658
670
  const finalizer = createStreamFinalizer({
@@ -672,7 +684,7 @@ export async function executeStreaming(args: {
672
684
  });
673
685
  return new Response(
674
686
  args.protocol.streamBody({
675
- id: args.requestId,
687
+ id: requestId,
676
688
  model: execution.model,
677
689
  routing: args.choice.decision,
678
690
  events: observed.events,
@@ -695,19 +707,34 @@ export async function executeStreaming(args: {
695
707
  trackBackgroundTelemetry(finalizer.afterResponseDetached(outcome));
696
708
  },
697
709
  }),
698
- { headers: streamHeaders(execution) },
710
+ { headers: streamHeaders(execution, requestId) },
699
711
  );
700
712
  }
701
713
 
702
- function streamHeaders(execution: ProviderExecution): Record<string, string> {
714
+ function streamHeaders(execution: ProviderExecution, requestId: string): Record<string, string> {
703
715
  return {
704
716
  "Content-Type": "text/event-stream",
705
717
  "Cache-Control": "no-cache",
706
718
  "Connection": "keep-alive",
707
719
  ...execution.headers,
720
+ "X-Request-Id": requestId,
708
721
  };
709
722
  }
710
723
 
724
+ /**
725
+ * The request ID the client is told, in the response and its `X-Request-Id`:
726
+ * this gateway's own, except for a request hosted Dari served. Hosted logs
727
+ * that one under the ID it answered with, and Activity finds it only by that.
728
+ */
729
+ function servedRequestId(
730
+ requestId: string,
731
+ execution: ProviderExecution,
732
+ capture: ProviderResponseCapture | undefined,
733
+ ): string {
734
+ if (execution.provider !== HOSTED_DARI_PROVIDER) return requestId;
735
+ return capture?.succeeded?.get("x-request-id")?.trim() || requestId;
736
+ }
737
+
711
738
  function customerAbortRequested(
712
739
  clientSignal: AbortSignal | undefined,
713
740
  ): boolean {